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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b38ccf128d443e4068965a90fc79f744eb360371 | 1,409 | cpp | C++ | src/contract/Data.cpp | pestotoast/mmx-node | eb9e27aa077c111e814c62cc5b716c4957eac09e | [
"Apache-2.0"
] | 2 | 2022-01-12T02:00:10.000Z | 2022-02-05T03:59:43.000Z | src/contract/Data.cpp | pestotoast/mmx-node | eb9e27aa077c111e814c62cc5b716c4957eac09e | [
"Apache-2.0"
] | null | null | null | src/contract/Data.cpp | pestotoast/mmx-node | eb9e27aa077c111e814c62cc5b716c4957eac09e | [
"Apache-2.0"
] | null | null | null | /*
* Data.cpp
*
* Created on: Jan 19, 2022
* Author: mad
*/
#include <mmx/contract/Data.hxx>
#include <mmx/write_bytes.h>
namespace mmx {
namespace contract {
hash_t Data::calc_hash() const
{
std::vector<uint8_t> buffer;
vnx::VectorOutputStream stream(&buffer);
vnx::OutputBuffer out(&stream);
write_bytes(out, get_type_hash());
write_bytes(out, version);
write_bytes(out, owner);
write_bytes(out, value);
out.flush();
return hash_t(buffer);
}
uint64_t Data::calc_cost(std::shared_ptr<const ChainParams> params) const {
return (8 + 4 + (owner ? 32 : 0) + value.size()) * params->min_txfee_byte;
}
std::vector<addr_t> Data::get_dependency() const {
if(owner) {
return {*owner};
}
return {};
}
std::vector<addr_t> Data::get_parties() const {
return get_dependency();
}
vnx::optional<addr_t> Data::get_owner() const {
return owner;
}
std::vector<tx_out_t> Data::validate(std::shared_ptr<const Operation> operation, std::shared_ptr<const Context> context) const
{
if(!owner) {
throw std::logic_error("!owner");
}
{
auto contract = context->get_contract(*owner);
if(!contract) {
throw std::logic_error("missing dependency");
}
contract->validate(operation, context);
}
return {};
}
void Data::transfer(const vnx::optional<addr_t>& new_owner)
{
owner = new_owner;
}
void Data::set(const vnx::Variant& value_)
{
value = value_;
}
} // contract
} // mmx
| 18.298701 | 126 | 0.682754 | pestotoast |
b38f32236bf0a3cece67f7e108e6e7721cff7281 | 132,716 | cc | C++ | libgav1/src/dsp/x86/loop_restoration_10bit_avx2.cc | P-404/android_external_libgav1 | 4e6f3403a267fc31f9a6fa85683f824fb8b15bd8 | [
"Apache-2.0"
] | null | null | null | libgav1/src/dsp/x86/loop_restoration_10bit_avx2.cc | P-404/android_external_libgav1 | 4e6f3403a267fc31f9a6fa85683f824fb8b15bd8 | [
"Apache-2.0"
] | null | null | null | libgav1/src/dsp/x86/loop_restoration_10bit_avx2.cc | P-404/android_external_libgav1 | 4e6f3403a267fc31f9a6fa85683f824fb8b15bd8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The libgav1 Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/dsp/loop_restoration.h"
#include "src/utils/cpu.h"
#if LIBGAV1_TARGETING_AVX2 && LIBGAV1_MAX_BITDEPTH >= 10
#include <immintrin.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include "src/dsp/common.h"
#include "src/dsp/constants.h"
#include "src/dsp/dsp.h"
#include "src/dsp/x86/common_avx2.h"
#include "src/utils/common.h"
#include "src/utils/constants.h"
namespace libgav1 {
namespace dsp {
namespace {
inline void WienerHorizontalClip(const __m256i s[2],
int16_t* const wiener_buffer) {
constexpr int offset =
1 << (10 + kWienerFilterBits - kInterRoundBitsHorizontal - 1);
constexpr int limit = (offset << 2) - 1;
const __m256i offsets = _mm256_set1_epi16(-offset);
const __m256i limits = _mm256_set1_epi16(limit - offset);
const __m256i round = _mm256_set1_epi32(1 << (kInterRoundBitsHorizontal - 1));
const __m256i sum0 = _mm256_add_epi32(s[0], round);
const __m256i sum1 = _mm256_add_epi32(s[1], round);
const __m256i rounded_sum0 =
_mm256_srai_epi32(sum0, kInterRoundBitsHorizontal);
const __m256i rounded_sum1 =
_mm256_srai_epi32(sum1, kInterRoundBitsHorizontal);
const __m256i rounded_sum = _mm256_packs_epi32(rounded_sum0, rounded_sum1);
const __m256i d0 = _mm256_max_epi16(rounded_sum, offsets);
const __m256i d1 = _mm256_min_epi16(d0, limits);
StoreAligned32(wiener_buffer, d1);
}
inline void WienerHorizontalTap7Kernel(const __m256i s[7],
const __m256i filter[2],
int16_t* const wiener_buffer) {
const __m256i s06 = _mm256_add_epi16(s[0], s[6]);
const __m256i s15 = _mm256_add_epi16(s[1], s[5]);
const __m256i s24 = _mm256_add_epi16(s[2], s[4]);
const __m256i ss0 = _mm256_unpacklo_epi16(s06, s15);
const __m256i ss1 = _mm256_unpackhi_epi16(s06, s15);
const __m256i ss2 = _mm256_unpacklo_epi16(s24, s[3]);
const __m256i ss3 = _mm256_unpackhi_epi16(s24, s[3]);
__m256i madds[4];
madds[0] = _mm256_madd_epi16(ss0, filter[0]);
madds[1] = _mm256_madd_epi16(ss1, filter[0]);
madds[2] = _mm256_madd_epi16(ss2, filter[1]);
madds[3] = _mm256_madd_epi16(ss3, filter[1]);
madds[0] = _mm256_add_epi32(madds[0], madds[2]);
madds[1] = _mm256_add_epi32(madds[1], madds[3]);
WienerHorizontalClip(madds, wiener_buffer);
}
inline void WienerHorizontalTap5Kernel(const __m256i s[5], const __m256i filter,
int16_t* const wiener_buffer) {
const __m256i s04 = _mm256_add_epi16(s[0], s[4]);
const __m256i s13 = _mm256_add_epi16(s[1], s[3]);
const __m256i s2d = _mm256_add_epi16(s[2], s[2]);
const __m256i s0m = _mm256_sub_epi16(s04, s2d);
const __m256i s1m = _mm256_sub_epi16(s13, s2d);
const __m256i ss0 = _mm256_unpacklo_epi16(s0m, s1m);
const __m256i ss1 = _mm256_unpackhi_epi16(s0m, s1m);
__m256i madds[2];
madds[0] = _mm256_madd_epi16(ss0, filter);
madds[1] = _mm256_madd_epi16(ss1, filter);
const __m256i s2_lo = _mm256_unpacklo_epi16(s[2], _mm256_setzero_si256());
const __m256i s2_hi = _mm256_unpackhi_epi16(s[2], _mm256_setzero_si256());
const __m256i s2x128_lo = _mm256_slli_epi32(s2_lo, 7);
const __m256i s2x128_hi = _mm256_slli_epi32(s2_hi, 7);
madds[0] = _mm256_add_epi32(madds[0], s2x128_lo);
madds[1] = _mm256_add_epi32(madds[1], s2x128_hi);
WienerHorizontalClip(madds, wiener_buffer);
}
inline void WienerHorizontalTap3Kernel(const __m256i s[3], const __m256i filter,
int16_t* const wiener_buffer) {
const __m256i s02 = _mm256_add_epi16(s[0], s[2]);
const __m256i ss0 = _mm256_unpacklo_epi16(s02, s[1]);
const __m256i ss1 = _mm256_unpackhi_epi16(s02, s[1]);
__m256i madds[2];
madds[0] = _mm256_madd_epi16(ss0, filter);
madds[1] = _mm256_madd_epi16(ss1, filter);
WienerHorizontalClip(madds, wiener_buffer);
}
inline void WienerHorizontalTap7(const uint16_t* src,
const ptrdiff_t src_stride,
const ptrdiff_t width, const int height,
const __m256i* const coefficients,
int16_t** const wiener_buffer) {
__m256i filter[2];
filter[0] = _mm256_shuffle_epi32(*coefficients, 0x0);
filter[1] = _mm256_shuffle_epi32(*coefficients, 0x55);
for (int y = height; y != 0; --y) {
ptrdiff_t x = 0;
do {
__m256i s[7];
s[0] = LoadUnaligned32(src + x + 0);
s[1] = LoadUnaligned32(src + x + 1);
s[2] = LoadUnaligned32(src + x + 2);
s[3] = LoadUnaligned32(src + x + 3);
s[4] = LoadUnaligned32(src + x + 4);
s[5] = LoadUnaligned32(src + x + 5);
s[6] = LoadUnaligned32(src + x + 6);
WienerHorizontalTap7Kernel(s, filter, *wiener_buffer + x);
x += 16;
} while (x < width);
src += src_stride;
*wiener_buffer += width;
}
}
inline void WienerHorizontalTap5(const uint16_t* src,
const ptrdiff_t src_stride,
const ptrdiff_t width, const int height,
const __m256i* const coefficients,
int16_t** const wiener_buffer) {
const __m256i filter =
_mm256_shuffle_epi8(*coefficients, _mm256_set1_epi32(0x05040302));
for (int y = height; y != 0; --y) {
ptrdiff_t x = 0;
do {
__m256i s[5];
s[0] = LoadUnaligned32(src + x + 0);
s[1] = LoadUnaligned32(src + x + 1);
s[2] = LoadUnaligned32(src + x + 2);
s[3] = LoadUnaligned32(src + x + 3);
s[4] = LoadUnaligned32(src + x + 4);
WienerHorizontalTap5Kernel(s, filter, *wiener_buffer + x);
x += 16;
} while (x < width);
src += src_stride;
*wiener_buffer += width;
}
}
inline void WienerHorizontalTap3(const uint16_t* src,
const ptrdiff_t src_stride,
const ptrdiff_t width, const int height,
const __m256i* const coefficients,
int16_t** const wiener_buffer) {
const auto filter = _mm256_shuffle_epi32(*coefficients, 0x55);
for (int y = height; y != 0; --y) {
ptrdiff_t x = 0;
do {
__m256i s[3];
s[0] = LoadUnaligned32(src + x + 0);
s[1] = LoadUnaligned32(src + x + 1);
s[2] = LoadUnaligned32(src + x + 2);
WienerHorizontalTap3Kernel(s, filter, *wiener_buffer + x);
x += 16;
} while (x < width);
src += src_stride;
*wiener_buffer += width;
}
}
inline void WienerHorizontalTap1(const uint16_t* src,
const ptrdiff_t src_stride,
const ptrdiff_t width, const int height,
int16_t** const wiener_buffer) {
for (int y = height; y != 0; --y) {
ptrdiff_t x = 0;
do {
const __m256i s0 = LoadUnaligned32(src + x);
const __m256i d0 = _mm256_slli_epi16(s0, 4);
StoreAligned32(*wiener_buffer + x, d0);
x += 16;
} while (x < width);
src += src_stride;
*wiener_buffer += width;
}
}
inline __m256i WienerVertical7(const __m256i a[4], const __m256i filter[4]) {
const __m256i madd0 = _mm256_madd_epi16(a[0], filter[0]);
const __m256i madd1 = _mm256_madd_epi16(a[1], filter[1]);
const __m256i madd2 = _mm256_madd_epi16(a[2], filter[2]);
const __m256i madd3 = _mm256_madd_epi16(a[3], filter[3]);
const __m256i madd01 = _mm256_add_epi32(madd0, madd1);
const __m256i madd23 = _mm256_add_epi32(madd2, madd3);
const __m256i sum = _mm256_add_epi32(madd01, madd23);
return _mm256_srai_epi32(sum, kInterRoundBitsVertical);
}
inline __m256i WienerVertical5(const __m256i a[3], const __m256i filter[3]) {
const __m256i madd0 = _mm256_madd_epi16(a[0], filter[0]);
const __m256i madd1 = _mm256_madd_epi16(a[1], filter[1]);
const __m256i madd2 = _mm256_madd_epi16(a[2], filter[2]);
const __m256i madd01 = _mm256_add_epi32(madd0, madd1);
const __m256i sum = _mm256_add_epi32(madd01, madd2);
return _mm256_srai_epi32(sum, kInterRoundBitsVertical);
}
inline __m256i WienerVertical3(const __m256i a[2], const __m256i filter[2]) {
const __m256i madd0 = _mm256_madd_epi16(a[0], filter[0]);
const __m256i madd1 = _mm256_madd_epi16(a[1], filter[1]);
const __m256i sum = _mm256_add_epi32(madd0, madd1);
return _mm256_srai_epi32(sum, kInterRoundBitsVertical);
}
inline __m256i WienerVerticalClip(const __m256i s[2]) {
const __m256i d = _mm256_packus_epi32(s[0], s[1]);
return _mm256_min_epu16(d, _mm256_set1_epi16(1023));
}
inline __m256i WienerVerticalFilter7(const __m256i a[7],
const __m256i filter[2]) {
const __m256i round = _mm256_set1_epi16(1 << (kInterRoundBitsVertical - 1));
__m256i b[4], c[2];
b[0] = _mm256_unpacklo_epi16(a[0], a[1]);
b[1] = _mm256_unpacklo_epi16(a[2], a[3]);
b[2] = _mm256_unpacklo_epi16(a[4], a[5]);
b[3] = _mm256_unpacklo_epi16(a[6], round);
c[0] = WienerVertical7(b, filter);
b[0] = _mm256_unpackhi_epi16(a[0], a[1]);
b[1] = _mm256_unpackhi_epi16(a[2], a[3]);
b[2] = _mm256_unpackhi_epi16(a[4], a[5]);
b[3] = _mm256_unpackhi_epi16(a[6], round);
c[1] = WienerVertical7(b, filter);
return WienerVerticalClip(c);
}
inline __m256i WienerVerticalFilter5(const __m256i a[5],
const __m256i filter[3]) {
const __m256i round = _mm256_set1_epi16(1 << (kInterRoundBitsVertical - 1));
__m256i b[3], c[2];
b[0] = _mm256_unpacklo_epi16(a[0], a[1]);
b[1] = _mm256_unpacklo_epi16(a[2], a[3]);
b[2] = _mm256_unpacklo_epi16(a[4], round);
c[0] = WienerVertical5(b, filter);
b[0] = _mm256_unpackhi_epi16(a[0], a[1]);
b[1] = _mm256_unpackhi_epi16(a[2], a[3]);
b[2] = _mm256_unpackhi_epi16(a[4], round);
c[1] = WienerVertical5(b, filter);
return WienerVerticalClip(c);
}
inline __m256i WienerVerticalFilter3(const __m256i a[3],
const __m256i filter[2]) {
const __m256i round = _mm256_set1_epi16(1 << (kInterRoundBitsVertical - 1));
__m256i b[2], c[2];
b[0] = _mm256_unpacklo_epi16(a[0], a[1]);
b[1] = _mm256_unpacklo_epi16(a[2], round);
c[0] = WienerVertical3(b, filter);
b[0] = _mm256_unpackhi_epi16(a[0], a[1]);
b[1] = _mm256_unpackhi_epi16(a[2], round);
c[1] = WienerVertical3(b, filter);
return WienerVerticalClip(c);
}
inline __m256i WienerVerticalTap7Kernel(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[2], __m256i a[7]) {
a[0] = LoadAligned32(wiener_buffer + 0 * wiener_stride);
a[1] = LoadAligned32(wiener_buffer + 1 * wiener_stride);
a[2] = LoadAligned32(wiener_buffer + 2 * wiener_stride);
a[3] = LoadAligned32(wiener_buffer + 3 * wiener_stride);
a[4] = LoadAligned32(wiener_buffer + 4 * wiener_stride);
a[5] = LoadAligned32(wiener_buffer + 5 * wiener_stride);
a[6] = LoadAligned32(wiener_buffer + 6 * wiener_stride);
return WienerVerticalFilter7(a, filter);
}
inline __m256i WienerVerticalTap5Kernel(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[3], __m256i a[5]) {
a[0] = LoadAligned32(wiener_buffer + 0 * wiener_stride);
a[1] = LoadAligned32(wiener_buffer + 1 * wiener_stride);
a[2] = LoadAligned32(wiener_buffer + 2 * wiener_stride);
a[3] = LoadAligned32(wiener_buffer + 3 * wiener_stride);
a[4] = LoadAligned32(wiener_buffer + 4 * wiener_stride);
return WienerVerticalFilter5(a, filter);
}
inline __m256i WienerVerticalTap3Kernel(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[2], __m256i a[3]) {
a[0] = LoadAligned32(wiener_buffer + 0 * wiener_stride);
a[1] = LoadAligned32(wiener_buffer + 1 * wiener_stride);
a[2] = LoadAligned32(wiener_buffer + 2 * wiener_stride);
return WienerVerticalFilter3(a, filter);
}
inline void WienerVerticalTap7Kernel2(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[2], __m256i d[2]) {
__m256i a[8];
d[0] = WienerVerticalTap7Kernel(wiener_buffer, wiener_stride, filter, a);
a[7] = LoadAligned32(wiener_buffer + 7 * wiener_stride);
d[1] = WienerVerticalFilter7(a + 1, filter);
}
inline void WienerVerticalTap5Kernel2(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[3], __m256i d[2]) {
__m256i a[6];
d[0] = WienerVerticalTap5Kernel(wiener_buffer, wiener_stride, filter, a);
a[5] = LoadAligned32(wiener_buffer + 5 * wiener_stride);
d[1] = WienerVerticalFilter5(a + 1, filter);
}
inline void WienerVerticalTap3Kernel2(const int16_t* wiener_buffer,
const ptrdiff_t wiener_stride,
const __m256i filter[2], __m256i d[2]) {
__m256i a[4];
d[0] = WienerVerticalTap3Kernel(wiener_buffer, wiener_stride, filter, a);
a[3] = LoadAligned32(wiener_buffer + 3 * wiener_stride);
d[1] = WienerVerticalFilter3(a + 1, filter);
}
inline void WienerVerticalTap7(const int16_t* wiener_buffer,
const ptrdiff_t width, const int height,
const int16_t coefficients[4], uint16_t* dst,
const ptrdiff_t dst_stride) {
const __m256i c = _mm256_broadcastq_epi64(LoadLo8(coefficients));
__m256i filter[4];
filter[0] = _mm256_shuffle_epi32(c, 0x0);
filter[1] = _mm256_shuffle_epi32(c, 0x55);
filter[2] = _mm256_shuffle_epi8(c, _mm256_set1_epi32(0x03020504));
filter[3] =
_mm256_set1_epi32((1 << 16) | static_cast<uint16_t>(coefficients[0]));
for (int y = height >> 1; y > 0; --y) {
ptrdiff_t x = 0;
do {
__m256i d[2];
WienerVerticalTap7Kernel2(wiener_buffer + x, width, filter, d);
StoreUnaligned32(dst + x, d[0]);
StoreUnaligned32(dst + dst_stride + x, d[1]);
x += 16;
} while (x < width);
dst += 2 * dst_stride;
wiener_buffer += 2 * width;
}
if ((height & 1) != 0) {
ptrdiff_t x = 0;
do {
__m256i a[7];
const __m256i d =
WienerVerticalTap7Kernel(wiener_buffer + x, width, filter, a);
StoreUnaligned32(dst + x, d);
x += 16;
} while (x < width);
}
}
inline void WienerVerticalTap5(const int16_t* wiener_buffer,
const ptrdiff_t width, const int height,
const int16_t coefficients[3], uint16_t* dst,
const ptrdiff_t dst_stride) {
const __m256i c = _mm256_broadcastq_epi64(LoadLo8(coefficients));
__m256i filter[3];
filter[0] = _mm256_shuffle_epi32(c, 0x0);
filter[1] = _mm256_shuffle_epi8(c, _mm256_set1_epi32(0x03020504));
filter[2] =
_mm256_set1_epi32((1 << 16) | static_cast<uint16_t>(coefficients[0]));
for (int y = height >> 1; y > 0; --y) {
ptrdiff_t x = 0;
do {
__m256i d[2];
WienerVerticalTap5Kernel2(wiener_buffer + x, width, filter, d);
StoreUnaligned32(dst + x, d[0]);
StoreUnaligned32(dst + dst_stride + x, d[1]);
x += 16;
} while (x < width);
dst += 2 * dst_stride;
wiener_buffer += 2 * width;
}
if ((height & 1) != 0) {
ptrdiff_t x = 0;
do {
__m256i a[5];
const __m256i d =
WienerVerticalTap5Kernel(wiener_buffer + x, width, filter, a);
StoreUnaligned32(dst + x, d);
x += 16;
} while (x < width);
}
}
inline void WienerVerticalTap3(const int16_t* wiener_buffer,
const ptrdiff_t width, const int height,
const int16_t coefficients[2], uint16_t* dst,
const ptrdiff_t dst_stride) {
__m256i filter[2];
filter[0] =
_mm256_set1_epi32(*reinterpret_cast<const int32_t*>(coefficients));
filter[1] =
_mm256_set1_epi32((1 << 16) | static_cast<uint16_t>(coefficients[0]));
for (int y = height >> 1; y > 0; --y) {
ptrdiff_t x = 0;
do {
__m256i d[2][2];
WienerVerticalTap3Kernel2(wiener_buffer + x, width, filter, d[0]);
StoreUnaligned32(dst + x, d[0][0]);
StoreUnaligned32(dst + dst_stride + x, d[0][1]);
x += 16;
} while (x < width);
dst += 2 * dst_stride;
wiener_buffer += 2 * width;
}
if ((height & 1) != 0) {
ptrdiff_t x = 0;
do {
__m256i a[3];
const __m256i d =
WienerVerticalTap3Kernel(wiener_buffer + x, width, filter, a);
StoreUnaligned32(dst + x, d);
x += 16;
} while (x < width);
}
}
inline void WienerVerticalTap1Kernel(const int16_t* const wiener_buffer,
uint16_t* const dst) {
const __m256i a = LoadAligned32(wiener_buffer);
const __m256i b = _mm256_add_epi16(a, _mm256_set1_epi16(8));
const __m256i c = _mm256_srai_epi16(b, 4);
const __m256i d = _mm256_max_epi16(c, _mm256_setzero_si256());
const __m256i e = _mm256_min_epi16(d, _mm256_set1_epi16(1023));
StoreUnaligned32(dst, e);
}
inline void WienerVerticalTap1(const int16_t* wiener_buffer,
const ptrdiff_t width, const int height,
uint16_t* dst, const ptrdiff_t dst_stride) {
for (int y = height >> 1; y > 0; --y) {
ptrdiff_t x = 0;
do {
WienerVerticalTap1Kernel(wiener_buffer + x, dst + x);
WienerVerticalTap1Kernel(wiener_buffer + width + x, dst + dst_stride + x);
x += 16;
} while (x < width);
dst += 2 * dst_stride;
wiener_buffer += 2 * width;
}
if ((height & 1) != 0) {
ptrdiff_t x = 0;
do {
WienerVerticalTap1Kernel(wiener_buffer + x, dst + x);
x += 16;
} while (x < width);
}
}
void WienerFilter_AVX2(
const RestorationUnitInfo& restoration_info, const void* const source,
const ptrdiff_t stride, const void* const top_border,
const ptrdiff_t top_border_stride, const void* const bottom_border,
const ptrdiff_t bottom_border_stride, const int width, const int height,
RestorationBuffer* const restoration_buffer, void* const dest) {
const int16_t* const number_leading_zero_coefficients =
restoration_info.wiener_info.number_leading_zero_coefficients;
const int number_rows_to_skip = std::max(
static_cast<int>(number_leading_zero_coefficients[WienerInfo::kVertical]),
1);
const ptrdiff_t wiener_stride = Align(width, 16);
int16_t* const wiener_buffer_vertical = restoration_buffer->wiener_buffer;
// The values are saturated to 13 bits before storing.
int16_t* wiener_buffer_horizontal =
wiener_buffer_vertical + number_rows_to_skip * wiener_stride;
// horizontal filtering.
// Over-reads up to 15 - |kRestorationHorizontalBorder| values.
const int height_horizontal =
height + kWienerFilterTaps - 1 - 2 * number_rows_to_skip;
const int height_extra = (height_horizontal - height) >> 1;
assert(height_extra <= 2);
const auto* const src = static_cast<const uint16_t*>(source);
const auto* const top = static_cast<const uint16_t*>(top_border);
const auto* const bottom = static_cast<const uint16_t*>(bottom_border);
const __m128i c =
LoadLo8(restoration_info.wiener_info.filter[WienerInfo::kHorizontal]);
const __m256i coefficients_horizontal = _mm256_broadcastq_epi64(c);
if (number_leading_zero_coefficients[WienerInfo::kHorizontal] == 0) {
WienerHorizontalTap7(top + (2 - height_extra) * top_border_stride - 3,
top_border_stride, wiener_stride, height_extra,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap7(src - 3, stride, wiener_stride, height,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap7(bottom - 3, bottom_border_stride, wiener_stride,
height_extra, &coefficients_horizontal,
&wiener_buffer_horizontal);
} else if (number_leading_zero_coefficients[WienerInfo::kHorizontal] == 1) {
WienerHorizontalTap5(top + (2 - height_extra) * top_border_stride - 2,
top_border_stride, wiener_stride, height_extra,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap5(src - 2, stride, wiener_stride, height,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap5(bottom - 2, bottom_border_stride, wiener_stride,
height_extra, &coefficients_horizontal,
&wiener_buffer_horizontal);
} else if (number_leading_zero_coefficients[WienerInfo::kHorizontal] == 2) {
// The maximum over-reads happen here.
WienerHorizontalTap3(top + (2 - height_extra) * top_border_stride - 1,
top_border_stride, wiener_stride, height_extra,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap3(src - 1, stride, wiener_stride, height,
&coefficients_horizontal, &wiener_buffer_horizontal);
WienerHorizontalTap3(bottom - 1, bottom_border_stride, wiener_stride,
height_extra, &coefficients_horizontal,
&wiener_buffer_horizontal);
} else {
assert(number_leading_zero_coefficients[WienerInfo::kHorizontal] == 3);
WienerHorizontalTap1(top + (2 - height_extra) * top_border_stride,
top_border_stride, wiener_stride, height_extra,
&wiener_buffer_horizontal);
WienerHorizontalTap1(src, stride, wiener_stride, height,
&wiener_buffer_horizontal);
WienerHorizontalTap1(bottom, bottom_border_stride, wiener_stride,
height_extra, &wiener_buffer_horizontal);
}
// vertical filtering.
// Over-writes up to 15 values.
const int16_t* const filter_vertical =
restoration_info.wiener_info.filter[WienerInfo::kVertical];
auto* dst = static_cast<uint16_t*>(dest);
if (number_leading_zero_coefficients[WienerInfo::kVertical] == 0) {
// Because the top row of |source| is a duplicate of the second row, and the
// bottom row of |source| is a duplicate of its above row, we can duplicate
// the top and bottom row of |wiener_buffer| accordingly.
memcpy(wiener_buffer_horizontal, wiener_buffer_horizontal - wiener_stride,
sizeof(*wiener_buffer_horizontal) * wiener_stride);
memcpy(restoration_buffer->wiener_buffer,
restoration_buffer->wiener_buffer + wiener_stride,
sizeof(*restoration_buffer->wiener_buffer) * wiener_stride);
WienerVerticalTap7(wiener_buffer_vertical, wiener_stride, height,
filter_vertical, dst, stride);
} else if (number_leading_zero_coefficients[WienerInfo::kVertical] == 1) {
WienerVerticalTap5(wiener_buffer_vertical + wiener_stride, wiener_stride,
height, filter_vertical + 1, dst, stride);
} else if (number_leading_zero_coefficients[WienerInfo::kVertical] == 2) {
WienerVerticalTap3(wiener_buffer_vertical + 2 * wiener_stride,
wiener_stride, height, filter_vertical + 2, dst, stride);
} else {
assert(number_leading_zero_coefficients[WienerInfo::kVertical] == 3);
WienerVerticalTap1(wiener_buffer_vertical + 3 * wiener_stride,
wiener_stride, height, dst, stride);
}
}
//------------------------------------------------------------------------------
// SGR
constexpr int kSumOffset = 24;
// SIMD overreads the number of pixels in SIMD registers - (width % 8) - 2 *
// padding pixels, where padding is 3 for Pass 1 and 2 for Pass 2. The number of
// bytes in SIMD registers is 16 for SSE4.1 and 32 for AVX2.
constexpr int kOverreadInBytesPass1_128 = 4;
constexpr int kOverreadInBytesPass2_128 = 8;
constexpr int kOverreadInBytesPass1_256 = kOverreadInBytesPass1_128 + 16;
constexpr int kOverreadInBytesPass2_256 = kOverreadInBytesPass2_128 + 16;
inline void LoadAligned16x2U16(const uint16_t* const src[2], const ptrdiff_t x,
__m128i dst[2]) {
dst[0] = LoadAligned16(src[0] + x);
dst[1] = LoadAligned16(src[1] + x);
}
inline void LoadAligned32x2U16(const uint16_t* const src[2], const ptrdiff_t x,
__m256i dst[2]) {
dst[0] = LoadAligned32(src[0] + x);
dst[1] = LoadAligned32(src[1] + x);
}
inline void LoadAligned32x2U16Msan(const uint16_t* const src[2],
const ptrdiff_t x, const ptrdiff_t border,
__m256i dst[2]) {
dst[0] = LoadAligned32Msan(src[0] + x, sizeof(**src) * (x + 16 - border));
dst[1] = LoadAligned32Msan(src[1] + x, sizeof(**src) * (x + 16 - border));
}
inline void LoadAligned16x3U16(const uint16_t* const src[3], const ptrdiff_t x,
__m128i dst[3]) {
dst[0] = LoadAligned16(src[0] + x);
dst[1] = LoadAligned16(src[1] + x);
dst[2] = LoadAligned16(src[2] + x);
}
inline void LoadAligned32x3U16(const uint16_t* const src[3], const ptrdiff_t x,
__m256i dst[3]) {
dst[0] = LoadAligned32(src[0] + x);
dst[1] = LoadAligned32(src[1] + x);
dst[2] = LoadAligned32(src[2] + x);
}
inline void LoadAligned32x3U16Msan(const uint16_t* const src[3],
const ptrdiff_t x, const ptrdiff_t border,
__m256i dst[3]) {
dst[0] = LoadAligned32Msan(src[0] + x, sizeof(**src) * (x + 16 - border));
dst[1] = LoadAligned32Msan(src[1] + x, sizeof(**src) * (x + 16 - border));
dst[2] = LoadAligned32Msan(src[2] + x, sizeof(**src) * (x + 16 - border));
}
inline void LoadAligned32U32(const uint32_t* const src, __m128i dst[2]) {
dst[0] = LoadAligned16(src + 0);
dst[1] = LoadAligned16(src + 4);
}
inline void LoadAligned32x2U32(const uint32_t* const src[2], const ptrdiff_t x,
__m128i dst[2][2]) {
LoadAligned32U32(src[0] + x, dst[0]);
LoadAligned32U32(src[1] + x, dst[1]);
}
inline void LoadAligned64x2U32(const uint32_t* const src[2], const ptrdiff_t x,
__m256i dst[2][2]) {
LoadAligned64(src[0] + x, dst[0]);
LoadAligned64(src[1] + x, dst[1]);
}
inline void LoadAligned64x2U32Msan(const uint32_t* const src[2],
const ptrdiff_t x, const ptrdiff_t border,
__m256i dst[2][2]) {
LoadAligned64Msan(src[0] + x, sizeof(**src) * (x + 16 - border), dst[0]);
LoadAligned64Msan(src[1] + x, sizeof(**src) * (x + 16 - border), dst[1]);
}
inline void LoadAligned32x3U32(const uint32_t* const src[3], const ptrdiff_t x,
__m128i dst[3][2]) {
LoadAligned32U32(src[0] + x, dst[0]);
LoadAligned32U32(src[1] + x, dst[1]);
LoadAligned32U32(src[2] + x, dst[2]);
}
inline void LoadAligned64x3U32(const uint32_t* const src[3], const ptrdiff_t x,
__m256i dst[3][2]) {
LoadAligned64(src[0] + x, dst[0]);
LoadAligned64(src[1] + x, dst[1]);
LoadAligned64(src[2] + x, dst[2]);
}
inline void LoadAligned64x3U32Msan(const uint32_t* const src[3],
const ptrdiff_t x, const ptrdiff_t border,
__m256i dst[3][2]) {
LoadAligned64Msan(src[0] + x, sizeof(**src) * (x + 16 - border), dst[0]);
LoadAligned64Msan(src[1] + x, sizeof(**src) * (x + 16 - border), dst[1]);
LoadAligned64Msan(src[2] + x, sizeof(**src) * (x + 16 - border), dst[2]);
}
inline void StoreAligned32U32(uint32_t* const dst, const __m128i src[2]) {
StoreAligned16(dst + 0, src[0]);
StoreAligned16(dst + 4, src[1]);
}
// The AVX2 ymm register holds ma[0], ma[1], ..., ma[7], and ma[16], ma[17],
// ..., ma[23].
// There is an 8 pixel gap between the first half and the second half.
constexpr int kMaStoreOffset = 8;
inline void StoreAligned32_ma(uint16_t* src, const __m256i v) {
StoreAligned16(src + 0 * 8, _mm256_extracti128_si256(v, 0));
StoreAligned16(src + 2 * 8, _mm256_extracti128_si256(v, 1));
}
inline void StoreAligned64_ma(uint16_t* src, const __m256i v[2]) {
// The next 4 lines are much faster than:
// StoreAligned32(src + 0, _mm256_permute2x128_si256(v[0], v[1], 0x20));
// StoreAligned32(src + 16, _mm256_permute2x128_si256(v[0], v[1], 0x31));
StoreAligned16(src + 0 * 8, _mm256_extracti128_si256(v[0], 0));
StoreAligned16(src + 1 * 8, _mm256_extracti128_si256(v[1], 0));
StoreAligned16(src + 2 * 8, _mm256_extracti128_si256(v[0], 1));
StoreAligned16(src + 3 * 8, _mm256_extracti128_si256(v[1], 1));
}
// Don't use _mm_cvtepu8_epi16() or _mm_cvtepu16_epi32() in the following
// functions. Some compilers may generate super inefficient code and the whole
// decoder could be 15% slower.
inline __m256i VaddlLo8(const __m256i src0, const __m256i src1) {
const __m256i s0 = _mm256_unpacklo_epi8(src0, _mm256_setzero_si256());
const __m256i s1 = _mm256_unpacklo_epi8(src1, _mm256_setzero_si256());
return _mm256_add_epi16(s0, s1);
}
inline __m256i VaddlHi8(const __m256i src0, const __m256i src1) {
const __m256i s0 = _mm256_unpackhi_epi8(src0, _mm256_setzero_si256());
const __m256i s1 = _mm256_unpackhi_epi8(src1, _mm256_setzero_si256());
return _mm256_add_epi16(s0, s1);
}
inline __m256i VaddwLo8(const __m256i src0, const __m256i src1) {
const __m256i s1 = _mm256_unpacklo_epi8(src1, _mm256_setzero_si256());
return _mm256_add_epi16(src0, s1);
}
inline __m256i VaddwHi8(const __m256i src0, const __m256i src1) {
const __m256i s1 = _mm256_unpackhi_epi8(src1, _mm256_setzero_si256());
return _mm256_add_epi16(src0, s1);
}
inline __m256i VmullNLo8(const __m256i src0, const int src1) {
const __m256i s0 = _mm256_unpacklo_epi16(src0, _mm256_setzero_si256());
return _mm256_madd_epi16(s0, _mm256_set1_epi32(src1));
}
inline __m256i VmullNHi8(const __m256i src0, const int src1) {
const __m256i s0 = _mm256_unpackhi_epi16(src0, _mm256_setzero_si256());
return _mm256_madd_epi16(s0, _mm256_set1_epi32(src1));
}
inline __m128i VmullLo16(const __m128i src0, const __m128i src1) {
const __m128i s0 = _mm_unpacklo_epi16(src0, _mm_setzero_si128());
const __m128i s1 = _mm_unpacklo_epi16(src1, _mm_setzero_si128());
return _mm_madd_epi16(s0, s1);
}
inline __m256i VmullLo16(const __m256i src0, const __m256i src1) {
const __m256i s0 = _mm256_unpacklo_epi16(src0, _mm256_setzero_si256());
const __m256i s1 = _mm256_unpacklo_epi16(src1, _mm256_setzero_si256());
return _mm256_madd_epi16(s0, s1);
}
inline __m128i VmullHi16(const __m128i src0, const __m128i src1) {
const __m128i s0 = _mm_unpackhi_epi16(src0, _mm_setzero_si128());
const __m128i s1 = _mm_unpackhi_epi16(src1, _mm_setzero_si128());
return _mm_madd_epi16(s0, s1);
}
inline __m256i VmullHi16(const __m256i src0, const __m256i src1) {
const __m256i s0 = _mm256_unpackhi_epi16(src0, _mm256_setzero_si256());
const __m256i s1 = _mm256_unpackhi_epi16(src1, _mm256_setzero_si256());
return _mm256_madd_epi16(s0, s1);
}
inline __m128i VrshrU16(const __m128i src0, const int src1) {
const __m128i sum = _mm_add_epi16(src0, _mm_set1_epi16(1 << (src1 - 1)));
return _mm_srli_epi16(sum, src1);
}
inline __m256i VrshrU16(const __m256i src0, const int src1) {
const __m256i sum =
_mm256_add_epi16(src0, _mm256_set1_epi16(1 << (src1 - 1)));
return _mm256_srli_epi16(sum, src1);
}
inline __m256i VrshrS32(const __m256i src0, const int src1) {
const __m256i sum =
_mm256_add_epi32(src0, _mm256_set1_epi32(1 << (src1 - 1)));
return _mm256_srai_epi32(sum, src1);
}
inline __m128i VrshrU32(const __m128i src0, const int src1) {
const __m128i sum = _mm_add_epi32(src0, _mm_set1_epi32(1 << (src1 - 1)));
return _mm_srli_epi32(sum, src1);
}
inline __m256i VrshrU32(const __m256i src0, const int src1) {
const __m256i sum =
_mm256_add_epi32(src0, _mm256_set1_epi32(1 << (src1 - 1)));
return _mm256_srli_epi32(sum, src1);
}
inline void Square(const __m128i src, __m128i dst[2]) {
const __m128i s0 = _mm_unpacklo_epi16(src, _mm_setzero_si128());
const __m128i s1 = _mm_unpackhi_epi16(src, _mm_setzero_si128());
dst[0] = _mm_madd_epi16(s0, s0);
dst[1] = _mm_madd_epi16(s1, s1);
}
inline void Square(const __m256i src, __m256i dst[2]) {
const __m256i s0 = _mm256_unpacklo_epi16(src, _mm256_setzero_si256());
const __m256i s1 = _mm256_unpackhi_epi16(src, _mm256_setzero_si256());
dst[0] = _mm256_madd_epi16(s0, s0);
dst[1] = _mm256_madd_epi16(s1, s1);
}
inline void Prepare3_8(const __m256i src[2], __m256i dst[3]) {
dst[0] = _mm256_alignr_epi8(src[1], src[0], 0);
dst[1] = _mm256_alignr_epi8(src[1], src[0], 1);
dst[2] = _mm256_alignr_epi8(src[1], src[0], 2);
}
inline void Prepare3_16(const __m128i src[2], __m128i dst[3]) {
dst[0] = src[0];
dst[1] = _mm_alignr_epi8(src[1], src[0], 2);
dst[2] = _mm_alignr_epi8(src[1], src[0], 4);
}
inline void Prepare3_32(const __m128i src[2], __m128i dst[3]) {
dst[0] = src[0];
dst[1] = _mm_alignr_epi8(src[1], src[0], 4);
dst[2] = _mm_alignr_epi8(src[1], src[0], 8);
}
inline void Prepare3_32(const __m256i src[2], __m256i dst[3]) {
dst[0] = src[0];
dst[1] = _mm256_alignr_epi8(src[1], src[0], 4);
dst[2] = _mm256_alignr_epi8(src[1], src[0], 8);
}
inline void Prepare5_16(const __m128i src[2], __m128i dst[5]) {
Prepare3_16(src, dst);
dst[3] = _mm_alignr_epi8(src[1], src[0], 6);
dst[4] = _mm_alignr_epi8(src[1], src[0], 8);
}
inline void Prepare5_32(const __m128i src[2], __m128i dst[5]) {
Prepare3_32(src, dst);
dst[3] = _mm_alignr_epi8(src[1], src[0], 12);
dst[4] = src[1];
}
inline void Prepare5_32(const __m256i src[2], __m256i dst[5]) {
Prepare3_32(src, dst);
dst[3] = _mm256_alignr_epi8(src[1], src[0], 12);
dst[4] = src[1];
}
inline __m128i Sum3_16(const __m128i src0, const __m128i src1,
const __m128i src2) {
const __m128i sum = _mm_add_epi16(src0, src1);
return _mm_add_epi16(sum, src2);
}
inline __m256i Sum3_16(const __m256i src0, const __m256i src1,
const __m256i src2) {
const __m256i sum = _mm256_add_epi16(src0, src1);
return _mm256_add_epi16(sum, src2);
}
inline __m128i Sum3_16(const __m128i src[3]) {
return Sum3_16(src[0], src[1], src[2]);
}
inline __m256i Sum3_16(const __m256i src[3]) {
return Sum3_16(src[0], src[1], src[2]);
}
inline __m128i Sum3_32(const __m128i src0, const __m128i src1,
const __m128i src2) {
const __m128i sum = _mm_add_epi32(src0, src1);
return _mm_add_epi32(sum, src2);
}
inline __m256i Sum3_32(const __m256i src0, const __m256i src1,
const __m256i src2) {
const __m256i sum = _mm256_add_epi32(src0, src1);
return _mm256_add_epi32(sum, src2);
}
inline __m128i Sum3_32(const __m128i src[3]) {
return Sum3_32(src[0], src[1], src[2]);
}
inline __m256i Sum3_32(const __m256i src[3]) {
return Sum3_32(src[0], src[1], src[2]);
}
inline void Sum3_32(const __m128i src[3][2], __m128i dst[2]) {
dst[0] = Sum3_32(src[0][0], src[1][0], src[2][0]);
dst[1] = Sum3_32(src[0][1], src[1][1], src[2][1]);
}
inline void Sum3_32(const __m256i src[3][2], __m256i dst[2]) {
dst[0] = Sum3_32(src[0][0], src[1][0], src[2][0]);
dst[1] = Sum3_32(src[0][1], src[1][1], src[2][1]);
}
inline __m256i Sum3WLo16(const __m256i src[3]) {
const __m256i sum = VaddlLo8(src[0], src[1]);
return VaddwLo8(sum, src[2]);
}
inline __m256i Sum3WHi16(const __m256i src[3]) {
const __m256i sum = VaddlHi8(src[0], src[1]);
return VaddwHi8(sum, src[2]);
}
inline __m128i Sum5_16(const __m128i src[5]) {
const __m128i sum01 = _mm_add_epi16(src[0], src[1]);
const __m128i sum23 = _mm_add_epi16(src[2], src[3]);
const __m128i sum = _mm_add_epi16(sum01, sum23);
return _mm_add_epi16(sum, src[4]);
}
inline __m256i Sum5_16(const __m256i src[5]) {
const __m256i sum01 = _mm256_add_epi16(src[0], src[1]);
const __m256i sum23 = _mm256_add_epi16(src[2], src[3]);
const __m256i sum = _mm256_add_epi16(sum01, sum23);
return _mm256_add_epi16(sum, src[4]);
}
inline __m128i Sum5_32(const __m128i* const src0, const __m128i* const src1,
const __m128i* const src2, const __m128i* const src3,
const __m128i* const src4) {
const __m128i sum01 = _mm_add_epi32(*src0, *src1);
const __m128i sum23 = _mm_add_epi32(*src2, *src3);
const __m128i sum = _mm_add_epi32(sum01, sum23);
return _mm_add_epi32(sum, *src4);
}
inline __m256i Sum5_32(const __m256i* const src0, const __m256i* const src1,
const __m256i* const src2, const __m256i* const src3,
const __m256i* const src4) {
const __m256i sum01 = _mm256_add_epi32(*src0, *src1);
const __m256i sum23 = _mm256_add_epi32(*src2, *src3);
const __m256i sum = _mm256_add_epi32(sum01, sum23);
return _mm256_add_epi32(sum, *src4);
}
inline __m128i Sum5_32(const __m128i src[5]) {
return Sum5_32(&src[0], &src[1], &src[2], &src[3], &src[4]);
}
inline __m256i Sum5_32(const __m256i src[5]) {
return Sum5_32(&src[0], &src[1], &src[2], &src[3], &src[4]);
}
inline void Sum5_32(const __m128i src[5][2], __m128i dst[2]) {
dst[0] = Sum5_32(&src[0][0], &src[1][0], &src[2][0], &src[3][0], &src[4][0]);
dst[1] = Sum5_32(&src[0][1], &src[1][1], &src[2][1], &src[3][1], &src[4][1]);
}
inline void Sum5_32(const __m256i src[5][2], __m256i dst[2]) {
dst[0] = Sum5_32(&src[0][0], &src[1][0], &src[2][0], &src[3][0], &src[4][0]);
dst[1] = Sum5_32(&src[0][1], &src[1][1], &src[2][1], &src[3][1], &src[4][1]);
}
inline __m128i Sum3Horizontal16(const __m128i src[2]) {
__m128i s[3];
Prepare3_16(src, s);
return Sum3_16(s);
}
inline __m256i Sum3Horizontal16(const uint16_t* const src,
const ptrdiff_t over_read_in_bytes) {
__m256i s[3];
s[0] = LoadUnaligned32Msan(src + 0, over_read_in_bytes + 0);
s[1] = LoadUnaligned32Msan(src + 1, over_read_in_bytes + 2);
s[2] = LoadUnaligned32Msan(src + 2, over_read_in_bytes + 4);
return Sum3_16(s);
}
inline __m128i Sum5Horizontal16(const __m128i src[2]) {
__m128i s[5];
Prepare5_16(src, s);
return Sum5_16(s);
}
inline __m256i Sum5Horizontal16(const uint16_t* const src,
const ptrdiff_t over_read_in_bytes) {
__m256i s[5];
s[0] = LoadUnaligned32Msan(src + 0, over_read_in_bytes + 0);
s[1] = LoadUnaligned32Msan(src + 1, over_read_in_bytes + 2);
s[2] = LoadUnaligned32Msan(src + 2, over_read_in_bytes + 4);
s[3] = LoadUnaligned32Msan(src + 3, over_read_in_bytes + 6);
s[4] = LoadUnaligned32Msan(src + 4, over_read_in_bytes + 8);
return Sum5_16(s);
}
inline void SumHorizontal16(const uint16_t* const src,
const ptrdiff_t over_read_in_bytes,
__m256i* const row3, __m256i* const row5) {
__m256i s[5];
s[0] = LoadUnaligned32Msan(src + 0, over_read_in_bytes + 0);
s[1] = LoadUnaligned32Msan(src + 1, over_read_in_bytes + 2);
s[2] = LoadUnaligned32Msan(src + 2, over_read_in_bytes + 4);
s[3] = LoadUnaligned32Msan(src + 3, over_read_in_bytes + 6);
s[4] = LoadUnaligned32Msan(src + 4, over_read_in_bytes + 8);
const __m256i sum04 = _mm256_add_epi16(s[0], s[4]);
*row3 = Sum3_16(s + 1);
*row5 = _mm256_add_epi16(sum04, *row3);
}
inline void SumHorizontal16(const uint16_t* const src,
const ptrdiff_t over_read_in_bytes,
__m256i* const row3_0, __m256i* const row3_1,
__m256i* const row5_0, __m256i* const row5_1) {
SumHorizontal16(src + 0, over_read_in_bytes + 0, row3_0, row5_0);
SumHorizontal16(src + 16, over_read_in_bytes + 32, row3_1, row5_1);
}
inline void SumHorizontal32(const __m128i src[5], __m128i* const row_sq3,
__m128i* const row_sq5) {
const __m128i sum04 = _mm_add_epi32(src[0], src[4]);
*row_sq3 = Sum3_32(src + 1);
*row_sq5 = _mm_add_epi32(sum04, *row_sq3);
}
inline void SumHorizontal32(const __m256i src[5], __m256i* const row_sq3,
__m256i* const row_sq5) {
const __m256i sum04 = _mm256_add_epi32(src[0], src[4]);
*row_sq3 = Sum3_32(src + 1);
*row_sq5 = _mm256_add_epi32(sum04, *row_sq3);
}
inline void SumHorizontal32(const __m128i src[3], __m128i* const row_sq3_0,
__m128i* const row_sq3_1, __m128i* const row_sq5_0,
__m128i* const row_sq5_1) {
__m128i s[5];
Prepare5_32(src + 0, s);
SumHorizontal32(s, row_sq3_0, row_sq5_0);
Prepare5_32(src + 1, s);
SumHorizontal32(s, row_sq3_1, row_sq5_1);
}
inline void SumHorizontal32(const __m256i src[3], __m256i* const row_sq3_0,
__m256i* const row_sq3_1, __m256i* const row_sq5_0,
__m256i* const row_sq5_1) {
__m256i s[5];
Prepare5_32(src + 0, s);
SumHorizontal32(s, row_sq3_0, row_sq5_0);
Prepare5_32(src + 1, s);
SumHorizontal32(s, row_sq3_1, row_sq5_1);
}
inline void Sum3Horizontal32(const __m128i src[3], __m128i dst[2]) {
__m128i s[3];
Prepare3_32(src + 0, s);
dst[0] = Sum3_32(s);
Prepare3_32(src + 1, s);
dst[1] = Sum3_32(s);
}
inline void Sum3Horizontal32(const __m256i src[3], __m256i dst[2]) {
__m256i s[3];
Prepare3_32(src + 0, s);
dst[0] = Sum3_32(s);
Prepare3_32(src + 1, s);
dst[1] = Sum3_32(s);
}
inline void Sum5Horizontal32(const __m128i src[3], __m128i dst[2]) {
__m128i s[5];
Prepare5_32(src + 0, s);
dst[0] = Sum5_32(s);
Prepare5_32(src + 1, s);
dst[1] = Sum5_32(s);
}
inline void Sum5Horizontal32(const __m256i src[3], __m256i dst[2]) {
__m256i s[5];
Prepare5_32(src + 0, s);
dst[0] = Sum5_32(s);
Prepare5_32(src + 1, s);
dst[1] = Sum5_32(s);
}
void SumHorizontal16(const __m128i src[2], __m128i* const row3,
__m128i* const row5) {
__m128i s[5];
Prepare5_16(src, s);
const __m128i sum04 = _mm_add_epi16(s[0], s[4]);
*row3 = Sum3_16(s + 1);
*row5 = _mm_add_epi16(sum04, *row3);
}
inline __m256i Sum343Lo(const __m256i ma3[3]) {
const __m256i sum = Sum3WLo16(ma3);
const __m256i sum3 = Sum3_16(sum, sum, sum);
return VaddwLo8(sum3, ma3[1]);
}
inline __m256i Sum343Hi(const __m256i ma3[3]) {
const __m256i sum = Sum3WHi16(ma3);
const __m256i sum3 = Sum3_16(sum, sum, sum);
return VaddwHi8(sum3, ma3[1]);
}
inline __m256i Sum343(const __m256i src[3]) {
const __m256i sum = Sum3_32(src);
const __m256i sum3 = Sum3_32(sum, sum, sum);
return _mm256_add_epi32(sum3, src[1]);
}
inline void Sum343(const __m256i src[3], __m256i dst[2]) {
__m256i s[3];
Prepare3_32(src + 0, s);
dst[0] = Sum343(s);
Prepare3_32(src + 1, s);
dst[1] = Sum343(s);
}
inline __m256i Sum565Lo(const __m256i src[3]) {
const __m256i sum = Sum3WLo16(src);
const __m256i sum4 = _mm256_slli_epi16(sum, 2);
const __m256i sum5 = _mm256_add_epi16(sum4, sum);
return VaddwLo8(sum5, src[1]);
}
inline __m256i Sum565Hi(const __m256i src[3]) {
const __m256i sum = Sum3WHi16(src);
const __m256i sum4 = _mm256_slli_epi16(sum, 2);
const __m256i sum5 = _mm256_add_epi16(sum4, sum);
return VaddwHi8(sum5, src[1]);
}
inline __m256i Sum565(const __m256i src[3]) {
const __m256i sum = Sum3_32(src);
const __m256i sum4 = _mm256_slli_epi32(sum, 2);
const __m256i sum5 = _mm256_add_epi32(sum4, sum);
return _mm256_add_epi32(sum5, src[1]);
}
inline void Sum565(const __m256i src[3], __m256i dst[2]) {
__m256i s[3];
Prepare3_32(src + 0, s);
dst[0] = Sum565(s);
Prepare3_32(src + 1, s);
dst[1] = Sum565(s);
}
inline void BoxSum(const uint16_t* src, const ptrdiff_t src_stride,
const ptrdiff_t width, const ptrdiff_t sum_stride,
const ptrdiff_t sum_width, uint16_t* sum3, uint16_t* sum5,
uint32_t* square_sum3, uint32_t* square_sum5) {
const ptrdiff_t overread_in_bytes_128 =
kOverreadInBytesPass1_128 - sizeof(*src) * width;
const ptrdiff_t overread_in_bytes_256 =
kOverreadInBytesPass1_256 - sizeof(*src) * width;
int y = 2;
do {
__m128i s0[2], sq_128[4], s3, s5, sq3[2], sq5[2];
__m256i sq[8];
s0[0] = LoadUnaligned16Msan(src + 0, overread_in_bytes_128 + 0);
s0[1] = LoadUnaligned16Msan(src + 8, overread_in_bytes_128 + 16);
Square(s0[0], sq_128 + 0);
Square(s0[1], sq_128 + 2);
SumHorizontal16(s0, &s3, &s5);
StoreAligned16(sum3, s3);
StoreAligned16(sum5, s5);
SumHorizontal32(sq_128, &sq3[0], &sq3[1], &sq5[0], &sq5[1]);
StoreAligned32U32(square_sum3, sq3);
StoreAligned32U32(square_sum5, sq5);
src += 8;
sum3 += 8;
sum5 += 8;
square_sum3 += 8;
square_sum5 += 8;
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
ptrdiff_t x = sum_width;
do {
__m256i s[2], row3[2], row5[2], row_sq3[2], row_sq5[2];
s[0] = LoadUnaligned32Msan(
src + 8, overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 8));
s[1] = LoadUnaligned32Msan(
src + 24,
overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 24));
Square(s[0], sq + 2);
Square(s[1], sq + 6);
sq[0] = _mm256_permute2x128_si256(sq[0], sq[2], 0x21);
sq[1] = _mm256_permute2x128_si256(sq[1], sq[3], 0x21);
sq[4] = _mm256_permute2x128_si256(sq[2], sq[6], 0x21);
sq[5] = _mm256_permute2x128_si256(sq[3], sq[7], 0x21);
SumHorizontal16(
src, overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 8),
&row3[0], &row3[1], &row5[0], &row5[1]);
StoreAligned64(sum3, row3);
StoreAligned64(sum5, row5);
SumHorizontal32(sq + 0, &row_sq3[0], &row_sq3[1], &row_sq5[0],
&row_sq5[1]);
StoreAligned64(square_sum3 + 0, row_sq3);
StoreAligned64(square_sum5 + 0, row_sq5);
SumHorizontal32(sq + 4, &row_sq3[0], &row_sq3[1], &row_sq5[0],
&row_sq5[1]);
StoreAligned64(square_sum3 + 16, row_sq3);
StoreAligned64(square_sum5 + 16, row_sq5);
sq[0] = sq[6];
sq[1] = sq[7];
src += 32;
sum3 += 32;
sum5 += 32;
square_sum3 += 32;
square_sum5 += 32;
x -= 32;
} while (x != 0);
src += src_stride - sum_width - 8;
sum3 += sum_stride - sum_width - 8;
sum5 += sum_stride - sum_width - 8;
square_sum3 += sum_stride - sum_width - 8;
square_sum5 += sum_stride - sum_width - 8;
} while (--y != 0);
}
template <int size>
inline void BoxSum(const uint16_t* src, const ptrdiff_t src_stride,
const ptrdiff_t width, const ptrdiff_t sum_stride,
const ptrdiff_t sum_width, uint16_t* sums,
uint32_t* square_sums) {
static_assert(size == 3 || size == 5, "");
int overread_in_bytes_128, overread_in_bytes_256;
if (size == 3) {
overread_in_bytes_128 = kOverreadInBytesPass2_128;
overread_in_bytes_256 = kOverreadInBytesPass2_256;
} else {
overread_in_bytes_128 = kOverreadInBytesPass1_128;
overread_in_bytes_256 = kOverreadInBytesPass1_256;
}
overread_in_bytes_128 -= sizeof(*src) * width;
overread_in_bytes_256 -= sizeof(*src) * width;
int y = 2;
do {
__m128i s_128[2], ss, sq_128[4], sqs[2];
__m256i sq[8];
s_128[0] = LoadUnaligned16Msan(src + 0, overread_in_bytes_128);
s_128[1] = LoadUnaligned16Msan(src + 8, overread_in_bytes_128 + 16);
Square(s_128[0], sq_128 + 0);
Square(s_128[1], sq_128 + 2);
if (size == 3) {
ss = Sum3Horizontal16(s_128);
Sum3Horizontal32(sq_128, sqs);
} else {
ss = Sum5Horizontal16(s_128);
Sum5Horizontal32(sq_128, sqs);
}
StoreAligned16(sums, ss);
StoreAligned32U32(square_sums, sqs);
src += 8;
sums += 8;
square_sums += 8;
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
ptrdiff_t x = sum_width;
do {
__m256i s[2], row[2], row_sq[4];
s[0] = LoadUnaligned32Msan(
src + 8, overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 8));
s[1] = LoadUnaligned32Msan(
src + 24,
overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 24));
Square(s[0], sq + 2);
Square(s[1], sq + 6);
sq[0] = _mm256_permute2x128_si256(sq[0], sq[2], 0x21);
sq[1] = _mm256_permute2x128_si256(sq[1], sq[3], 0x21);
sq[4] = _mm256_permute2x128_si256(sq[2], sq[6], 0x21);
sq[5] = _mm256_permute2x128_si256(sq[3], sq[7], 0x21);
if (size == 3) {
row[0] = Sum3Horizontal16(
src, overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 8));
row[1] =
Sum3Horizontal16(src + 16, overread_in_bytes_256 +
sizeof(*src) * (sum_width - x + 24));
Sum3Horizontal32(sq + 0, row_sq + 0);
Sum3Horizontal32(sq + 4, row_sq + 2);
} else {
row[0] = Sum5Horizontal16(
src, overread_in_bytes_256 + sizeof(*src) * (sum_width - x + 8));
row[1] =
Sum5Horizontal16(src + 16, overread_in_bytes_256 +
sizeof(*src) * (sum_width - x + 24));
Sum5Horizontal32(sq + 0, row_sq + 0);
Sum5Horizontal32(sq + 4, row_sq + 2);
}
StoreAligned64(sums, row);
StoreAligned64(square_sums + 0, row_sq + 0);
StoreAligned64(square_sums + 16, row_sq + 2);
sq[0] = sq[6];
sq[1] = sq[7];
src += 32;
sums += 32;
square_sums += 32;
x -= 32;
} while (x != 0);
src += src_stride - sum_width - 8;
sums += sum_stride - sum_width - 8;
square_sums += sum_stride - sum_width - 8;
} while (--y != 0);
}
template <int n>
inline __m128i CalculateMa(const __m128i sum, const __m128i sum_sq,
const uint32_t scale) {
static_assert(n == 9 || n == 25, "");
// a = |sum_sq|
// d = |sum|
// p = (a * n < d * d) ? 0 : a * n - d * d;
const __m128i dxd = _mm_madd_epi16(sum, sum);
// _mm_mullo_epi32() has high latency. Using shifts and additions instead.
// Some compilers could do this for us but we make this explicit.
// return _mm_mullo_epi32(sum_sq, _mm_set1_epi32(n));
__m128i axn = _mm_add_epi32(sum_sq, _mm_slli_epi32(sum_sq, 3));
if (n == 25) axn = _mm_add_epi32(axn, _mm_slli_epi32(sum_sq, 4));
const __m128i sub = _mm_sub_epi32(axn, dxd);
const __m128i p = _mm_max_epi32(sub, _mm_setzero_si128());
const __m128i pxs = _mm_mullo_epi32(p, _mm_set1_epi32(scale));
return VrshrU32(pxs, kSgrProjScaleBits);
}
template <int n>
inline __m128i CalculateMa(const __m128i sum, const __m128i sum_sq[2],
const uint32_t scale) {
static_assert(n == 9 || n == 25, "");
const __m128i b = VrshrU16(sum, 2);
const __m128i sum_lo = _mm_unpacklo_epi16(b, _mm_setzero_si128());
const __m128i sum_hi = _mm_unpackhi_epi16(b, _mm_setzero_si128());
const __m128i z0 = CalculateMa<n>(sum_lo, VrshrU32(sum_sq[0], 4), scale);
const __m128i z1 = CalculateMa<n>(sum_hi, VrshrU32(sum_sq[1], 4), scale);
return _mm_packus_epi32(z0, z1);
}
template <int n>
inline __m256i CalculateMa(const __m256i sum, const __m256i sum_sq,
const uint32_t scale) {
static_assert(n == 9 || n == 25, "");
// a = |sum_sq|
// d = |sum|
// p = (a * n < d * d) ? 0 : a * n - d * d;
const __m256i dxd = _mm256_madd_epi16(sum, sum);
// _mm256_mullo_epi32() has high latency. Using shifts and additions instead.
// Some compilers could do this for us but we make this explicit.
// return _mm256_mullo_epi32(sum_sq, _mm256_set1_epi32(n));
__m256i axn = _mm256_add_epi32(sum_sq, _mm256_slli_epi32(sum_sq, 3));
if (n == 25) axn = _mm256_add_epi32(axn, _mm256_slli_epi32(sum_sq, 4));
const __m256i sub = _mm256_sub_epi32(axn, dxd);
const __m256i p = _mm256_max_epi32(sub, _mm256_setzero_si256());
const __m256i pxs = _mm256_mullo_epi32(p, _mm256_set1_epi32(scale));
return VrshrU32(pxs, kSgrProjScaleBits);
}
template <int n>
inline __m256i CalculateMa(const __m256i sum, const __m256i sum_sq[2],
const uint32_t scale) {
static_assert(n == 9 || n == 25, "");
const __m256i b = VrshrU16(sum, 2);
const __m256i sum_lo = _mm256_unpacklo_epi16(b, _mm256_setzero_si256());
const __m256i sum_hi = _mm256_unpackhi_epi16(b, _mm256_setzero_si256());
const __m256i z0 = CalculateMa<n>(sum_lo, VrshrU32(sum_sq[0], 4), scale);
const __m256i z1 = CalculateMa<n>(sum_hi, VrshrU32(sum_sq[1], 4), scale);
return _mm256_packus_epi32(z0, z1);
}
inline void CalculateB5(const __m128i sum, const __m128i ma, __m128i b[2]) {
// one_over_n == 164.
constexpr uint32_t one_over_n =
((1 << kSgrProjReciprocalBits) + (25 >> 1)) / 25;
// one_over_n_quarter == 41.
constexpr uint32_t one_over_n_quarter = one_over_n >> 2;
static_assert(one_over_n == one_over_n_quarter << 2, "");
// |ma| is in range [0, 255].
const __m128i m = _mm_maddubs_epi16(ma, _mm_set1_epi16(one_over_n_quarter));
const __m128i m0 = VmullLo16(m, sum);
const __m128i m1 = VmullHi16(m, sum);
b[0] = VrshrU32(m0, kSgrProjReciprocalBits - 2);
b[1] = VrshrU32(m1, kSgrProjReciprocalBits - 2);
}
inline void CalculateB5(const __m256i sum, const __m256i ma, __m256i b[2]) {
// one_over_n == 164.
constexpr uint32_t one_over_n =
((1 << kSgrProjReciprocalBits) + (25 >> 1)) / 25;
// one_over_n_quarter == 41.
constexpr uint32_t one_over_n_quarter = one_over_n >> 2;
static_assert(one_over_n == one_over_n_quarter << 2, "");
// |ma| is in range [0, 255].
const __m256i m =
_mm256_maddubs_epi16(ma, _mm256_set1_epi16(one_over_n_quarter));
const __m256i m0 = VmullLo16(m, sum);
const __m256i m1 = VmullHi16(m, sum);
b[0] = VrshrU32(m0, kSgrProjReciprocalBits - 2);
b[1] = VrshrU32(m1, kSgrProjReciprocalBits - 2);
}
inline void CalculateB3(const __m128i sum, const __m128i ma, __m128i b[2]) {
// one_over_n == 455.
constexpr uint32_t one_over_n =
((1 << kSgrProjReciprocalBits) + (9 >> 1)) / 9;
const __m128i m0 = VmullLo16(ma, sum);
const __m128i m1 = VmullHi16(ma, sum);
const __m128i m2 = _mm_mullo_epi32(m0, _mm_set1_epi32(one_over_n));
const __m128i m3 = _mm_mullo_epi32(m1, _mm_set1_epi32(one_over_n));
b[0] = VrshrU32(m2, kSgrProjReciprocalBits);
b[1] = VrshrU32(m3, kSgrProjReciprocalBits);
}
inline void CalculateB3(const __m256i sum, const __m256i ma, __m256i b[2]) {
// one_over_n == 455.
constexpr uint32_t one_over_n =
((1 << kSgrProjReciprocalBits) + (9 >> 1)) / 9;
const __m256i m0 = VmullLo16(ma, sum);
const __m256i m1 = VmullHi16(ma, sum);
const __m256i m2 = _mm256_mullo_epi32(m0, _mm256_set1_epi32(one_over_n));
const __m256i m3 = _mm256_mullo_epi32(m1, _mm256_set1_epi32(one_over_n));
b[0] = VrshrU32(m2, kSgrProjReciprocalBits);
b[1] = VrshrU32(m3, kSgrProjReciprocalBits);
}
inline void CalculateSumAndIndex5(const __m128i s5[5], const __m128i sq5[5][2],
const uint32_t scale, __m128i* const sum,
__m128i* const index) {
__m128i sum_sq[2];
*sum = Sum5_16(s5);
Sum5_32(sq5, sum_sq);
*index = CalculateMa<25>(*sum, sum_sq, scale);
}
inline void CalculateSumAndIndex5(const __m256i s5[5], const __m256i sq5[5][2],
const uint32_t scale, __m256i* const sum,
__m256i* const index) {
__m256i sum_sq[2];
*sum = Sum5_16(s5);
Sum5_32(sq5, sum_sq);
*index = CalculateMa<25>(*sum, sum_sq, scale);
}
inline void CalculateSumAndIndex3(const __m128i s3[3], const __m128i sq3[3][2],
const uint32_t scale, __m128i* const sum,
__m128i* const index) {
__m128i sum_sq[2];
*sum = Sum3_16(s3);
Sum3_32(sq3, sum_sq);
*index = CalculateMa<9>(*sum, sum_sq, scale);
}
inline void CalculateSumAndIndex3(const __m256i s3[3], const __m256i sq3[3][2],
const uint32_t scale, __m256i* const sum,
__m256i* const index) {
__m256i sum_sq[2];
*sum = Sum3_16(s3);
Sum3_32(sq3, sum_sq);
*index = CalculateMa<9>(*sum, sum_sq, scale);
}
template <int n>
inline void LookupIntermediate(const __m128i sum, const __m128i index,
__m128i* const ma, __m128i b[2]) {
static_assert(n == 9 || n == 25, "");
const __m128i idx = _mm_packus_epi16(index, index);
// Actually it's not stored and loaded. The compiler will use a 64-bit
// general-purpose register to process. Faster than using _mm_extract_epi8().
uint8_t temp[8];
StoreLo8(temp, idx);
*ma = _mm_cvtsi32_si128(kSgrMaLookup[temp[0]]);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[1]], 1);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[2]], 2);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[3]], 3);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[4]], 4);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[5]], 5);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[6]], 6);
*ma = _mm_insert_epi8(*ma, kSgrMaLookup[temp[7]], 7);
// b = ma * b * one_over_n
// |ma| = [0, 255]
// |sum| is a box sum with radius 1 or 2.
// For the first pass radius is 2. Maximum value is 5x5x255 = 6375.
// For the second pass radius is 1. Maximum value is 3x3x255 = 2295.
// |one_over_n| = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n
// When radius is 2 |n| is 25. |one_over_n| is 164.
// When radius is 1 |n| is 9. |one_over_n| is 455.
// |kSgrProjReciprocalBits| is 12.
// Radius 2: 255 * 6375 * 164 >> 12 = 65088 (16 bits).
// Radius 1: 255 * 2295 * 455 >> 12 = 65009 (16 bits).
const __m128i maq = _mm_unpacklo_epi8(*ma, _mm_setzero_si128());
if (n == 9) {
CalculateB3(sum, maq, b);
} else {
CalculateB5(sum, maq, b);
}
}
// Repeat the first 48 elements in kSgrMaLookup with a period of 16.
alignas(32) constexpr uint8_t kSgrMaLookupAvx2[96] = {
255, 128, 85, 64, 51, 43, 37, 32, 28, 26, 23, 21, 20, 18, 17, 16,
255, 128, 85, 64, 51, 43, 37, 32, 28, 26, 23, 21, 20, 18, 17, 16,
15, 14, 13, 13, 12, 12, 11, 11, 10, 10, 9, 9, 9, 9, 8, 8,
15, 14, 13, 13, 12, 12, 11, 11, 10, 10, 9, 9, 9, 9, 8, 8,
8, 8, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5,
8, 8, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5};
// Set the shuffle control mask of indices out of range [0, 15] to (1xxxxxxx)b
// to get value 0 as the shuffle result. The most significiant bit 1 comes
// either from the comparison instruction, or from the sign bit of the index.
inline __m128i ShuffleIndex(const __m128i table, const __m128i index) {
__m128i mask;
mask = _mm_cmpgt_epi8(index, _mm_set1_epi8(15));
mask = _mm_or_si128(mask, index);
return _mm_shuffle_epi8(table, mask);
}
inline __m256i ShuffleIndex(const __m256i table, const __m256i index) {
__m256i mask;
mask = _mm256_cmpgt_epi8(index, _mm256_set1_epi8(15));
mask = _mm256_or_si256(mask, index);
return _mm256_shuffle_epi8(table, mask);
}
inline __m128i AdjustValue(const __m128i value, const __m128i index,
const int threshold) {
const __m128i thresholds = _mm_set1_epi8(threshold - 128);
const __m128i offset = _mm_cmpgt_epi8(index, thresholds);
return _mm_add_epi8(value, offset);
}
inline __m256i AdjustValue(const __m256i value, const __m256i index,
const int threshold) {
const __m256i thresholds = _mm256_set1_epi8(threshold - 128);
const __m256i offset = _mm256_cmpgt_epi8(index, thresholds);
return _mm256_add_epi8(value, offset);
}
inline void CalculateIntermediate(const __m128i sum[2], const __m128i index[2],
__m128i* const ma, __m128i b0[2],
__m128i b1[2]) {
// Use table lookup to read elements whose indices are less than 48.
const __m128i c0 = LoadAligned16(kSgrMaLookup + 0 * 16);
const __m128i c1 = LoadAligned16(kSgrMaLookup + 1 * 16);
const __m128i c2 = LoadAligned16(kSgrMaLookup + 2 * 16);
const __m128i indices = _mm_packus_epi16(index[0], index[1]);
__m128i idx;
// Clip idx to 127 to apply signed comparison instructions.
idx = _mm_min_epu8(indices, _mm_set1_epi8(127));
// All elements whose indices are less than 48 are set to 0.
// Get shuffle results for indices in range [0, 15].
*ma = ShuffleIndex(c0, idx);
// Get shuffle results for indices in range [16, 31].
// Subtract 16 to utilize the sign bit of the index.
idx = _mm_sub_epi8(idx, _mm_set1_epi8(16));
const __m128i res1 = ShuffleIndex(c1, idx);
// Use OR instruction to combine shuffle results together.
*ma = _mm_or_si128(*ma, res1);
// Get shuffle results for indices in range [32, 47].
// Subtract 16 to utilize the sign bit of the index.
idx = _mm_sub_epi8(idx, _mm_set1_epi8(16));
const __m128i res2 = ShuffleIndex(c2, idx);
*ma = _mm_or_si128(*ma, res2);
// For elements whose indices are larger than 47, since they seldom change
// values with the increase of the index, we use comparison and arithmetic
// operations to calculate their values.
// Add -128 to apply signed comparison instructions.
idx = _mm_add_epi8(indices, _mm_set1_epi8(-128));
// Elements whose indices are larger than 47 (with value 0) are set to 5.
*ma = _mm_max_epu8(*ma, _mm_set1_epi8(5));
*ma = AdjustValue(*ma, idx, 55); // 55 is the last index which value is 5.
*ma = AdjustValue(*ma, idx, 72); // 72 is the last index which value is 4.
*ma = AdjustValue(*ma, idx, 101); // 101 is the last index which value is 3.
*ma = AdjustValue(*ma, idx, 169); // 169 is the last index which value is 2.
*ma = AdjustValue(*ma, idx, 254); // 254 is the last index which value is 1.
// b = ma * b * one_over_n
// |ma| = [0, 255]
// |sum| is a box sum with radius 1 or 2.
// For the first pass radius is 2. Maximum value is 5x5x255 = 6375.
// For the second pass radius is 1. Maximum value is 3x3x255 = 2295.
// |one_over_n| = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n
// When radius is 2 |n| is 25. |one_over_n| is 164.
// When radius is 1 |n| is 9. |one_over_n| is 455.
// |kSgrProjReciprocalBits| is 12.
// Radius 2: 255 * 6375 * 164 >> 12 = 65088 (16 bits).
// Radius 1: 255 * 2295 * 455 >> 12 = 65009 (16 bits).
const __m128i maq0 = _mm_unpacklo_epi8(*ma, _mm_setzero_si128());
CalculateB3(sum[0], maq0, b0);
const __m128i maq1 = _mm_unpackhi_epi8(*ma, _mm_setzero_si128());
CalculateB3(sum[1], maq1, b1);
}
template <int n>
inline void CalculateIntermediate(const __m256i sum[2], const __m256i index[2],
__m256i ma[3], __m256i b0[2], __m256i b1[2]) {
static_assert(n == 9 || n == 25, "");
// Use table lookup to read elements whose indices are less than 48.
const __m256i c0 = LoadAligned32(kSgrMaLookupAvx2 + 0 * 32);
const __m256i c1 = LoadAligned32(kSgrMaLookupAvx2 + 1 * 32);
const __m256i c2 = LoadAligned32(kSgrMaLookupAvx2 + 2 * 32);
const __m256i indices = _mm256_packus_epi16(index[0], index[1]); // 0 2 1 3
__m256i idx, mas;
// Clip idx to 127 to apply signed comparison instructions.
idx = _mm256_min_epu8(indices, _mm256_set1_epi8(127));
// All elements whose indices are less than 48 are set to 0.
// Get shuffle results for indices in range [0, 15].
mas = ShuffleIndex(c0, idx);
// Get shuffle results for indices in range [16, 31].
// Subtract 16 to utilize the sign bit of the index.
idx = _mm256_sub_epi8(idx, _mm256_set1_epi8(16));
const __m256i res1 = ShuffleIndex(c1, idx);
// Use OR instruction to combine shuffle results together.
mas = _mm256_or_si256(mas, res1);
// Get shuffle results for indices in range [32, 47].
// Subtract 16 to utilize the sign bit of the index.
idx = _mm256_sub_epi8(idx, _mm256_set1_epi8(16));
const __m256i res2 = ShuffleIndex(c2, idx);
mas = _mm256_or_si256(mas, res2);
// For elements whose indices are larger than 47, since they seldom change
// values with the increase of the index, we use comparison and arithmetic
// operations to calculate their values.
// Add -128 to apply signed comparison instructions.
idx = _mm256_add_epi8(indices, _mm256_set1_epi8(-128));
// Elements whose indices are larger than 47 (with value 0) are set to 5.
mas = _mm256_max_epu8(mas, _mm256_set1_epi8(5));
mas = AdjustValue(mas, idx, 55); // 55 is the last index which value is 5.
mas = AdjustValue(mas, idx, 72); // 72 is the last index which value is 4.
mas = AdjustValue(mas, idx, 101); // 101 is the last index which value is 3.
mas = AdjustValue(mas, idx, 169); // 169 is the last index which value is 2.
mas = AdjustValue(mas, idx, 254); // 254 is the last index which value is 1.
ma[2] = _mm256_permute4x64_epi64(mas, 0x63); // 32-39 8-15 16-23 24-31
ma[0] = _mm256_blend_epi32(ma[0], ma[2], 0xfc); // 0-7 8-15 16-23 24-31
ma[1] = _mm256_permute2x128_si256(ma[0], ma[2], 0x21);
// b = ma * b * one_over_n
// |ma| = [0, 255]
// |sum| is a box sum with radius 1 or 2.
// For the first pass radius is 2. Maximum value is 5x5x255 = 6375.
// For the second pass radius is 1. Maximum value is 3x3x255 = 2295.
// |one_over_n| = ((1 << kSgrProjReciprocalBits) + (n >> 1)) / n
// When radius is 2 |n| is 25. |one_over_n| is 164.
// When radius is 1 |n| is 9. |one_over_n| is 455.
// |kSgrProjReciprocalBits| is 12.
// Radius 2: 255 * 6375 * 164 >> 12 = 65088 (16 bits).
// Radius 1: 255 * 2295 * 455 >> 12 = 65009 (16 bits).
const __m256i maq0 = _mm256_unpackhi_epi8(ma[0], _mm256_setzero_si256());
const __m256i maq1 = _mm256_unpacklo_epi8(ma[1], _mm256_setzero_si256());
__m256i sums[2];
sums[0] = _mm256_permute2x128_si256(sum[0], sum[1], 0x20);
sums[1] = _mm256_permute2x128_si256(sum[0], sum[1], 0x31);
if (n == 9) {
CalculateB3(sums[0], maq0, b0);
CalculateB3(sums[1], maq1, b1);
} else {
CalculateB5(sums[0], maq0, b0);
CalculateB5(sums[1], maq1, b1);
}
}
inline void CalculateIntermediate5(const __m128i s5[5], const __m128i sq5[5][2],
const uint32_t scale, __m128i* const ma,
__m128i b[2]) {
__m128i sum, index;
CalculateSumAndIndex5(s5, sq5, scale, &sum, &index);
LookupIntermediate<25>(sum, index, ma, b);
}
inline void CalculateIntermediate3(const __m128i s3[3], const __m128i sq3[3][2],
const uint32_t scale, __m128i* const ma,
__m128i b[2]) {
__m128i sum, index;
CalculateSumAndIndex3(s3, sq3, scale, &sum, &index);
LookupIntermediate<9>(sum, index, ma, b);
}
inline void Store343_444(const __m256i b3[3], const ptrdiff_t x,
__m256i sum_b343[2], __m256i sum_b444[2],
uint32_t* const b343, uint32_t* const b444) {
__m256i b[3], sum_b111[2];
Prepare3_32(b3 + 0, b);
sum_b111[0] = Sum3_32(b);
sum_b444[0] = _mm256_slli_epi32(sum_b111[0], 2);
sum_b343[0] = _mm256_sub_epi32(sum_b444[0], sum_b111[0]);
sum_b343[0] = _mm256_add_epi32(sum_b343[0], b[1]);
Prepare3_32(b3 + 1, b);
sum_b111[1] = Sum3_32(b);
sum_b444[1] = _mm256_slli_epi32(sum_b111[1], 2);
sum_b343[1] = _mm256_sub_epi32(sum_b444[1], sum_b111[1]);
sum_b343[1] = _mm256_add_epi32(sum_b343[1], b[1]);
StoreAligned64(b444 + x, sum_b444);
StoreAligned64(b343 + x, sum_b343);
}
inline void Store343_444Lo(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, __m256i* const sum_ma343,
__m256i* const sum_ma444, __m256i sum_b343[2],
__m256i sum_b444[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
const __m256i sum_ma111 = Sum3WLo16(ma3);
*sum_ma444 = _mm256_slli_epi16(sum_ma111, 2);
StoreAligned32_ma(ma444 + x, *sum_ma444);
const __m256i sum333 = _mm256_sub_epi16(*sum_ma444, sum_ma111);
*sum_ma343 = VaddwLo8(sum333, ma3[1]);
StoreAligned32_ma(ma343 + x, *sum_ma343);
Store343_444(b3, x, sum_b343, sum_b444, b343, b444);
}
inline void Store343_444Hi(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, __m256i* const sum_ma343,
__m256i* const sum_ma444, __m256i sum_b343[2],
__m256i sum_b444[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
const __m256i sum_ma111 = Sum3WHi16(ma3);
*sum_ma444 = _mm256_slli_epi16(sum_ma111, 2);
StoreAligned32_ma(ma444 + x, *sum_ma444);
const __m256i sum333 = _mm256_sub_epi16(*sum_ma444, sum_ma111);
*sum_ma343 = VaddwHi8(sum333, ma3[1]);
StoreAligned32_ma(ma343 + x, *sum_ma343);
Store343_444(b3, x + kMaStoreOffset, sum_b343, sum_b444, b343, b444);
}
inline void Store343_444Lo(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, __m256i* const sum_ma343,
__m256i sum_b343[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_ma444, sum_b444[2];
Store343_444Lo(ma3, b3, x, sum_ma343, &sum_ma444, sum_b343, sum_b444, ma343,
ma444, b343, b444);
}
inline void Store343_444Hi(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, __m256i* const sum_ma343,
__m256i sum_b343[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_ma444, sum_b444[2];
Store343_444Hi(ma3, b3, x, sum_ma343, &sum_ma444, sum_b343, sum_b444, ma343,
ma444, b343, b444);
}
inline void Store343_444Lo(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_ma343, sum_b343[2];
Store343_444Lo(ma3, b3, x, &sum_ma343, sum_b343, ma343, ma444, b343, b444);
}
inline void Store343_444Hi(const __m256i ma3[3], const __m256i b3[2],
const ptrdiff_t x, uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_ma343, sum_b343[2];
Store343_444Hi(ma3, b3, x, &sum_ma343, sum_b343, ma343, ma444, b343, b444);
}
// Don't combine the following 2 functions, which would be slower.
inline void Store343_444(const __m256i ma3[3], const __m256i b3[6],
const ptrdiff_t x, __m256i* const sum_ma343_lo,
__m256i* const sum_ma343_hi,
__m256i* const sum_ma444_lo,
__m256i* const sum_ma444_hi, __m256i sum_b343_lo[2],
__m256i sum_b343_hi[2], __m256i sum_b444_lo[2],
__m256i sum_b444_hi[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_mat343[2], sum_mat444[2];
const __m256i sum_ma111_lo = Sum3WLo16(ma3);
sum_mat444[0] = _mm256_slli_epi16(sum_ma111_lo, 2);
const __m256i sum333_lo = _mm256_sub_epi16(sum_mat444[0], sum_ma111_lo);
sum_mat343[0] = VaddwLo8(sum333_lo, ma3[1]);
Store343_444(b3, x, sum_b343_lo, sum_b444_lo, b343, b444);
const __m256i sum_ma111_hi = Sum3WHi16(ma3);
sum_mat444[1] = _mm256_slli_epi16(sum_ma111_hi, 2);
*sum_ma444_lo = _mm256_permute2x128_si256(sum_mat444[0], sum_mat444[1], 0x20);
*sum_ma444_hi = _mm256_permute2x128_si256(sum_mat444[0], sum_mat444[1], 0x31);
StoreAligned32(ma444 + x + 0, *sum_ma444_lo);
StoreAligned32(ma444 + x + 16, *sum_ma444_hi);
const __m256i sum333_hi = _mm256_sub_epi16(sum_mat444[1], sum_ma111_hi);
sum_mat343[1] = VaddwHi8(sum333_hi, ma3[1]);
*sum_ma343_lo = _mm256_permute2x128_si256(sum_mat343[0], sum_mat343[1], 0x20);
*sum_ma343_hi = _mm256_permute2x128_si256(sum_mat343[0], sum_mat343[1], 0x31);
StoreAligned32(ma343 + x + 0, *sum_ma343_lo);
StoreAligned32(ma343 + x + 16, *sum_ma343_hi);
Store343_444(b3 + 3, x + 16, sum_b343_hi, sum_b444_hi, b343, b444);
}
inline void Store343_444(const __m256i ma3[3], const __m256i b3[6],
const ptrdiff_t x, __m256i* const sum_ma343_lo,
__m256i* const sum_ma343_hi, __m256i sum_b343_lo[2],
__m256i sum_b343_hi[2], uint16_t* const ma343,
uint16_t* const ma444, uint32_t* const b343,
uint32_t* const b444) {
__m256i sum_ma444[2], sum_b444[2], sum_mat343[2];
const __m256i sum_ma111_lo = Sum3WLo16(ma3);
sum_ma444[0] = _mm256_slli_epi16(sum_ma111_lo, 2);
const __m256i sum333_lo = _mm256_sub_epi16(sum_ma444[0], sum_ma111_lo);
sum_mat343[0] = VaddwLo8(sum333_lo, ma3[1]);
Store343_444(b3, x, sum_b343_lo, sum_b444, b343, b444);
const __m256i sum_ma111_hi = Sum3WHi16(ma3);
sum_ma444[1] = _mm256_slli_epi16(sum_ma111_hi, 2);
StoreAligned64_ma(ma444 + x, sum_ma444);
const __m256i sum333_hi = _mm256_sub_epi16(sum_ma444[1], sum_ma111_hi);
sum_mat343[1] = VaddwHi8(sum333_hi, ma3[1]);
*sum_ma343_lo = _mm256_permute2x128_si256(sum_mat343[0], sum_mat343[1], 0x20);
*sum_ma343_hi = _mm256_permute2x128_si256(sum_mat343[0], sum_mat343[1], 0x31);
StoreAligned32(ma343 + x + 0, *sum_ma343_lo);
StoreAligned32(ma343 + x + 16, *sum_ma343_hi);
Store343_444(b3 + 3, x + 16, sum_b343_hi, sum_b444, b343, b444);
}
inline void PermuteB(const __m256i t[4], __m256i b[7]) {
// Input:
// 0 1 2 3 // b[0]
// 4 5 6 7 // b[1]
// 8 9 10 11 24 25 26 27 // t[0]
// 12 13 14 15 28 29 30 31 // t[1]
// 16 17 18 19 32 33 34 35 // t[2]
// 20 21 22 23 36 37 38 39 // t[3]
// Output:
// 0 1 2 3 8 9 10 11 // b[0]
// 4 5 6 7 12 13 14 15 // b[1]
// 8 9 10 11 16 17 18 19 // b[2]
// 16 17 18 19 24 25 26 27 // b[3]
// 20 21 22 23 28 29 30 31 // b[4]
// 24 25 26 27 32 33 34 35 // b[5]
// 20 21 22 23 36 37 38 39 // b[6]
b[0] = _mm256_permute2x128_si256(b[0], t[0], 0x21);
b[1] = _mm256_permute2x128_si256(b[1], t[1], 0x21);
b[2] = _mm256_permute2x128_si256(t[0], t[2], 0x20);
b[3] = _mm256_permute2x128_si256(t[2], t[0], 0x30);
b[4] = _mm256_permute2x128_si256(t[3], t[1], 0x30);
b[5] = _mm256_permute2x128_si256(t[0], t[2], 0x31);
b[6] = t[3];
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess5Lo(
const __m128i s[2][2], const uint32_t scale, uint16_t* const sum5[5],
uint32_t* const square_sum5[5], __m128i sq[2][4], __m128i* const ma,
__m128i b[2]) {
__m128i s5[2][5], sq5[5][2];
Square(s[0][1], sq[0] + 2);
Square(s[1][1], sq[1] + 2);
s5[0][3] = Sum5Horizontal16(s[0]);
StoreAligned16(sum5[3], s5[0][3]);
s5[0][4] = Sum5Horizontal16(s[1]);
StoreAligned16(sum5[4], s5[0][4]);
Sum5Horizontal32(sq[0], sq5[3]);
StoreAligned32U32(square_sum5[3], sq5[3]);
Sum5Horizontal32(sq[1], sq5[4]);
StoreAligned32U32(square_sum5[4], sq5[4]);
LoadAligned16x3U16(sum5, 0, s5[0]);
LoadAligned32x3U32(square_sum5, 0, sq5);
CalculateIntermediate5(s5[0], sq5, scale, ma, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess5(
const uint16_t* const src0, const uint16_t* const src1,
const ptrdiff_t over_read_in_bytes, const ptrdiff_t sum_width,
const ptrdiff_t x, const uint32_t scale, uint16_t* const sum5[5],
uint32_t* const square_sum5[5], __m256i sq[2][8], __m256i ma[3],
__m256i b[3]) {
__m256i s[2], s5[2][5], sq5[5][2], sum[2], index[2], t[4];
s[0] = LoadUnaligned32Msan(src0 + 8, over_read_in_bytes + 16);
s[1] = LoadUnaligned32Msan(src1 + 8, over_read_in_bytes + 16);
Square(s[0], sq[0] + 2);
Square(s[1], sq[1] + 2);
sq[0][0] = _mm256_permute2x128_si256(sq[0][0], sq[0][2], 0x21);
sq[0][1] = _mm256_permute2x128_si256(sq[0][1], sq[0][3], 0x21);
sq[1][0] = _mm256_permute2x128_si256(sq[1][0], sq[1][2], 0x21);
sq[1][1] = _mm256_permute2x128_si256(sq[1][1], sq[1][3], 0x21);
s5[0][3] = Sum5Horizontal16(src0 + 0, over_read_in_bytes + 0);
s5[1][3] = Sum5Horizontal16(src0 + 16, over_read_in_bytes + 32);
s5[0][4] = Sum5Horizontal16(src1 + 0, over_read_in_bytes + 0);
s5[1][4] = Sum5Horizontal16(src1 + 16, over_read_in_bytes + 32);
StoreAligned32(sum5[3] + x + 0, s5[0][3]);
StoreAligned32(sum5[3] + x + 16, s5[1][3]);
StoreAligned32(sum5[4] + x + 0, s5[0][4]);
StoreAligned32(sum5[4] + x + 16, s5[1][4]);
Sum5Horizontal32(sq[0], sq5[3]);
StoreAligned64(square_sum5[3] + x, sq5[3]);
Sum5Horizontal32(sq[1], sq5[4]);
StoreAligned64(square_sum5[4] + x, sq5[4]);
LoadAligned32x3U16(sum5, x, s5[0]);
LoadAligned64x3U32(square_sum5, x, sq5);
CalculateSumAndIndex5(s5[0], sq5, scale, &sum[0], &index[0]);
s[0] = LoadUnaligned32Msan(src0 + 24, over_read_in_bytes + 48);
s[1] = LoadUnaligned32Msan(src1 + 24, over_read_in_bytes + 48);
Square(s[0], sq[0] + 6);
Square(s[1], sq[1] + 6);
sq[0][4] = _mm256_permute2x128_si256(sq[0][2], sq[0][6], 0x21);
sq[0][5] = _mm256_permute2x128_si256(sq[0][3], sq[0][7], 0x21);
sq[1][4] = _mm256_permute2x128_si256(sq[1][2], sq[1][6], 0x21);
sq[1][5] = _mm256_permute2x128_si256(sq[1][3], sq[1][7], 0x21);
Sum5Horizontal32(sq[0] + 4, sq5[3]);
StoreAligned64(square_sum5[3] + x + 16, sq5[3]);
Sum5Horizontal32(sq[1] + 4, sq5[4]);
StoreAligned64(square_sum5[4] + x + 16, sq5[4]);
LoadAligned32x3U16Msan(sum5, x + 16, sum_width, s5[1]);
LoadAligned64x3U32Msan(square_sum5, x + 16, sum_width, sq5);
CalculateSumAndIndex5(s5[1], sq5, scale, &sum[1], &index[1]);
CalculateIntermediate<25>(sum, index, ma, t, t + 2);
PermuteB(t, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess5LastRowLo(
const __m128i s[2], const uint32_t scale, const uint16_t* const sum5[5],
const uint32_t* const square_sum5[5], __m128i sq[4], __m128i* const ma,
__m128i b[2]) {
__m128i s5[5], sq5[5][2];
Square(s[1], sq + 2);
s5[3] = s5[4] = Sum5Horizontal16(s);
Sum5Horizontal32(sq, sq5[3]);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
LoadAligned16x3U16(sum5, 0, s5);
LoadAligned32x3U32(square_sum5, 0, sq5);
CalculateIntermediate5(s5, sq5, scale, ma, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess5LastRow(
const uint16_t* const src, const ptrdiff_t over_read_in_bytes,
const ptrdiff_t sum_width, const ptrdiff_t x, const uint32_t scale,
const uint16_t* const sum5[5], const uint32_t* const square_sum5[5],
__m256i sq[3], __m256i ma[3], __m256i b[3]) {
const __m256i s0 = LoadUnaligned32Msan(src + 8, over_read_in_bytes + 16);
__m256i s5[2][5], sq5[5][2], sum[2], index[2], t[4];
Square(s0, sq + 2);
sq[0] = _mm256_permute2x128_si256(sq[0], sq[2], 0x21);
sq[1] = _mm256_permute2x128_si256(sq[1], sq[3], 0x21);
s5[0][3] = Sum5Horizontal16(src + 0, over_read_in_bytes + 0);
s5[1][3] = Sum5Horizontal16(src + 16, over_read_in_bytes + 32);
s5[0][4] = s5[0][3];
s5[1][4] = s5[1][3];
Sum5Horizontal32(sq, sq5[3]);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
LoadAligned32x3U16(sum5, x, s5[0]);
LoadAligned64x3U32(square_sum5, x, sq5);
CalculateSumAndIndex5(s5[0], sq5, scale, &sum[0], &index[0]);
const __m256i s1 = LoadUnaligned32Msan(src + 24, over_read_in_bytes + 48);
Square(s1, sq + 6);
sq[4] = _mm256_permute2x128_si256(sq[2], sq[6], 0x21);
sq[5] = _mm256_permute2x128_si256(sq[3], sq[7], 0x21);
Sum5Horizontal32(sq + 4, sq5[3]);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
LoadAligned32x3U16Msan(sum5, x + 16, sum_width, s5[1]);
LoadAligned64x3U32Msan(square_sum5, x + 16, sum_width, sq5);
CalculateSumAndIndex5(s5[1], sq5, scale, &sum[1], &index[1]);
CalculateIntermediate<25>(sum, index, ma, t, t + 2);
PermuteB(t, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess3Lo(
const __m128i s[2], const uint32_t scale, uint16_t* const sum3[3],
uint32_t* const square_sum3[3], __m128i sq[4], __m128i* const ma,
__m128i b[2]) {
__m128i s3[3], sq3[3][2];
Square(s[1], sq + 2);
s3[2] = Sum3Horizontal16(s);
StoreAligned16(sum3[2], s3[2]);
Sum3Horizontal32(sq, sq3[2]);
StoreAligned32U32(square_sum3[2], sq3[2]);
LoadAligned16x2U16(sum3, 0, s3);
LoadAligned32x2U32(square_sum3, 0, sq3);
CalculateIntermediate3(s3, sq3, scale, ma, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess3(
const uint16_t* const src, const ptrdiff_t over_read_in_bytes,
const ptrdiff_t x, const ptrdiff_t sum_width, const uint32_t scale,
uint16_t* const sum3[3], uint32_t* const square_sum3[3], __m256i sq[8],
__m256i ma[3], __m256i b[7]) {
__m256i s[2], s3[4], sq3[3][2], sum[2], index[2], t[4];
s[0] = LoadUnaligned32Msan(src + 8, over_read_in_bytes + 16);
s[1] = LoadUnaligned32Msan(src + 24, over_read_in_bytes + 48);
Square(s[0], sq + 2);
sq[0] = _mm256_permute2x128_si256(sq[0], sq[2], 0x21);
sq[1] = _mm256_permute2x128_si256(sq[1], sq[3], 0x21);
s3[2] = Sum3Horizontal16(src, over_read_in_bytes);
s3[3] = Sum3Horizontal16(src + 16, over_read_in_bytes + 32);
StoreAligned64(sum3[2] + x, s3 + 2);
Sum3Horizontal32(sq + 0, sq3[2]);
StoreAligned64(square_sum3[2] + x, sq3[2]);
LoadAligned32x2U16(sum3, x, s3);
LoadAligned64x2U32(square_sum3, x, sq3);
CalculateSumAndIndex3(s3, sq3, scale, &sum[0], &index[0]);
Square(s[1], sq + 6);
sq[4] = _mm256_permute2x128_si256(sq[2], sq[6], 0x21);
sq[5] = _mm256_permute2x128_si256(sq[3], sq[7], 0x21);
Sum3Horizontal32(sq + 4, sq3[2]);
StoreAligned64(square_sum3[2] + x + 16, sq3[2]);
LoadAligned32x2U16Msan(sum3, x + 16, sum_width, s3 + 1);
LoadAligned64x2U32Msan(square_sum3, x + 16, sum_width, sq3);
CalculateSumAndIndex3(s3 + 1, sq3, scale, &sum[1], &index[1]);
CalculateIntermediate<9>(sum, index, ma, t, t + 2);
PermuteB(t, b);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcessLo(
const __m128i s[2][4], const uint16_t scales[2], uint16_t* const sum3[4],
uint16_t* const sum5[5], uint32_t* const square_sum3[4],
uint32_t* const square_sum5[5], __m128i sq[2][8], __m128i ma3[2][3],
__m128i b3[2][10], __m128i* const ma5, __m128i b5[2]) {
__m128i s3[4], s5[5], sq3[4][2], sq5[5][2], sum[2], index[2];
Square(s[0][1], sq[0] + 2);
Square(s[1][1], sq[1] + 2);
SumHorizontal16(s[0], &s3[2], &s5[3]);
SumHorizontal16(s[1], &s3[3], &s5[4]);
StoreAligned16(sum3[2], s3[2]);
StoreAligned16(sum3[3], s3[3]);
StoreAligned16(sum5[3], s5[3]);
StoreAligned16(sum5[4], s5[4]);
SumHorizontal32(sq[0], &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
StoreAligned32U32(square_sum3[2], sq3[2]);
StoreAligned32U32(square_sum5[3], sq5[3]);
SumHorizontal32(sq[1], &sq3[3][0], &sq3[3][1], &sq5[4][0], &sq5[4][1]);
StoreAligned32U32(square_sum3[3], sq3[3]);
StoreAligned32U32(square_sum5[4], sq5[4]);
LoadAligned16x2U16(sum3, 0, s3);
LoadAligned32x2U32(square_sum3, 0, sq3);
LoadAligned16x3U16(sum5, 0, s5);
LoadAligned32x3U32(square_sum5, 0, sq5);
CalculateSumAndIndex3(s3 + 0, sq3 + 0, scales[1], &sum[0], &index[0]);
CalculateSumAndIndex3(s3 + 1, sq3 + 1, scales[1], &sum[1], &index[1]);
CalculateIntermediate(sum, index, &ma3[0][0], b3[0], b3[1]);
ma3[1][0] = _mm_srli_si128(ma3[0][0], 8);
CalculateIntermediate5(s5, sq5, scales[0], ma5, b5);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcess(
const uint16_t* const src0, const uint16_t* const src1,
const ptrdiff_t over_read_in_bytes, const ptrdiff_t x,
const uint16_t scales[2], uint16_t* const sum3[4], uint16_t* const sum5[5],
uint32_t* const square_sum3[4], uint32_t* const square_sum5[5],
const ptrdiff_t sum_width, __m256i sq[2][8], __m256i ma3[2][3],
__m256i b3[2][7], __m256i ma5[3], __m256i b5[5]) {
__m256i s[2], s3[2][4], s5[2][5], sq3[4][2], sq5[5][2], sum_3[2][2],
index_3[2][2], sum_5[2], index_5[2], t[4];
s[0] = LoadUnaligned32Msan(src0 + 8, over_read_in_bytes + 16);
s[1] = LoadUnaligned32Msan(src1 + 8, over_read_in_bytes + 16);
Square(s[0], sq[0] + 2);
Square(s[1], sq[1] + 2);
sq[0][0] = _mm256_permute2x128_si256(sq[0][0], sq[0][2], 0x21);
sq[0][1] = _mm256_permute2x128_si256(sq[0][1], sq[0][3], 0x21);
sq[1][0] = _mm256_permute2x128_si256(sq[1][0], sq[1][2], 0x21);
sq[1][1] = _mm256_permute2x128_si256(sq[1][1], sq[1][3], 0x21);
SumHorizontal16(src0, over_read_in_bytes, &s3[0][2], &s3[1][2], &s5[0][3],
&s5[1][3]);
SumHorizontal16(src1, over_read_in_bytes, &s3[0][3], &s3[1][3], &s5[0][4],
&s5[1][4]);
StoreAligned32(sum3[2] + x + 0, s3[0][2]);
StoreAligned32(sum3[2] + x + 16, s3[1][2]);
StoreAligned32(sum3[3] + x + 0, s3[0][3]);
StoreAligned32(sum3[3] + x + 16, s3[1][3]);
StoreAligned32(sum5[3] + x + 0, s5[0][3]);
StoreAligned32(sum5[3] + x + 16, s5[1][3]);
StoreAligned32(sum5[4] + x + 0, s5[0][4]);
StoreAligned32(sum5[4] + x + 16, s5[1][4]);
SumHorizontal32(sq[0], &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
SumHorizontal32(sq[1], &sq3[3][0], &sq3[3][1], &sq5[4][0], &sq5[4][1]);
StoreAligned64(square_sum3[2] + x, sq3[2]);
StoreAligned64(square_sum5[3] + x, sq5[3]);
StoreAligned64(square_sum3[3] + x, sq3[3]);
StoreAligned64(square_sum5[4] + x, sq5[4]);
LoadAligned32x2U16(sum3, x, s3[0]);
LoadAligned64x2U32(square_sum3, x, sq3);
CalculateSumAndIndex3(s3[0], sq3, scales[1], &sum_3[0][0], &index_3[0][0]);
CalculateSumAndIndex3(s3[0] + 1, sq3 + 1, scales[1], &sum_3[1][0],
&index_3[1][0]);
LoadAligned32x3U16(sum5, x, s5[0]);
LoadAligned64x3U32(square_sum5, x, sq5);
CalculateSumAndIndex5(s5[0], sq5, scales[0], &sum_5[0], &index_5[0]);
s[0] = LoadUnaligned32Msan(src0 + 24, over_read_in_bytes + 48);
s[1] = LoadUnaligned32Msan(src1 + 24, over_read_in_bytes + 48);
Square(s[0], sq[0] + 6);
Square(s[1], sq[1] + 6);
sq[0][4] = _mm256_permute2x128_si256(sq[0][2], sq[0][6], 0x21);
sq[0][5] = _mm256_permute2x128_si256(sq[0][3], sq[0][7], 0x21);
sq[1][4] = _mm256_permute2x128_si256(sq[1][2], sq[1][6], 0x21);
sq[1][5] = _mm256_permute2x128_si256(sq[1][3], sq[1][7], 0x21);
SumHorizontal32(sq[0] + 4, &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
SumHorizontal32(sq[1] + 4, &sq3[3][0], &sq3[3][1], &sq5[4][0], &sq5[4][1]);
StoreAligned64(square_sum3[2] + x + 16, sq3[2]);
StoreAligned64(square_sum5[3] + x + 16, sq5[3]);
StoreAligned64(square_sum3[3] + x + 16, sq3[3]);
StoreAligned64(square_sum5[4] + x + 16, sq5[4]);
LoadAligned32x2U16Msan(sum3, x + 16, sum_width, s3[1]);
LoadAligned64x2U32Msan(square_sum3, x + 16, sum_width, sq3);
CalculateSumAndIndex3(s3[1], sq3, scales[1], &sum_3[0][1], &index_3[0][1]);
CalculateSumAndIndex3(s3[1] + 1, sq3 + 1, scales[1], &sum_3[1][1],
&index_3[1][1]);
CalculateIntermediate<9>(sum_3[0], index_3[0], ma3[0], t, t + 2);
PermuteB(t, b3[0]);
CalculateIntermediate<9>(sum_3[1], index_3[1], ma3[1], t, t + 2);
PermuteB(t, b3[1]);
LoadAligned32x3U16Msan(sum5, x + 16, sum_width, s5[1]);
LoadAligned64x3U32Msan(square_sum5, x + 16, sum_width, sq5);
CalculateSumAndIndex5(s5[1], sq5, scales[0], &sum_5[1], &index_5[1]);
CalculateIntermediate<25>(sum_5, index_5, ma5, t, t + 2);
PermuteB(t, b5);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcessLastRowLo(
const __m128i s[2], const uint16_t scales[2], const uint16_t* const sum3[4],
const uint16_t* const sum5[5], const uint32_t* const square_sum3[4],
const uint32_t* const square_sum5[5], __m128i sq[4], __m128i* const ma3,
__m128i* const ma5, __m128i b3[2], __m128i b5[2]) {
__m128i s3[3], s5[5], sq3[3][2], sq5[5][2];
Square(s[1], sq + 2);
SumHorizontal16(s, &s3[2], &s5[3]);
SumHorizontal32(sq, &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
LoadAligned16x3U16(sum5, 0, s5);
s5[4] = s5[3];
LoadAligned32x3U32(square_sum5, 0, sq5);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
CalculateIntermediate5(s5, sq5, scales[0], ma5, b5);
LoadAligned16x2U16(sum3, 0, s3);
LoadAligned32x2U32(square_sum3, 0, sq3);
CalculateIntermediate3(s3, sq3, scales[1], ma3, b3);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPreProcessLastRow(
const uint16_t* const src, const ptrdiff_t over_read_in_bytes,
const ptrdiff_t sum_width, const ptrdiff_t x, const uint16_t scales[2],
const uint16_t* const sum3[4], const uint16_t* const sum5[5],
const uint32_t* const square_sum3[4], const uint32_t* const square_sum5[5],
__m256i sq[6], __m256i ma3[2], __m256i ma5[2], __m256i b3[5],
__m256i b5[5]) {
const __m256i s0 = LoadUnaligned32Msan(src + 8, over_read_in_bytes + 16);
__m256i s3[2][3], s5[2][5], sq3[4][2], sq5[5][2], sum_3[2], index_3[2],
sum_5[2], index_5[2], t[4];
Square(s0, sq + 2);
sq[0] = _mm256_permute2x128_si256(sq[0], sq[2], 0x21);
sq[1] = _mm256_permute2x128_si256(sq[1], sq[3], 0x21);
SumHorizontal16(src, over_read_in_bytes, &s3[0][2], &s3[1][2], &s5[0][3],
&s5[1][3]);
SumHorizontal32(sq, &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
LoadAligned32x2U16(sum3, x, s3[0]);
LoadAligned64x2U32(square_sum3, x, sq3);
CalculateSumAndIndex3(s3[0], sq3, scales[1], &sum_3[0], &index_3[0]);
LoadAligned32x3U16(sum5, x, s5[0]);
s5[0][4] = s5[0][3];
LoadAligned64x3U32(square_sum5, x, sq5);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
CalculateSumAndIndex5(s5[0], sq5, scales[0], &sum_5[0], &index_5[0]);
const __m256i s1 = LoadUnaligned32Msan(src + 24, over_read_in_bytes + 48);
Square(s1, sq + 6);
sq[4] = _mm256_permute2x128_si256(sq[2], sq[6], 0x21);
sq[5] = _mm256_permute2x128_si256(sq[3], sq[7], 0x21);
SumHorizontal32(sq + 4, &sq3[2][0], &sq3[2][1], &sq5[3][0], &sq5[3][1]);
LoadAligned32x2U16Msan(sum3, x + 16, sum_width, s3[1]);
LoadAligned64x2U32Msan(square_sum3, x + 16, sum_width, sq3);
CalculateSumAndIndex3(s3[1], sq3, scales[1], &sum_3[1], &index_3[1]);
CalculateIntermediate<9>(sum_3, index_3, ma3, t, t + 2);
PermuteB(t, b3);
LoadAligned32x3U16Msan(sum5, x + 16, sum_width, s5[1]);
s5[1][4] = s5[1][3];
LoadAligned64x3U32Msan(square_sum5, x + 16, sum_width, sq5);
sq5[4][0] = sq5[3][0];
sq5[4][1] = sq5[3][1];
CalculateSumAndIndex5(s5[1], sq5, scales[0], &sum_5[1], &index_5[1]);
CalculateIntermediate<25>(sum_5, index_5, ma5, t, t + 2);
PermuteB(t, b5);
}
inline void BoxSumFilterPreProcess5(const uint16_t* const src0,
const uint16_t* const src1, const int width,
const uint32_t scale,
uint16_t* const sum5[5],
uint32_t* const square_sum5[5],
const ptrdiff_t sum_width, uint16_t* ma565,
uint32_t* b565) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2][2], ma0, sq_128[2][4], b0[2];
__m256i mas[3], sq[2][8], bs[10];
s[0][0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[0][1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
s[1][0] = LoadUnaligned16Msan(src1 + 0, overread_in_bytes + 0);
s[1][1] = LoadUnaligned16Msan(src1 + 8, overread_in_bytes + 16);
Square(s[0][0], sq_128[0]);
Square(s[1][0], sq_128[1]);
BoxFilterPreProcess5Lo(s, scale, sum5, square_sum5, sq_128, &ma0, b0);
sq[0][0] = SetrM128i(sq_128[0][2], sq_128[0][2]);
sq[0][1] = SetrM128i(sq_128[0][3], sq_128[0][3]);
sq[1][0] = SetrM128i(sq_128[1][2], sq_128[1][2]);
sq[1][1] = SetrM128i(sq_128[1][3], sq_128[1][3]);
mas[0] = SetrM128i(ma0, ma0);
bs[0] = SetrM128i(b0[0], b0[0]);
bs[1] = SetrM128i(b0[1], b0[1]);
int x = 0;
do {
__m256i ma5[3], ma[2], b[4];
BoxFilterPreProcess5(
src0 + x + 8, src1 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), sum_width,
x + 8, scale, sum5, square_sum5, sq, mas, bs);
Prepare3_8(mas, ma5);
ma[0] = Sum565Lo(ma5);
ma[1] = Sum565Hi(ma5);
StoreAligned64_ma(ma565, ma);
Sum565(bs + 0, b + 0);
Sum565(bs + 3, b + 2);
StoreAligned64(b565, b + 0);
StoreAligned64(b565 + 16, b + 2);
sq[0][0] = sq[0][6];
sq[0][1] = sq[0][7];
sq[1][0] = sq[1][6];
sq[1][1] = sq[1][7];
mas[0] = mas[2];
bs[0] = bs[5];
bs[1] = bs[6];
ma565 += 32;
b565 += 32;
x += 32;
} while (x < width);
}
template <bool calculate444>
LIBGAV1_ALWAYS_INLINE void BoxSumFilterPreProcess3(
const uint16_t* const src, const int width, const uint32_t scale,
uint16_t* const sum3[3], uint32_t* const square_sum3[3],
const ptrdiff_t sum_width, uint16_t* ma343, uint16_t* ma444, uint32_t* b343,
uint32_t* b444) {
const ptrdiff_t overread_in_bytes_128 =
kOverreadInBytesPass2_128 - sizeof(*src) * width;
__m128i s[2], ma0, sq_128[4], b0[2];
__m256i mas[3], sq[8], bs[7];
s[0] = LoadUnaligned16Msan(src + 0, overread_in_bytes_128 + 0);
s[1] = LoadUnaligned16Msan(src + 8, overread_in_bytes_128 + 16);
Square(s[0], sq_128);
BoxFilterPreProcess3Lo(s, scale, sum3, square_sum3, sq_128, &ma0, b0);
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
mas[0] = SetrM128i(ma0, ma0);
bs[0] = SetrM128i(b0[0], b0[0]);
bs[1] = SetrM128i(b0[1], b0[1]);
int x = 0;
do {
__m256i ma3[3];
BoxFilterPreProcess3(
src + x + 8, kOverreadInBytesPass2_256 + sizeof(*src) * (x + 8 - width),
x + 8, sum_width, scale, sum3, square_sum3, sq, mas, bs);
Prepare3_8(mas, ma3);
if (calculate444) { // NOLINT(readability-simplify-boolean-expr)
Store343_444Lo(ma3, bs + 0, 0, ma343, ma444, b343, b444);
Store343_444Hi(ma3, bs + 3, kMaStoreOffset, ma343, ma444, b343, b444);
ma444 += 32;
b444 += 32;
} else {
__m256i ma[2], b[4];
ma[0] = Sum343Lo(ma3);
ma[1] = Sum343Hi(ma3);
StoreAligned64_ma(ma343, ma);
Sum343(bs + 0, b + 0);
Sum343(bs + 3, b + 2);
StoreAligned64(b343 + 0, b + 0);
StoreAligned64(b343 + 16, b + 2);
}
sq[0] = sq[6];
sq[1] = sq[7];
mas[0] = mas[2];
bs[0] = bs[5];
bs[1] = bs[6];
ma343 += 32;
b343 += 32;
x += 32;
} while (x < width);
}
inline void BoxSumFilterPreProcess(
const uint16_t* const src0, const uint16_t* const src1, const int width,
const uint16_t scales[2], uint16_t* const sum3[4], uint16_t* const sum5[5],
uint32_t* const square_sum3[4], uint32_t* const square_sum5[5],
const ptrdiff_t sum_width, uint16_t* const ma343[4], uint16_t* const ma444,
uint16_t* ma565, uint32_t* const b343[4], uint32_t* const b444,
uint32_t* b565) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2][4], ma3_128[2][3], ma5_128[3], sq_128[2][8], b3_128[2][10],
b5_128[10];
__m256i ma3[2][3], ma5[3], sq[2][8], b3[2][7], b5[7];
s[0][0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[0][1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
s[1][0] = LoadUnaligned16Msan(src1 + 0, overread_in_bytes + 0);
s[1][1] = LoadUnaligned16Msan(src1 + 8, overread_in_bytes + 16);
Square(s[0][0], sq_128[0]);
Square(s[1][0], sq_128[1]);
BoxFilterPreProcessLo(s, scales, sum3, sum5, square_sum3, square_sum5, sq_128,
ma3_128, b3_128, &ma5_128[0], b5_128);
sq[0][0] = SetrM128i(sq_128[0][2], sq_128[0][2]);
sq[0][1] = SetrM128i(sq_128[0][3], sq_128[0][3]);
sq[1][0] = SetrM128i(sq_128[1][2], sq_128[1][2]);
sq[1][1] = SetrM128i(sq_128[1][3], sq_128[1][3]);
ma3[0][0] = SetrM128i(ma3_128[0][0], ma3_128[0][0]);
ma3[1][0] = SetrM128i(ma3_128[1][0], ma3_128[1][0]);
ma5[0] = SetrM128i(ma5_128[0], ma5_128[0]);
b3[0][0] = SetrM128i(b3_128[0][0], b3_128[0][0]);
b3[0][1] = SetrM128i(b3_128[0][1], b3_128[0][1]);
b3[1][0] = SetrM128i(b3_128[1][0], b3_128[1][0]);
b3[1][1] = SetrM128i(b3_128[1][1], b3_128[1][1]);
b5[0] = SetrM128i(b5_128[0], b5_128[0]);
b5[1] = SetrM128i(b5_128[1], b5_128[1]);
int x = 0;
do {
__m256i ma[2], b[4], ma3x[3], ma5x[3];
BoxFilterPreProcess(
src0 + x + 8, src1 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), x + 8,
scales, sum3, sum5, square_sum3, square_sum5, sum_width, sq, ma3, b3,
ma5, b5);
Prepare3_8(ma3[0], ma3x);
ma[0] = Sum343Lo(ma3x);
ma[1] = Sum343Hi(ma3x);
StoreAligned64_ma(ma343[0] + x, ma);
Sum343(b3[0], b);
Sum343(b3[0] + 3, b + 2);
StoreAligned64(b343[0] + x, b);
StoreAligned64(b343[0] + x + 16, b + 2);
Prepare3_8(ma3[1], ma3x);
Store343_444Lo(ma3x, b3[1], x, ma343[1], ma444, b343[1], b444);
Store343_444Hi(ma3x, b3[1] + 3, x + kMaStoreOffset, ma343[1], ma444,
b343[1], b444);
Prepare3_8(ma5, ma5x);
ma[0] = Sum565Lo(ma5x);
ma[1] = Sum565Hi(ma5x);
StoreAligned64_ma(ma565, ma);
Sum565(b5, b);
StoreAligned64(b565, b);
Sum565(b5 + 3, b);
StoreAligned64(b565 + 16, b);
sq[0][0] = sq[0][6];
sq[0][1] = sq[0][7];
sq[1][0] = sq[1][6];
sq[1][1] = sq[1][7];
ma3[0][0] = ma3[0][2];
ma3[1][0] = ma3[1][2];
ma5[0] = ma5[2];
b3[0][0] = b3[0][5];
b3[0][1] = b3[0][6];
b3[1][0] = b3[1][5];
b3[1][1] = b3[1][6];
b5[0] = b5[5];
b5[1] = b5[6];
ma565 += 32;
b565 += 32;
x += 32;
} while (x < width);
}
template <int shift>
inline __m256i FilterOutput(const __m256i ma_x_src, const __m256i b) {
// ma: 255 * 32 = 8160 (13 bits)
// b: 65088 * 32 = 2082816 (21 bits)
// v: b - ma * 255 (22 bits)
const __m256i v = _mm256_sub_epi32(b, ma_x_src);
// kSgrProjSgrBits = 8
// kSgrProjRestoreBits = 4
// shift = 4 or 5
// v >> 8 or 9 (13 bits)
return VrshrS32(v, kSgrProjSgrBits + shift - kSgrProjRestoreBits);
}
template <int shift>
inline __m256i CalculateFilteredOutput(const __m256i src, const __m256i ma,
const __m256i b[2]) {
const __m256i ma_x_src_lo = VmullLo16(ma, src);
const __m256i ma_x_src_hi = VmullHi16(ma, src);
const __m256i dst_lo = FilterOutput<shift>(ma_x_src_lo, b[0]);
const __m256i dst_hi = FilterOutput<shift>(ma_x_src_hi, b[1]);
return _mm256_packs_epi32(dst_lo, dst_hi); // 13 bits
}
inline __m256i CalculateFilteredOutputPass1(const __m256i src,
const __m256i ma[2],
const __m256i b[2][2]) {
const __m256i ma_sum = _mm256_add_epi16(ma[0], ma[1]);
__m256i b_sum[2];
b_sum[0] = _mm256_add_epi32(b[0][0], b[1][0]);
b_sum[1] = _mm256_add_epi32(b[0][1], b[1][1]);
return CalculateFilteredOutput<5>(src, ma_sum, b_sum);
}
inline __m256i CalculateFilteredOutputPass2(const __m256i src,
const __m256i ma[3],
const __m256i b[3][2]) {
const __m256i ma_sum = Sum3_16(ma);
__m256i b_sum[2];
Sum3_32(b, b_sum);
return CalculateFilteredOutput<5>(src, ma_sum, b_sum);
}
inline __m256i SelfGuidedFinal(const __m256i src, const __m256i v[2]) {
const __m256i v_lo =
VrshrS32(v[0], kSgrProjRestoreBits + kSgrProjPrecisionBits);
const __m256i v_hi =
VrshrS32(v[1], kSgrProjRestoreBits + kSgrProjPrecisionBits);
const __m256i vv = _mm256_packs_epi32(v_lo, v_hi);
return _mm256_add_epi16(src, vv);
}
inline __m256i SelfGuidedDoubleMultiplier(const __m256i src,
const __m256i filter[2], const int w0,
const int w2) {
__m256i v[2];
const __m256i w0_w2 =
_mm256_set1_epi32((w2 << 16) | static_cast<uint16_t>(w0));
const __m256i f_lo = _mm256_unpacklo_epi16(filter[0], filter[1]);
const __m256i f_hi = _mm256_unpackhi_epi16(filter[0], filter[1]);
v[0] = _mm256_madd_epi16(w0_w2, f_lo);
v[1] = _mm256_madd_epi16(w0_w2, f_hi);
return SelfGuidedFinal(src, v);
}
inline __m256i SelfGuidedSingleMultiplier(const __m256i src,
const __m256i filter, const int w0) {
// weight: -96 to 96 (Sgrproj_Xqd_Min/Max)
__m256i v[2];
v[0] = VmullNLo8(filter, w0);
v[1] = VmullNHi8(filter, w0);
return SelfGuidedFinal(src, v);
}
inline void ClipAndStore(uint16_t* const dst, const __m256i val) {
const __m256i val0 = _mm256_max_epi16(val, _mm256_setzero_si256());
const __m256i val1 = _mm256_min_epi16(val0, _mm256_set1_epi16(1023));
StoreUnaligned32(dst, val1);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPass1(
const uint16_t* const src, const uint16_t* const src0,
const uint16_t* const src1, const ptrdiff_t stride, uint16_t* const sum5[5],
uint32_t* const square_sum5[5], const int width, const ptrdiff_t sum_width,
const uint32_t scale, const int16_t w0, uint16_t* const ma565[2],
uint32_t* const b565[2], uint16_t* const dst) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2][2], ma0, sq_128[2][4], b0[2];
__m256i mas[3], sq[2][8], bs[7];
s[0][0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[0][1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
s[1][0] = LoadUnaligned16Msan(src1 + 0, overread_in_bytes + 0);
s[1][1] = LoadUnaligned16Msan(src1 + 8, overread_in_bytes + 16);
Square(s[0][0], sq_128[0]);
Square(s[1][0], sq_128[1]);
BoxFilterPreProcess5Lo(s, scale, sum5, square_sum5, sq_128, &ma0, b0);
sq[0][0] = SetrM128i(sq_128[0][2], sq_128[0][2]);
sq[0][1] = SetrM128i(sq_128[0][3], sq_128[0][3]);
sq[1][0] = SetrM128i(sq_128[1][2], sq_128[1][2]);
sq[1][1] = SetrM128i(sq_128[1][3], sq_128[1][3]);
mas[0] = SetrM128i(ma0, ma0);
bs[0] = SetrM128i(b0[0], b0[0]);
bs[1] = SetrM128i(b0[1], b0[1]);
int x = 0;
do {
__m256i ma5[3], ma[4], b[4][2];
BoxFilterPreProcess5(
src0 + x + 8, src1 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), sum_width,
x + 8, scale, sum5, square_sum5, sq, mas, bs);
Prepare3_8(mas, ma5);
ma[2] = Sum565Lo(ma5);
ma[3] = Sum565Hi(ma5);
ma[1] = _mm256_permute2x128_si256(ma[2], ma[3], 0x20);
ma[3] = _mm256_permute2x128_si256(ma[2], ma[3], 0x31);
StoreAligned32(ma565[1] + x + 0, ma[1]);
StoreAligned32(ma565[1] + x + 16, ma[3]);
Sum565(bs + 0, b[1]);
Sum565(bs + 3, b[3]);
StoreAligned64(b565[1] + x, b[1]);
StoreAligned64(b565[1] + x + 16, b[3]);
const __m256i sr0_lo = LoadUnaligned32(src + x + 0);
ma[0] = LoadAligned32(ma565[0] + x);
LoadAligned64(b565[0] + x, b[0]);
const __m256i p0 = CalculateFilteredOutputPass1(sr0_lo, ma, b);
const __m256i d0 = SelfGuidedSingleMultiplier(sr0_lo, p0, w0);
ClipAndStore(dst + x + 0, d0);
const __m256i sr0_hi = LoadUnaligned32(src + x + 16);
ma[2] = LoadAligned32(ma565[0] + x + 16);
LoadAligned64(b565[0] + x + 16, b[2]);
const __m256i p1 = CalculateFilteredOutputPass1(sr0_hi, ma + 2, b + 2);
const __m256i d1 = SelfGuidedSingleMultiplier(sr0_hi, p1, w0);
ClipAndStore(dst + x + 16, d1);
const __m256i sr1_lo = LoadUnaligned32(src + stride + x + 0);
const __m256i p10 = CalculateFilteredOutput<4>(sr1_lo, ma[1], b[1]);
const __m256i d10 = SelfGuidedSingleMultiplier(sr1_lo, p10, w0);
ClipAndStore(dst + stride + x + 0, d10);
const __m256i sr1_hi = LoadUnaligned32(src + stride + x + 16);
const __m256i p11 = CalculateFilteredOutput<4>(sr1_hi, ma[3], b[3]);
const __m256i d11 = SelfGuidedSingleMultiplier(sr1_hi, p11, w0);
ClipAndStore(dst + stride + x + 16, d11);
sq[0][0] = sq[0][6];
sq[0][1] = sq[0][7];
sq[1][0] = sq[1][6];
sq[1][1] = sq[1][7];
mas[0] = mas[2];
bs[0] = bs[5];
bs[1] = bs[6];
x += 32;
} while (x < width);
}
inline void BoxFilterPass1LastRow(
const uint16_t* const src, const uint16_t* const src0, const int width,
const ptrdiff_t sum_width, const uint32_t scale, const int16_t w0,
uint16_t* const sum5[5], uint32_t* const square_sum5[5], uint16_t* ma565,
uint32_t* b565, uint16_t* const dst) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2], ma0[2], sq_128[8], b0[6];
__m256i mas[3], sq[8], bs[7];
s[0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
Square(s[0], sq_128);
BoxFilterPreProcess5LastRowLo(s, scale, sum5, square_sum5, sq_128, &ma0[0],
b0);
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
mas[0] = SetrM128i(ma0[0], ma0[0]);
bs[0] = SetrM128i(b0[0], b0[0]);
bs[1] = SetrM128i(b0[1], b0[1]);
int x = 0;
do {
__m256i ma5[3], ma[4], b[4][2];
BoxFilterPreProcess5LastRow(
src0 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), sum_width,
x + 8, scale, sum5, square_sum5, sq, mas, bs);
Prepare3_8(mas, ma5);
ma[2] = Sum565Lo(ma5);
ma[3] = Sum565Hi(ma5);
Sum565(bs + 0, b[1]);
Sum565(bs + 3, b[3]);
const __m256i sr0_lo = LoadUnaligned32(src + x + 0);
ma[0] = LoadAligned32(ma565 + x);
ma[1] = _mm256_permute2x128_si256(ma[2], ma[3], 0x20);
LoadAligned64(b565 + x, b[0]);
const __m256i p0 = CalculateFilteredOutputPass1(sr0_lo, ma, b);
const __m256i d0 = SelfGuidedSingleMultiplier(sr0_lo, p0, w0);
ClipAndStore(dst + x + 0, d0);
const __m256i sr0_hi = LoadUnaligned32(src + x + 16);
ma[0] = LoadAligned32(ma565 + x + 16);
ma[1] = _mm256_permute2x128_si256(ma[2], ma[3], 0x31);
LoadAligned64(b565 + x + 16, b[2]);
const __m256i p1 = CalculateFilteredOutputPass1(sr0_hi, ma, b + 2);
const __m256i d1 = SelfGuidedSingleMultiplier(sr0_hi, p1, w0);
ClipAndStore(dst + x + 16, d1);
sq[0] = sq[6];
sq[1] = sq[7];
mas[0] = mas[2];
bs[0] = bs[5];
bs[1] = bs[6];
x += 32;
} while (x < width);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterPass2(
const uint16_t* const src, const uint16_t* const src0, const int width,
const ptrdiff_t sum_width, const uint32_t scale, const int16_t w0,
uint16_t* const sum3[3], uint32_t* const square_sum3[3],
uint16_t* const ma343[3], uint16_t* const ma444[2], uint32_t* const b343[3],
uint32_t* const b444[2], uint16_t* const dst) {
const ptrdiff_t overread_in_bytes_128 =
kOverreadInBytesPass2_128 - sizeof(*src0) * width;
__m128i s0[2], ma0, sq_128[4], b0[2];
__m256i mas[3], sq[8], bs[7];
s0[0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes_128 + 0);
s0[1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes_128 + 16);
Square(s0[0], sq_128);
BoxFilterPreProcess3Lo(s0, scale, sum3, square_sum3, sq_128, &ma0, b0);
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
mas[0] = SetrM128i(ma0, ma0);
bs[0] = SetrM128i(b0[0], b0[0]);
bs[1] = SetrM128i(b0[1], b0[1]);
int x = 0;
do {
__m256i ma[4], b[4][2], ma3[3];
BoxFilterPreProcess3(
src0 + x + 8,
kOverreadInBytesPass2_256 + sizeof(*src0) * (x + 8 - width), x + 8,
sum_width, scale, sum3, square_sum3, sq, mas, bs);
Prepare3_8(mas, ma3);
Store343_444(ma3, bs, x, &ma[2], &ma[3], b[2], b[3], ma343[2], ma444[1],
b343[2], b444[1]);
const __m256i sr_lo = LoadUnaligned32(src + x + 0);
const __m256i sr_hi = LoadUnaligned32(src + x + 16);
ma[0] = LoadAligned32(ma343[0] + x);
ma[1] = LoadAligned32(ma444[0] + x);
LoadAligned64(b343[0] + x, b[0]);
LoadAligned64(b444[0] + x, b[1]);
const __m256i p0 = CalculateFilteredOutputPass2(sr_lo, ma, b);
ma[1] = LoadAligned32(ma343[0] + x + 16);
ma[2] = LoadAligned32(ma444[0] + x + 16);
LoadAligned64(b343[0] + x + 16, b[1]);
LoadAligned64(b444[0] + x + 16, b[2]);
const __m256i p1 = CalculateFilteredOutputPass2(sr_hi, ma + 1, b + 1);
const __m256i d0 = SelfGuidedSingleMultiplier(sr_lo, p0, w0);
const __m256i d1 = SelfGuidedSingleMultiplier(sr_hi, p1, w0);
ClipAndStore(dst + x + 0, d0);
ClipAndStore(dst + x + 16, d1);
sq[0] = sq[6];
sq[1] = sq[7];
mas[0] = mas[2];
bs[0] = bs[5];
bs[1] = bs[6];
x += 32;
} while (x < width);
}
LIBGAV1_ALWAYS_INLINE void BoxFilter(
const uint16_t* const src, const uint16_t* const src0,
const uint16_t* const src1, const ptrdiff_t stride, const int width,
const uint16_t scales[2], const int16_t w0, const int16_t w2,
uint16_t* const sum3[4], uint16_t* const sum5[5],
uint32_t* const square_sum3[4], uint32_t* const square_sum5[5],
const ptrdiff_t sum_width, uint16_t* const ma343[4],
uint16_t* const ma444[3], uint16_t* const ma565[2], uint32_t* const b343[4],
uint32_t* const b444[3], uint32_t* const b565[2], uint16_t* const dst) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2][4], ma3_128[2][3], ma5_0, sq_128[2][8], b3_128[2][10], b5_128[2];
__m256i ma3[2][3], ma5[3], sq[2][8], b3[2][7], b5[7];
s[0][0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[0][1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
s[1][0] = LoadUnaligned16Msan(src1 + 0, overread_in_bytes + 0);
s[1][1] = LoadUnaligned16Msan(src1 + 8, overread_in_bytes + 16);
Square(s[0][0], sq_128[0]);
Square(s[1][0], sq_128[1]);
BoxFilterPreProcessLo(s, scales, sum3, sum5, square_sum3, square_sum5, sq_128,
ma3_128, b3_128, &ma5_0, b5_128);
sq[0][0] = SetrM128i(sq_128[0][2], sq_128[0][2]);
sq[0][1] = SetrM128i(sq_128[0][3], sq_128[0][3]);
sq[1][0] = SetrM128i(sq_128[1][2], sq_128[1][2]);
sq[1][1] = SetrM128i(sq_128[1][3], sq_128[1][3]);
ma3[0][0] = SetrM128i(ma3_128[0][0], ma3_128[0][0]);
ma3[1][0] = SetrM128i(ma3_128[1][0], ma3_128[1][0]);
ma5[0] = SetrM128i(ma5_0, ma5_0);
b3[0][0] = SetrM128i(b3_128[0][0], b3_128[0][0]);
b3[0][1] = SetrM128i(b3_128[0][1], b3_128[0][1]);
b3[1][0] = SetrM128i(b3_128[1][0], b3_128[1][0]);
b3[1][1] = SetrM128i(b3_128[1][1], b3_128[1][1]);
b5[0] = SetrM128i(b5_128[0], b5_128[0]);
b5[1] = SetrM128i(b5_128[1], b5_128[1]);
int x = 0;
do {
__m256i ma[3][4], mat[3][3], b[3][3][2], bt[3][3][2], p[2][2], ma3x[2][3],
ma5x[3];
BoxFilterPreProcess(
src0 + x + 8, src1 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), x + 8,
scales, sum3, sum5, square_sum3, square_sum5, sum_width, sq, ma3, b3,
ma5, b5);
Prepare3_8(ma3[0], ma3x[0]);
Prepare3_8(ma3[1], ma3x[1]);
Prepare3_8(ma5, ma5x);
Store343_444(ma3x[0], b3[0], x, &ma[1][2], &mat[1][2], &ma[2][1],
&mat[2][1], b[1][2], bt[1][2], b[2][1], bt[2][1], ma343[2],
ma444[1], b343[2], b444[1]);
Store343_444(ma3x[1], b3[1], x, &ma[2][2], &mat[2][2], b[2][2], bt[2][2],
ma343[3], ma444[2], b343[3], b444[2]);
ma[0][2] = Sum565Lo(ma5x);
ma[0][3] = Sum565Hi(ma5x);
ma[0][1] = _mm256_permute2x128_si256(ma[0][2], ma[0][3], 0x20);
ma[0][3] = _mm256_permute2x128_si256(ma[0][2], ma[0][3], 0x31);
StoreAligned32(ma565[1] + x + 0, ma[0][1]);
StoreAligned32(ma565[1] + x + 16, ma[0][3]);
Sum565(b5, b[0][1]);
StoreAligned64(b565[1] + x, b[0][1]);
const __m256i sr0_lo = LoadUnaligned32(src + x);
const __m256i sr1_lo = LoadUnaligned32(src + stride + x);
ma[0][0] = LoadAligned32(ma565[0] + x);
LoadAligned64(b565[0] + x, b[0][0]);
p[0][0] = CalculateFilteredOutputPass1(sr0_lo, ma[0], b[0]);
p[1][0] = CalculateFilteredOutput<4>(sr1_lo, ma[0][1], b[0][1]);
ma[1][0] = LoadAligned32(ma343[0] + x);
ma[1][1] = LoadAligned32(ma444[0] + x);
// Keeping the following 4 redundant lines is faster. The reason is that
// there are not enough registers available, and these values could be saved
// and loaded which is even slower.
ma[1][2] = LoadAligned32(ma343[2] + x); // Redundant line 1.
LoadAligned64(b343[0] + x, b[1][0]);
LoadAligned64(b444[0] + x, b[1][1]);
p[0][1] = CalculateFilteredOutputPass2(sr0_lo, ma[1], b[1]);
ma[2][0] = LoadAligned32(ma343[1] + x);
ma[2][1] = LoadAligned32(ma444[1] + x); // Redundant line 2.
LoadAligned64(b343[1] + x, b[2][0]);
p[1][1] = CalculateFilteredOutputPass2(sr1_lo, ma[2], b[2]);
const __m256i d00 = SelfGuidedDoubleMultiplier(sr0_lo, p[0], w0, w2);
ClipAndStore(dst + x, d00);
const __m256i d10x = SelfGuidedDoubleMultiplier(sr1_lo, p[1], w0, w2);
ClipAndStore(dst + stride + x, d10x);
Sum565(b5 + 3, bt[0][1]);
StoreAligned64(b565[1] + x + 16, bt[0][1]);
const __m256i sr0_hi = LoadUnaligned32(src + x + 16);
const __m256i sr1_hi = LoadUnaligned32(src + stride + x + 16);
ma[0][2] = LoadAligned32(ma565[0] + x + 16);
LoadAligned64(b565[0] + x + 16, bt[0][0]);
p[0][0] = CalculateFilteredOutputPass1(sr0_hi, ma[0] + 2, bt[0]);
p[1][0] = CalculateFilteredOutput<4>(sr1_hi, ma[0][3], bt[0][1]);
mat[1][0] = LoadAligned32(ma343[0] + x + 16);
mat[1][1] = LoadAligned32(ma444[0] + x + 16);
mat[1][2] = LoadAligned32(ma343[2] + x + 16); // Redundant line 3.
LoadAligned64(b343[0] + x + 16, bt[1][0]);
LoadAligned64(b444[0] + x + 16, bt[1][1]);
p[0][1] = CalculateFilteredOutputPass2(sr0_hi, mat[1], bt[1]);
mat[2][0] = LoadAligned32(ma343[1] + x + 16);
mat[2][1] = LoadAligned32(ma444[1] + x + 16); // Redundant line 4.
LoadAligned64(b343[1] + x + 16, bt[2][0]);
p[1][1] = CalculateFilteredOutputPass2(sr1_hi, mat[2], bt[2]);
const __m256i d01 = SelfGuidedDoubleMultiplier(sr0_hi, p[0], w0, w2);
ClipAndStore(dst + x + 16, d01);
const __m256i d11 = SelfGuidedDoubleMultiplier(sr1_hi, p[1], w0, w2);
ClipAndStore(dst + stride + x + 16, d11);
sq[0][0] = sq[0][6];
sq[0][1] = sq[0][7];
sq[1][0] = sq[1][6];
sq[1][1] = sq[1][7];
ma3[0][0] = ma3[0][2];
ma3[1][0] = ma3[1][2];
ma5[0] = ma5[2];
b3[0][0] = b3[0][5];
b3[0][1] = b3[0][6];
b3[1][0] = b3[1][5];
b3[1][1] = b3[1][6];
b5[0] = b5[5];
b5[1] = b5[6];
x += 32;
} while (x < width);
}
inline void BoxFilterLastRow(
const uint16_t* const src, const uint16_t* const src0, const int width,
const ptrdiff_t sum_width, const uint16_t scales[2], const int16_t w0,
const int16_t w2, uint16_t* const sum3[4], uint16_t* const sum5[5],
uint32_t* const square_sum3[4], uint32_t* const square_sum5[5],
uint16_t* const ma343, uint16_t* const ma444, uint16_t* const ma565,
uint32_t* const b343, uint32_t* const b444, uint32_t* const b565,
uint16_t* const dst) {
const ptrdiff_t overread_in_bytes =
kOverreadInBytesPass1_128 - sizeof(*src0) * width;
__m128i s[2], ma3_0, ma5_0, sq_128[4], b3_128[2], b5_128[2];
__m256i ma3[3], ma5[3], sq[8], b3[7], b5[7];
s[0] = LoadUnaligned16Msan(src0 + 0, overread_in_bytes + 0);
s[1] = LoadUnaligned16Msan(src0 + 8, overread_in_bytes + 16);
Square(s[0], sq_128);
BoxFilterPreProcessLastRowLo(s, scales, sum3, sum5, square_sum3, square_sum5,
sq_128, &ma3_0, &ma5_0, b3_128, b5_128);
sq[0] = SetrM128i(sq_128[2], sq_128[2]);
sq[1] = SetrM128i(sq_128[3], sq_128[3]);
ma3[0] = SetrM128i(ma3_0, ma3_0);
ma5[0] = SetrM128i(ma5_0, ma5_0);
b3[0] = SetrM128i(b3_128[0], b3_128[0]);
b3[1] = SetrM128i(b3_128[1], b3_128[1]);
b5[0] = SetrM128i(b5_128[0], b5_128[0]);
b5[1] = SetrM128i(b5_128[1], b5_128[1]);
int x = 0;
do {
__m256i ma[4], mat[4], b[3][2], bt[3][2], ma3x[3], ma5x[3], p[2];
BoxFilterPreProcessLastRow(
src0 + x + 8,
kOverreadInBytesPass1_256 + sizeof(*src0) * (x + 8 - width), sum_width,
x + 8, scales, sum3, sum5, square_sum3, square_sum5, sq, ma3, ma5, b3,
b5);
Prepare3_8(ma3, ma3x);
Prepare3_8(ma5, ma5x);
ma[2] = Sum565Lo(ma5x);
Sum565(b5, b[1]);
mat[1] = Sum565Hi(ma5x);
Sum565(b5 + 3, bt[1]);
ma[3] = Sum343Lo(ma3x);
Sum343(b3, b[2]);
mat[2] = Sum343Hi(ma3x);
Sum343(b3 + 3, bt[2]);
const __m256i sr_lo = LoadUnaligned32(src + x);
ma[0] = LoadAligned32(ma565 + x);
ma[1] = _mm256_permute2x128_si256(ma[2], mat[1], 0x20);
mat[1] = _mm256_permute2x128_si256(ma[2], mat[1], 0x31);
LoadAligned64(b565 + x, b[0]);
p[0] = CalculateFilteredOutputPass1(sr_lo, ma, b);
ma[0] = LoadAligned32(ma343 + x);
ma[1] = LoadAligned32(ma444 + x);
ma[2] = _mm256_permute2x128_si256(ma[3], mat[2], 0x20);
LoadAligned64(b343 + x, b[0]);
LoadAligned64(b444 + x, b[1]);
p[1] = CalculateFilteredOutputPass2(sr_lo, ma, b);
const __m256i d0 = SelfGuidedDoubleMultiplier(sr_lo, p, w0, w2);
const __m256i sr_hi = LoadUnaligned32(src + x + 16);
mat[0] = LoadAligned32(ma565 + x + 16);
LoadAligned64(b565 + x + 16, bt[0]);
p[0] = CalculateFilteredOutputPass1(sr_hi, mat, bt);
mat[0] = LoadAligned32(ma343 + x + 16);
mat[1] = LoadAligned32(ma444 + x + 16);
mat[2] = _mm256_permute2x128_si256(ma[3], mat[2], 0x31);
LoadAligned64(b343 + x + 16, bt[0]);
LoadAligned64(b444 + x + 16, bt[1]);
p[1] = CalculateFilteredOutputPass2(sr_hi, mat, bt);
const __m256i d1 = SelfGuidedDoubleMultiplier(sr_hi, p, w0, w2);
ClipAndStore(dst + x + 0, d0);
ClipAndStore(dst + x + 16, d1);
sq[0] = sq[6];
sq[1] = sq[7];
ma3[0] = ma3[2];
ma5[0] = ma5[2];
b3[0] = b3[5];
b3[1] = b3[6];
b5[0] = b5[5];
b5[1] = b5[6];
x += 32;
} while (x < width);
}
LIBGAV1_ALWAYS_INLINE void BoxFilterProcess(
const RestorationUnitInfo& restoration_info, const uint16_t* src,
const ptrdiff_t stride, const uint16_t* const top_border,
const ptrdiff_t top_border_stride, const uint16_t* bottom_border,
const ptrdiff_t bottom_border_stride, const int width, const int height,
SgrBuffer* const sgr_buffer, uint16_t* dst) {
const auto temp_stride = Align<ptrdiff_t>(width, 32);
const auto sum_width = temp_stride + 8;
const auto sum_stride = temp_stride + 32;
const int sgr_proj_index = restoration_info.sgr_proj_info.index;
const uint16_t* const scales = kSgrScaleParameter[sgr_proj_index]; // < 2^12.
const int16_t w0 = restoration_info.sgr_proj_info.multiplier[0];
const int16_t w1 = restoration_info.sgr_proj_info.multiplier[1];
const int16_t w2 = (1 << kSgrProjPrecisionBits) - w0 - w1;
uint16_t *sum3[4], *sum5[5], *ma343[4], *ma444[3], *ma565[2];
uint32_t *square_sum3[4], *square_sum5[5], *b343[4], *b444[3], *b565[2];
sum3[0] = sgr_buffer->sum3 + kSumOffset;
square_sum3[0] = sgr_buffer->square_sum3 + kSumOffset;
ma343[0] = sgr_buffer->ma343;
b343[0] = sgr_buffer->b343;
for (int i = 1; i <= 3; ++i) {
sum3[i] = sum3[i - 1] + sum_stride;
square_sum3[i] = square_sum3[i - 1] + sum_stride;
ma343[i] = ma343[i - 1] + temp_stride;
b343[i] = b343[i - 1] + temp_stride;
}
sum5[0] = sgr_buffer->sum5 + kSumOffset;
square_sum5[0] = sgr_buffer->square_sum5 + kSumOffset;
for (int i = 1; i <= 4; ++i) {
sum5[i] = sum5[i - 1] + sum_stride;
square_sum5[i] = square_sum5[i - 1] + sum_stride;
}
ma444[0] = sgr_buffer->ma444;
b444[0] = sgr_buffer->b444;
for (int i = 1; i <= 2; ++i) {
ma444[i] = ma444[i - 1] + temp_stride;
b444[i] = b444[i - 1] + temp_stride;
}
ma565[0] = sgr_buffer->ma565;
ma565[1] = ma565[0] + temp_stride;
b565[0] = sgr_buffer->b565;
b565[1] = b565[0] + temp_stride;
assert(scales[0] != 0);
assert(scales[1] != 0);
BoxSum(top_border, top_border_stride, width, sum_stride, temp_stride, sum3[0],
sum5[1], square_sum3[0], square_sum5[1]);
sum5[0] = sum5[1];
square_sum5[0] = square_sum5[1];
const uint16_t* const s = (height > 1) ? src + stride : bottom_border;
BoxSumFilterPreProcess(src, s, width, scales, sum3, sum5, square_sum3,
square_sum5, sum_width, ma343, ma444[0], ma565[0],
b343, b444[0], b565[0]);
sum5[0] = sgr_buffer->sum5 + kSumOffset;
square_sum5[0] = sgr_buffer->square_sum5 + kSumOffset;
for (int y = (height >> 1) - 1; y > 0; --y) {
Circulate4PointersBy2<uint16_t>(sum3);
Circulate4PointersBy2<uint32_t>(square_sum3);
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
BoxFilter(src + 3, src + 2 * stride, src + 3 * stride, stride, width,
scales, w0, w2, sum3, sum5, square_sum3, square_sum5, sum_width,
ma343, ma444, ma565, b343, b444, b565, dst);
src += 2 * stride;
dst += 2 * stride;
Circulate4PointersBy2<uint16_t>(ma343);
Circulate4PointersBy2<uint32_t>(b343);
std::swap(ma444[0], ma444[2]);
std::swap(b444[0], b444[2]);
std::swap(ma565[0], ma565[1]);
std::swap(b565[0], b565[1]);
}
Circulate4PointersBy2<uint16_t>(sum3);
Circulate4PointersBy2<uint32_t>(square_sum3);
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
if ((height & 1) == 0 || height > 1) {
const uint16_t* sr[2];
if ((height & 1) == 0) {
sr[0] = bottom_border;
sr[1] = bottom_border + bottom_border_stride;
} else {
sr[0] = src + 2 * stride;
sr[1] = bottom_border;
}
BoxFilter(src + 3, sr[0], sr[1], stride, width, scales, w0, w2, sum3, sum5,
square_sum3, square_sum5, sum_width, ma343, ma444, ma565, b343,
b444, b565, dst);
}
if ((height & 1) != 0) {
if (height > 1) {
src += 2 * stride;
dst += 2 * stride;
Circulate4PointersBy2<uint16_t>(sum3);
Circulate4PointersBy2<uint32_t>(square_sum3);
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
Circulate4PointersBy2<uint16_t>(ma343);
Circulate4PointersBy2<uint32_t>(b343);
std::swap(ma444[0], ma444[2]);
std::swap(b444[0], b444[2]);
std::swap(ma565[0], ma565[1]);
std::swap(b565[0], b565[1]);
}
BoxFilterLastRow(src + 3, bottom_border + bottom_border_stride, width,
sum_width, scales, w0, w2, sum3, sum5, square_sum3,
square_sum5, ma343[0], ma444[0], ma565[0], b343[0],
b444[0], b565[0], dst);
}
}
inline void BoxFilterProcessPass1(const RestorationUnitInfo& restoration_info,
const uint16_t* src, const ptrdiff_t stride,
const uint16_t* const top_border,
const ptrdiff_t top_border_stride,
const uint16_t* bottom_border,
const ptrdiff_t bottom_border_stride,
const int width, const int height,
SgrBuffer* const sgr_buffer, uint16_t* dst) {
const auto temp_stride = Align<ptrdiff_t>(width, 32);
const auto sum_width = temp_stride + 8;
const auto sum_stride = temp_stride + 32;
const int sgr_proj_index = restoration_info.sgr_proj_info.index;
const uint32_t scale = kSgrScaleParameter[sgr_proj_index][0]; // < 2^12.
const int16_t w0 = restoration_info.sgr_proj_info.multiplier[0];
uint16_t *sum5[5], *ma565[2];
uint32_t *square_sum5[5], *b565[2];
sum5[0] = sgr_buffer->sum5 + kSumOffset;
square_sum5[0] = sgr_buffer->square_sum5 + kSumOffset;
for (int i = 1; i <= 4; ++i) {
sum5[i] = sum5[i - 1] + sum_stride;
square_sum5[i] = square_sum5[i - 1] + sum_stride;
}
ma565[0] = sgr_buffer->ma565;
ma565[1] = ma565[0] + temp_stride;
b565[0] = sgr_buffer->b565;
b565[1] = b565[0] + temp_stride;
assert(scale != 0);
BoxSum<5>(top_border, top_border_stride, width, sum_stride, temp_stride,
sum5[1], square_sum5[1]);
sum5[0] = sum5[1];
square_sum5[0] = square_sum5[1];
const uint16_t* const s = (height > 1) ? src + stride : bottom_border;
BoxSumFilterPreProcess5(src, s, width, scale, sum5, square_sum5, sum_width,
ma565[0], b565[0]);
sum5[0] = sgr_buffer->sum5 + kSumOffset;
square_sum5[0] = sgr_buffer->square_sum5 + kSumOffset;
for (int y = (height >> 1) - 1; y > 0; --y) {
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
BoxFilterPass1(src + 3, src + 2 * stride, src + 3 * stride, stride, sum5,
square_sum5, width, sum_width, scale, w0, ma565, b565, dst);
src += 2 * stride;
dst += 2 * stride;
std::swap(ma565[0], ma565[1]);
std::swap(b565[0], b565[1]);
}
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
if ((height & 1) == 0 || height > 1) {
const uint16_t* sr[2];
if ((height & 1) == 0) {
sr[0] = bottom_border;
sr[1] = bottom_border + bottom_border_stride;
} else {
sr[0] = src + 2 * stride;
sr[1] = bottom_border;
}
BoxFilterPass1(src + 3, sr[0], sr[1], stride, sum5, square_sum5, width,
sum_width, scale, w0, ma565, b565, dst);
}
if ((height & 1) != 0) {
src += 3;
if (height > 1) {
src += 2 * stride;
dst += 2 * stride;
std::swap(ma565[0], ma565[1]);
std::swap(b565[0], b565[1]);
Circulate5PointersBy2<uint16_t>(sum5);
Circulate5PointersBy2<uint32_t>(square_sum5);
}
BoxFilterPass1LastRow(src, bottom_border + bottom_border_stride, width,
sum_width, scale, w0, sum5, square_sum5, ma565[0],
b565[0], dst);
}
}
inline void BoxFilterProcessPass2(const RestorationUnitInfo& restoration_info,
const uint16_t* src, const ptrdiff_t stride,
const uint16_t* const top_border,
const ptrdiff_t top_border_stride,
const uint16_t* bottom_border,
const ptrdiff_t bottom_border_stride,
const int width, const int height,
SgrBuffer* const sgr_buffer, uint16_t* dst) {
assert(restoration_info.sgr_proj_info.multiplier[0] == 0);
const auto temp_stride = Align<ptrdiff_t>(width, 32);
const auto sum_width = temp_stride + 8;
const auto sum_stride = temp_stride + 32;
const int16_t w1 = restoration_info.sgr_proj_info.multiplier[1];
const int16_t w0 = (1 << kSgrProjPrecisionBits) - w1;
const int sgr_proj_index = restoration_info.sgr_proj_info.index;
const uint32_t scale = kSgrScaleParameter[sgr_proj_index][1]; // < 2^12.
uint16_t *sum3[3], *ma343[3], *ma444[2];
uint32_t *square_sum3[3], *b343[3], *b444[2];
sum3[0] = sgr_buffer->sum3 + kSumOffset;
square_sum3[0] = sgr_buffer->square_sum3 + kSumOffset;
ma343[0] = sgr_buffer->ma343;
b343[0] = sgr_buffer->b343;
for (int i = 1; i <= 2; ++i) {
sum3[i] = sum3[i - 1] + sum_stride;
square_sum3[i] = square_sum3[i - 1] + sum_stride;
ma343[i] = ma343[i - 1] + temp_stride;
b343[i] = b343[i - 1] + temp_stride;
}
ma444[0] = sgr_buffer->ma444;
ma444[1] = ma444[0] + temp_stride;
b444[0] = sgr_buffer->b444;
b444[1] = b444[0] + temp_stride;
assert(scale != 0);
BoxSum<3>(top_border, top_border_stride, width, sum_stride, temp_stride,
sum3[0], square_sum3[0]);
BoxSumFilterPreProcess3<false>(src, width, scale, sum3, square_sum3,
sum_width, ma343[0], nullptr, b343[0],
nullptr);
Circulate3PointersBy1<uint16_t>(sum3);
Circulate3PointersBy1<uint32_t>(square_sum3);
const uint16_t* s;
if (height > 1) {
s = src + stride;
} else {
s = bottom_border;
bottom_border += bottom_border_stride;
}
BoxSumFilterPreProcess3<true>(s, width, scale, sum3, square_sum3, sum_width,
ma343[1], ma444[0], b343[1], b444[0]);
for (int y = height - 2; y > 0; --y) {
Circulate3PointersBy1<uint16_t>(sum3);
Circulate3PointersBy1<uint32_t>(square_sum3);
BoxFilterPass2(src + 2, src + 2 * stride, width, sum_width, scale, w0, sum3,
square_sum3, ma343, ma444, b343, b444, dst);
src += stride;
dst += stride;
Circulate3PointersBy1<uint16_t>(ma343);
Circulate3PointersBy1<uint32_t>(b343);
std::swap(ma444[0], ma444[1]);
std::swap(b444[0], b444[1]);
}
int y = std::min(height, 2);
src += 2;
do {
Circulate3PointersBy1<uint16_t>(sum3);
Circulate3PointersBy1<uint32_t>(square_sum3);
BoxFilterPass2(src, bottom_border, width, sum_width, scale, w0, sum3,
square_sum3, ma343, ma444, b343, b444, dst);
src += stride;
dst += stride;
bottom_border += bottom_border_stride;
Circulate3PointersBy1<uint16_t>(ma343);
Circulate3PointersBy1<uint32_t>(b343);
std::swap(ma444[0], ma444[1]);
std::swap(b444[0], b444[1]);
} while (--y != 0);
}
// If |width| is non-multiple of 32, up to 31 more pixels are written to |dest|
// in the end of each row. It is safe to overwrite the output as it will not be
// part of the visible frame.
void SelfGuidedFilter_AVX2(
const RestorationUnitInfo& restoration_info, const void* const source,
const ptrdiff_t stride, const void* const top_border,
const ptrdiff_t top_border_stride, const void* const bottom_border,
const ptrdiff_t bottom_border_stride, const int width, const int height,
RestorationBuffer* const restoration_buffer, void* const dest) {
const int index = restoration_info.sgr_proj_info.index;
const int radius_pass_0 = kSgrProjParams[index][0]; // 2 or 0
const int radius_pass_1 = kSgrProjParams[index][2]; // 1 or 0
const auto* const src = static_cast<const uint16_t*>(source);
const auto* const top = static_cast<const uint16_t*>(top_border);
const auto* const bottom = static_cast<const uint16_t*>(bottom_border);
auto* const dst = static_cast<uint16_t*>(dest);
SgrBuffer* const sgr_buffer = &restoration_buffer->sgr_buffer;
if (radius_pass_1 == 0) {
// |radius_pass_0| and |radius_pass_1| cannot both be 0, so we have the
// following assertion.
assert(radius_pass_0 != 0);
BoxFilterProcessPass1(restoration_info, src - 3, stride, top - 3,
top_border_stride, bottom - 3, bottom_border_stride,
width, height, sgr_buffer, dst);
} else if (radius_pass_0 == 0) {
BoxFilterProcessPass2(restoration_info, src - 2, stride, top - 2,
top_border_stride, bottom - 2, bottom_border_stride,
width, height, sgr_buffer, dst);
} else {
BoxFilterProcess(restoration_info, src - 3, stride, top - 3,
top_border_stride, bottom - 3, bottom_border_stride, width,
height, sgr_buffer, dst);
}
}
void Init10bpp() {
Dsp* const dsp = dsp_internal::GetWritableDspTable(kBitdepth10);
assert(dsp != nullptr);
#if DSP_ENABLED_10BPP_AVX2(WienerFilter)
dsp->loop_restorations[0] = WienerFilter_AVX2;
#endif
#if DSP_ENABLED_10BPP_AVX2(SelfGuidedFilter)
dsp->loop_restorations[1] = SelfGuidedFilter_AVX2;
#endif
}
} // namespace
void LoopRestorationInit10bpp_AVX2() { Init10bpp(); }
} // namespace dsp
} // namespace libgav1
#else // !(LIBGAV1_TARGETING_AVX2 && LIBGAV1_MAX_BITDEPTH >= 10)
namespace libgav1 {
namespace dsp {
void LoopRestorationInit10bpp_AVX2() {}
} // namespace dsp
} // namespace libgav1
#endif // LIBGAV1_TARGETING_AVX2 && LIBGAV1_MAX_BITDEPTH >= 10
| 42.025332 | 80 | 0.632335 | P-404 |
b393c0652240bdc03fc3ce5f55bbfff84e879e37 | 3,679 | hpp | C++ | Include/xsim/xsim.hpp | raving-bots/expansim-sdk | 22f5c794523abbe9c27688963b607b13671ff118 | [
"BSL-1.0"
] | 1 | 2020-01-17T14:10:22.000Z | 2020-01-17T14:10:22.000Z | Include/xsim/xsim.hpp | raving-bots/expansim-sdk | 22f5c794523abbe9c27688963b607b13671ff118 | [
"BSL-1.0"
] | null | null | null | Include/xsim/xsim.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 <string>
#include <unordered_map>
#include <tuple>
#include <functional>
#include <yymp/typelist_fwd.hpp>
#include <yymp/for_each.hpp>
#include <xsim/utils.hpp>
#include <xsim/types.hpp>
#include <xsim/logs.hpp>
#if defined(XSIM_PLUGINS_TEST) && __has_include(<xsim/generated/test/abi.hpp>)
# include <xsim/generated/test/abi.hpp>
#else
# include <xsim/generated/abi.hpp>
#endif
namespace xsim
{
template <typename... Interfaces>
struct PluginV1 : Interfaces...
{
using Implements = yymp::typelist<Interfaces...>;
};
struct IPluginWrapper
{
virtual ~IPluginWrapper() = default;
virtual int32_t QueryInterface(const wchar_t* name, void** output, uint64_t* checksum) noexcept = 0;
};
namespace detail
{
template <typename Plugin>
struct PluginWrapper final : IPluginV1, IPluginWrapper
{
explicit PluginWrapper()
{
RegisterWrapper<IPluginV1>();
yymp::for_each(typename Plugin::Implements{}, [&](auto item)
{
(void)item; // only need the type
using Interface = typename decltype(item)::type;
RegisterPlugin<Interface>();
});
}
virtual ~PluginWrapper() = default;
void OnLoad() noexcept override
{
xsim::Protect([&]
{
m_Plugin = std::make_unique<Plugin>();
});
}
void OnUnload() noexcept override
{
xsim::Protect([&]
{
m_Plugin.reset();
});
}
int32_t QueryInterface(const wchar_t* name, void** output, uint64_t* checksum) noexcept override
{
if (auto it = m_Interfaces.find(name); it != m_Interfaces.end())
{
*checksum = it->second.m_Checksum;
*output = it->second.m_GetPointer(m_Plugin.get());
return 1;
}
return 0;
}
private:
struct ImplementedInterface
{
uint64_t m_Checksum{};
std::function<void*(Plugin*)> m_GetPointer{};
ImplementedInterface(uint64_t checksum, std::function<void*(Plugin*)> getPointer)
: m_Checksum(checksum)
, m_GetPointer(std::move(getPointer))
{
}
};
template <typename Interface>
void RegisterPlugin()
{
Register<Interface>([](Plugin* plugin) -> void*
{
return static_cast<Interface*>(plugin);
});
}
template <typename Interface>
void RegisterWrapper()
{
Register<Interface>([=](Plugin*)-> void*
{
return this;
});
}
template <typename Interface>
void Register(std::function<void*(Plugin*)> getPointer)
{
using Traits = InterfaceTraits<Interface>;
auto name = Traits::Name;
auto checksum = Traits::Checksum;
m_Interfaces.emplace(name, ImplementedInterface(checksum, std::move(getPointer)));
}
std::unique_ptr<Plugin> m_Plugin{};
std::unordered_map<std::wstring, ImplementedInterface> m_Interfaces{};
};
XSIM_EXPORT int32_t QueryInterface(const wchar_t* name, void** output, uint64_t* checksum) noexcept;
}
template <typename Plugin>
std::unique_ptr<IPluginWrapper> MakePlugin()
{
static_assert(
std::is_default_constructible<Plugin>::value, "The plugin type must be default-constructible"
);
static_assert(
sizeof(typename Plugin::Implements) != 0, "The plugin type must derive from PluginV1 for the SDK framework to work"
);
return std::unique_ptr<IPluginWrapper>(new detail::PluginWrapper<Plugin>());
}
std::unique_ptr<IPluginWrapper> GetPlugin();
}
| 24.045752 | 119 | 0.650177 | raving-bots |
b394f91427c5e81209e4319d9cd100da0bcf9e78 | 3,053 | hpp | C++ | experimental/vector_implementation/vector.hpp | jamesjallorina/Data_Structures_And_Algorithm_Analysis_in_CPP | 1162eae63ef894419d5e806541129adf73817130 | [
"MIT"
] | 3 | 2019-07-07T17:24:46.000Z | 2020-03-15T23:21:39.000Z | experimental/vector_implementation/vector.hpp | jamesjallorina/Data_Structures_And_Algorithm_Analysis_in_CPP | 1162eae63ef894419d5e806541129adf73817130 | [
"MIT"
] | null | null | null | experimental/vector_implementation/vector.hpp | jamesjallorina/Data_Structures_And_Algorithm_Analysis_in_CPP | 1162eae63ef894419d5e806541129adf73817130 | [
"MIT"
] | null | null | null | #ifndef EXPERIMENTAL_VECTOR_IMPLEMENTATION_VECTOR_HPP
#define EXPERIMENTAL_VECTOR_IMPLEMENTATION_VECTOR_HPP
#include <algorithm>
namespace experimental {
namespace vector_implementation
{
template <typename Object>
class vector
{
public:
explicit vector ( int initSize = 0 ) : theSize{ initSize },
theCapacity{ initSize + SPARE_CAPACITY }
{ objects = new Object[ theCapacity ]; }
vector( const vector & rhs ) : theSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ nullptr }
{
objects = new Object[ theCapacity ];
for( int k = 0; k < theSize; ++k )
objects[ k ] = rhs.objects[ k ];
}
vector & operator= ( const vector & rhs )
{
vector copy = rhs;
std::swap( *this, copy );
return *this;
}
~vector() { delete [] objects; }
vector( vector && rhs ) noexcept : theSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ rhs.objects }
{
rhs.objects = nullptr;
rhs.theSize = 0;
rhs.theCapacity = 0;
}
vector &operator= ( vector && rhs ) noexcept
{
std::swap( theSize, rhs.theSize );
std::swap( theCapacity, rhs.theCapacity);
std::swap( objects, rhs.objects );
return *this;
}
void resize( int newSize )
{
if( newSize > theCapacity )
reserve( newSize * 2 );
theSize = newSize;
}
void reserve( int newCapacity )
{
if( newCapacity < theSize )
return;
Object *newArray = new Object[ newCapacity ];
for(int k = 0; k < theSize; ++k)
newArray[ k ] = std::move( objects[ k ] );
theCapacity = newCapacity;
std::swap( objects, newArray );
delete [] newArray;
}
Object &operator[] ( int index )
{ return objects[ index ]; }
const Object & operator[] ( int index ) const
{ return objects[ index ]; }
bool empty( ) const
{ return size() == 0; }
int size( ) const
{ return theSize; }
int capacity( ) const
{ return theCapacity; }
void push_back( const Object & x )
{
if( theSize == theCapacity )
reserve( 2 * theCapacity + 1 );
objects[ theSize++ ] = x;
}
void push_back( Object && x )
{
if( theSize == theCapacity )
reserve( 2 * theCapacity + 1);
objects[ theSize++ ] = std::move( x );
}
void pop_back( )
{
--theSize;
}
const Object & back ( ) const
{
return objects[ theSize - 1 ];
}
using iterator = Object *;
using const_iterator = const Object *;
iterator begin( )
{ return &objects[ 0 ]; }
const_iterator begin( ) const
{ return &objects[ 0 ]; }
iterator end( )
{ return &objects[ size() ]; }
const_iterator end( ) const
{ return &objects[ size() ]; }
static constexpr short SPARE_CAPACITY = 16;
private:
int theSize;
int theCapacity;
Object * objects;
};
} // namespace vector_implementation
} // namespace experimental
#endif //EXPERIMENTAL_VECTOR_IMPLEMENTATION_VECTOR_HPP
| 22.123188 | 64 | 0.585981 | jamesjallorina |
b395fbb7d4c67e25a8f6a19a3f643bf92223765c | 9,692 | cpp | C++ | DFNs/Registration3D/IcpCC.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | DFNs/Registration3D/IcpCC.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | DFNs/Registration3D/IcpCC.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /**
* @author Alessandro Bianco
*/
/**
* @addtogroup DFNs
* @{
*/
#include "IcpCC.hpp"
#include <Converters/PointCloudToPclPointCloudConverter.hpp>
#include <Macros/YamlcppMacros.hpp>
#include <Errors/Assert.hpp>
#include <pcl/registration/icp.h>
#include <yaml-cpp/yaml.h>
#include <cloudcompare-core/PointCloud.h>
using namespace Converters;
using namespace PointCloudWrapper;
using namespace PoseWrapper;
using namespace CCLib;
namespace CDFF
{
namespace DFN
{
namespace Registration3D
{
IcpCC::IcpCC()
{
parameters = DEFAULT_PARAMETERS;
parametersHelper.AddParameter<ConvergenceType, ConvergenceTypeHelper>("GeneralParameters", "ConvergenceType", parameters.convergenceType, DEFAULT_PARAMETERS.convergenceType);
parametersHelper.AddParameter<double>("GeneralParameters", "MinimumErrorReduction", parameters.minimumErrorReduction, DEFAULT_PARAMETERS.minimumErrorReduction);
parametersHelper.AddParameter<int>("GeneralParameters", "MaximumNumberOfIterations", parameters.maximumNumberOfIterations, DEFAULT_PARAMETERS.maximumNumberOfIterations);
parametersHelper.AddParameter<bool>("GeneralParameters", "ScaleIsAdjustable", parameters.scaleIsAdjustable, DEFAULT_PARAMETERS.scaleIsAdjustable);
parametersHelper.AddParameter<bool>("GeneralParameters", "FarthestPointsAreFilteredOut", parameters.farthestPointsAreFilteredOut, DEFAULT_PARAMETERS.farthestPointsAreFilteredOut);
parametersHelper.AddParameter<int>("GeneralParameters", "SamplingLimit", parameters.samplingLimit, DEFAULT_PARAMETERS.samplingLimit);
parametersHelper.AddParameter<double>("GeneralParameters", "FinalOverlapRatio", parameters.finalOverlapRatio, DEFAULT_PARAMETERS.finalOverlapRatio);
parametersHelper.AddParameter<int>("GeneralParameters", "MaximumNumberOfThreads", parameters.maximumNumberOfThreads, DEFAULT_PARAMETERS.maximumNumberOfThreads);
configurationFilePath = "";
}
IcpCC::~IcpCC()
{
}
void IcpCC::configure()
{
parametersHelper.ReadFile(configurationFilePath);
ValidateParameters();
ConvertParametersToCCParametersList();
}
void IcpCC::process()
{
// Read data from input ports
if (GetNumberOfPoints(inSourceCloud) == 0 || GetNumberOfPoints(inSinkCloud) == 0)
{
outSuccess = false;
return;
}
CCLib::PointCloud *inputSourceCloud = Convert(&inSourceCloud);
CCLib::PointCloud *inputSinkCloud = Convert(&inSinkCloud);
// Process data
ValidateInputs(inputSourceCloud, inputSinkCloud);
ComputeTransform(inputSourceCloud, inputSinkCloud);
// Write data to output ports
// done in ComputeTransform, nothing to do here
// Cleanup
delete inputSourceCloud;
delete inputSinkCloud;
}
IcpCC::ConvergenceTypeHelper::ConvergenceTypeHelper(const std::string& parameterName, ConvergenceType& boundVariable, const ConvergenceType& defaultValue)
: ParameterHelper(parameterName, boundVariable, defaultValue)
{
}
IcpCC::ConvergenceType IcpCC::ConvergenceTypeHelper::Convert(const std::string& outputConvergenceType)
{
if (outputConvergenceType == "ErrorReduction" || outputConvergenceType == "0")
{
return MINIMUM_ERROR_REDUCTION;
}
else if (outputConvergenceType == "NumberOfIterations" || outputConvergenceType == "1")
{
return NUMBER_OF_ITERATIONS;
}
ASSERT(false, "Icp3D Error: unhandled convergence type: it should be either ErrorReduction or NumberOfIterations");
return MINIMUM_ERROR_REDUCTION;
}
const IcpCC::IcpOptionsSet IcpCC::DEFAULT_PARAMETERS =
{
/*.convergenceType =*/ MINIMUM_ERROR_REDUCTION,
/*.minimumErrorReduction =*/ 1e-5,
/*.maximumNumberOfIterations =*/ 20,
/*.scaleIsAdjustable =*/ false,
/*.farthestPointsAreFilteredOut =*/ false,
/*.samplingLimit =*/ 50000,
/*.finalOverlapRatio =*/ 1.0,
/*.maximumNumberOfThreads =*/ 0
};
void IcpCC::ConvertParametersToCCParametersList()
{
if (parameters.convergenceType == MINIMUM_ERROR_REDUCTION)
{
ccParametersList.convType = ICPRegistrationTools::MAX_ERROR_CONVERGENCE;
ccParametersList.minRMSDecrease = parameters.minimumErrorReduction;
}
else
{
ccParametersList.convType = ICPRegistrationTools::MAX_ITER_CONVERGENCE;
ccParametersList.nbMaxIterations = static_cast<unsigned>(parameters.maximumNumberOfIterations);
}
ccParametersList.adjustScale = parameters.scaleIsAdjustable;
ccParametersList.filterOutFarthestPoints = parameters.farthestPointsAreFilteredOut;
ccParametersList.samplingLimit = static_cast<unsigned>(parameters.samplingLimit);
ccParametersList.finalOverlapRatio = parameters.finalOverlapRatio;
ccParametersList.maxThreadCount = static_cast<unsigned>(parameters.maximumNumberOfThreads);
}
CCLib::PointCloud* IcpCC::Convert(PointCloudConstPtr cloud)
{
CCLib::PointCloud* ccCloud = new CCLib::PointCloud();
ccCloud->reserve( GetNumberOfPoints(*cloud) );
for (int pointIndex = 0; pointIndex < GetNumberOfPoints(*cloud); pointIndex++)
{
CCVector3 newPoint( GetXCoordinate(*cloud, pointIndex), GetYCoordinate(*cloud, pointIndex), GetZCoordinate(*cloud, pointIndex) );
ccCloud->addPoint(newPoint);
}
int fieldIndex = ccCloud->addScalarField("RegistrationDistances");
if (fieldIndex ==-1) {
ASSERT(true, "IcpCC error, it was not possible to add RegistrationDistances scalar field. Not enough memory?");
}
else {
ccCloud->setCurrentScalarField(fieldIndex);
}
return ccCloud;
}
// The required initial estimate/guess/output is the position of the source
// cloud's frame in the frame of the sink cloud. It is the inverse of the
// geometric transformation that brings the source cloud in the sink cloud.
RegistrationTools::ScaledTransformation IcpCC::ConvertTrasformToCCTransform(const Pose3D& transform)
{
RegistrationTools::ScaledTransformation ccTransform;
ccTransform.T.x = -GetXPosition(transform);
ccTransform.T.y = -GetYPosition(transform);
ccTransform.T.z = -GetZPosition(transform);
ccTransform.s = 1.0;
// We need this representation of the quaternion in order to use
// the method from CC that converts to a rotation matrix
double quaternion[4];
quaternion[0] = GetWOrientation(transform);
quaternion[1] = GetXOrientation(transform);
quaternion[2] = GetYOrientation(transform);
quaternion[3] = GetZOrientation(transform);
// Normalization, required for computing the rotation matrix
double norm = std::sqrt( quaternion[0]*quaternion[0] + quaternion[1]*quaternion[1] + quaternion[2]*quaternion[2] + quaternion[3]*quaternion[3]);
quaternion[0] = quaternion[0] / norm;
quaternion[1] = quaternion[1] / norm;
quaternion[2] = quaternion[2] / norm;
quaternion[3] = quaternion[3] / norm;
SquareMatrix rotationMatrix(3);
rotationMatrix.initFromQuaternion(quaternion);
ccTransform.R = rotationMatrix.inv();
return ccTransform;
}
Pose3D IcpCC::ConvertCCTransformToTranform(const RegistrationTools::ScaledTransformation& ccTransform)
{
ASSERT(ccTransform.s >= 0.99999 && ccTransform.s <= 1.00001, "IcpCC error, ccTransform does not have expected scale of 1");
Pose3D transform;
SetPosition(transform, -ccTransform.T.x, -ccTransform.T.y, -ccTransform.T.z);
// We need a non-cost matrix to call the toQuatenion method. (It is not expected indeed.)
SquareMatrix rotationMatrixCopy = ccTransform.R.inv();
double quaternion[4];
bool success = rotationMatrixCopy.toQuaternion(quaternion);
ASSERT(success, "IcpCC error, could not convert ccTransform rotation matrix to Transform quaternion");
SetOrientation(transform, quaternion[1], quaternion[2], quaternion[3], quaternion[0]);
return transform;
}
void IcpCC::ComputeTransform(CCLib::PointCloud* sourceCloud, CCLib::PointCloud* sinkCloud)
{
RegistrationTools::ScaledTransformation scaledTransform;
if (inUseGuess)
{
scaledTransform = ConvertTrasformToCCTransform(inTransformGuess);
}
else
{
scaledTransform.R = SquareMatrix(3);
scaledTransform.R.toIdentity();
scaledTransform.T.x = 0;
scaledTransform.T.y = 0;
scaledTransform.T.z = 0;
scaledTransform.s = 1.0;
}
double finalRMS;
unsigned finalPointCount;
ICPRegistrationTools::RESULT_TYPE result = ICPRegistrationTools::Register(sourceCloud, nullptr, sinkCloud, ccParametersList, scaledTransform, finalRMS, finalPointCount);
if (result == ICPRegistrationTools::ICP_APPLY_TRANSFO || result == ICPRegistrationTools::ICP_NOTHING_TO_DO)
{
outTransform = ConvertCCTransformToTranform(scaledTransform);
outSuccess = true;
}
else
{
outSuccess = false;
}
}
void IcpCC::ValidateParameters()
{
ASSERT(parameters.minimumErrorReduction > 0 || parameters.convergenceType != MINIMUM_ERROR_REDUCTION, "IcpCC Configuration error, Minimum Error Reduction has to be positive");
ASSERT(parameters.maximumNumberOfIterations > 0 || parameters.convergenceType != NUMBER_OF_ITERATIONS, "IcpCC Configuration error, Maximum number of iterations has to be positive");
ASSERT(parameters.samplingLimit > 0, "IcpCC Configuration error, Sampling limit has to be positive");
ASSERT(parameters.finalOverlapRatio >= 0 && parameters.finalOverlapRatio <= 1, "IcpCC Configuration error, finalOverlapRatio has to be between 0 and 1");
ASSERT(parameters.maximumNumberOfThreads >= 0, "IcpCC Configuration Error, maximumNumberOfThreads has to be greater or equal to zero");
}
void IcpCC::ValidateInputs(CCLib::PointCloud* sourceCloud, CCLib::PointCloud* sinkCloud)
{
ValidateCloud(sourceCloud);
ValidateCloud(sinkCloud);
}
void IcpCC::ValidateCloud(CCLib::PointCloud* cloud)
{
for (unsigned pointIndex = 0; pointIndex < cloud->size(); pointIndex++)
{
const CCVector3* point = cloud->getPoint(pointIndex);
ASSERT_EQUAL(point->x, point->x, "IcpCC Error, Cloud contains an NaN point");
ASSERT_EQUAL(point->y, point->y, "IcpCC Error, Cloud contains an NaN point");
ASSERT_EQUAL(point->z, point->z, "IcpCC Error, Cloud contains an NaN point");
}
}
}
}
}
/** @} */
| 36.02974 | 182 | 0.78343 | H2020-InFuse |
b397aaa9154a2bd8607974b463d6a39b7ad4a395 | 52 | hpp | C++ | include/tools/miniz.hpp | turgu1/ESP-IDF-Inkplate | 35840f1cbc73a155bbdd902ea78b78baa2257214 | [
"BSD-2-Clause"
] | 5 | 2021-02-10T15:01:14.000Z | 2022-03-08T00:43:43.000Z | include/tools/miniz.hpp | turgu1/ESP-IDF-Inkplate | 35840f1cbc73a155bbdd902ea78b78baa2257214 | [
"BSD-2-Clause"
] | 6 | 2021-03-02T16:36:38.000Z | 2022-01-14T19:40:53.000Z | include/tools/miniz.hpp | turgu1/ESP-IDF-Inkplate | 35840f1cbc73a155bbdd902ea78b78baa2257214 | [
"BSD-2-Clause"
] | 3 | 2021-01-28T08:04:13.000Z | 2021-08-12T23:33:33.000Z | #define MINIZ_HEADER_FILE_ONLY
#include "miniz.cpp"
| 17.333333 | 30 | 0.826923 | turgu1 |
b3a725bbdf3f0fa6de92e4559ce92656326f8842 | 1,039 | cpp | C++ | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program16.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | 1 | 2020-12-03T15:26:20.000Z | 2020-12-03T15:26:20.000Z | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program16.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program16.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | // Chapter 4: Program 16
/***
Write a C++ program to read two numbers. Perform AND operation and O
operations on two numbers. Perform NOT operation on first number. Declare AND,
OR, and NOT varables type of short int.
**/
# include <iostream>
# include <math.h>
# include <string>
using namespace std;
int main(void)
{
short int First_Number, Second_Number;
bool AND, OR, NOT;
cout << "\n\t Please enter first number \n";
cin >> First_Number;
cout << "\n\t Please enter second number \n";
cin >> Second_Number;
// Perform AND, OR NOT operations
(First_Number && Second_Number) ? AND = true : AND = false;
(First_Number || Second_Number) ? OR = true : OR = false;
(First_Number) ? NOT = false : NOT = true;
cout << "\t AND operation of two numbers is " << AND << endl;
cout << "\t OR operation of two numbers is " << OR << endl;
cout << "\t NOT operation of first numbers is " << NOT << endl;
system("pause");
return 0;
}
// Code written by: Othneil Drew
| 27.342105 | 78 | 0.628489 | othneildrew |
b3ac2f9b3e5db409e3f5a69f12140ca1e3bd9c92 | 679 | hpp | C++ | code/src/utility/profiling.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 3 | 2020-04-29T14:55:58.000Z | 2020-08-20T08:43:24.000Z | code/src/utility/profiling.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 1 | 2022-03-12T11:37:46.000Z | 2022-03-12T20:17:38.000Z | code/src/utility/profiling.hpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | null | null | null | #pragma once
#if PROFILING_COZ
# include <coz.h>
#endif
namespace utility
{
namespace detail
{
#if PROFILING_COZ
struct CallWhenDestroyed
{
void (* func)();
~CallWhenDestroyed()
{
func();
}
explicit CallWhenDestroyed(void (* func)())
: func(func)
{}
};
#endif
}
}
#if PROFILING_COZ
# define profile_begin(name) do {} while(0)
# define profile_end(name) COZ_PROGRESS_NAMED(name)
# define profile_scope(name) utility::detail::CallWhenDestroyed _profile_scope_([](){ COZ_PROGRESS_NAMED(name); });
#else
# define profile_begin(name) do {} while(0)
# define profile_end(name) do {} while(0)
# define profile_scope(name) do {} while(0)
#endif
| 16.975 | 115 | 0.683358 | shossjer |
b3aca3444df7f5d0b8d4bcd29d666b52a6bc78c7 | 3,494 | cc | C++ | src/client/main.cc | sensssz/SQPKV | 828f2afec14db104f090ae2b4ed4729b97d3d9b6 | [
"Apache-2.0"
] | 1 | 2020-06-15T10:35:20.000Z | 2020-06-15T10:35:20.000Z | src/client/main.cc | sensssz/SQPKV | 828f2afec14db104f090ae2b4ed4729b97d3d9b6 | [
"Apache-2.0"
] | null | null | null | src/client/main.cc | sensssz/SQPKV | 828f2afec14db104f090ae2b4ed4729b97d3d9b6 | [
"Apache-2.0"
] | null | null | null | #include "sqpkv/connection.h"
#include "gflags/gflags.h"
#include "spdlog/spdlog.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdio>
DEFINE_string(server_addr, "127.0.0.1", "Address of the server");
DEFINE_int32(port, 4242, "Port number of the server");
void Show(std::string message) {
std::cout << message << std::endl;
std::cout << "> ";
}
void ShowStatus(sqpkv::Status &status) {
if (status.err()) {
Show(status.message());
} else if (status.eof()) {
std::cout << "Server is lost, exiting..." << std::endl;
exit(EXIT_FAILURE);
} else {
std::cout << "> ";
}
}
void ShowList(std::vector<std::string> list) {
size_t max_len = 0;
for (auto &item : list) {
if (item.length() > max_len) {
max_len = item.length();
}
}
max_len += 2;
std::stringstream ss;
for (size_t i = 0; i < max_len; i++) {
ss << "─";
}
auto hline = ss.str();
std::cout << "┌" << hline << "┐" << std::endl;
if (list.size() > 0) {
std::string &item = list[0];
int lpad = static_cast<int>((max_len - item.length()) / 2);
int rpad = static_cast<int>(max_len - lpad - item.length() - 1);
printf("│ %*s%*s │\n", lpad, item.c_str(), rpad, "");
}
for (size_t i = 1; i < list.size(); i++) {
auto &item = list[i];
std::cout << "├" << hline << "┤" << std::endl;
int lpad = static_cast<int>((max_len - item.length()) / 2);
int rpad = static_cast<int>(max_len - lpad - item.length() - 1);
printf("│ %*s%*s │\n", lpad, item.c_str(), rpad, "");
}
std::cout << "└" << hline << "┘" << std::endl;
std::cout << "> ";
}
// You could also take an existing vector as a parameter.
std::vector<std::string> split(std::string str, char delimiter) {
std::vector<std::string> internal;
std::stringstream ss(str); // Turn the string into a stream.
std::string tok;
while(std::getline(ss, tok, delimiter)) {
internal.push_back(tok);
}
return internal;
}
int main(int argc, char *argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
spdlog::set_pattern("[%H:%M:%S] %v");
spdlog::set_level(spdlog::level::debug);
auto console = spdlog::stdout_color_mt("console");
auto connection = sqpkv::Connection::ConnectTo(FLAGS_server_addr, FLAGS_port);
if (connection.err()) {
spdlog::get("console")->error(connection.status().ToString());
return 1;
}
Show("Welcome to SQPKV");
bool quit = false;
std::string line;
while (!quit) {
std::getline(std::cin, line);
if (line.find("get all ") == 0) {
auto parts = split(line, ' ');
std::vector<std::string> keys;
auto status = connection->GetAll(parts[2], keys);
if (status.ok()) {
ShowList(keys);
} else {
ShowStatus(status);
}
} else if (line.find("get ") == 0) {
auto parts = split(line, ' ');
std::string value;
auto status = connection->Get(parts[1], value);
if (status.ok()) {
Show(value);
} else {
ShowStatus(status);
}
} else if (line.find("put ") == 0) {
auto parts = split(line, ' ');
auto status = connection->Put(parts[1], parts[2]);
ShowStatus(status);
} else if (line.find("delete ") == 0) {
auto parts = split(line, ' ');
auto status = connection->Delete(parts[1]);
ShowStatus(status);
} else if (line.find("quit") == 0) {
quit = true;
} else {
Show("Unsupported syntax");
}
}
return 0;
}
| 27.296875 | 80 | 0.571551 | sensssz |
b3ad496d60706b021245241f40308af7a2dde686 | 773 | cpp | C++ | 2DProject2ndYear/RigidBody.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | 2DProject2ndYear/RigidBody.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | 2DProject2ndYear/RigidBody.cpp | ryan0432/AIE_PhysicsBS | 0ed7181b2e0624174e28dfa7b2035f8f1e597198 | [
"MIT"
] | null | null | null | #include "Rigidbody.h"
#include <iostream>
Rigidbody::Rigidbody(ShapeType shapeID, glm::vec2 position, glm::vec2 velocity,
float rotation, float mass) : PhysicsObject(shapeID)
{
m_position = position;
m_velocity = velocity;
m_mass = mass;
m_rotation = rotation;
}
void Rigidbody::fixedUpdate(glm::vec2 gravity, float timeStep)
{
addForce(gravity * m_mass * timeStep);
m_position += m_velocity * timeStep;
}
void Rigidbody::debug()
{
}
void Rigidbody::addForce(glm::vec2 force)
{
glm::vec2 acc;
acc = force / m_mass; //[F = m * a] Therefore [a = F / m]
m_velocity += acc;
}
void Rigidbody::addForceToActor(Rigidbody* actor, glm::vec2 force)
{
//add force to the other object
actor->addForce(force);
//add negative force to self object
addForce(-force);
}
| 20.891892 | 79 | 0.711514 | ryan0432 |
a2a8849c07fcadb5b1dda577dfc2643c3fec2f07 | 4,398 | cpp | C++ | src/Leviathan_Editor/Leviathan_Editor.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/Leviathan_Editor/Leviathan_Editor.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/Leviathan_Editor/Leviathan_Editor.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include "Leviathan_Editor.h"
#include <thread>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QSplitter>
#include <QSizePolicy>
#include "LevScene.h"
#include "LevAttributeWidget.h"
Leviathan_Editor::Leviathan_Editor(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
bool seted = _setupWidget();
LEV_ASSERT(seted);
m_timer.reset(new QTimer);
m_timer->setInterval(100);
connect(m_openGL_widget.data(), SIGNAL(resized()), this, SLOT(SLOT_RESIZE()));
connect(m_timer.data(), SIGNAL(timeout()), this, SLOT(SLOT_UPDATE()));
m_timer->start();
}
void Leviathan_Editor::SLOT_RESIZE()
{
if (!m_leviathan_proxy || !m_leviathan_proxy->HasInited())
{
return;
}
unsigned handle = m_leviathan_proxy->GetWindowHandle();
unsigned width = m_openGL_widget->width();
unsigned height = m_openGL_widget->height();
MoveWindow((HWND)handle, 0, 0, width, height, true);
}
void Leviathan_Editor::resizeEvent(QResizeEvent *event)
{
static bool _first = true;
if (_first)
{
_widget_initialized();
_first = false;
}
}
void Leviathan_Editor::closeEvent(QCloseEvent * event)
{
m_leviathan_proxy->Stop();
while (!m_leviathan_proxy->HasStoped())
{
Sleep(100);
}
QMainWindow::closeEvent(event);
}
void Leviathan_Editor::SLOT_UPDATE()
{
static bool _proxy_inited = false;
if (!_proxy_inited && m_leviathan_proxy && m_leviathan_proxy->HasInited())
{
_leviathan_initialized();
_proxy_inited = true;
return;
}
if (_proxy_inited)
{
m_runtime_object_view->Update();
}
}
void Leviathan_Editor::_widget_initialized()
{
_attachRenderer();
}
void Leviathan_Editor::_leviathan_initialized()
{
SLOT_RESIZE();
auto _scene_modified_callback = [this]()
{
_update_runtime_scene_object();
};
m_leviathan_proxy->UpdateSceneData([this, _scene_modified_callback](Scene::LevScene& scene)
{
scene.RegisterModifiedCallback(_scene_modified_callback);
});
_update_runtime_scene_object();
}
void Leviathan_Editor::_update_runtime_scene_object()
{
m_leviathan_proxy->UpdateSceneData([this](Scene::LevScene& scene)
{
m_runtime_object_view->SetSceneData(scene.GetSceneData());
});
}
void Leviathan_Editor::_attachRenderer()
{
unsigned width = m_openGL_widget->width();
unsigned height = m_openGL_widget->height();
unsigned handle = m_openGL_widget->winId();
std::thread _lev_render_thread([this, width, height, handle]()
{
m_leviathan_proxy.Reset(new LeviathanProxy);
m_leviathan_proxy->Init(width, height, handle);
while (!m_leviathan_proxy->HasStoped())
{
m_leviathan_proxy->Update();
}
LogLine("[DEBUG] Exit leviathan proxy.");
});
_lev_render_thread.detach();
}
bool Leviathan_Editor::_setupWidget()
{
EXIT_IF_FALSE(_setupResourceListView());
EXIT_IF_FALSE(_setupSceneRuntimeObjectView());
EXIT_IF_FALSE(_setupAttributePanelView());
m_openGL_widget.reset(new QOpenGLWidget);
m_main_splitter.reset(new QSplitter(Qt::Horizontal, ui.centralWidget));
m_middle_splitter.reset(new QSplitter(Qt::Vertical));
m_middle_splitter->addWidget(m_openGL_widget.data());
m_middle_splitter->addWidget(m_resource_view.data());
m_middle_splitter->setStretchFactor(0, 5);
m_middle_splitter->setStretchFactor(1, 1);
m_main_splitter->addWidget(m_runtime_object_view.data());
m_main_splitter->addWidget(m_middle_splitter.data());
m_main_splitter->addWidget(m_attribute_view.data());
m_main_splitter->setStretchFactor(0, 1);
m_main_splitter->setStretchFactor(1, 5);
m_main_splitter->setStretchFactor(2, 1);
ui.centralWidget->setLayout(new QGridLayout);
ui.centralWidget->layout()->addWidget(m_main_splitter.data());
return true;
}
bool Leviathan_Editor::_setupResourceListView()
{
m_resource_view.reset(new LevResourcesListView);
// For test
auto command_args = QApplication::arguments();
if (command_args.size() > 1)
{
auto& resource_folder_path = command_args[1];
// TODO: the way getting raw char pointer too stupid
EXIT_IF_FALSE(m_resource_view->SetResourcesFolderPath(resource_folder_path.toStdString().c_str()));
EXIT_IF_FALSE(m_resource_view->InitItemsFormNode(m_resource_view->GetRootNode()));
}
return true;
}
bool Leviathan_Editor::_setupSceneRuntimeObjectView()
{
m_runtime_object_view.reset(new LevSceneObjectTreeView);
return true;
}
bool Leviathan_Editor::_setupAttributePanelView()
{
m_attribute_view.reset(new LevAttributeWidget);
return true;
}
| 22.553846 | 101 | 0.75648 | wakare |
a2a8db066a24c9703388246c07a9656f7ca23c20 | 3,544 | cpp | C++ | nmpc_controller/test/test_nmpc_controller.cpp | robomechanics/quad-software | 89154df18e98162249f38301b669df27ee595220 | [
"MIT"
] | 20 | 2021-12-05T03:40:28.000Z | 2022-03-30T02:53:56.000Z | nmpc_controller/test/test_nmpc_controller.cpp | robomechanics/rml-spirit-firmware | 89154df18e98162249f38301b669df27ee595220 | [
"MIT"
] | 45 | 2021-12-06T12:45:05.000Z | 2022-03-31T22:15:47.000Z | nmpc_controller/test/test_nmpc_controller.cpp | robomechanics/rml-spirit-firmware | 89154df18e98162249f38301b669df27ee595220 | [
"MIT"
] | 2 | 2021-12-06T03:20:15.000Z | 2022-02-20T04:19:41.000Z | #include <gtest/gtest.h>
#include <ros/ros.h>
#include <chrono>
#include "nmpc_controller/nmpc_controller.h"
TEST(NMPCTest, testNMPCController) {
ros::NodeHandle nh;
const int robot_id_ = 0;
int N_;
double dt_;
ros::param::get("/local_planner/horizon_length", N_);
ros::param::get("/local_planner/timestep", dt_);
std::shared_ptr<NMPCController> leg_planner_ =
std::make_shared<NMPCController>(nh, robot_id_);
Eigen::MatrixXd ref_body_plan_(N_, 12);
ref_body_plan_.fill(0);
ref_body_plan_.col(2).fill(0.3);
Eigen::MatrixXd foot_positions_body_(N_, 12);
Eigen::MatrixXd foot_positions_world_(N_, 12);
Eigen::MatrixXd foot_velocities_world_(N_, 12);
foot_velocities_world_.setZero();
for (size_t i = 0; i < N_; i++) {
foot_positions_body_.row(i) << 0.2263, 0.098, -0.3, 0.2263, -0.098, -0.3,
-0.2263, 0.098, -0.3, -0.2263, -0.098, -0.3;
foot_positions_world_.row(i) << 0.2263, 0.098, 0, -0.2263, 0.098, 0, 0.2263,
-0.098, 0, -0.2263, -0.098, 0;
}
// Load the current state
Eigen::VectorXd current_state_(12);
current_state_.fill(0);
current_state_(2) = 0.2;
current_state_(9) = 0;
std::vector<std::vector<bool>> adpative_contact_schedule_;
adpative_contact_schedule_.resize(N_);
for (size_t i = 0; i < N_; i++) {
adpative_contact_schedule_.at(i).resize(4);
if (i % 12 < 6) {
adpative_contact_schedule_.at(i) = {true, false, false, true};
} else {
adpative_contact_schedule_.at(i) = {false, true, true, false};
}
}
Eigen::VectorXd ref_ground_height(N_);
ref_ground_height.fill(0);
Eigen::MatrixXd body_plan_(N_, 12);
body_plan_.col(2).fill(0.3);
Eigen::MatrixXd grf_plan_(N_ - 1, 12);
grf_plan_.fill(0);
grf_plan_.col(2).fill(13.3 * 9.81 / 2);
grf_plan_.col(5).fill(13.3 * 9.81 / 2);
grf_plan_.col(8).fill(13.3 * 9.81 / 2);
grf_plan_.col(11).fill(13.3 * 9.81 / 2);
double first_element_duration = dt_;
bool same_plan_index = false;
std::chrono::steady_clock::time_point tic, toc;
tic = std::chrono::steady_clock::now();
Eigen::VectorXd joint_positions(12), joint_velocities(12), torques(12);
grid_map::GridMap map({"z_inpainted", "traversability"});
map.setGeometry(grid_map::Length(10, 10), 0.01);
for (grid_map::GridMapIterator it(map); !it.isPastEnd(); ++it) {
grid_map::Position position;
map.getPosition(*it, position);
map.at("z_inpainted", *it) = 0;
map.at("traversability", *it) = 1;
}
for (int i = 0; i < 10; i++) {
tic = std::chrono::steady_clock::now();
leg_planner_->computeLegPlan(
current_state_, ref_body_plan_, foot_positions_body_,
foot_positions_world_, foot_velocities_world_,
adpative_contact_schedule_, ref_ground_height, first_element_duration,
same_plan_index, map, body_plan_, grf_plan_);
toc = std::chrono::steady_clock::now();
std::cout << "Time difference = "
<< std::chrono::duration_cast<std::chrono::microseconds>(toc -
tic)
.count()
<< "[µs]" << std::endl;
current_state_ = body_plan_.block(1, 0, 1, 12).transpose();
std::rotate(adpative_contact_schedule_.begin(),
adpative_contact_schedule_.begin() + 1,
adpative_contact_schedule_.end());
}
EXPECT_TRUE(true);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "nmpc_controller_tester");
return RUN_ALL_TESTS();
}
| 31.087719 | 80 | 0.642212 | robomechanics |
a2ab09cce7e03cbb35a3257ee378bde0b4543c79 | 3,107 | cpp | C++ | Effects/Tools/CVarActivationSystem.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Effects/Tools/CVarActivationSystem.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Effects/Tools/CVarActivationSystem.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
// Simple data driven system to activate cvars.
// Includes
#include "StdAfx.h"
#include "CVarActivationSystem.h"
#include "IItemSystem.h"
#include "Effects/GameEffectsSystem.h"
//--------------------------------------------------------------------------------------------------
// Name: Initialise
// Desc: Initialises cvar activation system from data
// Uses the xml node name for the cvar, and activeValue attribute
// eg <cl_fov activeValue="85"/>
//--------------------------------------------------------------------------------------------------
void CCVarActivationSystem::Initialise(const IItemParamsNode* cvarListXmlNode)
{
if(cvarListXmlNode)
{
const IItemParamsNode* cvarXmlNode = NULL;
SCVarParam* param = NULL;
int cvarCount = cvarListXmlNode->GetChildCount();
m_cvarParam.resize(cvarCount);
for(int i=0; i<cvarCount; i++)
{
param = &m_cvarParam[i];
cvarXmlNode = cvarListXmlNode->GetChild(i);
param->cvar = gEnv->pConsole->GetCVar(cvarXmlNode->GetName());
FX_ASSERT_MESSAGE(param->cvar,"Failed to find a CVAR for a game effect");
cvarXmlNode->GetAttribute("activeValue",param->activeValue);
param->originalValue = 0.0f;
}
}
}//-------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// Name: Release
// Desc: Releases data used for CVar activation system
//--------------------------------------------------------------------------------------------------
void CCVarActivationSystem::Release()
{
m_cvarParam.Free();
}//-------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// Name: StoreCurrentValues
// Desc: Stores current values of CVars
//--------------------------------------------------------------------------------------------------
void CCVarActivationSystem::StoreCurrentValues()
{
SCVarParam* param = NULL;
for(uint32 i=0; i<m_cvarParam.Size(); i++)
{
param = &m_cvarParam[i];
if(param->cvar)
{
param->originalValue = param->cvar->GetFVal();
}
}
}//-------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// Name: SetCVarsActive
// Desc: Sets active status of cvars
//--------------------------------------------------------------------------------------------------
void CCVarActivationSystem::SetCVarsActive(bool isActive)
{
SCVarParam* param = NULL;
float value = 0.0f;
for(uint32 i=0; i<m_cvarParam.Size(); i++)
{
param = &m_cvarParam[i];
if(param->cvar)
{
if(isActive)
{
param->cvar->Set(param->activeValue);
}
else
{
param->cvar->Set(param->originalValue);
}
}
}
}//-------------------------------------------------------------------------------------------------
| 34.910112 | 100 | 0.429675 | IvarJonsson |
a2aea435a00c9958982569042c2b3a366c8dec1e | 36,981 | hh | C++ | cc/json-importer.hh | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | cc/json-importer.hh | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | cc/json-importer.hh | acorg/acmacs-base | a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049 | [
"MIT"
] | null | null | null | #pragma once
#error Obsolete, use rjson
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <typeinfo>
#include <functional>
#include <iostream>
#include <memory>
#include "acmacs-base/rapidjson.hh"
// ----------------------------------------------------------------------
namespace json_importer
{
class EventHandler;
namespace storers {
class Base
{
public:
virtual ~Base() {}
virtual Base* StartObject();
virtual Base* EndObject();
virtual Base* StartArray();
virtual Base* EndArray();
virtual Base* Key(const char* str, rapidjson::SizeType length);
virtual Base* String(const char* str, rapidjson::SizeType length);
virtual Base* Int(int i);
virtual Base* Uint(unsigned u);
virtual Base* Double(double d);
virtual Base* Bool(bool b);
virtual Base* Null();
virtual Base* Int64(int64_t i);
virtual Base* Uint64(uint64_t u);
}; // class Base
namespace _i {
class Msg : public Base
{
public:
enum Tag { Failure, Pop, Pop2 };
static Msg sMsg;
void failure(std::string aMessage) { mTag = Failure; mMessage = aMessage; }
void pop() { mTag = Pop; }
void pop2() { mTag = Pop2; }
void report() const { if (mTag == Failure && !mMessage.empty()) std::cerr << "ERROR: " << mMessage << std::endl; }
bool is_failure() const { return mTag == Failure; }
bool is_pop() const { return mTag == Pop; }
bool is_pop2() const { return mTag == Pop2; }
private:
Msg() : mTag(Failure) {}
Tag mTag;
std::string mMessage;
};
class Failure : public std::runtime_error { public: using std::runtime_error::runtime_error; Failure() : std::runtime_error{""} {} };
class Pop : public std::exception { public: using std::exception::exception; };
class Pop2 : public std::exception { public: using std::exception::exception; };
inline Msg* failure(std::string aMessage) { throw Failure(aMessage); }
inline Msg* pop() { throw Pop(); }
inline Msg* pop2() { throw Pop2(); }
} // namespace _i
inline Base* Base::StartObject() { return _i::failure(typeid(*this).name() + std::string("::StartObject")); }
inline Base* Base::EndObject() { return _i::failure(typeid(*this).name() + std::string("::EndObject")); } // { throw Pop(); }
inline Base* Base::StartArray() { return _i::failure(typeid(*this).name() + std::string("::StartArray")); }
inline Base* Base::EndArray() { return _i::failure(typeid(*this).name() + std::string("::EndArray")); } // { throw Pop(); }
inline Base* Base::Key(const char* str, rapidjson::SizeType length) { return _i::failure(typeid(*this).name() + std::string("::Key \"") + std::string(str, length) + "\""); }
inline Base* Base::String(const char* str, rapidjson::SizeType length) { return _i::failure(typeid(*this).name() + std::string("::String \"") + std::string(str, length) + "\""); }
inline Base* Base::Int(int i) { return _i::failure(typeid(*this).name() + std::string("::Int ") + std::to_string(i)); }
inline Base* Base::Uint(unsigned u) { return _i::failure(typeid(*this).name() + std::string("::Uint ") + std::to_string(u)); }
inline Base* Base::Double(double d) { return _i::failure(typeid(*this).name() + std::string("::Double ") + std::to_string(d)); }
inline Base* Base::Bool(bool b) { return _i::failure(typeid(*this).name() + std::string("::Bool ") + std::to_string(b)); }
inline Base* Base::Null() { return _i::failure(typeid(*this).name() + std::string("::Null")); }
inline Base* Base::Int64(int64_t i) { return _i::failure(typeid(*this).name() + std::string("::Int64 ") + std::to_string(i)); }
inline Base* Base::Uint64(uint64_t u) { return _i::failure(typeid(*this).name() + std::string("::Uint64 ") + std::to_string(u)); }
template <typename F> class Storer : public Base
{
public:
Storer(F aStorage) : mStorage(aStorage) {}
protected:
virtual Base* pop() { return nullptr; }
template <typename ...Args> Base* store(Args... args) { mStorage(args...); return pop(); }
F& storage() { return mStorage; }
private:
F mStorage;
};
template <typename F> class StringLength : public Storer<F>
{
public:
using Storer<F>::Storer;
virtual Base* String(const char* str, rapidjson::SizeType length) { return this->store(str, length); }
};
template <typename F> class Double_ : public Storer<F>
{
public:
using Storer<F>::Storer;
virtual Base* Double(double d) { return this->store(d); }
virtual Base* Int(int i) { return this->store(static_cast<double>(i)); }
virtual Base* Uint(unsigned u) { return this->store(static_cast<double>(u)); }
};
template <typename F> class Unsigned_ : public Storer<F>
{
public:
using Storer<F>::Storer;
virtual Base* Uint(unsigned u) { return this->store(u); }
virtual Base* Int(int i) { if (i == -1) return this->store(static_cast<unsigned>(i)); else return Storer<F>::Int(i); } // to read -1 for some size_t fields
};
template <typename F> class Int_ : public Storer<F>
{
public:
using Storer<F>::Storer;
virtual Base* Int(int i) { return this->store(i); }
virtual Base* Uint(unsigned u) { return Int(static_cast<int>(u)); }
};
template <typename F> class Bool_ : public Storer<F>
{
public:
using Storer<F>::Storer;
virtual Base* Bool(bool b) { return this->store(b); }
// virtual Base* Int(int i) { return Bool(i != 0); }
virtual Base* Uint(unsigned u) { return Bool(u != 0); }
};
// ----------------------------------------------------------------------
// Type detector functions
// They are never called but used by field(std::vector<Field>& (Parent::*accessor)()) and reader(void(T::*setter)(V), T& target) functions below to infer of the storer's type
// ----------------------------------------------------------------------
template <typename F> inline Unsigned_<F> type_detector(size_t) { throw std::exception{}; }
template <typename F> inline Unsigned_<F> type_detector(unsigned) { throw std::exception{}; }
template <typename F> inline Int_<F> type_detector(int) { throw std::exception{}; }
template <typename F> inline Double_<F> type_detector(double) { throw std::exception{}; }
template <typename F> inline Bool_<F> type_detector(bool) { throw std::exception{}; }
template <typename F> inline StringLength<F> type_detector(std::string) { throw std::exception{}; }
// ----------------------------------------------------------------------
// to be used as template parameter F for the above to store Array values
// ----------------------------------------------------------------------
template <typename Target> class ArrayElement
{
public:
ArrayElement(std::vector<Target>& aTarget) : mTarget(aTarget) {}
// void operator()(Target aValue) { mTarget.emplace_back(aValue); }
// void operator()(const char* str, size_t length) { mTarget.emplace_back(str, length); }
template <typename ...Args> void operator()(Args ...args) { mTarget.emplace_back(args...); }
private:
std::vector<Target>& mTarget;
};
template <typename Target> class ArrayOfArrayElementTarget
{
public:
ArrayOfArrayElementTarget(Target& aTarget) : mTarget(aTarget) {}
// void operator()(Target aValue) { mTarget.back().emplace_back(aValue); }
template <typename ...Args> void operator()(Args ...args) { mTarget.back().emplace_back(args...); }
size_t size() const { return mTarget.size(); }
void clear() { mTarget.clear(); }
void new_nested() { mTarget.emplace_back(); }
private:
Target& mTarget;
};
template <typename Target> using ArrayOfArrayElement = ArrayOfArrayElementTarget<std::vector<std::vector<Target>>>;
// ----------------------------------------------------------------------
// storer ignoring value
// ----------------------------------------------------------------------
class Ignore : public Base
{
public:
Ignore() : mNesting(0) {}
Base* pop() { if (mNesting == 0) return _i::pop(); else return nullptr; }
Base* decr() { --mNesting; return pop(); }
virtual Base* StartObject() { ++mNesting; return nullptr; }
virtual Base* EndObject() { return decr(); }
virtual Base* StartArray() { ++mNesting; return nullptr; }
virtual Base* EndArray() { return decr(); }
virtual Base* Key(const char*, rapidjson::SizeType) { return nullptr; }
virtual Base* String(const char*, rapidjson::SizeType) { return pop(); }
virtual Base* Int(int) { return pop(); }
virtual Base* Uint(unsigned) { return pop(); }
virtual Base* Double(double) { return pop(); }
virtual Base* Bool(bool) { return pop(); }
virtual Base* Null() { return pop(); }
virtual Base* Int64(int64_t) { return pop(); }
virtual Base* Uint64(uint64_t) { return pop(); }
private:
size_t mNesting;
};
} // namespace storers
// ----------------------------------------------------------------------
namespace readers {
using Base = storers::Base;
// ----------------------------------------------------------------------
// reader: Object
// ----------------------------------------------------------------------
template <typename Target> class Object : public Base
{
public:
Object(Target aTarget, bool aStarted = false) : mTarget(aTarget), mStarted(aStarted) {}
virtual Base* Key(const char* str, rapidjson::SizeType length)
{
if (!mStarted)
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected Key event"));
Base* r = match_key(str, length);
if (!r) {
if (length > 0 && (str[0] == '?' || str[length - 1] == '?'))
r = new storers::Ignore{}; // support for keys starting or ending with ? and "_"
else
r = Base::Key(str, length);
}
// else
// std::cerr << "readers::Object " << std::string(str, length) << " -> PUSH " << typeid(*r).name() << std::endl;
return r;
}
virtual Base* StartObject()
{
if (mStarted)
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected StartObject event"));
mStarted = true;
return nullptr;
}
virtual Base* EndObject()
{
return storers::_i::pop();
}
protected:
virtual Base* match_key(const char* str, rapidjson::SizeType length) = 0;
Target& target() { return mTarget; }
private:
Target mTarget;
bool mStarted;
};
// ----------------------------------------------------------------------
// reader: value storer
// ----------------------------------------------------------------------
template <typename ValueStorer> class Value : public ValueStorer
{
public:
using ValueStorer::ValueStorer;
protected:
virtual Base* pop() { return storers::_i::pop(); }
};
// ----------------------------------------------------------------------
// reader maker base
// ----------------------------------------------------------------------
namespace makers
{
template <typename Parent> class Base
{
public:
Base() = default;
virtual ~Base() {}
virtual readers::Base* reader(Parent& parent) = 0;
};
} // namespace makers
// ----------------------------------------------------------------------
// Structure to keep object reader description
// ----------------------------------------------------------------------
template <typename Parent> using data = std::map<std::string,std::shared_ptr<makers::Base<Parent>>>; // cannot have unique_ptr here because std::map requires copying
// ----------------------------------------------------------------------
// reader: DataRef
// ----------------------------------------------------------------------
template <typename Target> class DataRef : public Object<Target&>
{
public:
DataRef(Target& aTarget, data<Target>& aData, bool aStarted = false) : Object<Target&>(aTarget, aStarted), mData(aData) {}
protected:
virtual readers::Base* match_key(const char* str, rapidjson::SizeType length)
{
const std::string k{str, length};
// std::cerr << typeid(*this).name() << " " << k << std::endl;
auto e = mData.find(k);
if (e != mData.end())
// return e->second(this->target());
return e->second->reader(this->target());
return nullptr;
}
private:
data<Target>& mData;
}; // class DataRef<Target>
// ----------------------------------------------------------------------
// reader: ArrayOfObjects
// ----------------------------------------------------------------------
template <typename Element> class ArrayOfObjects : public Base
{
public:
ArrayOfObjects(std::vector<Element>& aArray, data<Element>& aData) : mArray(aArray), mData(aData), mStarted(false) {}
virtual Base* StartArray()
{
if (mStarted)
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected StartArray event"));
mStarted = true;
mArray.clear(); // erase all old elements
return nullptr;
}
virtual Base* EndArray()
{
// std::cerr << "EndArray of " << typeid(Element).name() << " elements:" << mArray.size() << std::endl;
return storers::_i::pop();
}
virtual Base* StartObject()
{
if (!mStarted)
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected StartObject event"));
mArray.emplace_back();
return new DataRef<Element>(mArray.back(), mData, true);
}
private:
std::vector<Element>& mArray;
data<Element>& mData;
bool mStarted;
}; // class ArrayOfObjects<Element>
// ----------------------------------------------------------------------
// reader: ArrayOfValues
// ----------------------------------------------------------------------
template <typename Element, typename Storer> class ArrayOfValues : public Storer
{
public:
ArrayOfValues(std::vector<Element>& aArray) : Storer(aArray), mArray(aArray), mStarted(false) {}
virtual Base* StartArray()
{
if (mStarted)
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected StartArray event"));
mStarted = true;
mArray.clear(); // erase all old elements
return nullptr;
}
virtual Base* EndArray()
{
return storers::_i::pop();
}
private:
std::vector<Element>& mArray;
bool mStarted;
}; // class ArrayOfValues<Element>
// ----------------------------------------------------------------------
// reader: ArrayOfArrayOfValues
// ----------------------------------------------------------------------
template <typename Target, typename Storer> class ArrayOfArrayOfValuesTarget : public Storer
{
public:
ArrayOfArrayOfValuesTarget(Target& aArray) : Storer(aArray), mNesting(0) {}
virtual Base* StartArray()
{
switch (mNesting) {
case 0:
this->storage().clear(); // erase all old elements
break;
case 1:
this->storage().new_nested();
break;
default:
return storers::_i::failure(typeid(*this).name() + std::string(": unexpected StartArray event"));
}
++mNesting;
return nullptr;
}
virtual Base* EndArray()
{
switch (mNesting) {
case 1:
return storers::_i::pop();
case 2:
break;
default:
return storers::_i::failure(typeid(*this).name() + std::string(": internal, EndArray event with nesting ") + std::to_string(mNesting));
}
--mNesting;
return nullptr;
}
private:
size_t mNesting;
}; // class ArrayOfArrayOfValuesTarget<Target, Storer>
template <typename Element, typename Storer> using ArrayOfArrayOfValues = ArrayOfArrayOfValuesTarget<std::vector<std::vector<Element>>, Storer>;
// ----------------------------------------------------------------------
// reader: template helpers
// ----------------------------------------------------------------------
template <typename T> inline Base* reader(void(T::*setter)(const char*, size_t), T& target)
{
using Bind = decltype(std::bind(setter, &target, std::placeholders::_1, std::placeholders::_2));
return new Value<storers::StringLength<Bind>>(std::bind(setter, &target, std::placeholders::_1, std::placeholders::_2));
}
template <typename T, typename V> inline Base* reader(void(T::*setter)(V), T& target)
{
using Bind = decltype(std::bind(setter, &target, std::placeholders::_1));
using Storer = decltype(storers::type_detector<Bind>(std::declval<V>()));
return new Value<Storer>(std::bind(setter, &target, std::placeholders::_1));
}
template <typename T, typename V> inline Base* reader(V T::* setter, T& target)
{
auto store = [setter,&target](V value) { target.*setter = value; };
using Storer = decltype(storers::type_detector<decltype(store)>(std::declval<V>()));
return new Value<Storer>(store);
}
template <typename T> inline Base* reader(std::string T::* setter, T& target)
{
auto store = [setter,&target](const char* str, size_t length) { (target.*setter).assign(str, length); };
using Storer = decltype(storers::type_detector<decltype(store)>(std::declval<std::string>()));
return new Value<Storer>(store);
}
// // for readers::Object<> derivatives, e.g. return readers::reader<JsonReaderChart>(&Ace::chart, target());
// template <template<typename> class Reader, typename Parent, typename Field> inline Base* reader(Field& (Parent::*accessor)(), Parent& parent)
// {
// using Bind = decltype(std::bind(std::declval<Field& (Parent::*&)()>(), std::declval<Parent*>()));
// return new Reader<Bind>(std::bind(accessor, &parent));
// }
// ----------------------------------------------------------------------
// reader makers
// ----------------------------------------------------------------------
namespace makers
{
template <typename Parent, typename Func>
class Setter : public Base<Parent>
{
public:
Setter(Func aF) : mF(aF) {}
virtual readers::Base* reader(Parent& parent) { return readers::reader(mF, parent); }
private:
Func mF;
};
template <typename Parent, typename Field, typename Func>
class Accessor : public Base<Parent>
{
public:
Accessor(Func aF, data<Field>& aData) : mF(aF), mData(aData) {}
virtual readers::Base* reader(Parent& parent)
{
return new DataRef<Field>(std::bind(mF, &parent)(), mData);
}
private:
Func mF;
data<Field>& mData;
};
template <typename Parent, typename Field>
class AccessorField : public Base<Parent>
{
public:
AccessorField(Field Parent::* aF, data<Field>& aData) : mF(aF), mData(aData) {}
virtual readers::Base* reader(Parent& parent)
{
return new DataRef<Field>(parent.*mF, mData);
}
private:
Field Parent::* mF;
data<Field>& mData;
};
template <typename Parent, typename Element, typename Func>
class ArrayOfObjectsAccessor : public Base<Parent>
{
public:
ArrayOfObjectsAccessor(Func aF, data<Element>& aData) : mF(aF), mData(aData) {}
virtual readers::Base* reader(Parent& parent)
{
return new ArrayOfObjects<Element>(std::bind(mF, &parent)(), mData);
}
private:
Func mF;
data<Element>& mData;
};
template <typename Parent, typename Element, typename Func, typename Storer>
class ArrayOfValuesAccessor : public Base<Parent>
{
public:
ArrayOfValuesAccessor(Func aF) : mF(aF) {}
virtual readers::Base* reader(Parent& parent)
{
return new ArrayOfValues<Element, Storer>(std::bind(mF, &parent)());
}
private:
Func mF;
};
template <typename Parent, typename Target, typename Func, typename Storer>
class ArrayOfArrayOfValuesTargetAccessor : public Base<Parent>
{
public:
ArrayOfArrayOfValuesTargetAccessor(Func aF) : mF(aF) {}
virtual readers::Base* reader(Parent& parent)
{
return new ArrayOfArrayOfValuesTarget<Target, Storer>(std::bind(mF, &parent)());
}
private:
Func mF;
};
template <typename Parent, typename Element, typename Func, typename Storer>
class ArrayOfArrayOfValuesAccessor : public Base<Parent>
{
public:
ArrayOfArrayOfValuesAccessor(Func aF) : mF(aF) {}
virtual readers::Base* reader(Parent& parent)
{
return new ArrayOfArrayOfValues<Element, Storer>(std::bind(mF, &parent)());
}
private:
Func mF;
};
template <typename Storer, typename Parent, typename Field>
class GenericAccessor : public Base<Parent>
{
public:
using Accessor = Field& (Parent::*)();
GenericAccessor(Accessor aAccessor) : mAccessor(aAccessor) {}
virtual readers::Base* reader(Parent& parent)
{
return new Storer(std::bind(mAccessor, &parent)());
}
private:
Accessor mAccessor;
};
template <typename Storer, typename Parent, typename Field>
class GenericAccessorField : public Base<Parent>
{
public:
using Accessor = Field Parent::*;
GenericAccessorField(Accessor aAccessor) : mAccessor(aAccessor) {}
virtual readers::Base* reader(Parent& parent)
{
return new Storer(parent.*mAccessor);
}
private:
Accessor mAccessor;
};
} // namespace makers
// ----------------------------------------------------------------------
} // namespace readers
// ----------------------------------------------------------------------
// Rapidjson event handler
// ----------------------------------------------------------------------
class EventHandler : public rapidjson::BaseReaderHandler<rapidjson::UTF8<>, EventHandler>
{
public:
// template <typename Target> EventHandler(Target& aTarget)
// {
// mHandler.emplace(json_reader(aTarget));
// }
template <typename Target> EventHandler(Target& aTarget, readers::data<Target>& aData)
{
mHandler.emplace(new readers::DataRef<Target>(aTarget, aData));
}
private:
#ifdef NO_EXCEPTIONS
template <typename... Args> bool handler(readers::Base* (readers::Base::*aHandler)(Args... args), Args... args)
{
auto new_handler = ((*mHandler.top()).*aHandler)(args...);
if (storers::_i::failure(new_handler)) {
return false;
}
else if (storers::_i::pop(new_handler)) {
if (mHandler.empty())
return false;
mHandler.pop();
}
else if (storers::_i::pop2(new_handler)) {
if (mHandler.empty())
return false;
mHandler.pop();
if (mHandler.empty())
return false;
mHandler.pop();
}
else if (new_handler) {
mHandler.emplace(new_handler);
}
return true;
}
#else
template <typename... Args> bool handler(readers::Base* (readers::Base::*aHandler)(Args... args), Args... args)
{
try {
auto new_handler = ((*mHandler.top()).*aHandler)(args...);
if (new_handler)
mHandler.emplace(new_handler);
}
catch (storers::_i::Pop&) {
if (mHandler.empty())
return false;
mHandler.pop();
}
catch (storers::_i::Pop2&) {
if (mHandler.empty())
return false;
mHandler.pop();
if (mHandler.empty())
return false;
mHandler.pop();
}
catch (storers::_i::Failure& err) {
if (*err.what())
std::cerr << "ERROR: " << err.what() << std::endl;
return false;
}
// catch (std::exception& err) {
// std::cerr << "ERROR: " << err.what() << std::endl;
// return false;
// }
return true;
}
#endif
public:
bool StartObject() { return handler(&readers::Base::StartObject); }
bool EndObject(rapidjson::SizeType /*memberCount*/) { return handler(&readers::Base::EndObject); }
bool StartArray() { return handler(&readers::Base::StartArray); }
bool EndArray(rapidjson::SizeType /*elementCount*/) { return handler(&readers::Base::EndArray); }
bool Key(const char* str, rapidjson::SizeType length, bool /*copy*/) { return handler(&readers::Base::Key, str, length); }
bool String(const char* str, rapidjson::SizeType length, bool /*copy*/) { return handler(&readers::Base::String, str, length); }
bool Int(int i) { return handler(&readers::Base::Int, i); }
bool Uint(unsigned u) { return handler(&readers::Base::Uint, u); }
bool Double(double d) { return handler(&readers::Base::Double, d); }
bool Bool(bool b) { return handler(&readers::Base::Bool, b); }
bool Null() { return handler(&readers::Base::Null); }
bool Int64(int64_t i) { return handler(&readers::Base::Int64, i); }
bool Uint64(uint64_t u) { return handler(&readers::Base::Uint64, u); }
private:
std::stack<std::unique_ptr<readers::Base>> mHandler;
}; // class EventHandler<>
// ======================================================================
// Exports
// ======================================================================
template <typename Parent> using data = readers::data<Parent>;
// Base class for custom Storers
using StorerBase = storers::Base;
// Field is a simple object set via setter: void Parent::setter(const Value& value)
template <typename Parent, typename ...Args> inline std::shared_ptr<readers::makers::Base<Parent>> field(void (Parent::*setter)(Args...))
{
return std::make_shared<readers::makers::Setter<Parent, decltype(setter)>>(setter);
}
// Field is a simple value set directly (e.g. double)
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field Parent::*setter)
{
return std::make_shared<readers::makers::Setter<Parent, decltype(setter)>>(setter);
}
// Field is a simple object set via setter: void ParentBase::setter(const Value& value)
// Parent is derived from ParentBase, setter declared in ParentBase (and accessible in Parent)
// must be specified as field<Parent>(&Parent::accessor)
template <typename Parent, typename ParentBase, typename ...Args> inline std::shared_ptr<readers::makers::Base<Parent>> field(void (ParentBase::*setter)(Args...))
{
using Setter = void (Parent::*)(Args...);
return std::make_shared<readers::makers::Setter<Parent, Setter>>(setter);
}
// Field is an Object accessible via: Field& Parent::accessor()
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field& (Parent::*accessor)(), data<Field>& aData)
{
return std::make_shared<readers::makers::Accessor<Parent, Field, decltype(accessor)>>(accessor, aData);
}
// Field is an Object accessible directly
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field Parent::*accessor, data<Field>& aData)
{
return std::make_shared<readers::makers::AccessorField<Parent, Field>>(accessor, aData);
}
// Array of Objects
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(std::vector<Field>& (Parent::*accessor)(), data<Field>& aData)
{
return std::make_shared<readers::makers::ArrayOfObjectsAccessor<Parent, Field, decltype(accessor)>>(accessor, aData);
}
// Array of values (via accessor function)
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(std::vector<Field>& (Parent::*accessor)())
{
using Storer = decltype(storers::type_detector<storers::ArrayElement<Field>>(std::declval<Field>()));
return std::make_shared<readers::makers::ArrayOfValuesAccessor<Parent, Field, decltype(accessor), Storer>>(accessor);
}
// Array of values (with inheritance)
// Access for Field of Parent, where
// Field is derived from std::vector<Element>
// Parent is derived from ParentBase, accessor declared in ParentBase (and accessible in Parent)
// must be specified as field<Element, Parent>(&Parent::accessor)
template <typename Element, typename Parent, typename ParentBase, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field& (ParentBase::*accessor)())
{
using Storer = decltype(storers::type_detector<storers::ArrayElement<Element>>(std::declval<Element>()));
return std::make_shared<readers::makers::ArrayOfValuesAccessor<Parent, Element, decltype(accessor), Storer>>(accessor);
}
// Array of array of values
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(std::vector<std::vector<Field>>& (Parent::*accessor)())
{
using Storer = decltype(storers::type_detector<storers::ArrayOfArrayElement<Field>>(std::declval<Field>()));
return std::make_shared<readers::makers::ArrayOfArrayOfValuesAccessor<Parent, Field, decltype(accessor), Storer>>(accessor);
}
// Array of array of double with inheritance
template <typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field& (Parent::*accessor)())
{
using Storer = decltype(storers::type_detector<storers::ArrayOfArrayElementTarget<Field>>(std::declval<double>()));
return std::make_shared<readers::makers::ArrayOfArrayOfValuesTargetAccessor<Parent, Field, decltype(accessor), Storer>>(accessor);
}
// Custom Storer (derived from storers::Base)
// must be specified as field<Storer, Parent, Field>(&Parent::accessor)
template <typename Storer, typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field& (Parent::*accessor)())
{
return std::make_shared<readers::makers::GenericAccessor<Storer, Parent, Field>>(accessor);
}
// Custom Storer (derived from storers::Base)
// must be specified as field<Storer, Parent, Field>(&Parent::field)
template <typename Storer, typename Parent, typename Field> inline std::shared_ptr<readers::makers::Base<Parent>> field(Field Parent::*accessor, typename std::enable_if<std::is_base_of<storers::Base, Storer>::value>::type* = nullptr)
{
return std::make_shared<readers::makers::GenericAccessorField<Storer, Parent, Field>>(accessor);
}
// ----------------------------------------------------------------------
template <typename Target> inline void import(std::string aSource, Target& aTarget, data<Target>& aData)
{
EventHandler handler{aTarget, aData};
rapidjson::Reader reader;
rapidjson::StringStream ss(aSource.c_str());
reader.Parse(ss, handler);
if (reader.HasParseError()) {
const auto message = "json_importer failed at " + std::to_string(reader.GetErrorOffset()) + ": "
+ GetParseError_En(reader.GetParseErrorCode()) + "\n"
+ aSource.substr(reader.GetErrorOffset(), 50);
throw std::runtime_error(message);
}
}
// ----------------------------------------------------------------------
} // namespace json_importer
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 44.235646 | 237 | 0.499419 | acorg |
a2af95919e3fffef582d72c7dacfbb8c82e25db2 | 3,237 | cpp | C++ | day/day_7/main.cpp | moki/aoc2020 | 6eaaaac14aa8a63aea8a6e462be4aa00b5ed385b | [
"BSD-3-Clause"
] | null | null | null | day/day_7/main.cpp | moki/aoc2020 | 6eaaaac14aa8a63aea8a6e462be4aa00b5ed385b | [
"BSD-3-Clause"
] | null | null | null | day/day_7/main.cpp | moki/aoc2020 | 6eaaaac14aa8a63aea8a6e462be4aa00b5ed385b | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <deque>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
typedef std::pair<std::string, size_t> bag;
constexpr char *delimeter = const_cast<char *>(" bag");
std::vector<bag>
parse_rule(std::string & line) {
size_t pos = 0;
bool first = true;
std::vector<bag> bags{};
while ((pos = line.find(delimeter)) != std::string::npos) {
auto rule = line.substr(0, pos);
line = line.substr(pos);
size_t amount = 1;
if (isdigit(rule[0])) {
auto pos_num_end = rule.find(" ");
amount = std::stoi(rule.substr(0, pos_num_end));
rule = rule.substr(pos_num_end + 1);
}
bags.push_back({rule, amount});
for (pos = 0; line[pos] && !isdigit(line[pos]); pos++)
;
line = line.substr(pos);
}
return bags;
}
int main(int argc, char **argv) {
std::fstream input(*++argv);
if (!input) {
exit(1);
}
std::vector<std::string> ass{};
auto sum = 0;
std::unordered_map<std::string, std::vector<bag>> paths{};
for (std::string line; std::getline(input, line);) {
auto bags = parse_rule(line);
auto it = bags.begin();
auto key = (*it).first;
bags.erase(it);
paths.insert({key, std::move(bags)});
}
auto lookup_bag = "shiny gold";
auto found = 0;
for (auto &path : paths) {
std::deque<bag> stack(path.second.begin(), path.second.end());
while (!stack.empty()) {
auto item = stack.back();
if (item.first == lookup_bag) {
found++;
break;
}
stack.pop_back();
auto lookup_path = paths.find(item.first);
if (lookup_path != paths.end()) {
stack.insert(stack.end(),
lookup_path->second.begin(),
lookup_path->second.end());
}
}
}
std::cout << "part 1: " << found << std::endl;
found = 0;
auto shiny_path = paths.find(lookup_bag);
std::deque<bag> stack(shiny_path->second.begin(),
shiny_path->second.end());
while (!stack.empty()) {
auto item = stack.back();
stack.pop_back();
auto path = paths.find(item.first);
if (path == paths.end())
break;
auto depth = item.second;
while (depth--) {
found++;
stack.insert(stack.end(), path->second.begin(),
path->second.end());
}
}
std::cout << "part 2: " << found << std::endl;
}
| 29.162162 | 78 | 0.416435 | moki |
a2b18846e34ac88590c98cf8ad3c6fb2236afccb | 232 | cpp | C++ | Source/JavascriptUMG/JavascriptMenuContext.cpp | keicoon/Unreal.js-core | 2d1ee2f909406cc778273590c1e2c2d3eb72c74a | [
"BSD-3-Clause"
] | 1 | 2021-12-30T17:12:48.000Z | 2021-12-30T17:12:48.000Z | Source/JavascriptUMG/JavascriptMenuContext.cpp | keicoon/Unreal.js-core | 2d1ee2f909406cc778273590c1e2c2d3eb72c74a | [
"BSD-3-Clause"
] | null | null | null | Source/JavascriptUMG/JavascriptMenuContext.cpp | keicoon/Unreal.js-core | 2d1ee2f909406cc778273590c1e2c2d3eb72c74a | [
"BSD-3-Clause"
] | null | null | null | #include "JavascriptMenuContext.h"
bool UJavascriptMenuContext::Public_CanExecute()
{
return OnCanExecute.IsBound() ? OnCanExecute.Execute() : true;
}
void UJavascriptMenuContext::Public_Execute()
{
OnExecute.ExecuteIfBound();
} | 21.090909 | 63 | 0.788793 | keicoon |
a2b7cee28bc2f4d79b96181d36bfaf70ea2d789f | 2,050 | hpp | C++ | contrib/autoboost/autoboost/preprocessor/seq/cat.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | contrib/autoboost/autoboost/preprocessor/seq/cat.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | contrib/autoboost/autoboost/preprocessor/seq/cat.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef AUTOBOOST_PREPROCESSOR_SEQ_CAT_HPP
# define AUTOBOOST_PREPROCESSOR_SEQ_CAT_HPP
#
# include <autoboost/preprocessor/arithmetic/dec.hpp>
# include <autoboost/preprocessor/config/config.hpp>
# include <autoboost/preprocessor/control/if.hpp>
# include <autoboost/preprocessor/seq/fold_left.hpp>
# include <autoboost/preprocessor/seq/seq.hpp>
# include <autoboost/preprocessor/seq/size.hpp>
# include <autoboost/preprocessor/tuple/eat.hpp>
#
# /* AUTOBOOST_PP_SEQ_CAT */
#
# define AUTOBOOST_PP_SEQ_CAT(seq) \
AUTOBOOST_PP_IF( \
AUTOBOOST_PP_DEC(AUTOBOOST_PP_SEQ_SIZE(seq)), \
AUTOBOOST_PP_SEQ_CAT_I, \
AUTOBOOST_PP_SEQ_HEAD \
)(seq) \
/**/
# define AUTOBOOST_PP_SEQ_CAT_I(seq) AUTOBOOST_PP_SEQ_FOLD_LEFT(AUTOBOOST_PP_SEQ_CAT_O, AUTOBOOST_PP_SEQ_HEAD(seq), AUTOBOOST_PP_SEQ_TAIL(seq))
#
# define AUTOBOOST_PP_SEQ_CAT_O(s, st, elem) AUTOBOOST_PP_SEQ_CAT_O_I(st, elem)
# define AUTOBOOST_PP_SEQ_CAT_O_I(a, b) a ## b
#
# /* AUTOBOOST_PP_SEQ_CAT_S */
#
# define AUTOBOOST_PP_SEQ_CAT_S(s, seq) \
AUTOBOOST_PP_IF( \
AUTOBOOST_PP_DEC(AUTOBOOST_PP_SEQ_SIZE(seq)), \
AUTOBOOST_PP_SEQ_CAT_S_I_A, \
AUTOBOOST_PP_SEQ_CAT_S_I_B \
)(s, seq) \
/**/
# define AUTOBOOST_PP_SEQ_CAT_S_I_A(s, seq) AUTOBOOST_PP_SEQ_FOLD_LEFT_ ## s(AUTOBOOST_PP_SEQ_CAT_O, AUTOBOOST_PP_SEQ_HEAD(seq), AUTOBOOST_PP_SEQ_TAIL(seq))
# define AUTOBOOST_PP_SEQ_CAT_S_I_B(s, seq) AUTOBOOST_PP_SEQ_HEAD(seq)
#
# endif
| 41 | 156 | 0.628293 | CaseyCarter |
a2bdd69ffc8253373656cc6a59da5a138a5d3a58 | 3,233 | hpp | C++ | include/LIV/SDK/Unity/TEXTURE_COLOR_SPACE.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/LIV/SDK/Unity/TEXTURE_COLOR_SPACE.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/LIV/SDK/Unity/TEXTURE_COLOR_SPACE.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: LIV.SDK.Unity
namespace LIV::SDK::Unity {
// Forward declaring type: TEXTURE_COLOR_SPACE
struct TEXTURE_COLOR_SPACE;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::LIV::SDK::Unity::TEXTURE_COLOR_SPACE, "LIV.SDK.Unity", "TEXTURE_COLOR_SPACE");
// Type namespace: LIV.SDK.Unity
namespace LIV::SDK::Unity {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: LIV.SDK.Unity.TEXTURE_COLOR_SPACE
// [TokenAttribute] Offset: FFFFFFFF
struct TEXTURE_COLOR_SPACE/*, public ::System::Enum*/ {
public:
public:
// public System.UInt32 value__
// Size: 0x4
// Offset: 0x0
uint value;
// Field size check
static_assert(sizeof(uint) == 0x4);
public:
// Creating value type constructor for type: TEXTURE_COLOR_SPACE
constexpr TEXTURE_COLOR_SPACE(uint value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator uint
constexpr operator uint() const noexcept {
return value;
}
// static field const value: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE UNDEFINED
static constexpr const uint UNDEFINED = 0u;
// Get static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE UNDEFINED
static ::LIV::SDK::Unity::TEXTURE_COLOR_SPACE _get_UNDEFINED();
// Set static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE UNDEFINED
static void _set_UNDEFINED(::LIV::SDK::Unity::TEXTURE_COLOR_SPACE value);
// static field const value: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE LINEAR
static constexpr const uint LINEAR = 1u;
// Get static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE LINEAR
static ::LIV::SDK::Unity::TEXTURE_COLOR_SPACE _get_LINEAR();
// Set static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE LINEAR
static void _set_LINEAR(::LIV::SDK::Unity::TEXTURE_COLOR_SPACE value);
// static field const value: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE SRGB
static constexpr const uint SRGB = 2u;
// Get static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE SRGB
static ::LIV::SDK::Unity::TEXTURE_COLOR_SPACE _get_SRGB();
// Set static field: static public LIV.SDK.Unity.TEXTURE_COLOR_SPACE SRGB
static void _set_SRGB(::LIV::SDK::Unity::TEXTURE_COLOR_SPACE value);
// Get instance field reference: public System.UInt32 value__
uint& dyn_value__();
}; // LIV.SDK.Unity.TEXTURE_COLOR_SPACE
#pragma pack(pop)
static check_size<sizeof(TEXTURE_COLOR_SPACE), 0 + sizeof(uint)> __LIV_SDK_Unity_TEXTURE_COLOR_SPACESizeCheck;
static_assert(sizeof(TEXTURE_COLOR_SPACE) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 46.185714 | 112 | 0.72193 | RedBrumbler |
a2c13609a84ada4859b763fa0ef94b36240730aa | 553 | cpp | C++ | PharmacySystem/Purchase.cpp | ismaeelvaris/PharmacySystem | 940ab00dd3a26db467e34142eb2e4028a509b723 | [
"MIT"
] | 1 | 2018-04-25T18:05:07.000Z | 2018-04-25T18:05:07.000Z | PharmacySystem/Purchase.cpp | ismaeelvaris/PharmacySystem | 940ab00dd3a26db467e34142eb2e4028a509b723 | [
"MIT"
] | null | null | null | PharmacySystem/Purchase.cpp | ismaeelvaris/PharmacySystem | 940ab00dd3a26db467e34142eb2e4028a509b723 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <string>
using namespace std;
struct Purchase {
public:
Purchase(int prescriptionId, int itemId, int quantity, int salePrice) {
this->prescriptionId = prescriptionId;
this->itemId = itemId;
this->quantity = quantity;
this->salePrice = salePrice;
}
int getPrescriptionId() { return prescriptionId; }
int getItemId() { return itemId; }
int getQuantity() { return quantity; }
int getSalePrice() { return salePrice; }
private:
int prescriptionId;
int itemId;
int quantity;
int salePrice;
}; | 19.068966 | 72 | 0.723327 | ismaeelvaris |
a2c23e86007dcdf743c2c93d7fcda24247ae0568 | 3,785 | cpp | C++ | Code Chef/Iron, Magnet and Wall.cpp | akashmodak97/Competitive-Coding-and-Interview-Problems | a34fcb50378cf4bf4e5fd34e910eb68a1c05c066 | [
"MIT"
] | 51 | 2020-02-24T11:14:00.000Z | 2022-03-24T09:32:18.000Z | Code Chef/Iron, Magnet and Wall.cpp | akashmodak97/Competitive-Coding-and-Interview-Problems | a34fcb50378cf4bf4e5fd34e910eb68a1c05c066 | [
"MIT"
] | 3 | 2020-10-02T08:16:09.000Z | 2021-04-17T16:32:38.000Z | Code Chef/Iron, Magnet and Wall.cpp | akashmodak97/Competitive-Coding-and-Interview-Problems | a34fcb50378cf4bf4e5fd34e910eb68a1c05c066 | [
"MIT"
] | 18 | 2020-04-24T15:33:36.000Z | 2022-03-24T09:32:20.000Z | /* Code Chef */
/* Title - Iron, Magnet and Wall */
/* Created By - Akash Modak */
/* Date - 26/12/2020 */
// Chef loves to play with iron (Fe) and magnets (Ma). He took a row of N cells (numbered 1 through N) and placed some objects in some of these cells. You are given a string S with length N describing them; for each valid i, the i-th character of S is one of the following:
// 'I' if the i-th cell contains a piece of iron
// 'M' if the i-th cell contains a magnet
// '_' if the i-th cell is empty
// ':' if the i-th cell contains a conducting sheet
// 'X' if the i-th cell is blocked
// If there is a magnet in a cell i and iron in a cell j, the attraction power between these cells is Pi,j=K+1−|j−i|−Si,j, where Si,j is the number of cells containing sheets between cells i and j. This magnet can only attract this iron if Pi,j>0 and there are no blocked cells between the cells i and j.
// Chef wants to choose some magnets (possibly none) and to each of these magnets, assign a piece of iron which this magnet should attract. Each piece of iron may only be attracted by at most one magnet and only if the attraction power between them is positive and there are no blocked cells between them. Find the maximum number of magnets Chef can choose.
// Input
// The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
// The first line of each test case contains two space-separated integers N and K.
// The second line contains a single string S with length N.
// Output
// For each test case, print a single line containing one integer ― the maximum number of magnets that can attract iron.
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define F first
#define S second
#define pb push_back
#define MP make_pair
#define REP(i,a,b) for (int i = a; i <= b; i++)
#define FLSH fflush(stdout)
#define count_1(n) __builtin_popcountll(n)
#define max(x,y) (x>y)?x:y
#define min(x,y) (x<y)?x:y
#define mid(s,e) (s+(e-s)/2)
#define mini INT_MIN
#define maxi INT_MAX
const int MOD = 1000000007;
const int FMOD = 998244353;
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
int main() {
// your code goes here
fast;
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
string s;
cin>>s;
int i,j=0,m=0,p=k+1,l,r,count=0;
queue<int> mag,iron;
for(i=0;i<n;i++){
if(s[i]=='M')
mag.push(i);
if(s[i]=='I')
iron.push(i);
if(s[i]=='X' || i==n-1){
int l,r,sheet=0,q;
while(!mag.empty() && !iron.empty()){
sheet=0;
l = min(mag.front(),iron.front());
r = max(mag.front(),iron.front());
for(q=l;q<=r;q++){
if(s[q]==':')
sheet++;
}
if((p-abs(l-r)-sheet)>0){
count++;
mag.pop();
iron.pop();
}
else if(mag.front()<iron.front()){
mag.pop();
}
else{
iron.pop();
}
}
while(!mag.empty())
mag.pop();
while(!iron.empty())
iron.pop();
}
}
cout<<count<<"\n";
}
return 0;
}
| 38.622449 | 358 | 0.529458 | akashmodak97 |
a2c3f83e25469243923c5bf9fc73de2f0899c3f3 | 2,494 | hpp | C++ | openstudiocore/src/model/ModelObjectList.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/ModelObjectList.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/ModelObjectList.hpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2013, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_MODELOBJECTLIST_HPP
#define MODEL_MODELOBJECTLIST_HPP
#include <model/ModelAPI.hpp>
#include <model/ModelObject.hpp>
namespace openstudio {
namespace model {
namespace detail {
class ModelObjectList_Impl;
} // detail
/** ModelObjectList is a ModelObject that wraps the OpenStudio IDD object 'OS:ModelObjectList'. */
class MODEL_API ModelObjectList : public ModelObject {
public:
/** @name Constructors and Destructors */
//@{
explicit ModelObjectList(const Model& model);
virtual ~ModelObjectList() {}
//@}
static IddObjectType iddObjectType();
std::vector<IdfObject> remove();
ModelObject clone(Model model) const;
bool addModelObject(const ModelObject & modelObject );
void removeModelObject(const ModelObject & modelObject );
void removeAllModelObjects();
std::vector< ModelObject > modelObjects() const;
protected:
/// @cond
typedef detail::ModelObjectList_Impl ImplType;
explicit ModelObjectList(boost::shared_ptr<detail::ModelObjectList_Impl> impl);
friend class detail::ModelObjectList_Impl;
friend class Model;
friend class IdfObject;
friend class openstudio::detail::IdfObject_Impl;
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.ModelObjectList");
};
/** \relates ModelObjectList*/
typedef boost::optional<ModelObjectList> OptionalModelObjectList;
/** \relates ModelObjectList*/
typedef std::vector<ModelObjectList> ModelObjectListVector;
} // model
} // openstudio
#endif // MODEL_MODELOBJECTLIST_HPP
| 28.666667 | 98 | 0.709703 | bobzabcik |
a2c447a7acd7c74cdf2cf2d09f451b5b5c43a410 | 32,824 | cpp | C++ | DeviceCode/pal/PKCS11/Tokens/OpenSSL/OpenSSL_PKCS11_objects.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 529 | 2015-03-10T00:17:45.000Z | 2022-03-17T02:21:19.000Z | DeviceCode/pal/PKCS11/Tokens/OpenSSL/OpenSSL_PKCS11_objects.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 495 | 2015-03-10T22:02:46.000Z | 2019-05-16T13:05:00.000Z | DeviceCode/pal/PKCS11/Tokens/OpenSSL/OpenSSL_PKCS11_objects.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 332 | 2015-03-10T08:04:36.000Z | 2022-03-29T04:18:36.000Z | #include "OpenSSL_pkcs11.h"
#include <PEM\pem.h>
#include <PKCS12\pkcs12.h>
#include <TinyCLR\ssl_functions.h>
OBJECT_DATA PKCS11_Objects_OpenSSL::s_Objects[];
void PKCS11_Objects_OpenSSL::IntitializeObjects()
{
memset(PKCS11_Objects_OpenSSL::s_Objects, 0, sizeof(PKCS11_Objects_OpenSSL::s_Objects));
}
int PKCS11_Objects_OpenSSL::FindEmptyObjectHandle()
{
int index;
for(index=0; index<ARRAYSIZE(s_Objects); index++)
{
if(s_Objects[index].Data == NULL) break;
}
return index < ARRAYSIZE(s_Objects) ? index : -1;
}
OBJECT_DATA* PKCS11_Objects_OpenSSL::GetObjectFromHandle(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject)
{
OBJECT_DATA* retVal;
if((int)hObject < 0 || hObject >= ARRAYSIZE(s_Objects))
{
return NULL;
}
retVal = &s_Objects[(int)hObject];
return (retVal->Data == NULL) ? NULL : retVal;
}
BOOL PKCS11_Objects_OpenSSL::FreeObject(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject)
{
OBJECT_DATA* retVal;
if((int)hObject < 0 || hObject >= ARRAYSIZE(s_Objects))
{
return FALSE;
}
retVal = &s_Objects[(int)hObject];
if(retVal->Data == NULL) return FALSE;
TINYCLR_SSL_FREE(retVal->Data);
retVal->Data = NULL;
retVal->RefCount = 0;
return TRUE;
}
CK_OBJECT_HANDLE PKCS11_Objects_OpenSSL::AllocObject(Cryptoki_Session_Context* pSessionCtx, ObjectType type, size_t size, OBJECT_DATA** ppData)
{
int idx = FindEmptyObjectHandle();
*ppData = NULL;
if(idx == -1) return idx;
*ppData = &s_Objects[idx];
(*ppData)->Type = type;
(*ppData)->Data = TINYCLR_SSL_MALLOC(size);
(*ppData)->RefCount = 1;
if((*ppData)->Data == NULL) return CK_OBJECT_HANDLE_INVALID;
TINYCLR_SSL_MEMSET((*ppData)->Data, 0, size);
return (CK_OBJECT_HANDLE)idx;
}
CK_RV PKCS11_Objects_OpenSSL::LoadX509Cert(Cryptoki_Session_Context* pSessionCtx, X509* x, OBJECT_DATA** ppObject, EVP_PKEY* privateKey, CK_OBJECT_HANDLE_PTR phObject)
{
CERT_DATA* pCert;
EVP_PKEY* pubKey = X509_get_pubkey(x);
UINT32 keyType = CKK_VENDOR_DEFINED;
if(phObject == NULL) return CKR_ARGUMENTS_BAD;
*phObject = AllocObject(pSessionCtx, CertificateType, sizeof(CERT_DATA), ppObject);
if(*phObject == CK_OBJECT_HANDLE_INVALID)
{
return CKR_FUNCTION_FAILED;
}
if(pubKey != NULL)
{
switch(pubKey->type)
{
case EVP_PKEY_RSA:
case EVP_PKEY_RSA2:
keyType = CKK_RSA;
break;
case EVP_PKEY_DSA:
case EVP_PKEY_DSA1:
case EVP_PKEY_DSA2:
case EVP_PKEY_DSA3:
case EVP_PKEY_DSA4:
keyType = CKK_DSA;
break;
case EVP_PKEY_DH:
keyType = CKK_DH;
break;
case EVP_PKEY_EC:
keyType = CKK_DH;
break;
}
}
pCert = (CERT_DATA*)(*ppObject)->Data;
pCert->cert = x;
pCert->privKeyData.key = privateKey;
if(privateKey != NULL)
{
pCert->privKeyData.attrib = Private;
pCert->privKeyData.type = keyType;
pCert->privKeyData.size = EVP_PKEY_bits(privateKey);
}
pCert->pubKeyData.key = pubKey;
pCert->pubKeyData.attrib = Public;
pCert->pubKeyData.type = keyType;
pCert->pubKeyData.size = EVP_PKEY_bits(pubKey);
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::CreateObject(Cryptoki_Session_Context* pSessionCtx, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject)
{
UINT32 attribIndex = 0;
if(pTemplate[attribIndex].type == CKA_CLASS && pTemplate[attribIndex].ulValueLen == sizeof(CK_OBJECT_CLASS))
{
CK_OBJECT_CLASS cls = SwapEndianIfBEc32(*(CK_OBJECT_CLASS*)pTemplate[attribIndex].pValue);
CHAR pwd[64];
int len;
switch(cls)
{
case CKO_CERTIFICATE:
for(++attribIndex; attribIndex < ulCount; attribIndex++)
{
switch(pTemplate[attribIndex].type)
{
case CKA_PASSWORD:
len = pTemplate[attribIndex].ulValueLen;
if(len >= ARRAYSIZE(pwd))
{
len = ARRAYSIZE(pwd) - 1;
}
TINYCLR_SSL_MEMCPY(pwd, pTemplate[attribIndex].pValue, len);
pwd[len] = 0;
break;
case CKA_VALUE:
{
OBJECT_DATA* pObject = NULL;
EVP_PKEY* privateKey = NULL;
X509 *x = ssl_parse_certificate(pTemplate[attribIndex].pValue, pTemplate[attribIndex].ulValueLen, pwd, &privateKey);
if (x == NULL)
{
TINYCLR_SSL_PRINTF("Unable to load certificate\n");
return CKR_FUNCTION_FAILED;
}
else
{
CK_RV retVal = LoadX509Cert(pSessionCtx, x, &pObject, privateKey, phObject);
if(retVal != CKR_OK) X509_free(x);
return retVal;
}
}
}
}
break;
}
}
return CKR_FUNCTION_NOT_SUPPORTED;
}
CK_RV PKCS11_Objects_OpenSSL::CopyObject(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phNewObject)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
CK_RV PKCS11_Objects_OpenSSL::DestroyObject(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject)
{
OBJECT_DATA* pData = GetObjectFromHandle(pSessionCtx, hObject);
if(pData == NULL) return CKR_OBJECT_HANDLE_INVALID;
if(--pData->RefCount <= 0)
{
if(pData->Type == KeyType)
{
PKCS11_Keys_OpenSSL::DeleteKey(pSessionCtx, (KEY_DATA *)pData->Data);
}
else if(pData->Type == CertificateType)
{
CERT_DATA* pCert = (CERT_DATA*)pData->Data;
X509_free(pCert->cert);
}
return FreeObject(pSessionCtx, hObject) == NULL ? CKR_OBJECT_HANDLE_INVALID : CKR_OK;
}
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::GetObjectSize(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
//MS: copied decoding algo from get_ASN1_UTCTIME of asn1_openssl.lib
//MS: populate DATE_TIME_INFO struct with year,month, day,hour,minute,second,etc
static int ssl_get_ASN1_UTCTIME(const ASN1_UTCTIME *tm, DATE_TIME_INFO *dti)
{
const char *v;
int gmt=0;
int i;
int y=0,M=0,d=0,h=0,m=0,s=0;
memset(dti, 0, sizeof(*dti));
i=tm->length;
v=(const char *)tm->data;
if (i < 10) { goto err; }
if (v[i-1] == 'Z') gmt=1;
for (i=0; i<10; i++)
if ((v[i] > '9') || (v[i] < '0')) { goto err; }
y= (v[0]-'0')*10+(v[1]-'0');
if (y < 50) y+=100;
M= (v[2]-'0')*10+(v[3]-'0');
if ((M > 12) || (M < 1)) { goto err; }
d= (v[4]-'0')*10+(v[5]-'0');
h= (v[6]-'0')*10+(v[7]-'0');
m= (v[8]-'0')*10+(v[9]-'0');
if (tm->length >=12 &&
(v[10] >= '0') && (v[10] <= '9') &&
(v[11] >= '0') && (v[11] <= '9'))
s= (v[10]-'0')*10+(v[11]-'0');
dti->year = SwapEndianIfBEc32(y+1900);
dti->month = SwapEndianIfBEc32(M);
dti->day = SwapEndianIfBEc32(d);
dti->hour = SwapEndianIfBEc32(h);
dti->minute = SwapEndianIfBEc32(m);
dti->second = SwapEndianIfBEc32(s);
dti->dlsTime = 0; //TODO:HOW to find
dti->tzOffset = SwapEndianIfBEc32(gmt); //TODO:How to find
return(1);
err:
TINYCLR_SSL_PRINTF("Bad time value\r\n");
return(0);
}
CK_RV PKCS11_Objects_OpenSSL::GetAttributeValue(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
{
OBJECT_DATA* pObj = PKCS11_Objects_OpenSSL::GetObjectFromHandle(pSessionCtx, hObject);
if(pObj == NULL) return CKR_OBJECT_HANDLE_INVALID;
if(pObj->Type == CertificateType)
{
CERT_DATA* pCertData = (CERT_DATA*)pObj->Data;
X509* pCert = pCertData->cert;
INT32 valLen = 0;
for(int i=0; i<(int)ulCount; i++)
{
switch(pTemplate[i].type)
{
case CKA_CLASS:
*(INT32*)pTemplate[i].pValue = SwapEndianIfBEc32(CKO_CERTIFICATE);
break;
case CKA_PRIVATE:
*(INT32*)pTemplate[i].pValue = SwapEndianIfBEc32(pCertData->privKeyData.key == NULL ? 0 : 1);
valLen = sizeof(INT32);
break;
case CKA_VALUE_BITS:
{
*(INT32*)pTemplate[i].pValue = SwapEndianIfBEc32(pCertData->pubKeyData.size);
valLen = sizeof(INT32);
}
break;
case CKA_KEY_TYPE:
{
*(UINT32*)pTemplate[i].pValue = SwapEndianIfBEc32(pCertData->pubKeyData.type);
valLen = sizeof(UINT32);
}
break;
case CKA_ISSUER:
{
char* name=X509_NAME_oneline(X509_get_issuer_name(pCert),NULL,0);
valLen = TINYCLR_SSL_STRLEN(name) + 1;
if(valLen > pTemplate[i].ulValueLen) valLen = pTemplate[i].ulValueLen;
hal_strcpy_s((char*)pTemplate[i].pValue, valLen, name);
OPENSSL_free(name);
}
break;
case CKA_SUBJECT:
{
char* subject=X509_NAME_oneline(X509_get_subject_name(pCert),NULL,0);
valLen = TINYCLR_SSL_STRLEN(subject) + 1;
if(valLen > pTemplate[i].ulValueLen) valLen = pTemplate[i].ulValueLen;
hal_strcpy_s((char*)pTemplate[i].pValue, valLen, subject);
OPENSSL_free(subject);
}
break;
case CKA_SERIAL_NUMBER:
{
ASN1_INTEGER* asn = X509_get_serialNumber(pCert);
valLen = asn->length;
if(valLen > pTemplate[i].ulValueLen) valLen = pTemplate[i].ulValueLen;
TINYCLR_SSL_MEMCPY(pTemplate[i].pValue, asn->data, valLen);
}
break;
case CKA_MECHANISM_TYPE:
if(pCert->sig_alg != NULL)
{
int signature_nid;
CK_MECHANISM_TYPE type = CKM_VENDOR_DEFINED;
signature_nid = OBJ_obj2nid(pCert->sig_alg->algorithm);
switch(signature_nid)
{
case NID_sha1WithRSA:
case NID_sha1WithRSAEncryption:
//szNid = "1.2.840.113549.1.1.5";
type = CKM_SHA1_RSA_PKCS;
break;
case NID_md5WithRSA:
case NID_md5WithRSAEncryption:
//szNid = "1.2.840.113549.1.1.4";
type = CKM_MD5_RSA_PKCS;
break;
case NID_sha256WithRSAEncryption:
//szNid = "1.2.840.113549.1.1.11";
type = CKM_SHA256_RSA_PKCS;
break;
case NID_sha384WithRSAEncryption:
//szNid = "1.2.840.113549.1.1.12";
type = CKM_SHA384_RSA_PKCS;
break;
case NID_sha512WithRSAEncryption:
//szNid = "1.2.840.113549.1.1.13";
type = CKM_SHA512_RSA_PKCS;
break;
}
valLen = sizeof(CK_MECHANISM_TYPE);
*(CK_MECHANISM_TYPE*)pTemplate[i].pValue = SwapEndianIfBEc32(type);
}
break;
case CKA_START_DATE:
{
DATE_TIME_INFO dti;
ssl_get_ASN1_UTCTIME(X509_get_notBefore(pCert), &dti);
valLen = (INT32)pTemplate[i].ulValueLen;
if(valLen > sizeof(dti)) valLen = sizeof(dti);
TINYCLR_SSL_MEMCPY(pTemplate[i].pValue, &dti, valLen);
}
break;
case CKA_END_DATE:
{
DATE_TIME_INFO dti;
ssl_get_ASN1_UTCTIME(X509_get_notAfter(pCert), &dti);
valLen = pTemplate[i].ulValueLen;
if(valLen > sizeof(dti)) valLen = sizeof(dti);
TINYCLR_SSL_MEMCPY(pTemplate[i].pValue, &dti, valLen);
}
break;
case CKA_VALUE:
{
UINT8* pData = (UINT8*)pTemplate[i].pValue;
UINT8* pTmp = pData;
valLen = i2d_X509(pCert, NULL);
if(valLen > pTemplate[i].ulValueLen) return CKR_DEVICE_MEMORY;
valLen = i2d_X509(pCert, &pTmp);
if(valLen < 0) return CKR_FUNCTION_FAILED;
}
break;
case CKA_VALUE_LEN:
*(UINT32*)pTemplate[i].pValue = SwapEndianIfBEc32(valLen);
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
}
}
else if(pObj->Type == KeyType)
{
KEY_DATA* pKey = (KEY_DATA*)pObj->Data;
int valLen = 0;
bool isPrivate = false;
for(int i=0; i<(int)ulCount; i++)
{
switch(pTemplate[i].type)
{
case CKA_CLASS:
*(INT32*)pTemplate[i].pValue = SwapEndianIfBEc32((0 != (pKey->attrib & Private) ? CKO_PRIVATE_KEY : 0 != (pKey->attrib & Public) ? CKO_PUBLIC_KEY : CKO_SECRET_KEY));
break;
case CKA_MODULUS:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->n, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_EXPONENT_1:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->dmp1, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_EXPONENT_2:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->dmq1, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_COEFFICIENT:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->iqmp, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PRIME_1:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->p, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PRIME_2:
if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->q, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PRIVATE_EXPONENT:
if(pKey->type == CKK_DSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.dsa->priv_key, (UINT8*)pTemplate[i].pValue);
}
else if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->d, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PUBLIC_EXPONENT:
if(pKey->type == CKK_DSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.dsa->pub_key, (UINT8*)pTemplate[i].pValue);
}
else if(pKey->type == CKK_EC)
{
UINT8 pTmp[66*2+1];
EC_KEY* pEC = ((EVP_PKEY*)pKey->key)->pkey.ec;
const EC_POINT* point = EC_KEY_get0_public_key(pEC);
valLen = EC_POINT_point2oct(EC_KEY_get0_group(pEC), point, POINT_CONVERSION_UNCOMPRESSED, (UINT8*)pTmp, ARRAYSIZE(pTmp), NULL);
if(valLen == 0) return CKR_FUNCTION_FAILED;
memmove(pTemplate[i].pValue, &pTmp[1], valLen-1); // remove POINT_CONVERSION_UNCOMPRESSED header byte
}
else if(pKey->type == CKK_RSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.rsa->e, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PRIME:
if(pKey->type == CKK_DSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.dsa->p, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_SUBPRIME:
if(pKey->type == CKK_DSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.dsa->q, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_BASE:
if(pKey->type == CKK_DSA)
{
EVP_PKEY* pRealKey = (EVP_PKEY*)pKey->key;
valLen = BN_bn2bin(pRealKey->pkey.dsa->g, (UINT8*)pTemplate[i].pValue);
}
break;
case CKA_PRIVATE:
isPrivate = 0 != *(INT32*)pTemplate[i].pValue;
break;
case CKA_KEY_TYPE:
*(INT32*)pTemplate[i].pValue = SwapEndianIfBEc32(pKey->type);
break;
case CKA_VALUE_BITS:
*(UINT32*)pTemplate[i].pValue = SwapEndianIfBEc32(pKey->size);
break;
case CKA_VALUE:
switch(pKey->type)
{
case CKK_AES:
case CKK_GENERIC_SECRET:
{
// TODO: Add permissions to export key
int len = (pKey->size + 7) / 8;
if(len > (INT32)pTemplate[i].ulValueLen) len = (int)pTemplate[i].ulValueLen;
TINYCLR_SSL_MEMCPY(pTemplate[i].pValue, pKey->key, len);
valLen = len;
}
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
break;
case CKA_VALUE_LEN:
switch(pKey->type)
{
case CKK_EC:
*(UINT32*)pTemplate[i].pValue = SwapEndianIfBEc32(valLen);
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
}
}
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::SetAttributeValue(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
{
OBJECT_DATA* pObj = PKCS11_Objects_OpenSSL::GetObjectFromHandle(pSessionCtx, hObject);
if(pObj == NULL) return CKR_OBJECT_HANDLE_INVALID;
if(pObj->Type == CertificateType)
{
CERT_DATA* pCertData = (CERT_DATA*)pObj->Data;
X509* pCert = pCertData->cert;
CHAR group[20] = {0};
CHAR fileName[20] = {0};
INT32 len = 0;
BOOL fSave = FALSE;
BOOL fDelete = FALSE;
for(int i=0; i<(int)ulCount; i++)
{
switch(pTemplate[i].type)
{
case CKA_PERSIST:
fSave = SwapEndianIfBEc32(*(INT32*)pTemplate[i].pValue) != 0;
fDelete = !fSave;
break;
case CKA_LABEL:
len = pTemplate[i].ulValueLen;
if(len >= ARRAYSIZE(group))
{
len = ARRAYSIZE(group) - 1;
}
TINYCLR_SSL_MEMCPY(group, pTemplate[i].pValue, len);
group[len] = 0;
break;
case CKA_OBJECT_ID:
len = pTemplate[i].ulValueLen;
if(len >= ARRAYSIZE(fileName))
{
len = ARRAYSIZE(fileName) - 1;
}
TINYCLR_SSL_MEMCPY(fileName, pTemplate[i].pValue, len);
fileName[len] = 0;
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
}
if(fDelete)
{
hal_strcpy_s(fileName, ARRAYSIZE(pObj->FileName), pObj->FileName);
pObj->GroupName[0] = 0;
if(g_OpenSSL_Token.Storage != NULL && g_OpenSSL_Token.Storage->Delete != NULL)
{
if(!g_OpenSSL_Token.Storage->Delete(fileName, group)) return CKR_FUNCTION_FAILED;
}
else
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
}
else if(fSave)
{
hal_strcpy_s(pObj->GroupName, ARRAYSIZE(pObj->GroupName), group );
hal_strcpy_s(pObj->FileName , ARRAYSIZE(pObj->FileName ), fileName);
if(g_OpenSSL_Token.Storage != NULL && g_OpenSSL_Token.Storage->Create != NULL)
{
BOOL res;
UINT8* pData, *pTmp;
INT32 len = i2d_X509( pCert, NULL );
if(len <= 0) return CKR_FUNCTION_FAILED;
pData = (UINT8*)TINYCLR_SSL_MALLOC(len);
if(pData == NULL) return CKR_DEVICE_MEMORY;
pTmp = pData;
i2d_X509(pCert, &pTmp);
// TODO: Save private key as well
res = g_OpenSSL_Token.Storage->Create( fileName, group, CertificateType, pData, len );
TINYCLR_SSL_FREE(pData);
if(!res) return CKR_FUNCTION_FAILED;
}
else
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
}
else
{
return CKR_ATTRIBUTE_TYPE_INVALID;
}
}
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::FindObjectsInit(Cryptoki_Session_Context* pSessionCtx, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
{
FIND_OBJECT_DATA *pData;
INT32 i = 0, len;
if(pSessionCtx->FindObjectsCtx != NULL)
{
return CKR_FUNCTION_NOT_PARALLEL;
}
pData = (FIND_OBJECT_DATA*)TINYCLR_SSL_MALLOC(sizeof(FIND_OBJECT_DATA));
if(pData == NULL) return CKR_DEVICE_MEMORY;
pSessionCtx->FindObjectsCtx = pData;
pData->FileName[0] = 0;
pData->GroupName[0] = 0;
while(i < ulCount)
{
switch(pTemplate[i].type)
{
case CKA_CLASS:
switch(SwapEndianIfBEc32(*(INT32*)pTemplate[i].pValue))
{
case CKO_CERTIFICATE:
pData->ObjectType = CertificateType;
break;
case CKO_PUBLIC_KEY:
case CKO_SECRET_KEY:
case CKO_PRIVATE_KEY:
pData->ObjectType = KeyType;
break;
default:
pData->ObjectType = DataType;
break;
}
break;
case CKA_LABEL:
len = pTemplate[i].ulValueLen;
if(len >= ARRAYSIZE(pData->GroupName))
{
len = ARRAYSIZE(pData->GroupName) - 1;
}
TINYCLR_SSL_MEMCPY( pData->GroupName, pTemplate[i].pValue, len );
pData->GroupName[len] = 0;
break;
case CKA_OBJECT_ID:
len = pTemplate[i].ulValueLen;
if(len >= ARRAYSIZE(pData->FileName))
{
len = ARRAYSIZE(pData->FileName) - 1;
}
TINYCLR_SSL_MEMCPY( pData->FileName, pTemplate[i].pValue, len );
pData->FileName[len] = 0;
break;
default:
return CKR_ATTRIBUTE_TYPE_INVALID;
}
i++;
}
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::FindObjects(Cryptoki_Session_Context* pSessionCtx, CK_OBJECT_HANDLE_PTR phObjects, CK_ULONG ulMaxCount, CK_ULONG_PTR pulObjectCount)
{
FIND_OBJECT_DATA *pData = (FIND_OBJECT_DATA*)pSessionCtx->FindObjectsCtx;
UINT32 cntObj = 0;
*pulObjectCount = 0;
if(pData == NULL) return CKR_FUNCTION_FAILED;
if(ulMaxCount == 0) return CKR_ARGUMENTS_BAD;
{
FileEnumCtx ctx;
CHAR fileName[20];
if(g_OpenSSL_Token.Storage == NULL || g_OpenSSL_Token.Storage->GetFileEnum == NULL)
{
return CKR_FUNCTION_NOT_SUPPORTED;
}
if(!g_OpenSSL_Token.Storage->GetFileEnum(pData->GroupName, pData->ObjectType, ctx)) return CKR_FUNCTION_FAILED;
while(g_OpenSSL_Token.Storage->GetNextFile(ctx, fileName, ARRAYSIZE(fileName)))
{
UINT32 dataLen = 0;
if(g_OpenSSL_Token.Storage->Read(fileName, pData->GroupName, pData->ObjectType, NULL, dataLen))
{
UINT8* pObj = (UINT8*)TINYCLR_SSL_MALLOC(dataLen);
if(pObj)
{
g_OpenSSL_Token.Storage->Read(fileName, pData->GroupName, pData->ObjectType, pObj, dataLen);
switch(pData->ObjectType)
{
case CertificateType:
{
OBJECT_DATA *pObject = NULL;
const UINT8* pTmp = pObj;
CK_OBJECT_HANDLE hObjTmp, *pObjHandle;
X509* x509 = d2i_X509(NULL, &pTmp, dataLen);
if(x509 == NULL)
{
TINYCLR_SSL_FREE(pObj);
return CKR_FUNCTION_FAILED;
}
if(phObjects == NULL)
{
pObjHandle = &hObjTmp;
}
else
{
pObjHandle = &phObjects[cntObj];
}
if(CKR_OK != LoadX509Cert(pSessionCtx, x509, &pObject, NULL, pObjHandle))
{
X509_free(x509);
TINYCLR_SSL_FREE(pObj);
//return CKR_FUNCTION_FAILED;
g_OpenSSL_Token.Storage->Delete( fileName, pData->GroupName );
continue;
}
hal_strcpy_s(pObject->GroupName, ARRAYSIZE(pObject->GroupName), pData->GroupName);
hal_strcpy_s(pObject->FileName , ARRAYSIZE(pObject->FileName ), fileName );
cntObj++;
TINYCLR_SSL_FREE(pObj);
if(cntObj >= ulMaxCount)
{
*pulObjectCount = cntObj;
return CKR_OK;
}
}
break;
case KeyType:
{
// TODO:
TINYCLR_SSL_FREE(pObj);
}
break;
default:
// TODO:
TINYCLR_SSL_FREE(pObj);
break;
}
}
}
}
}
*pulObjectCount = cntObj;
return CKR_OK;
}
CK_RV PKCS11_Objects_OpenSSL::FindObjectsFinal(Cryptoki_Session_Context* pSessionCtx)
{
if(pSessionCtx->FindObjectsCtx != NULL)
{
TINYCLR_SSL_FREE(pSessionCtx->FindObjectsCtx);
pSessionCtx->FindObjectsCtx = NULL;
}
return CKR_OK;
}
| 34.085151 | 186 | 0.443486 | PervasiveDigital |
a2c9a23508b58bc55999787bef84c073718a6d0a | 404 | cpp | C++ | src/datatype.cpp | BergerZvika/smt-switch | c65dc8529c81b04443807147da2c5cebdccf216d | [
"BSD-3-Clause"
] | 49 | 2018-02-20T12:47:28.000Z | 2021-08-14T17:06:19.000Z | src/datatype.cpp | BergerZvika/smt-switch | c65dc8529c81b04443807147da2c5cebdccf216d | [
"BSD-3-Clause"
] | 117 | 2017-06-30T18:26:02.000Z | 2021-08-17T19:50:18.000Z | src/datatype.cpp | BergerZvika/smt-switch | c65dc8529c81b04443807147da2c5cebdccf216d | [
"BSD-3-Clause"
] | 21 | 2019-10-10T22:22:03.000Z | 2021-07-22T14:15:10.000Z | #include "datatype.h"
namespace smt {
// Overloaded operators simply call the constructors' comparison functions
bool operator==(const DatatypeConstructorDecl & d1,
const DatatypeConstructorDecl & d2)
{
return d1->compare(d2);
}
bool operator!=(const DatatypeConstructorDecl & d1,
const DatatypeConstructorDecl & d2)
{
return !d1->compare(d2);
}
} // namespace smt
| 23.764706 | 74 | 0.695545 | BergerZvika |
a2c9d1f01f2381e62d83070eac23d802a34f568e | 2,122 | cpp | C++ | backup/2/interviewbit/c++/pretty-json.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/interviewbit/c++/pretty-json.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/interviewbit/c++/pretty-json.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/interviewbit/pretty-json.html .
string prefix(int ind) {
string res;
for (int i = 0; i < ind; i++) {
res += "\t";
}
return res;
}
vector<string> clean(vector<string> words) {
vector<string> res;
for (string word : words) {
if (word.length() <= 0) {
continue;
}
bool valid = false;
for (int i = 0; i < word.length(); i++) {
if (word[i] != '\t') {
valid = true;
break;
}
}
if (valid) {
res.push_back(word);
}
}
return res;
}
vector<string> Solution::prettyJSON(string A) {
vector<string> res;
int ind = 0, len = A.length();
char pre = '\0';
string delimiter = "{}[]";
string line;
for (int i = 0; i < len; i++) {
char ch = A[i];
if (pre == ',') {
res.push_back(line);
line = prefix(ind);
}
if (delimiter.find(ch) != string::npos) {
res.push_back(line);
if (ch == '{' || ch == '[') {
line = prefix(ind) + ch;
ind++;
res.push_back(line);
line = prefix(ind);
} else {
ind--;
line = prefix(ind) + ch;
if (i + 1 < len && A[i + 1] == ',') {
} else {
res.push_back(line);
line = prefix(ind);
}
}
} else {
line += ch;
}
pre = ch;
}
return clean(res);
}
| 30.753623 | 345 | 0.48115 | yangyanzhan |
a2cc68bb94ff35f052fcee5cc345f80efed3d234 | 14,064 | cpp | C++ | src/obstruction_free_dictionary.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | src/obstruction_free_dictionary.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | src/obstruction_free_dictionary.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | #include <obstruction_free_dictionary.hpp>
namespace nonblocking
{
template<> versioned<obstruction_free_dictionary::bucket_state>::versioned(unsigned int version, obstruction_free_dictionary::bucket_state value) : _version{version}
{
switch (value)
{
case obstruction_free_dictionary::bucket_state::empty: _value = 0; break;
case obstruction_free_dictionary::bucket_state::busy: _value = 1; break;
case obstruction_free_dictionary::bucket_state::inserting: _value = 2; break;
case obstruction_free_dictionary::bucket_state::member: _value = 3; break;
case obstruction_free_dictionary::bucket_state::updating: _value = 4; break;
}
}
template <> versioned<obstruction_free_dictionary::bucket_state>::versioned() noexcept : _version{0}, _value{0} {}
template <> bool versioned<obstruction_free_dictionary::bucket_state>::operator==(versioned<obstruction_free_dictionary::bucket_state> other)
{
return (_version == other._version) && (_value == other._value);
}
template<> obstruction_free_dictionary::bucket_state versioned<obstruction_free_dictionary::bucket_state>::value()
{
switch (_value)
{
case 0: return obstruction_free_dictionary::bucket_state::empty;
case 1: return obstruction_free_dictionary::bucket_state::busy;
case 2: return obstruction_free_dictionary::bucket_state::inserting;
case 3: return obstruction_free_dictionary::bucket_state::member;
case 4: return obstruction_free_dictionary::bucket_state::updating;
default: return obstruction_free_dictionary::bucket_state::busy;
}
}
template<> unsigned int versioned<obstruction_free_dictionary::bucket_state>::version()
{
return _version;
}
obstruction_free_dictionary::bucket::bucket(unsigned int key, unsigned int value, unsigned int version, bucket_state state) : key{key}, state(versioned<obstruction_free_dictionary::bucket_state>(version, state)), value(versioned<unsigned int>(version, value)), copy(versioned<unsigned int>(version, 0)) {}
obstruction_free_dictionary::bucket::bucket() : key{0}, state(versioned<obstruction_free_dictionary::bucket_state>()), value(versioned<unsigned int>()), copy(versioned<unsigned int>()) {}
obstruction_free_dictionary::bucket::bucket(unsigned int key, versioned<unsigned int> value, versioned<unsigned int> copy, versioned<bucket_state> state) : key{key}, value{value}, copy{copy}, state{state} {}
obstruction_free_dictionary::bucket* obstruction_free_dictionary::bucket_at(unsigned int h, int index)
{
return &buckets[(h+index*(index+1)/2)%size];
}
obstruction_free_dictionary::bucket::bucket(const obstruction_free_dictionary::bucket& b)
{
key.store(b.key.load(std::memory_order_relaxed), std::memory_order_relaxed);
state.store(b.state.load(std::memory_order_relaxed), std::memory_order_relaxed);
value.store(b.value.load(std::memory_order_relaxed), std::memory_order_relaxed);
copy.store(b.copy.load(std::memory_order_relaxed), std::memory_order_relaxed);
}
bool obstruction_free_dictionary::does_bucket_contain_collision(unsigned int h, int index)
{
versioned<bucket_state> state;
versioned<bucket_state> later_state;
unsigned int key;
do
{
bucket* bkt_at = bucket_at(h, index);
state = bkt_at->state.load(std::memory_order_acquire);
key = bkt_at->key.load(std::memory_order_acquire);
later_state = bkt_at->state.load(std::memory_order_relaxed);
} while (!(state == later_state));
if ((state.value() == inserting) || (state.value() == member) || (state.value() == updating))
{
if (hash(key) == h)
{
return true;
}
}
return false;
}
obstruction_free_dictionary::obstruction_free_dictionary(unsigned int size) : base(size)
{
buckets = new bucket[size];
}
obstruction_free_dictionary::~obstruction_free_dictionary()
{
delete buckets;
}
std::pair<obstruction_free_dictionary::bucket*, obstruction_free_dictionary::bucket> obstruction_free_dictionary::read_bucket(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
versioned<bucket_state> state;
versioned<bucket_state> later_state;
versioned<unsigned int> value;
versioned<unsigned int> copy;
unsigned int bkt_key;
do
{
state = bucket_at(h, i)->state.load(std::memory_order_acquire);
bkt_key = bucket_at(h, i)->key.load(std::memory_order_acquire);
if (bkt_key != key)
{
break;
}
if ((state.value() == busy) || (state.value() == inserting) || (state.value() == empty))
{
break;
}
value = bucket_at(h, i)->value.load(std::memory_order_acquire);
copy = bucket_at(h, i)->copy.load(std::memory_order_acquire);
later_state = bucket_at(h, i)->state.load(std::memory_order_relaxed);
}
while (!(state == later_state));
if (bkt_key == key)
{
if ((state.value() == member) || (state.value() == updating))
{
return std::make_pair(bucket_at(h, i), bucket(key, value, copy, state));
}
}
}
return std::make_pair(nullptr, bucket());
}
std::pair<bool, unsigned int> obstruction_free_dictionary::lookup(unsigned int key)
{
std::pair<bucket*, bucket> bkt = read_bucket(key);
if (std::get<0>(bkt))
{
auto bkt_at = std::get<1>(bkt);
if (bkt_at.state.load(std::memory_order_relaxed).value() == member)
{
return std::make_pair(true, bkt_at.value.load(std::memory_order_relaxed).value());
}
else if (bkt_at.state.load(std::memory_order_relaxed).value() == updating)
{
return std::make_pair(true, bkt_at.copy.load(std::memory_order_relaxed).value());
}
}
return std::make_pair(false, 0);
}
bool obstruction_free_dictionary::erase(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
while (true)
{
auto* bkt_at = bucket_at(h, i);
auto state = bkt_at->state.load(std::memory_order_acquire);
auto bkt_key = bkt_at->key.load(std::memory_order_acquire);
if (((state.value() == member) || (state.value() == updating)) && (bkt_key == key))
{
if (std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &state, versioned<bucket_state>(state.version(), busy), std::memory_order_release, std::memory_order_acquire))
{
conditionally_lower_bound(h, i);
bkt_at->state.store(versioned<bucket_state>(state.version()+1, empty), std::memory_order_release);
return true;
}
// Some other operation (delete/update) got in our way -- try again
continue;
}
// No match: try another bucket
break;
}
}
return false;
}
void obstruction_free_dictionary::set(unsigned int key, unsigned int value)
{
while (true)
{
bool aborted = false;
std::pair<bucket*, bucket> bkt = read_bucket(key);
if (auto* bkt_at = std::get<0>(bkt))
{
// Update
auto bkt_value = std::get<1>(bkt);
auto state = bkt_value.state.load(std::memory_order_relaxed);
if (state.value() == member)
{
// Copy value to copy
auto old_copy = bkt_value.copy.load();
if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->copy, &old_copy, bkt_value.value.load(std::memory_order_relaxed), std::memory_order_release, std::memory_order_relaxed))
{
// Failed to copy -- another updater is present: abort
continue;
}
}
auto new_state = versioned<bucket_state>(state.version() + 1, updating);
if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &state, new_state, std::memory_order_release, std::memory_order_relaxed))
{
// Status modified: abort
continue;
}
// Ensure that ALL the previous happened before modifying the value
std::atomic_thread_fence(std::memory_order_acquire);
// Update the value
auto old_value = bkt_value.value.load(std::memory_order_relaxed);
if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->value, &old_value, versioned<unsigned int>(state.version() + 1, value), std::memory_order_relaxed, std::memory_order_relaxed))
{
// Value modified: abort
continue;
}
// Move back to member status
if (std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &new_state, versioned<bucket_state>(state.version() + 1, member), std::memory_order_release, std::memory_order_relaxed))
{
return;
}
}
else
{
// Insert
unsigned int h = hash(key);
int i = -1;
unsigned int version;
versioned<bucket_state> old_state;
versioned<bucket_state> new_state;
do
{
if (++i > size)
{
throw "Table full";
}
version = bucket_at(h, i)->state.load(std::memory_order_acquire).version();
old_state = versioned<bucket_state>(version, empty);
new_state = versioned<bucket_state>(version, busy);
}
while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->state, &old_state, new_state, std::memory_order_release, std::memory_order_relaxed));
unsigned int new_version = version+1;
bucket_at(h, i)->key.store(key, std::memory_order_relaxed);
bucket_at(h, i)->value.store(versioned<unsigned int>(new_version, value), std::memory_order_relaxed);
versioned<bucket_state> inserting_state;
do
{
inserting_state = versioned<bucket_state>(new_version, inserting);
bucket_at(h, i)->state.store(inserting_state, std::memory_order_release);
conditionally_raise_bound(h, i);
auto max = get_probe_bound(h);
for (unsigned int j = 0; j <= max; ++j)
{
if (j != i)
{
auto* bkt_at = bucket_at(h, j);
unsigned int bkt_key;
do
{
old_state = bkt_at->state.load(std::memory_order_acquire);
bkt_key = bkt_at->key.load(std::memory_order_acquire);
if ((bkt_key != key) || (old_state.value() == busy) || (old_state.value() == empty))
{
break;
}
new_state = bkt_at->state.load(std::memory_order_relaxed);
}
while (!(old_state == new_state));
if (bkt_key == key)
{
if (old_state.value() == inserting)
{
auto j_insert = versioned<bucket_state>(old_state.version(), inserting);
std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &j_insert, versioned<bucket_state>(old_state.version(), busy), std::memory_order_release, std::memory_order_relaxed);
}
else if ((old_state.value() == member) || (old_state.value() == updating))
{
bucket_at(h, i)->state.store(versioned<bucket_state>(version, busy));
conditionally_lower_bound(h, i);
bucket_at(h, i)->state.store(versioned<bucket_state>(version, empty));
aborted = true;
break;
}
}
}
}
if (aborted)
{
break;
}
}
while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->state, &inserting_state, versioned<bucket_state>(new_version, member), std::memory_order_release, std::memory_order_relaxed));
if (!aborted)
{
return;
}
}
}
}
}
| 46.88 | 309 | 0.539676 | cconklin |
a2d06373c54b5876208d9a6ef81c7f4ae347e232 | 1,944 | cpp | C++ | algoritma-dan-struktur-data/linked_list.cpp | kodeaqua/script-praktikum | 807000b053ff2e0765ee28f7a5decb676131238d | [
"MIT"
] | 3 | 2021-12-25T06:08:42.000Z | 2022-01-04T01:22:45.000Z | algoritma-dan-struktur-data/linked_list.cpp | kodeaqua/script-praktikum | 807000b053ff2e0765ee28f7a5decb676131238d | [
"MIT"
] | 3 | 2022-01-04T05:09:06.000Z | 2022-03-10T07:33:41.000Z | algoritma-dan-struktur-data/linked_list.cpp | kodeaqua/script-praktikum | 807000b053ff2e0765ee28f7a5decb676131238d | [
"MIT"
] | 12 | 2021-12-04T12:28:41.000Z | 2022-03-31T02:29:21.000Z | /*
Praktikum Struktur Data
Laboratorium Komputer
Universitas Pakuan
2022
*/
#include <iostream>
using namespace std;
struct Node {
string nama;
Node* next;
};
void print(Node* head) {
while (head != NULL) {
cout << head->nama << "->";
head = head->next;
}
cout << endl << endl;
}
int main() {
cout << " >>> CONTOH LINKED LIST <<<" << endl << endl;
Node* node1 = NULL;
Node* node2 = NULL;
Node* node3 = NULL;
// Membuat 3 node
node1 = new Node();
node2 = new Node();
node3 = new Node();
// Menginputkan nilai ke dalam node
node1->nama = "Fahmi";
node2->nama = "Noor";
node3->nama = "Fiqri";
// Sambungkan node-node
node1->next = node2;
node2->next = node3;
node3->next = NULL;
// --- menampilkan linked list awal
cout << "Linked List Awal" << endl;
print(node1);
// --- menambahkan elemen pada akhir linked list
Node* node4 = new Node();
node4->nama = "Fauzan";
node3->next = node4;
cout << "Menambahkan elemen pada akhir linked list" << endl;
print(node1);
// --- menambahkan elemen pada awal linked list
Node* node0 = new Node();
node0->nama = "Adam";
node0->next = node1;
cout << "Menambahkan elemen pada awal linked list" << endl;
print(node0);
// --- menambahkan elemen setelah elemen kedua pada linked list
Node* node12 = new Node();
node12->nama = "Reyhan";
node12->next = node2;
node1->next = node12;
cout << "Menambahkan elemen pada awal linked list" << endl;
print(node0);
// -- mengambil elemen ke-i pada linked list
cout << "Mengambil elemen ke-2 pada linked list" << endl;
string nilai_dicari;
Node* nodeDicari = node0;
for (auto i = 0; i < 1; i++) {
nodeDicari = nodeDicari->next;
};
cout << nodeDicari->nama << endl << endl;
// --- menghapus elemen pada akhir linked list
node3->next = NULL;
cout << "Menghapus elemen pada akhir linked list" << endl;
print(node0);
return 0;
}
| 20.25 | 65 | 0.618827 | kodeaqua |
a2d2627dae9849dea59e2d46467e2478af70ee31 | 1,589 | cc | C++ | src/orthog/CLP.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/orthog/CLP.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/orthog/CLP.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*-----------------------------------//
/**
* @file CLP.cc
* @brief CLP member definitions
* @note Copyright (C) 2013 Jeremy Roberts
*/
//----------------------------------------------------------------------------//
#include "CLP.hh"
#include "utilities/DBC.hh"
#ifdef DETRAN_ENABLE_BOOST
#include <boost/math/special_functions/legendre.hpp>
#endif
namespace detran_orthog
{
//----------------------------------------------------------------------------//
CLP::CLP(const Parameters &p)
: ContinuousOrthogonalBasis(p)
{
#ifndef DETRAN_ENABLE_BOOST
THROW("CLP needs boost to be enabled.");
#else
// Allocate the basis matrix
d_basis = new callow::MatrixDense(d_size, d_order + 1, 0.0);
// Allocate the normalization array
d_a = Vector::Create(d_order + 1, 0.0);
// The weights are just the qw's.
double L = d_upper_bound - d_lower_bound;
for (size_t i = 0; i < d_w->size(); ++i)
{
d_x[i] = 2.0*(d_x[i] - d_lower_bound)/L - 1.0;
(*d_w)[i] = d_qw[i];
}
// Build the basis
for (size_t l = 0; l <= d_order; ++l)
{
for (size_t i = 0; i < d_size; ++i)
{
(*d_basis)(i, l) = boost::math::legendre_p(l, d_x[i]);
}
// Inverse of normalization coefficient.
(*d_a)[l] = (2.0 * l + 1.0) / 2.0;
}
//d_orthonormal = true;
//compute_a();
#endif
}
} // end namespace detran_orthog
//----------------------------------------------------------------------------//
// end of file CLP.cc
//----------------------------------------------------------------------------//
| 26.04918 | 80 | 0.458779 | baklanovp |
a2d287905820c7c2c0439ca043d8006003de8419 | 4,004 | cpp | C++ | RoiSelector/RoiSelector.cpp | valerydol/drone_vision | ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71 | [
"MIT"
] | 3 | 2019-11-19T13:50:18.000Z | 2020-01-15T11:50:22.000Z | RoiSelector/RoiSelector.cpp | valerydol/drone_vision | ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71 | [
"MIT"
] | null | null | null | RoiSelector/RoiSelector.cpp | valerydol/drone_vision | ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71 | [
"MIT"
] | null | null | null | #include "RoiSelector.h"
RoiSelector::RoiSelector(float _offset_roi_x, float _offset_roi_y, float _width_roi_x, float _height_roi_y, bool _isEmptyFlag)
: offset_roi_x(_offset_roi_x), offset_roi_y(_offset_roi_y), width_roi_x(_width_roi_x), height_roi_y(_height_roi_y), isEmptyFlag(true), roiNotCroped(), roiCroped()
{
}
RoiSelector::~RoiSelector()
{
}
//if ROI was detected?
//step B.0
bool RoiSelector::isEmpty()
{
return isEmptyFlag;
}
//select ROI with new data and crope
//step A.3
void RoiSelector::cropeNewROI(Mat &src, Mat &dstNotCroped, Mat &dstCroped)
{
// Define the roi
Rect roi((int)getOffsetRoi_X(), (int)getOffsetRoi_Y(), (int)getRoiWidth_X(), (int)getRoiHeight_Y());
// Crop clone
dstCroped = src(roi);
dstNotCroped = src.clone();
//copy croped roi
roiCroped = dstCroped.clone();
//copy src roi
roiNotCroped = src.clone();
//change isEmptyFlag
isEmptyFlag = false;
}
//set new ROI offsets , new roi boarder sizes
//where is X / Y of start ROI
//step A.2.4
void RoiSelector:: setNewRoiOffsets(int src_cols_width, int src_rows_height, float &startOnX, float &startOnY)
{
setOffsetRoi_X((src_cols_width / 2) - (getRoiWidth_X() / 2.0F));
//setOffsetRoi_Y((src_rows_height / 2) - (getRoiHeight_Y() / 2));
setOffsetRoi_Y((src_rows_height ) - (getRoiHeight_Y())-15.0F);
startOnX = getOffsetRoi_X();
startOnY = getOffsetRoi_Y();
}
//calculate ROI Width Height
//do bigger
//step A.2.3
void RoiSelector::doBigger(int src_cols_width, int src_rows_height)
{
//check if we can do our ROI bigger
if (((getRoiWidth_X() + ROI_DELTA) < src_cols_width) && ((getRoiHeight_Y() + ROI_DELTA) < src_rows_height))
{
setRoiWidth_X((float)(getRoiWidth_X() + ROI_DELTA)); //set Width_X
setRoiHeight_Y((float)(getRoiHeight_Y() + ROI_DELTA));//set Height_Y
}
else//set max size
{
setRoiWidth_X((float)src_cols_width);//set Width_X
setRoiHeight_Y((float)src_rows_height);//set Height_Y
}
}
//calculate ROI Width Height
//do smaller
//step A.2.3
void RoiSelector::doSmaller(int src_cols_width, int src_rows_height)
{
//check if we can do our ROI smaller
if (((getRoiWidth_X() - ROI_DELTA) > ROI_MIN_SIZE_WIDTH) && ((getRoiHeight_Y() - ROI_DELTA) > ROI_MIN_SIZE_HEIGTH))
{
if (getRoiWidth_X() != src_cols_width)
{
setRoiWidth_X((float)(getRoiWidth_X() - ROI_DELTA)); //set Width_X
setRoiHeight_Y((float)(getRoiHeight_Y() - ROI_DELTA));//set Height_Y
}
else //if last roi.size equel src.size
{
//set width equels to height
setRoiWidth_X((float)src_rows_height);//set Width_X
setRoiHeight_Y((float)src_rows_height);//set Height_Y
}
}
else // we can`t do ROI SMALLER , set ROI_SIZE_X1
{
setRoiWidth_X((float)ROI_DEFAULT_SIZE_WIDTH);
setRoiHeight_Y((float)ROI_DEFAULT_SIZE_HEIGTH);
}
}
//we need calculate roi size or get DEFAULT_SIZE
//step A.2.2
void RoiSelector:: getNewRoiSize(const Mat &src, float &width_frame_cols, float &height_frame_rows, COMMAND roi_size)
{
int w = src.cols;
int h = src.rows;
if (roi_size == ROI_NEW)
{
setRoiWidth_X((float)ROI_DEFAULT_SIZE_WIDTH);
setRoiHeight_Y((float)ROI_DEFAULT_SIZE_HEIGTH);
}
else if ((roi_size == ROI_BIGGER) || (roi_size == ROI_SMALLER))
{
if (roi_size == ROI_BIGGER)
{
doBigger(w, h);
}
else
{
doSmaller(w, h);
}
}
width_frame_cols = getRoiWidth_X();
height_frame_rows = getRoiHeight_Y();
}
//return croped Mat
// Define the roi and Crop img to ROI new size
//step A.2
void RoiSelector::GetRoiFromImg(Mat &src, Mat &dstNotCroped , Mat &dstCroped, float &startOnX, float &startOnY, float &width_frame_cols, float &height_frame_rows, COMMAND roi_size)
{
//get new roi size
getNewRoiSize(src, width_frame_cols, height_frame_rows, roi_size);
//set start points for ROI
setNewRoiOffsets(src.cols, src.rows, startOnX, startOnY);
//crope ROI
cropeNewROI(src, dstNotCroped, dstCroped);
}
| 27.054054 | 181 | 0.697053 | valerydol |
a2d2afe1a5c2c4b5d9b78ae5898e3948814d9744 | 994 | cpp | C++ | TCPsrv/TCPsrv/main.cpp | yu-s/_code_bak | 08308f7c836d05a9c4d610def19fc1a3e7c6ecf4 | [
"MIT"
] | null | null | null | TCPsrv/TCPsrv/main.cpp | yu-s/_code_bak | 08308f7c836d05a9c4d610def19fc1a3e7c6ecf4 | [
"MIT"
] | null | null | null | TCPsrv/TCPsrv/main.cpp | yu-s/_code_bak | 08308f7c836d05a9c4d610def19fc1a3e7c6ecf4 | [
"MIT"
] | 1 | 2020-05-05T12:28:45.000Z | 2020-05-05T12:28:45.000Z |
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sockets = socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrsrv;
addrsrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrsrv.sin_family = AF_INET;
addrsrv.sin_port = htons(6666);
bind(sockets,(sockaddr*)&addrsrv,sizeof(SOCKADDR));
listen(sockets,5);
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while(true)
{
SOCKET sockcoen = accept(sockets,(SOCKADDR*)&addrClient,&len);
char sendbuf[100];
sprintf(sendbuf,"welcome %s to this",inet_ntoa(addrClient.sin_addr));
send(sockcoen,sendbuf,strlen(sendbuf)+1,0);
char recvbuf[100];
recv(sockcoen,recvbuf,100,0);
printf("%s\n",recvbuf);
closesocket(sockcoen);
}
} | 20.708333 | 71 | 0.690141 | yu-s |
a2d4de27027e955cb9a41693af9ab7a6f90c5a57 | 2,984 | cpp | C++ | samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp | mitchelsellers/iis-docs | 376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429 | [
"CC-BY-4.0",
"MIT"
] | 90 | 2017-06-13T19:56:04.000Z | 2022-03-15T16:42:09.000Z | samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp | mitchelsellers/iis-docs | 376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429 | [
"CC-BY-4.0",
"MIT"
] | 453 | 2017-05-22T18:00:05.000Z | 2022-03-30T21:07:55.000Z | samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp | mitchelsellers/iis-docs | 376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429 | [
"CC-BY-4.0",
"MIT"
] | 343 | 2017-05-26T08:57:30.000Z | 2022-03-25T23:05:04.000Z | // <Snippet1>
#define _WINSOCKAPI_
#include <windows.h>
#include <sal.h>
#include <httpserv.h>
// Create the module class.
class MyHttpModule : public CHttpModule
{
public:
REQUEST_NOTIFICATION_STATUS
OnMapRequestHandler(
IN IHttpContext * pHttpContext,
IN IMapHandlerProvider * pProvider
)
{
// Create an HRESULT to receive return values from methods.
HRESULT hr;
// Retrieve a pointer to the URL.
DWORD cchScriptName = 0;
PCWSTR pwszUrl = pHttpContext->GetScriptName(&cchScriptName);
// Test for an error.
if ((NULL != pwszUrl) && (cchScriptName>0))
{
// Compare the request URL to limit the module's scope.
if (0 == wcscmp(pwszUrl,L"/default.htm"))
{
// Create a buffer to contain the script name.
PCWSTR pszScriptName = L"/example/default.htm";
// Retrive the length of the script name.
cchScriptName = (DWORD) wcslen(pszScriptName);
// Specify the file name.
hr = pProvider->SetScriptName(pszScriptName,cchScriptName);
// Test for an error.
if (FAILED(hr))
{
// Specify the error condition to return.
pProvider->SetErrorStatus( hr );
// End additional processing.
return RQ_NOTIFICATION_FINISH_REQUEST;
}
}
}
// Return processing to the pipeline.
return RQ_NOTIFICATION_CONTINUE;
}
};
// Create the module's class factory.
class MyHttpModuleFactory : public IHttpModuleFactory
{
public:
HRESULT
GetHttpModule(
OUT CHttpModule ** ppModule,
IN IModuleAllocator * pAllocator
)
{
UNREFERENCED_PARAMETER( pAllocator );
// Create a new instance.
MyHttpModule * pModule = new MyHttpModule;
// Test for an error.
if (!pModule)
{
// Return an error if the factory cannot create the instance.
return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
}
else
{
// Return a pointer to the module.
*ppModule = pModule;
pModule = NULL;
// Return a success status.
return S_OK;
}
}
void Terminate()
{
// Remove the class from memory.
delete this;
}
};
// Create the module's exported registration function.
HRESULT
__stdcall
RegisterModule(
DWORD dwServerVersion,
IHttpModuleRegistrationInfo * pModuleInfo,
IHttpServer * pGlobalInfo
)
{
UNREFERENCED_PARAMETER( dwServerVersion );
UNREFERENCED_PARAMETER( pGlobalInfo );
// Set the request notifications and exit.
return pModuleInfo->SetRequestNotifications(
new MyHttpModuleFactory,
RQ_MAP_REQUEST_HANDLER,
0
);
}
// </Snippet1> | 26.882883 | 75 | 0.580764 | mitchelsellers |
a2d75b15fedfdb232f50064e81df8bd18c0dbed4 | 1,077 | cpp | C++ | Software/lib/motor.cpp | JiaxunHong/Smart-Pets-Feeder | 4204c669880377d7dc79d194f1d0e2a60c666e67 | [
"MIT"
] | 12 | 2021-04-10T16:03:04.000Z | 2021-04-27T08:14:59.000Z | Software/lib/motor.cpp | JiaxunHong/Smart-Pets-Feeder | 4204c669880377d7dc79d194f1d0e2a60c666e67 | [
"MIT"
] | 4 | 2021-04-15T11:33:45.000Z | 2021-04-18T07:02:23.000Z | Software/lib/motor.cpp | JiaxunHong/Smart-Pets-Feeder | 4204c669880377d7dc79d194f1d0e2a60c666e67 | [
"MIT"
] | 6 | 2021-04-10T16:03:36.000Z | 2021-04-19T12:07:51.000Z | #include "motor.h"
#include <iostream> //C++ Standard library
#include <wiringPi.h> //GPIO library
using namespace std; //Namespace Declarations
void motor::motor_init()
{
for(auto i:m)pinMode(i, OUTPUT); //Initialising stepper motor pins
}
void motor::motopa(int zf)
{
auto di=0;
int jnum = 0;
if(zf == 1)
{
while(1){
for(auto j=0;j<4;++j){
if(di==j)
digitalWrite(m[j], 1);
else
digitalWrite(m[j], 0);
}
di++;
if(di==4){di=0;jnum++;} //One set of pulses sent out
if(jnum>=128){return;} //512/2/2 = 128 90°
delay(2);
}
}
if(zf == 0)
{
di = 3;
while(1){
for(auto j=0;j<4;++j){
if(di==j)
digitalWrite(m[j], 1);
else
digitalWrite(m[j], 0);
}
di--;
if(di==-1){di=3;jnum++;}
if(jnum>=128){return;}
delay(2);
}
}
};
| 21.117647 | 70 | 0.410399 | JiaxunHong |
a2db34a0fc0974ffd62643604af63c4695bddcee | 3,890 | cpp | C++ | modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 734 | 2018-11-16T09:39:40.000Z | 2022-03-30T16:56:14.000Z | modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 100 | 2018-11-16T18:04:08.000Z | 2022-03-31T17:47:53.000Z | modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 123 | 2018-11-16T15:51:50.000Z | 2022-03-29T12:21:27.000Z | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
#pragma once
namespace tracktion_graph
{
#if GRAPH_UNIT_TESTS_PLAYHEADSTATE
//==============================================================================
//==============================================================================
class PlayHeadStateTests : public juce::UnitTest
{
public:
PlayHeadStateTests()
: juce::UnitTest ("PlayHeadStateTests", "tracktion_graph")
{
}
void runTest() override
{
constexpr int64_t blockSize = 44'100;
beginTest ("Loop edges");
{
PlayHead playHead;
PlayHeadState playHeadState (playHead);
playHead.play ({ 44'100, 176'400 }, true); // 1-4s
auto referenceRange = juce::Range<int64_t>::withStartAndLength (0, blockSize);
playHeadState.update (referenceRange); // This is reference samples
expect (! playHeadState.isContiguousWithPreviousBlock());
expect (playHeadState.didPlayheadJump());
expect (playHeadState.isFirstBlockOfLoop());
expect (! playHeadState.isLastBlockOfLoop());
referenceRange += blockSize;
playHead.setReferenceSampleRange (referenceRange);
playHeadState.update (referenceRange);
expect (playHeadState.isContiguousWithPreviousBlock());
expect (! playHeadState.didPlayheadJump());
expect (! playHeadState.isFirstBlockOfLoop());
expect (! playHeadState.isLastBlockOfLoop());
referenceRange += blockSize;
playHead.setReferenceSampleRange (referenceRange);
playHeadState.update (referenceRange);
expect (playHeadState.isContiguousWithPreviousBlock());
expect (! playHeadState.didPlayheadJump());
expect (! playHeadState.isFirstBlockOfLoop());
expect (playHeadState.isLastBlockOfLoop());
}
beginTest ("Not looping");
{
PlayHead playHead;
PlayHeadState playHeadState (playHead);
playHead.play ({ 44'100, 176'400 }, false); // 1-4s
auto referenceRange = juce::Range<int64_t>::withStartAndLength (0, blockSize);
playHeadState.update (referenceRange); // This is reference samples
expect (! playHeadState.isContiguousWithPreviousBlock());
expect (playHeadState.didPlayheadJump());
expect (! playHeadState.isFirstBlockOfLoop());
expect (! playHeadState.isLastBlockOfLoop());
referenceRange += blockSize;
playHead.setReferenceSampleRange (referenceRange);
playHeadState.update (referenceRange);
expect (playHeadState.isContiguousWithPreviousBlock());
expect (! playHeadState.didPlayheadJump());
expect (! playHeadState.isFirstBlockOfLoop());
expect (! playHeadState.isLastBlockOfLoop());
referenceRange += blockSize;
playHead.setReferenceSampleRange (referenceRange);
playHeadState.update (referenceRange);
expect (playHeadState.isContiguousWithPreviousBlock());
expect (! playHeadState.didPlayheadJump());
expect (! playHeadState.isFirstBlockOfLoop());
expect (! playHeadState.isLastBlockOfLoop());
}
}
};
static PlayHeadStateTests playHeadStateTests;
#endif
}
| 36.698113 | 90 | 0.554242 | jbloit |
a2e2dbd71bc519938ad5621593b4f95b42e4fa6d | 877 | hpp | C++ | paxos++/detail/util/conversion.hpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | 54 | 2015-02-09T11:46:30.000Z | 2021-08-13T14:08:52.000Z | paxos++/detail/util/conversion.hpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | null | null | null | paxos++/detail/util/conversion.hpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | 17 | 2015-01-13T03:18:49.000Z | 2022-03-23T02:20:57.000Z | /*!
Copyright (c) 2012, Leon Mergen, all rights reserved.
*/
#ifndef LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP
#define LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP
#include <string>
#include "debug.hpp"
namespace paxos { namespace detail { namespace util {
/*!
\brief Defines helper functions that convert by arrays to ints and vice versa.
*/
class conversion
{
public:
/*!
\brief Converts POD type to byte array (as string)
*/
template <typename T> static std::string
to_byte_array (
T input);
/*!
\brief Converts bytearray (as string) to POD type
\pre input.size () == sizeof (T)
*/
template <typename T> static T
from_byte_array (
std::string const & input);
private:
};
}; }; };
#include "conversion.inl"
#endif //! LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP
| 19.488889 | 81 | 0.641961 | armos-db |
a2ec6d3136d35858e38c4b358dfd0ba70819f809 | 8,355 | cpp | C++ | examples/auth/src/micro_http.cpp | kamaroly/yb-orm | b53987f6b316a4a2e7c23cb82525ad1570d107b7 | [
"MIT"
] | null | null | null | examples/auth/src/micro_http.cpp | kamaroly/yb-orm | b53987f6b316a4a2e7c23cb82525ad1570d107b7 | [
"MIT"
] | null | null | null | examples/auth/src/micro_http.cpp | kamaroly/yb-orm | b53987f6b316a4a2e7c23cb82525ad1570d107b7 | [
"MIT"
] | null | null | null | #include "micro_http.h"
#include <sstream>
#include <util/thread.h>
#include <util/utility.h>
#include <util/string_utils.h>
using namespace std;
using namespace Yb;
using namespace Yb::StrUtils;
HttpServerBase::HttpServerBase(int port, ILogger *root_logger,
const String &content_type, const String &bad_resp)
: port_(port)
, content_type_(content_type)
, bad_resp_(bad_resp)
, log_(root_logger->new_logger("http_serv").release())
{}
bool
HttpServerBase::send_response(TcpSocket &cl_sock, ILogger &logger,
int code, const string &desc, const string &body,
const String &cont_type)
{
try {
ostringstream out;
out << "HTTP/1.0 " << code << " " << desc
<< "\nContent-Type: " << NARROW(cont_type)
<< "\nContent-Length: " << body.size()
<< "\n\n" << body;
cl_sock.write(out.str());
cl_sock.close(true);
return true;
}
catch (const std::exception &ex) {
logger.error(string("exception: ") + ex.what());
}
return false;
}
void
HttpServerBase::process(HttpServerBase *server, SOCKET cl_s)
{
TcpSocket cl_sock(cl_s);
ILogger::Ptr logger = server->log_->new_logger("worker");
string bad_resp = NARROW(server->bad_resp_);
String cont_type_resp = server->content_type_;
// read and process request
try {
// read request header
string buf = cl_sock.readline();
logger->debug(buf);
int cont_len = -1;
String cont_type;
while (1) { // skip to request's body
string s = cl_sock.readline();
if (!s.size())
throw HttpParserError("process", "short read");
if (s == "\r\n" || s == "\n")
break;
logger->debug(s);
String s2 = WIDEN(s);
if (starts_with(str_to_upper(s2), _T("CONTENT-LENGTH: "))) {
try {
Strings parts;
split_str_by_chars(s2, _T(" "), parts, 2);
from_string(parts[1], cont_len);
}
catch (const std::exception &ex) {
logger->warning(
string("couldn't parse CONTENT-LENGTH: ") + ex.what());
}
}
if (starts_with(str_to_upper(s2), _T("CONTENT-TYPE: "))) {
try {
Strings parts;
split_str_by_chars(s2, _T(": "), parts, 2);
cont_type = trim_trailing_space(parts[1]);
}
catch (const std::exception &ex) {
logger->warning(
string("couldn't parse CONTENT-TYPE: ") + ex.what());
}
}
}
// parse request
StringDict req = parse_http(WIDEN(buf));
req[_T("&content-type")] = cont_type;
String method = req.get(_T("&method"));
if (method != _T("GET") && method != _T("POST")) {
logger->error("unsupported method \""
+ NARROW(method) + "\"");
send_response(cl_sock, *logger,
400, "Bad request", bad_resp, cont_type_resp);
}
else {
if (method == _T("POST") && cont_len > 0) {
String post_data = WIDEN(cl_sock.read(cont_len));
if (cont_type == _T("application/x-www-form-urlencoded"))
req.update(parse_params(post_data));
else
req[_T("&post-data")] = post_data;
}
String uri = req.get(_T("&uri"));
if (!server->has_uri(uri)) {
logger->error("URI " + NARROW(uri) + " not found!");
send_response(cl_sock, *logger,
404, "Not found", bad_resp, cont_type_resp);
}
else {
// handle the request
send_response(cl_sock, *logger, 200, "OK",
server->call_uri(uri, req), cont_type_resp);
}
}
}
catch (const SocketEx &ex) {
logger->error(string("socket error: ") + ex.what());
try {
send_response(cl_sock, *logger,
400, "Short read", bad_resp, cont_type_resp);
}
catch (const std::exception &ex2) {
logger->error(string("unable to send: ") + ex2.what());
}
}
catch (const HttpParserError &ex) {
logger->error(string("parser error: ") + ex.what());
try {
send_response(cl_sock, *logger,
400, "Bad request", bad_resp, cont_type_resp);
}
catch (const std::exception &ex2) {
logger->error(string("unable to send: ") + ex2.what());
}
}
catch (const std::exception &ex) {
logger->error(string("exception: ") + ex.what());
try {
send_response(cl_sock, *logger,
500, "Internal server error", bad_resp, cont_type_resp);
}
catch (const std::exception &ex2) {
logger->error(string("unable to send: ") + ex2.what());
}
}
cl_sock.close(true);
}
typedef void (*WorkerFunc)(HttpServerBase *, SOCKET);
class WorkerThread: public Thread {
HttpServerBase *serv_;
SOCKET s_;
WorkerFunc worker_;
void on_run() { worker_(serv_, s_); }
public:
WorkerThread(HttpServerBase *serv, SOCKET s, WorkerFunc worker)
: serv_(serv), s_(s), worker_(worker)
{}
};
void
HttpServerBase::serve()
{
TcpSocket::init_socket_lib();
log_->info("start server on port " + to_stdstring(port_));
sock_ = TcpSocket(TcpSocket::create());
sock_.bind(port_);
sock_.listen();
typedef SharedPtr<WorkerThread>::Type WorkerThreadPtr;
typedef std::vector<WorkerThreadPtr> Workers;
Workers workers;
while (1) {
// accept request
try {
string ip_addr;
int ip_port;
SOCKET cl_sock = sock_.accept(&ip_addr, &ip_port);
log_->info("accepted from " + ip_addr + ":" + to_stdstring(ip_port));
WorkerThreadPtr worker(new WorkerThread(
this, cl_sock, HttpServerBase::process));
workers.push_back(worker);
worker->start();
Workers workers_dead, workers_alive;
for (Workers::iterator i = workers.begin(); i != workers.end(); ++i)
if ((*i)->finished())
workers_dead.push_back(*i);
else
workers_alive.push_back(*i);
for (Workers::iterator i = workers_dead.begin(); i != workers_dead.end(); ++i) {
(*i)->terminate();
(*i)->wait();
}
workers.swap(workers_alive);
}
catch (const std::exception &ex) {
log_->error(string("exception: ") + ex.what());
}
}
}
StringDict parse_params(const String &msg)
{
StringDict params;
Strings param_parts;
split_str_by_chars(msg, _T("&"), param_parts);
for (size_t i = 0; i < param_parts.size(); ++i) {
Strings value_parts;
split_str_by_chars(param_parts[i], _T("="), value_parts, 2);
if (value_parts.size() < 1)
throw HttpParserError("parse_params", "value_parts.size() < 1");
String n = value_parts[0];
String v;
if (value_parts.size() == 2)
v = WIDEN(url_decode(value_parts[1]));
StringDict::iterator it = params.find(n);
if (it == params.end())
params[n] = v;
else
params[n] += v;
}
return params;
}
StringDict parse_http(const String &msg)
{
Strings head_parts;
split_str_by_chars(msg, _T(" \t\r\n"), head_parts);
if (head_parts.size() != 3)
throw HttpParserError("parse_http", "head_parts.size() != 3");
Strings uri_parts;
split_str_by_chars(head_parts[1], _T("?"), uri_parts, 2);
if (uri_parts.size() < 1)
throw HttpParserError("parse_http", "uri_parts.size() < 1");
StringDict params;
if (uri_parts.size() == 2)
params = parse_params(uri_parts[1]);
params[_T("&method")] = head_parts[0];
params[_T("&version")] = head_parts[2];
params[_T("&uri")] = uri_parts[0];
return params;
}
// vim:ts=4:sts=4:sw=4:et:
| 34.102041 | 92 | 0.529982 | kamaroly |
a2ee52976e7071314a16371f9be22822de6cace6 | 3,357 | cpp | C++ | src/ResourceManagement/MeshLoader.cpp | Ekozmaster/DwarfQuest | 02b0406b1796093a6d55ba49fa42873cfba2e6ba | [
"MIT"
] | null | null | null | src/ResourceManagement/MeshLoader.cpp | Ekozmaster/DwarfQuest | 02b0406b1796093a6d55ba49fa42873cfba2e6ba | [
"MIT"
] | null | null | null | src/ResourceManagement/MeshLoader.cpp | Ekozmaster/DwarfQuest | 02b0406b1796093a6d55ba49fa42873cfba2e6ba | [
"MIT"
] | null | null | null | #include <string>
#include <glm/glm.hpp>
#include <vector>
#include <cstring>
#include <src/ResourceManagement/MeshLoader.h>
#include <src/Utils/Logger.h>
namespace Core {
Mesh* LoadMesh(const char* path) {
FILE* file = std::fopen(path, "r");
if (file == NULL) {
Logger::Error("LoadMesh - Could not read file path: " + std::string(path));
return NULL;
}
std::vector<glm::vec3> vertices;
std::vector<unsigned int> verticesIndices;
std::vector<glm::vec3> normals;
std::vector<unsigned int> normalsIndices;
std::vector<glm::vec2> uvs;
std::vector<unsigned int> uvsIndices;
unsigned int indicesCount = 0;
char lineHeader[128];
int res = fscanf(file, "%s", lineHeader);
int scanfRes = 0;
while (res != EOF) {
if (strcmp(lineHeader, "v") == 0) { // POSITION
glm::vec3 vertex;
scanfRes = fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
vertices.push_back(vertex);
} else if (strcmp(lineHeader, "vt") == 0) { // UVs
glm::vec2 uv;
scanfRes = fscanf(file, "%f %f\n", &uv.x, &uv.y);
uvs.push_back(uv);
} else if (strcmp(lineHeader, "vn") == 0) { // NORMALS
glm::vec3 normal;
scanfRes = fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
normals.push_back(normal);
} else if (strcmp(lineHeader, "f") == 0) { // INDICES
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
scanfRes = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
verticesIndices.push_back(vertexIndex[0]);
verticesIndices.push_back(vertexIndex[1]);
verticesIndices.push_back(vertexIndex[2]);
normalsIndices.push_back(normalIndex[0]);
normalsIndices.push_back(normalIndex[1]);
normalsIndices.push_back(normalIndex[2]);
uvsIndices.push_back(uvIndex[0]);
uvsIndices.push_back(uvIndex[1]);
uvsIndices.push_back(uvIndex[2]);
indicesCount += 3;
}
res = fscanf(file, "%s", lineHeader);
}
std::fclose(file);
// TODO: This method makes unnecessary copies of vertices even though they're being shared among multiple triangles.
Vertex* finalMesh = new Vertex[verticesIndices.size()];
for (unsigned int i = 0; i < verticesIndices.size(); i++) {
unsigned int vertexIndex = verticesIndices[i] - 1;
finalMesh[i].position = vertices[verticesIndices[i] - 1];
finalMesh[i].normal = normals[normalsIndices[i] - 1];
finalMesh[i].uv = uvs[uvsIndices[i] - 1];
finalMesh[i].color = glm::vec3(1.0);
}
for (unsigned int i = 0; i < verticesIndices.size(); i++) verticesIndices[i] = i;
Mesh* mesh = new Mesh();
mesh->Create((GLfloat*)finalMesh, verticesIndices.size(), &verticesIndices[0], verticesIndices.size());
delete[] finalMesh;
return mesh;
}
}
| 41.9625 | 213 | 0.554662 | Ekozmaster |
a2f04173536c35eb07af20d35cdd94248896bc71 | 19,485 | hpp | C++ | src/io/filtered_sequence_iterator.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 16 | 2016-06-07T22:12:02.000Z | 2021-12-15T12:40:52.000Z | src/io/filtered_sequence_iterator.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 1 | 2017-11-13T20:59:33.000Z | 2018-12-14T16:40:01.000Z | src/io/filtered_sequence_iterator.hpp | tcpan/bliss | 0062fe91fdeef66fce4d1e897c15318241130277 | [
"Apache-2.0"
] | 7 | 2016-08-19T21:31:41.000Z | 2021-12-19T14:58:45.000Z | /*
* Copyright 2015 Georgia Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file filtered_sequence_iterator.hpp
* @ingroup io
* @author Tony Pan <tpan7@gatech.edu>
* @date Feb 5, 2014
* @brief Contains an iterator for traversing a sequence data, record by record, a FASTQ format specific parser for use by the iterator,
* Sequence Id datatype definition, and 2 sequence types (with and without quality score iterators)
*
*
*/
#ifndef Filtered_SequencesIterator_HPP_
#define Filtered_SequencesIterator_HPP_
// C includes
#include "io/sequence_iterator.hpp"
#include "iterators/filter_iterator.hpp"
#include "io/fastq_loader.hpp"
#include "io/file_loader.hpp"
#include <algorithm>
namespace bliss
{
namespace io
{
/**
* @class bliss::io::FilteredSequencesIterator
* @brief Iterator for parsing and traversing a block of data to access individual sequence records (of some file format), filtered by a user supplied predicate.
* @details This is a convenience class that allows sequence records to be filtered on the fly based on a user supplied predicate function
* The predicate can be used to detect presence of "N" character, or to keep only high quality reads.
* Sequences that satisfies the predicate (returns true) are passed through.
*
* Predicate should have operation with input parameter <sequenceType>
*
* @note this iterator is not a random access or bidirectional iterator, as traversing in reverse is not implemented.
*
* @tparam Iterator Base iterator type to be parsed into sequences
* @tparam SeqParser Functoid type to parse data pointed by Iterator into sequence objects..
* @tparam SequenceType Sequence Type. replaceable as long as it supports Quality if SeqParser requires it.
*/
template<typename Iterator, template <typename> class SeqParser, typename Predicate>
class FilteredSequencesIterator : public ::bliss::iterator::filter_iterator<
Predicate,
::bliss::io::SequencesIterator<Iterator, SeqParser> >
{
// TODO: for long sequence FASTA file, this likely will NOT behave correctly.
static_assert(!std::is_same<SeqParser<Iterator>, ::bliss::io::BaseFileParser<Iterator>>::value, "SplitSequencesIterator currently works only with FASTQ and FASTA files where sequences are defined." );
protected:
using SeqIterType = ::bliss::io::SequencesIterator<Iterator, SeqParser>;
using FilterIterType = ::bliss::iterator::filter_iterator<Predicate, SeqIterType>;
public:
using iterator_category = typename SeqIterType::iterator_category;
using value_type = typename SeqIterType::value_type;
using difference_type = typename SeqIterType::difference_type;
using pointer = typename SeqIterType::pointer;
using reference = typename SeqIterType::reference;
/**
* @brief constructor, initializes with a start and end. this represents the start of the output iterator
* @details at construction, the internal _curr, _next iterators are set to the input start iterator, and _end is set to the input end.
* then immediately the first record is parsed, with output populated with the first entry and next pointer advanced.
*
* @param f parser functoid for parsing the data.
* @param start beginning of the data to be parsed
* @param end end of the data to be parsed.
* @param _range the Range associated with the start and end of the source data. coordinates relative to the file being processed.
*/
explicit FilteredSequencesIterator(const SeqParser<Iterator> & f,
Iterator start,
Iterator end,
const size_t &_offset,
const Predicate & pred = Predicate())
: FilterIterType(pred, SeqIterType(f, start, end, _offset), SeqIterType(end)) {};
/**
* @brief constructor, initializes with only the end. this represents the end of the output iterator.
* @details at construction, the internal _curr, _next, and _end iterators are set to the input end iterator.
* this instance therefore does not traverse and only serves as marker for comparing to the traversing FilteredSequencesIterator.
* @param end end of the data to be parsed.
*/
explicit FilteredSequencesIterator(Iterator end,
const Predicate & pred = Predicate())
: FilterIterType(pred, SeqIterType(end)) {}
/**
* @brief default copy constructor
* @param Other The FilteredSequencesIterator to copy from
*/
FilteredSequencesIterator(const FilteredSequencesIterator& Other)
: FilterIterType(Other) {}
/**
* @brief default copy assignment operator
* @param Other The FilteredSequencesIterator to copy from
* @return modified copy of self.
*/
FilteredSequencesIterator& operator=(const FilteredSequencesIterator& Other)
{
this->FilterIterType::operator=(Other);
return *this;
}
/**
* @brief default copy constructor
* @param Other The FilteredSequencesIterator to copy from
*/
FilteredSequencesIterator(FilteredSequencesIterator && Other)
: FilterIterType(::std::forward<FilteredSequencesIterator>(Other)) {}
/**
* @brief default copy assignment operator
* @param Other The FilteredSequencesIterator to copy from
* @return modified copy of self.
*/
FilteredSequencesIterator& operator=(FilteredSequencesIterator && Other)
{
this->FilterIterType::operator=(::std::forward<FilteredSequencesIterator>(Other));
return *this;
}
/// default constructor deleted.
FilteredSequencesIterator() = default;
};
/**
* @class bliss::io::SequenceNPredicate
* @brief given a sequence, determines if it DOES NOT contain N.
*/
struct NSequenceFilter {
template <typename SEQ>
bool operator()(SEQ const & x) {
// scan through x to look for N.
return ::std::find(x.seq_begin, x.seq_end, 'N') == x.seq_end;
}
};
template <typename Iterator, template <typename> class SeqParser>
using NFilterSequencesIterator = bliss::io::FilteredSequencesIterator<Iterator, SeqParser, bliss::io::NSequenceFilter>;
/**
* @class bliss::io::SplitSequencesIterator
* @brief Iterator for parsing and traversing a block of data to access individual sequence records (of some file format), split when predicate fails.
* @details for each sequence, scan with predicate. when predicate fails, split the sequence, and continue on.
* EFFECTIVELY BREAKS THE SEQUENCE INTO PARTS WHERE PREDICATE FAILS.
*
* @note this iterator is a forward iterator only (for now).
*
* @tparam Iterator Base iterator type to be parsed into sequences
* @tparam SeqParser Functoid type to parse data pointed by Iterator into sequence objects..
* @tparam SequenceType Sequence Type. replaceable as long as it supports Quality if SeqParser requires it.
*/
template<typename Iterator, template <typename> class SeqParser, typename Predicate>
class SplitSequencesIterator : public ::std::iterator<
typename ::std::conditional<
::std::is_same<typename ::std::iterator_traits<Iterator>::iterator_category,
::std::input_iterator_tag>::value,
::std::input_iterator_tag,
::std::forward_iterator_tag>::type,
typename SeqParser<Iterator>::SequenceType,
typename std::iterator_traits<Iterator>::difference_type
>
{
static_assert(!std::is_same<SeqParser<Iterator>, ::bliss::io::BaseFileParser<Iterator>>::value, "SplitSequencesIterator currently works only with FASTQ and FASTA files where sequences are defined." );
protected:
/// predicate function
Predicate pred;
/// internal sequence iterator type
using SeqIterType = ::bliss::io::SequencesIterator<Iterator, SeqParser>;
/// current position
SeqIterType _curr;
/// max (end) position
SeqIterType _end;
/// cache of the current result to return
typename SeqParser<Iterator>::SequenceType seq;
/// cache of the next result to check
typename SeqParser<Iterator>::SequenceType next;
/// get next candidate sequence.
void get_next() {
// repeatedly get a valid seq. seq should not be "empty", and _curr should not be at end.
while ((_curr != _end) && (next.seq_begin == next.seq_end)) {
// move to next position.
++_curr;
// get the next sequence if curr is not at end.
if (_curr != _end) next = *_curr;
}
}
/// splits a sequence based on predicate on chars.
void split_seq() {
// first copy
// leave the quality score as is. traversal is confined by seq_begin/seq_end.
seq = next;
// std::cout << "RAW SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl;
// std::cout << "RAW NEXT " << next << " len " << std::distance(next.seq_begin, next.seq_end) << std::endl;
// find the beginning of valid.
seq.seq_begin = std::find_if(next.seq_begin, next.seq_end, pred);
// std::cout << "first SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl;
// find the end of the valid range
seq.seq_end = std::find_if_not(seq.seq_begin, next.seq_end, pred);
// std::cout << "second SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl;
// now update the next seq object.
next.seq_begin_offset += std::distance(next.seq_begin, seq.seq_end);
next.seq_begin = seq.seq_end;
// std::cout << "SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl;
// std::cout << "NEXT " << next << " len " << std::distance(next.seq_begin, next.seq_end) << std::endl;
}
public:
using iterator_category = typename SeqIterType::iterator_category;
using value_type = typename SeqIterType::value_type;
using difference_type = typename SeqIterType::difference_type;
using pointer = typename SeqIterType::pointer;
using reference = typename SeqIterType::reference;
/**
* @brief constructor, initializes with a start and end. this represents the start of the output iterator
* @details at construction, the internal _curr, _next iterators are set to the input start iterator, and _end is set to the input end.
* then immediately the first record is parsed, with output populated with the first entry and next pointer advanced.
*
* @param f parser functoid for parsing the data.
* @param start beginning of the data to be parsed
* @param end end of the data to be parsed.
* @param _range the Range associated with the start and end of the source data. coordinates relative to the file being processed.
*/
explicit SplitSequencesIterator(const SeqParser<Iterator> & f,
Iterator start,
Iterator end, const size_t &_offset,
const Predicate & _pred = Predicate())
: pred(_pred), _curr(f, start, end, _offset), _end(end) {
// first initialize one.
if (_curr != _end) next = *_curr;
// this would not actually increment unless next is empty, but it will split seq.
this->operator++();
};
/**
* @brief constructor, initializes with only the end. this represents the end of the output iterator.
* @details at construction, the internal _curr, _next, and _end iterators are set to the input end iterator.
* this instance therefore does not traverse and only serves as marker for comparing to the traversing SplitSequencesIterator.
* @param end end of the data to be parsed.
*/
explicit SplitSequencesIterator(Iterator end,
const Predicate & _pred = Predicate())
: pred(_pred), _curr(end), _end(end) {}
/**
* @brief default copy constructor
* @param Other The SplitSequencesIterator to copy from
*/
SplitSequencesIterator(const SplitSequencesIterator& Other)
: pred(Other.pred), _curr(Other._curr), _end(Other._end),
seq(Other.seq), next(Other.next) {}
/**
* @brief default copy assignment operator
* @param Other The SplitSequencesIterator to copy from
* @return modified copy of self.
*/
SplitSequencesIterator& operator=(const SplitSequencesIterator& Other)
{
pred = Other.pred;
_curr = Other._curr;
_end = Other._end;
seq = Other.seq;
next = Other.next;
return *this;
}
/**
* @brief default copy constructor
* @param Other The SplitSequencesIterator to copy from
*/
SplitSequencesIterator(SplitSequencesIterator && Other)
: pred(::std::move(Other.pred)),
_curr(::std::move(Other._curr)), _end(::std::move(Other._end)),
seq(::std::move(Other.seq)), next(::std::move(Other.next)) {}
/**
* @brief default copy assignment operator
* @param Other The SplitSequencesIterator to copy from
* @return modified copy of self.
*/
SplitSequencesIterator& operator=(SplitSequencesIterator && Other)
{
pred = std::move(Other.pred );
_curr = std::move(Other._curr);
_end = std::move(Other._end );
seq = std::move(Other.seq );
next = std::move(Other.next );
return *this;
}
/// default constructor deleted.
SplitSequencesIterator() = default;
/**
* @brief iterator's pre increment operation
* @details to increment, the class uses the parser functoid to parse and traverse the input iterator
* At the end of the traversal, a FASTQ sequence record has been made and is kept in the parser functoid
* as state variable, and the input iterator has advanced to where parsing would start for the next record.
* The corresponding starting of the current record is saved as _curr iterator.
*
* conversely, to get the starting position of the next record, we need to parse the current record.
*
* @note for end iterator, because _curr and _end are both pointing to the input's end, "increment" does not do anything.
* @return self, updated with internal position.
*/
SplitSequencesIterator &operator++()
{
// TODO get the next, and apply the predicate.
this->get_next();
// split if not empty
if ((_curr != _end) && (next.seq_begin != next.seq_end)) this->split_seq();
//== states updated. return self.
return *this;
}
/**
* @brief iterator's post increment operation
* @details to increment, the class uses the parser functoid to parse and traverse the input iterator
* At the end of the traversal, a FASTQ sequence record has been made and is kept in the parser functoid
* as state variable, and the input iterator has advanced to where parsing would start for the next record.
* The corresponding starting of the current record is saved as _curr iterator.
*
* conversely, to get the starting position of the next record, we need to parse the current record.
*
* @note for end iterator, because _curr and _end are both pointing to the input's end, "increment" does not do anything.
* @param unnamed
* @return copy of self incremented.
*/
SplitSequencesIterator operator++(int)
{
SplitSequencesIterator output(*this);
this->operator++();
return output;
}
/**
* @brief comparison operator.
* @details compares the underlying base iterator positions.
* @param rhs the SequenceIterator to compare to.
* @return true if this and rhs SequenceIterators match.
*/
bool operator==(const SplitSequencesIterator& rhs) const
{
return (_curr == rhs._curr) && ((_curr == _end) ||
(seq.seq_begin == rhs.seq.seq_begin));
}
/**
* @brief comparison operator.
* @details compares the underlying base iterator positions.
* @param rhs the SequenceIterator to compare to.
* @return true if this and rhs SequenceIterators do not match.
*/
bool operator!=(const SplitSequencesIterator& rhs) const
{
return !(this->operator==(rhs));
}
/**
* @brief dereference operator
* @return a const reference to the cached sequence object
*/
typename SeqParser<Iterator>::SequenceType & operator*()
{
return seq;
}
/**
* @brief pointer dereference operator
* @return a const reference to the cached sequence object
*/
typename SeqParser<Iterator>::SequenceType *operator->() {
return &seq;
}
};
/**
* @class bliss::io::NCharFilter
* @brief given a character, return true if it's NOT N.
*/
struct NCharFilter {
template <typename T>
bool operator()(T const & x) {
// scan through x to look for NOT N
return (x != 'N') && (x != 'n');
}
};
template <typename Iterator, template <typename> class SeqParser>
using NSplitSequencesIterator = bliss::io::SplitSequencesIterator<Iterator, SeqParser, bliss::io::NCharFilter>;
// TODO: filter for other characters.
// TODO: quality score filter for sequences.
} // iterator
} // bliss
#endif /* Filtered_SequencesIterator_HPP_ */
| 43.396437 | 208 | 0.618938 | tcpan |
a2f5096b80b4a1a241a0d41f4e16ea60c77b12f4 | 7,912 | cpp | C++ | snapshotable_allocator_impl.cpp | jyaif/snapshotable_allocator | 711dff8d6414265476bf8eb83eece563c0c183a8 | [
"MIT"
] | null | null | null | snapshotable_allocator_impl.cpp | jyaif/snapshotable_allocator | 711dff8d6414265476bf8eb83eece563c0c183a8 | [
"MIT"
] | null | null | null | snapshotable_allocator_impl.cpp | jyaif/snapshotable_allocator | 711dff8d6414265476bf8eb83eece563c0c183a8 | [
"MIT"
] | null | null | null | #include "application/memory/snapshotable_allocator_impl.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdlib>
#include "application/memory/aligned_alloc.h"
#include "application/memory/bit_vector.h"
#include "application/memory/fls.h"
#include "application/memory/memory_snapshot_impl.h"
#include "application/memory/scoped_allocator_usage.h"
#include "application/memory/snapshotable_allocator_impl.h"
namespace {
constexpr int extra_bytes_ = 16;
}
ItemBucket::ItemBucket(size_t item_size, size_t item_count)
: free_map_(item_count), item_size_(item_size), item_count_(item_count) {
// +16 to also store |free_slots_ptr_|.
// +4 would be enough, but then the alignment would be bad (we need 16 byte
// alignment).
// 16 bytes alignment is necessary because `movaps` can be generated, and
// crashes if the alignment is not 16 bytes.
//|free_slots_ptr_| is stored in the same contiguous bag of bytes
// to allow fast snapshoting/restoring of the free slot counter.
allocated_memory_ = static_cast<uint32_t*>(
AlignedAlloc(16, item_size * item_count + extra_bytes_));
free_slots_ptr_ = allocated_memory_;
memory_ = reinterpret_cast<uint8_t*>(allocated_memory_) + extra_bytes_;
*free_slots_ptr_ = static_cast<uint32_t>(item_count);
}
ItemBucket::~ItemBucket() {
AlignedFree(allocated_memory_);
}
void* ItemBucket::Allocate() {
if (!HasSpaceLeft()) {
assert(false);
return nullptr;
}
int allocated_index = free_map_.GetFirstBitSetAndClear();
(*free_slots_ptr_)--;
return memory_ + (allocated_index * item_size_);
}
bool ItemBucket::HasSpaceLeft() {
return (*free_slots_ptr_) > 0;
}
bool ItemBucket::IsUnused() {
return (*free_slots_ptr_) == item_count_;
}
void ItemBucket::Free(void* ptr) {
size_t offset_from_base = static_cast<uint8_t*>(ptr) - memory_;
offset_from_base /= item_size_;
assert(offset_from_base >= 0 && offset_from_base < item_count_);
free_map_.SetBit(offset_from_base);
(*free_slots_ptr_)++;
}
FixedSizeAllocator2::FixedSizeAllocator2(size_t item_size,
size_t item_per_bucket,
SnapshotableAllocatorImpl& memory)
: memory_(memory),
item_size_(item_size),
item_per_bucket_(item_per_bucket) {
ScopedAllocatorUsage sau;
first_bucket_ = new ItemBucket(item_size_, item_per_bucket_);
memory_.NewBucketWasCreated(*first_bucket_);
}
FixedSizeAllocator2::~FixedSizeAllocator2() {
ScopedAllocatorUsage sau;
delete first_bucket_;
}
void* FixedSizeAllocator2::Allocate() {
ItemBucket* bucket = first_bucket_;
while (!bucket->HasSpaceLeft()) {
ItemBucket* next = bucket->next_bucket_;
if (next == nullptr) {
ScopedAllocatorUsage sau;
next = new ItemBucket(item_size_, item_per_bucket_);
memory_.NewBucketWasCreated(*next);
bucket->next_bucket_ = next;
}
bucket = next;
}
return bucket->Allocate();
}
SnapshotableAllocatorImpl::SnapshotableAllocatorImpl(
size_t min_size_for_individual_copy)
: min_size_for_individual_copy_(min_size_for_individual_copy) {
ScopedAllocatorUsage sau;
std::array<std::pair<size_t, size_t>, 20> m = {{
{1, 32}, {2, 32}, {4, 32}, {8, 128}, {16, 256},
{32, 512}, {64, 1024}, {128, 512}, {256, 256}, {512, 128},
{1024, 32}, {2048, 16}, {4096, 4}, {8192, 4}, {16384, 4},
{32768, 4}, {65536, 4}, {131072, 4}, {262144, 2}, {524288, 2},
}};
// |reserve| is necessary to avoid copying the elements of |allocators_|
// when the vector is resized:
// Copying an allocator is very expensive.
allocators_.reserve(m.size());
for (auto const& p : m) {
allocators_.emplace_back(p.first, p.second, *this);
}
}
void* SnapshotableAllocatorImpl::Alloc(size_t size) {
auto ptr = InternalAlloc(size);
InitializeMemory(ptr);
return ptr;
}
void* SnapshotableAllocatorImpl::Realloc(void* ptr, size_t size) {
if (ptr == nullptr) {
return Alloc(size);
}
void* old_ptr = ptr;
ItemBucket* bucket = BucketForPointer(ptr);
size_t old_size = bucket->GetItemSize();
bucket->Free(ptr);
void* new_ptr = InternalAlloc(size);
if (new_ptr != old_ptr) {
if (old_size < size) {
memcpy(new_ptr, old_ptr, old_size);
}
if (old_size >= size) {
memcpy(new_ptr, old_ptr, size);
}
}
return new_ptr;
}
void SnapshotableAllocatorImpl::Free(void* ptr) {
if (!ptr) {
return;
}
BucketForPointer(ptr)->Free(ptr);
}
void SnapshotableAllocatorImpl::LoadMemoryFromSnapshot(
MemorySnapshot const& snapshot) {
MemorySnapshotImpl const& ms =
static_cast<MemorySnapshotImpl const&>(snapshot);
ms.RestoreEverything();
}
void SnapshotableAllocatorImpl::SaveMemoryIntoSnapshot(
MemorySnapshot& snapshot) {
MemorySnapshotImpl& ms = static_cast<MemorySnapshotImpl&>(snapshot);
ms.Clear();
int skipped_memory_ = 0;
for (AllocatorPositionInMemory& allocator_position : sorted_buckets_) {
auto bucket = allocator_position.bucket_;
ms.AppendData(bucket->free_map_.GetDataLocation(),
bucket->free_map_.GetDataLength());
if (bucket->IsUnused()) {
ms.AppendData(bucket->allocated_memory_, 4);
} else {
// Memory optimization where only the slots used in the buckets are
// copied, as opposed to the entire bucket.
// The lower the threshold, the more memory is saved.
// In practice, saves 50% memory with a size of 128.
if (bucket->GetItemSize() >= min_size_for_individual_copy_) {
const size_t count = bucket->GetItemCount();
ms.AppendData(bucket->allocated_memory_, extra_bytes_);
uint8_t* bucket_start_ =
reinterpret_cast<uint8_t*>(bucket->allocated_memory_);
bucket_start_ += extra_bytes_;
for (uint32_t index = 0; index < count; index++) {
if (!bucket->free_map_.GetBit(index)) {
ms.AppendData(bucket_start_, bucket->GetItemSize());
} else {
skipped_memory_ += bucket->GetItemSize();
}
bucket_start_ += bucket->GetItemSize();
}
} else {
ms.AppendData(
bucket->allocated_memory_,
(bucket->GetItemSize() * bucket->GetItemCount()) + extra_bytes_);
}
}
}
}
std::unique_ptr<MemorySnapshot> SnapshotableAllocatorImpl::NewEmptySnapshot() {
return std::make_unique<MemorySnapshotImpl>();
}
void SnapshotableAllocatorImpl::NewBucketWasCreated(ItemBucket& bucket) {
AllocatorPositionInMemory apim = {
bucket.memory_ + bucket.GetItemSize() * bucket.GetItemCount(), &bucket};
auto it =
std::upper_bound(sorted_buckets_.begin(), sorted_buckets_.end(), apim);
sorted_buckets_.insert(it, apim);
assert(std::is_sorted(sorted_buckets_.begin(), sorted_buckets_.end()));
}
void SnapshotableAllocatorImpl::SetMemoryInitializationStyle(
MemoryInitialization initialization_style) {
initialization_style_ = initialization_style;
}
ItemBucket* SnapshotableAllocatorImpl::BucketForPointer(void* ptr) {
AllocatorPositionInMemory apim = {ptr, nullptr};
auto it =
std::lower_bound(sorted_buckets_.begin(), sorted_buckets_.end(), apim);
if (it == sorted_buckets_.end()) {
assert(false);
}
return it->bucket_;
}
void* SnapshotableAllocatorImpl::InternalAlloc(size_t size) {
int index = FindLastBitSet(static_cast<int32_t>(size));
assert(index < allocators_.size());
return allocators_[index].Allocate();
}
void SnapshotableAllocatorImpl::InitializeMemory(void* ptr) {
switch (initialization_style_) {
case NONE:
break;
case ZERO:
memset(ptr, 0, BucketForPointer(ptr)->GetItemSize());
break;
case RANDOM: {
uint8_t* p = (uint8_t*)ptr;
size_t size = BucketForPointer(ptr)->GetItemSize();
for (size_t i = 0; i < size; i++) {
p[i] = rand() % 255;
}
break;
}
}
}
| 31.7751 | 79 | 0.687184 | jyaif |
a2f951cda23845319d2644ac4a63932f2e829017 | 507 | hpp | C++ | include/IteratorRecognition/Support/Utils/DebugInfo.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | null | null | null | include/IteratorRecognition/Support/Utils/DebugInfo.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | 6 | 2019-05-29T21:11:03.000Z | 2021-07-01T10:47:02.000Z | include/IteratorRecognition/Support/Utils/DebugInfo.hpp | robcasloz/IteratorRecognition | fa1a1e67c36cde3639ac40528228ae85e54e3b13 | [
"MIT"
] | 1 | 2019-05-13T11:55:39.000Z | 2019-05-13T11:55:39.000Z | //
//
//
#pragma once
#include "IteratorRecognition/Config.hpp"
#include <string>
// using std::string
#include <tuple>
// using std::make_tuple
namespace llvm {
class Loop;
class Instruction;
} // namespace llvm
namespace iteratorrecognition {
namespace dbg {
std::string extract(const llvm::Instruction &I);
using LoopDebugInfoT = std::tuple<unsigned, unsigned, std::string, std::string>;
LoopDebugInfoT extract(const llvm::Loop &CurLoop);
} // namespace dbg
} // namespace iteratorrecognition
| 15.84375 | 80 | 0.733728 | robcasloz |
a2f9a8c664abf121f5cb44e53e4638b5f11d0e6b | 340 | cpp | C++ | src/NBaseFunction.cpp | justinmann/sj | 24d0a75723b024f17de6dab9070979a4f1bf1a60 | [
"Apache-2.0"
] | 2 | 2017-01-04T02:27:10.000Z | 2017-01-22T05:36:41.000Z | src/NBaseFunction.cpp | justinmann/sj | 24d0a75723b024f17de6dab9070979a4f1bf1a60 | [
"Apache-2.0"
] | null | null | null | src/NBaseFunction.cpp | justinmann/sj | 24d0a75723b024f17de6dab9070979a4f1bf1a60 | [
"Apache-2.0"
] | 1 | 2020-06-15T12:17:26.000Z | 2020-06-15T12:17:26.000Z | #include <sjc.h>
FunctionParameter FunctionParameter::create(bool isDefaultValue, AssignOp op, shared_ptr<CVar> var) {
FunctionParameter param;
param.isDefaultValue = isDefaultValue;
param.op = op;
param.var = var;
return param;
}
void CBaseFunction::setHasThis() {
assert(name != "global");
hasThis = true;
} | 22.666667 | 101 | 0.694118 | justinmann |
a2f9fc84e6580004190ec17f39301b3897aa6803 | 209 | cpp | C++ | Engine/Graphics/ImGui_Window.cpp | Antd23rus/S2DE_DirectX11 | 4f729278e6c795f7d606afc70a292c6501b0cafd | [
"MIT"
] | null | null | null | Engine/Graphics/ImGui_Window.cpp | Antd23rus/S2DE_DirectX11 | 4f729278e6c795f7d606afc70a292c6501b0cafd | [
"MIT"
] | null | null | null | Engine/Graphics/ImGui_Window.cpp | Antd23rus/S2DE_DirectX11 | 4f729278e6c795f7d606afc70a292c6501b0cafd | [
"MIT"
] | 1 | 2021-09-06T08:30:20.000Z | 2021-09-06T08:30:20.000Z | #include "ImGui_Window.h"
namespace S2DE::Render
{
ImGui_Window::ImGui_Window()
: m_draw(false)
{
}
ImGui_Window::~ImGui_Window()
{
}
void ImGui_Window::ToggleDraw()
{
m_draw = !m_draw;
}
} | 10.45 | 32 | 0.650718 | Antd23rus |
0c06cb94f1791b3c77a1e2f28308eeb60d302d95 | 284 | cc | C++ | test/camera.cc | imkaywu/open3DCV | 33ef0507e565bce2ccff7409ff35a8970e6eed2d | [
"BSD-3-Clause"
] | 37 | 2018-07-30T15:34:29.000Z | 2022-01-10T22:50:39.000Z | test/camera.cc | imkaywu/open3DCV | 33ef0507e565bce2ccff7409ff35a8970e6eed2d | [
"BSD-3-Clause"
] | 1 | 2020-10-09T17:51:42.000Z | 2020-11-11T19:41:06.000Z | test/camera.cc | imkaywu/open3DCV | 33ef0507e565bce2ccff7409ff35a8970e6eed2d | [
"BSD-3-Clause"
] | 14 | 2017-12-03T15:24:01.000Z | 2021-09-16T02:13:31.000Z | //
// camera.cpp
// open3DCV_test
//
// Created by KaiWu on Jul/5/17.
// Copyright © 2017 KaiWu. All rights reserved.
//
#include <stdio.h>
#include "camera.h"
using namespace std;
using namespace open3DCV;
int main(int argc, const char * argv[]) {
return 0;
}
| 12.909091 | 48 | 0.630282 | imkaywu |
0c0ddeeabdb96e2f498a7e49b45488068edea2da | 7,651 | cpp | C++ | Fuji/Source/Drivers/PS2/MFInput_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 35 | 2015-01-19T22:07:48.000Z | 2022-02-21T22:17:53.000Z | Fuji/Source/Drivers/PS2/MFInput_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 1 | 2022-02-23T09:34:15.000Z | 2022-02-23T09:34:15.000Z | Fuji/Source/Drivers/PS2/MFInput_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 4 | 2015-05-11T03:31:35.000Z | 2018-09-27T04:55:57.000Z | #include "Fuji_Internal.h"
#if MF_INPUT == MF_DRIVER_PS2
#include "MFVector.h"
#include "MFInput_Internal.h"
#include "MFHeap.h"
#include "MFIni.h"
/*** Structure definitions ***/
/*** Globals ***/
int gGamepadCount = 0;
int gKeyboardCount = 0;
int gMouseCount = 0;
char gKeyState[256];
bool gExclusiveMouse = false;
float deadZone = 0.3f;
float mouseMultiplier = 1.0f;
static const char * const gPS2Buttons[] =
{
// PS2 controller enums
"X",
"Circle",
"Box",
"Triangle",
"L1",
"R1",
"L2",
"R2",
"Start",
"Select",
"L3",
"R3",
// general controller enums
"DPad Up",
"DPad Down",
"DPad Left",
"DPad Right",
"Left X-Axis",
"Left Y-Axis",
"Right X-Axis",
"Right Y-Axis"
};
/**** Platform Specific Functions ****/
#include <stdio.h>
#include <kernel.h>
#include <sifrpc.h>
#include <loadfile.h>
#include "libpad.h"
static char padBuf[256] __attribute__((aligned(64)));
static char actAlign[6];
static int actuators;
struct padButtonStatus buttons;
u32 new_pad;
// Using the X* variety of modules doesnt work for me, so I stick to the vanilla versions
#define ROM_PADMAN
static int
loadModules(void)
{
int ret;
#ifdef ROM_PADMAN
ret = SifLoadModule("rom0:SIO2MAN", 0, NULL);
#else
ret = SifLoadModule("rom0:XSIO2MAN", 0, NULL);
#endif
if (ret < 0)
{
MFDebug_Message(MFStr("sifLoadModule sio failed: %d", ret));
return -1;
}
#ifdef ROM_PADMAN
ret = SifLoadModule("rom0:PADMAN", 0, NULL);
#else
ret = SifLoadModule("rom0:XPADMAN", 0, NULL);
#endif
if (ret < 0)
{
printf("sifLoadModule pad failed: %d\n", ret);
return -1;
}
return 0;
}
int waitPadReady(int port, int slot)
{
int state;
state = padGetState(port, slot);
while((state != PAD_STATE_STABLE) && (state != PAD_STATE_FINDCTP1))
{
state=padGetState(port, slot);
}
return 0;
}
int initializePad(int port, int slot)
{
MFCALLSTACK;
int ret;
int modes;
int i;
waitPadReady(port, slot);
// How many different modes can this device operate in?
// i.e. get # entrys in the modetable
modes = padInfoMode(port, slot, PAD_MODETABLE, -1);
// If modes == 0, this is not a Dual shock controller
// (it has no actuator engines)
if(modes == 0)
{
// printf("This is a digital controller?\n");
return 1;
}
// Verify that the controller has a DUAL SHOCK mode
i = 0;
do
{
if(padInfoMode(port, slot, PAD_MODETABLE, i) == PAD_TYPE_DUALSHOCK)
break;
i++;
} while (i < modes);
if(i >= modes)
{
// printf("This is no Dual Shock controller\n");
return 1;
}
// If ExId != 0x0 => This controller has actuator engines
// This check should always pass if the Dual Shock test above passed
ret = padInfoMode(port, slot, PAD_MODECUREXID, 0);
if(ret == 0)
{
// printf("This is no Dual Shock controller??\n");
return 1;
}
// When using MMODE_LOCK, user cant change mode with Select button
padSetMainMode(port, slot, PAD_MMODE_DUALSHOCK, PAD_MMODE_LOCK);
waitPadReady(port, slot);
actuators = padInfoAct(port, slot, -1, 0);
if(actuators != 0)
{
actAlign[0] = 0; // Enable small engine
actAlign[1] = 1; // Enable big engine
actAlign[2] = 0xff;
actAlign[3] = 0xff;
actAlign[4] = 0xff;
actAlign[5] = 0xff;
waitPadReady(port, slot);
}
else
{
// printf("Did not find any actuators.\n");
}
waitPadReady(port, slot);
return 1;
}
void MFInput_InitModulePlatformSpecific()
{
MFCALLSTACK;
int port, slot;
int ret;
SifInitRpc(0);
if(loadModules())
{
printf("UNABLE to load modules\n");
return;
}
if(padInit(0))
{
printf("UNABLE to init pad\n");
return;
}
port = 0; // 0 -> Connector 1, 1 -> Connector 2
slot = 0; // Always zero if not using multitap
// printf("PortMax: %d\n", padGetPortMax());
// printf("SlotMax: %d\n", padGetSlotMax(port));
if((ret = padPortOpen(port, slot, padBuf)) == 0)
{
printf("padOpenPort failed: %d\n", ret);
return;
}
if(!initializePad(port, slot))
{
printf("pad initalization failed!\n");
return ;
}
}
void MFInput_DeinitModulePlatformSpecific()
{
MFCALLSTACK;
}
void MFInput_UpdatePlatformSpecific()
{
int ret;
int port =0, slot = 0;
MFCALLSTACK;
ret=padGetState(port, slot);
while((ret != PAD_STATE_STABLE) && (ret != PAD_STATE_FINDCTP1))
{
if(ret==PAD_STATE_DISCONN)
{
printf("Pad(%d, %d) is disconnected\n", port, slot);
printf("What now?\n");
while(1);
}
ret=padGetState(port, slot);
}
ret = padRead(port, slot, &buttons);
if (ret != 0)
{
new_pad = 0xffff ^ buttons.btns;
return;
}
}
MFInputDeviceStatus MFInput_GetDeviceStatusInternal(int device, int id)
{
if(device == IDD_Gamepad && id < 2)
return IDS_Disconnected;
return IDS_Unavailable;
}
void MFInput_GetGamepadStateInternal(int id, MFGamepadState *pGamepadState)
{
MFCALLSTACK;
MFZeroMemory(pGamepadState, sizeof(MFGamepadState));
pGamepadState->values[Button_P2_Cross] = (new_pad & PAD_CROSS )?1.0f:0.0f;
pGamepadState->values[Button_P2_Circle] = (new_pad & PAD_CIRCLE)?1.0f:0.0f;
pGamepadState->values[Button_P2_Box] = (new_pad & PAD_SQUARE)?1.0f:0.0f;
pGamepadState->values[Button_P2_Triangle] = (new_pad & PAD_TRIANGLE)?1.0f:0.0f;
pGamepadState->values[Button_P2_L1] = (new_pad & PAD_L1)?1.0f:0.0f;
pGamepadState->values[Button_P2_R1] = (new_pad & PAD_R1)?1.0f:0.0f;
pGamepadState->values[Button_P2_L2] = (new_pad & PAD_L2)?1.0f:0.0f;
pGamepadState->values[Button_P2_R2] = (new_pad & PAD_R2)?1.0f:0.0f;
pGamepadState->values[Button_P2_Start] = (new_pad & PAD_START)?1.0f:0.0f;
pGamepadState->values[Button_P2_Select] = (new_pad & PAD_SELECT)?1.0f:0.0f;
pGamepadState->values[Button_P2_L3] = (new_pad & PAD_L3)?1.0f:0.0f;
pGamepadState->values[Button_P2_R3] = (new_pad & PAD_R3)?1.0f:0.0f;
pGamepadState->values[Button_DUp] = (new_pad & PAD_UP)?1.0f:0.0f;
pGamepadState->values[Button_DDown] = (new_pad & PAD_DOWN)?1.0f:0.0f;
pGamepadState->values[Button_DLeft] = (new_pad & PAD_LEFT)?1.0f:0.0f;
pGamepadState->values[Button_DRight] = (new_pad & PAD_RIGHT)?1.0f:0.0f;
pGamepadState->values[Axis_LX] = (float)buttons.ljoy_h /127.5f - 1.0f;
pGamepadState->values[Axis_LY] = -((float)buttons.ljoy_v/127.5f - 1.0f);
pGamepadState->values[Axis_RX] = (float)buttons.rjoy_h /127.5f - 1.0f;
pGamepadState->values[Axis_RY] = -((float)buttons.rjoy_v/127.5f - 1.0f);
}
void MFInput_GetKeyStateInternal(int id, MFKeyState *pKeyState)
{
MFCALLSTACK;
MFZeroMemory(pKeyState, sizeof(MFKeyState));
}
void MFInput_GetMouseStateInternal(int id, MFMouseState *pMouseState)
{
MFCALLSTACK;
MFZeroMemory(pMouseState, sizeof(MFMouseState));
}
const char* MFInput_GetDeviceNameInternal(int source, int sourceID)
{
switch(source)
{
case IDD_Gamepad:
return "DualShock 2";
case IDD_Mouse:
return "Mouse";
case IDD_Keyboard:
return "Keyboard";
default:
break;
}
return NULL;
}
const char* MFInput_GetGamepadButtonNameInternal(int button, int sourceID)
{
MFDebug_Assert(sourceID < 2, "Only two gamepads available on PS2..."); // multitap??
return gPS2Buttons[button];
}
MF_API bool MFInput_GetKeyboardStatusState(int keyboardState, int keyboardID)
{
switch(keyboardState)
{
case KSS_NumLock:
break;
case KSS_CapsLock:
break;
case KSS_ScrollLock:
break;
case KSS_Insert:
break;
}
return 0;
}
#endif
| 21.077135 | 90 | 0.649327 | TurkeyMan |
0c12563f6dc15690aaa6754dda968b5f12ea895d | 31,784 | cpp | C++ | Build/hosEditor/hosEditorDlg.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | null | null | null | Build/hosEditor/hosEditorDlg.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | null | null | null | Build/hosEditor/hosEditorDlg.cpp | Game-institute-1st-While-true/hosEngine | 2cc0b464740a976a8b37afd7a9e3479fe7484cf0 | [
"MIT"
] | 2 | 2021-07-14T00:14:18.000Z | 2021-07-27T04:16:53.000Z |
// hosEditorDlg.cpp: 구현 파일
//
#include "pch.h"
#include "framework.h"
#include "hosEditor.h"
#include "SceneView.h"
#include "TransformView.h"
#include "BoxCollisionview.h"
#include "SphereCollisionView.h"
#include "CapsuleCollisionView.h"
#include "CameraView.h"
#include "RigidbodyView.h"
#include "AudioListenerView.h"
#include "AudioSourceView.h"
#include "ScriptView.h"
#include "LIghtView.h"
#include "MeshFilterView.h"
#include "MeshRendererView.h"
#include "SkinnedMeshRendererView.h"
#include "AnimationView.h"
#include "UIImageView.h"
#include "UITextView.h"
#include "UIButtonView.h"
#include "UIInputFieldView.h"
#include "SceneInfoView.h"
#include "NavInfoView.h"
#include "hosEditorDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다.
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
// 구현입니다.
protected:
DECLARE_MESSAGE_MAP()
public:
// afx_msg void OnClose();
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
// ON_WM_CLOSE()
END_MESSAGE_MAP()
// ChosEditorDlg 대화 상자
ChosEditorDlg::ChosEditorDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_HOSEditor_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void ChosEditorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TREE_GAME_OBJECT_HIERARCHY, GameObjectHierachy);
DDX_Control(pDX, IDC_EDIT_GAME_OBJECT_NAME, GameObjectName);
DDX_Control(pDX, IDC_LIST_COMPONENT_LIST, ComponentList);
DDX_Control(pDX, IDC_COMBO_COMPONENT_LIST, ComponentSelectList);
DDX_Control(pDX, IDC_EDIT_SCENE_NAME, EditSceneName);
DDX_Control(pDX, IDC_LIST_PREFAB_LIST, ListPrefabList);
}
BEGIN_MESSAGE_MAP(ChosEditorDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_CREATE_GAME_OBJECT, &ChosEditorDlg::OnBnClickedButtonCreateGameObject)
ON_BN_CLICKED(IDC_BUTTON_CHANGE_GAME_OBJECT_NAME, &ChosEditorDlg::OnBnClickedButtonChangeGameObjectName)
// ON_WM_CLOSE()
ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnTvnSelchangedTreeGameObjectHierarchy)
ON_BN_CLICKED(IDC_BUTTON_REMOVE_GAME_OBJECT, &ChosEditorDlg::OnBnClickedButtonRemoveGameObject)
ON_NOTIFY(NM_RCLICK, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnNMRClickTreeGameObjectHierarchy)
ON_BN_CLICKED(IDC_BUTTON_ADD_COMPONENT, &ChosEditorDlg::OnBnClickedButtonAddComponent)
ON_BN_CLICKED(IDC_BUTTON_REMOVE_COMPONENT, &ChosEditorDlg::OnBnClickedButtonRemoveComponent)
ON_LBN_SELCHANGE(IDC_LIST_COMPONENT_LIST, &ChosEditorDlg::OnLbnSelchangeListComponentList)
ON_EN_CHANGE(IDC_EDIT_SCENE_NAME, &ChosEditorDlg::OnEnChangeEditSceneName)
ON_BN_CLICKED(IDC_BUTTON_SCENE_SAVE, &ChosEditorDlg::OnBnClickedButtonSceneSave)
ON_BN_CLICKED(IDC_BUTTON_SCENE_LOAD, &ChosEditorDlg::OnBnClickedButtonSceneLoad)
ON_BN_CLICKED(IDC_BUTTON_GAME_OBJECT_SAVE, &ChosEditorDlg::OnBnClickedButtonGameObjectSave)
ON_BN_CLICKED(IDC_BUTTON_GAME_OBJECT_LOAD, &ChosEditorDlg::OnBnClickedButtonGameObjectLoad)
ON_NOTIFY(TVN_BEGINDRAG, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnTvnBegindragTreeGameObjectHierarchy)
ON_BN_CLICKED(IDC_BUTTON_ADD_GAME_DATA, &ChosEditorDlg::OnBnClickedButtonAddGameData)
ON_BN_CLICKED(IDC_BUTTON_LOAD_GAME_DATA, &ChosEditorDlg::OnBnClickedButtonLoadGameData)
ON_WM_CLOSE()
ON_NOTIFY(NM_DBLCLK, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnNMDblclkTreeGameObjectHierarchy)
ON_BN_CLICKED(IDC_BUTTON_SCENE_INFO, &ChosEditorDlg::OnBnClickedButtonSceneInfo)
ON_BN_CLICKED(IDC_BUTTON_NAV_INFO, &ChosEditorDlg::OnBnClickedButtonNavInfo)
END_MESSAGE_MAP()
// ChosEditorDlg 메시지 처리기
BOOL ChosEditorDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다.
// IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는
// 프레임워크가 이 작업을 자동으로 수행합니다.
SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다.
SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다.
// TODO: 여기에 추가 초기화 작업을 추가합니다.
/// 다이얼로그 만들어야 함
m_SceneView = new SceneView();
m_SceneView->Create(IDD_SceneView, CWnd::GetDesktopWindow());
RECT Size;
Size.left = 0;
Size.top = 0;
Size.right = 1920;
Size.bottom = 1080;
AdjustWindowRect(&Size, WS_OVERLAPPEDWINDOW, false);
m_SceneView->SetWindowPos(NULL, 0, 0, Size.right - Size.left, Size.bottom - Size.top, SWP_NOMOVE | SWP_NOZORDER);
m_SceneView->ShowWindow(SW_SHOW);
EditorManager::GetIns()->Initialize(m_SceneView->GetSafeHwnd());
ComponentSelectList.AddString(L"Camera");
ComponentSelectList.AddString(L"BoxCollision");
ComponentSelectList.AddString(L"SphereCollision");
ComponentSelectList.AddString(L"CapsuleCollision");
ComponentSelectList.AddString(L"Rigidbody");
ComponentSelectList.AddString(L"AudioListener");
ComponentSelectList.AddString(L"AudioSource");
ComponentSelectList.AddString(L"Script");
ComponentSelectList.AddString(L"Light");
ComponentSelectList.AddString(L"MeshFilter");
ComponentSelectList.AddString(L"MeshRenderer");
ComponentSelectList.AddString(L"SkinnedMeshRenderer");
ComponentSelectList.AddString(L"Animation");
ComponentSelectList.AddString(L"NavAgent");
ComponentSelectList.AddString(L"Networkcomponent");
ComponentSelectList.AddString(L"UIImage");
ComponentSelectList.AddString(L"UIText");
ComponentSelectList.AddString(L"UIButton");
ComponentSelectList.AddString(L"UIInputField");
EditSceneName.SetWindowTextW(EditorManager::GetIns()->GetNowScene()->GetName().c_str());
GameObjectHierachy.InsertItem(L"MainCamera");
GameObjectHierachy.InsertItem(L"DirectionalLight1");
GameObjectHierachy.InsertItem(L"DirectionalLight2");
GameObjectHierachy.InsertItem(L"DirectionalLight3");
CCreateContext context;
ZeroMemory(&context, sizeof(context));
CRect _rect;
GetDlgItem(IDC_STATIC_INSPECTOR_AREA)->GetWindowRect(&_rect);
ScreenToClient(&_rect);
m_TransformView = new TransformView();
m_TransformView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_TransformView->OnInitialUpdate();
m_TransformView->ShowWindow(SW_HIDE);
m_BoxCollisionView = new BoxCollisionView();
m_BoxCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_BoxCollisionView->OnInitialUpdate();
m_BoxCollisionView->ShowWindow(SW_HIDE);
m_SphereCollisionView = new SphereCollisionView();
m_SphereCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_SphereCollisionView->OnInitialUpdate();
m_SphereCollisionView->ShowWindow(SW_HIDE);
m_CapsuleCollisionView = new CapsuleCollisionView();
m_CapsuleCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_CapsuleCollisionView->OnInitialUpdate();
m_CapsuleCollisionView->ShowWindow(SW_HIDE);
m_CameraView = new CameraView();
m_CameraView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_CameraView->OnInitialUpdate();
m_CameraView->ShowWindow(SW_HIDE);
m_RigidbodyView = new RigidbodyView();
m_RigidbodyView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_RigidbodyView->OnInitialUpdate();
m_RigidbodyView->ShowWindow(SW_HIDE);
m_AudioListenerView = new AudioListenerView();
m_AudioListenerView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_AudioListenerView->OnInitialUpdate();
m_AudioListenerView->ShowWindow(SW_HIDE);
m_AudioSourceView = new AudioSourceView();
m_AudioSourceView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_AudioSourceView->OnInitialUpdate();
m_AudioSourceView->ShowWindow(SW_HIDE);
m_ScriptView = new ScriptView();
m_ScriptView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_ScriptView->OnInitialUpdate();
m_ScriptView->ShowWindow(SW_HIDE);
m_LightView = new LIghtView();
m_LightView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_LightView->OnInitialUpdate();
m_LightView->ShowWindow(SW_HIDE);
m_MeshFilterView = new MeshFilterView();
m_MeshFilterView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_MeshFilterView->OnInitialUpdate();
m_MeshFilterView->ShowWindow(SW_HIDE);
m_MeshRendererView = new MeshRendererView();
m_MeshRendererView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_MeshRendererView->OnInitialUpdate();
m_MeshRendererView->ShowWindow(SW_HIDE);
m_SkinnedMeshRendererView = new SkinnedMeshRendererView();
m_SkinnedMeshRendererView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_SkinnedMeshRendererView->OnInitialUpdate();
m_SkinnedMeshRendererView->ShowWindow(SW_HIDE);
m_AnimationView = new AnimationView();
m_AnimationView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_AnimationView->OnInitialUpdate();
m_AnimationView->ShowWindow(SW_HIDE);
m_UIImageView = new UIImageView();
m_UIImageView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_UIImageView->OnInitialUpdate();
m_UIImageView->ShowWindow(SW_HIDE);
m_UITextView = new UITextView();
m_UITextView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_UITextView->OnInitialUpdate();
m_UITextView->ShowWindow(SW_HIDE);
m_UIButtonView = new UIButtonView();
m_UIButtonView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_UIButtonView->OnInitialUpdate();
m_UIButtonView->ShowWindow(SW_HIDE);
m_UIInputFieldView = new UIInputFieldView();
m_UIInputFieldView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_UIInputFieldView->OnInitialUpdate();
m_UIInputFieldView->ShowWindow(SW_HIDE);
m_SceneInfoView = new SceneInfoView();
m_SceneInfoView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_SceneInfoView->OnInitialUpdate();
m_SceneInfoView->ShowWindow(SW_HIDE);
m_NavInfoView = new NavInfoView();
m_NavInfoView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context);
m_NavInfoView->OnInitialUpdate();
m_NavInfoView->ShowWindow(SW_HIDE);
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다.
}
void ChosEditorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면
// 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 애플리케이션의 경우에는
// 프레임워크에서 이 작업을 자동으로 수행합니다.
void ChosEditorDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다.
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다.
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 아이콘을 그립니다.
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서
// 이 함수를 호출합니다.
HCURSOR ChosEditorDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void ChosEditorDlg::ResetComponentList(CString* gameObject)
{
while (ComponentList.GetCount() != 0)
{
ComponentList.DeleteString(0);
}
if (gameObject)
{
hos::com::GameObject* obj = EditorManager::GetIns()->GetNowScene()->FindGameObjectWithName(T2W(gameObject->GetBuffer()));
if (obj)
{
int _ComponentCount = obj->GetComponents().size();
for (int i = 0; i < _ComponentCount; i++)
{
ComponentList.AddString(obj->GetComponents()[i]->GetName().c_str());
}
}
}
}
void ChosEditorDlg::HideAllComponentView()
{
m_TransformView->ShowWindow(SW_HIDE);
m_BoxCollisionView->ShowWindow(SW_HIDE);
m_SphereCollisionView->ShowWindow(SW_HIDE);
m_CapsuleCollisionView->ShowWindow(SW_HIDE);
m_CameraView->ShowWindow(SW_HIDE);
m_RigidbodyView->ShowWindow(SW_HIDE);
m_AudioListenerView->ShowWindow(SW_HIDE);
m_AudioSourceView->ShowWindow(SW_HIDE);
m_ScriptView->ShowWindow(SW_HIDE);
m_LightView->ShowWindow(SW_HIDE);
m_MeshFilterView->ShowWindow(SW_HIDE);
m_MeshRendererView->ShowWindow(SW_HIDE);
m_SkinnedMeshRendererView->ShowWindow(SW_HIDE);
m_AnimationView->ShowWindow(SW_HIDE);
m_UIImageView->ShowWindow(SW_HIDE);
m_UITextView->ShowWindow(SW_HIDE);
m_UIButtonView->ShowWindow(SW_HIDE);
m_UIInputFieldView->ShowWindow(SW_HIDE);
m_SceneInfoView->ShowWindow(SW_HIDE);
m_NavInfoView->ShowWindow(SW_HIDE);
}
void ChosEditorDlg::ResetAllComponentView()
{
m_TransformView->ResetTransformView();
m_BoxCollisionView->ResetBoxCollisionView();
m_SphereCollisionView->ResetSphereCollisionView();
m_CapsuleCollisionView->ResetCapsuleCollisionView();
m_CameraView->ResetCameraView();
m_RigidbodyView->ResetRigidbodyView();
m_AudioListenerView->ResetAudioListenerView();
m_AudioSourceView->ResetAudioSourceView();
m_ScriptView->ResetScriptView();
m_LightView->ResetLightView();
m_MeshFilterView->ResetMeshFilterView();
m_MeshRendererView->ResetMeshRendererView();
m_SkinnedMeshRendererView->ResetSkinnedMeshRendererView();
m_AnimationView->ResetAnimationView();
m_UIImageView->ResetUIImageView();
m_UITextView->ResetUITextView();
m_UIButtonView->ResetUIButtonView();
m_UIInputFieldView->ResetUIInputFieldView();
m_SceneInfoView->ResetSceneInfoView();
m_NavInfoView->ResetNavInfoView();
}
void ChosEditorDlg::UpdateGameObjectHierarchy()
{
// 기존 계층구조 삭제
GameObjectHierachy.DeleteAllItems();
// 현재 씬의 오브젝트 계층구조를 가져와서 갱신시키기
for (int i = 0; i < EditorManager::GetIns()->GetNowScene()->GetRoots().size(); i++)
{
// 루트 오브젝트 가져오기
hos::com::GameObject* _GameObject = EditorManager::GetIns()->GetNowScene()->GetRoots()[i];
// 루트 오브젝트 이름 계층구조에 넣기
HTREEITEM _TreeItem = GameObjectHierachy.InsertItem(_GameObject->GetName().c_str());;
// 자식 오브젝트 있는지 확인 후 계층구조에 추가 (반복)
MakeGameObjectHierarchy(_GameObject, &_TreeItem);
}
HideAllComponentView();
ResetComponentList(nullptr);
hos::com::GameObject* _ObjectTemp = nullptr;
EditorManager::GetIns()->SetNowGameObject(_ObjectTemp);
}
void ChosEditorDlg::MakeGameObjectHierarchy(hos::com::GameObject* gameObject, HTREEITEM* treeItem)
{
int _ChildGameObjectCount = gameObject->GetComponent<hos::com::Transform>()->GetChildCount();
if (_ChildGameObjectCount > 0)
{
for (int i = 0; i < _ChildGameObjectCount; i++)
{
hos::com::GameObject* _GameObject = gameObject->GetComponent<hos::com::Transform>()->GetChilds()[i]->m_GameObject;
HTREEITEM _TreeItem = GameObjectHierachy.InsertItem(_GameObject->GetName().c_str(), *treeItem);
MakeGameObjectHierarchy(_GameObject, &_TreeItem);
}
}
}
void ChosEditorDlg::OnBnClickedButtonCreateGameObject()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
HideAllComponentView();
//ResetAllComponentView();
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _temp;
if (_TreeItem)
{
// 하위에 오브젝트 생성
CString _ParentName = GameObjectHierachy.GetItemText(_TreeItem);
_temp = EditorManager::GetIns()->CreateGameObject(&_ParentName);
GameObjectHierachy.InsertItem(_temp, _TreeItem);
}
else
{
// 루트 오브젝트 생성
_temp = EditorManager::GetIns()->CreateGameObject();
//GameObjectHierachy.InsertItem(_temp, nullptr, nullptr);
GameObjectHierachy.InsertItem(_temp);
}
// 선택 해제
GameObjectHierachy.SelectItem(nullptr);
Invalidate(TRUE);
}
void ChosEditorDlg::OnBnClickedButtonChangeGameObjectName()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
int _StringCount = GameObjectName.GetWindowTextLengthW();
if (_StringCount <= 0)
{
return;
}
CString _ChangedName;
GameObjectName.GetWindowTextW(_ChangedName);
if (_ChangedName.GetLength() > 0)
{
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
if (_TreeItem != nullptr)
{
CString _temp = GameObjectHierachy.GetItemText(_TreeItem);
_ChangedName = EditorManager::GetIns()->ChangeGameObjectName(&_temp, &_ChangedName);
GameObjectHierachy.SetItemText(_TreeItem, _ChangedName);
GameObjectHierachy.SelectItem(nullptr);
Invalidate(TRUE);
}
}
}
void ChosEditorDlg::OnClose()
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
EditorManager::GetIns()->Finalize();
EditorManager::GetIns()->Destory();
delete m_SceneView;
m_SceneView = nullptr;
delete m_TransformView;
delete m_BoxCollisionView;
delete m_SphereCollisionView;
delete m_CapsuleCollisionView;
delete m_CameraView;
delete m_RigidbodyView;
delete m_AudioListenerView;
delete m_AudioSourceView;
delete m_ScriptView;
delete m_LightView;
delete m_MeshFilterView;
delete m_MeshRendererView;
delete m_SkinnedMeshRendererView;
delete m_AnimationView;
delete m_UIImageView;
delete m_UIButtonView;
delete m_UIInputFieldView;
delete m_SceneInfoView;
delete m_NavInfoView;
CDialogEx::OnClose();
}
void ChosEditorDlg::OnTvnSelchangedTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
*pResult = 0;
// 현재 선택한 GameObject Hierarchy Node 가져오기
CString _temp = GameObjectHierachy.GetItemText(pNMTreeView->itemNew.hItem);
GameObjectName.SetWindowTextW(_temp);
ResetComponentList(nullptr);
HideAllComponentView();
hos::com::GameObject* _ObjectTemp = nullptr;
EditorManager::GetIns()->SetNowGameObject(_ObjectTemp);
if (_temp.GetLength() > 0)
{
// 컴포넌트 리스트 초기화
// 선택한 오브젝트의 컴포넌트들을 가져와야 함
ResetComponentList(&_temp);
EditorManager::GetIns()->SetNowGameObject(&_temp);
}
ComponentList.SetCurSel(0);
OnLbnSelchangeListComponentList();
/// 테스트 해봄
//SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOP)
//CFileFind finder;
//bool IsFind = finder.FindFile(L"..\\Resource");
//IsFind = finder.FindNextFileW();
//CString temp = finder.GetFileTitle();
//temp = finder.GetFilePath();
//temp = finder.GetFileName();
Invalidate(TRUE);
}
void ChosEditorDlg::OnBnClickedButtonRemoveGameObject()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
ResetComponentList(nullptr);
HideAllComponentView();
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _temp = GameObjectHierachy.GetItemText(_TreeItem);
if (_TreeItem)
{
EditorManager::GetIns()->RemoveGameObject(&_temp);
GameObjectHierachy.DeleteItem(_TreeItem);
GameObjectHierachy.SelectItem(nullptr);
Invalidate(TRUE);
}
}
void ChosEditorDlg::OnNMRClickTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
*pResult = 0;
ResetComponentList(nullptr);
GameObjectHierachy.SelectItem(nullptr);
hos::com::GameObject* _temp = nullptr;
EditorManager::GetIns()->SetNowGameObject(_temp);
HideAllComponentView();
ResetAllComponentView();
Invalidate(TRUE);
}
void ChosEditorDlg::OnBnClickedButtonAddComponent()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
// 선택한 오브젝트와 추가를 하고싶은 컴포넌트를 보내자
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _SelectedGameObject = GameObjectHierachy.GetItemText(_TreeItem);
CString _ComponentName;
ComponentSelectList.GetLBText(ComponentSelectList.GetCurSel(), _ComponentName);
if (_SelectedGameObject.GetLength() > 0 && _ComponentName.GetLength() > 0)
{
EditorManager::GetIns()->AddComponent(&_SelectedGameObject, &_ComponentName, ComponentList.GetCount());
// 컴포넌트 리스트 초기화 후 갱신
ResetComponentList(&_SelectedGameObject);
}
}
void ChosEditorDlg::OnBnClickedButtonRemoveComponent()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
// Transform은 제거 안 됨
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _SelectedGameObject = GameObjectHierachy.GetItemText(_TreeItem);
CString _ComponentName;
ComponentList.GetText(ComponentList.GetCurSel(), _ComponentName);
if (_SelectedGameObject.GetLength() > 0 && _ComponentName.GetLength() > 0)
{
EditorManager::GetIns()->RemoveComponent(&_SelectedGameObject, &_ComponentName, ComponentList.GetCurSel());
// 컴포넌트 리스트 초기화 후 갱신
ResetComponentList(&_SelectedGameObject);
HideAllComponentView();
}
}
void ChosEditorDlg::OnLbnSelchangeListComponentList()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
// 선택한 것이 있으면 띄우자
HideAllComponentView();
//////////////////////////////////////////////////////////////////////////
/// 해당하는 컴포넌트마다 띄울게 다르다..
CString _ComponentName;
if (ComponentList.GetCurSel() >= 0)
{
ComponentList.GetText(ComponentList.GetCurSel(), _ComponentName);
}
if (_ComponentName.Collate(L"Transform") == 0)
{
m_TransformView->SetTransformView();
m_TransformView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"BoxCollision") == 0)
{
m_BoxCollisionView->SetBoxCollisionView();
m_BoxCollisionView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"SphereCollision") == 0)
{
m_SphereCollisionView->SetSphereCollisionView();
m_SphereCollisionView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"CapsuleCollision") == 0)
{
m_CapsuleCollisionView->SetCapsuleCollisionView();
m_CapsuleCollisionView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"Rigidbody") == 0)
{
m_RigidbodyView->SetRigidbodyView();
m_RigidbodyView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"Camera") == 0)
{
m_CameraView->SetCameraView();
m_CameraView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"AudioListener") == 0)
{
m_AudioListenerView->SetAudioListenerView();
m_AudioListenerView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"AudioSource") == 0)
{
m_AudioSourceView->SetAudioSourceView();
m_AudioSourceView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"Script") == 0)
{
m_ScriptView->SetScriptView(ComponentList.GetCurSel());
m_ScriptView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"Light") == 0)
{
m_LightView->SetLightView();
m_LightView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"MeshFilter") == 0)
{
m_MeshFilterView->SetMeshFilterView();
m_MeshFilterView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"MeshRenderer") == 0)
{
m_MeshRendererView->SetMeshRendererView();
m_MeshRendererView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"SkinnedMeshRenderer") == 0)
{
m_SkinnedMeshRendererView->SetSkinnedMeshRendererView();
m_SkinnedMeshRendererView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"Animation") == 0)
{
m_AnimationView->SetAnimationView();
m_AnimationView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"UIImage") == 0)
{
m_UIImageView->SetUIImageView();
m_UIImageView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"UIText") == 0)
{
m_UITextView->SetUITextView();
m_UITextView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"UIButton") == 0)
{
m_UIButtonView->SetUIButtonView();
m_UIButtonView->ShowWindow(SW_SHOW);
}
else if (_ComponentName.Collate(L"UIInputField") == 0)
{
m_UIInputFieldView->SetUIInputFieldView();
m_UIInputFieldView->ShowWindow(SW_SHOW);
}
else
{
HideAllComponentView();
}
}
void ChosEditorDlg::OnEnChangeEditSceneName()
{
// TODO: RICHEDIT 컨트롤인 경우, 이 컨트롤은
// CDialogEx::OnInitDialog() 함수를 재지정
//하고 마스크에 OR 연산하여 설정된 ENM_CHANGE 플래그를 지정하여 CRichEditCtrl().SetEventMask()를 호출하지 않으면
// 이 알림 메시지를 보내지 않습니다.
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
int _Length = EditSceneName.GetWindowTextLengthW();
if (_Length > 0)
{
CString _tempString;
EditSceneName.GetWindowTextW(_tempString);
EditorManager::GetIns()->GetNowScene()->SetName(T2W(_tempString.GetBuffer()));
}
}
void ChosEditorDlg::OnBnClickedButtonSceneSave()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
//static TCHAR BASED_CODE szFilter[] = _T("*.*||");// 모든파일(*.*) | *.* || ");
// 경로 불러오기
CFileDialog _PathDialog(false, L"", L"저장 할 위치나 씬 선택", OFN_HIDEREADONLY);
if (IDOK == _PathDialog.DoModal())
{
CString _Path = _PathDialog.GetPathName();
CString _File = _PathDialog.GetFileName();
// 씬이 있다면
int _ScenesInPath = _Path.Find(L"Scenes");
int _AssetsInPath = _Path.Find(L"Assets");
if (_AssetsInPath > 0 && _ScenesInPath > 0)
{
if (_AssetsInPath < _ScenesInPath)
{
CString _Assets;
_Assets = _Path.Left(_AssetsInPath);
_Assets.Append(L"Assets");
_Path = _Assets;
}
}
else
{
// 끝에 씬 이름 빼기
_Path.TrimRight(_File);
_Path.TrimRight(L"\\");
}
//////////////////////////////////////////////////////////////////////////
// Assets 폴더에 생성하는지 확인하기
// Assets 폴더가 아니라면 해당 경로에 Assets 폴더 생성
hos::string _FindAssets;
hos::string _IsAssets;
_FindAssets = T2W(_Path.GetBuffer());
_IsAssets = _FindAssets.substr(_FindAssets.find_last_of(L"\\") + 1);
if (_IsAssets.compare(L"Assets") == 0)
{
_Path.Append(L"\\");
}
else
{
_Path.Append(L"\\Assets\\");
CreateDirectory(_Path, nullptr);
}
//////////////////////////////////////////////////////////////////////////
// 매니저에 경로를 보낸다.
EditorManager::GetIns()->SaveScene(&_Path);
// 데이터 매니저 내부의 데이터들을 해당 폴더에 저장하기
EditorManager::GetIns()->SaveDataManager(&_Path);
MessageBox(L"Save Complete!!!", L"Save", MB_OK);
}
}
void ChosEditorDlg::OnBnClickedButtonSceneLoad()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
static TCHAR BASED_CODE szFilter[] = _T("*.scene, *.scene | *.scene; *.scene |");// 모든파일(*.*) | *.* || ");
// 경로 불러오기
CFileDialog _PathDialog(true, L"*.scene", L"", OFN_HIDEREADONLY, szFilter);
if (IDOK == _PathDialog.DoModal())
{
CString _Path = _PathDialog.GetPathName();
// 매니저에 경로를 보낸다.
bool b = EditorManager::GetIns()->LoadScene(&_Path);
if (b)
{
// 씬 이름 변경하기
EditSceneName.SetWindowTextW(EditorManager::GetIns()->GetNowScene()->GetName().c_str());
// Object Hierarchy 갱신해야 함.. 얽
UpdateGameObjectHierarchy();
}
}
}
void ChosEditorDlg::OnBnClickedButtonGameObjectSave()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
// 프리팹을 저장한다.
// 오브젝트 계층구조에서 선택된 오브젝트가 있는가
if (GameObjectHierachy.GetSelectedItem())
{
// 경로 가져와서 저장하기
static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || ");
// 경로 불러오기
CFileDialog _PathDialog(false, L"*.prefab", L"이 이름으로 저장 안 됨", OFN_HIDEREADONLY, szFilter);
if (IDOK == _PathDialog.DoModal())
{
CString _Path = _PathDialog.GetPathName();
CString _File = _PathDialog.GetFileName();
// 끝에 오브젝트 이름 빼기
_Path.TrimRight(_File);
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _temp;
_temp = GameObjectHierachy.GetItemText(_TreeItem);
// 경로와 오브젝트의 이름을 보낸다.
EditorManager::GetIns()->SavePrefab(&_Path, &_temp);
}
}
}
void ChosEditorDlg::OnBnClickedButtonGameObjectLoad()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || ");
// 경로 불러오기
CFileDialog _PathDialog(true, L"*.prefab", L"", OFN_HIDEREADONLY, szFilter);
if (IDOK == _PathDialog.DoModal())
{
CString _Path = _PathDialog.GetPathName();
bool b;
// 오브젝트 계층구조에서 선택된 오브젝트가 있는다.
if (GameObjectHierachy.GetSelectedItem())
{
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _temp;
_temp = GameObjectHierachy.GetItemText(_TreeItem);
b = EditorManager::GetIns()->LoadPrefab(&_Path, &_temp);
}
else
{
// 없으면 루트 오브젝트로 넣는다.
b = EditorManager::GetIns()->LoadPrefab(&_Path, nullptr);
}
if (b)
{
// Object Hierarchy 갱신해야 함.. 얽
UpdateGameObjectHierarchy();
}
}
}
void ChosEditorDlg::OnTvnBegindragTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
*pResult = 0;
}
void ChosEditorDlg::OnBnClickedButtonAddGameData()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
//static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || ");
// 경로 불러오기
CFileDialog _PathDialog(true, L"", L"", OFN_HIDEREADONLY);
if (IDOK == _PathDialog.DoModal())
{
CString _Path = _PathDialog.GetPathName();
EditorManager::GetIns()->LoadGameData(&_Path);
UpdateGameObjectHierarchy();
// 프리팹 리스트를 업데이트 한다.
while (ListPrefabList.GetCount() != 0)
{
ListPrefabList.DeleteString(0);
}
for (auto [name, data] : EditorManager::GetIns()->GetDataManager()->Prefabs)
{
ListPrefabList.AddString(name.c_str());
}
}
}
void ChosEditorDlg::OnBnClickedButtonLoadGameData()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
// 선택한 프리팹을 오브젝트 하이어라키에 불러오자
CString _PrefabName;
ListPrefabList.GetText(ListPrefabList.GetCurSel(), _PrefabName);
// 오브젝트 하이어라키에서 선택한 오브젝트가 있는 경우
HideAllComponentView();
ResetComponentList(nullptr);
HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem();
CString _temp;
if (_TreeItem)
{
// 하위에 오브젝트 생성
CString _ParentName = GameObjectHierachy.GetItemText(_TreeItem);
_temp = EditorManager::GetIns()->AddPrefab(&_PrefabName, &_ParentName);
GameObjectHierachy.InsertItem(_temp, _TreeItem);
}
else
{
// 루트 오브젝트 생성
_temp = EditorManager::GetIns()->AddPrefab(&_PrefabName);
GameObjectHierachy.InsertItem(_temp);
}
// 선택 해제
GameObjectHierachy.SelectItem(nullptr);
UpdateGameObjectHierarchy();
Invalidate(TRUE);
}
BOOL ChosEditorDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
if (pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam == VK_RETURN) // ENTER키 눌릴 시
return TRUE;
else if (pMsg->wParam == VK_ESCAPE) // ESC키 눌릴 시
return TRUE;
}
return CDialogEx::PreTranslateMessage(pMsg);
}
void ChosEditorDlg::ExpandAll(HTREEITEM hUserRoot)
{
if (GameObjectHierachy.ItemHasChildren(hUserRoot))
{
// 확장
GameObjectHierachy.Expand(hUserRoot, TVE_EXPAND);
// 자식 노드 확인
hUserRoot = GameObjectHierachy.GetChildItem(hUserRoot);
if (hUserRoot)
{
do
{
// 재귀로 하위 확인
ExpandAll(hUserRoot);
} while ((hUserRoot = GameObjectHierachy.GetNextSiblingItem(hUserRoot)) != NULL);
}
}
}
void ChosEditorDlg::CollapseAll(HTREEITEM hUserRoot)
{
if (GameObjectHierachy.ItemHasChildren(hUserRoot))
{
// 확장
GameObjectHierachy.Expand(hUserRoot, TVE_COLLAPSE);
// 자식 노드 확인
hUserRoot = GameObjectHierachy.GetChildItem(hUserRoot);
if (hUserRoot)
{
do
{
// 재귀로 하위 확인
ExpandAll(hUserRoot);
} while ((hUserRoot = GameObjectHierachy.GetNextSiblingItem(hUserRoot)) != NULL);
}
}
}
void ChosEditorDlg::OnNMDblclkTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult)
{
HTREEITEM hSelectItem = GameObjectHierachy.GetSelectedItem();
static bool bClose = true;
if (bClose)
{
ExpandAll(hSelectItem);
}
else
{
CollapseAll(hSelectItem);
}
bClose = !bClose;
*pResult = 1;
}
void ChosEditorDlg::OnBnClickedButtonSceneInfo()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
HideAllComponentView();
m_SceneInfoView->SetSceneInfoView();
m_SceneInfoView->ShowWindow(SW_SHOW);
}
void ChosEditorDlg::OnBnClickedButtonNavInfo()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
HideAllComponentView();
m_NavInfoView->SetNavInfoView();
m_NavInfoView->ShowWindow(SW_SHOW);
}
| 26.619765 | 123 | 0.745532 | Game-institute-1st-While-true |
0c12971dc38865e8bb095a745228a17b25f99525 | 75,153 | cpp | C++ | src/WndResizer/WndResizer.cpp | AbsCoDes-lib/WndCommons | 5af3ce02ad0396617299496cab60673e36a0e653 | [
"Apache-2.0"
] | null | null | null | src/WndResizer/WndResizer.cpp | AbsCoDes-lib/WndCommons | 5af3ce02ad0396617299496cab60673e36a0e653 | [
"Apache-2.0"
] | null | null | null | src/WndResizer/WndResizer.cpp | AbsCoDes-lib/WndCommons | 5af3ce02ad0396617299496cab60673e36a0e653 | [
"Apache-2.0"
] | null | null | null | /*
DISCLAIMER
Auther: Mizan Rahman
Original publication location: http://www.codeproject.com/KB/dialog/WndResizer.aspx
This work is provided under the terms and condition described in The Code Project Open License (CPOL)
(http://www.codeproject.com/info/cpol10.aspx)
This disclaimer should not be removed and should exist in any reproduction of this work.
*/
#pragma comment(lib, "uxtheme")
#include "stdafx.h"
#include "WndResizer/WndResizer.h"
namespace abscodes {
namespace wndcommons {
static CMap<HWND, HWND, CWndResizer*, CWndResizer*> WndResizerData;
// ensures that all windows have been unhooked correctly upon process exit
struct VerifyUnHooking {
~VerifyUnHooking() {
ASSERT(WndResizerData.IsEmpty());
}
};
static VerifyUnHooking s_verifyUnHooking;
///////////////////////////// CWndResizer
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CWndResizer(void) {
m_pHookedWnd = NULL;
m_pfnWndProc = NULL;
m_root.Name = _T("_root");
m_pCaptured = NULL;
m_hOldCursor = NULL;
m_splitterOffset = 0;
m_bAutoHandlePaint = TRUE;
}
CWndResizer::~CWndResizer(void) {}
BOOL CWndResizer::GetAutoHandlePaint() {
return m_bAutoHandlePaint;
}
BOOL CWndResizer::SetAutoHandlePaint(BOOL bHandle) {
m_bAutoHandlePaint = bHandle;
return TRUE;
}
void CWndResizer::GetTrueClientRect(CWnd* pWnd, CRect* prc) {
int nMin = 0;
int nMax = 0;
int nCur = 0;
pWnd->GetClientRect(prc);
if((pWnd->GetStyle() & WS_HSCROLL) > 0) {
pWnd->GetScrollRange(SB_HORZ, &nMin, &nMax);
nCur = pWnd->GetScrollPos(SB_HORZ);
prc->right = prc->left + nMax;
prc->OffsetRect(-nCur, 0);
}
if((pWnd->GetStyle() & WS_VSCROLL) > 0) {
pWnd->GetScrollRange(SB_VERT, &nMin, &nMax);
nCur = pWnd->GetScrollPos(SB_VERT);
prc->bottom = prc->top + nMax;
prc->OffsetRect(0, -nCur);
}
}
void CWndResizer::EnsureRootMinMax() {
if(m_root.Width() < m_root.MinSize.cx) {
m_root.right = m_root.left + m_root.MinSize.cx;
}
if(m_root.Width() > m_root.MaxSize.cx) {
m_root.right = m_root.left + m_root.MaxSize.cx;
}
if(m_root.Height() < m_root.MinSize.cy) {
m_root.bottom = m_root.top + m_root.MinSize.cy;
}
if(m_root.Height() > m_root.MaxSize.cy) {
m_root.bottom = m_root.top + m_root.MaxSize.cy;
}
}
void CWndResizer::OnSize(UINT nType, int cx, int cy) {
GetTrueClientRect(m_pHookedWnd, &m_root);
EnsureRootMinMax();
m_root.OnResized();
ResizeUI(&m_root);
}
void CWndResizer::OnScroll() {
GetTrueClientRect(m_pHookedWnd, &m_root);
EnsureRootMinMax();
m_root.OnResized();
ResizeUI(&m_root);
}
BOOL CWndResizer::Hook(CWnd* pParent) {
ASSERT(m_pHookedWnd == NULL);
m_pHookedWnd = pParent;
GetTrueClientRect(m_pHookedWnd, &m_root);
m_root.m_pHookWnd = m_pHookedWnd;
// create the resize gripper panel
CRect rcResziGrip(&m_root);
int cx = ::GetSystemMetrics(SM_CXHSCROLL);
int cy = ::GetSystemMetrics(SM_CYVSCROLL);
rcResziGrip.DeflateRect(m_root.Width() - cx, m_root.Height() - cy, 0, 0);
CGripperPanel* pResizeGripper = new CGripperPanel(&rcResziGrip);
pResizeGripper->SetAnchor(ANCHOR_RIGHT | ANCHOR_BOTTOM);
pResizeGripper->Name = _T("_resizeGrip");
m_root.AddChild(pResizeGripper);
WndResizerData.SetAt(m_pHookedWnd->m_hWnd, this);
m_pfnWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)WindowProc);
return TRUE;
}
BOOL CWndResizer::Hook(CWnd* pParent, CSize& size) {
ASSERT(m_pHookedWnd == NULL);
m_pHookedWnd = pParent;
GetTrueClientRect(m_pHookedWnd, &m_root);
m_root.right = m_root.left + size.cx;
m_root.bottom = m_root.top + size.cy;
m_root.m_pHookWnd = m_pHookedWnd;
// create the resize gripper panel
CRect rcResziGrip(&m_root);
int cx = ::GetSystemMetrics(SM_CXHSCROLL);
int cy = ::GetSystemMetrics(SM_CYVSCROLL);
rcResziGrip.DeflateRect(m_root.Width() - cx, m_root.Height() - cy, 0, 0);
CGripperPanel* pResizeGripper = new CGripperPanel(&rcResziGrip);
pResizeGripper->SetAnchor(ANCHOR_RIGHT | ANCHOR_BOTTOM);
pResizeGripper->Name = _T("_resizeGrip");
m_root.AddChild(pResizeGripper);
WndResizerData.SetAt(m_pHookedWnd->m_hWnd, this);
m_pfnWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)WindowProc);
return TRUE;
}
BOOL CWndResizer::Draw(CPaintDC* pDC) {
CPanelList panelList;
GetVisualPanels(&m_root, &panelList);
POSITION pos = panelList.GetHeadPosition();
while(pos != NULL) {
CVisualPanel* pPanel = (CVisualPanel*)panelList.GetNext(pos);
if(pPanel->m_bVisible) {
pPanel->Draw(pDC);
}
}
return TRUE;
}
void CWndResizer::ResizeUI(CWndResizer::CPanel* pRoot) {
CPanelList panels;
GetUIPanels(pRoot, &panels, FALSE);
POSITION pos = NULL;
if(panels.GetCount() > 0) {
HDWP hDWP = ::BeginDeferWindowPos((int)panels.GetCount());
ASSERT(hDWP != NULL);
pos = panels.GetHeadPosition();
while(pos != NULL) {
CUIPanel* pPanel = (CUIPanel*)panels.GetNext(pos);
::DeferWindowPos(hDWP, m_pHookedWnd->GetDlgItem(pPanel->m_uID)->m_hWnd, NULL, pPanel->left, pPanel->top, pPanel->Width(), pPanel->Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
}
BOOL bOk = ::EndDeferWindowPos(hDWP);
ASSERT(bOk);
m_pHookedWnd->InvalidateRect(pRoot, FALSE);
}
panels.RemoveAll();
GetUIPanels(pRoot, &panels, TRUE);
pos = panels.GetHeadPosition();
while(pos != NULL) {
CUIPanel* pPanel = (CUIPanel*)panels.GetNext(pos);
m_pHookedWnd->GetDlgItem(pPanel->m_uID)->MoveWindow(pPanel);
}
}
void CWndResizer::OnLButtonDown(UINT nFlags, CPoint point) {
UpdateSplitterOffset(point);
}
void CWndResizer::OnMouseMove(UINT nFlags, CPoint point) {
if(m_pCaptured != NULL) {
if((nFlags & MK_LBUTTON) <= 0) {
CPoint ptScreen = point;
m_pHookedWnd->ClientToScreen(&ptScreen);
HWND hWndFromPoint = ::WindowFromPoint(ptScreen);
if(m_pCaptured->PtInRect(point) == FALSE || hWndFromPoint != m_pHookedWnd->m_hWnd) {
::ReleaseCapture();
m_pCaptured = NULL;
ASSERT(m_hOldCursor != NULL);
HCURSOR hCur = ::SetCursor(m_hOldCursor);
::DestroyCursor(hCur);
m_hOldCursor = NULL;
}
}
}
if(m_pCaptured == NULL && nFlags == 0) {
m_pCaptured = FindSplitterFromPoint(&m_root, point);
if(m_pCaptured != NULL) {
m_pHookedWnd->SetCapture();
LPCTSTR cursor = NULL;
CSplitContainer* pSplitContainer = (CSplitContainer*)m_pCaptured->Parent;
if(pSplitContainer->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
cursor = IDC_SIZEWE;
}
else {
cursor = IDC_SIZENS;
}
HCURSOR hCur = AfxGetApp()->LoadStandardCursor(cursor);
m_hOldCursor = ::SetCursor(hCur);
}
}
if(m_pCaptured != NULL && (nFlags & MK_LBUTTON) > 0) {
CSplitContainer* pSplitterContainer = (CSplitContainer*)m_pCaptured->Parent;
int nCurSplitterPos = pSplitterContainer->GetSplitterPosition();
if(pSplitterContainer->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
pSplitterContainer->SetSplitterPosition(point.x - m_splitterOffset);
}
else {
pSplitterContainer->SetSplitterPosition(point.y - m_splitterOffset);
}
UpdateSplitterOffset(point);
if(nCurSplitterPos != pSplitterContainer->GetSplitterPosition()) {
ResizeUI(pSplitterContainer);
}
}
}
void CWndResizer::OnLButtonUp(UINT nFlags, CPoint point) {
OnMouseMove(nFlags, point);
}
void CWndResizer::UpdateSplitterOffset(CPoint ptCurr) {
if(m_pCaptured == NULL) {
return;
}
if(((CSplitContainer*)m_pCaptured->Parent)->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
if(ptCurr.x < m_pCaptured->left) {
m_splitterOffset = 0;
}
else if(ptCurr.x > m_pCaptured->right) {
m_splitterOffset = m_pCaptured->Width();
}
else {
m_splitterOffset = ptCurr.x - m_pCaptured->left;
}
}
else {
if(ptCurr.y < m_pCaptured->top) {
m_splitterOffset = 0;
}
else if(ptCurr.y > m_pCaptured->bottom) {
m_splitterOffset = m_pCaptured->Height();
}
else {
m_splitterOffset = ptCurr.y - m_pCaptured->top;
}
}
}
void CWndResizer::OnSizing(UINT fwSide, LPRECT pRect) {
CRect* prc = (CRect*)pRect;
CRect rcMin(0, 0, m_root.MinSize.cx, m_root.MinSize.cy);
CRect rcMax(0, 0, m_root.MaxSize.cx, m_root.MaxSize.cy);
LONG_PTR style = GetWindowLongPtr(m_pHookedWnd->m_hWnd, GWL_STYLE);
LONG_PTR styleEx = GetWindowLongPtr(m_pHookedWnd->m_hWnd, GWL_EXSTYLE);
::AdjustWindowRectEx(&rcMin, (DWORD)style, (m_pHookedWnd->GetMenu() != NULL), (DWORD)styleEx);
::AdjustWindowRectEx(&rcMax, (DWORD)style, (m_pHookedWnd->GetMenu() != NULL), (DWORD)styleEx);
switch(fwSide) {
case WMSZ_BOTTOM:
if(prc->Height() < rcMin.Height()) {
prc->bottom = prc->top + rcMin.Height();
}
if(prc->Height() > rcMax.Height()) {
prc->bottom = prc->top + rcMax.Height();
}
break;
case WMSZ_BOTTOMLEFT:
if(prc->Height() < rcMin.Height()) {
prc->bottom = prc->top + rcMin.Height();
}
if(prc->Width() < rcMin.Width()) {
prc->left = prc->right - rcMin.Width();
}
if(prc->Height() > rcMax.Height()) {
prc->bottom = prc->top + rcMax.Height();
}
if(prc->Width() > rcMax.Width()) {
prc->left = prc->right - rcMax.Width();
}
break;
case WMSZ_BOTTOMRIGHT:
if(prc->Height() < rcMin.Height()) {
prc->bottom = prc->top + rcMin.Height();
}
if(prc->Width() < rcMin.Width()) {
prc->right = prc->left + rcMin.Width();
}
if(prc->Height() > rcMax.Height()) {
prc->bottom = prc->top + rcMax.Height();
}
if(prc->Width() > rcMax.Width()) {
prc->right = prc->left + rcMax.Width();
}
break;
case WMSZ_LEFT:
if(prc->Width() < rcMin.Width()) {
prc->left = prc->right - rcMin.Width();
}
if(prc->Width() > rcMax.Width()) {
prc->left = prc->right - rcMax.Width();
}
break;
case WMSZ_RIGHT:
if(prc->Width() < rcMin.Width()) {
prc->right = prc->left + rcMin.Width();
}
if(prc->Width() > rcMax.Width()) {
prc->right = prc->left + rcMax.Width();
}
break;
case WMSZ_TOP:
if(prc->Height() < rcMin.Height()) {
prc->top = prc->bottom - rcMin.Height();
}
if(prc->Height() > rcMax.Height()) {
prc->top = prc->bottom - rcMax.Height();
}
break;
case WMSZ_TOPLEFT:
if(prc->Height() < rcMin.Height()) {
prc->top = prc->bottom - rcMin.Height();
}
if(prc->Width() < rcMin.Width()) {
prc->left = prc->right - rcMin.Width();
}
if(prc->Height() > rcMax.Height()) {
prc->top = prc->bottom - rcMax.Height();
}
if(prc->Width() > rcMax.Width()) {
prc->left = prc->right - rcMax.Width();
}
break;
case WMSZ_TOPRIGHT:
if(prc->Height() < rcMin.Height()) {
prc->top = prc->bottom - rcMin.Height();
}
if(prc->Width() < rcMin.Width()) {
prc->right = prc->left + rcMin.Width();
}
if(prc->Height() > rcMax.Height()) {
prc->top = prc->bottom - rcMax.Height();
}
if(prc->Width() > rcMax.Width()) {
prc->right = prc->left + rcMax.Width();
}
break;
}
}
void CWndResizer::OnPaint() {
if(m_pHookedWnd == NULL) {
return;
}
if(!GetAutoHandlePaint()) {
return;
}
CPaintDC dc(m_pHookedWnd); // device context for painting
Draw(&dc);
}
BOOL CWndResizer::SetAnchor(LPCTSTR panelName, UINT uAnchor) {
// container must already exist
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
return pPanel->SetAnchor(uAnchor);
}
BOOL CWndResizer::SetAnchor(UINT uID, UINT uAnchor) {
ASSERT(m_pHookedWnd != NULL);
CUIPanel* pPanel = GetUIPanel(uID);
if(pPanel == NULL) {
return FALSE;
}
pPanel->SetAnchor(uAnchor);
return TRUE;
}
BOOL CWndResizer::GetAnchor(LPCTSTR panelName, UINT& anchor) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) // name of parent must already exist
{
return FALSE;
}
anchor = pPanel->Anchor;
return TRUE;
}
BOOL CWndResizer::GetAnchor(UINT uID, UINT& anchor) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist
{
return FALSE;
}
anchor = pPanel->Anchor;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL CWndResizer::SetDock(LPCTSTR panelName, UINT uDock) {
// container must already exist
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
pPanel->Dock = uDock;
return TRUE;
}
BOOL CWndResizer::SetDock(UINT uID, UINT uDock) {
ASSERT(m_pHookedWnd != NULL);
CUIPanel* pPanel = GetUIPanel(uID);
if(pPanel == NULL) {
return FALSE;
}
pPanel->Dock = uDock;
return TRUE;
}
BOOL CWndResizer::GetDock(LPCTSTR panelName, UINT& uDock) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) // name of parent must already exist
{
return FALSE;
}
uDock = pPanel->Dock;
return TRUE;
}
BOOL CWndResizer::GetDock(UINT uID, UINT& uDock) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist
{
return FALSE;
}
uDock = pPanel->Dock;
return TRUE;
}
//////////////////////
BOOL CWndResizer::SetParent(LPCTSTR panelName, LPCTSTR parentName) {
ASSERT(m_pHookedWnd != NULL);
// now make sure parentName is OK
CPanel* pParent = NULL;
if((pParent = FindPanelByName(&m_root, parentName)) == NULL) // name of parent must already exist
{
return FALSE;
}
// make sure panelName exist
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
return pParent->AddChild(pPanel);
}
BOOL CWndResizer::SetParent(UINT uID, LPCTSTR parentName) {
ASSERT(m_pHookedWnd != NULL);
// now make sure parentName is OK
CPanel* pParent = NULL;
if((pParent = FindPanelByName(&m_root, parentName)) == NULL) // name of parent must already exist
{
return FALSE;
}
// first see if it is already defined
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) {
if((pPanel = CreateUIPanel(uID)) == NULL) {
return FALSE;
}
}
return pParent->AddChild(pPanel);
}
BOOL CWndResizer::SetParent(LPCTSTR panelName, UINT uParentID) {
ASSERT(m_pHookedWnd != NULL);
// now make sure parentName is OK
CPanel* pParent = NULL;
if((pParent = GetUIPanel(uParentID)) == NULL) // name of parent must already exist
{
return FALSE;
}
// make sure panelName exist
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
return pParent->AddChild(pPanel);
}
BOOL CWndResizer::SetParent(UINT uID, UINT uParentID) {
// now make sure parentName is OK
CPanel* pParent = NULL;
if((pParent = GetUIPanel(uParentID)) == NULL) // name of parent must already exist
{
return FALSE;
}
// make sure panelName exist
CPanel* pPanel = NULL;
if((pPanel = GetUIPanel(uID)) == NULL) {
return FALSE;
}
return pParent->AddChild(pPanel);
}
BOOL CWndResizer::GetParent(LPCTSTR panelName, CString& parentName) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
parentName = pPanel->Parent->Name;
return TRUE;
}
BOOL CWndResizer::GetParent(UINT uID, CString& parentName) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist
{
return FALSE;
}
parentName = pPanel->Parent->Name;
return TRUE;
}
BOOL CWndResizer::SetFixedPanel(LPCTSTR splitContainerName, short panel) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
pSplitContainer->SetFixedPanel(panel);
return TRUE;
}
BOOL CWndResizer::GetFixedPanel(LPCTSTR splitContainerName, short& panel) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
panel = pSplitContainer->GetFixedPanel();
return TRUE;
}
BOOL CWndResizer::SetIsSplitterFixed(LPCTSTR splitContainerName, BOOL fixed) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
pSplitContainer->SetIsSplitterFixed(fixed);
return TRUE;
}
BOOL CWndResizer::GetIsSplitterFixed(LPCTSTR splitContainerName, BOOL& fixed) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
fixed = pSplitContainer->GetIsSplitterFixed();
return TRUE;
}
BOOL CWndResizer::SetShowSplitterGrip(LPCTSTR splitContainerName, BOOL bShow) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
pSplitContainer->SetShowSplitterGrip(bShow);
return TRUE;
}
BOOL CWndResizer::GetShowSplitterGrip(LPCTSTR splitContainerName, BOOL& bShow) {
CPanel* pContainer = FindPanelByName(&m_root, splitContainerName);
if(pContainer == NULL) {
return FALSE;
}
CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer);
if(pSplitContainer == NULL) {
return FALSE;
}
bShow = pSplitContainer->GetShowSplitterGrip();
return TRUE;
}
/////////////////////////
BOOL CWndResizer::SetMinimumSize(LPCTSTR panelName, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
return pPanel->SetMinSize(size);
}
BOOL CWndResizer::SetMinimumSize(UINT uID, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) {
if((pPanel = CreateUIPanel(uID)) == NULL) {
return FALSE;
}
}
return pPanel->SetMinSize(size);
}
BOOL CWndResizer::GetMinimumSize(LPCTSTR panelName, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
size = pPanel->MinSize;
return TRUE;
}
BOOL CWndResizer::GetMinimumSize(UINT uID, CSize& size) {
const CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) {
return FALSE;
}
size = pPanel->MinSize;
return TRUE;
}
BOOL CWndResizer::SetMaximumSize(UINT uID, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) {
return FALSE;
}
return pPanel->SetMaxSize(size);
}
BOOL CWndResizer::SetMaximumSize(LPCTSTR panelName, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
return pPanel->SetMaxSize(size);
}
BOOL CWndResizer::GetMaximumSize(LPCTSTR panelName, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) {
return FALSE;
}
size = pPanel->MaxSize;
return TRUE;
}
BOOL CWndResizer::GetMaximumSize(UINT uID, CSize& size) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) {
return FALSE;
}
size = pPanel->MaxSize;
return TRUE;
}
void CWndResizer::SetShowResizeGrip(BOOL show) {
CGripperPanel* pPanel = (CGripperPanel*)FindPanelByName(&m_root, _T("_resizeGrip"));
ASSERT(pPanel != NULL);
if(pPanel->m_bVisible != show) {
pPanel->m_bVisible = show;
m_pHookedWnd->Invalidate(TRUE);
}
}
BOOL CWndResizer::GetShowResizeGrip() {
CGripperPanel* pPanel = (CGripperPanel*)FindPanelByName(&m_root, _T("_resizeGrip"));
ASSERT(pPanel != NULL);
return pPanel->m_bVisible;
}
void CWndResizer::OnDestroy() {
if(m_pHookedWnd != NULL) {
Unhook();
}
}
BOOL CWndResizer::Unhook() {
ASSERT(m_pHookedWnd != NULL);
if(m_pHookedWnd == NULL) {
return FALSE; // hasent been hooked
}
WNDPROC pWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)m_pfnWndProc);
WndResizerData.RemoveKey(m_pHookedWnd->m_hWnd);
m_root.m_pHookWnd = NULL;
m_pHookedWnd = NULL;
// destroy all chilldren
while(m_root.Children.GetCount() > 0) {
CPanel* pChild = m_root.Children.RemoveHead();
delete pChild;
}
return TRUE;
}
LRESULT CALLBACK CWndResizer::WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
CWndResizer* pResizer = NULL;
WndResizerData.Lookup(hWnd, pResizer);
ASSERT(pResizer != NULL);
switch(uMsg) {
case WM_SIZE: {
int cx = 0;
int cy = 0;
cx = LOWORD(lParam);
cy = HIWORD(lParam);
pResizer->OnSize((UINT)wParam, cx, cy);
} break;
case WM_SIZING: pResizer->OnSizing((UINT)wParam, (LPRECT)lParam); break;
case WM_DESTROY: pResizer->OnDestroy(); break;
case WM_MOUSEMOVE: pResizer->OnMouseMove((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break;
case WM_LBUTTONDOWN: pResizer->OnLButtonDown((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break;
case WM_LBUTTONUP: pResizer->OnLButtonUp((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break;
case WM_PAINT: pResizer->OnPaint(); break;
case WM_HSCROLL:
case WM_VSCROLL:
pResizer->OnScroll();
break;
// case WM_ERASEBKGND:
// return FALSE;
// break;
default: break;
}
return ::CallWindowProc(pResizer->m_pfnWndProc, hWnd, uMsg, wParam, lParam);
}
BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, LPCTSTR panelNameA, LPCTSTR panelNameB) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) {
return FALSE;
}
CPanel* pPanelA = NULL;
if((pPanelA = FindPanelByName(&m_root, panelNameA)) == NULL) {
return FALSE;
}
CPanel* pPanelB = NULL;
if((pPanelB = FindPanelByName(&m_root, panelNameB)) == NULL) {
return FALSE;
}
if(pPanelA == pPanelB) // two panel cannot be same
{
return FALSE;
}
CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB);
if(pSplitterContainer == NULL) {
return FALSE;
}
pSplitterContainer->Name = panelName;
return m_root.AddChild(pSplitterContainer);
}
BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, LPCTSTR panelNameA, UINT panelIDB) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) {
return FALSE;
}
CPanel* pPanelA = NULL;
if((pPanelA = FindPanelByName(&m_root, panelNameA)) == NULL) {
return FALSE;
}
CPanel* pPanelB = GetUIPanel(panelIDB);
if(pPanelB == NULL) {
return FALSE;
}
if(pPanelA == pPanelB) // two panel cannot be same
{
return FALSE;
}
// first lets make sure the two CRect are properly set
CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB);
if(pSplitterContainer == NULL) {
return FALSE;
}
pSplitterContainer->Name = panelName;
return m_root.AddChild(pSplitterContainer);
}
BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, UINT panelIDA, LPCTSTR panelNameB) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) {
return FALSE;
}
CPanel* pPanelA = GetUIPanel(panelIDA);
if(pPanelA == NULL) {
return FALSE;
}
CPanel* pPanelB = NULL;
if((pPanelB = FindPanelByName(&m_root, panelNameB)) == NULL) {
return FALSE;
}
if(pPanelA == pPanelB) // two panel cannot be same
{
return FALSE;
}
CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB);
if(pSplitterContainer == NULL) {
return FALSE;
}
pSplitterContainer->Name.Append(panelName);
return m_root.AddChild(pSplitterContainer);
}
BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, UINT panelIDA, UINT panelIDB) {
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) {
return FALSE;
}
CPanel* pPanelA = GetUIPanel(panelIDA);
if(pPanelA == NULL) {
return FALSE;
}
CPanel* pPanelB = GetUIPanel(panelIDB);
if(pPanelB == NULL) {
return FALSE;
}
if(pPanelA == pPanelB) // two panel cannot be same
{
return FALSE;
}
CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB);
if(pSplitterContainer == NULL) {
return FALSE;
}
pSplitterContainer->Name = panelName;
return m_root.AddChild(pSplitterContainer);
}
BOOL CWndResizer::SetSplitterPosition(LPCTSTR splitContainerName, UINT position) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, splitContainerName)) == NULL) {
return FALSE;
}
CSplitContainer* pContainer = dynamic_cast<CSplitContainer*>(pPanel);
if(pContainer == NULL) {
return FALSE;
}
pContainer->SetSplitterPosition((int)position);
ResizeUI(pContainer);
return TRUE;
}
BOOL CWndResizer::GetSplitterPosition(LPCTSTR splitContainerName, UINT& position) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, splitContainerName)) == NULL) {
return FALSE;
}
CSplitContainer* pContainer = dynamic_cast<CSplitContainer*>(pPanel);
if(pContainer == NULL) {
return FALSE;
}
position = (UINT)pContainer->GetSplitterPosition();
return TRUE;
}
BOOL CWndResizer::CreatePanel(UINT uID) {
ASSERT(m_pHookedWnd != NULL);
if(FindPanelByName(&m_root, IdToName(uID)) != NULL) {
return FALSE;
}
CUIPanel* pPanel = GetUIPanel(uID);
ASSERT(pPanel != NULL);
pPanel->m_bOle = TRUE;
return TRUE;
}
BOOL CWndResizer::SetFlowDirection(LPCTSTR flowPanelName, short direction) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
pFlowLayout->SetFlowDirection(direction == 1 ? CWndResizer::LEFT_TO_RIGHT : CWndResizer::TOP_TO_BOTTOM);
return TRUE;
}
BOOL CWndResizer::GetFlowDirection(LPCTSTR flowPanelName, short& direction) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
direction = (pFlowLayout->GetFlowDirection() == CWndResizer::LEFT_TO_RIGHT ? 1 : 2);
return TRUE;
}
BOOL CWndResizer::SetFlowItemSpacingX(LPCTSTR flowPanelName, int nSpacing) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
pFlowLayout->SetItemSpacingX(nSpacing);
return TRUE;
}
BOOL CWndResizer::GetFlowItemSpacingX(LPCTSTR flowPanelName, int& nSpacing) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
nSpacing = pFlowLayout->GetItemSpacingX();
return TRUE;
}
BOOL CWndResizer::SetFlowItemSpacingY(LPCTSTR flowPanelName, int nSpacing) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
pFlowLayout->SetItemSpacingY(nSpacing);
return TRUE;
}
BOOL CWndResizer::GetFlowItemSpacingY(LPCTSTR flowPanelName, int& nSpacing) {
ASSERT(m_pHookedWnd != NULL);
CPanel* pPanel = NULL;
if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) {
return FALSE;
}
CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel);
if(pFlowLayout == NULL) {
return FALSE;
}
nSpacing = pFlowLayout->GetItemSpacingY();
return TRUE;
}
BOOL CWndResizer::CreateFlowLayoutPanel(LPCTSTR panelName, const CRect* prcPanel) {
if(FindPanelByName(&m_root, panelName) != NULL) {
return FALSE;
}
CPanel* pPanel = new CFlowLayoutPanel(prcPanel);
pPanel->Name = panelName;
return m_root.AddChild(pPanel);
}
BOOL CWndResizer::CreateFlowLayoutPanel(LPCTSTR panelName, const CUIntArray* parrID, BOOL setAsChildren) {
ASSERT(m_pHookedWnd != NULL);
CRect rcFinal(0, 0, 0, 0);
for(int i = 0; i < parrID->GetCount(); i++) {
CRect rc(0, 0, 0, 0);
m_pHookedWnd->GetDlgItem(parrID->GetAt(i))->GetWindowRect(&rc);
m_pHookedWnd->ScreenToClient(&rc);
rcFinal.UnionRect(&rcFinal, &rc);
}
BOOL bOk = CreateFlowLayoutPanel(panelName, &rcFinal);
if(bOk == FALSE) {
return FALSE;
}
if(setAsChildren) {
CPanel* pPanel = FindPanelByName(&m_root, panelName);
for(int i = 0; i < parrID->GetCount(); i++) {
if(FindPanelByName(&m_root, IdToName(parrID->GetAt(i))) != NULL) {
bOk = m_root.RemoveChild(pPanel);
ASSERT(bOk);
delete pPanel;
return FALSE;
}
CUIPanel* pUIPanel = GetUIPanel(parrID->GetAt(i));
ASSERT(pUIPanel != NULL);
bOk = pPanel->AddChild(pUIPanel);
ASSERT(bOk);
}
}
return TRUE;
}
BOOL CWndResizer::CreatePanel(LPCTSTR panelName, const CRect* prcPanel) {
if(FindPanelByName(&m_root, panelName) != NULL) {
return FALSE;
}
CPanel* pPanel = new CPanel(prcPanel);
pPanel->Name = panelName;
return m_root.AddChild(pPanel);
}
BOOL CWndResizer::CreatePanel(LPCTSTR panelName, const CUIntArray* parrID, BOOL setAsChildren) {
ASSERT(m_pHookedWnd != NULL);
CRect rcFinal(0, 0, 0, 0);
for(int i = 0; i < parrID->GetCount(); i++) {
CRect rc(0, 0, 0, 0);
m_pHookedWnd->GetDlgItem(parrID->GetAt(i))->GetWindowRect(&rc);
m_pHookedWnd->ScreenToClient(&rc);
rcFinal.UnionRect(&rcFinal, &rc);
}
BOOL bOk = CreatePanel(panelName, &rcFinal);
if(bOk == FALSE) {
return FALSE;
}
if(setAsChildren) {
CPanel* pPanel = FindPanelByName(&m_root, panelName);
for(int i = 0; i < parrID->GetCount(); i++) {
if(FindPanelByName(&m_root, IdToName(parrID->GetAt(i))) != NULL) {
bOk = m_root.RemoveChild(pPanel);
ASSERT(bOk);
delete pPanel;
return FALSE;
}
CUIPanel* pUIPanel = GetUIPanel(parrID->GetAt(i));
ASSERT(pUIPanel != NULL);
bOk = pPanel->AddChild(pUIPanel);
ASSERT(bOk);
}
}
return TRUE;
}
CWndResizer::CPanel* CWndResizer::FindPanelByName(CWndResizer::CPanel* pRoot, LPCTSTR name) {
if(CString(name).GetLength() == 0) {
return NULL;
}
if(pRoot == NULL) {
return NULL;
}
if(pRoot->Name.CompareNoCase(name) == 0) {
return pRoot;
}
else {
POSITION pos = pRoot->Children.GetHeadPosition();
while(pos != NULL) {
CPanel* pChild = pRoot->Children.GetNext(pos);
CPanel* pFound = FindPanelByName(pChild, name);
if(pFound != NULL) {
return pFound;
}
}
}
return NULL;
}
void CWndResizer::GetUIPanels(CWndResizer::CPanel* pRoot, CPanelList* pList, BOOL bOle) {
if(pRoot == NULL) {
return;
}
CUIPanel* pUIPanel = dynamic_cast<CUIPanel*>(pRoot);
if(pUIPanel != NULL && pUIPanel->m_bOle == bOle) {
pList->AddTail(pRoot);
}
// try the childreen
POSITION pos = pRoot->Children.GetHeadPosition();
while(pos != NULL) {
CPanel* pChild = pRoot->Children.GetNext(pos);
GetUIPanels(pChild, pList, bOle);
}
}
void CWndResizer::GetVisualPanels(CWndResizer::CPanel* pRoot, CPanelList* pList) {
if(pRoot == NULL) {
return;
}
CVisualPanel* pUIPanel = dynamic_cast<CVisualPanel*>(pRoot);
if(pUIPanel != NULL) {
pList->AddTail(pRoot);
}
// try the childreen
POSITION pos = pRoot->Children.GetHeadPosition();
while(pos != NULL) {
CPanel* pChild = pRoot->Children.GetNext(pos);
GetVisualPanels(pChild, pList);
}
}
CWndResizer::CPanel* CWndResizer::FindSplitterFromPoint(CWndResizer::CPanel* pRoot, CPoint point) {
if(pRoot == NULL) {
return NULL;
}
CSpitterPanel* pSpitterPanel = dynamic_cast<CSpitterPanel*>(pRoot);
if(pSpitterPanel != NULL && pRoot->PtInRect(point) == TRUE) {
CSplitContainer* pContainer = (CSplitContainer*)pRoot->Parent;
if(!pContainer->GetIsSplitterFixed()) {
CPoint ptScreen = point;
m_pHookedWnd->ClientToScreen(&ptScreen);
HWND hWndFromPoint = ::WindowFromPoint(ptScreen);
if(m_pHookedWnd->m_hWnd == hWndFromPoint) {
return pRoot;
}
}
}
// try the childreen
POSITION pos = pRoot->Children.GetHeadPosition();
while(pos != NULL) {
CPanel* pChild = pRoot->Children.GetNext(pos);
CPanel* pFound = FindSplitterFromPoint(pChild, point);
if(pFound != NULL) {
return pFound;
}
}
return NULL;
}
CString CWndResizer::IdToName(UINT uID) {
CString sName;
sName.Format(_T("%d"), uID);
return sName;
}
CWndResizer::CUIPanel* CWndResizer::CreateUIPanel(UINT uID) {
ASSERT(m_pHookedWnd != NULL);
CWnd* pWnd = m_pHookedWnd->GetDlgItem(uID);
if(pWnd == NULL) {
return NULL;
}
CRect rc(0, 0, 0, 0);
pWnd->GetWindowRect(&rc);
m_pHookedWnd->ScreenToClient(&rc);
CUIPanel* pPanel = new CUIPanel(&rc, uID);
pPanel->Name = IdToName(uID);
return pPanel;
}
CWndResizer::CUIPanel* CWndResizer::GetUIPanel(UINT uID) {
CUIPanel* pPanel = NULL;
if((pPanel = (CUIPanel*)FindPanelByName(&m_root, IdToName(uID))) == NULL) {
pPanel = CreateUIPanel(uID);
if(pPanel != NULL) {
m_root.AddChild(pPanel);
}
}
return pPanel;
}
BOOL CWndResizer::InvokeOnResized() {
ASSERT(m_pHookedWnd != NULL);
OnSize(0, 0, 0);
return TRUE;
}
CString CWndResizer::GetDebugInfo() {
ASSERT(m_pHookedWnd != NULL);
CString sInfo;
CString sIndent;
GetDebugInfo(&m_root, sInfo, sIndent);
return sInfo;
}
void CWndResizer::GetDebugInfo(CPanel* pRoot, CString& info, CString indent) {
if(pRoot == NULL) {
return;
}
info.Append(_T("\n"));
info.Append(indent);
info.Append(pRoot->ToString());
indent.Append(_T(" "));
for(int i = 0; i < pRoot->Children.GetCount(); i++) {
CPanel* pChild = pRoot->Children.GetAt(pRoot->Children.FindIndex(i));
GetDebugInfo(pChild, info, indent);
}
}
///////////////////////////// CPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CPanel::CPanel()
: CRect(0, 0, 0, 0) {
Init();
}
CWndResizer::CPanel::CPanel(const CRect* prc)
: CRect(prc) {
Init();
}
void CWndResizer::CPanel::Init() {
Parent = NULL;
LeftOffset = 0;
TopOffset = 0;
RightOffset = 0;
BottomOffset = 0;
MinSize.SetSize(10, 10);
MaxSize.SetSize(100000, 100000);
Anchor = (ANCHOR_LEFT | ANCHOR_TOP);
Dock = DOCK_NONE;
}
CWndResizer::CPanel::~CPanel() {
while(Children.GetCount() > 0) {
delete Children.RemoveHead();
}
}
void CWndResizer::CPanel::OnResized() {
BOOL bOk = FALSE;
CRect rcEmpty(this); // available area for docking. ininitally it is the entire area
POSITION pos = Children.GetHeadPosition();
while(pos != NULL) {
CPanel* pChild = Children.GetNext(pos);
if(pChild->Dock != DOCK_NONE) {
switch(pChild->Dock) {
case DOCK_LEFT:
pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.left + pChild->Width(), rcEmpty.bottom);
bOk = rcEmpty.SubtractRect(&rcEmpty, pChild);
// ASSERT( bOk );
break;
case DOCK_TOP:
pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.right, rcEmpty.top + pChild->Height());
bOk = rcEmpty.SubtractRect(&rcEmpty, pChild);
// ASSERT( bOk );
break;
case DOCK_RIGHT:
pChild->SetRect(rcEmpty.right - pChild->Width(), rcEmpty.top, rcEmpty.right, rcEmpty.bottom);
bOk = rcEmpty.SubtractRect(&rcEmpty, pChild);
// ASSERT( bOk );
break;
case DOCK_BOTTOM:
pChild->SetRect(rcEmpty.left, rcEmpty.bottom - pChild->Height(), rcEmpty.right, rcEmpty.bottom);
bOk = rcEmpty.SubtractRect(&rcEmpty, pChild);
// ASSERT( bOk );
break;
case DOCK_FILL: pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.right, rcEmpty.bottom); break;
}
pChild->OnResized();
// if docking is in action, then we igonre anchor, therefore we continue
continue;
}
CRect rc(0, 0, 0, 0);
if((pChild->Anchor & ANCHOR_HORIZONTALLY_CENTERED) == ANCHOR_HORIZONTALLY_CENTERED) {
rc.left = this->left + ((int)((this->Width() - pChild->Width()) / 2));
rc.right = rc.left + pChild->Width();
BOOL bReposition = FALSE;
if(pChild->MinSize.cx > rc.Width()) {
bReposition = TRUE;
rc.right = rc.left + pChild->MinSize.cx;
}
if(pChild->MaxSize.cx < rc.Width()) {
bReposition = TRUE;
rc.right = rc.left + pChild->MaxSize.cx;
}
if(bReposition) {
int nWidth = rc.Width();
rc.left = (int)((this->Width() - nWidth) / 2);
rc.right = rc.left + nWidth;
}
}
else if((pChild->Anchor & ANCHOR_HORIZONTALLY) == ANCHOR_HORIZONTALLY) {
rc.left = this->left + pChild->LeftOffset;
rc.right = this->right - pChild->RightOffset;
// we will be left anchor if minsize or maxsize does not match
// (giving ANCHOR_LEFT priority over ANCHOR_RIGHT)
if((pChild->Anchor & ANCHOR_PRIORITY_RIGHT) == ANCHOR_PRIORITY_RIGHT) {
if(pChild->MinSize.cx > rc.Width()) {
rc.left = rc.right - pChild->MinSize.cx;
}
if(pChild->MaxSize.cx < rc.Width()) {
rc.left = rc.right - pChild->MaxSize.cx;
}
}
else {
if(pChild->MinSize.cx > rc.Width()) {
rc.right = rc.left + pChild->MinSize.cx;
}
if(pChild->MaxSize.cx < rc.Width()) {
rc.right = rc.left + pChild->MaxSize.cx;
}
}
}
else if((pChild->Anchor & ANCHOR_RIGHT) == ANCHOR_RIGHT) {
rc.right = this->right - pChild->RightOffset;
rc.left = rc.right - pChild->Width();
if(pChild->MinSize.cx > rc.Width()) {
rc.left = rc.right - pChild->MinSize.cx;
}
if(pChild->MaxSize.cx < rc.Width()) {
rc.left = rc.right - pChild->MaxSize.cx;
}
}
else if((pChild->Anchor & ANCHOR_LEFT) == ANCHOR_LEFT) {
rc.left = this->left + pChild->LeftOffset;
rc.right = rc.left + pChild->Width();
if(pChild->MinSize.cx > rc.Width()) {
rc.right = rc.left + pChild->MinSize.cx;
}
if(pChild->MaxSize.cx < rc.Width()) {
rc.right = rc.left + pChild->MaxSize.cx;
}
}
else {
// it should never be here
ASSERT(FALSE);
}
if((pChild->Anchor & ANCHOR_VERTICALLY_CENTERED) == ANCHOR_VERTICALLY_CENTERED) {
rc.top = this->top + ((int)((this->Height() - pChild->Height()) / 2));
rc.bottom = rc.top + pChild->Height();
BOOL bReposition = FALSE;
if(pChild->MinSize.cy > rc.Height()) {
bReposition = TRUE;
rc.bottom = rc.top + pChild->MinSize.cy;
}
if(pChild->MaxSize.cy < rc.Height()) {
bReposition = TRUE;
rc.bottom = rc.top + pChild->MaxSize.cy;
}
if(bReposition) {
int nHeight = rc.Height();
rc.top = (int)((this->Height() - nHeight) / 2);
rc.bottom = rc.top + nHeight;
}
}
else if((pChild->Anchor & ANCHOR_VERTICALLY) == ANCHOR_VERTICALLY) {
rc.top = this->top + pChild->TopOffset;
rc.bottom = this->bottom - pChild->BottomOffset;
if((pChild->Anchor & ANCHOR_PRIORITY_BOTTOM) == ANCHOR_PRIORITY_BOTTOM) {
if(pChild->MinSize.cy > rc.Height()) {
rc.top = rc.bottom - pChild->MinSize.cy;
}
if(pChild->MaxSize.cy < rc.Height()) {
rc.top = rc.bottom - pChild->MaxSize.cy;
}
}
else {
if(pChild->MinSize.cy > rc.Height()) {
rc.bottom = rc.top + pChild->MinSize.cy;
}
if(pChild->MaxSize.cy < rc.Height()) {
rc.bottom = rc.top + pChild->MaxSize.cy;
}
}
}
else if((pChild->Anchor & ANCHOR_BOTTOM) == ANCHOR_BOTTOM) {
rc.bottom = this->bottom - pChild->BottomOffset;
rc.top = rc.bottom - pChild->Height();
if(pChild->MinSize.cy > rc.Height()) {
rc.top = rc.bottom - pChild->MinSize.cy;
}
if(pChild->MaxSize.cy < rc.Height()) {
rc.top = rc.bottom - pChild->MaxSize.cy;
}
}
else if((pChild->Anchor & ANCHOR_TOP) == ANCHOR_TOP) {
rc.top = this->top + pChild->TopOffset;
rc.bottom = rc.top + pChild->Height();
if(pChild->MinSize.cy > rc.Height()) {
rc.bottom = rc.top + pChild->MinSize.cy;
}
if(pChild->MaxSize.cy < rc.Height()) {
rc.bottom = rc.top + pChild->MaxSize.cy;
}
}
else {
// it should never be here
ASSERT(FALSE);
}
pChild->SetRect(rc.TopLeft(), rc.BottomRight());
pChild->OnResized();
}
}
BOOL CWndResizer::CPanel::AddChild(CPanel* pChild) {
if(pChild->Parent != NULL) {
BOOL bOk = pChild->Parent->RemoveChild(pChild);
if(bOk == FALSE) {
return FALSE;
}
}
pChild->LeftOffset = pChild->left - this->left;
pChild->TopOffset = pChild->top - this->top;
pChild->RightOffset = this->right - pChild->right;
pChild->BottomOffset = this->bottom - pChild->bottom;
pChild->Parent = this;
Children.AddTail(pChild);
return TRUE;
}
BOOL CWndResizer::CPanel::RemoveChild(CPanel* pChild) {
POSITION pos = Children.Find(pChild);
if(pos == NULL) {
return FALSE;
}
Children.RemoveAt(pos);
return TRUE;
}
BOOL CWndResizer::CPanel::SetMinSize(CSize& size) {
if(MaxSize.cx < size.cx) {
return FALSE;
}
if(MaxSize.cy < size.cy) {
return FALSE;
}
MinSize = size;
return TRUE;
}
BOOL CWndResizer::CPanel::SetMaxSize(CSize& size) {
if(MinSize.cx > size.cx) {
return FALSE;
}
if(MinSize.cy > size.cy) {
return FALSE;
}
MaxSize = size;
return TRUE;
}
BOOL CWndResizer::CPanel::SetAnchor(UINT anchor) {
if((anchor & ANCHOR_VERTICALLY_CENTERED) <= 0) {
if((anchor & ANCHOR_TOP) <= 0) {
if((anchor & ANCHOR_BOTTOM) <= 0) {
anchor |= ANCHOR_TOP; // default
}
}
}
if((anchor & ANCHOR_HORIZONTALLY_CENTERED) <= 0) {
if((anchor & ANCHOR_LEFT) <= 0) {
if((anchor & ANCHOR_RIGHT) <= 0) {
anchor |= ANCHOR_LEFT; // default
}
}
}
Anchor = anchor;
return TRUE;
}
CString CWndResizer::CPanel::ToString() {
CString sFormat(_T("Name(%s), Type(%s), Anchor(%d), Size(w:%d, h:%d), Area(l:%d, t:%d, r:%d, b:%d), MinSize(w:%d, h:%d), MaxSize(w:%d, h:%d), ")
_T("Parent(%s), ChildrenCount(%d)"));
CString sTo;
sTo.Format(sFormat, Name, GetTypeName(), Anchor, Width(), Height(), left, top, right, bottom, MinSize.cx, MinSize.cy, MaxSize.cx, MaxSize.cy,
(Parent == NULL ? _T("NULL") : Parent->Name), Children.GetCount());
return sTo;
}
CString CWndResizer::CPanel::GetTypeName() {
return _T("CPanel");
}
CWnd* CWndResizer::CPanel::GetHookedWnd() {
if(Parent != NULL) {
return Parent->GetHookedWnd();
}
return NULL;
}
///////////////////////////// CSplitContainer
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CSplitContainer::CSplitContainer(CSplitPanel* pPanelA, CSplitPanel* pPanelB, CWndResizer::SplitterOrientation type)
: CPanel() {
m_IsSplitterFixed = FALSE;
m_FixedPanel = 0;
m_pPanelA = NULL;
m_pPanelB = NULL;
m_pSplitter = NULL;
m_Orientation = type;
m_pPanelA = pPanelA;
m_pPanelB = pPanelB;
UnionRect(m_pPanelA, m_pPanelB);
CRect rc(0, 0, 0, 0);
GetSplitArea(&rc);
m_pSplitter = new CSpitterPanel(&rc, type);
m_pSplitter->m_pGrippePanel->m_bVisible = FALSE;
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
m_pPanelA->Anchor = (ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_BOTTOM);
m_pPanelB->Anchor = (ANCHOR_RIGHT | ANCHOR_TOP | ANCHOR_BOTTOM);
}
else {
m_pPanelA->Anchor = (ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT);
m_pPanelB->Anchor = (ANCHOR_LEFT | ANCHOR_BOTTOM | ANCHOR_RIGHT);
}
m_nSplitterSize = GetSplitterSize(m_pPanelA, m_pPanelB);
BOOL bOk = AddChild(m_pPanelA);
ASSERT(bOk);
bOk = AddChild(m_pSplitter);
ASSERT(bOk);
bOk = AddChild(m_pPanelB);
ASSERT(bOk);
UpdateRatio();
}
CWndResizer::CSplitContainer::~CSplitContainer() {}
void CWndResizer::CSplitContainer::OnResized() {
CPanel::OnResized();
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
if(Width() < MinSize.cx) {
return;
}
if(m_FixedPanel == 1) // left panel is fixed
{
m_pPanelB->left = m_pPanelA->right + m_nSplitterSize;
if(m_pPanelB->MinSize.cx > m_pPanelB->Width()) {
m_pPanelB->left = m_pPanelB->right - m_pPanelB->MinSize.cx;
m_pPanelA->right = m_pPanelB->left - m_nSplitterSize;
}
}
else if(m_FixedPanel == 2) // right panel is fixed
{
m_pPanelA->right = m_pPanelB->left - m_nSplitterSize;
if(m_pPanelA->MinSize.cx > m_pPanelA->Width()) {
m_pPanelA->right = m_pPanelA->left + m_pPanelA->MinSize.cx;
m_pPanelB->left = m_pPanelA->right + m_nSplitterSize;
}
}
else {
m_pPanelA->right = (LONG)((double)m_pPanelA->left + ((double)this->Width() * m_nRatio));
if(m_pPanelA->MinSize.cx > m_pPanelA->Width()) {
m_pPanelA->right = m_pPanelA->left + m_pPanelA->MinSize.cx;
}
m_pPanelB->left = m_pPanelA->right + m_nSplitterSize;
if(m_pPanelB->MinSize.cx > m_pPanelB->Width()) {
m_pPanelB->left = m_pPanelB->right - m_pPanelB->MinSize.cx;
m_pPanelA->right = m_pPanelB->left - m_nSplitterSize;
}
}
}
else /*if (m_Orientation == CWndResizer::SPLIT_CONTAINER_V)*/
{
if(Height() < MinSize.cy) {
return;
}
if(m_FixedPanel == 1) // top panel is fixed
{
m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize;
if(m_pPanelB->MinSize.cy > m_pPanelB->Height()) {
m_pPanelB->top = m_pPanelB->bottom - m_pPanelB->MinSize.cy;
m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize;
}
}
else if(m_FixedPanel == 2) // bottom panel is fixed
{
m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize;
if(m_pPanelA->MinSize.cy > m_pPanelA->Height()) {
m_pPanelA->bottom = m_pPanelA->top + m_pPanelA->MinSize.cy;
m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize;
}
}
else {
m_pPanelA->bottom = (LONG)((double)m_pPanelA->top + ((double)this->Height() * m_nRatio));
if(m_pPanelA->MinSize.cy > m_pPanelA->Height()) {
m_pPanelA->bottom = m_pPanelA->top + m_pPanelA->MinSize.cy;
}
m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize;
if(m_pPanelB->MinSize.cy > m_pPanelB->Height()) {
m_pPanelB->top = m_pPanelB->bottom - m_pPanelB->MinSize.cy;
m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize;
}
}
}
GetSplitArea(m_pSplitter);
m_pPanelA->OnResized();
m_pPanelB->OnResized();
m_pSplitter->OnResized();
}
void CWndResizer::CSplitContainer::SetSplitterPosition(int leftOfSplitter) {
short nFixedPanel = m_FixedPanel;
m_FixedPanel = 0;
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
m_pPanelA->right = leftOfSplitter;
m_pPanelB->left = m_pPanelA->right + m_nSplitterSize;
}
else {
m_pPanelA->bottom = leftOfSplitter;
m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize;
}
UpdateRatio();
OnResized();
UpdateRatio();
m_FixedPanel = nFixedPanel;
}
int CWndResizer::CSplitContainer::GetSplitterPosition() {
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
return m_pPanelA->right;
}
else {
return m_pPanelA->bottom;
}
}
BOOL CWndResizer::CSplitContainer::AddChild(CPanel* prc) {
if(Children.GetCount() == 3) {
return FALSE;
}
return CPanel::AddChild(prc);
}
BOOL CWndResizer::CSplitContainer::RemoveChild(CPanel* prc) {
return FALSE; // cannot remove child from split container
}
void CWndResizer::CSplitContainer::GetSplitArea(CRect* pSplitterPanel) {
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
pSplitterPanel->left = m_pPanelA->right;
pSplitterPanel->top = this->top;
pSplitterPanel->right = m_pPanelB->left;
pSplitterPanel->bottom = this->bottom;
}
else // vertical
{
pSplitterPanel->left = this->left;
pSplitterPanel->top = m_pPanelA->bottom;
pSplitterPanel->right = this->right;
pSplitterPanel->bottom = m_pPanelB->top;
}
}
int CWndResizer::CSplitContainer::GetSplitterSize(CPanel* m_pPanelA, CPanel* m_pPanelB) {
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
int nWidth = m_pPanelB->left - m_pPanelA->right;
return nWidth;
}
else // vertical
{
int nHeight = m_pPanelB->top - m_pPanelA->bottom;
return nHeight;
}
}
void CWndResizer::CSplitContainer::UpdateRatio() {
if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) {
m_nRatio = (double)m_pPanelA->Width() / (double)this->Width();
}
else {
m_nRatio = (double)m_pPanelA->Height() / (double)this->Height();
}
}
CWndResizer::CSplitContainer* CWndResizer::CSplitContainer::Create(CPanel* pPanelA, CPanel* pPanelB) {
CSplitPanel* pSplitPanelA = dynamic_cast<CSplitPanel*>(pPanelA);
if(pSplitPanelA != NULL) {
return NULL; // already a part of a CSplitContainer
}
CSplitPanel* pSplitPanelB = dynamic_cast<CSplitPanel*>(pPanelB);
if(pSplitPanelB != NULL) {
return NULL; // already a part of a CSplitContainer
}
CRect rcDest(0, 0, 0, 0);
CWndResizer::SplitterOrientation orien = CWndResizer::SPLIT_CONTAINER_H;
if(::IntersectRect(&rcDest, pPanelA, pPanelB) == TRUE) // invalid spliter container, a spliter continer's two panel cannot intersect each other
{
return NULL;
}
if(pPanelA->right < pPanelB->left) {
orien = CWndResizer::SPLIT_CONTAINER_H;
}
else if(pPanelA->bottom < pPanelB->top) {
orien = CWndResizer::SPLIT_CONTAINER_V;
}
else {
return NULL;
}
if(pPanelA->Parent != NULL) {
if(pPanelA->Parent->RemoveChild(pPanelA) == FALSE) {
return NULL;
}
}
if(pPanelB->Parent != NULL) {
if(pPanelB->Parent->RemoveChild(pPanelB) == FALSE) {
return NULL;
}
}
pSplitPanelA = new CSplitPanel(pPanelA);
pSplitPanelB = new CSplitPanel(pPanelB);
CSplitContainer* pSpliter = new CSplitContainer(pSplitPanelA, pSplitPanelB, orien);
return pSpliter;
}
CString CWndResizer::CSplitContainer::GetTypeName() {
return _T("CSplitContainer");
}
void CWndResizer::CSplitContainer::SetFixedPanel(short nFixedPanel /* 1=left/top; 2=right/bototm; other=no fixed panel */) {
m_FixedPanel = nFixedPanel;
}
short CWndResizer::CSplitContainer::GetFixedPanel() {
return m_FixedPanel;
}
void CWndResizer::CSplitContainer::SetIsSplitterFixed(BOOL bFixed) {
m_IsSplitterFixed = bFixed;
}
BOOL CWndResizer::CSplitContainer::GetIsSplitterFixed() {
return m_IsSplitterFixed;
}
void CWndResizer::CSplitContainer::SetShowSplitterGrip(BOOL bShow) {
m_pSplitter->m_pGrippePanel->m_bVisible = bShow;
}
BOOL CWndResizer::CSplitContainer::GetShowSplitterGrip() {
return m_pSplitter->m_pGrippePanel->m_bVisible;
}
///////////////////////////// CRootPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CRootPanel::CRootPanel()
: CPanel() {
m_pHookWnd = NULL;
}
CWndResizer::CRootPanel::~CRootPanel() {}
CWnd* CWndResizer::CRootPanel::GetHookedWnd() {
return m_pHookWnd;
}
CString CWndResizer::CRootPanel::GetTypeName() {
return _T("CRootPanel");
}
///////////////////////////// CUIPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CUIPanel::CUIPanel(const CRect* prc, UINT uID)
: CPanel(prc) {
m_uID = uID;
m_bOle = FALSE;
}
CWndResizer::CUIPanel::~CUIPanel() {}
CString CWndResizer::CUIPanel::GetTypeName() {
return _T("CUIPanel");
}
///////////////////////////// CVisualPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CVisualPanel::CVisualPanel()
: CPanel() {
m_bVisible = FALSE;
m_rcPrev.SetRect(0, 0, 0, 0);
}
CWndResizer::CVisualPanel::CVisualPanel(const CRect* prc)
: CPanel(prc) {
m_bVisible = FALSE;
m_rcPrev.SetRect(this->left, this->top, this->right, this->bottom);
}
CWndResizer::CVisualPanel::~CVisualPanel() {}
void CWndResizer::CVisualPanel::Draw(CDC* pDC) {}
CString CWndResizer::CVisualPanel::GetTypeName() {
return _T("CVisualPanel");
}
void CWndResizer::CVisualPanel::OnResized() {
CWnd* pWnd = NULL;
if((pWnd = GetHookedWnd()) != NULL) {
pWnd->InvalidateRect(&m_rcPrev, FALSE);
pWnd->InvalidateRect(this, FALSE);
}
m_rcPrev.SetRect(this->left, this->top, this->right, this->bottom);
}
///////////////////////////// CGripperPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CGripperPanel::CGripperPanel()
: CVisualPanel() {
m_hTheme = NULL;
m_iPartId = SBP_SIZEBOX;
m_iStateId = 5; // SZB_HALFBOTTOMRIGHTALIGN;
m_sClassName = _T("SCROLLBAR");
}
CWndResizer::CGripperPanel::CGripperPanel(const CRect* prc)
: CVisualPanel(prc) {
m_hTheme = NULL;
m_iPartId = SBP_SIZEBOX;
m_iStateId = 5; // SZB_HALFBOTTOMRIGHTALIGN;
m_sClassName = _T("SCROLLBAR");
}
CWndResizer::CGripperPanel::~CGripperPanel() {
if(m_hTheme != NULL) {
HRESULT lres = ::CloseThemeData(m_hTheme);
ASSERT(SUCCEEDED(lres) == TRUE);
m_hTheme = NULL;
}
}
void CWndResizer::CGripperPanel::Draw(CDC* pDC) {
if(m_hTheme == NULL) {
CWnd* pHookedWnd = GetHookedWnd();
if(pHookedWnd == NULL) {
return;
}
m_hTheme = ::OpenThemeData(pHookedWnd->m_hWnd, m_sClassName.AllocSysString());
}
if(m_hTheme == NULL) {
BOOL bOk = pDC->DrawFrameControl(this, DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
ASSERT(bOk);
}
else {
HRESULT lres = ::DrawThemeBackground(m_hTheme, pDC->m_hDC, m_iPartId, m_iStateId, this, this);
ASSERT(SUCCEEDED(lres) == TRUE);
}
}
CString CWndResizer::CGripperPanel::GetTypeName() {
return _T("CGripperPanel");
}
///////////////////////////// CSplitterGripperPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CSplitterGripperPanel::CSplitterGripperPanel(CWndResizer::SplitterOrientation type)
: CVisualPanel() {
m_OrienType = type;
}
CWndResizer::CSplitterGripperPanel::~CSplitterGripperPanel() {}
void CWndResizer::CSplitterGripperPanel::Draw(CDC* pDC) {
CPen penDark(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW));
CPen penWhite(PS_SOLID, 1, RGB(255, 255, 255));
if(m_OrienType == CWndResizer::SPLIT_CONTAINER_H) {
CPen* pOrigPen = pDC->SelectObject(&penWhite);
CRect rc(0, 0, 0, 0);
rc.SetRect(left + 1, top + 1, left + 3, top + 3);
while(rc.bottom <= bottom) {
pDC->Rectangle(&rc);
rc.OffsetRect(0, 4);
}
pDC->SelectObject(&penDark);
rc.SetRect(left, top, left + 2, top + 2);
while(rc.bottom <= bottom) {
pDC->Rectangle(&rc);
rc.OffsetRect(0, 4);
}
pDC->SelectObject(pOrigPen);
}
else {
CPen* pOrigPen = pDC->SelectObject(&penWhite);
CRect rc(0, 0, 0, 0);
rc.SetRect(left + 1, top + 1, left + 3, top + 3);
while(rc.right <= right) {
pDC->Rectangle(&rc);
rc.OffsetRect(4, 0);
}
pDC->SelectObject(&penDark);
rc.SetRect(left, top, left + 2, top + 2);
while(rc.right <= right) {
pDC->Rectangle(&rc);
rc.OffsetRect(4, 0);
}
pDC->SelectObject(pOrigPen);
}
}
CString CWndResizer::CSplitterGripperPanel::GetTypeName() {
return _T("CSplitterGripperPanel");
}
///////////////////////////// CSpitterPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CSpitterPanel::CSpitterPanel(const CRect* prc, CWndResizer::SplitterOrientation type)
: CPanel(prc) {
m_OrienType = type;
m_pGrippePanel = NULL;
if(m_pGrippePanel == NULL) {
m_pGrippePanel = new CSplitterGripperPanel(type);
if(m_OrienType == CWndResizer::SPLIT_CONTAINER_H) {
m_pGrippePanel->SetRect(0, 0, 3, 12);
}
else {
m_pGrippePanel->SetRect(0, 0, 12, 3);
}
m_pGrippePanel->SetAnchor(ANCHOR_HORIZONTALLY_CENTERED | ANCHOR_VERTICALLY_CENTERED);
m_pGrippePanel->SetMinSize(CSize(2, 2));
BOOL bOk = AddChild(m_pGrippePanel);
ASSERT(bOk);
}
}
CWndResizer::CSpitterPanel::CSpitterPanel(CWndResizer::SplitterOrientation type)
: CPanel() {
m_OrienType = type;
m_pGrippePanel = NULL;
}
CWndResizer::CSpitterPanel::~CSpitterPanel() {}
CString CWndResizer::CSpitterPanel::GetTypeName() {
return _T("CSpitterPanel");
}
///////////////////////////// CSpitPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CSplitPanel::CSplitPanel(CPanel* pPanel)
: CPanel(pPanel) {
pPanel->LeftOffset = 0;
pPanel->TopOffset = 0;
pPanel->RightOffset = 0;
pPanel->BottomOffset = 0;
pPanel->Anchor = ANCHOR_ALL;
Name = pPanel->Name;
pPanel->Name = _T("");
m_pOriginalPanel = pPanel;
MaxSize = pPanel->MaxSize;
MinSize = pPanel->MinSize;
Children.AddTail(pPanel);
}
CWndResizer::CSplitPanel::~CSplitPanel() {}
BOOL CWndResizer::CSplitPanel::SetAnchor(UINT anchor) {
return FALSE;
}
BOOL CWndResizer::CSplitPanel::AddChild(CPanel* prc) {
return m_pOriginalPanel->AddChild(prc);
}
BOOL CWndResizer::CSplitPanel::RemoveChild(CPanel* prc) {
return m_pOriginalPanel->RemoveChild(prc);
}
CString CWndResizer::CSplitPanel::GetTypeName() {
return _T("CSplitPanel");
}
///////////////////////////// CFlowLayoutPanel
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CWndResizer::CFlowLayoutPanel::CFlowLayoutPanel()
: CPanel() {
m_nItemSpacingX = 0;
m_nItemSpacingY = 0;
m_nFlowDirection = CWndResizer::LEFT_TO_RIGHT;
}
CWndResizer::CFlowLayoutPanel::CFlowLayoutPanel(const CRect* prc)
: CPanel(prc) {
m_nItemSpacingX = 0;
m_nItemSpacingY = 0;
m_nFlowDirection = CWndResizer::LEFT_TO_RIGHT;
}
CWndResizer::CFlowLayoutPanel::~CFlowLayoutPanel() {}
void CWndResizer::CFlowLayoutPanel::OnResized() {
int max = 0; // maximimum height of a item in the row in case of left-to-right, otherwise maximum width of a item
int x = left;
int y = top;
POSITION pos = Children.GetHeadPosition();
// first one will be at the top-left corner, no matter what
if(pos != NULL) {
CPanel* pPanel = Children.GetNext(pos);
pPanel->MoveToXY(x, y);
pPanel->OnResized();
if(m_nFlowDirection == CWndResizer::LEFT_TO_RIGHT) {
x += pPanel->Width() + m_nItemSpacingX;
max = (pPanel->Height() > max ? pPanel->Height() : max);
}
else {
y += pPanel->Height() + m_nItemSpacingY;
max = (pPanel->Width() > max ? pPanel->Width() : max);
}
}
if(m_nFlowDirection == CWndResizer::LEFT_TO_RIGHT) {
while(pos != NULL) {
CPanel* pPanel = Children.GetNext(pos);
// check to see if it is to wrap
if(x + pPanel->Width() > right) {
x = left;
y += (max + m_nItemSpacingY);
max = 0;
}
pPanel->MoveToXY(x, y);
pPanel->OnResized();
x += pPanel->Width() + m_nItemSpacingX;
max = (pPanel->Height() > max ? pPanel->Height() : max);
}
}
else {
while(pos != NULL) {
CPanel* pPanel = Children.GetNext(pos);
// check to see if it is to wrap
if(y + pPanel->Height() > bottom) {
x += (max + m_nItemSpacingX);
y = top;
max = 0;
}
pPanel->MoveToXY(x, y);
pPanel->OnResized();
y += pPanel->Height() + m_nItemSpacingY;
max = (pPanel->Width() > max ? pPanel->Width() : max);
}
}
}
CString CWndResizer::CFlowLayoutPanel::GetTypeName() {
return _T("CFlowLayoutPanel");
}
void CWndResizer::CFlowLayoutPanel::SetFlowDirection(CWndResizer::FlowDirection direction) {
m_nFlowDirection = direction;
}
CWndResizer::FlowDirection CWndResizer::CFlowLayoutPanel::GetFlowDirection() {
return m_nFlowDirection;
}
void CWndResizer::CFlowLayoutPanel::SetItemSpacingX(int nSpace) {
m_nItemSpacingX = nSpace;
}
int CWndResizer::CFlowLayoutPanel::GetItemSpacingX() {
return m_nItemSpacingX;
}
void CWndResizer::CFlowLayoutPanel::SetItemSpacingY(int nSpace) {
m_nItemSpacingY = nSpace;
}
int CWndResizer::CFlowLayoutPanel::GetItemSpacingY() {
return m_nItemSpacingY;
}
} // namespace wndcommons
} // namespace abscodes
| 34.207101 | 155 | 0.527723 | AbsCoDes-lib |
0c19a5e41dfde254edb0756b883eb0365a0070d1 | 1,800 | cpp | C++ | src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp | linwaiwai/ios-runtime | 1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef | [
"Apache-2.0"
] | 1 | 2020-09-03T01:33:53.000Z | 2020-09-03T01:33:53.000Z | src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp | linwaiwai/ios-runtime | 1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef | [
"Apache-2.0"
] | null | null | null | src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp | linwaiwai/ios-runtime | 1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef | [
"Apache-2.0"
] | null | null | null | //
// FunctionReferenceConstructor.cpp
// NativeScript
//
// Created by Jason Zhekov on 10/20/14.
// Copyright (c) 2014 Telerik. All rights reserved.
//
#include "FunctionReferenceConstructor.h"
#include "FunctionReferenceInstance.h"
#include "Interop.h"
namespace NativeScript {
using namespace JSC;
const ClassInfo FunctionReferenceConstructor::s_info = { "FunctionReference", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(FunctionReferenceConstructor) };
void FunctionReferenceConstructor::finishCreation(VM& vm, JSValue prototype) {
Base::finishCreation(vm, this->classInfo()->className);
this->putDirect(vm, vm.propertyNames->prototype, prototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
this->putDirect(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum | PropertyAttribute::DontDelete);
}
EncodedJSValue JSC_HOST_CALL FunctionReferenceConstructor::constructFunctionReferenceInstance(ExecState* execState) {
CallData callData;
JSC::VM& vm = execState->vm();
if (!(execState->argumentCount() == 1 && JSC::getCallData(vm, execState->uncheckedArgument(0), callData) != CallType::None)) {
auto scope = DECLARE_THROW_SCOPE(vm);
return JSValue::encode(scope.throwException(execState, createError(execState, "Function required."_s)));
}
GlobalObject* globalObject = jsCast<GlobalObject*>(execState->lexicalGlobalObject());
JSCell* func = execState->uncheckedArgument(0).asCell();
auto functionReference = FunctionReferenceInstance::create(execState->vm(), globalObject, globalObject->interop()->functionReferenceInstanceStructure(), func);
return JSValue::encode(functionReference.get());
}
} // namespace NativeScript
| 43.902439 | 163 | 0.761667 | linwaiwai |
0c19c64ff9b0bfc0523431936929e35da155ecee | 8,027 | cpp | C++ | lib/libcpp/Solvers/applicationinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcpp/Solvers/applicationinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcpp/Solvers/applicationinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #include "Alat/stringvector.hpp"
#include "Solvers/applicationinterface.hpp"
#include "Mesh/meshunitinterface.hpp"
#include <cassert>
using namespace solvers;
/*--------------------------------------------------------------------------*/
ApplicationInterface::~ApplicationInterface() {}
ApplicationInterface::ApplicationInterface(): alat::InterfaceBase(), _mesh(NULL){}
ApplicationInterface::ApplicationInterface( const ApplicationInterface& applicationinterface): alat::InterfaceBase(applicationinterface)
{
assert(0);
}
ApplicationInterface& ApplicationInterface::operator=( const ApplicationInterface& applicationinterface)
{
assert(0);
alat::InterfaceBase::operator=(applicationinterface);
return *this;
}
std::string ApplicationInterface::getClassName() const
{
return "ApplicationInterface";
}
void ApplicationInterface::setModel(const solvers::ModelInterface* model){_model=model;}
/*--------------------------------------------------------------------------*/
std::unique_ptr<solvers::InitialConditionInterface> ApplicationInterface::newInitialCondition(std::string varname) const
{
return std::unique_ptr<solvers::InitialConditionInterface>(nullptr);
}
std::unique_ptr<solvers::RightHandSideInterface> ApplicationInterface::newRightHandSide(std::string varname) const
{
return std::unique_ptr<solvers::RightHandSideInterface>(nullptr);
}
std::unique_ptr<solvers::DirichletInterface> ApplicationInterface::newDirichlet(std::string varname) const
{
return std::unique_ptr<solvers::DirichletInterface>(nullptr);
}
std::unique_ptr<solvers::NeumannInterface> ApplicationInterface::newNeumann(std::string varname) const
{
return std::unique_ptr<solvers::NeumannInterface>(nullptr);
}
std::shared_ptr<solvers::FunctionInterface> ApplicationInterface::newDataFunction(std::string varname) const
{
return std::shared_ptr<solvers::FunctionInterface>(nullptr);
}
std::shared_ptr<solvers::FunctionInterface> ApplicationInterface::newExactSolution(std::string varname) const
{
return std::shared_ptr<solvers::FunctionInterface>(nullptr);
}
const InitialConditionInterface& ApplicationInterface::getInitialCondition(int ivar)const{return *_initialconditions[ivar].get();}
const RightHandSideInterface& ApplicationInterface::getRightHandSide(int ivar)const{assert(ivar<_righthandsides.size());return *_righthandsides[ivar].get();}
const DirichletInterface& ApplicationInterface::getDirichlet(int ivar)const{assert(ivar<_dirichlets.size()); return *_dirichlets[ivar].get();}
const NeumannInterface& ApplicationInterface::getNeumann(int ivar)const{assert(ivar<_neumanns.size()); return *_neumanns[ivar].get();}
const FunctionInterface& ApplicationInterface::getDataFunction(int ivar)const{assert(ivar<_datafunctions.size()); return *_datafunctions[ivar].get();}
const solvers::FunctionInterface& ApplicationInterface::getExactSolution(int ivar)const
{
assert(_exactsolutions[ivar]);
return *_exactsolutions[ivar].get();
}
solvers::FunctionInterface& ApplicationInterface::getExactSolution(int ivar)
{
assert(_exactsolutions[ivar]);
return *_exactsolutions[ivar].get();
}
const InitialConditionInterface& ApplicationInterface::getInitialCondition(std::string varname)const
{
return *_initialconditions[_indexofvar[varname]].get();
}
const RightHandSideInterface& ApplicationInterface::getRightHandSide(std::string varname)const
{
return *_righthandsides[_indexofvar[varname]].get();
}
const DirichletInterface& ApplicationInterface::getDirichlet(std::string varname)const
{
return *_dirichlets[_indexofvar[varname]].get();
}
const NeumannInterface& ApplicationInterface::getNeumann(std::string varname)const
{
return *_neumanns[_indexofvar[varname]].get();
}
const FunctionInterface& ApplicationInterface::getDataFunction(std::string varname)const
{
assert(_datafunctions[_indexofdatavar[varname]]);
return *_datafunctions[_indexofdatavar[varname]];
}
const solvers::FunctionInterface& ApplicationInterface::getExactSolution(std::string varname)const
{
return *_exactsolutions[_indexofvar[varname]].get();
}
solvers::FunctionInterface& ApplicationInterface::getExactSolution(std::string varname)
{
return *_exactsolutions[_indexofvar[varname]].get();
}
bool ApplicationInterface::hasInitialCondition(int ivar)const
{
assert(ivar<_initialconditions.size());
return _initialconditions[ivar] != nullptr;
}
bool ApplicationInterface::hasDataFunction(int ivar)const
{
assert(ivar<_datafunctions.size());
return _datafunctions[ivar] != nullptr;
}
bool ApplicationInterface::hasExactSolution(int ivar)const
{
assert(ivar<_exactsolutions.size());
return _exactsolutions[ivar] != nullptr;
}
bool ApplicationInterface::hasExactSolution(std::string varname)const
{
return hasExactSolution(_indexofvar[varname]);
}
bool ApplicationInterface::hasRightHandSide(int ivar)const{return _righthandsides[ivar] != nullptr;}
bool ApplicationInterface::hasDirichlet(int ivar)const{return _dirichlets[ivar] != nullptr;}
const alat::IntSet& ApplicationInterface::getStrongDirichletColor() const {return _dircolors;}
/*--------------------------------------------------------------------------*/
void ApplicationInterface::initApplication(const mesh::MeshUnitInterface* mesh, const alat::StringVector& varnames, const alat::StringVector& varnamesdata, const alat::armaivec& ncomps, const alat::armaivec& ncompsdata)
{
_mesh=mesh;
int nvars = varnames.size();
_initialconditions.set_size(nvars);
_righthandsides.set_size(nvars);
_dirichlets.set_size(nvars);
_neumanns.set_size(nvars);
_exactsolutions.set_size(nvars);
int dim = _mesh->getDimension();
for(int ivar=0;ivar<nvars;ivar++)
{
std::string varname = varnames[ivar];
_indexofvar[varname] = ivar;
_exactsolutions[ivar] = newExactSolution(varname);
_initialconditions[ivar] = newInitialCondition(varname);
_righthandsides[ivar] = newRightHandSide(varname);
_dirichlets[ivar] = newDirichlet(varname);
_neumanns[ivar] = newNeumann(varname);
if(_initialconditions[ivar]) {_initialconditions[ivar]->setNcompAndDim(ncomps[ivar], dim);}
if(_righthandsides[ivar]) {_righthandsides[ivar]->setNcompAndDim(ncomps[ivar], dim);}
if(_dirichlets[ivar]) {_dirichlets[ivar]->setNcompAndDim(ncomps[ivar], dim);}
if(_neumanns[ivar]) {_neumanns[ivar]->setNcompAndDim(ncomps[ivar], dim);}
}
int nvarsdata = varnamesdata.size();
_datafunctions.set_size(nvarsdata);
for(int ivar=0;ivar<nvarsdata;ivar++)
{
std::string varname = varnamesdata[ivar];
_indexofdatavar[varname] = ivar;
_datafunctions[ivar] = newDataFunction(varname);
if(_datafunctions[ivar]) {_datafunctions[ivar]->setNcompAndDim(ncompsdata[ivar], dim);}
}
_dircolors.clear();
for(mesh::MeshUnitInterface::BoundaryInformationMap::const_iterator p=_mesh->getBoundaryInformationMap().begin();p!=_mesh->getBoundaryInformationMap().end();p++)
{
int color = p->first;
if(isStrongDirichlet(color)) _dircolors.insert(color);
}
}
/*--------------------------------------------------------------------------*/
std::string ApplicationInterface::getInfo() const
{
std::stringstream ss;
ss << "\t RightHandSides: ";
int nvars = _righthandsides.size();
for(int ivar=0;ivar<nvars;ivar++)
{
if(_righthandsides[ivar])
{
ss << _righthandsides[ivar]->getClassName() << " ";
}
else
{
ss << " NULL ";
}
}
ss << "\n\t Dirichlets: ";
for(int ivar=0;ivar<nvars;ivar++)
{
if(_dirichlets[ivar])
{
ss << _dirichlets[ivar]->getClassName() << " ";
}
else
{
ss << " NULL ";
}
}
ss << "\n\t Neumanns: ";
for(int ivar=0;ivar<nvars;ivar++)
{
if(_neumanns[ivar])
{
ss << _neumanns[ivar]->getClassName() << " ";
}
else
{
ss << " NULL ";
}
}
ss << "\n\t Exactsolutoins: ";
for(int ivar=0;ivar<nvars;ivar++)
{
if(_exactsolutions[ivar])
{
ss << _exactsolutions[ivar]->getClassName() << " ";
}
else
{
ss << " NULL ";
}
}
return ss.str();
}
| 36.486364 | 219 | 0.722935 | beckerrh |
0c1cde67c4607587c8bff564ac0f6c1e2868ddd2 | 4,493 | cpp | C++ | source/gameos/src/winmain.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 38 | 2015-04-10T13:31:03.000Z | 2021-09-03T22:34:05.000Z | source/gameos/src/winmain.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 1 | 2020-07-09T09:48:44.000Z | 2020-07-12T12:41:43.000Z | source/gameos/src/winmain.cpp | mechasource/mechcommander2 | b2c7cecf001cec1f535aa8d29c31bdc30d9aa983 | [
"BSD-2-Clause"
] | 12 | 2015-06-29T08:06:57.000Z | 2021-10-13T13:11:41.000Z | /*******************************************************************************
This file consist of reversed and interpreted code from object source in the
x86 debug build gameos.lib. The code in this file can not be used in any way
other than serve as an information reference to the original released source of
Mechcommander2. The code is a work of progress and there is no guarantee it is
complete, accurate or useful in any way. The purpose is instead to make it
possible to safely remove any dependencies of gameos.lib from Mechcommander2.
All code is logically copyrighted to Microsoft
*******************************************************************************/
/*******************************************************************************
winmain.cpp - GameOS reference pseudo code
MechCommander;source code
;-07-24 Jerker Back, created
*******************************************************************************/
#include "stdinc.h"
#include "texture_manager.hpp"
#include "platform.hpp"
#include "windows.hpp"
// -----------------------------------------------------------------------------
// Global data exported from this module
MECH_IMPEXP PlatformType Platform;
MECH_IMPEXP char ApplicationName[256];
MECH_IMPEXP char AssetsDirectory1[MAX_PATH];
MECH_IMPEXP char AssetsDirectory2[MAX_PATH];
MECH_IMPEXP char ImageHelpPath[MAX_PATH];
MECH_IMPEXP bool gNoBlade;
// global referenced data not listed in headers
MECH_IMPEXP uint32_t gDirectX7;
MECH_IMPEXP uint32_t gDisableForceFeedback;
// local data
int64_t TUploadTexture;
char MachineInfoFile[MAX_PATH];
int64_t TRenderTextures;
int64_t TMipmapTexture;
char InitialLogFile[256];
char PauseSpewOn[256];
int64_t TConvertTexture;
int64_t volatile TimeMM;
char SpewOptions[256];
int64_t volatile TimeControls;
void (*DoScriptUpdate)(int32_t);
uint32_t gNoFree;
uint32_t StartupMemory;
uint32_t gLoadAllSymbols;
uint32_t gDisableJoystick;
uint32_t gNumberCompatFlags;
uint32_t gCompatFlags;
uint32_t gCompatFlags1;
uint32_t RenderersSkipped;
uint32_t gNoFPU;
uint32_t gEnableGosView;
uint32_t gUseBlade;
uint32_t gStartWithLog;
uint32_t gEnableSpew;
uint32_t gDisableSound;
uint32_t LastModalLoop;
uint32_t ModalLoop;
uint32_t gDisableRDTSC;
uint32_t gLocalize;
bool PerfCounters;
bool RealTerminate;
bool gShowAllocations;
bool gUse3D;
uint32_t InGameLogicCounter;
bool gPauseSpew;
bool gNoDialogs;
bool gDumpMachineInfo;
int64_t volatile TimeScripts;
int64_t volatile TimeScriptsUpdate;
int64_t volatile TimeGameLogic;
int64_t volatile TimeNetwork;
int64_t volatile TimeGameOS;
int64_t volatile TimeSoundStream;
int64_t volatile TimeGameOS1;
int64_t volatile TimeDebugger;
int64_t volatile TimeRenderers;
int64_t volatile TimeOutSideLoop;
int64_t volatile StartTimeOutSideLoop;
int64_t volatile TimeDisplay;
int64_t volatile TimeWindows;
int64_t volatile TimeEndScene;
int64_t volatile TimeFont3D;
int64_t volatile TimeD3D;
int64_t volatile TimeDXShow;
int64_t volatile TimeElementRenderers;
uint32_t ModalScripts;
uint32_t SavedSP;
uint32_t SavedBP;
bool RunFullScreen;
// -----------------------------------------------------------------------------
// global implemented functions in this module listed in headers
MECH_IMPEXP void _stdcall RunFromOtherApp(HINSTANCE hinstance, HWND hwnd, PSTR commandline);
MECH_IMPEXP int32_t _stdcall RunFromWinMain(
HINSTANCE hinstance, HINSTANCE hPrevInstance, PSTR commandline, int32_t nCmdShow);
MECH_IMPEXP void __stdcall RestartGameOS(void);
MECH_IMPEXP void __stdcall gos_UpdateDisplay(bool Everything);
MECH_IMPEXP uint32_t __stdcall RunGameOSLogic(void);
MECH_IMPEXP void __stdcall gos_TerminateApplication(void);
MECH_IMPEXP void __stdcall gos_AbortTermination(void);
MECH_IMPEXP uint8_t __stdcall gos_UserExit(void);
MECH_IMPEXP uint8_t __stdcall gos_RunMainLoop(void(__stdcall* DoGameLogic)(void) = nullptr);
// inline void __stdcall InitTextureManager(void)
// inline void __stdcall DestroyTextureManager(void);
// global implemented functions not listed in headers
// local functions
static int32_t __stdcall CheckOption(PSTR substr);
static void __stdcall InitializeGOS(HINSTANCE hinstance, PSTR commandline);
static void __stdcall ProfileRenderStart(void);
static int64_t __stdcall ProfileRenderEnd(int64_t);
static uint32_t __stdcall InternalRunGameOSLogic(void(__stdcall* DoGameLogic)(void));
// -----------------------------------------------------------------------------
// externals referenced in this file not specified in headers
| 34.829457 | 92 | 0.732918 | mechasource |
0c1cf45447ae41123638fe8c231d053cd93601c7 | 19,947 | cpp | C++ | reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp | linuxmao-org/shiru-plugins | 08853f99140012234649e67e5647906fda74f6cc | [
"WTFPL"
] | 11 | 2019-06-15T06:36:36.000Z | 2022-02-22T04:49:22.000Z | reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp | nyxkn/shiru-plugins | 8088c04b94afb498cec6a14bd03c448936bf31e9 | [
"WTFPL"
] | 6 | 2019-06-15T14:04:49.000Z | 2019-11-27T15:35:13.000Z | reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp | nyxkn/shiru-plugins | 8088c04b94afb498cec6a14bd03c448936bf31e9 | [
"WTFPL"
] | 2 | 2020-12-30T00:21:35.000Z | 2021-07-04T18:32:46.000Z | #include "PulseSynth.h"
AudioEffect* createEffectInstance(audioMasterCallback audioMaster)
{
return new PulseSynth(audioMaster);
}
PulseSynth::PulseSynth(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, NUM_PROGRAMS, NUM_PARAMS)
{
VstInt32 pgm,chn;
setNumInputs(NUM_INPUTS);
setNumOutputs(NUM_OUTPUTS);
setUniqueID(PLUGIN_UID);
isSynth();
canProcessReplacing();
programsAreChunks(true);
Program=0;
LoadPresetChunk((float*)ChunkPresetData);
for(pgm=0;pgm<NUM_PROGRAMS;++pgm)
{
strcpy(ProgramName[pgm],programDefaultNames[pgm]);
/*pAttack [pgm]=0;
pDecay [pgm]=0;
pSustain [pgm]=1.0f;
pRelease [pgm]=0;
pPulseWidth[pgm]=.25f;
pDetune [pgm]=.5f;
pLowBoost [pgm]=0;
pPolyphony [pgm]=1.0f;
pSlideSpeed[pgm]=1.0f;
pOutputGain[pgm]=1.0f;*/
}
for(chn=0;chn<SYNTH_CHANNELS;++chn)
{
SynthChannel[chn].note=-1;
SynthChannel[chn].freq=0;
SynthChannel[chn].freq_new=0;
SynthChannel[chn].acc=0;
SynthChannel[chn].e_stage=eStageReset;
SynthChannel[chn].e_delta=0;
SynthChannel[chn].e_level=0;
SynthChannel[chn].pulse=0;
SynthChannel[chn].volume=1.0f;
}
sEnvelopeDiv=0;
MidiQueue.clear();
MidiRPNLSB=0;
MidiRPNMSB=0;
MidiDataLSB=0;
MidiDataMSB=0;
MidiPitchBend=0;
MidiPitchBendRange=2.0f;
MidiModulationDepth=0;
MidiModulationCount=0;
sSlideStep=0;
memset(MidiKeyState,0,sizeof(MidiKeyState));
suspend();
}
PulseSynth::~PulseSynth()
{
}
void PulseSynth::setParameter(VstInt32 index,float value)
{
switch(index)
{
case pIdAttack: pAttack [Program]=value; break;
case pIdDecay: pDecay [Program]=value; break;
case pIdSustain: pSustain [Program]=value; break;
case pIdRelease: pRelease [Program]=value; break;
case pIdPulseWidth: pPulseWidth[Program]=value; break;
case pIdDetune: pDetune [Program]=value; break;
case pIdLowBoost: pLowBoost [Program]=value; break;
case pIdPolyphony: pPolyphony [Program]=value; break;
case pIdPortaSpeed: pPortaSpeed[Program]=value; break;
case pIdOutputGain: pOutputGain[Program]=value; break;
}
}
float PulseSynth::getParameter(VstInt32 index)
{
switch(index)
{
case pIdAttack: return pAttack [Program];
case pIdDecay: return pDecay [Program];
case pIdSustain: return pSustain [Program];
case pIdRelease: return pRelease [Program];
case pIdPulseWidth: return pPulseWidth[Program];
case pIdDetune: return pDetune [Program];
case pIdLowBoost: return pLowBoost [Program];
case pIdPolyphony: return pPolyphony [Program];
case pIdPortaSpeed: return pPortaSpeed[Program];
case pIdOutputGain: return pOutputGain[Program];
}
return 0;
}
void PulseSynth::getParameterName(VstInt32 index,char *label)
{
switch(index)
{
case pIdAttack: strcpy(label,"Attack time"); break;
case pIdDecay: strcpy(label,"Decay time"); break;
case pIdSustain: strcpy(label,"Sustain level"); break;
case pIdRelease: strcpy(label,"Release time"); break;
case pIdPulseWidth: strcpy(label,"Pulse width"); break;
case pIdDetune: strcpy(label,"Detune"); break;
case pIdLowBoost: strcpy(label,"Boost low end"); break;
case pIdPolyphony: strcpy(label,"Polyphony"); break;
case pIdPortaSpeed: strcpy(label,"Porta speed"); break;
case pIdOutputGain: strcpy(label,"Output gain"); break;
default: strcpy(label,"");
}
}
void PulseSynth::getParameterDisplay(VstInt32 index,char *text)
{
switch(index)
{
case pIdAttack: float2string(ENVELOPE_ATTACK_MAX_MS*pAttack[Program],text,6); break;
case pIdDecay: float2string(ENVELOPE_DECAY_MAX_MS*pDecay[Program],text,6); break;
case pIdSustain: float2string(pSustain[Program],text,5); break;
case pIdRelease: float2string(ENVELOPE_RELEASE_MAX_MS*pRelease[Program],text,5); break;
case pIdPulseWidth: float2string(PULSE_WIDTH_MAX_US*pPulseWidth[Program],text,5); break;
case pIdDetune: float2string(-1.0f+pDetune[Program]*2.0f,text,5); break;
case pIdLowBoost: strcpy(text,pLowBoost[Program]<.5f?"Disabled":"Enabled"); break;
case pIdPolyphony: strcpy(text,pPolyphonyModeNames[(int)(pPolyphony[Program]*2.99f)]); break;
case pIdPortaSpeed: float2string(pPortaSpeed[Program],text,5); break;
case pIdOutputGain: dB2string(pOutputGain[Program],text,3); break;
default: strcpy(text,"");
}
}
void PulseSynth::getParameterLabel(VstInt32 index,char *label)
{
switch(index)
{
case pIdAttack:
case pIdDecay:
case pIdRelease: strcpy(label,"ms"); break;
case pIdPulseWidth: strcpy(label,"us"); break;
case pIdOutputGain: strcpy(label,"dB"); break;
default: strcpy(label,"");
}
}
VstInt32 PulseSynth::getProgram(void)
{
return Program;
}
void PulseSynth::setProgram(VstInt32 program)
{
Program=program;
}
void PulseSynth::getProgramName(char* name)
{
strcpy(name,ProgramName[Program]);
}
void PulseSynth::setProgramName(char* name)
{
strncpy(ProgramName[Program],name,MAX_NAME_LEN);
ProgramName[Program][MAX_NAME_LEN-1]='\0';
}
VstInt32 PulseSynth::canDo(char* text)
{
if(!strcmp(text,"receiveVstEvents" )) return 1;
if(!strcmp(text,"receiveVstMidiEvent")) return 1;
return -1;
}
VstInt32 PulseSynth::getNumMidiInputChannels(void)
{
return 1;//monophonic
}
VstInt32 PulseSynth::getNumMidiOutputChannels(void)
{
return 0;//no MIDI output
}
VstInt32 PulseSynth::SaveStringChunk(char *str,float *dst)
{
VstInt32 i;
for(i=0;i<(VstInt32)strlen(str);++i) *dst++=str[i];
*dst++=0;
return (VstInt32)strlen(str)+1;
}
VstInt32 PulseSynth::LoadStringChunk(char *str,int max_length,float *src)
{
unsigned int c,ptr;
ptr=0;
while(1)
{
c=(unsigned int)*src++;
str[ptr++]=c;
if(!c) break;
if(ptr==max_length-1)
{
str[ptr]=0;
break;
}
}
return ptr;
}
VstInt32 PulseSynth::SavePresetChunk(float *chunk)
{
int ptr,pgm;
ptr=0;
chunk[ptr++]=DATA;
for(pgm=0;pgm<NUM_PROGRAMS;++pgm)
{
chunk[ptr++]=PROG; chunk[ptr++]=(float)pgm;
chunk[ptr++]=NAME; ptr+=SaveStringChunk(ProgramName[pgm],&chunk[ptr]);
chunk[ptr++]=EATT; chunk[ptr++]=pAttack [pgm];
chunk[ptr++]=EDEC; chunk[ptr++]=pDecay [pgm];
chunk[ptr++]=ESUS; chunk[ptr++]=pSustain [pgm];
chunk[ptr++]=EREL; chunk[ptr++]=pRelease [pgm];
chunk[ptr++]=PWDT; chunk[ptr++]=pPulseWidth[pgm];
chunk[ptr++]=DETU; chunk[ptr++]=pDetune [pgm];
chunk[ptr++]=LOWB; chunk[ptr++]=pLowBoost [pgm];
chunk[ptr++]=POLY; chunk[ptr++]=pPolyphony [pgm];
chunk[ptr++]=POSP; chunk[ptr++]=pPortaSpeed[pgm];
chunk[ptr++]=GAIN; chunk[ptr++]=pOutputGain[pgm];
}
chunk[ptr++]=DONE;
/*
FILE *file=fopen("g:/params.txt","wt");
fprintf(file,"DATA,\n\n");
for(pgm=0;pgm<NUM_PROGRAMS;++pgm)
{
fprintf(file,"PROG,%i,\n",pgm);
fprintf(file,"EATT,%1.3ff,",pAttack [pgm]);
fprintf(file,"EDEC,%1.3ff,",pDecay [pgm]);
fprintf(file,"ESUS,%1.3ff,",pSustain [pgm]);
fprintf(file,"EREL,%1.3ff,",pRelease [pgm]);
fprintf(file,"PWDT,%1.3ff,",pPulseWidth[pgm]);
fprintf(file,"DETU,%1.3ff,",pDetune [pgm]);
fprintf(file,"LOWB,%1.3ff,",pLowBoost [pgm]);
fprintf(file,"POLY,%1.3ff,",pPolyphony [pgm]);
fprintf(file,"POSP,%1.3ff,",pPortaSpeed[pgm]);
fprintf(file,"GAIN,%1.3ff,",pOutputGain[pgm]);
fprintf(file,"\n");
}
fprintf(file,"\nDONE");
fclose(file);
*/
return ptr*sizeof(float);//size in bytes
}
void PulseSynth::LoadPresetChunk(float *chunk)
{
int pgm;
float tag;
//default parameters for legacy data support
for(pgm=0;pgm<NUM_PROGRAMS;++pgm)
{
pLowBoost[pgm]=0;
}
if(chunk[0]!=DATA) //load legacy data
{
for(pgm=0;pgm<NUM_PROGRAMS;++pgm)
{
pAttack [pgm]=*chunk++;
pDecay [pgm]=*chunk++;
pSustain [pgm]=*chunk++;
pRelease [pgm]=*chunk++;
pPulseWidth[pgm]=*chunk++;
pDetune [pgm]=*chunk++;
pPolyphony [pgm]=*chunk++;
pPortaSpeed[pgm]=*chunk++;
pOutputGain[pgm]=*chunk++;
}
}
else //load normal data
{
while(1)
{
tag=*chunk++;
if(tag==DONE) break;
if(tag==PROG) pgm =(int)*chunk++;
if(tag==NAME) chunk+=LoadStringChunk(ProgramName[pgm],MAX_NAME_LEN,chunk);
if(tag==EATT) pAttack [pgm]=*chunk++;
if(tag==EDEC) pDecay [pgm]=*chunk++;
if(tag==ESUS) pSustain [pgm]=*chunk++;
if(tag==EREL) pRelease [pgm]=*chunk++;
if(tag==PWDT) pPulseWidth[pgm]=*chunk++;
if(tag==DETU) pDetune [pgm]=*chunk++;
if(tag==LOWB) pLowBoost [pgm]=*chunk++;
if(tag==POLY) pPolyphony [pgm]=*chunk++;
if(tag==POSP) pPortaSpeed[pgm]=*chunk++;
if(tag==GAIN) pOutputGain[pgm]=*chunk++;
}
}
}
VstInt32 PulseSynth::getChunk(void** data,bool isPreset)
{
int size;
size=SavePresetChunk(Chunk);
*data=Chunk;
return size;
}
VstInt32 PulseSynth::setChunk(void* data,VstInt32 byteSize,bool isPreset)
{
if(byteSize>sizeof(Chunk)) return 0;
memcpy(Chunk,data,byteSize);
LoadPresetChunk(Chunk);
return 0;
}
void PulseSynth::MidiAddNote(VstInt32 delta,VstInt32 note,VstInt32 velocity)
{
MidiQueueStruct entry;
entry.type =mEventTypeNote;
entry.delta =delta;
entry.note =note;
entry.velocity=velocity;//0 for key off
MidiQueue.push_back(entry);
}
void PulseSynth::MidiAddProgramChange(VstInt32 delta,VstInt32 program)
{
MidiQueueStruct entry;
entry.type =mEventTypeProgram;
entry.delta =delta;
entry.program=program;
MidiQueue.push_back(entry);
}
void PulseSynth::MidiAddPitchBend(VstInt32 delta,float depth)
{
MidiQueueStruct entry;
entry.type =mEventTypePitchBend;
entry.delta=delta;
entry.depth=depth;
MidiQueue.push_back(entry);
}
void PulseSynth::MidiAddModulation(VstInt32 delta,float depth)
{
MidiQueueStruct entry;
entry.type =mEventTypeModulation;
entry.delta=delta;
entry.depth=depth;
MidiQueue.push_back(entry);
}
bool PulseSynth::MidiIsAnyKeyDown(void)
{
int i;
for(i=0;i<128;++i) if(MidiKeyState[i]) return true;
return false;
}
VstInt32 PulseSynth::processEvents(VstEvents* ev)
{
VstMidiEvent* event;
VstInt32 i,status,note,velocity,wheel;
char* midiData;
for(i=0;i<ev->numEvents;++i)
{
event=(VstMidiEvent*)ev->events[i];
if(event->type!=kVstMidiType) continue;
midiData=event->midiData;
status=midiData[0]&0xf0;
switch(status)
{
case 0x80://note off
case 0x90://note on
{
note=midiData[1]&0x7f;
velocity=midiData[2]&0x7f;
if(status==0x80) velocity=0;
MidiAddNote(event->deltaFrames,note,velocity);
}
break;
case 0xb0://control change
{
if(midiData[1]==0x64) MidiRPNLSB =midiData[2]&0x7f;
if(midiData[1]==0x65) MidiRPNMSB =midiData[2]&0x7f;
if(midiData[1]==0x26) MidiDataLSB=midiData[2]&0x7f;
if(midiData[1]==0x01)
{
MidiModulationMSB=midiData[2]&0x7f;
MidiAddModulation(event->deltaFrames,(float)MidiModulationMSB/128.0f);
}
if(midiData[1]==0x06)
{
MidiDataMSB=midiData[2]&0x7f;
if(MidiRPNLSB==0&&MidiRPNMSB==0) MidiPitchBendRange=(float)MidiDataMSB*.5f;
}
if(midiData[1]>=0x7b)//all notes off and mono/poly mode changes that also requires to do all notes off
{
MidiAddNote(event->deltaFrames,-1,0);
}
}
break;
case 0xc0: //program change
{
MidiAddProgramChange(event->deltaFrames,midiData[1]&0x7f);
}
break;
case 0xe0://pitch bend change
{
wheel=(midiData[1]&0x7f)|((midiData[2]&0x7f)<<7);
MidiAddPitchBend(event->deltaFrames,(float)(wheel-0x2000)*MidiPitchBendRange/8192.0f);
}
break;
}
}
return 1;
}
VstInt32 PulseSynth::SynthAllocateVoice(VstInt32 note)
{
VstInt32 chn;
for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note==note) return chn;
for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note<0) return chn;
for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].e_stage==eStageRelease) return chn;
return -1;
}
void PulseSynth::SynthChannelChangeNote(VstInt32 chn,VstInt32 note)
{
SynthChannel[chn].note=note;
if(note>=0)
{
SynthChannel[chn].freq_new=(float)SynthChannel[chn].note-69;
sSlideStep=(SynthChannel[chn].freq-SynthChannel[chn].freq_new)*20.0f*log(1.0f-pPortaSpeed[Program]);
}
}
float PulseSynth::SynthEnvelopeTimeToDelta(float value,float max_ms)
{
return (1.0f/ENVELOPE_UPDATE_RATE_HZ)/(value*max_ms/1000.0f);
}
void PulseSynth::SynthRestartEnvelope(VstInt32 chn)
{
if(pAttack[Program]>0||pDecay[Program]>0)
{
SynthChannel[chn].e_stage=eStageAttack;
SynthChannel[chn].e_level=0;
SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pAttack[Program],ENVELOPE_ATTACK_MAX_MS);
}
else
{
SynthChannel[chn].e_stage=eStageSustain;
SynthChannel[chn].e_level=pSustain[Program];
}
}
void PulseSynth::SynthStopEnvelope(VstInt32 chn)
{
SynthChannel[chn].e_stage=eStageRelease;
SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pRelease[Program],ENVELOPE_RELEASE_MAX_MS);
}
void PulseSynth::SynthAdvanceEnvelopes(void)
{
VstInt32 chn;
for(chn=0;chn<SYNTH_CHANNELS;++chn)
{
if(SynthChannel[chn].e_stage==eStageReset)
{
SynthChannel[chn].note=-1;
SynthChannel[chn].e_level=0;
}
else
{
switch(SynthChannel[chn].e_stage)
{
case eStageAttack:
{
SynthChannel[chn].e_level+=SynthChannel[chn].e_delta;
if(SynthChannel[chn].e_level>=1.0f)
{
SynthChannel[chn].e_level=1.0f;
SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pDecay[Program],ENVELOPE_DECAY_MAX_MS);
SynthChannel[chn].e_stage=eStageDecay;
}
}
break;
case eStageDecay:
{
SynthChannel[chn].e_level-=SynthChannel[chn].e_delta;
if(SynthChannel[chn].e_level<=pSustain[Program])
{
SynthChannel[chn].e_level=pSustain[Program];
SynthChannel[chn].e_stage=eStageSustain;
}
}
break;
case eStageRelease:
{
SynthChannel[chn].e_level-=SynthChannel[chn].e_delta;
if(SynthChannel[chn].e_level<=0) SynthChannel[chn].e_stage=eStageReset;
}
break;
}
}
}
}
void PulseSynth::processReplacing(float **inputs,float **outputs,VstInt32 sampleFrames)
{
float *outL=outputs[0];
float *outR=outputs[1];
float level,pulsefix,modulation,mod_step,sampleRate;
unsigned int i,s,poly,out;
int chn,note,prev_note;
bool key_off;
sampleRate=(float)updateSampleRate();
mod_step=12.0f/sampleRate*(float)M_PI;
poly=(int)(pPolyphony[Program]*2.99f);
pulsefix=sampleRate*PULSE_WIDTH_MAX_US*OVERSAMPLING*pPulseWidth[Program];
while(--sampleFrames>=0)
{
if(MidiModulationDepth>=.01f) modulation=sinf(MidiModulationCount)*MidiModulationDepth; else modulation=0;
MidiModulationCount+=mod_step;
key_off=false;
for(i=0;i<MidiQueue.size();++i)
{
if(MidiQueue[i].delta>=0)
{
--MidiQueue[i].delta;
if(MidiQueue[i].delta<0)//new message
{
switch(MidiQueue[i].type)
{
case mEventTypeNote:
{
if(MidiQueue[i].velocity)//key on
{
MidiKeyState[MidiQueue[i].note]=1;
if(!poly) chn=0; else chn=SynthAllocateVoice(MidiQueue[i].note);
if(chn>=0)
{
prev_note=SynthChannel[chn].note;
SynthChannelChangeNote(chn,MidiQueue[i].note);
if(prev_note<0||poly) SynthChannel[chn].freq=SynthChannel[chn].freq_new;
if(poly||prev_note<0)
{
SynthChannel[chn].acc=0; //phase reset
SynthChannel[chn].volume=((float)MidiQueue[i].velocity/100.0f);
if(pLowBoost[Program]>=.5f) //even out energy spread to make lower end louder
{
SynthChannel[chn].volume*=.021f*pow(2.0f,(127.0f-MidiQueue[i].note)/12.0f);
}
SynthRestartEnvelope(chn);
}
}
}
else//key off
{
key_off=true;
if(MidiQueue[i].note>=0)
{
MidiKeyState[MidiQueue[i].note]=0;
if(poly)
{
for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note==MidiQueue[i].note) SynthStopEnvelope(chn);
}
else
{
for(note=127;note>=0;--note)
{
if(MidiKeyState[note])
{
SynthChannelChangeNote(0,note);
break;
}
}
}
}
else
{
memset(MidiKeyState,0,sizeof(MidiKeyState));
for(chn=0;chn<SYNTH_CHANNELS;++chn) SynthStopEnvelope(chn);
}
}
}
break;
case mEventTypeProgram:
{
Program=MidiQueue[i].program;
updateDisplay();
}
break;
case mEventTypePitchBend:
{
MidiPitchBend=MidiQueue[i].depth;
}
break;
case mEventTypeModulation:
{
MidiModulationDepth=MidiQueue[i].depth/4.0f;
}
break;
}
}
}
}
if(!poly&&key_off)
{
if(!MidiIsAnyKeyDown())
{
for(chn=0;chn<SYNTH_CHANNELS;++chn) SynthStopEnvelope(chn);
}
}
sEnvelopeDiv+=ENVELOPE_UPDATE_RATE_HZ/sampleRate;
if(sEnvelopeDiv>=1.0f)
{
sEnvelopeDiv-=1.0f;
SynthAdvanceEnvelopes();
}
for(chn=0;chn<SYNTH_CHANNELS;++chn)
{
if(SynthChannel[chn].note<0) continue;
if(pPortaSpeed[Program]>=1.0f)
{
SynthChannel[chn].freq=SynthChannel[chn].freq_new;
}
else
{
if(SynthChannel[chn].freq<SynthChannel[chn].freq_new)
{
SynthChannel[chn].freq+=sSlideStep/sampleRate;
if(SynthChannel[chn].freq>SynthChannel[chn].freq_new) SynthChannel[chn].freq=SynthChannel[chn].freq_new;
}
if(SynthChannel[chn].freq>SynthChannel[chn].freq_new)
{
SynthChannel[chn].freq+=sSlideStep/sampleRate;
if(SynthChannel[chn].freq<SynthChannel[chn].freq_new) SynthChannel[chn].freq=SynthChannel[chn].freq_new;
}
}
SynthChannel[chn].add=440.0f*pow(2.0f,(SynthChannel[chn].freq+modulation+MidiPitchBend+pDetune[Program]*2.0f-1.0f)/12.0f)/sampleRate/OVERSAMPLING;
}
level=0;
if(poly<2) //poly PWM
{
for(s=0;s<OVERSAMPLING;++s)
{
out=0;
for(chn=0;chn<SYNTH_CHANNELS;++chn)
{
if(SynthChannel[chn].note<0) continue;
SynthChannel[chn].acc+=SynthChannel[chn].add;
while(SynthChannel[chn].acc>=1.0f)
{
SynthChannel[chn].acc-=1.0f;
SynthChannel[0].pulse+=pulsefix*SynthChannel[chn].e_level*SynthChannel[chn].volume/1000000.0f;
}
}
if(SynthChannel[0].pulse>0)
{
SynthChannel[0].pulse-=1.0f;
out=1;
}
else
{
SynthChannel[0].pulse=0;
}
if(out) level+=1.0f/OVERSAMPLING;
}
}
else //poly ADD
{
for(s=0;s<OVERSAMPLING;++s)
{
for(chn=0;chn<SYNTH_CHANNELS;++chn)
{
if(SynthChannel[chn].note<0) continue;
SynthChannel[chn].acc+=SynthChannel[chn].add;
while(SynthChannel[chn].acc>=1.0f)
{
SynthChannel[chn].acc-=1.0f;
SynthChannel[chn].pulse+=pulsefix*SynthChannel[chn].e_level*SynthChannel[chn].volume/1000000.0f;
}
if(SynthChannel[chn].pulse>0)
{
SynthChannel[chn].pulse-=1.0f;
level+=1.0f/OVERSAMPLING/(SYNTH_CHANNELS/4);
}
else
{
SynthChannel[chn].pulse=0;
}
}
}
}
level=level*pOutputGain[Program];
(*outL++)=level;
(*outR++)=level;
}
MidiQueue.clear();
}
| 21.895719 | 150 | 0.636437 | linuxmao-org |
0c2b42e4ea8cc821ef8692d0338feb6737dbf398 | 196 | cpp | C++ | examples/tetris/lib/Moon/src/cmp/cmp_base.cpp | KEGEStudios/Moon | 0e6aa078c8bf876c60aafe875ef53217ebdc74f1 | [
"MIT"
] | 2 | 2021-05-20T06:55:38.000Z | 2021-05-23T05:09:06.000Z | examples/tetris/lib/Moon/src/cmp/cmp_base.cpp | KEGEStudios/Moon | 0e6aa078c8bf876c60aafe875ef53217ebdc74f1 | [
"MIT"
] | 15 | 2021-04-21T05:26:39.000Z | 2021-07-06T07:07:28.000Z | examples/tetris/lib/Moon/src/cmp/cmp_base.cpp | reitmas32/Moon | 02790eb476f039b44664e7d8f24fa2839187e4fc | [
"MIT"
] | 1 | 2021-02-21T08:26:40.000Z | 2021-02-21T08:26:40.000Z | #include "../../include/cmp/cmp_base.hpp"
namespace Moon::Core
{
ComponentBase_t::ComponentBase_t()
{
}
ComponentBase_t::~ComponentBase_t()
{
}
} // namespace Moon::Core
| 15.076923 | 41 | 0.622449 | KEGEStudios |
0c2e5ccbb3f844de01e73aef5083d8e28da739d5 | 1,284 | cpp | C++ | Luogu/P3052.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | Luogu/P3052.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | Luogu/P3052.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2022
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
int n, w, a[20], f[1 << 19], g[1 << 19];
long long sum[1 << 19];
int main()
{
scanf("%d%d", &n, &w);
for (int i = 0; i < n; ++i)
scanf("%d", a + i);
memset(f, 0x3f, sizeof(f));
f[0] = 1;
for (int S = 0; S < (1 << n); ++S)
{
for (int i = 0; i < n; ++i)
{
if ((S >> i) & 1)
continue;
if (g[S] + a[i] <= w)
{
if (f[S | (1 << i)] > f[S])
{
f[S | (1 << i)] = f[S];
g[S | (1 << i)] = g[S] + a[i];
}
else if (f[S | (1 << i)] == f[S] && g[S | (1 << i)] > g[S] + a[i])
g[S | (1 << i)] = g[S] + a[i];
}
else
{
if (f[S | (1 << i)] > f[S] + 1)
{
f[S | (1 << i)] = f[S] + 1;
g[S | (1 << i)] = a[i];
}
else if (f[S | (1 << i)] == f[S] + 1 && g[S | (1 << i)] > a[i])
g[S | (1 << i)] = a[i];
}
}
}
printf("%d\n", f[(1 << n) - 1]);
return 0;
} | 25.68 | 82 | 0.271028 | Nickel-Angel |
0c2f9485fc072c724cf0d8ec52627f4704423fa7 | 3,246 | cpp | C++ | src/mod/debug/quantum_duck.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 33 | 2016-02-18T04:27:53.000Z | 2022-01-15T18:59:53.000Z | src/mod/debug/quantum_duck.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 5 | 2018-01-10T18:41:38.000Z | 2020-10-01T13:34:53.000Z | src/mod/debug/quantum_duck.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 14 | 2017-08-06T23:02:49.000Z | 2021-08-24T00:24:16.000Z | #include "mod.h"
namespace Mod::Debug::Quantum_Duck
{
// +CBasePlayer::m_bDucked
// +CBasePlayer::m_bDucking
// +CBasePlayer::m_bInDuckJump
// +CBasePlayer::m_flDuckTime
// +CBasePlayer::m_flDuckJumpTime
// +CBasePlayer::m_bDuckToggled
// +CBasePlayer::m_fFlags <-- particularly FL_DUCKING, FL_ANIMDUCKING
// +CBasePlayer::m_afPhysicsFlags <-- particularly PFLAG_DUCKING
// CBasePlayer::m_vphysicsCollisionState << need prop accessors for these
// CBasePlayer::m_pShadowStand << need prop accessors for these
// CBasePlayer::m_pShadowCrouch << need prop accessors for these
// see game/server/playerlocaldata.h for descriptions of the meanings of these variables
// CLIENT ONLY
// - C_BasePlayer::PostThink: based on GetFlags() & FL_DUCKING, call SetCollisionBounds(...)
// SERVER ONLY
// - virtual CBasePlayer::Duck (TODO: is there a client equivalent for prediction?)
// - CBasePlayer::RunCommand
// - CBasePlayer::PreThink
// - FixPlayerCrouchStuck (only from CBasePlayer::Restore)
// - CBasePlayer::PostThink: based on GetFlags() & FL_DUCKING, calls SetCollisionBounds(...)
// - CBasePlayer::PostThinkVPhysics: based on GetFlags() & FL_DUCKING, may call SetVCollisionState(..., ..., VPHYS_CROUCH)
// - CBasePlayer::SetupVPhysicsShadow: based on GetFlags & FL_DUCKING, calls SetVCollisionState(..., ..., VPHYS_CROUCH or VPHYS_WALK)
// SHARED
// - CBasePlayer::GetPlayerMins: based on GetFlags() & FL_DUCKING, returns VEC(_DUCK)?_HULL_MIN_SCALED
// - CBasePlayer::GetPlayerMaxs: based on GetFlags() & FL_DUCKING, returns VEC(_DUCK)?_HULL_MAX_SCALED
// - CGameMovement::GetPlayerMins: based on parameter or m_Local.m_bDucked, returns VEC(_DUCK)?_HULL_MIN_SCALED
// - CGameMovement::GetPlayerMaxs: based on parameter or m_Local.m_bDucked, returns VEC(_DUCK)?_HULL_MAX_SCALED
// - CGameMovement::GetPlayerViewOffset: based on parameter, returns VEC(_DUCK)?_VIEW_SCALED
// - CGameMovement::FixPlayerCrouchStuck
// - CGameMovement::CanUnduck
// - CGameMovement::FinishUnDuck
// - CGameMovement::UpdateDuckJumpEyeOffset
// - CGameMovement::FinishUnDuckJump
// - CGameMovement::FinishDuck
// - CGameMovement::StartUnDuckJump
// - CGameMovement::SetDuckedEyeOffset
// - CGameMovement::Duck (ESPECIALLY THE HACK AT THE END OF THE FUNCTION!!)
// tweaks:
// - debug_latch_reset_onduck (STAGING_ONLY)
// overlays:
// player->CollisionProperty->OBBMins()
// player->CollisionProperty->OBBMaxs()
// player->EyePosition()
// player->GetViewOffset()
// player origin
// player wsc
// draw vphysics shadow
// draw all boxes that ICollideable will tell us about
// TODO: find in files for "crouch"
// TODO: find TF specific stuff
// - any users of CGameMovement::SplineFraction?
class CMod : public IMod
{
public:
CMod() : IMod("Debug:Quantum_Duck")
{
}
};
CMod s_Mod;
ConVar cvar_enable("sig_debug_quantum_duck", "0", FCVAR_NOTIFY,
"Debug: determine why quantum ducking is possible and how to fix it",
[](IConVar *pConVar, const char *pOldValue, float flOldValue){
s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool());
});
}
| 35.67033 | 135 | 0.705176 | fugueinheels |
0c3799b6c2560fd09d84cafa4ad16e1e896efc78 | 1,238 | cpp | C++ | 03/roh/2644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 2 | 2021-01-09T10:05:21.000Z | 2021-01-10T06:14:03.000Z | 03/roh/2644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | null | null | null | 03/roh/2644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 1 | 2021-02-03T13:09:09.000Z | 2021-02-03T13:09:09.000Z | #include<iostream>
#include<vector>
//lca(least common ancestor) 문제는 사실... log(n) 해결방법이 있습니다......
using namespace std;
//각노드의 부모의 인덱스를 저장하는 배열
int parent[1000];
//child가 final ancestor 에 도달할때까지의 방문하는 노드의 idx를 돌려준다.
vector<int> get_p(int child){
vector<int> result;
while(child != -1){
result.push_back(child);
child = parent[child];
}
return result;
}
int main(){
ios::sync_with_stdio(false);
for(int i =0 ;i<1000; i++){
parent[i] = -1;
}
int n_people;
cin>>n_people;
int target_a, target_b;
cin>>target_a>>target_b;
int n_rule;
cin>>n_rule;
while(n_rule--){
int c,p;
cin>>p>>c;
//트리를 만들어 줍니다!
//c번 노드의 부모는 p
parent[c] = p;
}
//a,b 가 final ancestor 까지 가려면 누구를 거쳐가야하는지 저장하는 리스트(벡터)
vector<int> a_parents = get_p(target_a);
vector<int> b_parents = get_p(target_b);
//만약 두 노드의 final ancestor 가 다르면 둘은 서로다른 트리에 존재하는것임.
if(a_parents.back() != b_parents.back()){
cout<<-1;
}
else{
//둘의 모든 공통된 조상들을 제외하고나면 그들이 최초로 공통되는 조상까지의 거리가 나온다.
while(!a_parents.empty() && !b_parents.empty() && a_parents.back() == b_parents.back()){
a_parents.pop_back();
b_parents.pop_back();
}
cout<<a_parents.size() + b_parents.size();
}
return 0;
} | 20.295082 | 92 | 0.62601 | Dcom-KHU |
0c3a6e0c49281a3641ac269e4b58fc34cf12dedf | 339 | hpp | C++ | snowman.hpp | Roniharel100/CPP_EX1-Snowman_b | 0b41fc0f7946a373350819386b3bd0947eb597ee | [
"MIT"
] | null | null | null | snowman.hpp | Roniharel100/CPP_EX1-Snowman_b | 0b41fc0f7946a373350819386b3bd0947eb597ee | [
"MIT"
] | null | null | null | snowman.hpp | Roniharel100/CPP_EX1-Snowman_b | 0b41fc0f7946a373350819386b3bd0947eb597ee | [
"MIT"
] | null | null | null | #include <string>
#include <array>
using namespace std;
namespace ariel {
string snowman(int code);
const int min_snowman_code = 11111111;
const int max_snowman_code = 44444444;
const int base_num = 10;
const int min_index = 0;
const int max_index = 3;
const int top_arm = 0;
const int bottom_arm = 1;
}
| 19.941176 | 42 | 0.675516 | Roniharel100 |
0c3cdf0a548cb47115845f53749009a730f9ea86 | 3,102 | cpp | C++ | Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp | xsolla/store-ue4-sdk | e25440e9d0b82663929ee7f49807e9b6bb09606b | [
"Apache-2.0"
] | 14 | 2019-08-28T19:49:07.000Z | 2021-12-04T14:34:18.000Z | Plugins/XSolla/Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp | anchorholdgames/anchorhold | 00b4fb6b1229c9fd2dd1aff01f09ad0e9a224bbb | [
"MIT"
] | 34 | 2019-08-17T08:23:18.000Z | 2021-12-08T08:25:14.000Z | Plugins/XSolla/Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp | anchorholdgames/anchorhold | 00b4fb6b1229c9fd2dd1aff01f09ad0e9a224bbb | [
"MIT"
] | 12 | 2019-09-25T15:14:58.000Z | 2022-03-21T09:27:58.000Z | // Copyright 2021 Xsolla Inc. All Rights Reserved.
#include "XsollaUtilsUrlBuilder.h"
XsollaUtilsUrlBuilder::XsollaUtilsUrlBuilder(const FString& UrlTemplate)
: Url(UrlTemplate)
{
}
FString XsollaUtilsUrlBuilder::Build()
{
FString ResultUrl = Url;
// set path params
for (const auto& Param : PathParams)
{
const FString ParamPlaceholder = FString::Printf(TEXT("{%s}"), *Param.Key);
if (ResultUrl.Contains(ParamPlaceholder))
{
ResultUrl = ResultUrl.Replace(*ParamPlaceholder, *Param.Value);
}
}
// add query params
for (const auto& Param : StringQueryParams)
{
const FString NewParam = FString::Printf(TEXT("%s%s=%s"), ResultUrl.Contains(TEXT("?")) ? TEXT("&") : TEXT("?"), *Param.Key, *Param.Value);
ResultUrl.Append(NewParam);
}
for (const auto& Param : NumberQueryParams)
{
const FString NewParam = FString::Printf(TEXT("%s%s=%d"), ResultUrl.Contains(TEXT("?")) ? TEXT("&") : TEXT("?"), *Param.Key, Param.Value);
ResultUrl.Append(NewParam);
}
return ResultUrl;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const FString& ParamValue)
{
PathParams.Add(TPair<FString, FString>(ParamName, ParamValue));
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const int32 ParamValue)
{
PathParams.Add(TPair<FString, FString>(ParamName, FString::FromInt(ParamValue)));
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const int64 ParamValue)
{
PathParams.Add(TPair<FString, FString>(ParamName, FString::Printf(TEXT("%llu"), ParamValue)));
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddStringQueryParam(const FString& ParamName, const FString& ParamValue, const bool IgnoreEmpty)
{
if (IgnoreEmpty && ParamValue.IsEmpty())
{
return *this;
}
StringQueryParams.Add(TPair<FString, FString>(ParamName, ParamValue));
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddArrayQueryParam(const FString& ParamName, const TArray<FString>& ParamValueArray, const bool IgnoreEmpty, const bool AsOneParam)
{
if (IgnoreEmpty && ParamValueArray.Num() == 0)
{
return *this;
}
if (AsOneParam)
{
FString AdditionalFieldsString = FString::Join(ParamValueArray, TEXT(","));
AdditionalFieldsString.RemoveFromEnd(",");
AddStringQueryParam(ParamName, AdditionalFieldsString, IgnoreEmpty);
}
else
{
for (const auto& Param : ParamValueArray)
{
AddStringQueryParam(ParamName, Param, IgnoreEmpty);
}
}
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddNumberQueryParam(const FString& ParamName, const int32 ParamValue)
{
NumberQueryParams.Add(TPair<FString, int32>(ParamName, ParamValue));
return *this;
}
XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddBoolQueryParam(const FString& ParamName, const bool ParamValue, const bool AsNumber)
{
if (AsNumber)
{
AddStringQueryParam(ParamName, ParamValue ? TEXT("1") : TEXT("0"), true);
}
else
{
AddStringQueryParam(ParamName, ParamValue ? TEXT("true") : TEXT("false"), true);
}
return *this;
} | 26.741379 | 177 | 0.742424 | xsolla |
0c3f7b33a7a6b6f3dbe2e0b6c39973c0265e6e78 | 2,342 | hpp | C++ | include/ccbase/filesystem/directory_entry.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 8 | 2015-01-08T05:44:43.000Z | 2021-05-11T15:54:17.000Z | include/ccbase/filesystem/directory_entry.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 1 | 2016-01-31T08:48:53.000Z | 2016-01-31T08:54:28.000Z | include/ccbase/filesystem/directory_entry.hpp | adityaramesh/ccbase | 595e1416aab3cc8bc976aad9bb3e262c7d11e3b2 | [
"BSD-3-Clause-Clear"
] | 2 | 2015-03-26T11:08:18.000Z | 2016-01-30T03:28:06.000Z | /*
** File Name: directory_entry.hpp
** Author: Aditya Ramesh
** Date: 08/23/2013
** Contact: _@adityaramesh.com
*/
#ifndef ZDDEA7CE4_14FD_40C7_AA27_9BBF59D67383
#define ZDDEA7CE4_14FD_40C7_AA27_9BBF59D67383
#include <cstdint>
#include <ostream>
#include <ccbase/format.hpp>
#include <ccbase/platform.hpp>
#if PLATFORM_KERNEL == PLATFORM_KERNEL_LINUX
#include <dirent.h>
#elif PLATFORM_KERNEL == PLATFORM_KERNEL_XNU
#include <sys/dirent.h>
#else
#error "Unsupported kernel."
#endif
namespace cc {
enum class file_type : unsigned char
{
block_device = DT_BLK,
character_device = DT_CHR,
directory = DT_DIR,
fifo = DT_FIFO,
symbolic_link = DT_LNK,
regular = DT_REG,
socket = DT_SOCK,
unknown = DT_UNKNOWN
};
std::ostream& operator<<(std::ostream& os, const file_type& t)
{
switch (t) {
case file_type::block_device: cc::write (os, "block device"); return os;
case file_type::character_device: cc::write (os, "character device"); return os;
case file_type::directory: cc::write (os, "directory"); return os;
case file_type::fifo: cc::write (os, "fifo"); return os;
case file_type::symbolic_link: cc::write (os, "symbolic link"); return os;
case file_type::regular: cc::write (os, "regular file"); return os;
case file_type::socket: cc::write (os, "socket"); return os;
case file_type::unknown: cc::write (os, "unknown"); return os;
}
return os;
}
class directory_iterator;
class directory_entry
{
friend class directory_iterator;
using length_type = uint16_t;
const directory_iterator& m_dir_it;
const boost::string_ref m_name;
const file_type m_type;
directory_entry(
const directory_iterator& dir_it,
const char* name,
const length_type len,
const file_type type
) noexcept : m_dir_it(dir_it), m_name{name, len}, m_type{type} {}
public:
// Defined in `directory_iterator.hpp` due to cyclic dependencies.
const boost::string_ref path() const noexcept;
const boost::string_ref name() const noexcept { return m_name; }
file_type type() const noexcept { return m_type; }
};
std::ostream& operator<<(std::ostream& os, const directory_entry& e)
{
cc::write(os, "{{name: \"$\", type: \"$\"}}", e.name(), e.type());
return os;
}
}
#endif
| 27.232558 | 81 | 0.675064 | adityaramesh |
0c432fde7e0d3200477a78e6ed0ed3cf5cd7b1d4 | 2,738 | c++ | C++ | tests/css/grammar/semantic/convert_to.test.c++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 19 | 2016-10-13T22:44:31.000Z | 2021-12-28T20:28:15.000Z | tests/css/grammar/semantic/convert_to.test.c++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 1 | 2021-05-16T15:15:22.000Z | 2021-05-16T17:01:26.000Z | tests/css/grammar/semantic/convert_to.test.c++ | rubenvb/skui | 5bda2d73232eb7a763ba9d788c7603298767a7d7 | [
"MIT"
] | 4 | 2017-03-07T05:37:02.000Z | 2018-06-05T03:14:48.000Z | /**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* 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 "css/test_rule.h++"
#include <core/string.h++>
#include <css/grammar/semantic/convert_to.h++>
namespace
{
namespace x3 = boost::spirit::x3;
using skui::core::string;
using skui::css::grammar::convert_to;
struct constructible_from_int
{
explicit constructible_from_int(int i = 0) : v{i} {}
int v;
};
struct constructible_from_float
{
explicit constructible_from_float(float f = 0.f) : v{f} {}
float v;
};
bool operator==(const constructible_from_int& lhs, const constructible_from_int& rhs)
{
return lhs.v == rhs.v;
}
bool operator==(const constructible_from_float& lhs, const constructible_from_float& rhs)
{
return lhs.v == rhs.v;
}
std::ostream& operator<<(std::ostream& os, const constructible_from_int& c)
{
return os << c.v;
}
std::ostream& operator<<(std::ostream& os, const constructible_from_float& c)
{
return os << c.v;
}
const auto conversion1 = x3::rule<struct conversion1, constructible_from_int>{"conversion1"}
= x3::int_[convert_to<constructible_from_int>{}];
const auto conversion2 = x3::rule<struct conversion2, constructible_from_float>{"conversion2"}
= x3::int_[convert_to<constructible_from_float, float>{}];
const string integer = "42";
}
int main()
{
using skui::test::check_rule_success;
using skui::test::check_rule_failure;
check_rule_success(conversion1, integer, constructible_from_int{42});
check_rule_success(conversion2, integer, constructible_from_float{42.f});
return skui::test::exit_code;
}
| 31.113636 | 96 | 0.71439 | rubenvb |
0c45416a540bd4eb84a6067dc74093fee62064f0 | 5,311 | inl | C++ | src/editor/include/agz/editor/resource/resource_panel.inl | AirGuanZ/Atrc | a0c4bc1b7bb96ddffff8bb1350f88b651b94d993 | [
"MIT"
] | 358 | 2018-11-29T08:15:05.000Z | 2022-03-31T07:48:37.000Z | src/editor/include/agz/editor/resource/resource_panel.inl | happyfire/Atrc | 74cac111e277be53eddea5638235d97cec96c378 | [
"MIT"
] | 23 | 2019-04-06T17:23:58.000Z | 2022-02-08T14:22:46.000Z | src/editor/include/agz/editor/resource/resource_panel.inl | happyfire/Atrc | 74cac111e277be53eddea5638235d97cec96c378 | [
"MIT"
] | 22 | 2019-03-04T01:47:56.000Z | 2022-01-13T06:06:49.000Z | #pragma once
AGZ_EDITOR_BEGIN
template<typename TracerObject>
ResourcePanel<TracerObject>::ResourcePanel(
ObjectContext &obj_ctx, const QString &default_type)
: obj_ctx_(obj_ctx)
{
type_selector_ = new ComboBoxWithoutWheelFocus(this);
type_selector_->addItems(obj_ctx.factory<TracerObject>().get_type_names());
type_selector_->setCurrentText(default_type);
auto change_type = [=](const QString &new_type)
{
if(rsc_widget_)
delete rsc_widget_;
rsc_widget_ = obj_ctx_.factory<TracerObject>()
.create_widget(new_type, obj_ctx_);
rsc_widget_->set_dirty_callback([=]
{
if(dirty_callback_)
dirty_callback_();
});
rsc_widget_->set_geometry_vertices_dirty_callback([=]
{
set_geometry_vertices_dirty();
});
rsc_widget_->set_entity_transform_dirty_callback([=]
{
set_entity_transform_dirty();
});
layout_->addWidget(rsc_widget_);
if(dirty_callback_)
dirty_callback_();
set_geometry_vertices_dirty();
set_entity_transform_dirty();
};
signal_to_callback_.connect_callback(
type_selector_, &ComboBoxWithoutWheelFocus::currentTextChanged,
change_type);
layout_ = new QVBoxLayout(this);
layout_->addWidget(type_selector_);
setContentsMargins(0, 0, 0, 0);
layout_->setContentsMargins(0, 0, 0, 0);
change_type(default_type);
}
template<typename TracerObject>
ResourcePanel<TracerObject>::ResourcePanel(
ObjectContext &obj_ctx,
ResourceWidget<TracerObject> *rsc_widget, const QString ¤t_type_name)
: obj_ctx_(obj_ctx)
{
type_selector_ = new ComboBoxWithoutWheelFocus(this);
type_selector_->addItems(obj_ctx.factory<TracerObject>().get_type_names());
type_selector_->setCurrentText(current_type_name);
signal_to_callback_.connect_callback(
type_selector_, &ComboBoxWithoutWheelFocus::currentTextChanged,
[=](const QString &new_type)
{
on_change_selected_type();
});
rsc_widget_ = rsc_widget;
rsc_widget_->set_dirty_callback([=]
{
if(dirty_callback_)
dirty_callback_();
});
rsc_widget_->set_geometry_vertices_dirty_callback([=]
{
set_geometry_vertices_dirty();
});
rsc_widget_->set_entity_transform_dirty_callback([=]
{
set_entity_transform_dirty();
});
layout_ = new QVBoxLayout(this);
layout_->addWidget(type_selector_);
layout_->addWidget(rsc_widget_);
setContentsMargins(0, 0, 0, 0);
layout_->setContentsMargins(0, 0, 0, 0);
}
template<typename TracerObject>
void ResourcePanel<TracerObject>::set_dirty_callback(std::function<void()> callback)
{
dirty_callback_ = std::move(callback);
}
template<typename TracerObject>
RC<TracerObject> ResourcePanel<TracerObject>::get_tracer_object()
{
return rsc_widget_->get_tracer_object();
}
template<typename TracerObject>
ResourcePanel<TracerObject> *ResourcePanel<TracerObject>::clone() const
{
return new ResourcePanel(
obj_ctx_, rsc_widget_->clone(), type_selector_->currentText());
}
template<typename TracerObject>
Box<ResourceThumbnailProvider> ResourcePanel<TracerObject>::get_thumbnail(
int width, int height) const
{
return rsc_widget_->get_thumbnail(width, height);
}
template<typename TracerObject>
void ResourcePanel<TracerObject>::save_asset(AssetSaver &saver) const
{
saver.write_string(type_selector_->currentText());
rsc_widget_->save_asset(saver);
}
template<typename TracerObject>
void ResourcePanel<TracerObject>::load_asset(AssetLoader &loader)
{
const QString type = loader.read_string();
type_selector_->setCurrentText(type);
rsc_widget_->load_asset(loader);
}
template<typename TracerObject>
RC<tracer::ConfigNode> ResourcePanel<TracerObject>::to_config(
JSONExportContext &ctx) const
{
return rsc_widget_->to_config(ctx);
}
template<typename TracerObject>
std::vector<EntityInterface::Vertex> ResourcePanel<TracerObject>::get_vertices() const
{
return rsc_widget_->get_vertices();
}
template<typename TracerObject>
DirectTransform ResourcePanel<TracerObject>::get_transform() const
{
return rsc_widget_->get_transform();
}
template<typename TracerObject>
void ResourcePanel<TracerObject>::set_transform(const DirectTransform &transform)
{
rsc_widget_->set_transform(transform);
}
template<typename TracerObject>
void ResourcePanel<TracerObject>::on_change_selected_type()
{
if(rsc_widget_)
delete rsc_widget_;
const QString new_type = type_selector_->currentText();
rsc_widget_ = obj_ctx_.factory<TracerObject>()
.create_widget(new_type, obj_ctx_);
rsc_widget_->set_dirty_callback([=]
{
if(dirty_callback_)
dirty_callback_();
});
rsc_widget_->set_geometry_vertices_dirty_callback([=]
{
set_geometry_vertices_dirty();
});
rsc_widget_->set_entity_transform_dirty_callback([=]
{
set_entity_transform_dirty();
});
layout_->addWidget(rsc_widget_);
if(dirty_callback_)
dirty_callback_();
set_geometry_vertices_dirty();
set_entity_transform_dirty();
}
AGZ_EDITOR_END
| 26.959391 | 86 | 0.707211 | AirGuanZ |
0c4558d91be24b04143ea10613ae3e7e98f4258c | 3,115 | cc | C++ | WinNTKline/KlineUtil/mygl/SDL_text.cc | TsyQi/MyAutomatic | 2afd3dcabba818051c7119fac7e6c099ff7954a7 | [
"Apache-2.0"
] | 4 | 2016-08-19T08:16:49.000Z | 2020-04-15T12:30:25.000Z | WinNTKline/KlineUtil/mygl/SDL_text.cc | TsyQi/Auto-control | d0dda0752d53d28f358346ee7ab217bf05118c96 | [
"Apache-2.0"
] | null | null | null | WinNTKline/KlineUtil/mygl/SDL_text.cc | TsyQi/Auto-control | d0dda0752d53d28f358346ee7ab217bf05118c96 | [
"Apache-2.0"
] | 3 | 2019-03-23T03:40:24.000Z | 2020-04-15T00:57:43.000Z | #include "SDL_text.h"
int SDL_GL_init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
return -1;
//Initialize SDL_ttf
return TTF_Init();
}
void SDL_GL_Enter2DMode(int w, int h)
{
/* Note, there may be other things you need to change,
depending on how you have your OpenGL state set up.
*/
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
/* This allows alpha blending of 2D textures with the scene */
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, (GLdouble)w, (GLdouble)h, 0.0, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
void SDL_GL_Leave2DMode()
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
}
/* Quick utility function for texture creation */
static int power_of_two(int input)
{
int value = 1;
while (value < input) {
value <<= 1;
}
return value;
}
GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord)
{
GLuint texture;
int w, h;
SDL_Surface *image;
SDL_Rect area;
Uint32 saved_flags;
Uint8 saved_alpha;
/* Use the surface width and height expanded to powers of 2 */
w = power_of_two(surface->w);
h = power_of_two(surface->h);
texcoord[0] = 0.0f; /* Min X */
texcoord[1] = 0.0f; /* Min Y */
texcoord[2] = (GLfloat)surface->w / w; /* Max X */
texcoord[3] = (GLfloat)surface->h / h; /* Max Y */
image = SDL_CreateRGBSurface(
SDL_SWSURFACE,
w, h,
32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000
#else
0xFF000000,
0x00FF0000,
0x0000FF00,
0x000000FF
#endif
);
if (image == NULL) {
return 0;
}
/* Save the alpha blending attributes */
saved_flags = surface->flags&(SDL_SRCALPHA | SDL_RLEACCELOK);
#if SDL_VERSION_ATLEAST(1, 3, 0)
SDL_GetSurfaceAlphaMod(surface, &saved_alpha);
SDL_SetSurfaceAlphaMod(surface, 0xFF);
#else
saved_alpha = surface->format->alpha;
if ((saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA) {
SDL_SetAlpha(surface, 0, 0);
}
#endif
/* Copy the surface into the GL texture image */
area.x = 0;
area.y = 0;
area.w = surface->w;
area.h = surface->h;
SDL_BlitSurface(surface, &area, image, &area);
/* Restore the alpha blending attributes */
#if SDL_VERSION_ATLEAST(1, 3, 0)
SDL_SetSurfaceAlphaMod(surface, saved_alpha);
#else
if ((saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA) {
SDL_SetAlpha(surface, saved_flags, saved_alpha);
}
#endif
/* Create an OpenGL texture for the image */
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
w, h,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image->pixels);
SDL_FreeSurface(image); /* No longer needed */
return texture;
}
| 22.092199 | 67 | 0.709791 | TsyQi |
0c475987bbe45d7f7c4f5d5c122d8c0ac6853adf | 17,922 | hpp | C++ | include/eixx/connect/transport_msg.hpp | heri16/eixx | 4352e356b68d2adbbdd0163ce3aaa93406c15ae2 | [
"Apache-2.0"
] | 91 | 2015-01-14T23:05:38.000Z | 2022-03-21T07:20:02.000Z | include/eixx/connect/transport_msg.hpp | heri16/eixx | 4352e356b68d2adbbdd0163ce3aaa93406c15ae2 | [
"Apache-2.0"
] | 32 | 2015-04-20T09:53:24.000Z | 2021-09-28T21:39:41.000Z | include/eixx/connect/transport_msg.hpp | heri16/eixx | 4352e356b68d2adbbdd0163ce3aaa93406c15ae2 | [
"Apache-2.0"
] | 21 | 2015-03-09T08:13:19.000Z | 2021-08-09T11:52:44.000Z | //----------------------------------------------------------------------------
/// \file transport_msg.hpp
//----------------------------------------------------------------------------
/// \brief Erlang distributed transport message type
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2010-09-12
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***** END LICENSE BLOCK *****
*/
#ifndef _EIXX_TRANSPORT_MSG_HPP_
#define _EIXX_TRANSPORT_MSG_HPP_
#include <eixx/marshal/eterm.hpp>
#include <eixx/util/common.hpp>
#include <ei.h>
namespace eixx {
namespace connect {
using eixx::marshal::tuple;
using eixx::marshal::list;
using eixx::marshal::eterm;
using eixx::marshal::epid;
using eixx::marshal::ref;
using eixx::marshal::trace;
/// Erlang distributed transport messages contain message type,
/// control message with message routing and other details, and
/// optional user message for send and reg_send message types.
template <typename Alloc>
class transport_msg {
public:
enum transport_msg_type {
UNDEFINED = 0
, LINK = 1 << ERL_LINK
, SEND = 1 << ERL_SEND
, EXIT = 1 << ERL_EXIT
, UNLINK = 1 << ERL_UNLINK
, NODE_LINK = 1 << ERL_NODE_LINK
, REG_SEND = 1 << ERL_REG_SEND
, GROUP_LEADER = 1 << ERL_GROUP_LEADER
, EXIT2 = 1 << ERL_EXIT2
, SEND_TT = 1 << ERL_SEND_TT
, EXIT_TT = 1 << ERL_EXIT_TT
, REG_SEND_TT = 1 << ERL_REG_SEND_TT
, EXIT2_TT = 1 << ERL_EXIT2_TT
, MONITOR_P = 1 << ERL_MONITOR_P
, DEMONITOR_P = 1 << ERL_DEMONITOR_P
, MONITOR_P_EXIT = 1 << ERL_MONITOR_P_EXIT
//---------------------------
, EXCEPTION = 1 << 31 // Non-Erlang defined code representing
// message handling exception
, NO_EXCEPTION_MASK = (uint32_t)EXCEPTION-1
};
private:
// Note that the m_type is mutable so that we can call set_error_flag() on
// constant objects.
mutable transport_msg_type m_type;
tuple<Alloc> m_cntrl;
eterm<Alloc> m_msg;
public:
transport_msg() : m_type(UNDEFINED) {}
transport_msg(int a_msgtype, const tuple<Alloc>& a_cntrl, const eterm<Alloc>* a_msg = NULL)
: m_type(1 << a_msgtype), m_cntrl(a_cntrl)
{
if (a_msg)
new (&m_msg) eterm<Alloc>(*a_msg);
}
transport_msg(const transport_msg& rhs)
: m_type(rhs.m_type), m_cntrl(rhs.m_cntrl), m_msg(rhs.m_msg)
{}
transport_msg(transport_msg&& rhs)
: m_type(rhs.m_type), m_cntrl(std::move(rhs.m_cntrl)), m_msg(std::move(rhs.m_msg))
{
rhs.m_type = UNDEFINED;
}
/// Return a string representation of the transport message type.
const char* type_string() const;
/// Transport message type
transport_msg_type type() const { return m_type; }
int to_type() const { return m_type == UNDEFINED ? 0 : bit_scan_forward(m_type); }
const tuple<Alloc>& cntrl() const { return m_cntrl;}
const eterm<Alloc>& msg() const { return m_msg; }
/// Returns true when the transport message contains message payload
/// associated with SEND or REG_SEND message type.
bool has_msg() const { return m_msg.type() != eixx::UNDEFINED; }
/// Indicates that there was an error processing this message
bool has_error() const { return (m_type & EXCEPTION) == EXCEPTION; }
/// Set an error flag indicating a problem processing this message
void set_error_flag() const {
m_type = static_cast<transport_msg_type>(m_type | EXCEPTION);
}
/// Return the term representing the message sender. The sender is
/// usually a pid, except for MONITOR_P_EXIT message type for which
/// the sender can be either pid or atom name.
const eterm<Alloc>& sender() const {
switch (m_type) {
case REG_SEND:
case LINK:
case UNLINK:
case EXIT:
case EXIT2:
case GROUP_LEADER:
case REG_SEND_TT:
case EXIT_TT:
case EXIT2_TT:
case MONITOR_P:
case DEMONITOR_P:
case MONITOR_P_EXIT:
return m_cntrl[1];
default:
throw err_wrong_type(m_type, "transport_msg.from()");
}
}
/// This function may only raise exception for MONITOR_P_EXIT
/// message types if the message sender is given by name rather than by pid.
/// @throws err_wrong_type
const epid<Alloc>& sender_pid() const {
return sender().to_pid();
}
/// Return the term representing the message sender. The sender is
/// usually a pid, except for MONITOR_P|DEMONITOR_P message type for which
/// the sender can be either pid or atom name.
const eterm<Alloc>& recipient() const {
switch (m_type) {
case REG_SEND:
return m_cntrl[3];
case REG_SEND_TT:
return m_cntrl[4];
case SEND:
case LINK:
case UNLINK:
case EXIT:
case EXIT2:
case GROUP_LEADER:
case SEND_TT:
case EXIT_TT:
case EXIT2_TT:
case MONITOR_P:
case DEMONITOR_P:
case MONITOR_P_EXIT:
return m_cntrl[2];
default:
throw err_wrong_type(m_type, "transport_msg.to()");
}
}
/// This function may only raise exception for MONITOR_P|DEMONITOR_P
/// message types if the message sender is given by name rather than by pid.
/// @throws err_wrong_type
const epid<Alloc>& recipient_pid() const {
return recipient().to_pid();
}
/// @throws err_wrong_type
const atom& recipient_name() const {
return recipient().to_atom();
}
/// @throws err_wrong_type
const eterm<Alloc>& trace_token() const {
switch (m_type) {
case SEND_TT:
case EXIT_TT:
case EXIT2_TT: return m_cntrl[3];
case REG_SEND_TT: return m_cntrl[4];
default:
throw err_wrong_type(m_type, "SEND_TT|EXIT_TT|EXIT2_TT|REG_SEND_TT");
}
}
/// @throws err_wrong_type
const ref<Alloc>& get_ref() const {
switch (m_type) {
case MONITOR_P:
case DEMONITOR_P:
case MONITOR_P_EXIT:
return m_cntrl[3].to_ref();
default:
throw err_wrong_type(m_type, "MONITOR_P|DEMONITOR_P|MONITOR_P_EXIT");
}
}
/// @throws err_wrong_type
const eterm<Alloc>& reason() const {
switch (m_type) {
case EXIT:
case EXIT2: return m_cntrl[3];
case EXIT_TT:
case EXIT2_TT:
case MONITOR_P_EXIT:return m_cntrl[4];
default:
throw err_wrong_type(m_type, "EXIT|EXIT2|EXIT_TT|EXIT2_TT|MONITOR_P_EXIT");
}
}
/// Initialize the object with given components.
void set(int a_msgtype, const tuple<Alloc>& a_cntrl, const eterm<Alloc>* a_msg = NULL) {
m_type = static_cast<transport_msg_type>(1 << a_msgtype);
m_cntrl = a_cntrl;
if (a_msg)
m_msg = *a_msg;
else
m_msg.clear();
}
/// Set the current message to represent a SEND message containing \a a_msg to
/// be sent to \a a_to pid.
void set_send(const epid<Alloc>& a_to, const eterm<Alloc>& a_msg,
const Alloc& a_alloc = Alloc())
{
const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET);
if (unlikely(token)) {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_SEND_TT, atom(), a_to, *token, a_alloc);
set(ERL_SEND_TT, l_cntrl, &a_msg);
} else {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_SEND, atom(), a_to, a_alloc);
set(ERL_SEND, l_cntrl, &a_msg);
}
}
/// Set the current message to represent a REG_SEND message containing
/// \a a_msg to be sent from \a a_from pid to \a a_to registered mailbox.
void set_reg_send(const epid<Alloc>& a_from, const atom& a_to,
const eterm<Alloc>& a_msg, const Alloc& a_alloc = Alloc())
{
const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET);
if (unlikely(token)) {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_REG_SEND_TT, a_from, atom(), a_to, *token, a_alloc);
set(ERL_REG_SEND_TT, l_cntrl, &a_msg);
} else {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_REG_SEND, a_from, atom(), a_to, a_alloc);
set(ERL_REG_SEND, l_cntrl, &a_msg);
}
}
/// Set the current message to represent a LINK message.
void set_link(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const Alloc& a_alloc = Alloc())
{
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_LINK, a_from, a_to, a_alloc);
set(LINK, l_cntrl, NULL);
}
/// Set the current message to represent an UNLINK message.
void set_unlink(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const Alloc& a_alloc = Alloc())
{
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(ERL_UNLINK, a_from, a_to, a_alloc);
set(UNLINK, l_cntrl, NULL);
}
/// Set the current message to represent an EXIT message with \a a_reason
/// sent from \a a_from pid to \a a_to pid.
void set_exit(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc())
{
set_exit_internal(ERL_EXIT, ERL_EXIT_TT, a_from, a_to, a_reason, a_alloc);
}
/// Set the current message to represent an EXIT2 message.
void set_exit2(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc())
{
set_exit_internal(ERL_EXIT2, ERL_EXIT2_TT, a_from, a_to, a_reason, a_alloc);
}
/// Set the current message to represent a MONITOR message.
void set_monitor(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc())
{
set_monitor_internal(ERL_MONITOR_P, a_from, a_to, a_ref, a_alloc);
}
/// Set the current message to represent a MONITOR message.
void set_monitor(const epid<Alloc>& a_from, const atom& a_to,
const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc())
{
set_monitor_internal(ERL_MONITOR_P, a_from, a_to, a_ref, a_alloc);
}
/// Set the current message to represent a DEMONITOR message.
void set_demonitor(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc())
{
set_monitor_internal(ERL_DEMONITOR_P, a_from, a_to, a_ref, a_alloc);
}
/// Set the current message to represent a DEMONITOR message.
void set_demonitor(const epid<Alloc>& a_from, const atom& a_to,
const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc())
{
set_monitor_internal(ERL_DEMONITOR_P, a_from, a_to, a_ref, a_alloc);
}
/// Set the current message to represent a MONITOR_EXIT message.
void set_monitor_exit(const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const ref<Alloc>& a_ref, const eterm<Alloc>& a_reason,
const Alloc& a_alloc = Alloc())
{
const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(
ERL_MONITOR_P_EXIT, a_from, a_to, a_ref, a_reason, a_alloc);
set(ERL_MONITOR_P_EXIT, l_cntrl, NULL);
}
/// Set the current message to represent a MONITOR_EXIT message.
void set_monitor_exit(const atom& a_from, const epid<Alloc>& a_to,
const ref<Alloc>& a_ref, const eterm<Alloc>& a_reason,
const Alloc& a_alloc = Alloc())
{
const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(
ERL_MONITOR_P_EXIT, a_from, a_to, a_ref, a_reason, a_alloc);
set(ERL_MONITOR_P_EXIT, l_cntrl, NULL);
}
/// Send RPC call request.
/// Result will be delivered to the mailbox of the \a a_from pid.
/// The RPC consists of two parts, send and receive.
/// Here is the send part: <tt>{ PidFrom, { call, Mod, Fun, Args, user }}</tt>
void set_send_rpc(const epid<Alloc>& a_from,
const atom& mod, const atom& fun, const list<Alloc>& args,
const epid<Alloc>* a_gleader = NULL, const Alloc& a_alloc = Alloc())
{
static atom s_cmd("call");
static eterm<Alloc> s_user(atom("user"));
eterm<Alloc> gleader(a_gleader == NULL ? s_user : eterm<Alloc>(*a_gleader));
const tuple<Alloc>& inner_tuple =
tuple<Alloc>::make(a_from,
tuple<Alloc>::make(s_cmd, mod, fun, args, gleader, a_alloc),
a_alloc);
set_send_rpc_internal(a_from, inner_tuple, a_alloc);
}
/// Send RPC cast request.
/// The result of this RPC cast is discarded.
/// Here is the send part:
/// <tt>{PidFrom, {'$gen_cast', {cast, Mod, Fun, Args, user}}}</tt>
void set_send_rpc_cast(const epid<Alloc>& a_from,
const atom& mod, const atom& fun, const list<Alloc>& args,
const epid<Alloc>* a_gleader = NULL, const Alloc& a_alloc = Alloc())
{
static atom s_gen_cast("$gen_cast");
static atom s_cmd("cast");
static eterm<Alloc> s_user(atom("user"));
eterm<Alloc> gleader(a_gleader == NULL ? s_user : eterm<Alloc>(*a_gleader));
const tuple<Alloc>& inner_tuple =
tuple<Alloc>::make(s_gen_cast,
tuple<Alloc>::make(s_cmd, mod, fun, args, gleader, a_alloc), a_alloc);
set_send_rpc_internal(a_from, inner_tuple, a_alloc);
}
std::ostream& dump(std::ostream& out) const {
out << "#DistMsg{" << (has_error() ? "has_error, " : "")
<< "type=" << type_string() << ", cntrl=" << cntrl();
if (has_msg())
out << ", msg=" << msg().to_string();
return out << '}';
}
std::string to_string() const {
std::stringstream s; dump(s); return s.str();
}
private:
void set_exit_internal(int a_type, int a_trace_type,
const epid<Alloc>& a_from, const epid<Alloc>& a_to,
const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc())
{
const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET);
if (unlikely(token)) {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(a_trace_type, a_from, a_to, *token, a_reason, a_alloc);
set(a_trace_type, l_cntrl, NULL);
} else {
const tuple<Alloc>& l_cntrl =
tuple<Alloc>::make(a_type, a_from, a_to, a_reason, a_alloc);
set(a_type, l_cntrl, NULL);
}
}
template <typename FromProc, typename ToProc>
void set_monitor_internal(int a_type,
FromProc a_from, ToProc a_to, const ref<Alloc>& a_ref,
const Alloc& a_alloc = Alloc())
{
const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(a_type, a_from, a_to, a_ref, a_alloc);
set(a_type, l_cntrl, NULL);
}
void set_send_rpc_internal(const epid<Alloc>& a_from, const tuple<Alloc>& a_cmd,
const Alloc& a_alloc = Alloc())
{
static atom rex("rex");
set_reg_send(a_from, rex, eterm<Alloc>(a_cmd), a_alloc);
}
};
template <typename Alloc>
const char* transport_msg<Alloc>::type_string() const {
switch (m_type & NO_EXCEPTION_MASK) {
case UNDEFINED: return "UNDEFINED";
case LINK: return "LINK";
case SEND: return "SEND";
case EXIT: return "EXIT";
case UNLINK: return "UNLINK";
case NODE_LINK: return "NODE_LINK";
case REG_SEND: return "REG_SEND";
case GROUP_LEADER: return "GROUP_LEADER";
case EXIT2: return "EXIT2";
case SEND_TT: return "SEND_TT";
case EXIT_TT: return "EXIT_TT";
case REG_SEND_TT: return "REG_SEND_TT";
case EXIT2_TT: return "EXIT2_TT";
case MONITOR_P: return "MONITOR_P";
case DEMONITOR_P: return "DEMONITOR_P";
case MONITOR_P_EXIT: return "MONITOR_P_EXIT";
default: {
// std::stringstream str; str << "UNSUPPORTED(" << bit_scan_forward(m_type) << ')';
// return str.str().c_str();
return "UNSUPPORTED";
}
}
}
} // namespace connect
} // namespace eixx
namespace std {
template <typename Alloc>
ostream& operator<< (ostream& out, eixx::connect::transport_msg<Alloc>& a_msg) {
return a_msg.dump(out);
}
} // namespace std
#endif // _EIXX_TRANSPORT_MSG_HPP_
| 37.572327 | 104 | 0.587267 | heri16 |
0c4a16d45949472519183e9243784ba1944d70c6 | 3,069 | cpp | C++ | server/src/sink.cpp | imsoo/darknet_server | adb94237804e62bcccbbe5f7810da60640aef1d9 | [
"MIT"
] | 25 | 2020-02-08T12:08:20.000Z | 2022-03-15T12:17:07.000Z | server/src/sink.cpp | gwnuysw/darknet_server | 8b587038a165be23a1c83c32b31e92509de631e2 | [
"MIT"
] | 12 | 2020-02-14T09:01:26.000Z | 2021-10-30T14:59:49.000Z | server/src/sink.cpp | gwnuysw/darknet_server | 8b587038a165be23a1c83c32b31e92509de631e2 | [
"MIT"
] | 11 | 2019-12-21T00:30:16.000Z | 2021-11-23T09:01:02.000Z | #include <zmq.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <csignal>
#include <assert.h>
#include <tbb/concurrent_hash_map.h>
#include <opencv2/opencv.hpp>
#include "share_queue.h"
#include "frame.hpp"
// ZMQ
void *sock_pull;
void *sock_pub;
// ShareQueue
tbb::concurrent_hash_map<int, Frame> frame_map;
SharedQueue<Frame> processed_frame_queue;
// pool
Frame_pool *frame_pool;
// signal
volatile bool exit_flag = false;
void sig_handler(int s)
{
exit_flag = true;
}
void *recv_in_thread(void *ptr)
{
int recv_json_len;
unsigned char json_buf[JSON_BUF_LEN];
Frame frame;
while(!exit_flag) {
recv_json_len = zmq_recv(sock_pull, json_buf, JSON_BUF_LEN, ZMQ_NOBLOCK);
if (recv_json_len > 0) {
frame = frame_pool->alloc_frame();
json_buf[recv_json_len] = '\0';
json_to_frame(json_buf, frame);
#ifdef DEBUG
std::cout << "Sink | Recv From Worker | SEQ : " << frame.seq_buf
<< " LEN : " << frame.msg_len << std::endl;
#endif
tbb::concurrent_hash_map<int, Frame>::accessor a;
while(1)
{
if(frame_map.insert(a, atoi((char *)frame.seq_buf))) {
a->second = frame;
break;
}
}
}
}
}
void *send_in_thread(void *ptr)
{
int send_json_len;
unsigned char json_buf[JSON_BUF_LEN];
Frame frame;
while(!exit_flag) {
if (processed_frame_queue.size() > 0) {
frame = processed_frame_queue.front();
processed_frame_queue.pop_front();
#ifdef DEBUG
std::cout << "Sink | Pub To Client | SEQ : " << frame.seq_buf
<< " LEN : " << frame.msg_len << std::endl;
#endif
send_json_len = frame_to_json(json_buf, frame);
zmq_send(sock_pub, json_buf, send_json_len, 0);
frame_pool->free_frame(frame);
}
}
}
int main()
{
// ZMQ
int ret;
void *context = zmq_ctx_new();
sock_pull = zmq_socket(context, ZMQ_PULL);
ret = zmq_bind(sock_pull, "ipc://processed");
assert(ret != -1);
sock_pub = zmq_socket(context, ZMQ_PUB);
ret = zmq_bind(sock_pub, "tcp://*:5570");
assert(ret != -1);
// frame_pool
frame_pool = new Frame_pool(5000);
// Thread
pthread_t recv_thread;
if (pthread_create(&recv_thread, 0, recv_in_thread, 0))
std::cerr << "Thread creation failed (recv_thread)" << std::endl;
pthread_t send_thread;
if (pthread_create(&send_thread, 0, send_in_thread, 0))
std::cerr << "Thread creation failed (recv_thread)" << std::endl;
pthread_detach(send_thread);
pthread_detach(recv_thread);
// frame
Frame frame;
volatile int track_frame = 1;
while(!exit_flag) {
if (!frame_map.empty()) {
tbb::concurrent_hash_map<int, Frame>::accessor c_a;
if (frame_map.find(c_a, (const int)track_frame))
{
frame = (Frame)c_a->second;
while(1) {
if (frame_map.erase(c_a))
break;
}
processed_frame_queue.push_back(frame);
track_frame++;
}
}
}
delete frame_pool;
zmq_close(sock_pull);
zmq_close(sock_pub);
zmq_ctx_destroy(context);
return 0;
}
| 21.612676 | 77 | 0.641251 | imsoo |
0c4b1659eb975da0e7c9e93a05b75480a5b514a8 | 8,861 | cpp | C++ | unit/json/json_parser.cpp | MatWise/cbmc | c9284aee34bae53ba2b3dce8810720735e0a94fa | [
"BSD-4-Clause"
] | null | null | null | unit/json/json_parser.cpp | MatWise/cbmc | c9284aee34bae53ba2b3dce8810720735e0a94fa | [
"BSD-4-Clause"
] | null | null | null | unit/json/json_parser.cpp | MatWise/cbmc | c9284aee34bae53ba2b3dce8810720735e0a94fa | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Example Catch Tests
Author: Diffblue Ltd.
\*******************************************************************/
#include <fstream>
#include <json/json_parser.h>
#include <testing-utils/message.h>
#include <testing-utils/use_catch.h>
#include <util/tempfile.h>
SCENARIO("Loading JSON files")
{
GIVEN("A invalid JSON file and a valid JSON file")
{
temporary_filet valid_json_file("cbmc_unit_json_parser_valid", ".json");
temporary_filet invalid_json_file("cbmc_unit_json_parser_invalid", ".json");
const std::string valid_json_path = valid_json_file();
const std::string invalid_json_path = invalid_json_file();
{
std::ofstream valid_json_out(valid_json_path);
valid_json_out << "{\n"
<< " \"hello\": \"world\"\n"
<< "}\n";
}
{
std::ofstream invalid_json_out(invalid_json_path);
invalid_json_out << "foo\n";
}
WHEN("Loading the invalid JSON file")
{
jsont invalid_json;
const auto invalid_parse_error =
parse_json(invalid_json_path, null_message_handler, invalid_json);
THEN("An error state should be returned")
{
REQUIRE(invalid_parse_error);
REQUIRE(invalid_json.is_null());
AND_WHEN("Loading the valid JSON file")
{
jsont valid_json;
const auto valid_parse_error =
parse_json(valid_json_path, null_message_handler, valid_json);
THEN("The JSON file should be parsed correctly")
{
REQUIRE_FALSE(valid_parse_error);
REQUIRE(valid_json.is_object());
const json_objectt &json_object = to_json_object(valid_json);
REQUIRE(json_object.find("hello") != json_object.end());
REQUIRE(json_object["hello"].value == "world");
}
}
}
}
WHEN("Loading the valid JSON file")
{
jsont valid_json;
const auto valid_parse_error =
parse_json(valid_json_path, null_message_handler, valid_json);
THEN("The JSON file should be parsed correctly")
{
REQUIRE_FALSE(valid_parse_error);
REQUIRE(valid_json.is_object());
const json_objectt &json_object = to_json_object(valid_json);
REQUIRE(json_object.find("hello") != json_object.end());
REQUIRE(json_object["hello"].value == "world");
AND_WHEN("Loading the invalid JSON file")
{
jsont invalid_json;
const auto invalid_parse_error =
parse_json(invalid_json_path, null_message_handler, invalid_json);
THEN("An error state should be returned")
{
REQUIRE(invalid_parse_error);
REQUIRE(invalid_json.is_null());
}
}
}
}
}
GIVEN("A JSON file containing hexadecimal Unicode symbols")
{
temporary_filet unicode_json_file("cbmc_unit_json_parser_unicode", ".json");
const std::string unicode_json_path = unicode_json_file();
{
std::ofstream unicode_json_out(unicode_json_path);
unicode_json_out << "{\n"
<< " \"one\": \"\\u0001\",\n"
<< " \"latin\": \"\\u0042\",\n"
<< " \"grave\": \"\\u00E0\",\n"
<< " \"trema\": \"\\u00FF\",\n"
<< " \"high\": \"\\uFFFF\",\n"
<< " \"several\": \"a\\u0041b\\u2FC3\\uFFFF\"\n"
<< "}\n";
}
WHEN("Loading the JSON file with the Unicode symbols")
{
jsont unicode_json;
const auto unicode_parse_error =
parse_json(unicode_json_path, null_message_handler, unicode_json);
THEN("The JSON file should be parsed correctly")
{
REQUIRE_FALSE(unicode_parse_error);
REQUIRE(unicode_json.is_object());
const json_objectt &json_object = to_json_object(unicode_json);
REQUIRE(json_object.find("one") != json_object.end());
REQUIRE(json_object["one"].value.size() == 1);
REQUIRE(json_object["one"].value == u8"\u0001");
REQUIRE(json_object.find("latin") != json_object.end());
REQUIRE(json_object["latin"].value == "B");
REQUIRE(json_object.find("grave") != json_object.end());
REQUIRE(json_object["grave"].value == "à");
REQUIRE(json_object.find("trema") != json_object.end());
REQUIRE(json_object["trema"].value == "ÿ");
REQUIRE(json_object.find("high") != json_object.end());
REQUIRE(json_object["high"].value == u8"\uFFFF");
REQUIRE(json_object.find("several") != json_object.end());
REQUIRE(json_object["several"].value == u8"aAb\u2FC3\uFFFF");
}
}
}
}
TEST_CASE("json equality", "[core][util][json]")
{
SECTION("null")
{
REQUIRE(jsont::null_json_object == jsont::null_json_object);
}
SECTION("boolean")
{
REQUIRE(jsont::json_boolean(false) == jsont::json_boolean(false));
REQUIRE(jsont::json_boolean(true) == jsont::json_boolean(true));
REQUIRE_FALSE(jsont::json_boolean(true) == jsont::json_boolean(false));
REQUIRE_FALSE(jsont::json_boolean(false) == jsont::null_json_object);
}
SECTION("number")
{
REQUIRE(json_numbert("0") == json_numbert("0"));
REQUIRE(json_numbert("1") == json_numbert("1"));
REQUIRE(json_numbert("-1") == json_numbert("-1"));
REQUIRE(json_numbert("1.578") == json_numbert("1.578"));
REQUIRE_FALSE(json_numbert("0") == json_numbert("1"));
REQUIRE_FALSE(json_numbert("1") == json_numbert("-1"));
REQUIRE_FALSE(json_numbert("-1") == json_numbert("1"));
REQUIRE_FALSE(json_numbert("1.578") == json_numbert("1.5789"));
REQUIRE_FALSE(json_numbert("0") == jsont::json_boolean(false));
REQUIRE_FALSE(jsont::json_boolean(false) == json_numbert("0"));
REQUIRE_FALSE(json_numbert("0") == jsont::null_json_object);
REQUIRE_FALSE(jsont::null_json_object == json_numbert("0"));
}
SECTION("string")
{
REQUIRE(json_stringt("") == json_stringt(""));
REQUIRE(json_stringt("foo") == json_stringt("foo"));
REQUIRE(json_stringt("bar") == json_stringt("bar"));
REQUIRE_FALSE(json_stringt("foo") == json_stringt("bar"));
REQUIRE_FALSE(json_stringt("bar") == json_stringt("baz"));
REQUIRE_FALSE(json_stringt("foo") == json_stringt("food"));
REQUIRE_FALSE(json_stringt("1") == json_numbert("1"));
REQUIRE_FALSE(json_stringt("true") == jsont::json_boolean("true"));
REQUIRE_FALSE(json_stringt("") == jsont::json_boolean("false"));
REQUIRE_FALSE(json_stringt("") == jsont::null_json_object);
}
SECTION("array")
{
REQUIRE(json_arrayt{} == json_arrayt{});
REQUIRE(
json_arrayt{jsont::null_json_object} ==
json_arrayt{jsont::null_json_object});
REQUIRE(
json_arrayt{json_numbert{"9"}, json_numbert{"6"}} ==
json_arrayt{json_numbert{"9"}, json_numbert{"6"}});
REQUIRE(
json_arrayt{
json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}} ==
json_arrayt{
json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}});
// different lengths
REQUIRE_FALSE(
json_arrayt{json_stringt{"foo"}, json_stringt{"bar"}} ==
json_arrayt{
json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}});
// different elements
REQUIRE_FALSE(
json_arrayt{
json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"foo"}} ==
json_arrayt{
json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}});
// different kind
REQUIRE_FALSE(json_arrayt{} == jsont::json_boolean(false));
REQUIRE_FALSE(json_arrayt{} == jsont::null_json_object);
}
SECTION("object")
{
REQUIRE(json_objectt{} == json_objectt{});
REQUIRE(
json_objectt{{"key", json_stringt{"value"}}} ==
json_objectt{{"key", json_stringt{"value"}}});
REQUIRE(
json_objectt{{"key1", json_stringt{"value1"}},
{"key2", json_stringt{"value2"}}} ==
json_objectt{{"key1", json_stringt{"value1"}},
{"key2", json_stringt{"value2"}}});
// Extra property
REQUIRE_FALSE(
json_objectt{{"key1", json_stringt{"value1"}},
{"key2", json_stringt{"value2"}},
{"key3", json_stringt{"value3"}}} ==
json_objectt{{"key1", json_stringt{"value1"}},
{"key2", json_stringt{"value2"}}});
// different field values
REQUIRE_FALSE(
json_objectt{{"key1", json_stringt{"foo"}},
{"key2", json_stringt{"bar"}}} ==
json_objectt{{"key1", json_stringt{"foo"}},
{"key2", json_stringt{"baz"}}});
// different kind
REQUIRE_FALSE(json_objectt{} == json_arrayt{});
REQUIRE_FALSE(json_objectt{} == jsont::null_json_object);
}
}
| 36.465021 | 80 | 0.601061 | MatWise |
0c4c295db47b3a08553e5a74646d2fbd50939d6f | 1,823 | cpp | C++ | CodeForces/educationalNuevo/e.cpp | CaDe27/Co-digos | 9eea1dbf6ed06fd115391328c0a2481029c83fc0 | [
"MIT"
] | null | null | null | CodeForces/educationalNuevo/e.cpp | CaDe27/Co-digos | 9eea1dbf6ed06fd115391328c0a2481029c83fc0 | [
"MIT"
] | null | null | null | CodeForces/educationalNuevo/e.cpp | CaDe27/Co-digos | 9eea1dbf6ed06fd115391328c0a2481029c83fc0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <math.h>
#include <numeric>
#include <queue>
#include <stack>
#include <utility>
#include <queue>
#include <set>
#include <iomanip>
using namespace std;
typedef int64_t ll;
typedef pair<int,ll> pill;
typedef pair<int,int> pii;
#define INF 1000000000000
#define MOD 998244353
#define loop(i,a,b) for(int i = a; i < b; ++i)
const int maxN = 18, maxNodos = (1<<18)-1;
int n, cantNodos;
string s;
string claseEquivalencia[maxNodos+5];
void calculaEquiv(int id){
if(id<<1 < cantNodos){
calculaEquiv(id<<1);
calculaEquiv( (id<<1) +1);
if(claseEquivalencia[id<<1] < claseEquivalencia[ (id<<1)+1])
claseEquivalencia[id] = s[id-1] + claseEquivalencia[id<<1] + claseEquivalencia[(id<<1)+1];
else
claseEquivalencia[id] = s[id-1] + claseEquivalencia[(id<<1)+1] + claseEquivalencia[id<<1];
}
else{
claseEquivalencia[id] = s[id-1];
}
}
ll dp[maxNodos+5];
void calculaDP(int id){
if( (id<<1) > cantNodos){
dp[id] = 1;
}
else{
calculaDP(id<<1);
calculaDP((id<<1) + 1);
if(claseEquivalencia[id<<1] == claseEquivalencia[(id<<1)+1])
dp[id] = (dp[id<<1]*dp[id<<1])%MOD;
else{
dp[id] = (dp[id<<1]*dp[(id<<1)+1])%MOD;
dp[id] = (2*dp[id])%MOD;
}
}
}
void solve(){
cin>>n>>s;
cantNodos = (1<<n)-1;
//calcula claseEquivalencia
calculaEquiv(1);
//calculaDP
calculaDP(1);
cout<<dp[1]<<"\n";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
//if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin);
int t = 1;
//int t; cin>>t;
loop(i, 0, t){
solve();
}
return 0;
}
| 21.963855 | 102 | 0.565551 | CaDe27 |
31b163ac7a95fe85444d6aefe014324f4638cd2f | 1,399 | cpp | C++ | C++/661. Image Smoother.cpp | WangYang-wy/LeetCode | c92fcb83f86c277de6785d5a950f16bc007ccd31 | [
"MIT"
] | 3 | 2018-07-28T15:36:18.000Z | 2020-03-17T01:26:22.000Z | C++/661. Image Smoother.cpp | WangYang-wy/LeetCode | c92fcb83f86c277de6785d5a950f16bc007ccd31 | [
"MIT"
] | null | null | null | C++/661. Image Smoother.cpp | WangYang-wy/LeetCode | c92fcb83f86c277de6785d5a950f16bc007ccd31 | [
"MIT"
] | null | null | null | //
// Created by 王阳 on 2018/4/18.
//
#include "header.h"
class Solution {
public:
vector<vector<int>> imageSmoother(vector<vector<int>> &M) {
vector<vector<int>> res;
int m = M.size();
int n = M[0].size();
for (int i = 0; i < m; i++) {
vector<int> tmp;
for (int j = 0; j < n; j++) {
tmp.push_back(0);
}
res.push_back(tmp);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int sum = 0;
int count = 0;
for (int p = max(0, i - 1); p < min(m, i + 2); p++) {
for (int q = max(0, j - 1); q < min(n, j + 2); q++) {
sum += M[p][q];
count++;
}
}
res[i][j] = floor(sum / count);
}
}
return res;
}
int max(int a, int b) {
return a > b ? a : b;
}
int min(int a, int b) {
return a < b ? a : b;
}
};
int main() {
Solution *solution = new Solution();
vector<vector<int>> res;
int m = 3;
int n = 3;
for (int i = 0; i < m; i++) {
vector<int> tmp;
for (int j = 0; j < n; j++) {
tmp.push_back(1);
}
res.push_back(tmp);
}
solution->imageSmoother(res);
return 0;
} | 22.934426 | 73 | 0.36955 | WangYang-wy |
31bcb2eb78b049353ab9b85429def598bdbe0e10 | 352 | cpp | C++ | Vision/ObjectRecognition/src/object.cpp | cxdcxd/sepanta3 | a65a3415f046631ac4d6b91f9342966b0c030226 | [
"MIT"
] | null | null | null | Vision/ObjectRecognition/src/object.cpp | cxdcxd/sepanta3 | a65a3415f046631ac4d6b91f9342966b0c030226 | [
"MIT"
] | null | null | null | Vision/ObjectRecognition/src/object.cpp | cxdcxd/sepanta3 | a65a3415f046631ac4d6b91f9342966b0c030226 | [
"MIT"
] | null | null | null |
#include <object.hpp>
Object::Object() : cloud(new pcl::PointCloud<pcl::PointXYZRGB>),
normals(new pcl::PointCloud<pcl::PointNormal>),
keypoints(new pcl::PointCloud<pcl::PointXYZRGB>),
descriptors(new pcl::PointCloud<pcl::SHOT1344>),
correspondences(new pcl::Correspondences()) {
}
| 35.2 | 66 | 0.605114 | cxdcxd |
31c0fb6840bfefa8006d3111b7c03a7d4f8f7b21 | 161 | hpp | C++ | src/shared/IServerConnection.hpp | sathwikmatsa/ndn-agar.io | a758414d0bb221a6183f20d332f101f3850505cf | [
"MIT"
] | 1 | 2020-06-10T07:44:43.000Z | 2020-06-10T07:44:43.000Z | src/shared/IServerConnection.hpp | sathwikmatsa/ndn-agar.io | a758414d0bb221a6183f20d332f101f3850505cf | [
"MIT"
] | null | null | null | src/shared/IServerConnection.hpp | sathwikmatsa/ndn-agar.io | a758414d0bb221a6183f20d332f101f3850505cf | [
"MIT"
] | null | null | null | #pragma once
class IServerConnection {
public:
virtual void client_connected(int clientIndex) = 0;
virtual void client_disconnected(int clientIndex) = 0;
};
| 23 | 56 | 0.776398 | sathwikmatsa |
31c73bcca22ef514ea7e8bf12579bd8e3891e4ae | 78 | hh | C++ | Include/AcpiCa.hh | ahoka/esrtk | bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc | [
"BSD-2-Clause"
] | 1 | 2018-07-08T15:47:57.000Z | 2018-07-08T15:47:57.000Z | Include/AcpiCa.hh | ahoka/esrtk | bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc | [
"BSD-2-Clause"
] | null | null | null | Include/AcpiCa.hh | ahoka/esrtk | bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc | [
"BSD-2-Clause"
] | null | null | null | #ifndef ACPICA_HH
#define ACPICA_HH
extern "C"
{
#include <acpi.h>
}
#endif
| 7.8 | 17 | 0.692308 | ahoka |
31cdacc3946022055e7d346eb258829294954eb3 | 1,519 | cpp | C++ | code/History.cpp | omerdagan84/neomem | 7d2f782bb37f1ab0ac6580d00672e114605afab7 | [
"MIT"
] | 1 | 2022-02-10T01:41:32.000Z | 2022-02-10T01:41:32.000Z | code/History.cpp | omerdagan84/neomem | 7d2f782bb37f1ab0ac6580d00672e114605afab7 | [
"MIT"
] | null | null | null | code/History.cpp | omerdagan84/neomem | 7d2f782bb37f1ab0ac6580d00672e114605afab7 | [
"MIT"
] | null | null | null |
// CHistory
#include "precompiled.h"
#include "NeoMem.h"
#include "History.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
CHistory::CHistory() :
m_nStart (0),
m_nStop (-1),
m_nPos (-1),
m_nPositions (0)
{
}
CHistory::~CHistory()
{
}
BOOL CHistory::SetSize(int nPositions)
{
m_nPositions = nPositions;
CObArray::SetSize(nPositions);
return TRUE;
}
BOOL CHistory::IsForwardValid()
{
return (GetForwardPositions() > 0);
}
BOOL CHistory::IsBackValid()
{
return (GetBackPositions() > 0);
}
// Set current position to the specified object
BOOL CHistory::SetCurrent(CObject* pobj)
{
m_nPos++;
SetAt(m_nPos % m_nPositions, pobj);
m_nStop = m_nPos; // save stop position (max forward)
// Move start position up if we're exceeding the number of positions in array
if (m_nPos - m_nStart >= m_nPositions)
m_nStart++;
return TRUE;
}
// How many back positions are available?
int CHistory::GetBackPositions()
{
return (m_nPos - m_nStart);
}
// How many forward positions are available?
int CHistory::GetForwardPositions()
{
return (m_nStop - m_nPos);
}
// Get previous object in history list
CObject* CHistory::GoBack()
{
CObject* pobj = 0;
if (GetBackPositions() > 0)
{
m_nPos--;
pobj = GetAt(m_nPos % m_nPositions);
}
return pobj;
}
// Get next object in history list
CObject* CHistory::GoForward()
{
CObject* pobj = 0;
if (GetForwardPositions() > 0)
{
m_nPos++;
pobj = GetAt(m_nPos % m_nPositions);
}
return pobj;
}
| 14.747573 | 78 | 0.692561 | omerdagan84 |
31ce7147b5c6cd02338b6d7d205fc1da6b21cc88 | 1,126 | cpp | C++ | libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file unit_test_fnd_config_noexcept.cpp
*
* @brief
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#include <gtest/gtest.h>
namespace bksge_config_noexcept_test
{
void f1();
void f2() BKSGE_NOEXCEPT;
void f3() BKSGE_NOEXCEPT_OR_NOTHROW;
void f4() BKSGE_NOEXCEPT_IF(true);
void f5() BKSGE_NOEXCEPT_IF(false);
void f6() BKSGE_NOEXCEPT_IF(BKSGE_NOEXCEPT_EXPR(f1()));
void f7() BKSGE_NOEXCEPT_IF(BKSGE_NOEXCEPT_EXPR(f2()));
void f8() BKSGE_NOEXCEPT_IF_EXPR(f1());
void f9() BKSGE_NOEXCEPT_IF_EXPR(f2());
GTEST_TEST(ConfigTest, NoexceptTest)
{
#if defined(BKSGE_HAS_CXX11_NOEXCEPT)
static_assert(!BKSGE_NOEXCEPT_EXPR(f1()), "");
static_assert( BKSGE_NOEXCEPT_EXPR(f2()), "");
static_assert( BKSGE_NOEXCEPT_EXPR(f3()), "");
static_assert( BKSGE_NOEXCEPT_EXPR(f4()), "");
static_assert(!BKSGE_NOEXCEPT_EXPR(f5()), "");
static_assert(!BKSGE_NOEXCEPT_EXPR(f6()), "");
static_assert( BKSGE_NOEXCEPT_EXPR(f7()), "");
static_assert(!BKSGE_NOEXCEPT_EXPR(f8()), "");
static_assert( BKSGE_NOEXCEPT_EXPR(f9()), "");
#endif
}
} // namespace bksge_config_noexcept_test
| 27.463415 | 56 | 0.713144 | myoukaku |
31d39f996c423a51578a99c36ebc1de204caee0c | 11,354 | cpp | C++ | src/OpenCV/library.cpp | TORU777/OpenR8 | be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0 | [
"Unlicense"
] | null | null | null | src/OpenCV/library.cpp | TORU777/OpenR8 | be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0 | [
"Unlicense"
] | null | null | null | src/OpenCV/library.cpp | TORU777/OpenR8 | be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0 | [
"Unlicense"
] | 3 | 2019-03-30T01:45:28.000Z | 2021-04-24T04:37:39.000Z | /*
Copyright (c) 2004-2017 Open Robot Club. All rights reserved.
OpenCV library for R7.
*/
#include <opencv2/opencv.hpp>
#include "R7.hpp"
using namespace std;
using namespace cv;
typedef struct {
VideoCapture *videoCapture;
int deviceNum;
int apiID;
Mat capturedImage;
} OpenCV_t;
vector<VideoCapture *> videoCapture_Vector;
#ifdef __cplusplus
extern "C"
{
#endif
static int OpenCV_VideoCapture_Init(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_InitVariableObject(r7Sn, functionSn, 1, sizeof(OpenCV_t));
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_InitVariableObject = %d", res);
return -1;
}
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
// Initial values of OpenCV_t.
videoCapturePtr->videoCapture = new VideoCapture();
videoCapturePtr->deviceNum = 0;
videoCapturePtr->apiID = CAP_ANY;
videoCapturePtr->capturedImage = Mat();
videoCapture_Vector.push_back(videoCapturePtr->videoCapture);
return 1;
}
static int OpenCV_VideoCapture_Release(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -1;
}
if (variableObject == NULL) {
R7_Printf(r7Sn, "ERROR! variableObject == NULL");
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
videoCapturePtr->capturedImage.release();
videoCapturePtr->videoCapture->~VideoCapture();
videoCapturePtr->videoCapture = NULL;
res = R7_ReleaseVariableObject(r7Sn, functionSn, 1);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_ReleaseVariableObject = %d", res);
return -3;
}
return 1;
}
static int OpenCV_VideoCapture_Open(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -1;
}
if (variableObject == NULL) {
R7_Printf(r7Sn, "ERROR! variableObject == NULL");
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
int deviceID = 0;
res = R7_GetVariableInt(r7Sn, functionSn, 2, &deviceID);
if (res > 0) {
videoCapturePtr->deviceNum = deviceID;
}
videoCapturePtr->videoCapture->open(videoCapturePtr->deviceNum + videoCapturePtr->apiID);
if (!videoCapturePtr->videoCapture->isOpened()) {
R7_Printf(r7Sn, "ERROR! Unable to open the Camera!");
return -4;
}
// Workaround for dark image at beginning.
Mat frame;
for (int i = 0; i < 10; i++) {
videoCapturePtr->videoCapture->grab();
videoCapturePtr->videoCapture->retrieve(frame);
}
frame.release();
return 1;
}
static int OpenCV_VideoCapture_SetResolution(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -1;
}
if (variableObject == NULL) {
R7_Printf(r7Sn, "ERROR! variableObject == NULL");
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
int frameWidth = 0;
int frameHeight = 0;
res = R7_GetVariableInt(r7Sn, functionSn, 2, &frameWidth);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableInt = %d", res);
return -3;
}
res = R7_GetVariableInt(r7Sn, functionSn, 3, &frameHeight);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableInt = %d", res);
return -3;
}
//R7_Printf(r7Sn, "frameWidth = %d\n", frameWidth);
//R7_Printf(r7Sn, "frameHeight = %d\n", frameHeight);
if (frameWidth < 0)
{
R7_Printf(r7Sn, "ERROR! frameWidth must be a positive value.\n");
return -3;
}
else if (frameHeight < 0)
{
R7_Printf(r7Sn, "ERROR! frameHeight must be a positive value.\n");
return -3;
}
// Set resolution of frame
videoCapturePtr->videoCapture->set(cv::CAP_PROP_FRAME_WIDTH, frameWidth);
videoCapturePtr->videoCapture->set(cv::CAP_PROP_FRAME_HEIGHT, frameHeight);
return 1;
}
static int OpenCV_VideoCapture_Grab(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -1;
}
if (variableObject == NULL) {
R7_Printf(r7Sn, "ERROR! variableObject == NULL");
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
videoCapturePtr->videoCapture->grab();
return 1;
}
static int OpenCV_VideoCapture_Retrieve(int r7Sn, int functionSn) {
int res;
void *variableObject = NULL;
res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res);
return -1;
}
if (variableObject == NULL) {
R7_Printf(r7Sn, "ERROR! variableObject == NULL");
return -2;
}
OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject);
videoCapturePtr->videoCapture->retrieve(videoCapturePtr->capturedImage);
if (videoCapturePtr->capturedImage.empty()) {
R7_Printf(r7Sn, "ERROR! Retrieved image is empty!");
return -3;
}
res = R7_SetVariableMat(r7Sn, functionSn, 2, videoCapturePtr->capturedImage);
if (res <= 0) {
R7_Printf(r7Sn, "ERROR! R7_SetVariableMat = %d", res);
return -4;
}
return 1;
}
R7_API int R7Library_Init(void) {
// Register your functions in this API.
R7_RegisterFunction("OpenCV_VideoCapture_Grab", (R7Function_t)&OpenCV_VideoCapture_Grab);
R7_RegisterFunction("OpenCV_VideoCapture_Init", (R7Function_t)&OpenCV_VideoCapture_Init);
R7_RegisterFunction("OpenCV_VideoCapture_Open", (R7Function_t)&OpenCV_VideoCapture_Open);
R7_RegisterFunction("OpenCV_VideoCapture_SetResolution", (R7Function_t)&OpenCV_VideoCapture_SetResolution);
R7_RegisterFunction("OpenCV_VideoCapture_Release", (R7Function_t)&OpenCV_VideoCapture_Release);
R7_RegisterFunction("OpenCV_VideoCapture_Retrieve", (R7Function_t)&OpenCV_VideoCapture_Retrieve);
return 1;
}
R7_API int R7Library_Close(void) {
// If you have something to do before close R7(ex: free memory), you should handle them in this API.
for (int i = 0; i < (int)videoCapture_Vector.size(); i++) {
if (videoCapture_Vector[i] != NULL) {
videoCapture_Vector[i]->~VideoCapture();
videoCapture_Vector[i] = NULL;
}
}
videoCapture_Vector.clear();
return 1;
}
inline void r7_AppendVariable(json_t *variableArray, const char *name, const char *type, const char *option) {
if (!variableArray) {
return;
}
json_t *variable;
json_t *variableObject;
variableObject = json_object();
variable = json_object();
json_object_set_new(variable, "variable", variableObject);
json_object_set_new(variableObject, "name", json_string(name));
json_object_set_new(variableObject, "type", json_string(type));
json_object_set_new(variableObject, "option", json_string(option));
json_array_append(variableArray, variable);
return;
}
R7_API int R7Library_GetSupportList(char *str, int strSize) {
// Define your functions and parameters in this API.
json_t *root = json_object();
json_t *functionGroupArray;
json_t *functionGroup;
json_t *functionGroupObject;
json_t *functionArray;
json_t *function;
json_t *functionObject;
json_t *variableArray;
functionGroupArray = json_array();
json_object_set_new(root, "functionGroups", functionGroupArray);
functionGroup = json_object();
functionGroupObject = json_object();
json_object_set_new(functionGroup, "functionGroup", functionGroupObject);
json_object_set_new(functionGroupObject, "name", json_string("OpenCV"));
json_array_append(functionGroupArray, functionGroup);
functionArray = json_array();
json_object_set_new(functionGroupObject, "functions", functionArray);
// OpenCV_VideoCapture_Grab
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Grab"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN");
// OpenCV_VideoCapture_Init
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Init"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "INOUT");
// OpenCV_VideoCapture_Open
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Open"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN");
r7_AppendVariable(variableArray, "deviceNumber", "Int", "IN");
// OpenCV_VideoCapture_SetResolution
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_SetResolution"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN");
r7_AppendVariable(variableArray, "frameWidth", "Int", "IN");
r7_AppendVariable(variableArray, "frameHeight", "Int", "IN");
// OpenCV_VideoCapture_Release
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Release"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "INOUT");
// OpenCV_VideoCapture_Retrieve
function = json_object();
functionObject = json_object();
json_object_set_new(function, "function", functionObject);
json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Retrieve"));
json_object_set_new(functionObject, "doc", json_string(""));
json_array_append(functionArray, function);
variableArray = json_array();
json_object_set_new(functionObject, "variables", variableArray);
r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN");
r7_AppendVariable(variableArray, "grabbedImage", "Image", "OUT");
sprintf_s(str, strSize, "%s", json_dumps(root, 0));
json_decref(root);
return 1;
}
#ifdef __cplusplus
}
#endif
| 30.686486 | 110 | 0.747578 | TORU777 |
31d428bd8e8fb3e91465f8c947d6dd05ae1740f2 | 1,318 | hpp | C++ | include/bg2e/platform.hpp | ferserc1/bg2e-cpp | f3a04c5202161846b1329918c5070a2e930bec42 | [
"MIT"
] | null | null | null | include/bg2e/platform.hpp | ferserc1/bg2e-cpp | f3a04c5202161846b1329918c5070a2e930bec42 | [
"MIT"
] | null | null | null | include/bg2e/platform.hpp | ferserc1/bg2e-cpp | f3a04c5202161846b1329918c5070a2e930bec42 | [
"MIT"
] | null | null | null |
#ifndef _bg2e_platform_hpp_
#define _bg2e_platform_hpp_
#include <bx/bx.h>
#define BG2E_PLATFORM_ANDROID 0
#define BG2E_PLATFORM_BSD 0
#define BG2E_PLATFORM_EMSCRIPTEN 0
#define BG2E_PLATFORM_IOS 0
#define BG2E_PLATFORM_LINUX 0
#define BG2E_PLATFORM_OSX 0
#define BG2E_PLATFORM_RPI 0
#define BG2E_PLATFORM_STEAMLINK 0
#define BG2E_PLATFORM_WINDOWS 0
#if BX_PLATFORM_ANDROID
#undef BG2E_PLATFORM_ANDROID
#define BG2E_PLATFORM_ANDROID 1
#elif BX_PLATFORM_BSD
#undef BG2E_PLATFORM_BSD
#define BG2E_PLATFORM_BSD 1
#elif BX_PLATFORM_EMSCRIPTEN
#define BG2E_PLATFORM_EMSCRIPTEN 1
#elif BX_PLATFORM_IOS
#undef BG2E_PLATFORM_IOS
#define BG2E_PLATFORM_IOS 1
#elif BX_PLATFORM_LINUX
#undef BG2E_PLATFORM_LINUX
#define BG2E_PLATFORM_LINUX 1
#elif BX_PLATFORM_OSX
#undef BG2E_PLATFORM_OSX
#define BG2E_PLATFORM_OSX 1
#elif BX_PLATFORM_RPI
#undef BG2E_PLATFORM_RPI
#define BG2E_PLATFORM_RPI 1
#elif BX_PLATFORM_STEAMLINK
#undef BG2E_PLATFORM_STEAMLINK
#define BG2E_PLATFORM_STEAMLINK 1
#elif BX_PLATFORM_WINDOWS
#undef BG2E_PLATFORM_WINDOWS
#define BG2E_PLATFORM_WINDOWS 1
#endif
#endif
| 28.042553 | 41 | 0.708649 | ferserc1 |
31d4321544086c76173ffd7e85b0d214d666b9a1 | 4,508 | cpp | C++ | rtsp-streamer/screenshot.cpp | alexeyz041/toolbox | dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc | [
"CC0-1.0"
] | 1 | 2022-02-17T22:23:59.000Z | 2022-02-17T22:23:59.000Z | rtsp-streamer/screenshot.cpp | alexeyz041/toolbox | dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc | [
"CC0-1.0"
] | null | null | null | rtsp-streamer/screenshot.cpp | alexeyz041/toolbox | dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc | [
"CC0-1.0"
] | null | null | null |
#include "screenshot.h"
void initimage( struct shmimage * image )
{
image->ximage = NULL ;
image->shminfo.shmaddr = (char *) -1 ;
}
void destroyimage( Display * dsp, struct shmimage * image )
{
if( image->ximage )
{
XShmDetach( dsp, &image->shminfo ) ;
XDestroyImage( image->ximage ) ;
image->ximage = NULL ;
}
if( image->shminfo.shmaddr != ( char * ) -1 )
{
shmdt( image->shminfo.shmaddr ) ;
image->shminfo.shmaddr = ( char * ) -1 ;
}
}
int createimage( Display * dsp, struct shmimage * image, int width, int height )
{
// Create a shared memory area
image->shminfo.shmid = shmget( IPC_PRIVATE, width * height * BPP, IPC_CREAT | 0600 ) ;
if( image->shminfo.shmid == -1 )
{
perror( "screenshot" ) ;
return false ;
}
// Map the shared memory segment into the address space of this process
image->shminfo.shmaddr = (char *) shmat( image->shminfo.shmid, 0, 0 ) ;
if( image->shminfo.shmaddr == (char *) -1 )
{
perror( "screenshot 2" ) ;
return false ;
}
image->data = (unsigned int*) image->shminfo.shmaddr ;
image->shminfo.readOnly = false ;
// Mark the shared memory segment for removal
// It will be removed even if this program crashes
shmctl( image->shminfo.shmid, IPC_RMID, 0 ) ;
// Allocate the memory needed for the XImage structure
image->ximage = XShmCreateImage( dsp, XDefaultVisual( dsp, XDefaultScreen( dsp ) ),
DefaultDepth( dsp, XDefaultScreen( dsp ) ), ZPixmap, 0,
&image->shminfo, 0, 0 ) ;
if( !image->ximage )
{
destroyimage( dsp, image ) ;
printf("could not allocate the XImage structure\n" ) ;
return false ;
}
image->ximage->data = (char *)image->data ;
image->ximage->width = width ;
image->ximage->height = height ;
// Ask the X server to attach the shared memory segment and sync
XShmAttach( dsp, &image->shminfo ) ;
XSync( dsp, false ) ;
return true ;
}
void getrootwindow( Display * dsp, struct shmimage * image )
{
XShmGetImage( dsp, XDefaultRootWindow( dsp ), image->ximage, 0, 0, AllPlanes ) ;
// This is how you access the image's BGRA packed pixels
// Lets set the alpha channel of each pixel to 0xff
int x, y ;
unsigned int * p = image->data ;
for( y = 0 ; y < image->ximage->height; ++y )
{
for( x = 0 ; x < image->ximage->width; ++x )
{
*p++ |= 0xff000000 ;
}
}
}
/*
void initpngimage( png_image * pi, struct shmimage * image )
{
bzero( pi, sizeof( png_image ) ) ;
pi->version = PNG_IMAGE_VERSION ;
pi->width = image->ximage->width ;
pi->height = image->ximage->height ;
pi->format = PNG_FORMAT_BGRA ;
}
int savepng( struct shmimage * image, char * path )
{
FILE * f = fopen( path, "w" ) ;
if( !f )
{
perror( "screenshot" ) ;
return false ;
}
png_image pi ;
initpngimage( &pi, image ) ;
unsigned int scanline = pi.width * BPP ;
if( !png_image_write_to_stdio( &pi, f, 0, image->data, scanline, NULL) )
{
fclose( f ) ;
printf( "could not save the png image\n" ) ;
return false ;
}
fclose( f ) ;
return true ;
}
*/
int ScreenShot::init()
{
dsp = XOpenDisplay( NULL ) ;
if( !dsp )
{
printf("could not open a connection to the X server\n" ) ;
return -1;
}
if( !XShmQueryExtension( dsp ) )
{
XCloseDisplay( dsp ) ;
printf("the X server does not support the XSHM extension\n" ) ;
return -1 ;
}
int screen = XDefaultScreen( dsp ) ;
initimage( &image ) ;
if( !createimage( dsp, &image, XDisplayWidth( dsp, screen ), XDisplayHeight( dsp, screen ) ) )
{
XCloseDisplay( dsp ) ;
return -1;
}
return 0;
}
void ScreenShot::get(int *width,int *height,uint32_t **buf)
{
getrootwindow(dsp, &image );
*width = image.ximage->width;
*height = image.ximage->height;
*buf = image.data;
// printf("%d x %d\n", image.ximage->width,image.ximage->height);
}
void ScreenShot::release()
{
destroyimage( dsp, &image ) ;
XCloseDisplay( dsp ) ;
}
//=============================================================================
ScreenShot::ScreenShot()
{
if(init() != 0) {
fprintf(stderr,"screenshot init failed\n");
exit(1);
}
}
ScreenShot::~ScreenShot()
{
release();
}
| 23.726316 | 98 | 0.564996 | alexeyz041 |
31d666cde3c384ff29df1851cbfb700f4b047df1 | 9,862 | hpp | C++ | Data/UnevenBlock.hpp | AnabelSMRuggiero/ann | edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45 | [
"Apache-2.0"
] | null | null | null | Data/UnevenBlock.hpp | AnabelSMRuggiero/ann | edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45 | [
"Apache-2.0"
] | null | null | null | Data/UnevenBlock.hpp | AnabelSMRuggiero/ann | edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45 | [
"Apache-2.0"
] | null | null | null | /*
NNDescent.cpp: Copyright (c) Anabel Ruggiero
At the time of writting, this code is unreleased and not published under a license.
As a result, I currently retain all legal rights I am legally entitled to.
I am currently considering a permissive license for releasing this code, such as the Apache 2.0 w/LLVM exception.
Please refer to the project repo for any updates regarding liscensing.
https://github.com/AnabelSMRuggiero/NNDescent.cpp
*/
#ifndef NND_UNEVENBLOCK_HPP
#define NND_UNEVENBLOCK_HPP
#include <cstddef>
#include <memory_resource>
#include <type_traits>
#include <new>
#include "../Type.hpp"
#include "../DataSerialization.hpp"
#include "../DataDeserialization.hpp"
#include "../AlignedMemory/DynamicArray.hpp"
namespace nnd{
template<typename ElementType>
struct UnevenBlockIterator{
using value_type = std::span<ElementType>;
using difference_type = std::ptrdiff_t;
using reference = std::span<ElementType>;
using const_reference = const std::span<const ElementType>;
UnevenBlockIterator(const size_t* vertexStart, ElementType* vertexNeighbors): vertexStart(vertexStart), vertexNeighbors(vertexNeighbors) {}
private:
const size_t* vertexStart;
ElementType* vertexNeighbors;
public:
UnevenBlockIterator& operator++(){
vertexNeighbors += *(vertexStart+1) - *vertexStart;
++vertexStart;
return *this;
}
UnevenBlockIterator operator++(int){
UnevenBlockIterator copy = *this;
vertexNeighbors += *(vertexStart+1) - *vertexStart;
++vertexStart;
return copy;
}
UnevenBlockIterator& operator--(){
vertexNeighbors -= *vertexStart - *(vertexStart-1);
--vertexStart;
return *this;
}
UnevenBlockIterator operator--(int){
UnevenBlockIterator copy = *this;
vertexNeighbors -= *vertexStart - *(vertexStart-1);
--vertexStart;
return copy;
}
UnevenBlockIterator operator+(std::ptrdiff_t inc) const {
UnevenBlockIterator copy{vertexStart+inc, vertexNeighbors + (*(vertexStart+inc) - *vertexStart)};
return copy;
}
UnevenBlockIterator operator-(std::ptrdiff_t inc) const {
UnevenBlockIterator copy{vertexStart-inc, vertexNeighbors - (*vertexStart - *(vertexStart-inc))};
return copy;
}
std::ptrdiff_t operator-(UnevenBlockIterator other) const {
return vertexStart - other.vertexStart;
}
bool operator==(UnevenBlockIterator other) const {
return vertexStart == other.vertexStart;
}
reference operator*(){
return reference{vertexNeighbors, *(vertexStart+1) - *vertexStart};
}
const_reference operator*()const{
return reference{vertexNeighbors, *(vertexStart+1) - *vertexStart};
}
reference operator[](size_t i) {
return *(*this + i);
}
const_reference operator[](size_t i)const {
return *(*this + i);
}
UnevenBlockIterator& operator+=(std::ptrdiff_t inc){
*this = *this + inc;
return *this;
}
UnevenBlockIterator& operator-=(std::ptrdiff_t inc){
*this = *this - inc;
return *this;
}
auto operator<=>(UnevenBlockIterator& rhs) const {
return vertexStart<=> rhs.vertexStart;
}
};
template<typename ElementType>
requires std::is_trivially_constructible_v<ElementType> && std::is_trivially_destructible_v<ElementType>
struct UnevenBlock{
using iterator = UnevenBlockIterator<ElementType>;
using const_iterator = UnevenBlockIterator<const ElementType>;
using reference = std::span<ElementType>;
using const_reference = std::span<const ElementType>;
ann::aligned_array<std::byte, static_cast<std::align_val_t>(std::max(alignof(size_t), alignof(ElementType)))> dataStorage;
size_t numArrays;
ElementType* firstIndex;
template<std::endian dataEndianess = std::endian::native>
static UnevenBlock deserialize(std::ifstream& inFile){
static_assert(dataEndianess == std::endian::native, "reverseEndianess not implemented yet for this class");
struct DeserializationArgs{
size_t numBytes;
size_t numArrays;
std::ptrdiff_t indexOffset;
};
DeserializationArgs args = Extract<DeserializationArgs>(inFile);
UnevenBlock retBlock{args.numBytes, args.numArrays, args.indexOffset};
Extract<std::byte>(inFile, retBlock.dataStorage.begin(), retBlock.dataStorage.end());
return retBlock;
}
UnevenBlock() = default;
//Default Copy Constructor is buggy
UnevenBlock(const UnevenBlock& other): dataStorage(other.dataStorage), numArrays(other.numArrays), firstIndex(nullptr){
this->firstIndex = static_cast<ElementType*>(static_cast<void*>(this->dataStorage.data()
+ other.IndexOffset()));
}
UnevenBlock& operator=(const UnevenBlock& other){
dataStorage = ann::aligned_array<std::byte, std::align_val_t{std::max(alignof(size_t), alignof(ElementType))}>(other.dataStorage.size());
numArrays = other.numArrays;
size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1];
std::ptrdiff_t indexOffset = static_cast<const std::byte*>(static_cast<const void*>(other.firstIndex)) - other.dataStorage.begin();
size_t numElements = static_cast<const ElementType*>(static_cast<const void*>(other.dataStorage.end())) - other.firstIndex;
firstIndex = new (dataStorage.begin() + indexOffset) ElementType[numElements];
std::copy(other.dataStorage.begin(), other.dataStorage.end(), dataStorage.begin());
return *this;
}
//NewUndirectedGraph(size_t numVerticies, size_t numNeighbors):
// verticies(numVerticies, std::vector<IndexType>(numNeighbors)){};
//template<typename DistType>
UnevenBlock(const size_t numBytes, const size_t numArrays, const size_t headerPadding, const size_t numIndecies): dataStorage(numBytes), numArrays(numArrays), firstIndex(nullptr){
size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1];
firstIndex = new (dataStorage.begin() + sizeof(size_t)*(numArrays+1) + headerPadding) ElementType[numIndecies];
}
UnevenBlock(const size_t numBytes, const size_t numArrays, const std::ptrdiff_t indexOffset): dataStorage(numBytes), numArrays(numArrays), firstIndex(nullptr){
size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1];
size_t numIndecies = (dataStorage.end() - (dataStorage.begin() + indexOffset))/sizeof(ElementType);
firstIndex = new (dataStorage.begin() + indexOffset) ElementType[numIndecies];
}
size_t size() const noexcept{
return numArrays;
}
constexpr iterator begin() noexcept{
return iterator{std::launder(static_cast<size_t*>(static_cast<void*>(dataStorage.begin()))), firstIndex};
}
constexpr const_iterator begin() const noexcept{
return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))), firstIndex};
}
constexpr const_iterator cbegin() const noexcept{
return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))), firstIndex};
}
constexpr iterator end() noexcept{
return iterator{std::launder(static_cast<size_t*>(static_cast<void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<ElementType*>(static_cast<void*>(dataStorage.end())))};
}
constexpr const_iterator end() const noexcept{
return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<const ElementType*>(static_cast<const void*>(dataStorage.end())))};
}
constexpr const_iterator cend() const noexcept{
return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<const ElementType*>(static_cast<const void*>(dataStorage.end())))};
}
reference operator[](size_t i){
return this->begin()[i];
}
constexpr const_reference operator[](size_t i) const{
return this->cbegin()[i];
}
std::byte* data(){
return dataStorage.data();
}
std::ptrdiff_t IndexOffset() const{
return static_cast<std::byte*>(static_cast<void*>(firstIndex)) - dataStorage.data();
}
};
template<typename ElementType>
requires std::is_trivially_constructible_v<ElementType> && std::is_trivially_destructible_v<ElementType>
UnevenBlock<ElementType> UninitUnevenBlock(const size_t numArrays, const size_t numElements){
size_t numberOfBytes = 0;
size_t headerBytes = sizeof(size_t)*(numArrays+1);
size_t headerPadding = 0;
if constexpr(alignof(ElementType)>alignof(size_t)){
size_t headerExcess = headerBytes%alignof(ElementType);
headerPadding = (headerExcess == 0) ? 0 : alignof(ElementType) - headerBytes%alignof(ElementType);
numberOfBytes = headerBytes + headerPadding + sizeof(ElementType)*numElements;
} else {
numberOfBytes = headerBytes + sizeof(ElementType)*numElements;
}
return UnevenBlock<ElementType>(numberOfBytes, numArrays, headerPadding, numElements);
}
template<typename BlockDataType>
void Serialize(const UnevenBlock<BlockDataType>& block, std::ofstream& outputFile){
auto outputFunc = BindSerializer(outputFile);
outputFunc(block.dataStorage.size());
outputFunc(block.size());
outputFunc(block.IndexOffset());
//this is already the size in bytes
outputFile.write(reinterpret_cast<const char*>(block.dataStorage.data()), block.dataStorage.size());
}
}
#endif | 36.257353 | 221 | 0.692253 | AnabelSMRuggiero |
31d933ab08d787839c96b18d68f21d42c08e803d | 36,240 | cpp | C++ | STF/Source/Types/STFString.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | STF/Source/Types/STFString.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | STF/Source/Types/STFString.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | ///
/// @brief Foundation classes for string handling
///
#include "STF/Interface/Types/STFString.h"
#include "STF/Interface/STFMemoryManagement.h"
#include "STF/Interface/STFCallingConventions.h"
#include "STF/Interface/STFDataManipulationMacros.h"
#include "STF/Interface/STFDebug.h"
#include <stdio.h>
#include <stdarg.h>
////////////////////////////////////////////////////////////////////
//
// Kernel String Buffer Class Declaration
//
////////////////////////////////////////////////////////////////////
class STFStringBuffer
{
protected:
char * GetNewBuffer(uint32 size);
public:
int32 useCnt;
int32 length;
char * buffer;
STFStringBuffer(const char * str);
STFStringBuffer(const char ch);
STFStringBuffer(STFStringBuffer * u, STFStringBuffer * v);
STFStringBuffer(STFStringBuffer * u, int32 start, int32 num);
STFStringBuffer(STFStringBuffer * u, int32 num);
STFStringBuffer(bool sign, uint32 value, int32 digits, int32 base, char fill);
~STFStringBuffer(void);
int32 Compare(STFStringBuffer * u);
void Obtain(void) { useCnt++; }
void Release(void) { if (!--useCnt) delete this; }
};
////////////////////////////////////////////////////////////////////
//
// Kernel String Buffer Class Implementation
//
////////////////////////////////////////////////////////////////////
//
// OS Specific Memory Allocator
//
inline char * STFStringBuffer::GetNewBuffer(uint32 size)
{
return new (PagedPool) char[size];
}
//
// Constructor (by character string)
//
STFStringBuffer::STFStringBuffer(const char * str)
{
const char * p;
char * q;
//lint --e{613}
ASSERT(str);
useCnt = 1;
length = 0;
p = str;
while ((*p++) != 0) length++;
buffer = GetNewBuffer(length + 2);
p = str;
q = buffer;
while ((*q++ = *p++) != 0) ;
}
//
// Constructor (by character)
//
STFStringBuffer::STFStringBuffer(const char ch)
{
useCnt = 1;
length = 1;
buffer = GetNewBuffer(2);
buffer[0] = ch;
buffer[1] = 0;
}
//
// Constructor (by two String buffers)
//
STFStringBuffer::STFStringBuffer(STFStringBuffer * u, STFStringBuffer * v)
{
char * p, * q;
useCnt = 1;
length = u->length + v->length;
buffer = GetNewBuffer(length + 1);
p = buffer;
q = u->buffer;
while ((*p++ = *q++) != 0) ;
p--;
q = v->buffer;
while ((*p++ = *q++) != 0) ;
}
//
// Constructor (by part of other buffer)
// NOTE: start and num are specified in characters here
//
STFStringBuffer::STFStringBuffer(STFStringBuffer * u, int32 start, int32 num)
{
char * p, * q;
int32 i;
useCnt = 1;
length = u->length - start;
if (length > num) length = num;
buffer = GetNewBuffer(length + 1);
p = buffer;
q = u->buffer + start;
for(i=0; i<length; i++) *p++ = *q++;
*p = 0;
}
//
// Constructor (put u n-times into new string buffer)
//
STFStringBuffer::STFStringBuffer(STFStringBuffer * u, int32 num)
{
char * p, * q;
int32 i;
useCnt = 1;
length = u->length * num;
buffer = GetNewBuffer(length + 1);
p = buffer;
for(i=0; i<num; i++)
{
q = u->buffer;
while ((*p++ = *q++) != 0) ;
p--;
}
p++;
}
//
// Constructor (by number)
//
STFStringBuffer::STFStringBuffer(bool sign, uint32 value, int32 digits, int32 base, char fill)
{
char lbuffer[12];
int32 pos = digits;
int32 i;
useCnt = 1;
if (!pos) pos = 10;
do {
i = (int32)(value % base);
if (i < 10)
lbuffer[--pos] = '0' + i;
else
lbuffer[--pos] = 'A' + i - 10;
value /= base;
} while (value && pos);
if (digits)
{
buffer = GetNewBuffer(digits + 1);
for(i=0; i<pos; i++)
buffer[i] = fill;
if (sign)
buffer[0] = '-';
for (i=pos; i<digits; i++)
buffer[i] = lbuffer[i];
buffer[digits] = 0;
length = digits;
}
else
{
if (sign)
{
buffer = GetNewBuffer(10 - pos + 2);
buffer[0] = '-';
i = 1;
length = 10 - pos + 1;
}
else
{
buffer = GetNewBuffer(10 - pos + 1);
i = 0;
length = 10 - pos;
}
while (pos < 10)
{
buffer[i++] = lbuffer[pos++];
}
buffer[i] = 0;
}
}
//
// Destructor
//
STFStringBuffer::~STFStringBuffer(void)
{
if (buffer)
delete[] buffer;
}
//
// Compare two STFStringBuffers
//
int32 STFStringBuffer::Compare(STFStringBuffer * u)
{
char * p, * q;
char cp, cq;
p = buffer;
q = u->buffer;
do {
cp = *p++;
cq = *q++;
if (cp < cq)
return -1;
else if (cp > cq)
return 1;
} while (cp != 0);
return 0;
}
////////////////////////////////////////////////////////////////////
//
// Kernel String Class
//
////////////////////////////////////////////////////////////////////
//
// Constructor (no init)
//
STFString::STFString(void)
{
buffer = NULL;
}
//
// Constructor (by character string)
//
STFString::STFString(const char * str)
{
if (str == NULL) buffer = NULL;
else
{
buffer = new (PagedPool) STFStringBuffer(str);
}
}
//
// Constructor (by character)
//
STFString::STFString(const char ch)
{
buffer = new (PagedPool) STFStringBuffer(ch);
}
//
// Constructor (by INT)
//
STFString::STFString(int32 value, int32 digits, int32 base, char fill)
{
if (value < 0)
buffer = new (PagedPool) STFStringBuffer(true, (uint32)(-value), digits, base, fill);
else
buffer = new (PagedPool) STFStringBuffer(false, (uint32)(value), digits, base, fill);
}
//
// Constructor (by uint16)
//
STFString::STFString(uint16 value, int32 digits, int32 base, char fill)
{
buffer = new (PagedPool) STFStringBuffer(false, value, digits, base, fill);
}
//
// Constructor (by uint32)
//
STFString::STFString(uint32 value, int32 digits, int32 base, char fill)
{
buffer = new (PagedPool) STFStringBuffer(false, value, digits, base, fill);
}
//
// Copy Constructor
//
STFString::STFString(const STFString & str)
{
buffer = str.buffer;
if (buffer)
buffer->Obtain();
}
//
// Destructor
//
STFString::~STFString(void)
{
if (buffer)
buffer->Release();
}
//
// Return length (in characters)
//
int32 STFString::Length(void) const
{
if (buffer)
return buffer->length;
else
return 0;
}
//
// Convert string to long
//
int32 STFString::ToInt(uint32 base)
{
long val = 0;
bool sign;
char c, * p;
if (buffer && buffer->length)
{
p = buffer->buffer;
if (*p == '-')
{
sign = true;
p++;
}
else
sign = false;
while ((c = *p++) != 0)
{
if (c >= '0' && c <= '9') val = val * base + c - '0';
else if (c >= 'a' && c <= 'f') val = val * base + c - 'a' + 10;
else if (c >= 'A' && c <= 'F') val = val * base + c - 'A' + 10;
else return 0;
}
if (sign)
return -val;
else
return val;
}
else
return 0;
}
//
// Convert string to uint32
//
uint32 STFString::ToUnsigned(uint32 base)
{
uint32 val = 0;
char c, * p;
if (buffer && buffer->length)
{
p = buffer->buffer;
while ((c = *p++) != 0)
{
if (c>='0' && c<= '9') val = val * base + c - '0';
else if (c>='a' && c<='f') val = val * base + c - 'a' + 10;
else if (c>='A' && c<='F') val = val * base + c - 'A' + 10;
else return 0;
}
return val;
}
else
return 0;
}
//
// Copy string into character array
// Return values signals success
// len is length of char * str
bool STFString::Get(char * str, int32 len)
{
char * p, * q;
if (buffer)
{
if (len > buffer->length)
{
p = str;
q = buffer->buffer;
while ((*p++ = * q++) != 0) ;
return true;
}
else
return false;
}
else if (len > 0)
{
str[0] = 0;
return true;
}
else
return false;
}
//
// Operator = (by char string)
//
STFString & STFString::operator= (const char * str)
{
if (buffer)
buffer->Release();
buffer = new (PagedPool) STFStringBuffer(str);
return * this;
}
//
// Operator = (by STFString)
//
STFString & STFString::operator= (const STFString str)
{
if (buffer)
buffer->Release();
buffer = str.buffer;
if (buffer)
buffer->Obtain();
return * this;
}
//
// Operator + (Concatenation)
//
LIBRARYCALL STFString operator+ (const STFString u, const STFString v)
{
STFString str = u;
str += v;
return str;
}
//
// Operator += (Append)
//
STFString & STFString::operator += (const STFString u)
{
STFStringBuffer * bp;
if (buffer)
{
if (u.buffer)
{
bp = new (PagedPool) STFStringBuffer(buffer, u.buffer);
buffer->Release();
buffer = bp;
}
}
else
{
buffer = u.buffer;
if (buffer) buffer->Obtain();
}
return *this;
}
//
// Operator *
//
LIBRARYCALL STFString operator* (const STFString u, const int32 num)
{
STFString str = u;
str *= num;
return str;
}
//
// Operator *=
//
STFString & STFString::operator *= (const int32 num)
{
STFStringBuffer * bp;
if (buffer)
{
if (num)
{
bp = new (PagedPool) STFStringBuffer(buffer, num);
buffer->Release();
buffer = bp;
}
else
{
buffer->Release();
buffer = NULL;
}
}
return *this;
}
//
// Compare two STFStrings
//
int32 STFString::Compare(const STFString str)
{
if (buffer == str.buffer)
return 0;
else if (!buffer)
return -1;
else if (!str.buffer)
return 1;
else
return buffer->Compare(str.buffer);
}
//
// Operator ==
//
LIBRARYCALL bool operator==(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) == 0;
}
//
// Operator !=
//
LIBRARYCALL bool operator!=(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) != 0;
}
//
// Operator <=
//
LIBRARYCALL bool operator<=(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) <= 0;
}
//
// Operator >=
//
LIBRARYCALL bool operator>=(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) >= 0;
}
//
// Operator <
//
LIBRARYCALL bool operator<(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) < 0;
}
//
// Operator >
//
LIBRARYCALL bool operator>(const STFString u, const STFString v)
{
return ((STFString)u).Compare(v) > 0;
}
//
// Operator []
//
char STFString::operator[] (const int32 index) const
{
if (buffer)
return buffer->buffer[index];
else
return 0;
}
void STFString::Set(int32 pos, char val)
{
if (pos < this->Length())
{
STFString str = *this;
str.buffer[pos] = val;
*this = str;
}
}
//
// Operator >>
//
LIBRARYCALL STFString operator >> (const STFString u, int32 num)
{
STFString str = u;
str >>= num;
return str;
}
//
// Operator <<
//
LIBRARYCALL STFString operator << (const STFString u, int32 num)
{
STFString str = u;
str <<= num;
return str;
}
//
// Operator <<=
//
STFString & STFString::operator <<= (int32 index)
{
STFStringBuffer * pb;
if (buffer)
{
if (index < buffer->length)
pb = new (PagedPool) STFStringBuffer(buffer, index, buffer->length - index);
else
pb = NULL;
buffer->Release();
buffer = pb;
}
return * this;
}
//
// Operator >>
//
STFString & STFString::operator >>= (int32 index)
{
STFStringBuffer * pb;
if (buffer)
{
if (index < buffer->length)
pb = new (PagedPool) STFStringBuffer(buffer, 0, buffer->length - index);
else
pb = NULL;
buffer->Release();
buffer = pb;
}
return * this;
}
//
// Return segment of string
//
STFString STFString::Seg(int32 start, int32 num) const
{
STFString str;
if (buffer)
{
if (start + num > buffer->length)
num = buffer->length - start;
if (num > 0)
str.buffer = new (PagedPool) STFStringBuffer(buffer, start, num);
}
return str;
}
//
// Return first num characters
//
STFString STFString::Head(int32 num) const
{
STFString str;
if (buffer && num > 0)
{
if (num > buffer->length)
num = buffer->length;
str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, num);
}
return str;
}
//
// Return last num characters
//
STFString STFString::Tail(int32 num) const
{
STFString str;
if (buffer && num > 0)
{
if (num <= buffer->length)
str.buffer = new (PagedPool) STFStringBuffer(buffer, buffer->length - num, num);
else
str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, num);
}
return str;
}
//
// Delete whitespaces at beginning or end of string
//
STFString STFString::Trim(void)
{
int32 i = 0;
STFString str = *this;
// delete leading tabs and spaces...
i = 0;
while ((str[i] == ' ') || (str[i] == '\t'))
i++;
str <<= i;
// delete trailing tabs and spaces ...
i = str.Length()-1;
while ((str[i] == ' ') || (str[i] == '\t'))
i--;
str = str.Seg(0, i + 1);
return str;
}
//
// Return upper case version of string
//
STFString STFString::Caps(void) const
{
STFString str;
int32 i;
char c;
if (Length())
{
str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, Length());
for (i=0; i<str.Length(); i++)
{
c = str[i];
if (c >= 'a' && c <= 'z')
str.buffer->buffer[i] = c + 'A' - 'a';
}
}
return str;
}
//
// Return lower case version of string
//
STFString STFString::DeCaps(void) const
{
STFString str;
int32 i;
char c;
if (Length())
{
str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, Length());
for (i=0; i<str.Length(); i++)
{
c = str[i];
if (c >= 'A' && c <= 'Z')
str.buffer->buffer[i] = c - ('A' - 'a');
}
}
return str;
}
//
// Find first occurrence of str
//
int32 STFString::First(STFString str) const
{
int32 i = 0;
while (i <= Length()-str.Length() && Seg(i, str.Length()) != str)
i++;
if (Seg(i, str.Length()) != str)
return -1;
else
return i;
}
//
// Find next occurrence of str
//
int32 STFString::Next(STFString str, int32 pos) const
{
int32 i = pos + 1;
while (i <= Length()-str.Length() && Seg(i, str.Length()) != str)
i++;
if (Seg(i, str.Length()) != str)
return -1;
else
return i;
}
//
// Find last occurrence of str
//
int32 STFString::Last(STFString str) const
{
int32 i = Length() - str.Length();
while (i>=0 && Seg(i, str.Length()) != str)
i--;
if (Seg(i, str.Length()) != str)
return -1;
else
return i;
}
//
// Find previous occurrence of str
//
int32 STFString::Prev(STFString str, int32 pos) const
{
int32 i = pos - 1;
while (i>=0 && Seg(i, str.Length()) != str)
i--;
if (Seg(i, str.Length()) != str)
return -1;
else
return i;
}
//
// Find first occurrence of c (-1 if not found)
//
int32 STFString::First(char c) const
{
int32 i = 0;
if (buffer)
{
while (i < Length())
{
if (buffer->buffer[i] == c)
return i;
i++;
}
}
return -1;
}
//
// Find next occurrence of c (-1 if not found)
//
int32 STFString::Next(char c, int32 pos) const
{
int32 i = 0;
if (buffer)
{
i = pos + 1;
while (i < Length())
{
if (buffer->buffer[i] == c)
return i;
i++;
}
}
return -1;
}
//
// Find last occurrence of c (-1 if not found)
//
int32 STFString::Last(char c) const
{
int32 i = 0;
if (buffer)
{
i = Length() - 1;
while (i >= 0)
{
if (buffer->buffer[i] == c)
return i;
i--;
}
}
return -1;
}
//
// Find previous occurrence of c (-1 if not found)
//
int32 STFString::Prev(char c, int32 pos) const
{
int32 i = 0;
if (buffer)
{
i = pos - 1;
while (i >= 0)
{
if (buffer->buffer[i] == c)
return i;
i--;
}
}
return -1;
}
//
// Test if string contains c
//
bool STFString::Contains(char c) const
{
int32 i;
if (buffer)
{
for (i=0; i<Length(); i++)
{
if (buffer->buffer[i] == c)
return true;
}
}
return false;
}
//
// Format string
//
static const uint32 MAXFORMATSTRINGLENGTH = 2000;
void STFString::Format(const char * format, ...)
{
va_list varArgs;
va_start(varArgs, format);
char str[MAXFORMATSTRINGLENGTH];
uint32 numWritten = vsprintf(str, format, varArgs);
ASSERT(numWritten < MAXFORMATSTRINGLENGTH); // if this assertion fails, the stack is most likely corrupted!
va_end(varArgs);
*this = str;
}
void STFString::Format(const char * format, va_list varArgs)
{
char str[MAXFORMATSTRINGLENGTH] ; // if this assertion fails, the stack is most likely corrupted!
uint32 numWritten = vsprintf(str, format, varArgs);
ASSERT(numWritten < MAXFORMATSTRINGLENGTH);
va_end(varArgs);
*this = str;
}
//
// Return pointer to string
//
STFString::operator char * (void) const
{
if (buffer)
return buffer->buffer;
else
return NULL;
}
////////////////////////////////////////////////////////////////////
//
// Kernel String Buffer (uint16 characters) Class Declaration
//
////////////////////////////////////////////////////////////////////
class STFStringBufferW
{
protected:
uint16 * GetNewBuffer(uint32 size);
public:
uint16 useCnt;
uint32 length;
uint16 * buffer;
STFStringBufferW(const char * str, bool fromUnicode = false);
STFStringBufferW(const char * str, uint32 len, bool fromUnicode = false);
STFStringBufferW(const uint16 ch);
STFStringBufferW(uint32 size); // Creates an UNINITIALIZED string with certain size
STFStringBufferW(STFStringBufferW * u, STFStringBufferW * v);
STFStringBufferW(STFStringBufferW * u, uint32 start, uint32 num);
STFStringBufferW(bool sign, uint32 value, int32 digits, int32 base, uint16 fill);
STFStringBufferW(const STFStringBufferW * u);
~STFStringBufferW(void);
uint32 Length(void) const { return length; }
int32 Compare(STFStringBufferW * u);
void Obtain(void) { useCnt++; }
void Release(void) { if (!--useCnt) delete this; }
};
////////////////////////////////////////////////////////////////////
//
// Kernel String Buffer (uint16) Class Implementation
//
////////////////////////////////////////////////////////////////////
//
// OS Specific Memory Allocator (allocates space for trailing 0)
//
inline uint16 * STFStringBufferW::GetNewBuffer(uint32 size)
{
return new (PagedPool) uint16[size + 1];
}
//
// Constructor (by character string)
//
STFStringBufferW::STFStringBufferW(const char * str, bool fromUnicode)
{
const char * src;
uint16 * dest;
uint32 i;
useCnt = 1;
length = 0;
src = str;
if (fromUnicode)
{
while (*src++ || *src++)
length++;
}
else
{
while (*src++)
length++;
}
buffer = GetNewBuffer(length);
src = str;
dest = buffer;
if (fromUnicode)
{
for (i=0; i<length; i++)
{
*dest++ = (src[0] << 8) | src[1];
src += 2;
}
}
else
{
for (i=0; i<length; i++)
*dest++ = (uint16)(*src++);
}
*dest = 0;
}
//
// Constructor (by character string with length in bytes)
//
STFStringBufferW::STFStringBufferW(const char * str, uint32 len, bool fromUnicode)
{
const char * src;
uint16 * dest;
uint32 i;
uint32 calcLen;
useCnt = 1;
// calculate the actual length. This is necessary to avoid wrong string length
// due to zeros in the characters given (Fixes GNBvd29973)
if (fromUnicode)
{
calcLen = 0;
src = str;
while ((*src++ || *src++) && (calcLen < len))
{
calcLen += 2;
}
}
else
{
calcLen = 0;
const char * s = str;
while ((*s) && (calcLen < len))
{
calcLen++;
s++;
}
}
// our length is the minimum of the length passed in and the character length
if (fromUnicode)
length = min(calcLen,len) >> 1;
else
length = min(calcLen, len);
buffer = GetNewBuffer(length);
src = str;
dest = buffer;
if (fromUnicode)
{
for (i=0; i<length; i++)
{
*dest++ = (src[0] << 8) | src[1];
src += 2;
}
}
else
{
for (i=0; i<length; i++)
*dest++ = (uint16)(*src++);
}
*dest = 0;
}
//
// Constructor (by character)
//
STFStringBufferW::STFStringBufferW(const uint16 ch)
{
useCnt = 1;
length = 1;
buffer = GetNewBuffer(2);
buffer[0] = ch;
buffer[1] = 0;
}
//
// Constructor (by size). Creates an UNINITIALIZED string.
//
STFStringBufferW::STFStringBufferW(uint32 size)
{
useCnt = 1;
length = size;
buffer = GetNewBuffer(size);
buffer[0] = 0;
}
//
// Constructor (by two string buffers)
//
STFStringBufferW::STFStringBufferW(STFStringBufferW * u, STFStringBufferW * v)
{
uint16 * src;
uint16 * dest;
useCnt = 1;
length = u->length + v->length;
buffer = GetNewBuffer(length);
src = u->buffer;
dest = buffer;
while ((*dest++ = *src++) != 0) ;
dest--; // Compensate trailing 0
src = v->buffer;
while ((*dest++ = *src++) != 0) ;
}
//
// Constructor (by part of other buffer)
// NOTE: start and num are specified in characters here
//
STFStringBufferW::STFStringBufferW(STFStringBufferW * u, uint32 start, uint32 num)
{
uint16 * src;
uint16 * dest;
uint32 i;
useCnt = 1;
//
// Make sure we don't copy too much
//
if (start + num > u->Length())
num = u->Length() - start;
length = num;
buffer = GetNewBuffer(length);
dest = buffer;
src = u->buffer + start;
for (i=0; i<length; i++)
*dest++ = *src++;
*dest = 0;
}
//
// Constructor (by number)
// 'digits' includes preceeding fill values and a sign (if -)
//
#define KSTRW_MAX_NUM_LENGTH 10
STFStringBufferW::STFStringBufferW(bool sign, uint32 value, int32 digits, int32 base, uint16 fill)
{
uint16 lbuffer[KSTRW_MAX_NUM_LENGTH + 2];
int32 pos = digits;
int32 i;
useCnt = 1;
if (!pos)
pos = KSTRW_MAX_NUM_LENGTH; // Pos 11 is for '\0'
do
{
i = (int32)(value % base);
if (i < 10)
lbuffer[--pos] = '0' + i;
else
lbuffer[--pos] = 'A' + i - 10;
value /= base;
}
while (value && pos);
//
// Now fill calculated digits into buffer
//
if (digits)
{
buffer = GetNewBuffer(digits + 1);
for (i=0; i<pos; i++)
buffer[i] = fill;
if (sign)
buffer[0] = '-';
for (i=pos; i<digits; i++)
buffer[i] = lbuffer[i];
buffer[digits] = 0;
length = digits;
}
else
{
if (sign)
{
buffer = GetNewBuffer(KSTRW_MAX_NUM_LENGTH - pos + 2); // Incl. sign and '\0'
buffer[0] = '-';
i = 1;
length = KSTRW_MAX_NUM_LENGTH - pos + 1;
}
else
{
buffer = GetNewBuffer(KSTRW_MAX_NUM_LENGTH - pos + 1); // Incl. '\0'
i = 0;
length = KSTRW_MAX_NUM_LENGTH - pos;
}
while (pos < KSTRW_MAX_NUM_LENGTH)
{
buffer[i++] = lbuffer[pos++];
}
buffer[i] = 0;
}
}
//
// Copy constructor
//
STFStringBufferW::STFStringBufferW(const STFStringBufferW * u)
{
uint16 * src;
uint16 * dest;
useCnt = 1;
length = u->Length();
buffer = GetNewBuffer(length);
src = u->buffer;
dest = buffer;
while ((*dest++ = *src++) != 0) ;
}
//
// Destructor
//
STFStringBufferW::~STFStringBufferW(void)
{
if (buffer)
delete[] buffer;
}
//
// Compare two STFStringBuffers
//
int32 STFStringBufferW::Compare(STFStringBufferW * u)
{
uint16 * strA;
uint16 * strB;
strA = buffer;
strB = u->buffer;
while (*strA && *strB)
{
if (*strA < *strB)
return -1;
else if (*strA > *strB)
return 1;
strA++;
strB++;
}
if (length < u->length)
return -1;
else if (length > u->length)
return 1;
else
return 0;
}
////////////////////////////////////////////////////////////////////
//
// Kernel String (uint16) Class
//
////////////////////////////////////////////////////////////////////
//
// Constructor (no init)
//
STFStringW::STFStringW(void)
{
buffer = NULL;
}
//
// Constructor (by character string)
//
STFStringW::STFStringW(const char * str, bool fromUnicode)
{
buffer = new (PagedPool) STFStringBufferW(str, fromUnicode);
}
//
// Constructor (by character string and length, probably Unicode)
//
STFStringW::STFStringW(const char * str, uint32 len, bool fromUnicode)
{
buffer = new (PagedPool) STFStringBufferW(str, len, fromUnicode);
}
//
// Constructor (by character)
//
STFStringW::STFStringW(const uint16 ch)
{
buffer = new (PagedPool) STFStringBufferW(ch);
}
//
// Constructor (by STFString)
//
STFStringW::STFStringW(const STFString & str)
{
uint32 i;
buffer = new (PagedPool) STFStringBufferW((uint32)str.Length());
for (i=0; i<(uint32)str.Length(); i++)
{
buffer->buffer[i] = (uint16)(/*(const uint8)*/ str[(int32)i]);
}
buffer->buffer[Length()] = 0;
}
//
// Copy Constructor
//
STFStringW::STFStringW(const STFStringW & str)
{
buffer = str.buffer;
if (buffer)
buffer->Obtain();
}
//
// Constructor (by uint32)
//
STFStringW::STFStringW(uint32 value, int32 digits, int32 base, uint16 fill)
{
buffer = new (PagedPool) STFStringBufferW(false, value, digits, base, fill);
}
//
// Constructor (by INT)
//
STFStringW::STFStringW(int32 value, int32 digits, int32 base, uint16 fill)
{
if (value < 0)
buffer = new (PagedPool) STFStringBufferW(true, (uint32)(-value), digits, base, fill);
else
buffer = new (PagedPool) STFStringBufferW(false, (uint32)(value), digits, base, fill);
}
//
// Destructor
//
STFStringW::~STFStringW(void)
{
if (buffer)
buffer->Release();
}
//
// Return length (in characters)
//
uint32 STFStringW::Length(void) const
{
if (buffer)
return buffer->Length();
else
return 0;
}
//
// Copy string into character array
// If there is not enough room to hold the string then as much as fits is filled in
// and GNR_NOT_ENOUGH_MEMORY is returned
//
STFResult STFStringW::Get(char * str, uint32 & len) const
{
STFResult err = STFRES_OK;
uint16 * src;
uint32 i;
if (buffer)
{
if ((len >> 1) > buffer->Length())
len = buffer->Length();
else
{
if ((len >> 1) - 1 < buffer->Length())
len = (len >> 1) - 1;
else
len = buffer->Length();
err = STFRES_NOT_ENOUGH_MEMORY;
}
src = buffer->buffer;
i = len;
while (i)
{
*str++ = (*src) & 0xff;
*str++ = (*src++) >> 8;
i--;
}
*str++ = 0;
*str = 0;
}
else
{
if (len > 1)
{
//
// STFStringW is empty and there is enough room for the 0 bytes
//
str[0] = 0;
str[1] = 0;
}
else
err = STFRES_NOT_ENOUGH_MEMORY;
len = 0;
}
STFRES_RAISE(err);
}
//
// Copy string as ASCII into character array (even bytes only)
// Return values signals success
//
STFResult STFStringW::GetAsAscii(char * str, uint32 & len) const
{
STFResult err = STFRES_OK;
uint16 * src;
uint32 i;
if (buffer)
{
if (len >= buffer->Length() +1)
len = buffer->Length();
else
{
if (len - 1 < buffer->Length())
len--;
else
len = buffer->Length();
STFRES_RAISE(STFRES_NOT_ENOUGH_MEMORY);
}
src = buffer->buffer;
i = len;
while (i)
{
*str++ = (*src++) & 0xff;
i--;
}
*str = 0;
}
else
{
if (len > 1)
{
//
// STFStringW is empty and there is enough room for the 0 bytes
//
str[0] = 0;
}
else
STFRES_RAISE(STFRES_NOT_ENOUGH_MEMORY);
len = 0;
}
STFRES_RAISE(err);
}
//
// Get single character
//
uint16 STFStringW::GetChar(uint32 index) const
{
//lint --e{613}
if (index < buffer->Length())
return buffer->buffer[index];
else
return 0;
}
//
// Operator = (by BYTE string)
//
STFStringW & STFStringW::operator= (const char * str)
{
if (buffer)
buffer->Release();
buffer = new (PagedPool) STFStringBufferW(str);
return * this;
}
//
// Operator = (by STFStringW)
//
STFStringW & STFStringW::operator= (const STFStringW & str)
{
if (buffer)
buffer->Release();
buffer = str.buffer;
if (buffer)
buffer->Obtain();
return * this;
}
//
// Operator + (Concatenation)
//
STFStringW operator+ (const STFStringW & u, const STFStringW & v)
{
STFStringW str = u;
str += v;
return str;
}
//
// Operator += (Append)
//
STFStringW & STFStringW::operator += (const STFStringW & u)
{
STFStringBufferW * bp;
if (buffer)
{
if (u.buffer)
{
bp = new (PagedPool) STFStringBufferW(buffer, u.buffer);
buffer->Release();
buffer = bp;
}
}
else
{
buffer = u.buffer;
if (buffer)
buffer->Obtain();
}
return *this;
}
//
// Compare two STFStringWs
//
int32 STFStringW::Compare(const STFStringW & str) const
{
if (buffer == str.buffer)
return 0;
else if (!buffer)
return -1;
else if (!str.buffer)
return 1;
else
return buffer->Compare(str.buffer);
}
//
// Operator ==
//
bool operator==(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) == 0;
}
//
// Operator !=
//
bool operator!=(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) != 0;
}
//
// Operator <=
//
bool operator<=(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) <= 0;
}
//
// Operator >=
//
bool operator>=(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) >= 0;
}
//
// Operator <
//
bool operator<(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) < 0;
}
//
// Operator >
//
bool operator>(const STFStringW & u, const STFStringW & v)
{
return u.Compare(v) > 0;
}
//
// Return segment of string
//
STFStringW STFStringW::Seg(uint32 start, uint32 num) const
{
STFStringW str;
if (buffer)
{
if (start + num > buffer->Length())
num = buffer->Length() - start;
if (num > 0)
str.buffer = new (PagedPool) STFStringBufferW(buffer, start, num);
}
return str;
}
//
// Return first num characters
//
STFStringW STFStringW::Head(uint32 num) const
{
STFStringW str;
if (buffer && num > 0)
{
if (num > buffer->Length())
num = buffer->Length();
str.buffer = new (PagedPool) STFStringBufferW(buffer, 0, num);
}
return str;
}
//
// Return last num characters
//
STFStringW STFStringW::Tail(uint32 num) const
{
STFStringW str;
if (buffer && num > 0)
{
if (num <= buffer->Length())
str.buffer = new (PagedPool) STFStringBufferW(buffer, buffer->Length() - num, num);
else
str.buffer = new (PagedPool) STFStringBufferW(buffer, 0, num);
}
return str;
}
//
// Delete whitespaces at beginning or end of string
//
STFStringW STFStringW::Trim(void) const
{
STFStringW str;
uint32 start = 0;
uint32 end;
if (buffer)
{
//
// Find leading tabs and spaces ...
//
while ((buffer->buffer[start] == ' ') || (buffer->buffer[start] == '\t'))
start++;
if (start >= Length())
{
str.buffer = new (PagedPool) STFStringBufferW((uint32)0);
}
else
{
//
// Find trailing tabs and spaces ...
//
end = Length() - 1;
while ((buffer->buffer[end] == ' ') || (buffer->buffer[end] == '\t'))
end--;
str = Seg(start, end - start + 1);
}
}
return str;
}
//
// Replace all occurrences of characters in 'what' with 'with', remove doubles
//
STFStringW STFStringW::Normalize(const uint16 * what, uint32 howManyWhats, uint16 with)
{
STFStringW str;
uint32 i;
uint32 j;
uint32 write = 0;
if (buffer)
{
str.buffer = new STFStringBufferW(Length());
for (i=0; i<Length(); i++)
{
for (j=0; j<howManyWhats; j++)
{
if (what[j] == buffer->buffer[i])
break;
}
//
// If we found a character inside 'what', then replace it
//
if (j < howManyWhats)
{
str.buffer->buffer[write] = with;
if (!write || str.buffer->buffer[write - 1] != with)
write++;
else
str.buffer->length--;
}
else
{
str.buffer->buffer[write] = buffer->buffer[i];
write++;
}
}
str.buffer->buffer[write] = 0;
}
return str;
}
//
// Return upper case version of string
//
STFStringW STFStringW::Caps(void) const
{
STFStringW str;
uint16 * p;
if (Length())
{
str.buffer = new STFStringBufferW(buffer);
p = str.buffer->buffer;
do
{
if (*p >= 'a' && *p <= 'z')
*p = *p + 'A' - 'a';
p++;
}
while (*p);
}
return str;
}
//
// Return lower case version of string
//
STFStringW STFStringW::DeCaps(void) const
{
STFStringW str;
uint16 * p;
if (Length())
{
str.buffer = new STFStringBufferW(buffer);
p = str.buffer->buffer;
do
{
if (*p >= 'A' && *p <= 'Z')
*p = *p + 'a' - 'A';
p++;
}
while (*p);
}
return str;
}
//
// Find first occurrence of str
//
uint32 STFStringW::First(const STFStringW & str) const
{
uint32 i = 0;
while (i <= Length() - str.Length() && Seg(i, str.Length()) != str)
i++;
if (i <= Length() - str.Length())
return i;
else
return KSTRW_NOT_FOUND;
}
//
// Find next occurrence of str
//
uint32 STFStringW::Next(const STFStringW & str, uint32 pos) const
{
uint32 i = pos+1;
while (i <= Length() - str.Length() && Seg(i, str.Length()) != str)
i++;
if (i <= Length() - str.Length())
return i;
else
return KSTRW_NOT_FOUND;
}
//
// Find last occurrence of str
//
uint32 STFStringW::Last(const STFStringW & str) const
{
int32 i = Length() - str.Length();
while (i >= 0 && Seg(i, str.Length()) != str)
i--;
if (i >= 0)
return (uint32)i;
else
return KSTRW_NOT_FOUND;
}
//
// Find previous occurrence of str
//
uint32 STFStringW::Prev(const STFStringW & str, uint32 pos) const
{
int32 i = pos - 1;
while (i >= 0 && Seg(i, str.Length()) != str)
i--;
if (i >= 0)
return (uint32)i;
else
return KSTRW_NOT_FOUND;
}
//
// Find first occurrence of c (KSTRW_NOT_FOUND if not found)
//
uint32 STFStringW::First(uint16 c) const
{
uint32 i = 0;
if (buffer)
{
while (i < Length())
{
if (buffer->buffer[i] == c)
return i;
i++;
}
}
return KSTRW_NOT_FOUND;
}
//
// Find next occurrence of c (KSTRW_NOT_FOUND if not found)
//
uint32 STFStringW::Next(uint16 c, uint32 pos) const
{
uint32 i;
if (buffer)
{
i = pos + 1;
while (i < Length())
{
if (buffer->buffer[i] == c)
return i;
i++;
}
}
return KSTRW_NOT_FOUND;
}
//
// Find last occurrence of c (KSTRW_NOT_FOUND if not found)
//
uint32 STFStringW::Last(uint16 c) const
{
int32 i = 0;
if (buffer)
{
i = Length() - 1;
while (i >= 0)
{
if (buffer->buffer[i] == c)
return (uint32)i;
i--;
}
}
return KSTRW_NOT_FOUND;
}
//
// Find previous occurrence of c (KSTRW_NOT_FOUND if not found)
//
uint32 STFStringW::Prev(uint16 c, uint32 pos) const
{
int32 i;
if (buffer)
{
i = pos - 1;
while (i >= 0)
{
if (buffer->buffer[i] == c)
return (uint32)i;
i--;
}
}
return KSTRW_NOT_FOUND;
}
//
// Test if string contains c
//
bool STFStringW::Contains(uint16 c) const
{
uint32 i = 0;
if (buffer)
{
while (buffer->buffer[i])
{
if (buffer->buffer[i] == c)
return true;
i++;
}
}
return false;
}
| 16.37596 | 109 | 0.544123 | rerunner |
31dc3ec907cfbc8ff5e912e7008b046477e3297c | 57 | cpp | C++ | code archive/TIOJ/1605.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/TIOJ/1605.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/TIOJ/1605.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | #include<stdio.h>
int main(){puts("APRIL FOOL'S DAY!");}
| 19 | 38 | 0.649123 | brianbbsu |
31e4db34d89d694ac261facf677a297b7c6e4912 | 2,715 | cpp | C++ | osc/reader/types/OscBlob.cpp | MugenSAS/osc-cpp-qt | 4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5 | [
"MIT"
] | 22 | 2015-03-05T17:00:41.000Z | 2022-03-19T19:39:21.000Z | osc/reader/types/OscBlob.cpp | MugenSAS/osc-cpp-qt | 4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5 | [
"MIT"
] | 3 | 2016-02-20T02:33:01.000Z | 2016-06-07T22:00:56.000Z | osc/reader/types/OscBlob.cpp | MugenSAS/osc-cpp-qt | 4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5 | [
"MIT"
] | 3 | 2016-12-05T19:16:47.000Z | 2021-02-01T08:22:06.000Z | /*
* Copyright (c) 2014 MUGEN SAS
*
* 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 <osc/reader/types/OscBlob.h>
#include <tools/ByteBuffer.h>
#include <osc/exceptions/CharConversionException.h>
#include <osc/exceptions/DoubleConversionException.h>
#include <osc/exceptions/IntegerConversionException.h>
#include <osc/exceptions/FloatConversionException.h>
#include <osc/exceptions/LongConversionException.h>
#include <osc/exceptions/StringConversionException.h>
OscBlob::OscBlob(ByteBuffer* packet, qint32 pos)
: OscValue('b', packet, pos)
{
try
{
get();
}
catch (const QException& e)
{
throw e;
}
}
/**
* Returns the blob data.
*
* @return a blob data.
*/
QByteArray& OscBlob::get()
{
try
{
mBlobSize = mPacket->getInt(mPos);
if (mBlobSize != 0)
{
mData = QByteArray(mBlobSize, 0);
mPacket->setPosition(mPos + 4);
mPacket->get(&mData, 0, mBlobSize);
qint32 rem = 4 - (mBlobSize % 4);
if (rem == 4)
rem = 0;
mPacket->setPosition(mPos + 4 + mBlobSize + rem);
}
return mData;
}
catch (const QException& e)
{
throw e;
}
}
bool OscBlob::toBoolean()
{
return (get().length() != 0);
}
QByteArray OscBlob::toBytes()
{
return get();
}
char OscBlob::toChar()
{
throw CharConversionException();
}
double OscBlob::toDouble()
{
throw DoubleConversionException();
}
float OscBlob::toFloat()
{
throw FloatConversionException();
}
qint32 OscBlob::toInteger()
{
throw IntegerConversionException();
}
qint64 OscBlob::toLong()
{
throw LongConversionException();
}
QString OscBlob::toString()
{
throw StringConversionException();
}
| 23.405172 | 80 | 0.698711 | MugenSAS |
31f140576d417e6fc6adb77286281f32c3af1028 | 20,725 | cpp | C++ | xmlcc/xmlccCfgConfig.cpp | cscheiblich/XMLCC | efda13ae7261b22304907432d1298a865d14bcdc | [
"MIT"
] | 1 | 2020-02-07T09:12:50.000Z | 2020-02-07T09:12:50.000Z | xmlcc/xmlccCfgConfig.cpp | cscheiblich/XMLCC | efda13ae7261b22304907432d1298a865d14bcdc | [
"MIT"
] | null | null | null | xmlcc/xmlccCfgConfig.cpp | cscheiblich/XMLCC | efda13ae7261b22304907432d1298a865d14bcdc | [
"MIT"
] | null | null | null | /**
* @file xmlccCfgConfig.cpp
* @author Christian (graetz23@gmail.com)
*
* XMLCC is distributed under the MIT License (MIT); this file is part of.
*
* Copyright (c) 2008-2022 Christian (graetz23@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.
*/
#include "./xmlccCfgConfig.h" // header
/******************************************************************************/
namespace XMLCC {
namespace CFG {
/******************************************************************************/
/// constructor
Config::Config( void ) {
_root = read( ); // one strategy, take DOM tree to mem
} // Config
/// destructor
Config::~Config( void ) {
if( _root != 0 )
delete _root; // delete DOM tree if read; always
} // ~Config
/******************************************************************************/
bool // check if config file is existing
Config::exists( void ) {
bool isExisting = false;
Str fileName = "xmlcc.xml"; // static file name
FileStr file; // standard file stream
file.open( (char*)fileName.c_str( ), std::ios::in );
if( !file.fail( ) )
isExisting = true;
file.close( );
return isExisting;
} // Config::isExisting
/******************************************************************************/
DOM::Root* // use this method in static way; Config::parseFile( "file.xml" );
Config::generate( void ) {
DOM::Root* xml = 0;
try { // try everything .. like chicken's road rash ~8>
xml =
new DOM::Root( "xmlcc.xml",
new DOM::Header( new DOM::Attribute( "version", "1.0" ) ),
new DOM::Comment( "XMLCC 1.00 20150101 Amara Faith" ),
new DOM::Comment( "config file of the xmlcc library" ),
new DOM::Element( "xmlcc:xmlcc",
new DOM::Comment( "library configuration; set by user" ),
new DOM::Element( "xmlcc:config",
new DOM::Comment( "parser configuration" ),
new DOM::Element( "xmlcc:parser",
new DOM::Element( "xmlcc:console",
new DOM::Attribute( "talk", "no" ) ),
new DOM::Element( "xmlcc:clean",
new DOM::Attribute( "tags", "yes" ),
new DOM::Attribute( "attributes", "yes" ),
new DOM::Attribute( "comments", "yes" ) ),
new DOM::Element( "xmlcc:memory",
new DOM::Attribute( "preallocation", "999" ) ) ),
new DOM::Comment( "tokenizer configuration" ),
new DOM::Element( "xmlcc:tokenizer",
new DOM::Element( "xmlcc:console",
new DOM::Attribute( "talk", "no" ) ) ) ),
new DOM::Comment( "library information; refreshed by each call" ),
new DOM::Element( "xmlcc:info",
new DOM::Element( "xmlcc:built",
new DOM::Attribute( "date", "01.01.2015" ) ),
new DOM::Element( "xmlcc:version",
new DOM::Attribute( "number", "1.00" ) ),
new DOM::Element( "xmlcc:package",
new DOM::Attribute( "name", "Amara Faith" ) ),
new DOM::Element( "xmlcc:license",
new DOM::Attribute( "type", "The MIT License (MIT)" ) ),
new DOM::Element( "xmlcc:project",
new DOM::Attribute( "url",
"https://github.com/graetz23/xmlcc/" ) ),
new DOM::Element( "xmlcc:user",
new DOM::Attribute( "name", "Christian" ),
new DOM::Attribute( "email", "graetz23@gmail.com" ) ) ),
new DOM::Comment( "library system; run unit tests, etc." ),
new DOM::Element( "xmlcc:system",
new DOM::Comment( "unit test framework configuration" ),
new DOM::Element( "xmlcc:test",
new DOM::Comment( "unit test framework configuration" ),
new DOM::Element( "xmlcc:sysList",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:sysStrTool",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:sysXmlTool",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:sysXmlParser",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:domTokenizer",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:domController",
new DOM::Attribute( "run", "no" ) ),
new DOM::Element( "xmlcc:xmlcc",
new DOM::Attribute( "run", "no" ) ),
new DOM::Comment(
"reads chars &compares them; due to use of STL file encoding" ),
new DOM::CData(
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ) ) ) ) );
} catch( SYS::Failure& f ) {
Str msg = "XMLCC::CFG::Config::generate - ";
throw SYS::Failure( msg.append( f.declare( ) ) );
} catch( SYS::Error& e ) {
Str msg = "XMLCC::CFG::Config::generate - ";
throw SYS::Error( msg.append( e.declare( ) ) );
} catch( SYS::Exception& e ) {
Str msg = "XMLCC::CFG::Config::generate - ";
throw SYS::Error( msg.append( e.declare( ) ) );
} catch( std::exception& e ) {
throw SYS::Exception(
"XMLCC::CFG::Config::generate - std::exception caught!" );
} catch( ... ) {
throw SYS::Exception( "XMLCC::CFG::Config::generate - unknown caught!" );
} // try
return xml;
} // Config::generate
/******************************************************************************/
void // use this method in static way; Config::parseFile( "file.xml" );
Config::write( DOM::Root* xml ) {
try { // try everything .. like chicken's road rash ~8>
std::fstream file; // open file
file.open( "xmlcc.xml", std::ios::out );
file << xml; // DOM::Node* 2 std::fstream or write XML file to drive
file.close( );
delete xml;
} catch( SYS::Failure& f ) {
Str msg = "XMLCC::CFG::Config::write - ";
throw SYS::Failure( msg.append( f.declare( ) ) );
} catch( SYS::Error& e ) {
Str msg = "XMLCC::CFG::Config::write - ";
throw SYS::Error( msg.append( e.declare( ) ) );
} catch( SYS::Exception& e ) {
Str msg = "XMLCC::CFG::Config::write - ";
throw SYS::Error( msg.append( e.declare( ) ) );
} catch( std::exception& e ) {
throw SYS::Exception(
"XMLCC::CFG::Config::write - std::exception caught!" );
} catch( ... ) {
throw SYS::Exception( "XMLCC::CFG::Config::write - unknown caught!" );
} // try
} // Config::write
/******************************************************************************/
DOM::Root* // use this method in static way; Config::parseFile( "file.xml" );
Config::read( void ) {
DOM::Root* xml = 0;
try { // try everything .. like chicken's road rash ~8>
DOM::Core core; // parsing, cleaning, tokenizing, and model building
xml = core.parseFile2DomTree( "xmlcc.xml" ); // parse 2 model tree
} catch( SYS::Failure& f ) { // recovery might be a dead lock ;-)
if( xml != 0 )
delete xml;
f.report( );
std::cout << "generating config file for xmlcc .. " << std::flush;
write( generate( ) );
std::cout << "done!" << std::endl << std::flush;
xml = read( ); // recovery
} catch( SYS::Error& e ) {
if( xml != 0 )
delete xml;
e.report( );
std::cout << "generating config file for xmlcc .. " << std::flush;
write( generate( ) );
std::cout << "done!" << std::endl << std::flush;
xml = read( ); // recovery
} catch( SYS::Exception& e ) {
if( xml != 0 )
delete xml;
e.report( );
std::cout << "generating config file for xmlcc .. " << std::flush;
write( generate( ) );
std::cout << "done!" << std::endl << std::flush;
xml = read( ); // recovery
} catch( std::exception& e ) {
if( xml != 0 )
delete xml;
std::cout << "generating config file for xmlcc .. " << std::flush;
write( generate( ) );
std::cout << "done!" << std::endl << std::flush;
xml = read( ); // recovery
} catch( ... ) {
if( xml != 0 )
delete xml;
std::cout << "generating config file for xmlcc .. " << std::flush;
write( generate( ) );
std::cout << "done!" << std::endl << std::flush;
xml = read( ); // recovery
} // try
return xml;
} // Config::read
/******************************************************************************/
/// <config><parser> .. </parser></config>
bool // get config parameter
Config::getConfigParserConsoleTalk( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:parser", "xmlcc:console", "talk" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigParserConsoleTalk
bool // get config parameter
Config::getConfigParserCleanTag( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:parser", "xmlcc:clean", "tags" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigParserCleanTag
bool // get config parameter
Config::getConfigParserCleanAttributes( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:parser", "xmlcc:clean", "attribute" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigParserCleanAttributes
bool // get config parameter
Config::getConfigParserCleanComments( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:parser", "xmlcc:clean", "comments" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigParserCleanComments
int // get config parameter
Config::getConfigParserMemoryPreallocation( void ) {
int parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:parser", "xmlcc:memory", "preallocation" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2I( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigParserMemoryPreallocation
/******************************************************************************/
/// <config><tokenizer> .. </tokenizer></config>
bool // get config parameter
Config::getConfigTokenizerTalk( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:config", "xmlcc:tokenizer", "xmlcc:console", "talk" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getConfigTokenizerTalk
/******************************************************************************/
/// <config><info> .. </info></config>
Str // get info parameter
Config::getInfoBuiltDate( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:built", "date" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoBuiltDate
Str // get info parameter
Config::getInfoVersionNumber( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:version", "number" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoVersionNumber
Str // get info parameter
Config::getInfoPackageName( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:package", "name" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoPackageName
Str // get info parameter
Config::getInfoLicenseType( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:license", "type" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoLicenseType
Str // get info parameter
Config::getInfoProjectUrl( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:project", "url" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoProjectUrl
Str // get info parameter
Config::getInfoUserName( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:user", "name" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoUserName
Str // get info parameter
Config::getInfoUserEmail( void ) {
Str parameter = ""; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:info", "xmlcc:user", "email" );
if( res != 0 )
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getInfoUserEmail
/******************************************************************************/
/// <config><system> .. </system></config>
bool // get system parameter
Config::getSystemTestSysList( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:sysList", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestSysList
bool // get system parameter
Config::getSystemTestSysStrTool( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:sysStrTool", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestStrTool
bool // get system parameter
Config::getSystemTestSysXmlTool( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:sysXmlTool", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestXmlTool
bool // get system parameter
Config::getSystemTestSysXmlParser( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:sysXmlParser", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestXmlParser
bool // get system parameter
Config::getSystemTestDomTokenizer( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:domTokenizer", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestDomTokenizer
bool // get system parameter
Config::getSystemTestDomController( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:domController", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestDomController
bool // get system parameter
Config::getSystemTestXmlcc( void ) {
bool parameter = true; // default
DOM::Root* xmlConfigFile = read( ); // load config file from drive
DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc",
"xmlcc:system", "xmlcc:test", "xmlcc:xmlcc", "run" );
if( res != 0 ) {
Str readParameter = ( (DOM::Attribute*)res )->getValue( );
parameter = _strTool.doS2B( readParameter ); // conversion
} // if
_controller.erase( xmlConfigFile );
return parameter;
} // Config::getSystemTestXmlcc
Str // get system parameter
Config::getSystemCData( void ) {
Str parameter = "";
throw SYS::Error( "CFG::Config::getSystemCData - not implemented yet!" );
return parameter;
} // Config::getSystemCData
/******************************************************************************/
} // namespace CFG
} // namespace XMLCC
/******************************************************************************/
| 38.738318 | 91 | 0.598022 | cscheiblich |
31f732a5b64e8278b8eccc43b4c15a8b373e9ef4 | 1,038 | hpp | C++ | macos/MersenneTwisterRandomizer.hpp | BoysTownorg/av-speech-in-noise | 71178c1f920e300f05c9da2d582d64035c591284 | [
"MIT"
] | null | null | null | macos/MersenneTwisterRandomizer.hpp | BoysTownorg/av-speech-in-noise | 71178c1f920e300f05c9da2d582d64035c591284 | [
"MIT"
] | null | null | null | macos/MersenneTwisterRandomizer.hpp | BoysTownorg/av-speech-in-noise | 71178c1f920e300f05c9da2d582d64035c591284 | [
"MIT"
] | null | null | null | #ifndef MACOS_MAIN_MERSENNETWISTERRANDOMIZER_HPP_
#define MACOS_MAIN_MERSENNETWISTERRANDOMIZER_HPP_
#include <av-speech-in-noise/playlist/RandomizedTargetPlaylists.hpp>
#include <av-speech-in-noise/core/RecognitionTestModel.hpp>
#include <random>
namespace av_speech_in_noise {
class MersenneTwisterRandomizer : public target_list::Randomizer,
public Randomizer {
std::mt19937 engine{std::random_device{}()};
public:
void shuffle(gsl::span<av_speech_in_noise::LocalUrl> s) override {
std::shuffle(s.begin(), s.end(), engine);
}
void shuffle(gsl::span<int> s) override {
std::shuffle(s.begin(), s.end(), engine);
}
auto betweenInclusive(double a, double b) -> double override {
std::uniform_real_distribution<> distribution{a, b};
return distribution(engine);
}
auto betweenInclusive(int a, int b) -> int override {
std::uniform_int_distribution<> distribution{a, b};
return distribution(engine);
}
};
}
#endif
| 28.833333 | 70 | 0.684008 | BoysTownorg |
31f8925b9ec4468bddf0b4a0e3d0c79fc554b481 | 776 | cpp | C++ | src/libugly/edge/edge_undirected.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null | src/libugly/edge/edge_undirected.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null | src/libugly/edge/edge_undirected.cpp | JoshuaSBrown/GraphCluster | d9c28204b276165cf59137c9668c4dfcfa397089 | [
"MIT"
] | null | null | null | #include "../../../include/ugly/edge_undirected.hpp"
namespace ugly {
const constants::EdgeType EdgeUndirected::class_type_ =
constants::EdgeType::undirected;
constants::EdgeType EdgeUndirected::getClassType() {
return EdgeUndirected::class_type_;
}
EdgeUndirected::EdgeUndirected(int vertex1, int vertex2) {
if (vertex1 < vertex2) {
vertex1_ = vertex1;
vertex2_ = vertex2;
} else {
vertex1_ = vertex2;
vertex2_ = vertex1;
}
edge_directed_ = false;
object_type_ = constants::EdgeType::undirected;
}
EdgeUndirected& EdgeUndirected::operator=(const EdgeUndirected& edge) {
vertex1_ = edge.vertex1_;
vertex2_ = edge.vertex2_;
edge_directed_ = edge.edge_directed_;
object_type_ = edge.object_type_;
return *this;
}
}
| 24.25 | 71 | 0.71134 | JoshuaSBrown |
31f910df850174b6c416aa9f8d7948b161dd94f0 | 4,966 | cpp | C++ | qtcreator/OpensslServer/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | qtcreator/OpensslServer/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | qtcreator/OpensslServer/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | #include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#define FAIL -1
using namespace std;
int OpenListener(int port)
{ int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
perror("can't bind port");
abort();
}
if ( listen(sd, 10) != 0 )
{
perror("Can't configure listening port");
abort();
}
return sd;
}
SSL_CTX* InitServerCTX(void)
{
SSL_CTX *ctx = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
const SSL_METHOD *method;
#else
SSL_METHOD *method;
#endif
SSL_library_init();
OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
SSL_load_error_strings(); /* load all error messages */
method = SSLv23_client_method(); /* create new server-method instance */
ctx = SSL_CTX_new(method); /* create new context from method */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, const char* CertFile, const char* KeyFile)
{
//New lines
if (SSL_CTX_load_verify_locations(ctx, CertFile, KeyFile) != 1)
ERR_print_errors_fp(stderr);
if (SSL_CTX_set_default_verify_paths(ctx) != 1)
ERR_print_errors_fp(stderr);
//End new lines
/* set the local certificate from CertFile */
if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
printf("LoadCertificates Compleate Successfully.....\n");
}
void ShowCertsClient(SSL* ssl)
{
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{
char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
ShowCertsClient(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
SSL_write(ssl, reply, strlen(reply)); /* send reply */
}
else
ERR_print_errors_fp(stderr);
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
int MainServer(int count, char *strings[])
{
SSL_CTX *ctx;
int server;
char *portnum;
if ( count != 2 )
{
printf("Usage: %s <portnum>\n", strings[0]);
exit(0);
}
else
{
printf("Usage: %s <portnum>\n", strings[1]);
}
SSL_library_init();
portnum = strings[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "/home/stud/kawsar/mycert.pem", "/home/stud/kawsar/mycert.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
| 29.736527 | 108 | 0.594442 | fasShare |
31fcf4e81b3f3cf3db97cdb905df7fa14a19d415 | 376 | cpp | C++ | Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp | riki00000/NOI-Compets-2008 | 8916dc9266c0b68853944a0c75d133dc08e0d00a | [
"MIT"
] | null | null | null | Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp | riki00000/NOI-Compets-2008 | 8916dc9266c0b68853944a0c75d133dc08e0d00a | [
"MIT"
] | null | null | null | Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp | riki00000/NOI-Compets-2008 | 8916dc9266c0b68853944a0c75d133dc08e0d00a | [
"MIT"
] | 1 | 2019-02-27T16:16:17.000Z | 2019-02-27T16:16:17.000Z | #include <iostream>
using namespace std;
int main()
{ int a,b,c;
cin>>a>>b>>c;
if (a == 1) cout<<"(\\_/)\n";
else if (a == 2) cout<<"(o.o)\n";
else if (a == 3) cout<<"(_._)\n";
if (b == 1) cout<<"(\\_/)\n";
else if (b == 2) cout<<"(o.o)\n";
else if (b == 3) cout<<"(_._)\n";
if (c == 1) cout<<"(\\_/)\n";
else if (c == 2) cout<<"(o.o)\n";
else if (c == 3) cout<<"(_._)\n";
}
| 23.5 | 34 | 0.454787 | riki00000 |
ee01f01a415005bdbfbf3b595d82a1f10ede00c5 | 15,926 | cpp | C++ | src/DesignRuleChecker.cpp | k2973363/PcbRouter | ec7befb1ff924dbe398cccb93088ccbbfff9dfd8 | [
"BSD-3-Clause"
] | 11 | 2020-02-13T22:15:53.000Z | 2021-11-04T02:37:46.000Z | src/DesignRuleChecker.cpp | k2973363/PcbRouter | ec7befb1ff924dbe398cccb93088ccbbfff9dfd8 | [
"BSD-3-Clause"
] | 4 | 2019-12-23T17:17:05.000Z | 2020-11-04T16:05:42.000Z | src/DesignRuleChecker.cpp | k2973363/PcbRouter | ec7befb1ff924dbe398cccb93088ccbbfff9dfd8 | [
"BSD-3-Clause"
] | 7 | 2020-05-23T01:49:19.000Z | 2021-09-08T09:56:34.000Z | #include "DesignRuleChecker.h"
int DesignRuleChecker::checkAcuteAngleViolationBetweenTracesAndPads() {
std::cout << "Starting " << __FUNCTION__ << "()..." << std::endl;
std::cout << std::fixed << std::setprecision((int)round(std::log(mInputPrecision)));
int numViolations = 0;
// Iterate nets
for (auto &net : mDb.getNets()) {
if (GlobalParam::gVerboseLevel <= VerboseLevel::DEBUG) {
std::cout << "\nNet: " << net.getName() << ", netId: " << net.getId() << ", netDegree: " << net.getPins().size() << "..." << std::endl;
}
auto &pins = net.getPins();
for (auto &pin : pins) {
// DB elements
auto &comp = mDb.getComponent(pin.getCompId());
auto &inst = mDb.getInstance(pin.getInstId());
auto &pad = comp.getPadstack(pin.getPadstackId());
// Handle GridPin's pinPolygon, which should be expanded by clearance
Point_2D<double> polyPadSize = pad.getSize();
Point_2D<double> pinDbLocation;
mDb.getPinPosition(pad, inst, &pinDbLocation);
// Get a exact locations expanded polygon in db's coordinates
std::vector<Point_2D<double>> exactDbLocPadPoly;
if (pad.getPadShape() == padShape::CIRCLE || pad.getPadShape() == padShape::OVAL) {
// WARNING!! shape_to_coords's pos can be origin only!!! Otherwise the rotate function will be wrong
exactDbLocPadPoly = shape_to_coords(polyPadSize, point_2d{0, 0}, padShape::CIRCLE, inst.getAngle(), pad.getAngle(), pad.getRoundRectRatio(), 32);
} else {
exactDbLocPadPoly = shape_to_coords(polyPadSize, point_2d{0, 0}, padShape::RECT, inst.getAngle(), pad.getAngle(), pad.getRoundRectRatio(), 32);
}
// Shift to exact location
for (auto &&pt : exactDbLocPadPoly) {
pt.m_x += pinDbLocation.m_x;
pt.m_y += pinDbLocation.m_y;
}
// Transform this into Boost's polygon in db's coordinates
polygon_double_t exactLocGridPadShapePoly;
for (const auto &pt : exactDbLocPadPoly) {
bg::append(exactLocGridPadShapePoly.outer(), point_double_t(pt.x(), pt.y()));
}
bg::correct(exactLocGridPadShapePoly);
// box_double_t pinBoundingBox;
// bg::envelope(exactLocGridPadShapePoly, pinBoundingBox);
// std::cout << "Pin's Polygon: " << boost::geometry::wkt(exactLocGridPadShapePoly) << std::endl;
//Iterate all the segments
for (auto &seg : net.getSegments()) {
if (!isPadstackAndSegmentHaveSameLayer(inst, pad, seg)) {
continue;
}
points_2d &points = seg.getPos();
if (points.size() < 2) {
std::cout << __FUNCTION__ << "(): Invalid # segment's points." << std::endl;
continue;
}
linestring_double_t bgLs{point_double_t(points[0].x(), points[0].y()), point_double_t(points[1].x(), points[1].y())};
// std::cout << "Seg: (" << bg::get<0>(bgLs.front()) << ", " << bg::get<1>(bgLs.front())
// << "), (" << bg::get<0>(bgLs.back()) << ", " << bg::get<1>(bgLs.back()) << ")" << std::endl;
if (bg::crosses(bgLs, exactLocGridPadShapePoly)) {
Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)};
Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)};
if (pad.getPadShape() == padShape::RECT) {
if (!isOrthogonalSegment(pt1, pt2)) {
// Get intersection point
std::vector<point_double_t> intersectPts;
bg::intersection(bgLs, exactLocGridPadShapePoly, intersectPts);
if (!intersectPts.empty()) {
if (!isIntersectionPointOnTheBoxCorner(intersectPts.front(), exactLocGridPadShapePoly, seg.getWidth(), mAcuteAngleTol)) {
std::cout << __FUNCTION__ << "(): Violation between segment: ("
<< points[0].x() << ", " << points[0].y() << "), ("
<< points[1].x() << ", " << points[1].y() << "), width: "
<< seg.getWidth() << ", and rectangle pad center at "
<< pinDbLocation.x() << ", " << pinDbLocation.y() << std::endl;
++numViolations;
}
}
}
} else if (pad.getPadShape() == padShape::CIRCLE) {
point_double_t center{pinDbLocation.x(), pinDbLocation.y()};
if (!isSegmentTouchAPoint(bgLs, center, seg.getWidth())) {
std::cout << __FUNCTION__ << "(): Violation between segment: ("
<< points[0].x() << ", " << points[0].y() << "), ("
<< points[1].x() << ", " << points[1].y() << ") and circle pad center at "
<< pinDbLocation.x() << ", " << pinDbLocation.y() << std::endl;
++numViolations;
}
}
}
}
}
}
std::cout << "Total # acute angle violations: " << numViolations << std::endl;
std::cout << "End of " << __FUNCTION__ << "()..." << std::endl;
return numViolations;
}
int DesignRuleChecker::checkTJunctionViolation() {
std::cout << "Starting " << __FUNCTION__ << "()..." << std::endl;
std::cout << std::fixed << std::setprecision((int)round(std::log(mInputPrecision)));
int numViolations = 0;
std::vector<TJunctionPatch> patches;
// Iterate nets
for (auto &net : mDb.getNets()) {
// if (net.getId() != 27) continue;
if (GlobalParam::gVerboseLevel <= VerboseLevel::DEBUG) {
std::cout << "\nNet: " << net.getName() << ", netId: " << net.getId() << ", netDegree: " << net.getPins().size() << "..." << std::endl;
}
for (int segId = 0; segId < net.getSegments().size(); ++segId) {
for (int segId2 = segId + 1; segId2 < net.getSegments().size(); ++segId2) {
auto &seg1 = net.getSegment(segId);
auto &seg2 = net.getSegment(segId2);
if (seg1.getLayer() != seg2.getLayer()) {
continue;
}
points_2d &ptsSeg1 = seg1.getPos();
points_2d &ptsSeg2 = seg2.getPos();
if (ptsSeg1.size() < 2 || ptsSeg2.size() < 2) {
std::cout << __FUNCTION__ << "(): Invalid # segment's points." << std::endl;
continue;
}
linestring_double_t bgLs1{point_double_t(ptsSeg1[0].x(), ptsSeg1[0].y()), point_double_t(ptsSeg1[1].x(), ptsSeg1[1].y())};
linestring_double_t bgLs2{point_double_t(ptsSeg2[0].x(), ptsSeg2[0].y()), point_double_t(ptsSeg2[1].x(), ptsSeg2[1].y())};
if (areConnectedSegments(bgLs1, bgLs2)) {
continue;
}
// Check if is T-Junction
++numViolations;
double patchSize = seg1.getWidth() * 2.0;
polygon_double_t patchPoly;
if (bg::distance(bgLs1.back(), bgLs2) < mTJunctionEpsilon) {
std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg1[1].x() << ", " << ptsSeg1[1].y() << ")" << std::endl;
addTJunctionPatch(bgLs1.back(), bgLs1, bgLs2, patchSize, patchPoly);
} else if (bg::distance(bgLs1.front(), bgLs2) < mTJunctionEpsilon) {
std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg1[0].x() << ", " << ptsSeg1[0].y() << ")" << std::endl;
addTJunctionPatch(bgLs1.front(), bgLs1, bgLs2, patchSize, patchPoly);
} else if (bg::distance(bgLs2.front(), bgLs1) < mTJunctionEpsilon) {
std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg2[0].x() << ", " << ptsSeg2[0].y() << ")" << std::endl;
addTJunctionPatch(bgLs2.front(), bgLs2, bgLs1, patchSize, patchPoly);
} else if (bg::distance(bgLs2.back(), bgLs1) < mTJunctionEpsilon) {
std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg2[1].x() << ", " << ptsSeg2[1].y() << ")" << std::endl;
addTJunctionPatch(bgLs2.back(), bgLs2, bgLs1, patchSize, patchPoly);
} else {
--numViolations;
}
if (!bg::is_empty(patchPoly)) {
patches.emplace_back(TJunctionPatch{patchPoly, seg1.getLayer(), seg1.getNetId()});
}
}
}
}
printTJunctionPatchToKiCadZone(patches);
std::cout << "Total # T-Junction violations: " << numViolations << std::endl;
std::cout << "End of " << __FUNCTION__ << "()..." << std::endl;
return numViolations;
}
void DesignRuleChecker::printTJunctionPatchToKiCadZone(std::vector<TJunctionPatch> &patches) {
// Print all the patches in KiCadPcbFormat
for (const auto &patch : patches) {
std::cout << "( zone ( net 0 )";
std::cout << "( polygon ( pts ";
// ( xy 148.9585 131.8135 )
for (auto it = boost::begin(bg::exterior_ring(patch.poly)); it != boost::end(bg::exterior_ring(patch.poly)); ++it) {
auto x = bg::get<0>(*it);
auto y = bg::get<1>(*it);
std::cout << "( xy " << x << " " << y << ") ";
}
std::cout << ")";
std::cout << ")";
std::cout << ")";
std::cout << std::endl;
}
}
void DesignRuleChecker::addTJunctionPatch(const point_double_t &point, const linestring_double_t &bgLs1, const linestring_double_t &bgLs2, const double size, polygon_double_t &patchPoly) {
std::cout << "Add T-Junction Patch at: " << std::endl;
std::cout << "Seg1: (" << bg::get<0>(bgLs1.front()) << ", " << bg::get<1>(bgLs1.front())
<< "), (" << bg::get<0>(bgLs1.back()) << ", " << bg::get<1>(bgLs1.back()) << ")" << std::endl;
std::cout << "Seg2: (" << bg::get<0>(bgLs2.front()) << ", " << bg::get<1>(bgLs2.front())
<< "), (" << bg::get<0>(bgLs2.back()) << ", " << bg::get<1>(bgLs2.back()) << ")" << std::endl;
std::cout << "bg::distance(bgLs1.back(), bgLs2): " << bg::distance(bgLs1.back(), bgLs2) << std::endl;
std::cout << "bg::distance(bgLs1.front(), bgLs2): " << bg::distance(bgLs1.front(), bgLs2) << std::endl;
std::cout << "bg::distance(bgLs2.front(), bgLs1): " << bg::distance(bgLs2.front(), bgLs1) << std::endl;
std::cout << "bg::distance(bgLs2.back(), bgLs1): " << bg::distance(bgLs2.back(), bgLs1) << std::endl;
// First Point
point_2d vec{bg::get<0>(bgLs2.front()) - bg::get<0>(point), bg::get<1>(bgLs2.front()) - bg::get<1>(point)};
double vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y());
point_2d unitVec{vec.x() / vecLen, vec.y() / vecLen};
double length = (size / 2.0);
if (length < vecLen) {
bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length));
} else {
bg::append(patchPoly.outer(), bgLs2.front());
}
// Seoncd Point
vec = point_2d{bg::get<0>(bgLs2.back()) - bg::get<0>(point), bg::get<1>(bgLs2.back()) - bg::get<1>(point)};
vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y());
unitVec = point_2d{vec.x() / vecLen, vec.y() / vecLen};
length = (size / 2.0);
if (length < vecLen) {
bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length));
} else {
bg::append(patchPoly.outer(), bgLs2.back());
}
// Third Point
point_double_t point2 = bg::distance(bgLs1.front(), point) > bg::distance(bgLs1.back(), point) ? bgLs1.front() : bgLs1.back();
vec = point_2d{bg::get<0>(point2) - bg::get<0>(point), bg::get<1>(point2) - bg::get<1>(point)};
vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y());
unitVec = point_2d{vec.x() / vecLen, vec.y() / vecLen};
length = ((size / 2.0) * sqrt(3));
if (length < vecLen) {
bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length));
} else {
bg::append(patchPoly.outer(), point2);
}
bg::correct(patchPoly);
}
bool DesignRuleChecker::areConnectedSegments(linestring_double_t &ls1, linestring_double_t &ls2) {
double minDis = numeric_limits<double>::max();
minDis = min(minDis, bg::distance(ls1.front(), ls2.front()));
minDis = min(minDis, bg::distance(ls1.front(), ls2.back()));
minDis = min(minDis, bg::distance(ls1.back(), ls2.back()));
minDis = min(minDis, bg::distance(ls1.back(), ls2.front()));
return minDis < this->mEpsilon;
}
bool DesignRuleChecker::isSegmentTouchAPoint(linestring_double_t &ls, point_double_t &point, double wireWidth) {
double minDis = numeric_limits<double>::max();
minDis = min(minDis, bg::distance(point, ls.front()));
minDis = min(minDis, bg::distance(point, ls.back()));
return minDis < (wireWidth / 2.0);
}
bool DesignRuleChecker::isIntersectionPointOnTheBoxCorner(point_double_t &point, polygon_double_t &poly, double wireWidth, double tol) {
//See if minimum distance to the corner is within half wire width
double minDis = numeric_limits<double>::max();
for (auto it = boost::begin(bg::exterior_ring(poly)); it != boost::end(bg::exterior_ring(poly)); ++it) {
minDis = min(minDis, bg::distance(point, *it));
}
return minDis < ((wireWidth / 2.0) * GlobalParam::gSqrt2 * (1 + tol));
// return minDis < (wireWidth / 2.0) * GlobalParam::gSqrt2;
}
bool DesignRuleChecker::isOrthogonalSegment(Point_2D<long long> &pt1, Point_2D<long long> &pt2) {
if ((pt1.x() == pt2.x() && pt1.y() != pt2.y()) ||
(pt1.x() != pt2.x() && pt2.y() == pt1.y())) {
return true;
}
return false;
}
bool DesignRuleChecker::isOrthogonalSegment(points_2d &points) {
Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)};
Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)};
return isOrthogonalSegment(pt1, pt2);
}
bool DesignRuleChecker::isDiagonalSegment(Point_2D<long long> &pt1, Point_2D<long long> &pt2) {
if (pt1.x() != pt2.x() && pt1.y() != pt2.y() && abs(pt1.x() - pt2.x()) == abs(pt1.y() - pt2.y())) {
return true;
}
return false;
}
bool DesignRuleChecker::isDiagonalSegment(points_2d &points) {
Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)};
Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)};
return isDiagonalSegment(pt1, pt2);
}
bool DesignRuleChecker::isPadstackAndSegmentHaveSameLayer(instance &inst, padstack &pad, Segment &seg) {
auto pinLayers = mDb.getPinLayer(inst.getId(), pad.getId());
for (const auto layerId : pinLayers) {
if (layerId == mDb.getLayerId(seg.getLayer())) {
return true;
}
}
return false;
} | 51.374194 | 188 | 0.538867 | k2973363 |
ee02f664246c6cfa29fe97715ec872f61385bd8c | 380 | cpp | C++ | tram.cpp | piyushmishra12/codeforces-practice | 4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f | [
"MIT"
] | null | null | null | tram.cpp | piyushmishra12/codeforces-practice | 4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f | [
"MIT"
] | null | null | null | tram.cpp | piyushmishra12/codeforces-practice | 4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n, i;
cin>> n;
int enter[n], exit[n], net_enter[n];
for(i = 0; i < n; i++)
{
cin>> exit[i];
cin>> enter[i];
}
net_enter[0] = enter[0];
for(i = 1; i < n; i++)
{
net_enter[i] = net_enter[i - 1] - exit[i] + enter[i];
}
sort(net_enter, net_enter + n);
cout<< net_enter[n - 1];
return 0;
} | 17.272727 | 55 | 0.563158 | piyushmishra12 |
ee093f7c722eee7467fd46465a2a21fd56584c3b | 334 | hpp | C++ | include/Node.hpp | Algorithms-and-Data-Structures-2021/semester-work-suffix-tree | a91dcaa869cd2c144869901247d16199e027e141 | [
"MIT"
] | null | null | null | include/Node.hpp | Algorithms-and-Data-Structures-2021/semester-work-suffix-tree | a91dcaa869cd2c144869901247d16199e027e141 | [
"MIT"
] | null | null | null | include/Node.hpp | Algorithms-and-Data-Structures-2021/semester-work-suffix-tree | a91dcaa869cd2c144869901247d16199e027e141 | [
"MIT"
] | 1 | 2021-05-22T19:20:20.000Z | 2021-05-22T19:20:20.000Z | #pragma once
#include "SuffixTree.hpp"
#include "Constants.hpp"
#include <algorithm>
namespace itis {
struct Node {
int start, end, slink;
int next[ALPHABET_SIZE]; // if there is an edge from node starting with certain ASCII letter
int edge_length(int pos) {
return std::min(end, pos + 1) - start;
}
};
}
| 19.647059 | 96 | 0.661677 | Algorithms-and-Data-Structures-2021 |
ee0ce34ba34e86595c7861d9bacbddab83798457 | 1,494 | cpp | C++ | LongestPalindromicSubstring.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | LongestPalindromicSubstring.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | LongestPalindromicSubstring.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
class Solution {
private:
const char sep_char = '\1';
public:
string longestPalindrome(string s) {
int max_len = 0;
int len = s.length();
if (len <= 1) return s;
string str;
str.push_back(sep_char);
for (int i=0; i<len; i++) {
str.push_back(s[i]);
str.push_back(sep_char);
}
cout<<str<<endl;
int nlen = 2 * len + 1;
vector<int> P(nlen, 0);
int last_i = 0;
int last_r = 0;
int maxv = -1;
int maxi = -1;
for (int i=0; i<nlen; i++) {
int p = i, q = i;
if (i < last_r) {
int j = 2 * last_i - i; // (i + j) / 2 = last_i
int slen = min(P[j], last_r - i);
p-= slen;
q+= slen;
}
while(p >= 0 && q < nlen && str[p] == str[q]) p--, q++;
if (q > last_r) {
last_r = q;
last_i = i;
}
P[i] = q - i;
if (P[i] > maxv) {
maxv = P[i];
maxi = i;
}
}
return s.substr((maxi + 1 - P[maxi]) / 2, P[maxi] - 1);
}
};
int main() {
string str("missing");
Solution s;
cout<<s.longestPalindrome(str)<<endl;
system("pause");
return 0;
}
| 21.652174 | 67 | 0.394913 | hgfeaon |
ee0d1fc6705ab1343fd8846b3e0a89896f6e86e8 | 1,675 | hpp | C++ | graph/edmonds_karp.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | 7 | 2019-04-30T14:25:40.000Z | 2020-12-19T17:38:11.000Z | graph/edmonds_karp.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | 46 | 2018-09-19T16:42:09.000Z | 2020-05-07T09:05:08.000Z | graph/edmonds_karp.hpp | fumiphys/programming_contest | b9466e646045e1c64571af2a1e64813908e70841 | [
"MIT"
] | null | null | null | /*
* Library for Edmonds Karp
*/
#ifndef _EDMONDS_KARP_H_
#define _EDMONDS_KARP_H_
#include <climits>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <limits>
using namespace std;
template <typename T>
struct edge {int to; T cap; int rev;};
template <typename T>
struct Graph{
int n;
vector<vector<edge<T>>> vec;
Graph(int n): n(n){
vec.resize(n);
}
void adde(int at, int to, T cap){
vec[at].push_back((edge<T>){to, cap, (int)vec[to].size()});
vec[to].push_back((edge<T>){at, 0, (int)vec[at].size() - 1});
}
T max_flow(int s, int t){
T f = 0;
while(true){
queue<int> q;
q.push(s);
vector<pair<int, int>> prev(n, make_pair(-1, -1));
prev[s] = make_pair(s, -1);
while(!q.empty() && prev[t].first < 0){
auto p = q.front(); q.pop();
for(int i = 0; i < vec[p].size(); i++){
auto e = vec[p][i];
if(prev[e.to].first < 0 && e.cap > 0){
prev[e.to] = make_pair(p, i);
q.push(e.to);
}
}
}
if(prev[t].first < 0)return f;
T mini = numeric_limits<T>::max();
for(int i = t; prev[i].first != i; i = prev[i].first){
int p = prev[i].first;
auto e = vec[p][prev[i].second];
mini = min(mini, e.cap);
}
for(int i = t; prev[i].first != i; i = prev[i].first){
int p = prev[i].first;
auto& e = vec[p][prev[i].second];
e.cap -= mini;
vec[i][e.rev].cap += mini;
}
f += mini;
}
}
T min_cut(int s, int t){
return max_flow(s, t);
}
};
using GraphI = Graph<int>;
using GraphL = Graph<long long>;
#endif
| 23.928571 | 65 | 0.518806 | fumiphys |
ee0e95c13a708e09aa3b0df85bc3e3bc0c3a3349 | 6,194 | cc | C++ | src/xzero/http/hpack/Parser-test.cc | pjsaksa/x0 | 96b69e5a54b006e3d929b9934c2708f7967371bb | [
"MIT"
] | 24 | 2016-07-10T08:05:11.000Z | 2021-11-16T10:53:48.000Z | src/xzero/http/hpack/Parser-test.cc | pjsaksa/x0 | 96b69e5a54b006e3d929b9934c2708f7967371bb | [
"MIT"
] | 14 | 2015-04-12T10:45:26.000Z | 2016-06-28T22:27:50.000Z | src/xzero/http/hpack/Parser-test.cc | pjsaksa/x0 | 96b69e5a54b006e3d929b9934c2708f7967371bb | [
"MIT"
] | 4 | 2016-10-05T17:51:38.000Z | 2020-04-20T07:45:23.000Z | // This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2018 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/http/hpack/Parser.h>
#include <xzero/http/HeaderFieldList.h>
#include <xzero/testing.h>
#include <optional>
using namespace xzero;
using namespace xzero::http;
using namespace xzero::http::hpack;
TEST(hpack_Parser, decodeInt) {
DynamicTable dt(4096);
Parser parser(&dt, 4096, nullptr);
uint8_t helloInt[4] = {0};
uint8_t* helloIntEnd = helloInt + 4;
uint64_t decodedInt = 0;
/* (C.1.1) Example 1: Encoding 10 Using a 5-Bit Prefix
*
* 0 1 2 3 4 5 6 7
* +---+---+---+---+---+---+---+---+
* | X | X | X | 0 | 1 | 0 | 1 | 0 | 10 stored on 5 bits
* +---+---+---+---+---+---+---+---+
*/
helloInt[0] = 0b00001010;
size_t nparsed = Parser::decodeInt(5, &decodedInt, helloInt, helloIntEnd);
ASSERT_EQ(1, nparsed);
ASSERT_EQ(10, decodedInt);
/* (C.1.2) Example 2: Encoding 1337 Using a 5-Bit Prefix
*
* 0 1 2 3 4 5 6 7
* +---+---+---+---+---+---+---+---+
* | X | X | X | 1 | 1 | 1 | 1 | 1 | Prefix = 31, I = 1306
* | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1306>=128, encode(154), I=1306/128
* | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 10<128, encode(10), done
* +---+---+---+---+---+---+---+---+
*/
helloInt[0] = 0b00011111;
helloInt[1] = 0b10011010;
helloInt[2] = 0b00001010;
nparsed = Parser::decodeInt(5, &decodedInt, helloInt, helloIntEnd);
ASSERT_EQ(3, nparsed);
ASSERT_EQ(1337, decodedInt);
/* (C.1.3) Example 3: Encoding 42 Starting at an Octet Boundary
*
* 0 1 2 3 4 5 6 7
* +---+---+---+---+---+---+---+---+
* | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 42 stored on 8 bits
* +---+---+---+---+---+---+---+---+
*/
helloInt[0] = 0b00101010;
nparsed = Parser::decodeInt(8, &decodedInt, helloInt, helloIntEnd);
ASSERT_EQ(1, nparsed);
ASSERT_EQ(42, decodedInt);
}
TEST(hpack_Parser, decodeString) {
std::string decoded;
size_t nparsed;
const uint8_t empty[] = {0x00};
nparsed = Parser::decodeString(&decoded, empty, std::end(empty));
ASSERT_EQ(1, nparsed);
ASSERT_EQ("", decoded);
const uint8_t hello[] = { 0x05, 'H', 'e', 'l', 'l', 'o' };
nparsed = Parser::decodeString(&decoded, hello, std::end(hello));
ASSERT_EQ(6, nparsed);
ASSERT_EQ("Hello", decoded);
}
TEST(hpack_Parser, literalHeaderFieldWithIndex) {
/* C.2.1 Literal Header Field with Indexing
*
* custom-key: custom-header
*
* 400a 6375 7374 6f6d 2d6b 6579 0d63 7573 | @.custom-key.cus
* 746f 6d2d 6865 6164 6572 | tom-header
*/
uint8_t block[] = {
0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65,
0x79, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x68, 0x65,
0x61, 0x64, 0x65, 0x72 };
std::string name;
std::string value;
std::optional<bool> sensitive;
auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) {
name = _name;
value = _value;
sensitive = s;
};
DynamicTable dt(4096);
Parser parser(&dt, 4096, gotcha);
size_t nparsed = parser.parse(block, std::end(block));
ASSERT_EQ(26, nparsed);
ASSERT_EQ("custom-key", name);
ASSERT_EQ("custom-header", value);
ASSERT_TRUE(sensitive.has_value());
ASSERT_FALSE(sensitive.value());
}
TEST(hpack_Parser, literalHeaderWithoutIndexing) {
/* C.2.2 Literal Header Field without Indexing
*
* :path: /sample/path
*
* 040c 2f73 616d 706c 652f 7061 7468 | ../sample/path
*/
uint8_t block[] = {
0x04, 0x0c, 0x2f, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f,
0x70, 0x61, 0x74, 0x68 };
std::string name;
std::string value;
std::optional<bool> sensitive;
auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) {
name = _name;
value = _value;
sensitive = s;
};
DynamicTable dt(4096);
Parser parser(&dt, 4096, gotcha);
size_t nparsed = parser.parse(block, std::end(block));
ASSERT_EQ(14, nparsed);
ASSERT_EQ(":path", name);
ASSERT_EQ("/sample/path", value);
ASSERT_TRUE(sensitive.has_value());
ASSERT_FALSE(sensitive.value());
}
TEST(hpack_Parser, literalHeaderNeverIndex) {
/* C.2.3 Literal Header Field Never Indexed
*
* password: secret
*/
uint8_t block[] = {
0x10, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64,
0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74 };
std::string name;
std::string value;
std::optional<bool> sensitive;
auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) {
name = _name;
value = _value;
sensitive = s;
};
DynamicTable dt(4096);
Parser parser(&dt, 4096, gotcha);
size_t nparsed = parser.parse(block, std::end(block));
ASSERT_EQ(17, nparsed);
ASSERT_EQ("password", name);
ASSERT_EQ("secret", value);
ASSERT_TRUE(sensitive.has_value());
ASSERT_TRUE(sensitive.value());
}
TEST(hpack_Parser, literalHeaderFieldFromIndex) {
/* C.2.4 Indexed Header Field
*
* :method: GET
*
* 82
*/
uint8_t block[] = { 0x82 };
std::string name;
std::string value;
std::optional<bool> sensitive;
auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) {
name = _name;
value = _value;
sensitive = s;
};
DynamicTable dt(4096);
Parser parser(&dt, 4096, gotcha);
size_t nparsed = parser.parse(block, std::end(block));
ASSERT_EQ(1, nparsed);
ASSERT_EQ(":method", name);
ASSERT_EQ("GET", value);
ASSERT_TRUE(sensitive.has_value());
ASSERT_FALSE(sensitive.value());
}
TEST(hpack_Parser, updateTableSize) {
uint8_t block[] = { 0x25 };
DynamicTable dt(4096);
Parser parser(&dt, 4096, nullptr);
size_t nparsed = parser.parse(block, std::end(block));
ASSERT_EQ(1, nparsed);
ASSERT_EQ(5, parser.internalMaxSize());
}
// TODO: C.3.x three requests without huffman coding
// TODO: C.4.x three requests with huffman coding
| 27.775785 | 82 | 0.611075 | pjsaksa |
ee17950bcdf71de7b006e8586be7abefaf3b17ff | 2,343 | cc | C++ | src/tools/binary_errors.cc | walkingeyerobot/wasp | 882f051f61af14308829686fa2b79f864ea1009d | [
"Apache-2.0"
] | 47 | 2020-10-24T18:29:12.000Z | 2022-03-31T02:08:17.000Z | src/tools/binary_errors.cc | walkingeyerobot/wasp | 882f051f61af14308829686fa2b79f864ea1009d | [
"Apache-2.0"
] | 27 | 2020-10-23T17:12:48.000Z | 2021-09-09T18:02:24.000Z | src/tools/binary_errors.cc | walkingeyerobot/wasp | 882f051f61af14308829686fa2b79f864ea1009d | [
"Apache-2.0"
] | 13 | 2020-10-23T06:28:12.000Z | 2022-03-14T10:08:01.000Z | //
// Copyright 2020 WebAssembly Community Group participants
//
// 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 "src/tools/binary_errors.h"
#include <iostream>
#include <utility>
#include "absl/strings/str_format.h"
namespace wasp::tools {
BinaryErrors::BinaryErrors(SpanU8 data) : BinaryErrors{"<unknown>", data} {}
BinaryErrors::BinaryErrors(string_view filename, SpanU8 data)
: filename{filename}, data{data} {}
void BinaryErrors::PrintTo(std::ostream& os) {
for (const auto& error : errors) {
os << ErrorToString(error);
}
}
void BinaryErrors::HandlePushContext(Location loc, string_view desc) {}
void BinaryErrors::HandlePopContext() {}
void BinaryErrors::HandleOnError(Location loc, string_view message) {
errors.push_back(Error{loc, std::string(message)});
}
auto BinaryErrors::ErrorToString(const Error& error) const -> std::string {
auto& loc = error.loc;
const ptrdiff_t before = 4, after = 8, max_size = 32;
size_t start = std::max(before, loc.begin() - data.begin()) - before;
size_t end = data.size() - std::max(after, data.end() - loc.end()) + after;
end = std::min(end, start + max_size);
Location context = MakeSpan(data.begin() + start, data.begin() + end);
std::string line1 = " ";
std::string line2 = " ";
bool space = false;
for (auto iter = context.begin(); iter < context.end(); ++iter) {
u8 x = *iter;
line1 += absl::StrFormat("%02x", x);
if (iter >= loc.begin() && iter < loc.end()) {
line2 += "^^";
} else {
line2 += " ";
}
if (space) {
line1 += ' ';
line2 += ' ';
}
space = !space;
}
return absl::StrFormat("%s:%08x: %s\n%s\n%s\n", filename,
loc.begin() - data.begin(), error.message, line1,
line2);
}
} // namespace wasp::tools
| 29.658228 | 77 | 0.647887 | walkingeyerobot |
ee1ea1d4d631eccf7690ba030ace94510499911a | 5,456 | cpp | C++ | src/util/sll/regexp.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/util/sll/regexp.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/util/sll/regexp.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "regexp.h"
#include <QDataStream>
#include <QtDebug>
#ifdef USE_PCRE
#include <pcre.h>
#else
#include <QRegExp>
#endif
namespace LeechCraft
{
namespace Util
{
#ifdef USE_PCRE
#ifndef PCRE_STUDY_JIT_COMPILE
#define PCRE_STUDY_JIT_COMPILE 0
#endif
class PCREWrapper
{
pcre *RE_;
pcre_extra *Extra_;
QString Pattern_;
Qt::CaseSensitivity CS_;
public:
PCREWrapper ()
: RE_ (0)
, Extra_ (0)
{
}
PCREWrapper (const QString& str, Qt::CaseSensitivity cs)
: RE_ (Compile (str, cs))
, Extra_ (0)
, Pattern_ (str)
, CS_ (cs)
{
if (RE_)
{
pcre_refcount (RE_, 1);
const char *error = 0;
const int opts = PCRE_STUDY_JIT_COMPILE;
Extra_ = pcre_study (RE_, opts, &error);
}
}
PCREWrapper (const PCREWrapper& other)
: RE_ (0)
, Extra_ (0)
{
*this = other;
}
PCREWrapper& operator= (const PCREWrapper& other)
{
if (RE_ && !pcre_refcount (RE_, -1))
{
FreeStudy ();
pcre_free (RE_);
}
RE_ = other.RE_;
Extra_ = other.Extra_;
if (RE_)
pcre_refcount (RE_, 1);
return *this;
}
~PCREWrapper ()
{
if (!RE_)
return;
if (!pcre_refcount (RE_, -1))
{
FreeStudy ();
pcre_free (RE_);
}
}
const QString& GetPattern () const
{
return Pattern_;
}
Qt::CaseSensitivity GetCS () const
{
return CS_;
}
int Exec (const QByteArray& utf8) const
{
return RE_ ? pcre_exec (RE_, Extra_, utf8.constData (), utf8.size (), 0, 0, NULL, 0) : -1;
}
private:
pcre* Compile (const QString& str, Qt::CaseSensitivity cs)
{
const char *error = 0;
int errOffset = 0;
int options = PCRE_UTF8;
if (cs == Qt::CaseInsensitive)
options |= PCRE_CASELESS;
auto re = pcre_compile (str.toUtf8 ().constData (), options, &error, &errOffset, NULL);
if (!re)
qWarning () << Q_FUNC_INFO
<< "failed compiling"
<< str
<< error;
return re;
}
void FreeStudy ()
{
if (Extra_)
#ifdef PCRE_CONFIG_JIT
pcre_free_study (Extra_);
#else
pcre_free (Extra_);
#endif
}
};
#endif
namespace
{
struct RegExpRegisterGuard
{
RegExpRegisterGuard ()
{
qRegisterMetaType<RegExp> ("Util::RegExp");
qRegisterMetaTypeStreamOperators<RegExp> ();
}
} Guard;
}
struct RegExpImpl
{
#if USE_PCRE
PCREWrapper PRx_;
#else
QRegExp Rx_;
#endif
};
bool RegExp::IsFast ()
{
#ifdef USE_PCRE
return true;
#else
return false;
#endif
}
RegExp::RegExp (const QString& str, Qt::CaseSensitivity cs)
#ifdef USE_PCRE
: Impl_ { new RegExpImpl { { str, cs } } }
#else
: Impl_ { new RegExpImpl { QRegExp { str, cs, QRegExp::RegExp } } }
#endif
{
}
bool RegExp::Matches (const QString& str) const
{
if (!Impl_)
return {};
#ifdef USE_PCRE
return Impl_->PRx_.Exec (str.toUtf8 ()) >= 0;
#else
return Impl_->Rx_.exactMatch (str);
#endif
}
QString RegExp::GetPattern () const
{
if (!Impl_)
return {};
#ifdef USE_PCRE
return Impl_->PRx_.GetPattern ();
#else
return Impl_->Rx_.pattern ();
#endif
}
Qt::CaseSensitivity RegExp::GetCaseSensitivity () const
{
if (!Impl_)
return {};
#ifdef USE_PCRE
return Impl_->PRx_.GetCS ();
#else
return Impl_->Rx_.caseSensitivity ();
#endif
}
}
}
QDataStream& operator<< (QDataStream& out, const LeechCraft::Util::RegExp& rx)
{
out << static_cast<quint8> (1);
out << rx.GetPattern ()
<< static_cast<quint8> (rx.GetCaseSensitivity ());
return out;
}
QDataStream& operator>> (QDataStream& in, LeechCraft::Util::RegExp& rx)
{
quint8 version = 0;
in >> version;
if (version != 1)
{
qWarning () << Q_FUNC_INFO
<< "unknown version"
<< version;
return in;
}
QString pattern;
quint8 cs;
in >> pattern
>> cs;
rx = LeechCraft::Util::RegExp { pattern, static_cast<Qt::CaseSensitivity> (cs) };
return in;
}
| 20.745247 | 93 | 0.649194 | MellonQ |
ee1ecca359fa54dde1bee94d93f2c071771ad0c4 | 22,690 | cpp | C++ | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | 4 | 2022-01-12T08:41:19.000Z | 2022-03-08T15:36:05.000Z | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | null | null | null | src/strpp.cpp | cjheath/strpp | 5de24ecdfbbb8aeb70a4144f50c5e7a13eb5711f | [
"MIT"
] | null | null | null | /*
* Unicode Strings
*
* String Value library:
* - By-value semantics with mutation
* - Thread-safe content sharing and garbage collection using atomic reference counting
* - Substring support using "slices" (substrings using shared content)
* - Unicode support using UTF-8
* - Character indexing, not byte offsets
* - Efficient forward and backward scanning using bookmarks to assist
*
* A shared string is never mutated. Mutation is allowed when only one reference exists.
* Mutating methods clone (unshare) a shared string before making changes.
*
* (c) Copyright Clifford Heath 2022. See LICENSE file for usage rights.
*/
#include <strpp.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
StrBody StrBody::nullBody("", false, 0, 0);
const StrVal StrVal::null;
// Empty string
StrVal::StrVal()
: body(&StrBody::nullBody)
, offset(0)
, num_chars(0)
{
}
// Normal copy constructor
StrVal::StrVal(const StrVal& s1)
: body(s1.body)
, offset(s1.offset)
, num_chars(s1.num_chars)
{
}
// A new reference to the same StrBody
StrVal::StrVal(StrBody* s1)
: body(s1)
, offset(0)
, num_chars(s1->numChars())
{
}
StrVal::StrVal(StrBody* s1, CharNum offs, CharNum len)
: body(s1)
, offset(offs)
, num_chars(len)
{
}
// Assignment operator
StrVal& StrVal::operator=(const StrVal& s1)
{
body = s1.body;
offset = s1.offset;
num_chars = s1.num_chars;
return *this;
}
// Null-terminated UTF8 data
// Don't allocate a new StrBody for an empty string
StrVal::StrVal(const UTF8* data)
: body(data == 0 || data[0] == '\0' ? &StrBody::nullBody : new StrBody(data, true, strlen((const char*)data)))
, offset(0)
, num_chars(body->numChars())
{
}
// Length-terminated UTF8 data
StrVal::StrVal(const UTF8* data, CharBytes length, size_t allocate)
: body(0)
, offset(0)
, num_chars(0)
, mark()
{
if (allocate < length)
allocate = length;
body = new StrBody(data, true, length, allocate);
num_chars = body->numChars();
}
// Single-character string
StrVal::StrVal(UCS4 character)
: body(0)
, offset(0)
, num_chars(0)
{
UTF8 one_char[7];
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, character);
*op = '\0';
body = new StrBody(one_char, true, op-one_char, 1);
num_chars = 1;
}
// Get our own copy of StrBody that we can safely mutate
void
StrVal::Unshare()
{
if (body->GetRefCount() <= 1)
return;
// Copy only this slice of the body's data, and reset our offset to zero
Bookmark savemark(mark); // copy the bookmark
const UTF8* cp = nthChar(0); // start of this substring
const UTF8* ep = nthChar(num_chars); // end of this substring
CharBytes prefix_bytes = cp - body->startChar(); // How many leading bytes of the body we are eliding
body = new StrBody(cp, true, ep-cp, 0);
mark.char_num = savemark.char_num - offset; // Restore the bookmark
mark.byte_num = savemark.byte_num - prefix_bytes;
offset = 0;
}
// Access characters:
UCS4
StrVal::operator[](int charNum) const
{
const UTF8* cp = nthChar(charNum);
return cp ? UTF8Get(cp) : UCS4_NONE;
}
const UTF8*
StrVal::asUTF8() // Must unshare data if it's a substring with elided suffix
{
const UTF8* ep = nthChar(num_chars);
if (ep < body->endChar())
{
Unshare();
// If we are the last reference and a substring, we might not be terminated
*body->nthChar(num_chars, mark) = '\0';
}
return nthChar(0);
}
const UTF8*
StrVal::asUTF8(CharBytes& bytes) const
{
const UTF8* cp = nthChar(0);
const UTF8* ep = nthChar(num_chars);
bytes = ep-cp;
return cp;
}
// Compare strings using different styles
int
StrVal::compare(const StrVal& comparand, CompareStyle style) const
{
int cmp;
switch (style)
{
case CompareRaw:
cmp = memcmp(nthChar(0), comparand.nthChar(0), numBytes());
if (cmp == 0)
cmp = numBytes() - comparand.numBytes();
return cmp;
case CompareCI:
assert(!"REVISIT: Case-independent comparison is not implemented");
case CompareNatural:
assert(!"REVISIT: Natural comparison is not implemented");
default:
return 0;
}
}
// Delete a substring from the middle:
void
StrVal::remove(CharNum at, int len)
{
if (at >= num_chars || len == 0)
return; // Nothing to do
Unshare();
body->remove(at, len);
}
StrVal
StrVal::substr(CharNum at, int len) const
{
assert(len >= -1);
// Quick check for a null substring:
if (at < 0 || at >= num_chars || len == 0)
return StrVal();
// Clamp substring length:
if (len == -1)
len = num_chars-at;
else if (len > num_chars-at)
len = num_chars-at;
return StrVal(body, offset+at, len);
}
int
StrVal::find(UCS4 ch, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
if (ch == UTF8Get(up))
return n; // Found at n
n++;
}
return -1; // Not found
}
int
StrVal::rfind(UCS4 ch, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
if (ch == UTF8Get(bp))
return n; // Found at n
n--;
}
return -1; // Not found
}
// Search for substrings:
int
StrVal::find(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
CharNum last_start = num_chars-s1.length(); // Last possible start position
const UTF8* s1start = s1.nthChar(0);
const UTF8* up;
while (n <= last_start && (up = nthChar(n)) != 0)
{
if (memcmp(up, s1start, s1.numBytes()) == 0)
return n;
n++;
}
return -1;
}
int
StrVal::rfind(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-s1.length() : before-1; // First CharNum we'll look at
if (n > num_chars-s1.length())
n = num_chars-s1.length();
const UTF8* s1start = s1.nthChar(0);
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
if (memcmp(bp, s1start, s1.numBytes()) == 0)
return n;
n--;
}
return -1;
}
// Search for characters in set:
int
StrVal::findAny(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(up);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
return n; // Found at n
n++;
}
return -1; // Not found
}
int
StrVal::rfindAny(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(bp);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
return n;
n--;
}
return -1;
}
// Search for characters not in set:
int
StrVal::findNot(const StrVal& s1, int after) const
{
CharNum n = after+1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* up;
while ((up = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(up);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
goto next; // Found at n
return n;
next:
n++;
}
return -1; // Not found
}
int
StrVal::rfindNot(const StrVal& s1, int before) const
{
CharNum n = before == -1 ? num_chars-1 : before-1; // First CharNum we'll look at
const UTF8* s1start = s1.nthChar(0);
const UTF8* ep = s1.nthChar(s1.length()); // Byte after the last char in s1
const UTF8* bp;
while ((bp = nthChar(n)) != 0)
{
UCS4 ch = UTF8Get(bp);
for (const UTF8* op = s1start; op < ep; n++)
if (ch == UTF8Get(op))
goto next; // Found at n
return n;
next:
n--;
}
return -1;
}
// Add, producing a new StrVal:
StrVal
StrVal::operator+(const StrVal& addend) const
{
// Handle the rare but important case of extending a slice with a contiguous slice of the same body
if ((StrBody*)body == (StrBody*)addend.body // From the same body
&& offset+num_chars == addend.offset) // And this ends where the addend starts
return StrVal(body, offset, num_chars+addend.num_chars);
const UTF8* cp = nthChar(0);
CharBytes len = numBytes();
StrVal str(cp, len, len+addend.numBytes());
str += addend;
return str;
}
StrVal
StrVal::operator+(UCS4 addend) const
{
// Convert addend using a stack-local buffer to save allocation here.
UTF8 buf[7]; // Enough for 6-byte content plus a NUL
UTF8* cp = buf;
UTF8Put(cp, addend);
*cp = '\0';
StrBody body(buf, false, cp-buf, 1);
return operator+(StrVal(&body));
}
// Add, StrVal is modified:
StrVal&
StrVal::operator+=(const StrVal& addend)
{
if (num_chars == 0 && !addend.noCopy())
return *this = addend; // Just assign, we were empty anyhow
append(addend);
return *this;
}
StrVal&
StrVal::operator+=(UCS4 addend)
{
// Convert addend using a stack-local buffer to save allocation here.
UTF8 buf[7]; // Enough for 6-byte content plus a NUL
UTF8* cp = buf;
UTF8Put(cp, addend);
*cp = '\0';
StrBody body(buf, false, cp-buf, 1);
operator+=(StrVal(&body));
return *this;
}
void
StrVal::insert(CharNum pos, const StrVal& addend)
{
// Handle the rare but important case of extending a slice with a contiguous slice of the same body
if (pos == num_chars // Appending at the end
&& (StrBody*)body == (StrBody*)addend.body // From the same body
&& offset+pos == addend.offset) // And addend starts where we end
{
num_chars += addend.length();
return;
}
Unshare();
body->insert(pos, addend);
num_chars += addend.length();
}
void
StrVal::toLower()
{
Unshare();
body->toLower();
num_chars = body->numChars();
}
void
StrVal::toUpper()
{
Unshare();
body->toUpper();
num_chars = body->numChars();
}
static inline int
HexAlpha(UCS4 ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
? (int)((ch & ~('a'-'A')) - 'A' + 10)
: -1;
}
static inline int
Digit(UCS4 ch, int radix)
{
int d;
if ((d = UCS4Digit(ch)) < 0) // Not decimal digit
{
if (radix > 10
&& (d = HexAlpha(ch)) < 0) // Not ASCII a-z, A-Z either
return -1; // ditch it
}
if (d < radix || (d == 1 && radix == 1))
return d;
else
return -1;
}
int32_t
StrVal::asInt32(
int* err_return, // error return
int radix, // base for conversion
CharNum* scanned // characters scanned
) const
{
size_t len = length(); // length of string
size_t i = 0; // position of next character
UCS4 ch = 0; // current character
int d; // current digit value
bool negative = false; // Was a '-' sign seen?
unsigned long l = 0; // Number being converted
unsigned long last;
unsigned long max;
if (err_return)
*err_return = 0;
// Check legal radix
if (radix < 0 || radix > 36)
{
if (err_return)
*err_return = STRERR_ILLEGAL_RADIX;
if (scanned)
*scanned = 0;
return 0;
}
// Skip leading white-space
while (i < len && UCS4IsWhite(ch = (*this)[i]))
i++;
if (i == len)
goto no_digits;
// Check for sign character
if (ch == '+' || ch == '-')
{
i++;
negative = ch == '-';
while (i < len && UCS4IsWhite(ch = (*this)[i]))
i++;
if (i == len)
goto no_digits;
}
if (radix == 0) // Auto-detect radix (octal, decimal, binary)
{
if (UCS4Digit(ch) == 0 && i+1 < len)
{
// ch is the digit zero, look ahead
switch ((*this)[i+1])
{
case 'b': case 'B':
if (radix == 0 || radix == 2)
{
radix = 2;
ch = (*this)[i += 2];
if (i == len)
goto no_digits;
}
break;
case 'x': case 'X':
if (radix == 0 || radix == 16)
{
radix = 16;
ch = (*this)[i += 2];
if (i == len)
goto no_digits;
}
break;
default:
if (radix == 0)
radix = 8;
break;
}
}
else
radix = 10;
}
// Check there's at least one digit:
if ((d = Digit(ch, radix)) < 0)
goto not_number;
max = (ULONG_MAX-1)/radix + 1;
// Convert digits
do {
i++; // We're definitely using this char
last = l;
if (l > max // Detect *unsigned* long overflow
|| (l = l*radix + d) < last)
{
// Overflowed unsigned long!
if (err_return)
*err_return = STRERR_NUMBER_OVERFLOW;
if (scanned)
*scanned = i;
return 0;
}
} while (i < len && (d = Digit((*this)[i], radix)) >= 0);
if (err_return)
*err_return = 0;
// Check for trailing non-white characters
while (i < len && UCS4IsWhite((*this)[i]))
i++;
if (i != len && err_return)
*err_return = STRERR_TRAIL_TEXT;
// Return number of digits scanned
if (scanned)
*scanned = i;
if (l > (unsigned long)LONG_MAX+(negative ? 1 : 0))
{
if (err_return)
*err_return = STRERR_NUMBER_OVERFLOW;
// Try anyway, they might have wanted unsigned!
}
/*
* Casting unsigned long down to long doesn't clear the high bit
* on a twos-complement architecture:
*/
return negative ? -(long)l : (long)l;
no_digits:
if (err_return)
*err_return = STRERR_NO_DIGITS;
if (scanned)
*scanned = i;
return 0;
not_number:
if (err_return)
*err_return = STRERR_NOT_NUMBER;
if (scanned)
*scanned = i;
return 0;
}
// Return a pointer to the start of the nth character, using our bookmark to help
const UTF8*
StrVal::nthChar(CharNum char_num)
{
if (char_num < 0 || char_num > num_chars)
return 0;
return body->nthChar(offset+char_num, mark);
}
// Return a pointer to the start of the nth character, without using a bookmark
const UTF8*
StrVal::nthChar(CharNum char_num) const
{
if (char_num < 0 || char_num > num_chars)
return 0;
Bookmark useless;
return body->nthChar(offset+char_num, useless);
}
bool
StrVal::noCopy() const
{
return body->noCopy();
}
StrBody::~StrBody()
{
if (start && num_alloc > 0)
delete[] start;
}
StrBody::StrBody()
: start(0)
, num_chars(0)
, num_bytes(0)
, num_alloc(0)
{
}
StrBody::StrBody(const UTF8* data, bool copy, CharBytes length, size_t allocate)
: start(0)
, num_chars(0)
, num_bytes(0)
, num_alloc(0)
{
if (copy)
{
if (allocate < length)
allocate = length;
resize(allocate+1); // Include space for a trailing NUL
if (length)
memcpy(start, data, length);
start[length] = '\0';
}
else
{
start = (UTF8*)data; // Cast const away; copy==false implies no change will occur
if (length == 0)
length = strlen(data);
AddRef(); // Cannot be deleted or resized
}
num_bytes = length;
}
StrBody&
StrBody::operator=(const StrBody& s1) // Assignment operator; ONLY for no-copy bodies
{
assert(s1.num_alloc == 0); // Must not do this if we would make two references to allocated data
start = s1.start;
num_chars = s1.num_chars;
num_bytes = s1.num_bytes;
num_alloc = 0;
return *this;
}
/*
* Counting the characters in a string also checks for valid UTF-8.
* If the string is allocated (not static) but unshared,
* it also compacts non-minimal UTF-8 coding.
*/
void
StrBody::countChars()
{
if (num_chars > 0 || num_bytes == 0)
return;
const UTF8* cp = start; // Progress pointer when reading data
UTF8* op = start; // Output for compacted data
UTF8* ep = start+num_bytes; // Marker for end of data
while (cp < ep)
{
const UTF8* char_start = cp; // Save the start of this character, for rewriting
UCS4 ch = UTF8Get(cp);
// We don't hold by Postel’s Law here. We really should throw an exception, but I'm feeling kind. N'yah!
if (ch == UCS4_NONE // Illegal encoding
|| cp > ep) // Overlaps the end of data
break; // An error occurred before the end of the data; truncate it.
if (num_alloc > 0 // Not a static string, so we can rewrite it
&& ref_count <= 1 // Not currently shared, so not breaking any Bookmarks
&& (UTF8Len(ch) < cp-char_start // Optimal length is shorter than this encoding. Start compacting
|| op < char_start)) // We were already compacting
UTF8Put(op, ch); // Rewrite the character in compact form
else
op = (UTF8*)cp; // Keep up
num_chars++;
}
if (op < cp)
{ // We were rewriting, or there was a coding eror, so we now have fewer bytes
num_bytes = op-start;
if (num_alloc > 0)
*op = '\0';
}
}
// Resize the memory allocation to make room for a larger string (size includes the trailing NUL)
void
StrBody::resize(size_t minimum)
{
if (minimum <= num_alloc)
return;
minimum = ((minimum-1)|0x7)+1; // round up to multiple of 8
if (num_alloc) // Minimum growth 50% rounded up to nearest 32
num_alloc = ((num_alloc*3/2) | 0x1F) + 1;
if (num_alloc < minimum)
num_alloc = minimum; // Still not enough, get enough
UTF8* newdata = new UTF8[num_alloc];
if (start)
{
memcpy(newdata, start, num_bytes);
newdata[num_bytes] = '\0';
delete[] start;
}
start = newdata;
}
// Return a pointer to the start of the nth character
UTF8*
StrBody::nthChar(CharNum char_num, StrVal::Bookmark& mark)
{
UTF8* up; // starting pointer for forward search
int start_char; // starting char number for forward search
UTF8* ep; // starting pointer for backward search
int end_char; // starting char number for backward search
if (char_num < 0 || char_num > (end_char = numChars())) // numChars() counts the string if necessary
return (UTF8*)0;
if (num_chars == num_bytes) // ASCII data only, use direct index!
return start+char_num;
up = start; // Set initial starting point for forward search
start_char = 0;
ep = start+num_bytes; // and for backward search (end_char is set above)
// If we have a bookmark, move either the forward or backward search starting point to it.
if (mark.char_num > 0)
{
if (char_num >= mark.char_num)
{ // forget about starting from the start
up += mark.byte_num;
start_char = mark.char_num;
}
else
{ // Don't search past here, maybe back from here
ep = start+mark.byte_num;
end_char = mark.char_num;
}
}
/*
* Decide whether to search forwards from up/start_char or backwards from ep/end_char.
*/
if (char_num-start_char < end_char-char_num)
{ // Forwards search is shorter
end_char = char_num-start_char; // How far forward should we search?
while (start_char < char_num && up < ep)
{
up += UTF8Len(up);
start_char++;
}
}
else
{ // Search back from end_char to char_num
while (end_char > char_num && ep && ep > up)
{
ep = (UTF8*)UTF8Backup(ep, start);
end_char--;
}
up = ep;
}
// Save the bookmark if it looks likely to be helpful.
if (up && char_num > 3 && char_num < num_chars-3)
{
mark.byte_num = up-start;
mark.char_num = char_num;
}
return up;
}
void
StrBody::insert(CharNum pos, const StrVal& addend)
{
CharBytes addend_bytes;
const UTF8* addend_data = addend.asUTF8(addend_bytes);
resize(num_bytes + addend_bytes + 1); // Include space for a trailing NUL
StrVal::Bookmark nullmark;
UTF8* insert_position = nthChar(pos, nullmark);
CharBytes unmoved = insert_position-start;
// Move data up, including the trailing NUL
memmove(insert_position+addend_bytes, insert_position, num_bytes-unmoved+1);
memcpy(insert_position, addend_data, addend_bytes);
num_bytes += addend_bytes;
num_chars += addend.length();
}
// Delete a substring from the middle
void
StrBody::remove(CharNum at, int len)
{
assert(ref_count <= 1);
assert(len >= -1);
StrVal::Bookmark nullmark;
UTF8* cp = (UTF8*)nthChar(at, nullmark); // Cast away the const
const UTF8* ep = (len == -1 ? start + num_bytes : nthChar(at + len, nullmark));
if (start+num_bytes+1 > ep) // Move trailing data down. include the '\0'!
memmove(cp, ep, start+num_bytes-ep+1);
num_bytes -= ep-cp;
num_chars -= len; // len says how many we deleted.
}
void
StrBody::toLower()
{
UTF8 one_char[7];
StrBody body; // Any StrVal that references this must have a shorter lifetime. transform() guarantees this.
transform(
[&](const UTF8*& cp, const UTF8* ep) -> StrVal
{
UCS4 ch = UTF8Get(cp); // Get UCS4 character
ch = UCS4ToLower(ch); // Transform it
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, ch);
*op = '\0';
// Assign this to the body in our closure
body = StrBody(one_char, false, op-one_char, 1);
return StrVal(&body);
}
);
}
void
StrBody::toUpper()
{
UTF8 one_char[7];
StrBody body; // Any StrVal that references this must have a shorter lifetime. transform() guarantees this.
transform(
[&](const UTF8*& cp, const UTF8* ep) -> StrVal
{
UCS4 ch = UTF8Get(cp); // Get UCS4 character
ch = UCS4ToUpper(ch); // Transform it
UTF8* op = one_char; // Pack it into our local buffer
UTF8Put(op, ch);
*op = '\0';
// Assign this to the body in our closure
body = StrBody(one_char, false, op-one_char, 1);
return StrVal(&body);
}
);
}
void
StrVal::transform(const std::function<StrVal(const UTF8*& cp, const UTF8* ep)> xform, int after)
{
Unshare();
body->transform(xform, after);
num_chars = body->numChars();
mark = Bookmark();
}
/*
* At every character position after the given point, the passed transform function
* can extract any number of chars (limited by ep) and return a replacement StrVal for those chars.
* To leave the remainder untransformed, return without advancing cp
* (but a returned StrVal will still be inserted)
*/
void
StrBody::transform(const std::function<StrVal(const UTF8*& cp, const UTF8* ep)> xform, int after)
{
assert(ref_count <= 1);
UTF8* old_start = start;
size_t old_num_bytes = num_bytes;
// Allocate new data, preserving the old
start = 0;
num_chars = 0;
num_bytes = 0;
num_alloc = 0;
resize(old_num_bytes+6+1); // Start with same allocation plus one character space and NUL
const UTF8* up = old_start; // Input pointer
const UTF8* ep = old_start+old_num_bytes; // Termination guard
CharNum processed_chars = 0; // Total input chars transformed
bool stopped = false; // Are we done yet?
UTF8* op = start; // Output pointer
while (up < ep)
{
const UTF8* next = up;
if (processed_chars+1 > after+1 // Not yet reached the point to start transforming
&& !stopped) // We have stopped transforming
{
StrVal replacement = xform(next, ep);
CharBytes replaced_bytes = next-up; // How many bytes were consumed?
CharNum replaced_chars = replacement.length(); // Replaced by how many chars?
// Advance 'up' over the replaced characters
while (up < next)
{
up += UTF8Len(up);
processed_chars++;
}
stopped |= (replaced_bytes == 0);
insert(num_chars, replacement);
op = start+num_bytes;
}
else
{ // Just copy one character and move on
UCS4 ch = UTF8Get(up); // Get UCS4 character
processed_chars++;
if (num_alloc < (op-start+6+1))
{
resize((op-start)+6+1); // Room for any char and NUL
op = start+num_bytes; // Reset our output pointer in case start has changed
}
UTF8Put(op, ch);
num_bytes = op-start;
num_chars++;
}
}
*op = '\0';
delete [] old_start;
}
| 23.709509 | 110 | 0.652975 | cjheath |
ee21efbdea5cdfb86caa639599d978d1ace03122 | 23,457 | cpp | C++ | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 16 | 2016-03-04T02:44:11.000Z | 2021-08-08T18:48:37.000Z | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 2 | 2015-11-19T11:28:43.000Z | 2020-05-05T09:25:50.000Z | src/SoyH264.cpp | SoylentGraham/ofxSoylent | 69ed35ba58e51f381c6ddccbdbd7148da32507a2 | [
"MIT"
] | 4 | 2017-01-06T06:09:34.000Z | 2019-06-25T17:12:29.000Z | #include "SoyH264.h"
size_t H264::GetNaluLengthSize(SoyMediaFormat::Type Format)
{
switch ( Format )
{
case SoyMediaFormat::H264_8: return 1;
case SoyMediaFormat::H264_16: return 2;
case SoyMediaFormat::H264_32: return 4;
case SoyMediaFormat::H264_ES:
case SoyMediaFormat::H264_SPS_ES:
case SoyMediaFormat::H264_PPS_ES:
return 0;
default:
break;
}
std::stringstream Error;
//Error << __func__ << " unhandled format " << Format;
Error << __func__ << " unhandled format ";
throw Soy::AssertException( Error.str() );
}
bool H264::IsNalu(const ArrayBridge<uint8>& Data,size_t& NaluSize,size_t& HeaderSize)
{
// too small to be nalu3
if ( Data.GetDataSize() < 4 )
return false;
// read magic
uint32 Magic;
memcpy( &Magic, Data.GetArray(), sizeof(Magic) );
// test for nalu sizes
// gr: big endian!
if ( (Magic & 0xffffffff) == 0x01000000 )
{
NaluSize = 4;
}
else if ( (Magic & 0xffffff) == 0x010000 )
{
NaluSize = 3;
}
else
{
return false;
}
// missing next byte
if ( Data.GetDataSize() < NaluSize+1 )
return false;
// eat nalu byte
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
uint8 NaluByte = Data[NaluSize];
try
{
H264::DecodeNaluByte( NaluByte, Content, Priority );
}
catch(...)
{
return false;
}
// +nalubyte
HeaderSize = NaluSize+1;
// eat another spare byte...
// todo: verify this is the proper way of doing things...
if ( Content == H264NaluContent::AccessUnitDelimiter )
{
// eat the AUD type value
HeaderSize += 1;
}
// real data should follow now
return true;
}
void H264::RemoveHeader(SoyMediaFormat::Type Format,ArrayBridge<uint8>&& Data,bool KeepNaluByte)
{
switch ( Format )
{
case SoyMediaFormat::H264_ES:
case SoyMediaFormat::H264_SPS_ES:
case SoyMediaFormat::H264_PPS_ES:
{
// gr: CMVideoFormatDescriptionCreateFromH264ParameterSets requires the byte!
size_t NaluSize,HeaderSize;
if ( IsNalu( Data, NaluSize, HeaderSize ) )
{
if ( KeepNaluByte )
Data.RemoveBlock( 0, NaluSize );
else
Data.RemoveBlock( 0, HeaderSize );
return;
}
throw Soy::AssertException("Tried to trim header from h264 ES data but couldn't find nalu header");
}
// gr: is there more to remove than the length?
case SoyMediaFormat::H264_8:
Data.RemoveBlock( 0, 1 );
return;
case SoyMediaFormat::H264_16:
Data.RemoveBlock( 0, 2 );
return;
case SoyMediaFormat::H264_32:
Data.RemoveBlock( 0, 4 );
return;
default:
break;
}
std::stringstream Error;
Error << __func__ << " trying to trim header from non h264 format ";// << Format;
throw Soy::AssertException( Error.str() );
}
bool H264::ResolveH264Format(SoyMediaFormat::Type& Format,ArrayBridge<uint8>& Data)
{
size_t NaluSize = 0;
size_t HeaderSize = 0;
// todo: could try and decode length size from Data size...
if ( !IsNalu( Data, NaluSize, HeaderSize ) )
return false;
uint8 NaluByte = Data[NaluSize];
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
try
{
DecodeNaluByte( NaluByte, Content, Priority );
}
catch(std::exception&e)
{
std::Debug << __func__ << " exception: " << e.what() << std::endl;
throw;
}
if ( Content == H264NaluContent::SequenceParameterSet )
Format = SoyMediaFormat::H264_SPS_ES;
else if ( Content == H264NaluContent::PictureParameterSet )
Format = SoyMediaFormat::H264_PPS_ES;
else
Format = SoyMediaFormat::H264_ES;
return true;
}
size_t H264::FindNaluStartIndex(ArrayBridge<uint8>&& Data,size_t& NaluSize,size_t& HeaderSize)
{
// look for start of nalu
for ( ssize_t i=0; i<Data.GetSize(); i++ )
{
auto ChunkPart = GetRemoteArray( &Data[i], Data.GetSize()-i );
if ( !H264::IsNalu( GetArrayBridge(ChunkPart), NaluSize, HeaderSize ) )
continue;
return i;
}
throw Soy::AssertException("Failed to find NALU start");
}
uint8 H264::EncodeNaluByte(H264NaluContent::Type Content,H264NaluPriority::Type Priority)
{
// uint8 Idc_Important = 0x3 << 5; // 0x60
// uint8 Idc = Idc_Important; // 011 XXXXX
uint8 Idc = Priority;
Idc <<= 5;
uint8 Type = Content;
uint8 Byte = Idc|Type;
return Byte;
}
void H264::DecodeNaluByte(uint8 Byte,H264NaluContent::Type& Content,H264NaluPriority::Type& Priority)
{
uint8 Zero = (Byte >> 7) & 0x1;
uint8 Idc = (Byte >> 5) & 0x3;
uint8 Content8 = (Byte >> 0) & (0x1f);
Soy::Assert( Zero==0, "Nalu zero bit non-zero");
// catch bad cases. look out for genuine cases, but if this is zero, NALU delin might have been read wrong
Soy::Assert( Content8!=0, "Nalu content type is invalid (zero)");
// swich this for magic_enum
//Priority = H264NaluPriority::Validate( Idc );
//Content = H264NaluContent::Validate( Content8 );
Priority = static_cast<H264NaluPriority::Type>( Idc );
Content = static_cast<H264NaluContent::Type>( Content8 );
}
void H264::DecodeNaluByte(SoyMediaFormat::Type Format,const ArrayBridge<uint8>&& Data,H264NaluContent::Type& Content,H264NaluPriority::Type& Priority)
{
size_t NaluSize;
size_t HeaderSize;
if ( !IsNalu( Data, NaluSize, HeaderSize ) )
{
Content = H264NaluContent::Invalid;
return;
}
DecodeNaluByte( Data[HeaderSize], Content, Priority );
}
class TBitReader
{
public:
TBitReader(const ArrayBridge<uint8>& Data) :
mData ( Data ),
mBitPos ( 0 )
{
}
TBitReader(const ArrayBridge<uint8>&& Data) :
mData ( Data ),
mBitPos ( 0 )
{
}
void Read(uint32& Data,size_t BitCount);
void Read(uint64& Data,size_t BitCount);
void Read(uint8& Data,size_t BitCount);
size_t BitPosition() const { return mBitPos; }
template<int BYTECOUNT,typename STORAGE>
void ReadBytes(STORAGE& Data,size_t BitCount);
void ReadExponentialGolombCode(uint32& Data);
void ReadExponentialGolombCodeSigned(sint32& Data);
private:
const ArrayBridge<uint8>& mData;
size_t mBitPos; // current bit-to-read/write-pos (the tail)
};
/*
unsigned int ReadBit()
{
ATLASSERT(m_nCurrentBit <= m_nLength * 8);
int nIndex = m_nCurrentBit / 8;
int nOffset = m_nCurrentBit % 8 + 1;
m_nCurrentBit ++;
return (m_pStart[nIndex] >> (8-nOffset)) & 0x01;
}
*/
void TBitReader::ReadExponentialGolombCode(uint32& Data)
{
int i = 0;
while( true )
{
uint8 Bit;
Read( Bit, 1 );
if ( (Bit == 0) && (i < 32) )
i++;
else
break;
}
Read( Data, i );
Data += (1 << i) - 1;
}
void TBitReader::ReadExponentialGolombCodeSigned(sint32& Data)
{
uint32 r;
ReadExponentialGolombCode(r);
if (r & 0x01)
{
Data = (r+1)/2;
}
else
{
Data = -size_cast<sint32>(r/2);
}
}
template<int BYTECOUNT,typename STORAGE>
void TBitReader::ReadBytes(STORAGE& Data,size_t BitCount)
{
// gr: definitly correct
Data = 0;
BufferArray<uint8,BYTECOUNT> Bytes;
int ComponentBitCount = size_cast<int>(BitCount);
while ( ComponentBitCount > 0 )
{
Read( Bytes.PushBack(), std::min<size_t>(8,ComponentBitCount) );
ComponentBitCount -= 8;
}
// gr: should we check for mis-aligned bitcount?
Data = 0;
for ( int i=0; i<Bytes.GetSize(); i++ )
{
int Shift = (i * 8);
Data |= static_cast<STORAGE>(Bytes[i]) << Shift;
}
STORAGE DataBackwardTest = 0;
for ( int i=0; i<Bytes.GetSize(); i++ )
{
auto Shift = (Bytes.GetSize()-1-i) * 8;
DataBackwardTest |= static_cast<STORAGE>(Bytes[i]) << Shift;
}
// turns out THIS is the right way
Data = DataBackwardTest;
}
void TBitReader::Read(uint32& Data,size_t BitCount)
{
// break up data
if ( BitCount <= 8 )
{
uint8 Data8;
Read( Data8, BitCount );
Data = Data8;
return;
}
if ( BitCount <= 8 )
{
ReadBytes<1>( Data, BitCount );
return;
}
if ( BitCount <= 16 )
{
ReadBytes<2>( Data, BitCount );
return;
}
if ( BitCount <= 32 )
{
ReadBytes<4>( Data, BitCount );
return;
}
std::stringstream Error;
Error << __func__ << " not handling bit count > 32; " << BitCount;
throw Soy::AssertException( Error.str() );
}
void TBitReader::Read(uint64& Data,size_t BitCount)
{
if ( BitCount <= 8 )
{
ReadBytes<1>( Data, BitCount );
return;
}
if ( BitCount <= 16 )
{
ReadBytes<2>( Data, BitCount );
return;
}
if ( BitCount <= 32 )
{
ReadBytes<4>( Data, BitCount );
return;
}
if ( BitCount <= 64 )
{
ReadBytes<8>( Data, BitCount );
return;
}
std::stringstream Error;
Error << __func__ << " not handling bit count > 32; " << BitCount;
throw Soy::AssertException( Error.str() );
}
void TBitReader::Read(uint8& Data,size_t BitCount)
{
if ( BitCount <= 0 )
return;
Soy::Assert( BitCount <= 8, "trying to read>8 bits to 8bit value");
// current byte
auto CurrentByte = mBitPos / 8;
auto CurrentBit = mBitPos % 8;
// out of range
Soy::Assert( CurrentByte < mData.GetSize(), "Reading byte out of range");
// move along
mBitPos += BitCount;
// get byte
Data = mData[CurrentByte];
// pick out certain bits
// gr: reverse endianess to what I thought...
//Data >>= CurrentBit;
Data >>= 8-CurrentBit-BitCount;
Data &= (1<<BitCount)-1;
}
/*
const unsigned char * m_pStart;
unsigned short m_nLength;
int m_nCurrentBit;
unsigned int ReadBit()
{
assert(m_nCurrentBit <= m_nLength * 8);
int nIndex = m_nCurrentBit / 8;
int nOffset = m_nCurrentBit % 8 + 1;
m_nCurrentBit ++;
return (m_pStart[nIndex] >> (8-nOffset)) & 0x01;
}
unsigned int ReadBits(int n)
{
int r = 0;
int i;
for (i = 0; i < n; i++)
{
r |= ( ReadBit() << ( n - i - 1 ) );
}
return r;
}
unsigned int ReadExponentialGolombCode()
{
int r = 0;
int i = 0;
while( (ReadBit() == 0) && (i < 32) )
{
i++;
}
r = ReadBits(i);
r += (1 << i) - 1;
return r;
}
unsigned int ReadSE()
{
int r = ReadExponentialGolombCode();
if (r & 0x01)
{
r = (r+1)/2;
}
else
{
r = -(r/2);
}
return r;
}
void Parse(const unsigned char * pStart, unsigned short nLen)
{
m_pStart = pStart;
m_nLength = nLen;
m_nCurrentBit = 0;
int frame_crop_left_offset=0;
int frame_crop_right_offset=0;
int frame_crop_top_offset=0;
int frame_crop_bottom_offset=0;
int profile_idc = ReadBits(8);
int constraint_set0_flag = ReadBit();
int constraint_set1_flag = ReadBit();
int constraint_set2_flag = ReadBit();
int constraint_set3_flag = ReadBit();
int constraint_set4_flag = ReadBit();
int constraint_set5_flag = ReadBit();
int reserved_zero_2bits = ReadBits(2);
int level_idc = ReadBits(8);
int seq_parameter_set_id = ReadExponentialGolombCode();
if( profile_idc == 100 || profile_idc == 110 ||
profile_idc == 122 || profile_idc == 244 ||
profile_idc == 44 || profile_idc == 83 ||
profile_idc == 86 || profile_idc == 118 )
{
int chroma_format_idc = ReadExponentialGolombCode();
if( chroma_format_idc == 3 )
{
int residual_colour_transform_flag = ReadBit();
}
int bit_depth_luma_minus8 = ReadExponentialGolombCode();
int bit_depth_chroma_minus8 = ReadExponentialGolombCode();
int qpprime_y_zero_transform_bypass_flag = ReadBit();
int seq_scaling_matrix_present_flag = ReadBit();
if (seq_scaling_matrix_present_flag)
{
int i=0;
for ( i = 0; i < 8; i++)
{
int seq_scaling_list_present_flag = ReadBit();
if (seq_scaling_list_present_flag)
{
int sizeOfScalingList = (i < 6) ? 16 : 64;
int lastScale = 8;
int nextScale = 8;
int j=0;
for ( j = 0; j < sizeOfScalingList; j++)
{
if (nextScale != 0)
{
int delta_scale = ReadSE();
nextScale = (lastScale + delta_scale + 256) % 256;
}
lastScale = (nextScale == 0) ? lastScale : nextScale;
}
}
}
}
}
int log2_max_frame_num_minus4 = ReadExponentialGolombCode();
int pic_order_cnt_type = ReadExponentialGolombCode();
if( pic_order_cnt_type == 0 )
{
int log2_max_pic_order_cnt_lsb_minus4 = ReadExponentialGolombCode();
}
else if( pic_order_cnt_type == 1 )
{
int delta_pic_order_always_zero_flag = ReadBit();
int offset_for_non_ref_pic = ReadSE();
int offset_for_top_to_bottom_field = ReadSE();
int num_ref_frames_in_pic_order_cnt_cycle = ReadExponentialGolombCode();
int i;
for( i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ )
{
ReadSE();
//sps->offset_for_ref_frame[ i ] = ReadSE();
}
}
int max_num_ref_frames = ReadExponentialGolombCode();
int gaps_in_frame_num_value_allowed_flag = ReadBit();
int pic_width_in_mbs_minus1 = ReadExponentialGolombCode();
int pic_height_in_map_units_minus1 = ReadExponentialGolombCode();
int frame_mbs_only_flag = ReadBit();
if( !frame_mbs_only_flag )
{
int mb_adaptive_frame_field_flag = ReadBit();
}
int direct_8x8_inference_flag = ReadBit();
int frame_cropping_flag = ReadBit();
if( frame_cropping_flag )
{
frame_crop_left_offset = ReadExponentialGolombCode();
frame_crop_right_offset = ReadExponentialGolombCode();
frame_crop_top_offset = ReadExponentialGolombCode();
frame_crop_bottom_offset = ReadExponentialGolombCode();
}
int vui_parameters_present_flag = ReadBit();
pStart++;
int Width = ((pic_width_in_mbs_minus1 +1)*16) - frame_crop_bottom_offset*2 - frame_crop_top_offset*2;
int Height = ((2 - frame_mbs_only_flag)* (pic_height_in_map_units_minus1 +1) * 16) - (frame_crop_right_offset * 2) - (frame_crop_left_offset * 2);
printf("\n\nWxH = %dx%d\n\n",Width,Height);
}
*/
H264::TSpsParams H264::ParseSps(const ArrayBridge<uint8>&& Data)
{
return ParseSps( Data );
}
H264::TSpsParams H264::ParseSps(const ArrayBridge<uint8>& Data)
{
// test against the working version from stackoverflow
//Parse( Data.GetArray(), Data.GetDataSize() );
TSpsParams Params;
auto _DataSkipNaluByte = GetRemoteArray( Data.GetArray()+1, Data.GetDataSize()-1 );
auto DataSkipNaluByte = GetArrayBridge( _DataSkipNaluByte );
bool SkipNaluByte = false;
try
{
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
DecodeNaluByte( Data[0], Content, Priority );
SkipNaluByte = true;
}
catch (...)
{
}
TBitReader Reader( SkipNaluByte ? DataSkipNaluByte : Data );
// http://stackoverflow.com/questions/12018535/get-the-width-height-of-the-video-from-h-264-nalu
uint8 Param8;
Reader.Read( Param8, 8 );
Params.mProfile = H264Profile::Validate( Param8 );
Reader.Read( Params.mConstraintFlag[0], 1 );
Reader.Read( Params.mConstraintFlag[1], 1 );
Reader.Read( Params.mConstraintFlag[2], 1 );
Reader.Read( Params.mConstraintFlag[3], 1 );
Reader.Read( Params.mConstraintFlag[4], 1 );
Reader.Read( Params.mConstraintFlag[5], 1 );
Reader.Read( Params.mReservedZero, 2 );
uint8 Level;
Reader.Read( Level, 8 );
Params.mLevel = H264::DecodeLevel( Level );
Reader.ReadExponentialGolombCode( Params.seq_parameter_set_id );
if( Params.mProfile == H264Profile::High ||
Params.mProfile == H264Profile::High10Intra ||
Params.mProfile == H264Profile::High422Intra ||
Params.mProfile == H264Profile::High4 ||
Params.mProfile == H264Profile::High5 ||
Params.mProfile == H264Profile::High6 ||
Params.mProfile == H264Profile::High7 ||
Params.mProfile == H264Profile::High8 ||
Params.mProfile == H264Profile::High9 ||
Params.mProfile == H264Profile::HighMultiviewDepth )
{
Reader.ReadExponentialGolombCode( Params.chroma_format_idc );
if( Params.chroma_format_idc == 3 )
{
Reader.Read( Params.residual_colour_transform_flag, 1 );
}
Reader.ReadExponentialGolombCode(Params.bit_depth_luma_minus8 );
Reader.ReadExponentialGolombCode(Params.bit_depth_chroma_minus8 );
Reader.ReadExponentialGolombCode(Params.qpprime_y_zero_transform_bypass_flag );
Reader.ReadExponentialGolombCode(Params.seq_scaling_matrix_present_flag );
if (Params.seq_scaling_matrix_present_flag)
{
int i=0;
for ( i = 0; i < 8; i++)
{
Reader.Read(Params.seq_scaling_list_present_flag,1);
if (Params.seq_scaling_list_present_flag)
{
int sizeOfScalingList = (i < 6) ? 16 : 64;
int lastScale = 8;
int nextScale = 8;
int j=0;
for ( j = 0; j < sizeOfScalingList; j++)
{
if (nextScale != 0)
{
Soy_AssertTodo();
//int delta_scale = ReadSE();
//nextScale = (lastScale + delta_scale + 256) % 256;
}
lastScale = (nextScale == 0) ? lastScale : nextScale;
}
}
}
}
}
Reader.ReadExponentialGolombCode( Params.log2_max_frame_num_minus4 );
Reader.ReadExponentialGolombCode( Params.pic_order_cnt_type );
if ( Params.pic_order_cnt_type == 0 )
{
Reader.ReadExponentialGolombCode( Params.log2_max_pic_order_cnt_lsb_minus4 );
}
else if ( Params.pic_order_cnt_type == 1 )
{
Reader.Read( Params.delta_pic_order_always_zero_flag, 1 );
Reader.ReadExponentialGolombCodeSigned( Params.offset_for_non_ref_pic );
Reader.ReadExponentialGolombCodeSigned( Params.offset_for_top_to_bottom_field );
Reader.ReadExponentialGolombCode( Params.num_ref_frames_in_pic_order_cnt_cycle );
for( int i = 0; i <Params.num_ref_frames_in_pic_order_cnt_cycle; i++ )
{
sint32 Dummy;
Reader.ReadExponentialGolombCodeSigned( Dummy );
//sps->offset_for_ref_frame[ i ] = ReadSE();
}
}
Reader.ReadExponentialGolombCode( Params.num_ref_frames );
Reader.Read( Params.gaps_in_frame_num_value_allowed_flag, 1 );
Reader.ReadExponentialGolombCode( Params.pic_width_in_mbs_minus_1 );
Reader.ReadExponentialGolombCode( Params.pic_height_in_map_units_minus_1 );
Reader.Read( Params.frame_mbs_only_flag, 1 );
if( !Params.frame_mbs_only_flag )
{
Reader.Read( Params.mb_adaptive_frame_field_flag, 1 );
}
Reader.Read( Params.direct_8x8_inference_flag, 1 );
Reader.Read( Params.frame_cropping_flag, 1 );
if( Params.frame_cropping_flag )
{
Reader.ReadExponentialGolombCode( Params.frame_crop_left_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_right_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_top_offset );
Reader.ReadExponentialGolombCode( Params.frame_crop_bottom_offset );
}
Reader.Read( Params.vui_prameters_present_flag, 1 );
Reader.Read( Params.rbsp_stop_one_bit, 1 );
Params.mWidth = ((Params.pic_width_in_mbs_minus_1 +1)*16) - Params.frame_crop_bottom_offset*2 - Params.frame_crop_top_offset*2;
Params.mHeight = ((2 - Params.frame_mbs_only_flag)* (Params.pic_height_in_map_units_minus_1 +1) * 16) - (Params.frame_crop_right_offset * 2) - (Params.frame_crop_left_offset * 2);
return Params;
}
void H264::SetSpsProfile(ArrayBridge<uint8>&& Data,H264Profile::Type Profile)
{
Soy::Assert( Data.GetSize() > 0, "Not enough SPS data");
auto& ProfileByte = Data[0];
// simple byte
ProfileByte = size_cast<uint8>( Profile );
}
Soy::TVersion H264::DecodeLevel(uint8 Level8)
{
// show level
// https://github.com/ford-prefect/gst-plugins-bad/blob/master/sys/applemedia/vtdec.c
// http://stackoverflow.com/questions/21120717/h-264-video-wont-play-on-ios
// value is decimal * 10. Even if the data is bad, this should still look okay
int Minor = Level8 % 10;
int Major = (Level8-Minor) / 10;
return Soy::TVersion( Major, Minor );
}
bool H264::IsKeyframe(H264NaluContent::Type Content) __noexcept
{
// gr: maybe we should take priority into effect too?
switch ( Content )
{
case H264NaluContent::Slice_CodedIDRPicture:
return true;
default:
return false;
}
}
bool H264::IsKeyframe(SoyMediaFormat::Type Format,const ArrayBridge<uint8>&& Data) __noexcept
{
try
{
H264NaluContent::Type Content;
H264NaluPriority::Type Priority;
DecodeNaluByte( Format, GetArrayBridge(Data), Content, Priority );
return IsKeyframe( Content );
}
catch(...)
{
return false;
}
}
void H264::ConvertNaluPrefix(ArrayBridge<uint8_t>& Nalu,H264::NaluPrefix::Type NaluPrefixType)
{
// assuming annexb, this will throw if not
auto PrefixLength = H264::GetNaluAnnexBLength(Nalu);
// quick implementation for now
if ( NaluPrefixType != H264::NaluPrefix::ThirtyTwo )
Soy_AssertTodo();
auto NewPrefixSize = static_cast<int>(NaluPrefixType);
// pad if prefix was 3 bytes
if ( PrefixLength == 3 )
Nalu.InsertAt(0,0);
else if ( PrefixLength != 4)
throw Soy::AssertException("Expecting nalu size of 4");
// write over prefix
uint32_t Size32 = Nalu.GetDataSize() - NewPrefixSize;
uint8_t* Size8s = reinterpret_cast<uint8_t*>(&Size32);
Nalu[0] = Size8s[3];
Nalu[1] = Size8s[2];
Nalu[2] = Size8s[1];
Nalu[3] = Size8s[0];
}
size_t H264::GetNextNaluOffset(const ArrayBridge<uint8_t>&& Data, size_t StartFrom)
{
if ( Data.GetDataSize() < 4 )
return 0;
// detect 001
auto* DataPtr = Data.GetArray();
for (int i = StartFrom; i < Data.GetDataSize()-3; i++)
{
if (DataPtr[i + 0] != 0) continue;
if (DataPtr[i + 1] != 0) continue;
if (DataPtr[i + 2] != 1) continue;
// check i-1 for 0 in case it's 0001 rather than 001
if (DataPtr[i - 1] == 0)
return i - 1;
return i;
}
return 0;
}
void H264::SplitNalu(const ArrayBridge<uint8_t>& Data,std::function<void(const ArrayBridge<uint8_t>&&)> OnNalu)
{
// gr: this was happening in android test app, GetSubArray() will throw, so catch it
if ( Data.IsEmpty() )
{
std::Debug << "Unexpected " << __PRETTY_FUNCTION__ << " Data.Size=" << Data.GetDataSize() << std::endl;
return;
}
// split up packet if there are multiple nalus
size_t PrevNalu = 0;
while (true)
{
auto PacketData = GetArrayBridge(Data).GetSubArray(PrevNalu);
auto NextNalu = H264::GetNextNaluOffset(GetArrayBridge(PacketData));
if (NextNalu == 0)
{
// everything left
OnNalu(GetArrayBridge(PacketData));
break;
}
else
{
auto SubArray = GetArrayBridge(PacketData).GetSubArray(0, NextNalu);
OnNalu(GetArrayBridge(SubArray));
PrevNalu += NextNalu;
}
}
}
size_t H264::GetNaluLength(const ArrayBridge<uint8_t>& Packet)
{
// todo: test for u8/u16/u32 size prefix
if ( Packet.GetSize() < 4 )
return 0;
auto p0 = Packet[0];
auto p1 = Packet[1];
auto p2 = Packet[2];
auto p3 = Packet[3];
if ( p0 == 0 && p1 == 0 && p2 == 1 )
return 3;
if ( p0 == 0 && p1 == 0 && p2 == 0 && p3 == 1)
return 4;
// couldn't detect, possibly no prefx and it's raw data
// could parse packet type to verify
return 0;
}
size_t H264::GetNaluAnnexBLength(const ArrayBridge<uint8_t>& Packet)
{
// todo: test for u8/u16/u32 size prefix
if ( Packet.GetSize() < 4 )
throw Soy::AssertException("Packet not long enough for annexb");
auto Data0 = Packet[0];
auto Data1 = Packet[1];
auto Data2 = Packet[2];
auto Data3 = Packet[3];
if (Data0 != 0 || Data1 != 0)
throw Soy::AssertException("Data is not bytestream NALU header (leading zeroes)");
if (Data2 == 1)
return 3;
if (Data2 == 0 && Data3 == 1)
return 4;
throw Soy::AssertException("Data is not bytestream NALU header (suffix)");
}
H264NaluContent::Type H264::GetPacketType(const ArrayBridge<uint8_t>&& Data)
{
auto HeaderLength = GetNaluLength(Data);
auto TypeAndPriority = Data[HeaderLength];
auto Type = TypeAndPriority & 0x1f;
auto Priority = TypeAndPriority >> 5;
auto TypeEnum = static_cast<H264NaluContent::Type>(Type);
return TypeEnum;
}
void ReformatDeliminator(ArrayBridge<uint8>& Data,
std::function<size_t(ArrayBridge<uint8>& Data,size_t Position)> ExtractChunk,
std::function<void(size_t ChunkLength,ArrayBridge<uint8>& Data,size_t& Position)> InsertChunk)
{
size_t Position = 0;
while ( true )
{
auto ChunkLength = ExtractChunk( Data, Position );
if ( ChunkLength == 0 )
break;
{
std::stringstream Error;
Error << "Extracted NALU length of " << ChunkLength << "/" << Data.GetDataSize();
Soy::Assert( ChunkLength <= Data.GetDataSize(), Error.str() );
}
InsertChunk( ChunkLength, Data, Position );
Position += ChunkLength;
}
}
| 24.613851 | 180 | 0.689432 | SoylentGraham |
ee270da9bd3331a6f82ae623113725a2f3c02b10 | 4,359 | cpp | C++ | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | 1 | 2021-04-26T14:15:20.000Z | 2021-04-26T14:15:20.000Z | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | null | null | null | src/interpolation.cpp | NChechulin/spline-interpolation | 34333b885c435d5dfd1ab892a9cc8a79e016c448 | [
"MIT"
] | null | null | null | #include "interpolation.h"
#include <QTextStream>
#include <cmath>
#include <fstream>
#include <vector>
#include "polynomial.h"
const double EPS = 1e-6;
Interpolation Interpolation::FromFile(QString path) {
Interpolation result;
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
throw std::runtime_error(file.errorString().toStdString());
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(' ');
if (fields.length() == 2) {
QPointF point(fields[0].toDouble(), fields[1].toDouble());
result.points.push_back(point);
}
}
file.close();
std::sort(result.points.begin(), result.points.end(),
[](QPointF a, QPointF b) { return (a.x() < b.x()); });
result.check_points();
return result;
}
void Interpolation::check_points() const {
if (this->points.size() <= 2) {
throw std::length_error("Less than 3 points were provided");
}
for (size_t i = 0; i < this->points.size() - 1; ++i) {
if (std::abs(points[i].x() - points[i + 1].x()) < EPS) {
throw std::range_error(
"There are at least 2 points with the same X coordinate");
}
}
}
void RREF(std::vector<std::vector<double>>& mat) {
size_t lead = 0;
for (size_t r = 0; r < mat.size(); r++) {
if (mat[0].size() <= lead) {
return;
}
size_t i = r;
while (mat[i][lead] == 0) {
i++;
if (mat.size() == i) {
i = r;
lead++;
if (mat[0].size() == lead) {
return;
}
}
}
std::swap(mat[i], mat[r]);
double val = mat[r][lead];
for (size_t j = 0; j < mat[0].size(); j++) {
mat[r][j] /= val;
}
for (size_t i = 0; i < mat.size(); i++) {
if (i == r) continue;
val = mat[i][lead];
for (size_t j = 0; j < mat[0].size(); j++) {
mat[i][j] = mat[i][j] - val * mat[r][j];
}
}
lead++;
}
}
std::vector<Polynomial> Interpolation::Interpolate() {
size_t size = this->points.size();
size_t solution_index = (size - 1) * 4;
size_t row = 0;
std::vector<std::vector<double>> matrix(
solution_index, std::vector<double>(solution_index + 1, 0));
// splines through equations
for (size_t functionNr = 0; functionNr < size - 1; functionNr++, row++) {
QPointF p0 = this->points[functionNr], p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = std::pow(p0.x(), 3);
matrix[row][functionNr * 4 + 1] = std::pow(p0.x(), 2);
matrix[row][functionNr * 4 + 2] = p0.x();
matrix[row][functionNr * 4 + 3] = 1;
matrix[row][solution_index] = p0.y();
matrix[++row][functionNr * 4 + 0] = std::pow(p1.x(), 3);
matrix[row][functionNr * 4 + 1] = std::pow(p1.x(), 2);
matrix[row][functionNr * 4 + 2] = p1.x();
matrix[row][functionNr * 4 + 3] = 1;
matrix[row][solution_index] = p1.y();
}
// first derivative
for (size_t functionNr = 0; functionNr < size - 2; functionNr++, row++) {
QPointF p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = std::pow(p1.x(), 2) * 3;
matrix[row][functionNr * 4 + 1] = p1.x() * 2;
matrix[row][functionNr * 4 + 2] = 1;
matrix[row][functionNr * 4 + 4] = std::pow(p1.x(), 2) * -3;
matrix[row][functionNr * 4 + 5] = p1.x() * -2;
matrix[row][functionNr * 4 + 6] = -1;
}
// second derivative
for (size_t functionNr = 0; functionNr < size - 2; functionNr++, row++) {
QPointF p1 = this->points[functionNr + 1];
matrix[row][functionNr * 4 + 0] = p1.x() * 6;
matrix[row][functionNr * 4 + 1] = 2;
matrix[row][functionNr * 4 + 4] = p1.x() * -6;
matrix[row][functionNr * 4 + 5] = -2;
}
matrix[row][0 + 0] = this->points[0].x() * 6;
matrix[row++][0 + 1] = 2;
matrix[row][solution_index - 4 + 0] = this->points[size - 1].x() * 6;
matrix[row][solution_index - 4 + 1] = 2;
RREF(matrix);
std::vector<double> coefficients;
coefficients.reserve(matrix.size());
for (auto& i : matrix) {
coefficients.push_back(i[i.size() - 1]);
}
std::vector<Polynomial> functions;
for (size_t i = 0; i < coefficients.size(); i += 4) {
Polynomial p = Polynomial::GetCoefficientsFromVector(coefficients.begin() + i);
p.from = this->points[i / 4].x();
p.to = this->points[i / 4 + 1].x();
functions.push_back(p);
}
return functions;
}
| 28.677632 | 83 | 0.561367 | NChechulin |
ee28152ca589510f65d2def7dd44083bfdc1b6d9 | 6,022 | hpp | C++ | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | file/Json.hpp | CltKitakami/MyLib | d2dc4fb06ea5c3379a1818b49b0ecf13f8cd2b36 | [
"MIT"
] | null | null | null | #ifndef _JSON_HPP_
#define _JSON_HPP_
#include <string>
#include <vector>
#include <list>
#include <map>
#include "common/Exception.hpp"
class JsonArray;
class JsonArrayAst;
class JsonObject;
class JsonObjectAst;
class JsonValue
{
public:
typedef enum Type
{
NULL_VALUE,
STRING,
NUMBER,
OBJECT,
ARRAY,
BOOLEAN
} Type;
typedef struct Object
{
JsonObject *obj;
JsonObjectAst *ast;
} Object;
typedef struct Array
{
JsonArray *arr;
JsonArrayAst *ast;
} Array;
JsonValue() : value(nullptr), refCount(new int(1)), type(NULL_VALUE) {}
JsonValue(const JsonValue &v) { copy(v); }
~JsonValue() { release(); }
static std::string typeToString(Type type);
void assertType(Type type) const;
Type getType() const { return this->type; }
static JsonValue create(const char *str, size_t length);
static JsonValue create(const std::string &str) { return create(str.data(), str.length()); }
static JsonValue create(bool value);
static JsonValue create(double value);
void createString(const char *str, size_t length);
void createString(const std::string &str) { createString(str.data(), str.length()); }
void setString(const std::string &str)
{
assertType(STRING);
*(std::string *)this->value = str;
}
std::string & getString() const
{
assertType(STRING);
return *(std::string *)this->value;
}
void createBoolean(bool value);
void setBoolean(bool value)
{
assertType(BOOLEAN);
this->value = value ? (void *)1 : nullptr;
}
bool getBoolean() const
{
assertType(BOOLEAN);
return this->value != nullptr;
}
void createNumber(double value);
void setNumber(double value)
{
assertType(NUMBER);
*(double *)this->value = value;
}
double getNumber() const
{
assertType(NUMBER);
return *(double *)this->value;
}
void createArray();
const JsonArray * getArray() const
{
assertType(ARRAY);
return ((Array *)this->value)->arr;
}
JsonArray * getArray()
{
assertType(ARRAY);
return ((Array *)this->value)->arr;
}
JsonArrayAst * getArrayAst()
{
assertType(ARRAY);
return ((Array *)this->value)->ast;
}
void createObject();
JsonObject * getObject() const
{
assertType(OBJECT);
return ((Object *)this->value)->obj;
}
JsonObjectAst * getObjectAst()
{
assertType(OBJECT);
return ((Object *)this->value)->ast;
}
std::string toString() const;
void assign(const JsonValue &v);
JsonValue & operator = (const JsonValue &v)
{ this->assign(v); return *this; }
private:
void release();
void copy(const JsonValue &v);
void *value;
int *refCount;
Type type;
};
class JsonArray
{
std::vector<JsonValue> array;
public:
void put(const JsonValue &v) { this->array.push_back(v); }
JsonValue & get(int index) { return this->array[(unsigned)index]; }
const JsonValue & get(int index) const { return this->array[(unsigned)index]; }
size_t getSize() const { return this->array.size(); }
JsonValue & operator [] (int index) { return this->get(index); }
const JsonValue & operator [] (int index) const { return this->get(index); }
};
class JsonPair
{
public:
JsonPair(const std::string &name) : name(name) {}
void setName(const std::string &name) { this->name = name; }
std::string getName() const { return this->name; }
void setValue(const JsonValue &value) { this->value = value; }
JsonValue getValue() const { return this->value; }
JsonValue * getReferenceValue() { return &this->value; }
bool equals(const std::string &name) const { return this->name == name; }
private:
std::string name;
JsonValue value;
};
class JsonObject
{
public:
typedef std::list<JsonPair> Pairs;
typedef std::map<std::string, JsonValue *> PairMap;
void addPair(const JsonPair &p) { pairs.push_back(p); }
void removePair(const std::string &name);
PairMap buildMap();
Pairs::iterator begin() { return pairs.begin(); }
Pairs::iterator end() { return pairs.end(); }
Pairs::const_iterator begin() const { return pairs.begin(); }
Pairs::const_iterator end() const { return pairs.end(); }
JsonPair & front() { return pairs.front(); }
const JsonPair & front() const { return pairs.front(); }
JsonPair & back() { return pairs.back(); }
const JsonPair & back() const { return pairs.back(); }
size_t getPairsSize() const { return pairs.size(); }
private:
Pairs pairs;
};
class Json
{
JsonObject object;
static void newLineToString(std::string &buffer, int tabDepth);
static void appendSpace(std::string &buffer);
static void valueToString(std::string &buffer, const JsonValue &value, int tabDepth);
static void arrayToString(std::string &buffer, const JsonArray &array, int tabDepth);
static void objectToString(std::string &buffer, const JsonObject &object, int tabDepth);
public:
typedef JsonObject::Pairs Pairs;
typedef JsonObject::PairMap PairMap;
Json() {}
Json(const char *fileName) { (void)open(fileName); }
Json(const std::string &fileName) { (void)open(fileName.data()); }
Json(const void *data, size_t length) { (void)openFromMemory(data, length); }
Json(const Json &json) : object(json.object) {}
Json(const JsonObject &object) : object(object) {}
bool open(const char *fileName);
bool openFromMemory(const void *data, size_t length);
void save(const char *fileName);
std::string toString() const;
void addPair(const JsonPair &p) { this->object.addPair(p); }
void removePair(const std::string &name) { this->object.removePair(name); }
Json & operator = (const Json &json) { this->object = json.object; return *this; }
PairMap buildMap() { return this->object.buildMap(); }
Pairs::iterator begin() { return this->object.begin(); }
Pairs::iterator end() { return this->object.end(); }
Pairs::const_iterator begin() const { return this->object.begin(); }
Pairs::const_iterator end() const { return this->object.end(); }
JsonPair & front() { return this->object.front(); }
const JsonPair & front() const { return this->object.front(); }
JsonPair & back() { return this->object.back(); }
const JsonPair & back() const { return this->object.back(); }
};
#endif
| 23.615686 | 93 | 0.688808 | CltKitakami |
0c5387e3cc3b310ac61a54a682a74767df2ea966 | 4,385 | hpp | C++ | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 22 | 2019-09-07T22:38:01.000Z | 2022-01-31T21:35:55.000Z | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | null | null | null | Tools/RegistersGenerator/GD32VF103/timer6registers.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 9 | 2019-09-22T11:26:24.000Z | 2022-03-21T10:53:15.000Z | /*******************************************************************************
* Filename : timer6registers.hpp
*
* Details : Basic-timers. This header file is auto-generated for GD32VF103
* device.
*
*
*******************************************************************************/
#if !defined(TIMER6REGISTERS_HPP)
#define TIMER6REGISTERS_HPP
#include "timer6fieldvalues.hpp" //for Bits Fields defs
#include "registerbase.hpp" //for RegisterBase
#include "register.hpp" //for Register
#include "accessmode.hpp" //for ReadMode, WriteMode, ReadWriteMode
struct TIMER6
{
struct TIMER6CTL0Base {} ;
struct CTL0 : public RegisterBase<0x40001400, 16, ReadWriteMode>
{
using ARSE = TIMER6_CTL0_ARSE_Values<TIMER6::CTL0, 7, 1, ReadWriteMode, TIMER6CTL0Base> ;
using SPM = TIMER6_CTL0_SPM_Values<TIMER6::CTL0, 3, 1, ReadWriteMode, TIMER6CTL0Base> ;
using UPS = TIMER6_CTL0_UPS_Values<TIMER6::CTL0, 2, 1, ReadWriteMode, TIMER6CTL0Base> ;
using UPDIS = TIMER6_CTL0_UPDIS_Values<TIMER6::CTL0, 1, 1, ReadWriteMode, TIMER6CTL0Base> ;
using CEN = TIMER6_CTL0_CEN_Values<TIMER6::CTL0, 0, 1, ReadWriteMode, TIMER6CTL0Base> ;
using FieldValues = TIMER6_CTL0_CEN_Values<TIMER6::CTL0, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CTL0Pack = Register<0x40001400, 16, ReadWriteMode, TIMER6CTL0Base, T...> ;
struct TIMER6CTL1Base {} ;
struct CTL1 : public RegisterBase<0x40001404, 16, ReadWriteMode>
{
using MMC = TIMER6_CTL1_MMC_Values<TIMER6::CTL1, 4, 3, ReadWriteMode, TIMER6CTL1Base> ;
using FieldValues = TIMER6_CTL1_MMC_Values<TIMER6::CTL1, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CTL1Pack = Register<0x40001404, 16, ReadWriteMode, TIMER6CTL1Base, T...> ;
struct TIMER6DMAINTENBase {} ;
struct DMAINTEN : public RegisterBase<0x4000140C, 16, ReadWriteMode>
{
using UPDEN = TIMER6_DMAINTEN_UPDEN_Values<TIMER6::DMAINTEN, 8, 1, ReadWriteMode, TIMER6DMAINTENBase> ;
using UPIE = TIMER6_DMAINTEN_UPIE_Values<TIMER6::DMAINTEN, 0, 1, ReadWriteMode, TIMER6DMAINTENBase> ;
using FieldValues = TIMER6_DMAINTEN_UPIE_Values<TIMER6::DMAINTEN, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using DMAINTENPack = Register<0x4000140C, 16, ReadWriteMode, TIMER6DMAINTENBase, T...> ;
struct TIMER6INTFBase {} ;
struct INTF : public RegisterBase<0x40001410, 16, ReadWriteMode>
{
using UPIF = TIMER6_INTF_UPIF_Values<TIMER6::INTF, 0, 1, ReadWriteMode, TIMER6INTFBase> ;
using FieldValues = TIMER6_INTF_UPIF_Values<TIMER6::INTF, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using INTFPack = Register<0x40001410, 16, ReadWriteMode, TIMER6INTFBase, T...> ;
struct TIMER6SWEVGBase {} ;
struct SWEVG : public RegisterBase<0x40001414, 16, WriteMode>
{
using UPG = TIMER6_SWEVG_UPG_Values<TIMER6::SWEVG, 0, 1, WriteMode, TIMER6SWEVGBase> ;
using FieldValues = TIMER6_SWEVG_UPG_Values<TIMER6::SWEVG, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using SWEVGPack = Register<0x40001414, 16, WriteMode, TIMER6SWEVGBase, T...> ;
struct TIMER6CNTBase {} ;
struct CNT : public RegisterBase<0x40001424, 16, ReadWriteMode>
{
using CNTField = TIMER6_CNT_CNT_Values<TIMER6::CNT, 0, 16, ReadWriteMode, TIMER6CNTBase> ;
using FieldValues = TIMER6_CNT_CNT_Values<TIMER6::CNT, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CNTPack = Register<0x40001424, 16, ReadWriteMode, TIMER6CNTBase, T...> ;
struct TIMER6PSCBase {} ;
struct PSC : public RegisterBase<0x40001428, 16, ReadWriteMode>
{
using PSCField = TIMER6_PSC_PSC_Values<TIMER6::PSC, 0, 16, ReadWriteMode, TIMER6PSCBase> ;
using FieldValues = TIMER6_PSC_PSC_Values<TIMER6::PSC, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using PSCPack = Register<0x40001428, 16, ReadWriteMode, TIMER6PSCBase, T...> ;
struct TIMER6CARBase {} ;
struct CAR : public RegisterBase<0x4000142C, 16, ReadWriteMode>
{
using CARL = TIMER6_CAR_CARL_Values<TIMER6::CAR, 0, 16, ReadWriteMode, TIMER6CARBase> ;
using FieldValues = TIMER6_CAR_CARL_Values<TIMER6::CAR, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CARPack = Register<0x4000142C, 16, ReadWriteMode, TIMER6CARBase, T...> ;
} ;
#endif //#if !defined(TIMER6REGISTERS_HPP)
| 37.801724 | 107 | 0.692132 | snorkysnark |
0c5e3aa49b9a7c1215e16b15156836dbc2b0291e | 2,547 | tpp | C++ | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 64 | 2018-05-15T01:57:55.000Z | 2021-12-14T01:49:18.000Z | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 3 | 2019-11-28T12:10:09.000Z | 2021-11-03T15:16:06.000Z | util/vecs.tpp | Mogami95/GMiner | d80c0fbad2f860d8cf1585440b57a2637993fb42 | [
"Apache-2.0"
] | 24 | 2018-05-15T01:57:22.000Z | 2021-11-24T14:09:14.000Z | //Copyright 2018 Husky Data Lab, CUHK
//Authors: Hongzhi Chen, Miao Liu
template <class KeyT, class MessageT>
MsgPair<KeyT, MessageT>::MsgPair()
{
}
template <class KeyT, class MessageT>
MsgPair<KeyT, MessageT>::MsgPair(KeyT v1, MessageT v2)
{
key = v1;
msg = v2;
}
template <class KeyT, class MessageT>
inline bool MsgPair<KeyT, MessageT>::operator < (const MsgPair<KeyT, MessageT>& rhs) const
{
return key < rhs.key;
}
template <class KeyT, class MessageT>
ibinstream& operator<<(ibinstream& m, const MsgPair<KeyT, MessageT>& v)
{
m << v.key;
m << v.msg;
return m;
}
template <class KeyT, class MessageT>
obinstream& operator>>(obinstream& m, MsgPair<KeyT, MessageT>& v)
{
m >> v.key;
m >> v.msg;
return m;
}
//===============================================
template <class KeyT, class MessageT, class HashT>
Vecs<KeyT, MessageT, HashT>::Vecs()
{
np_ = _num_workers;
vecs_.resize(_num_workers);
}
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::append(const KeyT key, const MessageT msg)
{
MsgPair<KeyT, MessageT> item(key, msg);
vecs_[hash_(key)].push_back(item);
}
template <class KeyT, class MessageT, class HashT>
typename Vecs<KeyT, MessageT, HashT>::Vec& Vecs<KeyT, MessageT, HashT>::get_buf(int pos)
{
return vecs_[pos];
}
template <class KeyT, class MessageT, class HashT>
typename Vecs<KeyT, MessageT, HashT>::VecGroup& Vecs<KeyT, MessageT, HashT>::get_bufs()
{
return vecs_;
}
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::clear()
{
for (int i = 0; i < np_; i++)
{
vecs_[i].clear();
}
}
//============================
//apply combiner logic
template <class KeyT, class MessageT, class HashT>
void Vecs<KeyT, MessageT, HashT>::combine()
{
Combiner<MessageT>* combiner = (Combiner<MessageT>*)get_combiner();
for (int i = 0; i < np_; i++)
{
sort(vecs_[i].begin(), vecs_[i].end());
Vec new_vec;
int size = vecs_[i].size();
if (size > 0)
{
new_vec.push_back(vecs_[i][0]);
KeyT preKey = vecs_[i][0].key;
for (int j = 1; j < size; j++)
{
MsgPair<KeyT, MessageT>& cur = vecs_[i][j];
if (cur.key != preKey)
{
new_vec.push_back(cur);
preKey = cur.key;
}
else
{
combiner->combine(new_vec.back().msg, cur.msg);
}
}
}
new_vec.swap(vecs_[i]);
}
}
template <class KeyT, class MessageT, class HashT>
long long Vecs<KeyT, MessageT, HashT>::get_total_msg()
{
long long sum = 0;
for (int i = 0; i < vecs_.size(); i++)
{
sum += vecs_[i].size();
}
return sum;
}
| 21.403361 | 90 | 0.638398 | Mogami95 |
0c5f4788784a52924e4bb52b314a86844da55221 | 4,448 | cpp | C++ | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | src/trashboy3k.cpp | nlang/tb3k | 6e19b47147081f2a68443e5b29861faee67dbe09 | [
"MIT"
] | null | null | null | #include "trashboy3k.h"
#define FLASH_LED_PIN 10
#define SPEAKER_PIN 9
#define OLED_DISPLAY_TYPE &SH1106_128x64
#define OLED_I2C_ADDRESS 0x3C // I2C address of OLED display
#define EEPROM_DATE_AREA_START 512
#define MAX_NUMBER_OF_DATES_IN_MEMORY 10
#define ACK_TRASHOUT_DATE_INTERRUPT_PIN 3
#define ACK_TRASHOUT_DATE_INTERRUPT_ID 1
#define BTLE_POWER_PIN 6
#define BTLE_SERIAL_RX_PIN 7
#define BTLE_SERIAL_TX_PIN 8
// TODO put into EEPROM as config
#define ALARM_ENABLED_FROM_HOUR 10
#define ALARM_ENABLED_TO_HOUR 22
DataStore dataStore = DataStore(EEPROM_DATE_AREA_START);
Display display = Display(OLED_DISPLAY_TYPE, OLED_I2C_ADDRESS);
SoftwareSerial btSerial(BTLE_SERIAL_RX_PIN, BTLE_SERIAL_TX_PIN);
int numberOfChannels = 0;
char channelNames[5][22];
int numberOfDates = 0;
TrashOutDate dates[MAX_NUMBER_OF_DATES_IN_MEMORY];
BLECommunication ble(&btSerial, &dataStore);
volatile unsigned long debounceLastAckBtnAction = 0;
volatile bool performAck = false;
volatile bool performingAck = false;
long lastAlaramMillis = 0;
bool lockMidnight = false;
void setup() {
Now::init();
Serial.begin(9600);
pinMode(BTLE_POWER_PIN, OUTPUT);
digitalWrite(BTLE_POWER_PIN, LOW);
pinMode(ACK_TRASHOUT_DATE_INTERRUPT_PIN, INPUT);
attachInterrupt(ACK_TRASHOUT_DATE_INTERRUPT_ID, ackButtonInterruptTriggered, RISING); // interrupt for ack button
char lines[][22] = {
"Hello!",
"I'm TrashBoy 3000",
"Happy birthday!",
};
if (isDanisBirthday()) {
display.showIntro(lines, 3);
SoundEffects::playHappyBirthday(SPEAKER_PIN);
} else {
display.showIntro(lines, 2);
delay(2000);
}
// TODO do something on first run?
// h min sec day mon y
//Now::setDateTime(23, 59, 40, 8, 8, 18);
//dataStore.eepromWrite();
numberOfChannels = dataStore.readChannelNames(channelNames);
numberOfDates = dataStore.readDates(dates, MAX_NUMBER_OF_DATES_IN_MEMORY);
ble.setCurrentList(&dates[0], numberOfDates);
// enable BTLE
digitalWrite(BTLE_POWER_PIN, HIGH);
ble.start();
}
void loop() {
ble.readDataIfAvailable();
if (true == performAck) {
performingAck = true;
performAck = false;
doPerformAck();
performingAck = false;
}
if (Now::isMidnight() && !lockMidnight) {
lockMidnight = true;
int numberOfAckDates = 0;
TrashOutDate ackDates[MAX_NUMBER_OF_DATES_IN_MEMORY];
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (date->isAck()) {
memcpy(&ackDates[i], date, sizeof(TrashOutDate));
numberOfAckDates++;
}
}
numberOfDates = dataStore.readDates(dates, MAX_NUMBER_OF_DATES_IN_MEMORY);
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
for (int j = 0; j < numberOfAckDates; j++) {
TrashOutDate *ackDate = ackDates + j;
if (date->isSameDate(ackDate)) {
date->ack();
break;
}
}
}
}
if (!Now::isMidnight() && lockMidnight) {
lockMidnight = false;
}
display.drawDateTimeLine();
if (hasActiveDate() && millis() - lastAlaramMillis > 2000) {
display.drawNextDates(dates, numberOfDates, channelNames, numberOfChannels, true);
digitalWrite(FLASH_LED_PIN, HIGH);
if (Now::getHour() >= ALARM_ENABLED_FROM_HOUR && Now::getHour() < ALARM_ENABLED_TO_HOUR) {
SoundEffects::playAlarmSignal(SPEAKER_PIN);
} else {
delay(60);
}
delay(140);
digitalWrite(FLASH_LED_PIN, LOW);
lastAlaramMillis = millis();
} else {
display.drawNextDates(dates, numberOfDates, channelNames, numberOfChannels, false);
}
}
bool isDanisBirthday(void) {
if (24 >= Now::getDay() && 8 == Now::getMonth() && 18 == Now::getYear2kBased()) {
return true;
}
return false;
}
bool hasActiveDate(void) {
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (!date->isAck() && (Now::isToday(date) || Now::isTomorrow(date))) {
return true;
}
}
return false;
}
void ackButtonInterruptTriggered() {
if ((millis() - debounceLastAckBtnAction) > 500) {
debounceLastAckBtnAction = millis();
if (!performingAck) {
performAck = true;
}
}
}
void doPerformAck(void) {
for (int i = 0; i < numberOfDates; i++) {
TrashOutDate *date = dates + i;
if (!date->isAck() && (Now::isToday(date) || Now::isTomorrow(date))) {
date->ack();
return;
}
}
SoundEffects::playErrorTone(SPEAKER_PIN);
}
| 26.634731 | 115 | 0.682554 | nlang |
0c643b724e962346eda2ddbfabbcf7c987c5aec9 | 3,713 | cpp | C++ | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/viewer/SkottieSlide2.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottieSlide.h"
#include "SkAnimTimer.h"
#include "SkCanvas.h"
#include "Skottie.h"
#include "SkOSFile.h"
#include "SkOSPath.h"
#include "SkStream.h"
const int CELL_WIDTH = 240;
const int CELL_HEIGHT = 160;
const int COL_COUNT = 4;
const int SPACER_X = 12;
const int SPACER_Y = 24;
const int MARGIN = 8;
SkottieSlide2::Rec::Rec(std::unique_ptr<skottie::Animation> anim) : fAnimation(std::move(anim))
{}
SkottieSlide2::Rec::Rec(Rec&& o)
: fAnimation(std::move(o.fAnimation))
, fTimeBase(o.fTimeBase)
, fName(o.fName)
, fShowAnimationInval(o.fShowAnimationInval)
{}
SkottieSlide2::SkottieSlide2(const SkString& path)
: fPath(path)
{
fName.set("skottie-dir");
}
void SkottieSlide2::load(SkScalar, SkScalar) {
SkString name;
SkOSFile::Iter iter(fPath.c_str(), "json");
while (iter.next(&name)) {
SkString path = SkOSPath::Join(fPath.c_str(), name.c_str());
if (auto anim = skottie::Animation::MakeFromFile(path.c_str())) {
fAnims.push_back(Rec(std::move(anim))).fName = name;
}
}
}
void SkottieSlide2::unload() {
fAnims.reset();
}
SkISize SkottieSlide2::getDimensions() const {
const int rows = (fAnims.count() + COL_COUNT - 1) / COL_COUNT;
return {
MARGIN + (COL_COUNT - 1) * SPACER_X + COL_COUNT * CELL_WIDTH + MARGIN,
MARGIN + (rows - 1) * SPACER_Y + rows * CELL_HEIGHT + MARGIN,
};
}
void SkottieSlide2::draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(12);
paint.setAntiAlias(true);
paint.setTextAlign(SkPaint::kCenter_Align);
const SkRect dst = SkRect::MakeIWH(CELL_WIDTH, CELL_HEIGHT);
int x = 0, y = 0;
canvas->translate(MARGIN, MARGIN);
for (const auto& rec : fAnims) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x * (CELL_WIDTH + SPACER_X), y * (CELL_HEIGHT + SPACER_Y));
canvas->drawText(rec.fName.c_str(), rec.fName.size(),
dst.centerX(), dst.bottom() + paint.getTextSize(), paint);
rec.fAnimation->render(canvas, &dst);
if (++x == COL_COUNT) {
x = 0;
y += 1;
}
}
}
bool SkottieSlide2::animate(const SkAnimTimer& timer) {
for (auto& rec : fAnims) {
if (rec.fTimeBase == 0) {
// Reset the animation time.
rec.fTimeBase = timer.msec();
}
rec.fAnimation->animationTick(timer.msec() - rec.fTimeBase);
}
return true;
}
bool SkottieSlide2::onMouse(SkScalar x, SkScalar y, sk_app::Window::InputState state,
uint32_t modifiers) {
if (fTrackingCell < 0 && state == sk_app::Window::kDown_InputState) {
fTrackingCell = this->findCell(x, y);
}
if (fTrackingCell >= 0 && state == sk_app::Window::kUp_InputState) {
int index = this->findCell(x, y);
if (fTrackingCell == index) {
fAnims[index].fShowAnimationInval = !fAnims[index].fShowAnimationInval;
fAnims[index].fAnimation->setShowInval(fAnims[index].fShowAnimationInval);
}
fTrackingCell = -1;
}
return fTrackingCell >= 0;
}
int SkottieSlide2::findCell(float x, float y) const {
x -= MARGIN;
y -= MARGIN;
int index = -1;
if (x >= 0 && y >= 0) {
int ix = (int)x;
int iy = (int)y;
int col = ix / (CELL_WIDTH + SPACER_X);
int row = iy / (CELL_HEIGHT + SPACER_Y);
index = row * COL_COUNT + col;
if (index >= fAnims.count()) {
index = -1;
}
}
return index;
}
| 28.782946 | 95 | 0.603016 | ndsol |
0c7c8b823c53868261dc861515c7f334ab885366 | 206 | hpp | C++ | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | include/xnn/layers/pooling.hpp | ktnyt/xdfa | 962ef8f99150556272ff87c7b37494fd87f5fe79 | [
"MIT"
] | null | null | null | #ifndef __XNN_LAYERS_POOLING_HPP__
#define __XNN_LAYERS_POOLING_HPP__
#include "xnn/layers/pooling/average_pooling.hpp"
#include "xnn/layers/pooling/max_pooling.hpp"
#endif // __XNN_LAYERS_POOLING_HPP__
| 25.75 | 49 | 0.839806 | ktnyt |
0c7dba69a42bc938712778de215e1a6ad3cc6de6 | 821 | cpp | C++ | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | 1 | 2020-03-06T21:05:14.000Z | 2020-03-06T21:05:14.000Z | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | 2 | 2020-03-09T05:08:14.000Z | 2020-03-09T05:14:09.000Z | challenge Pattern/Assignment/Assignment4/prob2.1.cpp | sgpritam/DSAlgo | 3e0e6b19d4f8978b2fc3be48195705a285dbdce8 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
for(int i=1;i<=n/2+1;i++)
{
for(int space=1;space<=n/2-i+1;space++)
{
cout<<" ";
}
for(int j=1;j<=2*i-1;j++)
{
if(j==1 || j==2*i-1)
{
cout<<"*";
}
else
{
cout<<" ";
}
}
cout<<endl;
}
// Lower loop
for(int i=1;i<=n/2;i++){
for(int space=1;space<=i;space++)
{
cout<<" ";
}
for(int j=1;j<=n-2*i;j++)
{
if(j==1 || j==n-2*i)
{
cout<<"*";
}
else
{
cout<<" ";
}
}
cout<<endl;
}
}
| 17.104167 | 47 | 0.267966 | sgpritam |
0c876c1c227c760ff856b96adf9a78cd92613320 | 132 | cpp | C++ | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 440 | 2019-08-25T13:07:04.000Z | 2022-03-30T21:57:15.000Z | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 401 | 2019-08-29T08:56:55.000Z | 2022-03-30T12:39:34.000Z | examples/ittapi/boo.cpp | varphone/hunter | 14a6b9a132d78ed0828497c7e8d9b42951209243 | [
"BSD-2-Clause"
] | 162 | 2019-09-02T13:31:36.000Z | 2022-03-30T09:16:54.000Z | #include <ittnotify.h>
int main() {
// pause data collection:
__itt_pause();
// Start data collection
__itt_resume();
}
| 13.2 | 27 | 0.643939 | varphone |
0c8b5808bcb5b95335ee6beb8f70aa6f8caa3acb | 713 | cpp | C++ | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | 3 | 2020-07-17T05:10:56.000Z | 2020-08-02T22:13:50.000Z | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | src/ast/InterfaceMethodDeclaration.cpp | skylang/sky | 518add25e6a101ca2701b3c6bea977b0e76b340e | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Stephan Unverwerth
// This code is licensed under MIT license (See LICENSE for details)
#include "InterfaceMethodDeclaration.h"
#include "Parameter.h"
#include "Expression.h"
#include <sstream>
namespace Sky {
std::string InterfaceMethodDeclaration::getDescription() {
std::stringstream sstr;
sstr << "function " << name << "(";
for (auto& param: parameters) {
if (param != parameters.front()) {
sstr << ", ";
}
sstr << param->name << ": " << param->declarationType->getFullName();
}
sstr << "): " << returnTypeExpression->typeValue->getFullName();
return sstr.str();
}
} | 29.708333 | 81 | 0.57784 | skylang |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.