hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d017ef874e206085c129ae12a3ce7c4117ace6a | 989 | cpp | C++ | src/modules/communication/buffer.cpp | molayab/bobot-car-iot | 978a7ce279b894619f3b03ceb6d7675d8a414e2b | [
"MIT"
] | null | null | null | src/modules/communication/buffer.cpp | molayab/bobot-car-iot | 978a7ce279b894619f3b03ceb6d7675d8a414e2b | [
"MIT"
] | null | null | null | src/modules/communication/buffer.cpp | molayab/bobot-car-iot | 978a7ce279b894619f3b03ceb6d7675d8a414e2b | [
"MIT"
] | null | null | null | #include "modules/communication/communication.h"
using namespace Communication;
Buffer::Buffer() {
context = std::vector<uint8_t>();
}
void Buffer::write_byte(uint8_t byte) {
context.push_back(byte);
}
uint8_t Buffer::read_byte() {
auto value = context[0];
context.erase(context.begin());
return value;
}
size_t Buffer::count() {
return context.size();
}
uint8_t* Buffer::unsafe_read_all() {
/**
* This pointer is only valid as long as the vector is not reallocated.
* Reallocation happens automatically if you insert more elements than will fit
* in the vector's remaining capacity (that is, if v.size() + NumberOfNewElements > v.capacity().
* You can use v.reserve(NewCapacity) to ensure the vector has a capacity of at least NewCapacity.
*
* Also remember that when the vector gets destroyed, the underlying array gets deleted as well.
* */
return &context[0];
}
void Buffer::clear() {
context.clear();
} | 27.472222 | 102 | 0.683519 | [
"vector"
] |
0d0e8017f1b94d9ccb0c51798f7b112ebad33432 | 19,569 | hpp | C++ | src/detail/ComputeMatrixTransform.hpp | x4kkk3r/IOMath | 1101090023b57bd2db34e5a3e07a620b9311ac0b | [
"MIT"
] | 3 | 2020-07-23T11:49:35.000Z | 2020-07-24T12:22:28.000Z | src/detail/ComputeMatrixTransform.hpp | x4kkk3r/IOMath | 1101090023b57bd2db34e5a3e07a620b9311ac0b | [
"MIT"
] | null | null | null | src/detail/ComputeMatrixTransform.hpp | x4kkk3r/IOMath | 1101090023b57bd2db34e5a3e07a620b9311ac0b | [
"MIT"
] | 1 | 2020-07-23T12:18:58.000Z | 2020-07-23T12:18:58.000Z | /*
MIT License
Copyright (c) 2020 x4kkk3r
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef _IO_MATH_COMPUTE_MATRIX_TRANSFORM_HPP
#define _IO_MATH_COMPUTE_MATRIX_TRANSFORM_HPP
#include "../types/matrices/TMatrix4x4.hpp"
#include "../types/vectors/TVector3.hpp"
#include "ComputeVectorGeometric.hpp"
#include <cmath>
namespace IOMath
{
namespace detail
{
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeTranslationMatrix(Types::TVector<3, T> const &translate) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
one, zero, zero, zero,
zero, one, zero, zero,
zero, zero, one, zero,
translate.x, translate.y, translate.z, one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
one, zero, zero, translate.x,
zero, one, zero, translate.y,
zero, zero, one, translate.z,
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeRotationMatrix(Types::TVector<3, T> const &axis, T angle) noexcept
{
T const sinAngle = std::sin(angle);
T const cosAngle = std::cos(angle);
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
Types::TVector<3, T> normalizedAxis = Types::TVector<3, T>(ComputeNormalize(axis));
Types::TVector<3, T> modifier = Types::TVector<3, T>(normalizedAxis * (one - cosAngle));
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
cosAngle + modifier.x * normalizedAxis.x, modifier.x * normalizedAxis.y + sinAngle * normalizedAxis.z, modifier.x * normalizedAxis.z - sinAngle * normalizedAxis.y, zero,
modifier.y * normalizedAxis.x - sinAngle * normalizedAxis.z, cosAngle + modifier.y * normalizedAxis.y, modifier.y * normalizedAxis.z + sinAngle * normalizedAxis.x, zero,
modifier.z * normalizedAxis.x + sinAngle * normalizedAxis.y, modifier.z * normalizedAxis.y - sinAngle * normalizedAxis.x, cosAngle + modifier.z * normalizedAxis.z, zero,
zero, zero, zero, one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
cosAngle + modifier.x * normalizedAxis.x, modifier.y * normalizedAxis.x - sinAngle * normalizedAxis.z, modifier.z * normalizedAxis.x + sinAngle * normalizedAxis.y, zero,
modifier.x * normalizedAxis.y + sinAngle * normalizedAxis.z, cosAngle + modifier.y * normalizedAxis.y, modifier.z * normalizedAxis.y - sinAngle * normalizedAxis.x, zero,
modifier.x * normalizedAxis.z - sinAngle * normalizedAxis.y, modifier.y * normalizedAxis.z + sinAngle * normalizedAxis.x, cosAngle + modifier.z * normalizedAxis.z, zero,
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeScaleMatrix(Types::TVector<3, T> const &scale) noexcept
{
T const zero = static_cast<T>(0);
return Types::TMatrix<4, 4, T>
(
scale.x, zero, zero, zero,
zero, scale.y, zero, zero,
zero, zero, scale.z, zero,
zero, zero, zero, static_cast<T>(1)
);
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeTranslate(Types::TMatrix<4, 4, T> const &object, Types::TVector<3, T> const &_translate) noexcept
{
Types::TMatrix<4, 4, T> result = object;
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
result[3] = object[0] * _translate[0] + object[1] * _translate[1] + object[2] * _translate[2] + object[3];
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
Types::TVector<4, T> translate = Types::TVector<4, T>(_translate, static_cast<T>(1));
result[0][3] = detail::ComputeDot(result[0], translate);
result[1][3] = detail::ComputeDot(result[1], translate);
result[2][3] = detail::ComputeDot(result[2], translate);
#endif
return result;
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeRotate(Types::TMatrix<4, 4, T> const &object, Types::TVector<3, T> const &axis, T angle) noexcept
{
T const sinAngle = std::sin(angle);
T const cosAngle = std::cos(angle);
Types::TVector<3, T> normalizedAxis = Types::TVector<3, T>(ComputeNormalize(axis));
Types::TVector<3, T> modifier = Types::TVector<3, T>(normalizedAxis * (static_cast<T>(1) - cosAngle));
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
Types::TMatrix<3, 3, T> rotateMatrix = Types::TMatrix<3, 3, T>
(
cosAngle + modifier.x * normalizedAxis.x, modifier.y * normalizedAxis.x - sinAngle * normalizedAxis.z, modifier.z * normalizedAxis.x + sinAngle * normalizedAxis.y,
modifier.x * normalizedAxis.y + sinAngle * normalizedAxis.z, cosAngle + modifier.y * normalizedAxis.y, modifier.z * normalizedAxis.y - sinAngle * normalizedAxis.x,
modifier.x * normalizedAxis.z - sinAngle * normalizedAxis.y, modifier.y * normalizedAxis.z + sinAngle * normalizedAxis.x, cosAngle + modifier.z * normalizedAxis.z
);
return Types::TMatrix<4, 4, T>
(
object[0] * rotateMatrix[0][0] + object[1] * rotateMatrix[1][0] + object[2] * rotateMatrix[2][0],
object[0] * rotateMatrix[0][1] + object[1] * rotateMatrix[1][1] + object[2] * rotateMatrix[2][1],
object[0] * rotateMatrix[0][2] + object[1] * rotateMatrix[1][2] + object[2] * rotateMatrix[2][2],
object[3]
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
Types::TMatrix<3, 3, T> transposedRotateMatrix = Types::TMatrix<3, 3, T>
(
cosAngle + modifier.x * normalizedAxis.x, modifier.x * normalizedAxis.y + sinAngle * normalizedAxis.z, modifier.x * normalizedAxis.z - sinAngle * normalizedAxis.y,
modifier.y * normalizedAxis.x - sinAngle * normalizedAxis.z, cosAngle + modifier.y * normalizedAxis.y, modifier.y * normalizedAxis.z + sinAngle * normalizedAxis.x,
modifier.z * normalizedAxis.x + sinAngle * normalizedAxis.y, modifier.z * normalizedAxis.y - sinAngle * normalizedAxis.x, cosAngle + modifier.z * normalizedAxis.z
);
Types::TMatrix<4, 3, T> object4x3 = Types::TMatrix<4, 3, T>::FromMatrix4x4(object);
return Types::TMatrix<4, 4, T>
(
detail::ComputeDot(object4x3[0], transposedRotateMatrix[0]), detail::ComputeDot(object4x3[0], transposedRotateMatrix[1]), detail::ComputeDot(object4x3[0], transposedRotateMatrix[2]), object[0][3],
detail::ComputeDot(object4x3[1], transposedRotateMatrix[0]), detail::ComputeDot(object4x3[1], transposedRotateMatrix[1]), detail::ComputeDot(object4x3[1], transposedRotateMatrix[2]), object[1][3],
detail::ComputeDot(object4x3[2], transposedRotateMatrix[0]), detail::ComputeDot(object4x3[2], transposedRotateMatrix[1]), detail::ComputeDot(object4x3[2], transposedRotateMatrix[2]), object[2][3],
detail::ComputeDot(object4x3[3], transposedRotateMatrix[0]), detail::ComputeDot(object4x3[3], transposedRotateMatrix[1]), detail::ComputeDot(object4x3[3], transposedRotateMatrix[2]), object[3][3]
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeScale(Types::TMatrix<4, 4, T> const &object, Types::TVector<3, T> const &_scale) noexcept
{
Types::TMatrix<4, 4, T> result = object;
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
result[0] = object[0] * _scale[0];
result[1] = object[1] * _scale[1];
result[2] = object[2] * _scale[2];
result[3] = object[3];
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
Types::TVector<4, T> scale = Types::TVector<4, T>(_scale, 1);
result[0] *= scale;
result[1] *= scale;
result[2] *= scale;
result[3] *= scale;
#endif
return result;
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeLookAtRightHandedMatrix(Types::TVector<3, T> const &eye, Types::TVector<3, T> const &target, Types::TVector<3, T> const &_up) noexcept
{
Types::TVector<3, T> const forward = Types::TVector<3, T>(detail::ComputeNormalize(target - eye));
Types::TVector<3, T> const side = Types::TVector<3, T>(detail::ComputeNormalize(detail::ComputeCross(forward, _up)));
Types::TVector<3, T> const up = Types::TVector<3, T>(detail::ComputeCross(side, forward));
T const zero = static_cast<T>(0);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
side.x, up.x, -forward.x, zero,
side.y, up.y, -forward.y, zero,
side.z, up.z, -forward.z, zero,
-detail::ComputeDot(side, eye), -detail::ComputeDot(up, eye), detail::ComputeDot(forward, eye), static_cast<T>(1)
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
side.x, side.y, side.z, -detail::ComputeDot(side, eye),
up.x, up.y, up.z, -detail::ComputeDot(up, eye),
-forward.x, -forward.y, -forward.z, detail::ComputeDot(forward, eye),
zero, zero, zero, static_cast<T>(1)
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeLookAtLeftHandedMatrix(Types::TVector<3, T> const &eye, Types::TVector<3, T> const &target, Types::TVector<3, T> const &_up) noexcept
{
Types::TVector<3, T> const forward = Types::TVector<3, T>(detail::ComputeNormalize(target - eye));
Types::TVector<3, T> const side = Types::TVector<3, T>(detail::ComputeNormalize(detail::ComputeCross(_up, forward)));
Types::TVector<3, T> const up = Types::TVector<3, T>(detail::ComputeCross(forward, side));
T const zero = static_cast<T>(0);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
side.x, up.x, forward.x, zero,
side.y, up.y, forward.y, zero,
side.z, up.z, forward.z, zero,
-detail::ComputeDot(side, eye), -detail::ComputeDot(up, eye), -detail::ComputeDot(forward, eye), static_cast<T>(1)
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
side.x, side.y, side.z, -detail::ComputeDot(side, eye),
up.x, up.y, up.z, -detail::ComputeDot(up, eye),
forward.x, forward.y, forward.z, -detail::ComputeDot(forward, eye),
zero, zero, zero, static_cast<T>(1)
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeSimpleOrthoMatrix(T left, T top, T right, T bottom) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, zero,
zero, two / (top - bottom), zero, zero,
zero, zero, -one, zero,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), zero, one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, -(right + left) / (right - left),
zero, two / (top - bottom), zero, -(top + bottom) / (top - bottom),
zero, zero, -one, zero,
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeOrthoRightHandedFromZeroToOneMatrix(T left, T top, T right, T bottom, T zNear, T zFar) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, zero,
zero, two / (top - bottom), zero, zero,
zero, zero, -one / (zFar - zNear), zero,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -zNear / (zFar - zNear), one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, -(right + left) / (right - left),
zero, two / (top - bottom), zero, -(top + bottom) / (top - bottom),
zero, zero, -one / (zFar - zNear), -zNear / (zFar - zNear),
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeOrthoRightHandedFromNegativeToOneMatrix(T left, T top, T right, T bottom, T zNear, T zFar) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, zero,
zero, two / (top - bottom), zero, zero,
zero, zero, -two / (zFar - zNear), zero,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(zFar + zNear) / (zFar - zNear), one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, -(right + left) / (right - left),
zero, two / (top - bottom), zero, -(top + bottom) / (top - bottom),
zero, zero, -two / (zFar - zNear), -(zFar + zNear) / (zFar - zNear),
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeOrthoLeftHandedFromZeroToOneMatrix(T left, T top, T right, T bottom, T zNear, T zFar) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, zero,
zero, two / (top - bottom), zero, zero,
zero, zero, one / (zFar - zNear), zero,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -zNear / (zFar - zNear), one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, -(right + left) / (right - left),
zero, two / (top - bottom), zero, -(top + bottom) / (top - bottom),
zero, zero, one / (zFar - zNear), -zNear / (zFar - zNear),
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputeOrthoLeftHandedFromNegativeToOneMatrix(T left, T top, T right, T bottom, T zNear, T zFar) noexcept
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, zero,
zero, two / (top - bottom), zero, zero,
zero, zero, two / (zFar - zNear), zero,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(zFar + zNear) / (zFar - zNear), one
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
two / (right - left), zero, zero, -(right + left) / (right - left),
zero, two / (top - bottom), zero, -(top + bottom) / (top - bottom),
zero, zero, two / (zFar - zNear), -(zFar + zNear) / (zFar - zNear),
zero, zero, zero, one
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputePerspectiveRightHandedFromZeroToOneMatrix(T fovy, T aspect, T zNear, T zFar) noexcept
{
T const tanHalfFovy = std::tan(fovy / static_cast<T>(2));
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / tanHalfFovy, zero, zero,
zero, zero, zFar / (zNear - zFar), -one,
zero, zero, -(zFar * zNear) / (zFar - zNear), zero
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / tanHalfFovy, zero, zero,
zero, zero, zFar / (zNear - zFar), -(zFar * zNear) / (zFar - zNear),
zero, zero, -one, zero
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputePerspectiveRightHandedFromNegativeToOneMatrix(T fovy, T aspect, T zNear, T zFar) noexcept
{
T const tanHalfFovy = std::tan(fovy / static_cast<T>(2));
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, -(zFar + zNear) / (zFar - zNear), -one,
zero, zero, -(static_cast<T>(2) * zFar * zNear) / (zFar - zNear), zero
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, -(zFar + zNear) / (zFar - zNear), -(static_cast<T>(2) * zFar * zNear) / (zFar - zNear),
zero, zero, -one, zero
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputePerspectiveLeftHandedFromZeroToOneMatrix(T fovy, T aspect, T zNear, T zFar) noexcept
{
T const tanHalfFovy = std::tan(fovy / static_cast<T>(2));
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, zFar / (zFar - zNear), one,
zero, zero, -(zFar * zNear) / (zFar - zNear), zero
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, zFar / (zFar - zNear), -(zFar * zNear) / (zFar - zNear),
zero, zero, one, zero
);
#endif
}
template <typename T>
constexpr Types::TMatrix<4, 4, T> ComputePerspectiveLeftHandedFromNegativeToOneMatrix(T fovy, T aspect, T zNear, T zFar) noexcept
{
T const tanHalfFovy = std::tan(fovy / static_cast<T>(2));
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
#ifdef IO_MATH_COLUMN_MAJOR_MATRIX_ORDER
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, (zFar + zNear) / (zFar - zNear), one,
zero, zero, -(static_cast<T>(2) * zFar * zNear) / (zFar - zNear), zero
);
#elif defined(IO_MATH_ROW_MAJOR_MATRIX_ORDER)
return Types::TMatrix<4, 4, T>
(
one / (aspect * tanHalfFovy), zero, zero, zero,
zero, one / (tanHalfFovy), zero, zero,
zero, zero, (zFar + zNear) / (zFar - zNear), -(static_cast<T>(2) * zFar * zNear) / (zFar - zNear),
zero, zero, one, zero
);
#endif
}
}
}
#endif | 40.76875 | 201 | 0.649905 | [
"object"
] |
0d198356ec7f9ca6abf11a4b2271061996282c82 | 753 | cpp | C++ | 0000/10/17a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 1 | 2020-07-03T15:55:52.000Z | 2020-07-03T15:55:52.000Z | 0000/10/17a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | null | null | null | 0000/10/17a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 3 | 2020-10-01T14:55:28.000Z | 2021-07-11T11:33:58.000Z | #include <algorithm>
#include <iostream>
#include <vector>
void answer(bool v)
{
constexpr const char* s[2] = { "NO", "YES" };
std::cout << s[v] << '\n';
}
void solve(unsigned n, unsigned k)
{
std::vector<unsigned> primes = { 2 };
for (unsigned x = 3; x <= n; x += 2) {
if (std::any_of(primes.cbegin(), primes.cend(), [x](unsigned p) { return x % p == 0; }))
continue;
primes.push_back(x);
}
unsigned c = 0;
for (size_t i = 1; i < primes.size(); ++i) {
if (std::find(primes.cbegin(), primes.cend(), primes[i-1] + primes[i] + 1) != primes.cend())
++c;
}
answer(c >= k);
}
int main()
{
unsigned n, k;
std::cin >> n >> k;
solve(n, k);
return 0;
}
| 18.825 | 100 | 0.499336 | [
"vector"
] |
0d1e492c777d2997044d54ac956adc57fa5b5638 | 31,532 | cc | C++ | wrappers/8.1.1/vtkChartXYWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/8.1.1/vtkChartXYWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/8.1.1/vtkChartXYWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkChartWrap.h"
#include "vtkChartXYWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkContext2DWrap.h"
#include "vtkPlotWrap.h"
#include "vtkAxisWrap.h"
#include "vtkChartLegendWrap.h"
#include "vtkTooltipItemWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkChartXYWrap::ptpl;
VtkChartXYWrap::VtkChartXYWrap()
{ }
VtkChartXYWrap::VtkChartXYWrap(vtkSmartPointer<vtkChartXY> _native)
{ native = _native; }
VtkChartXYWrap::~VtkChartXYWrap()
{ }
void VtkChartXYWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkChartXY").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("ChartXY").ToLocalChecked(), ConstructorGetter);
}
void VtkChartXYWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkChartXYWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkChartWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkChartWrap::ptpl));
tpl->SetClassName(Nan::New("VtkChartXYWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "AddPlot", AddPlot);
Nan::SetPrototypeMethod(tpl, "addPlot", AddPlot);
Nan::SetPrototypeMethod(tpl, "AdjustLowerBoundForLogPlotOff", AdjustLowerBoundForLogPlotOff);
Nan::SetPrototypeMethod(tpl, "adjustLowerBoundForLogPlotOff", AdjustLowerBoundForLogPlotOff);
Nan::SetPrototypeMethod(tpl, "AdjustLowerBoundForLogPlotOn", AdjustLowerBoundForLogPlotOn);
Nan::SetPrototypeMethod(tpl, "adjustLowerBoundForLogPlotOn", AdjustLowerBoundForLogPlotOn);
Nan::SetPrototypeMethod(tpl, "AutoAxesOff", AutoAxesOff);
Nan::SetPrototypeMethod(tpl, "autoAxesOff", AutoAxesOff);
Nan::SetPrototypeMethod(tpl, "AutoAxesOn", AutoAxesOn);
Nan::SetPrototypeMethod(tpl, "autoAxesOn", AutoAxesOn);
Nan::SetPrototypeMethod(tpl, "ClearPlots", ClearPlots);
Nan::SetPrototypeMethod(tpl, "clearPlots", ClearPlots);
Nan::SetPrototypeMethod(tpl, "DragPointAlongXOff", DragPointAlongXOff);
Nan::SetPrototypeMethod(tpl, "dragPointAlongXOff", DragPointAlongXOff);
Nan::SetPrototypeMethod(tpl, "DragPointAlongXOn", DragPointAlongXOn);
Nan::SetPrototypeMethod(tpl, "dragPointAlongXOn", DragPointAlongXOn);
Nan::SetPrototypeMethod(tpl, "DragPointAlongYOff", DragPointAlongYOff);
Nan::SetPrototypeMethod(tpl, "dragPointAlongYOff", DragPointAlongYOff);
Nan::SetPrototypeMethod(tpl, "DragPointAlongYOn", DragPointAlongYOn);
Nan::SetPrototypeMethod(tpl, "dragPointAlongYOn", DragPointAlongYOn);
Nan::SetPrototypeMethod(tpl, "DrawAxesAtOriginOff", DrawAxesAtOriginOff);
Nan::SetPrototypeMethod(tpl, "drawAxesAtOriginOff", DrawAxesAtOriginOff);
Nan::SetPrototypeMethod(tpl, "DrawAxesAtOriginOn", DrawAxesAtOriginOn);
Nan::SetPrototypeMethod(tpl, "drawAxesAtOriginOn", DrawAxesAtOriginOn);
Nan::SetPrototypeMethod(tpl, "ForceAxesToBoundsOff", ForceAxesToBoundsOff);
Nan::SetPrototypeMethod(tpl, "forceAxesToBoundsOff", ForceAxesToBoundsOff);
Nan::SetPrototypeMethod(tpl, "ForceAxesToBoundsOn", ForceAxesToBoundsOn);
Nan::SetPrototypeMethod(tpl, "forceAxesToBoundsOn", ForceAxesToBoundsOn);
Nan::SetPrototypeMethod(tpl, "GetAdjustLowerBoundForLogPlot", GetAdjustLowerBoundForLogPlot);
Nan::SetPrototypeMethod(tpl, "getAdjustLowerBoundForLogPlot", GetAdjustLowerBoundForLogPlot);
Nan::SetPrototypeMethod(tpl, "GetAutoAxes", GetAutoAxes);
Nan::SetPrototypeMethod(tpl, "getAutoAxes", GetAutoAxes);
Nan::SetPrototypeMethod(tpl, "GetAxis", GetAxis);
Nan::SetPrototypeMethod(tpl, "getAxis", GetAxis);
Nan::SetPrototypeMethod(tpl, "GetBarWidthFraction", GetBarWidthFraction);
Nan::SetPrototypeMethod(tpl, "getBarWidthFraction", GetBarWidthFraction);
Nan::SetPrototypeMethod(tpl, "GetDragPointAlongX", GetDragPointAlongX);
Nan::SetPrototypeMethod(tpl, "getDragPointAlongX", GetDragPointAlongX);
Nan::SetPrototypeMethod(tpl, "GetDragPointAlongY", GetDragPointAlongY);
Nan::SetPrototypeMethod(tpl, "getDragPointAlongY", GetDragPointAlongY);
Nan::SetPrototypeMethod(tpl, "GetDrawAxesAtOrigin", GetDrawAxesAtOrigin);
Nan::SetPrototypeMethod(tpl, "getDrawAxesAtOrigin", GetDrawAxesAtOrigin);
Nan::SetPrototypeMethod(tpl, "GetForceAxesToBounds", GetForceAxesToBounds);
Nan::SetPrototypeMethod(tpl, "getForceAxesToBounds", GetForceAxesToBounds);
Nan::SetPrototypeMethod(tpl, "GetHiddenAxisBorder", GetHiddenAxisBorder);
Nan::SetPrototypeMethod(tpl, "getHiddenAxisBorder", GetHiddenAxisBorder);
Nan::SetPrototypeMethod(tpl, "GetLegend", GetLegend);
Nan::SetPrototypeMethod(tpl, "getLegend", GetLegend);
Nan::SetPrototypeMethod(tpl, "GetPlotCorner", GetPlotCorner);
Nan::SetPrototypeMethod(tpl, "getPlotCorner", GetPlotCorner);
Nan::SetPrototypeMethod(tpl, "GetTooltip", GetTooltip);
Nan::SetPrototypeMethod(tpl, "getTooltip", GetTooltip);
Nan::SetPrototypeMethod(tpl, "GetZoomWithMouseWheel", GetZoomWithMouseWheel);
Nan::SetPrototypeMethod(tpl, "getZoomWithMouseWheel", GetZoomWithMouseWheel);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "Paint", Paint);
Nan::SetPrototypeMethod(tpl, "paint", Paint);
Nan::SetPrototypeMethod(tpl, "RecalculateBounds", RecalculateBounds);
Nan::SetPrototypeMethod(tpl, "recalculateBounds", RecalculateBounds);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetAdjustLowerBoundForLogPlot", SetAdjustLowerBoundForLogPlot);
Nan::SetPrototypeMethod(tpl, "setAdjustLowerBoundForLogPlot", SetAdjustLowerBoundForLogPlot);
Nan::SetPrototypeMethod(tpl, "SetAutoAxes", SetAutoAxes);
Nan::SetPrototypeMethod(tpl, "setAutoAxes", SetAutoAxes);
Nan::SetPrototypeMethod(tpl, "SetBarWidthFraction", SetBarWidthFraction);
Nan::SetPrototypeMethod(tpl, "setBarWidthFraction", SetBarWidthFraction);
Nan::SetPrototypeMethod(tpl, "SetDragPointAlongX", SetDragPointAlongX);
Nan::SetPrototypeMethod(tpl, "setDragPointAlongX", SetDragPointAlongX);
Nan::SetPrototypeMethod(tpl, "SetDragPointAlongY", SetDragPointAlongY);
Nan::SetPrototypeMethod(tpl, "setDragPointAlongY", SetDragPointAlongY);
Nan::SetPrototypeMethod(tpl, "SetDrawAxesAtOrigin", SetDrawAxesAtOrigin);
Nan::SetPrototypeMethod(tpl, "setDrawAxesAtOrigin", SetDrawAxesAtOrigin);
Nan::SetPrototypeMethod(tpl, "SetForceAxesToBounds", SetForceAxesToBounds);
Nan::SetPrototypeMethod(tpl, "setForceAxesToBounds", SetForceAxesToBounds);
Nan::SetPrototypeMethod(tpl, "SetHiddenAxisBorder", SetHiddenAxisBorder);
Nan::SetPrototypeMethod(tpl, "setHiddenAxisBorder", SetHiddenAxisBorder);
Nan::SetPrototypeMethod(tpl, "SetPlotCorner", SetPlotCorner);
Nan::SetPrototypeMethod(tpl, "setPlotCorner", SetPlotCorner);
Nan::SetPrototypeMethod(tpl, "SetSelectionMethod", SetSelectionMethod);
Nan::SetPrototypeMethod(tpl, "setSelectionMethod", SetSelectionMethod);
Nan::SetPrototypeMethod(tpl, "SetShowLegend", SetShowLegend);
Nan::SetPrototypeMethod(tpl, "setShowLegend", SetShowLegend);
Nan::SetPrototypeMethod(tpl, "SetTooltip", SetTooltip);
Nan::SetPrototypeMethod(tpl, "setTooltip", SetTooltip);
Nan::SetPrototypeMethod(tpl, "SetZoomWithMouseWheel", SetZoomWithMouseWheel);
Nan::SetPrototypeMethod(tpl, "setZoomWithMouseWheel", SetZoomWithMouseWheel);
Nan::SetPrototypeMethod(tpl, "Update", Update);
Nan::SetPrototypeMethod(tpl, "update", Update);
Nan::SetPrototypeMethod(tpl, "ZoomWithMouseWheelOff", ZoomWithMouseWheelOff);
Nan::SetPrototypeMethod(tpl, "zoomWithMouseWheelOff", ZoomWithMouseWheelOff);
Nan::SetPrototypeMethod(tpl, "ZoomWithMouseWheelOn", ZoomWithMouseWheelOn);
Nan::SetPrototypeMethod(tpl, "zoomWithMouseWheelOn", ZoomWithMouseWheelOn);
#ifdef VTK_NODE_PLUS_VTKCHARTXYWRAP_INITPTPL
VTK_NODE_PLUS_VTKCHARTXYWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkChartXYWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkChartXY> native = vtkSmartPointer<vtkChartXY>::New();
VtkChartXYWrap* obj = new VtkChartXYWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkChartXYWrap::AddPlot(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
vtkPlot * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->AddPlot(
info[0]->Int32Value()
);
VtkPlotWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPlotWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPlotWrap *w = new VtkPlotWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::AdjustLowerBoundForLogPlotOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AdjustLowerBoundForLogPlotOff();
}
void VtkChartXYWrap::AdjustLowerBoundForLogPlotOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AdjustLowerBoundForLogPlotOn();
}
void VtkChartXYWrap::AutoAxesOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AutoAxesOff();
}
void VtkChartXYWrap::AutoAxesOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AutoAxesOn();
}
void VtkChartXYWrap::ClearPlots(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ClearPlots();
}
void VtkChartXYWrap::DragPointAlongXOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DragPointAlongXOff();
}
void VtkChartXYWrap::DragPointAlongXOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DragPointAlongXOn();
}
void VtkChartXYWrap::DragPointAlongYOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DragPointAlongYOff();
}
void VtkChartXYWrap::DragPointAlongYOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DragPointAlongYOn();
}
void VtkChartXYWrap::DrawAxesAtOriginOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawAxesAtOriginOff();
}
void VtkChartXYWrap::DrawAxesAtOriginOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawAxesAtOriginOn();
}
void VtkChartXYWrap::ForceAxesToBoundsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ForceAxesToBoundsOff();
}
void VtkChartXYWrap::ForceAxesToBoundsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ForceAxesToBoundsOn();
}
void VtkChartXYWrap::GetAdjustLowerBoundForLogPlot(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetAdjustLowerBoundForLogPlot();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetAutoAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetAutoAxes();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetAxis(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
vtkAxis * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetAxis(
info[0]->Int32Value()
);
VtkAxisWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkAxisWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkAxisWrap *w = new VtkAxisWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::GetBarWidthFraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
float r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBarWidthFraction();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetDragPointAlongX(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDragPointAlongX();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetDragPointAlongY(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDragPointAlongY();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetDrawAxesAtOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawAxesAtOrigin();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetForceAxesToBounds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetForceAxesToBounds();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetHiddenAxisBorder(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetHiddenAxisBorder();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::GetLegend(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
vtkChartLegend * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLegend();
VtkChartLegendWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkChartLegendWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkChartLegendWrap *w = new VtkChartLegendWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkChartXYWrap::GetPlotCorner(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPlotWrap::ptpl))->HasInstance(info[0]))
{
VtkPlotWrap *a0 = ObjectWrap::Unwrap<VtkPlotWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPlotCorner(
(vtkPlot *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::GetTooltip(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
vtkTooltipItem * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTooltip();
VtkTooltipItemWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTooltipItemWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTooltipItemWrap *w = new VtkTooltipItemWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkChartXYWrap::GetZoomWithMouseWheel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
bool r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetZoomWithMouseWheel();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkChartXYWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
vtkChartXY * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkChartXYWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkChartXYWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkChartXYWrap *w = new VtkChartXYWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkChartXYWrap::Paint(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkContext2DWrap::ptpl))->HasInstance(info[0]))
{
VtkContext2DWrap *a0 = ObjectWrap::Unwrap<VtkContext2DWrap>(info[0]->ToObject());
bool r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Paint(
(vtkContext2D *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::RecalculateBounds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->RecalculateBounds();
}
void VtkChartXYWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
vtkChartXY * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
VtkChartXYWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkChartXYWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkChartXYWrap *w = new VtkChartXYWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetAdjustLowerBoundForLogPlot(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetAdjustLowerBoundForLogPlot(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetAutoAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetAutoAxes(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetBarWidthFraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBarWidthFraction(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetDragPointAlongX(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDragPointAlongX(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetDragPointAlongY(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDragPointAlongY(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetDrawAxesAtOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawAxesAtOrigin(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetForceAxesToBounds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetForceAxesToBounds(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetHiddenAxisBorder(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetHiddenAxisBorder(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetPlotCorner(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPlotWrap::ptpl))->HasInstance(info[0]))
{
VtkPlotWrap *a0 = ObjectWrap::Unwrap<VtkPlotWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlotCorner(
(vtkPlot *) a0->native.GetPointer(),
info[1]->Int32Value()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetSelectionMethod(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSelectionMethod(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetShowLegend(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetShowLegend(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetTooltip(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTooltipItemWrap::ptpl))->HasInstance(info[0]))
{
VtkTooltipItemWrap *a0 = ObjectWrap::Unwrap<VtkTooltipItemWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTooltip(
(vtkTooltipItem *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::SetZoomWithMouseWheel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsBoolean())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetZoomWithMouseWheel(
info[0]->BooleanValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkChartXYWrap::Update(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Update();
}
void VtkChartXYWrap::ZoomWithMouseWheelOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ZoomWithMouseWheelOff();
}
void VtkChartXYWrap::ZoomWithMouseWheelOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkChartXYWrap *wrapper = ObjectWrap::Unwrap<VtkChartXYWrap>(info.Holder());
vtkChartXY *native = (vtkChartXY *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ZoomWithMouseWheelOn();
}
| 31.06601 | 107 | 0.725136 | [
"object"
] |
0d22b9921037dda3f4fc5758082ab46cee35d22c | 5,699 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcElementQuantity.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcElementQuantity.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcElementQuantity.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcElementQuantity.h"
#include "include/IfcGloballyUniqueId.h"
#include "include/IfcLabel.h"
#include "include/IfcOwnerHistory.h"
#include "include/IfcPhysicalQuantity.h"
#include "include/IfcRelAssociates.h"
#include "include/IfcRelDeclares.h"
#include "include/IfcRelDefinesByProperties.h"
#include "include/IfcRelDefinesByTemplate.h"
#include "include/IfcText.h"
#include "include/IfcTypeObject.h"
// ENTITY IfcElementQuantity
IfcElementQuantity::IfcElementQuantity() { m_entity_enum = IFCELEMENTQUANTITY; }
IfcElementQuantity::IfcElementQuantity( int id ) { m_id = id; m_entity_enum = IFCELEMENTQUANTITY; }
IfcElementQuantity::~IfcElementQuantity() {}
shared_ptr<IfcPPObject> IfcElementQuantity::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcElementQuantity> copy_self( new IfcElementQuantity() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createGUID32_wstr().c_str() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_MethodOfMeasurement ) { copy_self->m_MethodOfMeasurement = dynamic_pointer_cast<IfcLabel>( m_MethodOfMeasurement->getDeepCopy(options) ); }
for( size_t ii=0; ii<m_Quantities.size(); ++ii )
{
auto item_ii = m_Quantities[ii];
if( item_ii )
{
copy_self->m_Quantities.push_back( dynamic_pointer_cast<IfcPhysicalQuantity>(item_ii->getDeepCopy(options) ) );
}
}
return copy_self;
}
void IfcElementQuantity::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCELEMENTQUANTITY" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_MethodOfMeasurement ) { m_MethodOfMeasurement->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
writeEntityList( stream, m_Quantities );
stream << ");";
}
void IfcElementQuantity::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcElementQuantity::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 6 ){ std::stringstream err; err << "Wrong parameter count for entity IfcElementQuantity, expecting 6, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0] );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2] );
m_Description = IfcText::createObjectFromSTEP( args[3] );
m_MethodOfMeasurement = IfcLabel::createObjectFromSTEP( args[4] );
readEntityReferenceList( args[5], m_Quantities, map );
}
void IfcElementQuantity::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcQuantitySet::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "MethodOfMeasurement", m_MethodOfMeasurement ) );
if( m_Quantities.size() > 0 )
{
shared_ptr<IfcPPAttributeObjectVector> Quantities_vec_object( new IfcPPAttributeObjectVector() );
std::copy( m_Quantities.begin(), m_Quantities.end(), std::back_inserter( Quantities_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "Quantities", Quantities_vec_object ) );
}
}
void IfcElementQuantity::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcQuantitySet::getAttributesInverse( vec_attributes_inverse );
}
void IfcElementQuantity::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcQuantitySet::setInverseCounterparts( ptr_self_entity );
}
void IfcElementQuantity::unlinkFromInverseCounterparts()
{
IfcQuantitySet::unlinkFromInverseCounterparts();
}
| 49.556522 | 226 | 0.736971 | [
"vector",
"model"
] |
0d23842010111b4f979dad06c592ccf735b09378 | 30,571 | cpp | C++ | hackathon/fl_cellseg/src/FL_evolve.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/fl_cellseg/src/FL_evolve.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | hackathon/fl_cellseg/src/FL_evolve.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | // curve/surface evolution according to the level set evolution equation in Chunming Li et al's paper:
// "Level Set Evolution Without Reinitialization: A New Variational Formulation"
// in Proceedings CVPR'2005
//latest 200910107
#ifndef __EVOLVE_CPP__
#define __EVOLVE_CPP__
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "img_definition.h"
#include "stackutil.h"
#include "basic_memory.h"
//compute 2D gradient
template <class T> void gradient(T **image, float **fx, float **fy, const V3DLONG *sz)
{
int x,y;
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
fx[y][x] = 0;
fy[y][x] = 0;
}
// y dimension
for(y=1;y<sz[1]-1;y++)
for(x=0;x<sz[0];x++)
{
fy[y][x] = ((float)image[y+1][x] - (float)image[y-1][x])/2;
}
//deal with margin
for(x=0;x<sz[0];x++)
{
fy[0][x] = (float)image[1][x] - (float)image[0][x];
fy[sz[1]-1][x] = (float)image[sz[1]-1][x] - (float)image[sz[1]-2][x];
}
// x dimension
for(y=0;y<sz[1];y++)
for(x=1;x<sz[0]-1;x++)
{
fx[y][x] = ((float)image[y][x+1] - (float)image[y][x-1])/2;
}
//deal with margin
for(y=0;y<sz[1];y++)
{
fx[y][0] = (float)image[y][1] - (float)image[y][0];
fx[y][sz[0]-1] = (float)image[y][sz[0]-1] - (float)image[y][sz[0]-2];
}
return;
}
//compute 3D gradient
template <class T> void gradient(T ***image, float ***fx, float ***fy, float ***fz, const V3DLONG *sz)
{
int x,y,z;
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
fx[z][y][x] = 0;
fy[z][y][x] = 0;
fz[z][y][x] = 0;
}
// z dimension
for(z=1;z<sz[2]-1;z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
fz[z][y][x] = ((float)image[z+1][y][x] - (float)image[z-1][y][x])/2;
}
//deal with margin
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
fz[0][y][x] = (float)image[1][y][x] - (float)image[0][y][x];
fz[sz[2]-1][y][x] = (float)image[sz[2]-1][y][x] - (float)image[sz[2]-2][y][x];
}
// y dimension
for(y=1;y<sz[1]-1;y++)
for(z=0;z<sz[2];z++)
for(x=0;x<sz[0];x++)
{
fy[z][y][x] = ((float)image[z][y+1][x] - (float)image[z][y-1][x])/2;
}
//deal with margin
for(z=0;z<sz[2];z++)
for(x=0;x<sz[0];x++)
{
fy[z][0][x] = (float)image[z][1][x] - (float)image[z][0][x];
fy[z][sz[1]-1][x] = (float)image[z][sz[1]-1][x] - (float)image[z][sz[1]-2][x];
}
// x dimension
for(x=1;x<sz[0]-1;x++)
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
{
fx[z][y][x] = ((float)image[z][y][x+1] - (float)image[z][y][x-1])/2;
}
//deal with margin
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
{
fx[z][y][0] = (float)image[z][y][1] - (float)image[z][y][0];
fx[z][y][sz[0]-1] = (float)image[z][y][sz[0]-1] - (float)image[z][y][sz[0]-2];
}
return;
}
//Normalize 2D gradient
void gradientNoramlize(float **fx, float **fy, const V3DLONG *sz)
{
int x,y;
float tmp;
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
tmp = sqrt(fx[y][x]*fx[y][x] + fy[y][x]*fy[y][x] + 1e-10);
fx[y][x] = fx[y][x]/tmp;
fy[y][x] = fy[y][x]/tmp;
}
}
//Normalize 3D gradient
void gradientNoramlize(float ***fx, float ***fy, float ***fz, const V3DLONG *sz)
{
int x,y,z;
float tmp;
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
tmp = sqrt(fx[z][y][x]*fx[z][y][x] + fy[z][y][x]*fy[z][y][x] + fz[z][y][x]*fz[z][y][x]+ 1e-10);
fx[z][y][x] = fx[z][y][x]/tmp;
fy[z][y][x] = fy[z][y][x]/tmp;
fz[z][y][x] = fz[z][y][x]/tmp;
}
}
//compute 2D laplacian
template <class T> void laplacian(T **image, float **lap, const V3DLONG *sz)
{
int x,y;
float **laptmp = 0, *laptmp1d=0;
laptmp1d = new float [sz[0]*sz[1]];
if (laptmp1d)
new2dpointer(laptmp, sz[0], sz[1], laptmp1d);
// initializing lap and laptmp to 0 decreases speed, not necessary here, but safe
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[y][x] = 0;
laptmp[y][x] = 0;
}
// y dimension
for(y=1;y<sz[1]-1;y++)
for(x=0;x<sz[0];x++)
{
lap[y][x] = ((float)image[y+1][x] + (float)image[y-1][x])/2 - (float)image[y][x];
}
// extrapolation
for (x=0;x<sz[0]; x++)
lap[0][x] = 2*(float)lap[1][x] - (float)lap[2][x];
for (x=0;x<sz[0]; x++)
lap[sz[1]-1][x] = -(float)lap[sz[1]-3][x] + 2*(float)lap[sz[1]-2][x];
// x dimension
for(y=0;y<sz[1];y++)
for(x=1;x<sz[0]-1;x++)
{
laptmp[y][x] = ((float)image[y][x+1] + (float)image[y][x-1])/2 - (float)image[y][x];
}
// extrapolation
for (y=0;y<sz[1]; y++)
laptmp[y][0] = 2*(float)laptmp[y][1] - (float)laptmp[y][2];
for (y=0;y<sz[1]; y++)
laptmp[y][sz[0]-1] = -(float)laptmp[y][sz[0]-3] + 2*(float)laptmp[y][sz[0]-2];
// combine x and y dimensions
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[y][x] = (lap[y][x]+laptmp[y][x])/2;
}
if (laptmp) delete2dpointer(laptmp, sz[0], sz[1]);
if (laptmp1d) {delete []laptmp1d; laptmp1d=0;}
}
//compute 3D laplacian
template <class T> void laplacian(T ***image, float ***lap, const V3DLONG *sz)
{
int x,y, z;
float ***laptmp = 0, *laptmp1d=0;
laptmp1d = new float [sz[0]*sz[1]*sz[2]];
if (laptmp1d)
new3dpointer(laptmp, sz[0], sz[1], sz[2], laptmp1d);
// initializing lap and laptmp to 0 decreases speed, not necessary here, but safe
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[z][y][x] = 0;
laptmp[z][y][x] = 0;
}
// z dimension
for(z=1;z<sz[2]-1;z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[z][y][x] = ((float)image[z+1][y][x] + (float)image[z-1][y][x])/2 - (float)image[z][y][x];
}
// extrapolation
for (y=0;y<sz[1];y++)
for (x=0;x<sz[0]; x++)
lap[0][y][x] = 2*(float)lap[1][y][x] - (float)lap[2][y][x];
for (y=0;y<sz[1];y++)
for (x=0;x<sz[0]; x++)
lap[sz[2]-1][y][x] = -(float)lap[sz[2]-3][y][x] + 2*(float)lap[sz[2]-2][y][x];
// y dimension
for(z=0;z<sz[2];z++)
for(y=1;y<sz[1]-1;y++)
for(x=0;x<sz[0];x++)
{
laptmp[z][y][x] = ((float)image[z][y+1][x] + (float)image[z][y-1][x])/2 - (float)image[z][y][x];
}
// extrapolation
for (z=0;z<sz[2];z++)
for (x=0;x<sz[0];x++)
laptmp[z][0][x] = 2*(float)laptmp[z][1][x] - (float)laptmp[z][2][x];
for (z=0;z<sz[2];z++)
for (x=0;x<sz[0];x++)
laptmp[z][sz[1]-1][x] = -(float)laptmp[z][sz[1]-3][x] + 2*(float)laptmp[z][sz[1]-2][x];
// combine y and z dimension
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[z][y][x]+=laptmp[z][y][x];
}
// x dimension
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=1;x<sz[0]-1;x++)
{
laptmp[z][y][x] = ((float)image[z][y][x+1] + (float)image[z][y][x-1])/2 - (float)image[z][y][x];
}
// extrapolation
for (z=0;z<sz[2];z++)
for (y=0;y<sz[1];y++)
laptmp[z][y][0] = 2*(float)laptmp[z][y][1] - (float)laptmp[z][y][2];
for (z=0;z<sz[2];z++)
for (y=0;y<sz[1];y++)
laptmp[z][y][sz[0]-1] = -(float)laptmp[z][y][sz[0]-3] + 2*(float)laptmp[z][y][sz[0]-2];
// combine x,y, and z dimension
for(z=0;z<sz[2];z++)
for(y=0;y<sz[1];y++)
for(x=0;x<sz[0];x++)
{
lap[z][y][x]=(lap[z][y][x] + laptmp[z][y][x])/3;
}
if (laptmp) delete3dpointer(laptmp, sz[0], sz[1], sz[2]);
if (laptmp1d) {delete []laptmp1d; laptmp1d=0;}
// for(z=1;z<sz[2]-1;z++)
// for(y=1;y<sz[1]-1;y++)
// for(x=1;x<sz[0]-1;x++)
// {
//// lap[z][y][x] = image[z][y][x+1] + image[z][y][x-1] + image[z][y+1][x] + image[z][y-1][x] + image[z+1][y][x] + image[z-1][y][x] - 6*image[z][y][x];
// lap[z][y][x] = (image[z][y][x+1] + image[z][y][x-1] + image[z][y+1][x] + image[z][y-1][x] + image[z+1][y][x] + image[z-1][y][x])/6 - image[z][y][x];
//
// }
}
//generate a smeared 2D dirac function, allocate memory of f2d before calling Dirac
// f2d is the output
//float **Dirac(float **x, float sigma, const V3DLONG *sz)
void Dirac(float **x, float sigma, const V3DLONG *sz, float **f2d)
{
// float *f1d, **f2d;
int i,j;
// //allocate memory for f2d
// V3DLONG tmplen = sz[0]*sz[1];
// if (tmplen>0 && sz[0]>0 && sz[1]>0)
// {
// f1d = new float [tmplen];
// if (f1d)
// {
// f2d = 0;
// new2dpointer(f2d, sz[0], sz[1], f1d);
// }
// }
//compute f2d
for(j=0; j<sz[1];j++)
for(i=0; i<sz[0]; i++)
{
if ((x[j][i]<=sigma) && (x[j][i]>=-sigma))
{
f2d[j][i]=(1.0/2.0/sigma)*(1+cos(3.1415926*x[j][i]/sigma)); // note if write 1/2, will cause serious problems
}
else
{
f2d[j][i] = 0;
}
}
// return f2d;
}
//generate a smeared 3D dirac function, not ready yet
void Dirac(float ***x, float sigma, const V3DLONG *sz, float ***f3d)
{
// float *f1d=0, ***f3d = 0;
int i,j,k;
// //allocate memory for f3d
// V3DLONG tmplen = sz[0]*sz[1]*sz[2];
// if (tmplen>0 && sz[0]>0 && sz[1]>0 && sz[2]>0)
// {
// f1d = new float [tmplen];
// if (f1d)
// new3dpointer(f3d, sz[0], sz[1], sz[2], f1d);
// }
//compute f3d
for(k=0; k<sz[2]; k++)
for(j=0; j<sz[1]; j++)
for(i=0; i<sz[0]; i++)
{
if ((x[k][j][i]<=sigma) && (x[k][j][i]>=-sigma))
{
f3d[k][j][i]=(1.0/2.0/sigma)*(1+cos(3.1415926*x[k][j][i]/sigma));
}
else
{
f3d[k][j][i] = 0;
}
}
// return f3d;
}
//compute 2D curvature, allocate memory of K before calling curvatureCentral
// K is the output
//float **curvatureCentral(float **nx, float **ny, const V3DLONG *sz, float **K)
void curvatureCentral(float **nx, float **ny, const V3DLONG *sz, float **K)
{
float **nxx=0,**nxy=0, **nyx=0, **nyy=0;
float *nxx1d=0, *nxy1d=0, *nyx1d=0, *nyy1d=0;
// float **nxx,**nxy, **nyx, **nyy, **K;
// float *nxx1d, *nxy1d, *nyx1d, *nyy1d, *K1d;
//allocat memory for nxx, nxy, nyx, nyy
V3DLONG tmplen = sz[0]*sz[1];
if (tmplen>0 && sz[0]>0 && sz[1]>0)
{
nxx1d = new float [tmplen];
if (nxx1d)
new2dpointer(nxx, sz[0], sz[1], nxx1d);
nxy1d = new float [tmplen];
if (nxy1d)
new2dpointer(nxy, sz[0], sz[1], nxy1d);
nyx1d = new float [tmplen];
if (nyx1d)
new2dpointer(nyx, sz[0], sz[1], nyx1d);
nyy1d = new float [tmplen];
if (nyy1d)
new2dpointer(nyy, sz[0], sz[1], nyy1d);
// K1d = new float [tmplen];
// if (K1d)
// {
// K = 0;
// new2dpointer(K, sz[0], sz[1], K1d);
// }
}
gradient(nx, nxx, nxy, sz);
gradient(ny, nyx, nyy, sz);
for (int j=0; j<sz[1]; j++)
for (int i=0; i<sz[0]; i++)
{
K[j][i] =nxx[j][i]+nyy[j][i];
}
// delete 1d and 2d pointers
if (nxx) delete2dpointer(nxx, sz[0], sz[1]);
if (nxx1d) {delete []nxx1d; nxx1d=0;}
if (nxy) delete2dpointer(nxy, sz[0], sz[1]);
if (nxy1d) {delete []nxy1d; nxy1d=0;}
if (nyx) delete2dpointer(nyx, sz[0], sz[1]);
if (nyx1d) {delete []nyx1d; nyx1d=0;}
if (nyy) delete2dpointer(nyy, sz[0], sz[1]);
if (nyy1d) {delete []nyy1d; nyy1d=0;}
// return K;
}
//compute 3D curvature, allocate memory of K before calling the function
// K is the output
float ***curvatureCentral(float ***nx, float ***ny, float ***nz, const V3DLONG *sz, float ***K)
{
float ***nxx=0,***nxy=0, ***nxz=0, ***nyx=0, ***nyy=0, ***nyz=0, ***nzx=0, ***nzy=0, ***nzz=0;
float *nxx1d=0, *nxy1d=0, *nxz1d=0, *nyx1d=0, *nyy1d=0, *nyz1d=0, *nzx1d=0, *nzy1d=0, *nzz1d=0;
//allocat memory for nxx, nxy, nxz, nyx, nyy, nyz, nzx, nzy, nzz;
V3DLONG tmplen = sz[0]*sz[1]*sz[2];
if (tmplen>0 && sz[0]>0 && sz[1]>0 && sz[2]>0)
{
nxx1d = new float [tmplen];
if (nxx1d)
new3dpointer(nxx, sz[0], sz[1], sz[2], nxx1d);
nxy1d = new float [tmplen];
if (nxy1d)
new3dpointer(nxy, sz[0], sz[1], sz[2], nxy1d);
nxz1d = new float [tmplen];
if (nxz1d)
new3dpointer(nxz, sz[0], sz[1], sz[2], nxz1d);
nyx1d = new float [tmplen];
if (nyx1d)
new3dpointer(nyx, sz[0], sz[1], sz[2], nyx1d);
nyy1d = new float [tmplen];
if (nyy1d)
new3dpointer(nyy, sz[0], sz[1], sz[2], nyy1d);
nyz1d = new float [tmplen];
if (nyz1d)
new3dpointer(nyz, sz[0], sz[1], sz[2], nyz1d);
nzx1d = new float [tmplen];
if (nzx1d)
new3dpointer(nzx, sz[0], sz[1], sz[2], nzx1d);
nzy1d = new float [tmplen];
if (nzy1d)
new3dpointer(nzy, sz[0], sz[1], sz[2], nzy1d);
nzz1d = new float [tmplen];
if (nzz1d)
new3dpointer(nzz, sz[0], sz[1], sz[2], nzz1d);
}
gradient(nx, nxx, nxy, nxz, sz);
gradient(ny, nyx, nyy, nyz, sz);
gradient(nz, nzx, nzy, nzz, sz);
for (int k=0; k<sz[2]; k++)
for (int j=0; j<sz[1]; j++)
for (int i=0; i<sz[0]; i++)
{
K[k][j][i] =nxx[k][j][i]+nyy[k][j][i] + nzz[k][j][i];
}
// delete 1d and 2d pointers
if (nxx) delete3dpointer(nxx, sz[0], sz[1], sz[2]);
if (nxx1d) {delete []nxx1d; nxx1d=0;}
if (nxy) delete3dpointer(nxy, sz[0], sz[1], sz[2]);
if (nxy1d) {delete []nxy1d; nxy1d=0;}
if (nxz) delete3dpointer(nxz, sz[0], sz[1], sz[2]);
if (nxz1d) {delete []nxz1d; nxz1d=0;}
if (nyx) delete3dpointer(nyx, sz[0], sz[1], sz[2]);
if (nyx1d) {delete []nyx1d; nyx1d=0;}
if (nyy) delete3dpointer(nyy, sz[0], sz[1], sz[2]);
if (nyy1d) {delete []nyy1d; nyy1d=0;}
if (nyz) delete3dpointer(nyz, sz[0], sz[1], sz[2]);
if (nyz1d) {delete []nyz1d; nyz1d=0;}
if (nzx) delete3dpointer(nzx, sz[0], sz[1], sz[2]);
if (nzx1d) {delete []nzx1d; nzx1d=0;}
if (nzy) delete3dpointer(nzy, sz[0], sz[1], sz[2]);
if (nzy1d) {delete []nzy1d; nzy1d=0;}
if (nzz) delete3dpointer(nzz, sz[0], sz[1], sz[2]);
if (nzz1d) {delete []nzz1d; nzz1d=0;}
// return K;
return K; //I un-comment this as MSVC compiler force to return the value check. 2010-05-20 by PHC
}
//Make a 2D function satisfy Neumann boundary condition
//float ** NeumannBoundCond(float **f, const V3DLONG *sz)
//void NeumannBoundCond(float ** &f, const V3DLONG *sz)
void NeumannBoundCond(float ** f, const V3DLONG *sz)
{
float **g=0, *g1d=0;
V3DLONG i,j;
//allocate memory for g
V3DLONG tmplen = sz[0]*sz[1];
if (tmplen>0 && sz[0]>0 && sz[1]>0)
{
g1d = new float [tmplen];
if (g1d)
new2dpointer(g, sz[0], sz[1], g1d);
}
for(j=0; j<sz[1]; j++)
for(i=0; i<sz[0]; i++)
{
g[j][i] = f[j][i];
}
g[0][0] = g[2][2];
g[0][sz[0]-1] = g[2][sz[0]-3];
g[sz[1]-1][0] = g[sz[1]-3][2];
g[sz[1]-1][sz[0]-1] = g[sz[1]-3][sz[0]-3];
for(i=1; i<sz[0]-1; i++)
{
g[0][i] = g[2][i];
g[sz[1]-1][i] = g[sz[1]-3][i];
}
for(j=1; j<sz[1]-1; j++)
{
g[j][0] = g[j][2];
g[j][sz[0]-1] = g[j][sz[0]-3];
}
for(j=0; j<sz[1]; j++)
for(i=0; i<sz[0]; i++)
{
f[j][i] = g[j][i];
}
if (g) delete2dpointer(g, sz[0], sz[1]);
if (g1d) {delete[]g1d; g1d = 0;}
// if (f)
// {
// float * f1d = f[0];
// delete2dpointer(f, sz[0], sz[1]);
// delete []f1d;
// }
// f = g;
// //return g;
}
//Make a 3D function satisfy Neumann boundary condition
void NeumannBoundCond(float ***f, const V3DLONG *sz)
{
float ***g=0, *g1d=0;
V3DLONG i,j,k;
//allocate memory for g
V3DLONG tmplen = sz[0]*sz[1]*sz[2];
if (tmplen>0 && sz[0]>0 && sz[1]>0 && sz[2]>0)
{
g1d = new float [tmplen];
if (g1d)
new3dpointer(g, sz[0], sz[1], sz[2], g1d);
}
for(k=0; k<sz[2]; k++)
for(j=0; j<sz[1]; j++)
for(i=0; i<sz[0]; i++)
{
g[k][j][i] = f[k][j][i];
}
// sweep along z dimension
for (k=0; k<sz[2]; k++)
{
g[k][0][0] = g[k][2][2];
g[k][0][sz[0]-1] = g[k][2][sz[0]-3];
g[k][sz[1]-1][0] = g[k][sz[1]-3][2];
g[k][sz[1]-1][sz[0]-1] = g[k][sz[1]-3][sz[0]-3];
for(i=1; i<sz[0]-1; i++)
{
g[k][0][i] = g[k][2][i];
g[k][sz[1]-1][i] = g[k][sz[1]-3][i];
}
for(j=1; j<sz[1]-1; j++)
{
g[k][j][0] = g[k][j][2];
g[k][j][sz[0]-1] = g[k][j][sz[0]-3];
}
}
//sweep along y dimension
for (j=0; j<sz[1]; j++)
{
g[0][j][0] = g[2][j][2];
g[0][j][sz[0]-1] = g[2][j][sz[0]-3];
g[sz[2]-1][j][0] = g[sz[2]-3][j][2];
g[sz[2]-1][j][sz[0]-1] = g[sz[2]-3][j][sz[0]-3];
for(i=1; i<sz[0]-1; i++)
{
g[0][j][i] = g[2][j][i];
g[sz[2]-1][j][i] = g[sz[2]-3][j][i];
}
for(k=1; k<sz[2]-1; k++)
{
g[k][j][0] = g[k][j][2];
g[k][j][sz[0]-1] = g[k][j][sz[0]-3];
}
}
// every point on the 6 faces of the cube has been replaced by an inner point,
// no need to sweep along x dimension any more
for(k=0; k<sz[2]; k++)
for(j=0; j<sz[1]; j++)
for(i=0; i<sz[0]; i++)
{
f[k][j][i] = g[k][j][i];
}
if (g) delete3dpointer(g, sz[0], sz[1], sz[2]);
if (g1d) {delete[]g1d; g1d = 0;}
// return g;
}
// 2d level set, with replelling force between neighboring regions
// input and out share the same memory u
void evloveLevelSet(float **u, float **uneighbor, float **g, float *para, const int numIter, const V3DLONG *sz)
{
// float **vx=0, **vy=0, **ux=0, **uy=0, **lap=0, **u=0;
// float *vx1d, *vy1d, *ux1d, *uy1d, *lap1d, *u1d;
// float **diracU=0, **K=0;
// float *diracU1d, *K1d;
float **vx=0, **vy=0, **ux=0, **uy=0, **lap=0;
float *vx1d=0, *vy1d=0, *ux1d=0, *uy1d=0, *lap1d=0;
float **diracU=0, **K=0;
float *diracU1d=0, *K1d=0;
float lamda = para[0], mu =para[1], alf=para[2], epsilon=para[3], delt=para[4], gama=para[5];
V3DLONG i,j;
float weightedLengthTerm, penalizingTerm, repellTerm, weightedAreaTerm;
// allocate memory for vx, vy, diracU, K
V3DLONG tmplen = sz[0]*sz[1];
if (tmplen>0 && sz[0]>0 && sz[1]>0)
{
vx1d = new float [tmplen];
if (vx1d)
new2dpointer(vx, sz[0], sz[1], vx1d);
vy1d = new float [tmplen];
if (vy1d)
new2dpointer(vy, sz[0], sz[1], vy1d);
ux1d = new float [tmplen];
if (ux1d)
new2dpointer(ux, sz[0], sz[1], ux1d);
uy1d = new float [tmplen];
if (uy1d)
new2dpointer(uy, sz[0], sz[1], uy1d);
lap1d = new float [tmplen];
if (lap1d)
new2dpointer(lap, sz[0], sz[1], lap1d);
diracU1d = new float [tmplen];
if (diracU1d)
new2dpointer(diracU, sz[0], sz[1], diracU1d);
K1d = new float [tmplen];
if (K1d)
new2dpointer(K, sz[0], sz[1], K1d);
// u1d = new float [tmplen];
// if (u1d)
// new2dpointer(u, sz[0], sz[1], u1d);
}
// for (j=0; j<sz[1]; j++)
// for (i=0; i<sz[0]; i++)
// {
// u[j][i] = u0[j][i];
// }
gradient(g,vx,vy,sz);
for (int k=0; k<numIter; k++)
{
//u = NeumannBoundCond(u, sz);
NeumannBoundCond(u, sz);
gradient(u, ux, uy, sz);
gradientNoramlize(ux,uy, sz);
// diracU = Dirac(u, epsilon, sz);
// K=curvatureCentral(ux,uy,sz);
Dirac(u, epsilon, sz, diracU);
curvatureCentral(ux,uy,sz, K);
laplacian(u, lap, sz);
// computer forces
for(j=0;j<sz[1];j++)
for(i=0;i<sz[0];i++)
{
weightedLengthTerm = lamda*diracU[j][i]*(vx[j][i]*ux[j][i] + vy[j][i]*uy[j][i] + g[j][i]*K[j][i]);
penalizingTerm=mu*(4*lap[j][i]-K[j][i]);
weightedAreaTerm=alf*diracU[j][i]*g[j][i];
repellTerm = - gama* uneighbor[j][i];
u[j][i]=u[j][i]+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm + repellTerm); // update the level set function
}
}
// delete pointer, free memory
if (vx) delete2dpointer(vx, sz[0], sz[1]);
if (vx1d) {delete []vx1d; vx1d=0;}
if (vy) delete2dpointer(vy, sz[0], sz[1]);
if (vy1d) {delete []vy1d; vy1d=0;}
if (ux) delete2dpointer(ux, sz[0], sz[1]);
if (ux1d) {delete []ux1d; ux1d=0;}
if (uy) delete2dpointer(uy, sz[0], sz[1]);
if (uy1d) {delete []uy1d; uy1d=0;}
if (lap) delete2dpointer(lap, sz[0], sz[1]);
if (lap1d) {delete []lap1d; lap1d=0;}
if (diracU) delete2dpointer(diracU, sz[0], sz[1]);
if (diracU1d) {delete []diracU1d; diracU1d=0;}
if (K) delete2dpointer(K, sz[0], sz[1]);
if (K1d) {delete []K1d; K1d=0;}
}
//2d level set without considering repelling force between neighboring regions
void evloveLevelSet(float **u, float **g, float *para, const int numIter, const V3DLONG *sz)
{
// float **vx=0, **vy=0, **ux=0, **uy=0, **lap=0, **u=0;
// float *vx1d, *vy1d, *ux1d, *uy1d, *lap1d, *u1d;
// float **diracU=0, **K=0;
// float *diracU1d, *K1d;
float **vx=0, **vy=0, **ux=0, **uy=0, **lap=0;
float *vx1d=0, *vy1d=0, *ux1d=0, *uy1d=0, *lap1d=0;
float **diracU=0, **K=0;
float *diracU1d=0, *K1d=0;
float lamda = para[0], mu =para[1], alf=para[2], epsilon=para[3], delt=para[4];
V3DLONG i,j;
float weightedLengthTerm, penalizingTerm, weightedAreaTerm;
// allocate memory for vx, vy, ux, uy, diracU, K
V3DLONG tmplen = sz[0]*sz[1];
if (tmplen>0 && sz[0]>0 && sz[1]>0)
{
vx1d = new float [tmplen];
if (vx1d)
new2dpointer(vx, sz[0], sz[1], vx1d);
vy1d = new float [tmplen];
if (vy1d)
new2dpointer(vy, sz[0], sz[1], vy1d);
ux1d = new float [tmplen];
if (ux1d)
new2dpointer(ux, sz[0], sz[1], ux1d);
uy1d = new float [tmplen];
if (uy1d)
new2dpointer(uy, sz[0], sz[1], uy1d);
lap1d = new float [tmplen];
if (lap1d)
new2dpointer(lap, sz[0], sz[1], lap1d);
diracU1d = new float [tmplen];
if (diracU1d)
new2dpointer(diracU, sz[0], sz[1], diracU1d);
K1d = new float [tmplen];
if (K1d)
new2dpointer(K, sz[0], sz[1], K1d);
// u1d = new float [tmplen];
// if (u1d)
// new2dpointer(u, sz[0], sz[1], u1d);
}
// for (j=0; j<sz[1]; j++)
// for (i=0; i<sz[0]; i++)
// {
// u[j][i] = u0[j][i];
// }
gradient(g,vx,vy,sz);
for (int k=0; k<numIter; k++)
{
//u = NeumannBoundCond(u, sz);
NeumannBoundCond(u, sz);
gradient(u, ux, uy, sz);
gradientNoramlize(ux,uy, sz);
// diracU = Dirac(u, epsilon, sz);
// K=curvatureCentral(ux,uy,sz);
Dirac(u, epsilon, sz, diracU);
curvatureCentral(ux,uy,sz, K);
laplacian(u, lap, sz);
// computer forces
for(j=0;j<sz[1];j++)
for(i=0;i<sz[0];i++)
{
weightedLengthTerm = lamda*diracU[j][i]*(vx[j][i]*ux[j][i] + vy[j][i]*uy[j][i] + g[j][i]*K[j][i]);
penalizingTerm=mu*(4*lap[j][i]-K[j][i]);
weightedAreaTerm=alf*diracU[j][i]*g[j][i];
u[j][i]=u[j][i]+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm); // update the level set function
}
}
// delete pointer, free memory
if (vx) delete2dpointer(vx, sz[0], sz[1]);
if (vx1d) {delete []vx1d; vx1d=0;}
if (vy) delete2dpointer(vy, sz[0], sz[1]);
if (vy1d) {delete []vy1d; vy1d=0;}
if (ux) delete2dpointer(ux, sz[0], sz[1]);
if (ux1d) {delete []ux1d; ux1d=0;}
if (uy) delete2dpointer(uy, sz[0], sz[1]);
if (uy1d) {delete []uy1d; uy1d=0;}
if (lap) delete2dpointer(lap, sz[0], sz[1]);
if (lap1d) {delete []lap1d; lap1d=0;}
if (diracU) delete2dpointer(diracU, sz[0], sz[1]);
if (diracU1d) {delete []diracU1d; diracU1d=0;}
if (K) delete2dpointer(K, sz[0], sz[1]);
if (K1d) {delete []K1d; K1d=0;}
// if (u0)
// {
// float * u01d = u0[0];
// delete2dpointer(u0, sz[0], sz[1]);
// delete []u01d;
// }
// u0 = u;
return;
}
// 3d level set, with repelling force between neighboring regions
// input and out share the same memory u
void evloveLevelSet(float ***u, float ***uneighbor, float ***g, float *para, const int numIter, const V3DLONG *sz)
{
float ***vx=0, ***vy=0, ***vz=0, ***ux=0, ***uy=0, ***uz=0, ***lap=0;
float *vx1d=0, *vy1d=0, *vz1d=0, *ux1d=0, *uy1d=0, *uz1d=0, *lap1d=0;
float ***diracU=0, ***K=0;
float *diracU1d=0, *K1d=0;
float lamda = para[0], mu =para[1], alf=para[2], epsilon=para[3], delt=para[4], gama=para[5];
V3DLONG i,j,k;
float weightedLengthTerm, penalizingTerm, repellTerm, weightedAreaTerm;
// allocate memory for vx, vy, vz, diracU, K
V3DLONG tmplen = sz[0]*sz[1]*sz[2];
if (tmplen>0 && sz[0]>0 && sz[1]>0 && sz[2]>0)
{
vx1d = new float [tmplen];
if (vx1d)
new3dpointer(vx, sz[0], sz[1], sz[2], vx1d);
vy1d = new float [tmplen];
if (vy1d)
new3dpointer(vy, sz[0], sz[1], sz[2], vy1d);
vz1d = new float [tmplen];
if (vz1d)
new3dpointer(vz, sz[0], sz[1], sz[2], vz1d);
ux1d = new float [tmplen];
if (ux1d)
new3dpointer(ux, sz[0], sz[1], sz[2], ux1d);
uy1d = new float [tmplen];
if (uy1d)
new3dpointer(uy, sz[0], sz[1], sz[2], uy1d);
uz1d = new float [tmplen];
if (uz1d)
new3dpointer(uz, sz[0], sz[1], sz[2], uz1d);
diracU1d = new float [tmplen];
if (diracU1d)
new3dpointer(diracU, sz[0], sz[1], sz[2], diracU1d);
K1d = new float [tmplen];
if (K1d)
new3dpointer(K, sz[0], sz[1], sz[2], K1d);
}
// for (k=0;k<sz[2];k++)
// for (j=0; j<sz[1]; j++)
// for (i=0; i<sz[0]; i++)
// {
// u[k][j][i] = u0[k][j][i];
// }
gradient(g,vx,vy,vz,sz);
for (k=0; k<numIter; k++)
{
NeumannBoundCond(u, sz); // 3D Neumann Boundary Conditions not clear, just do nothing
gradient(u, ux, uy, uz, sz);
gradientNoramlize(ux,uy,uz, sz);
Dirac(u, epsilon, sz, diracU);
curvatureCentral(ux,uy,uz,sz,K);
laplacian(u, lap, sz);
// computer forces
for(k=0;k<sz[2];k++)
for(j=0;j<sz[1];j++)
for(i=0;i<sz[0];i++)
{
weightedLengthTerm = lamda*diracU[k][j][i]*(vx[k][j][i]*ux[k][j][i] + vy[k][j][i]*uy[k][j][i] + vz[k][j][i]*uz[k][j][i]+g[k][j][i]*K[k][j][i]);
penalizingTerm=mu*(4*lap[k][j][i]-K[k][j][i]);
weightedAreaTerm=alf*diracU[k][j][i]*g[k][j][i];
repellTerm = - gama* uneighbor[k][j][i];
u[k][j][i]=u[k][j][i]+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm + repellTerm); // update the level set function
}
}
// delete pointer, free memory
if (vx) delete3dpointer(vx, sz[0], sz[1], sz[2]);
if (vx1d) {delete []vx1d; vx1d=0;}
if (vy) delete3dpointer(vy, sz[0], sz[1], sz[2]);
if (vy1d) {delete []vy1d; vy1d=0;}
if (vz) delete3dpointer(vz, sz[0], sz[1], sz[2]);
if (vz1d) {delete []vz1d; vz1d=0;}
if (ux) delete3dpointer(ux, sz[0], sz[1], sz[2]);
if (ux1d) {delete []ux1d; ux1d=0;}
if (uy) delete3dpointer(uy, sz[0], sz[1], sz[2]);
if (uy1d) {delete []uy1d; uy1d=0;}
if (uz) delete3dpointer(uz, sz[0], sz[1], sz[2]);
if (uz1d) {delete []uz1d; uz1d=0;}
if (lap) delete3dpointer(lap, sz[0], sz[1], sz[2]);
if (lap1d) {delete []lap1d; lap1d=0;}
if (diracU) delete3dpointer(diracU, sz[0], sz[1], sz[2]);
if (diracU1d) {delete []diracU1d; diracU1d=0;}
if (K) delete3dpointer(K, sz[0], sz[1], sz[2]);
if (K1d) {delete []K1d; K1d=0;}
// return u;
}
// 3d level set, without considering repelling force between neighboring regions
void evloveLevelSet(float ***u, float ***g, float *para, const int numIter, const V3DLONG *sz)
{
float ***vx=0, ***vy=0, ***vz=0, ***ux=0, ***uy=0, ***uz=0, ***lap=0;
float *vx1d=0, *vy1d=0, *vz1d=0, *ux1d=0, *uy1d=0, *uz1d=0, *lap1d=0;
float ***diracU=0, ***K=0;
float *diracU1d=0, *K1d=0;
float lamda = para[0], mu =para[1], alf=para[2], epsilon=para[3], delt=para[4], gama=para[5];
V3DLONG i,j,k;
float weightedLengthTerm, penalizingTerm, weightedAreaTerm;
// allocate memory for vx, vy, vz, ux, uy, uz, diracU, K
V3DLONG tmplen = sz[0]*sz[1]*sz[2];
if (tmplen>0 && sz[0]>0 && sz[1]>0 && sz[2]>0)
{
vx1d = new float [tmplen];
if (vx1d)
new3dpointer(vx, sz[0], sz[1], sz[2], vx1d);
vy1d = new float [tmplen];
if (vy1d)
new3dpointer(vy, sz[0], sz[1], sz[2], vy1d);
vz1d = new float [tmplen];
if (vz1d)
new3dpointer(vz, sz[0], sz[1], sz[2], vz1d);
ux1d = new float [tmplen];
if (ux1d)
new3dpointer(ux, sz[0], sz[1], sz[2], ux1d);
uy1d = new float [tmplen];
if (uy1d)
new3dpointer(uy, sz[0], sz[1], sz[2], uy1d);
uz1d = new float [tmplen];
if (uz1d)
new3dpointer(uz, sz[0], sz[1], sz[2], uz1d);
lap1d = new float [tmplen];
if (lap1d)
new3dpointer(lap, sz[0], sz[1], sz[2], lap1d);
diracU1d = new float [tmplen];
if (diracU1d)
new3dpointer(diracU, sz[0], sz[1], sz[2], diracU1d);
K1d = new float [tmplen];
if (K1d)
new3dpointer(K, sz[0], sz[1], sz[2], K1d);
}
// for (k=0;k<sz[2];k++)
// for (j=0; j<sz[1]; j++)
// for (i=0; i<sz[0]; i++)
// {
// u[k][j][i] = u0[k][j][i];
// }
gradient(g,vx,vy,vz,sz);
for (k=0; k<numIter; k++)
{
NeumannBoundCond(u, sz);
gradient(u, ux, uy, uz, sz);
gradientNoramlize(ux,uy,uz, sz);
Dirac(u, epsilon, sz, diracU);
curvatureCentral(ux,uy,uz,sz, K);
laplacian(u, lap, sz);
// computer forces
for(k=0;k<sz[2];k++)
for(j=0;j<sz[1];j++)
for(i=0;i<sz[0];i++)
{
weightedLengthTerm = lamda*diracU[k][j][i]*(vx[k][j][i]*ux[k][j][i] + vy[k][j][i]*uy[k][j][i] + vz[k][j][i]*uz[k][j][i] + g[k][j][i]*K[k][j][i]);
penalizingTerm=mu*(4*lap[k][j][i]-K[k][j][i]);
weightedAreaTerm=alf*diracU[k][j][i]*g[k][j][i];
u[k][j][i]=u[k][j][i]+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm); // update the level set function
}
}
// delete pointer, free memory
if (vx) delete3dpointer(vx, sz[0], sz[1], sz[2]);
if (vx1d) {delete []vx1d; vx1d=0;}
if (vy) delete3dpointer(vy, sz[0], sz[1], sz[2]);
if (vy1d) {delete []vy1d; vy1d=0;}
if (vz) delete3dpointer(vz, sz[0], sz[1], sz[2]);
if (vz1d) {delete []vz1d; vz1d=0;}
if (ux) delete3dpointer(ux, sz[0], sz[1], sz[2]);
if (ux1d) {delete []ux1d; ux1d=0;}
if (uy) delete3dpointer(uy, sz[0], sz[1], sz[2]);
if (uy1d) {delete []uy1d; uy1d=0;}
if (uz) delete3dpointer(uz, sz[0], sz[1], sz[2]);
if (uz1d) {delete []uz1d; uz1d=0;}
if (lap) delete3dpointer(lap, sz[0], sz[1], sz[2]);
if (lap1d) {delete []lap1d; lap1d=0;}
if (diracU) delete3dpointer(diracU, sz[0], sz[1], sz[2]);
if (diracU1d) {delete []diracU1d; diracU1d=0;}
if (K) delete3dpointer(K, sz[0], sz[1], sz[2]);
if (K1d) {delete []K1d; K1d=0;}
// return u;
}
#endif
| 25.518364 | 154 | 0.51526 | [
"3d"
] |
0d2630aa17075c40b82a5e7fde71ceb96064cde0 | 4,063 | cpp | C++ | src/EditorCamera.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | src/EditorCamera.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | src/EditorCamera.cpp | inugami-dev64/deng | 96e5bc4c9c9a91aa46cb7c71927853b0a764f7d9 | [
"Apache-2.0"
] | null | null | null | // DENG: dynamic engine - small but powerful 3D game engine
// licence: Apache, see LICENCE file
// file: EditorCamera.cpp - Editor camera class implementation
// author: Karl-Mihkel Ott
#define EDITOR_CAMERA_CPP
#include <EditorCamera.h>
namespace DENG {
EditorCamera::EditorCamera(Renderer &_rend, Window &_win, const Camera3DConfiguration &_conf, const std::string &_name) :
Camera3D(_rend, _win, _conf, _name)
{
DENG_ASSERT(m_config.index() == 2);
EditorCameraConfiguration &conf = std::get<EditorCameraConfiguration>(m_config);
m_translation = { 0.0f, 0.0f, conf.zoom_step };
}
void EditorCamera::_ForceLimits() {
// no x axis rotation overflow for angles greater / less than PI / 2 | -PI / 2 is allowed
if(m_rotation.x > PI / 2)
m_rotation.x = PI / 2;
else if(m_rotation.x < -PI / 2)
m_rotation.x = -PI / 2;
// don't allow y rotations greater / smaller than 2 * PI | -2 * PI
if(m_rotation.y > 2 * PI)
m_rotation.y = m_rotation.y - 2 * PI;
else if(m_rotation.y < -2 * PI)
m_rotation.y = m_rotation.y + 2 * PI;
}
void EditorCamera::_ConstructViewMatrix() {
_ForceLimits();
// construct quaternions representing the rotation of the camera
Libdas::Quaternion x = { sinf(m_rotation.x / 2), 0.0f, 0.0f, cosf(m_rotation.x / 2) };
Libdas::Quaternion y = { 0.0f, sinf(m_rotation.y / 2), 0.0f, cosf(m_rotation.y / 2) };
Libdas::Quaternion z = { 0.0f, 0.0f, sinf(m_rotation.z / 2), cosf(m_rotation.z / 2) };
// construct translation matrix
Libdas::Matrix4<float> translation = {
{ 1.0f, 0.0f, 0.0f, m_translation.x - m_origin.x },
{ 0.0f, 1.0f, 0.0f, m_translation.y - m_origin.y },
{ 0.0f, 0.0f, 1.0f, m_translation.z - m_origin.z },
{ 0.0f, 0.0f, 0.0f, 1.0f },
};
m_ubo.view_matrix = translation * (x * y * z).ExpandToMatrix4();
m_ubo.view_matrix = m_ubo.view_matrix.Transpose();
}
void EditorCamera::EnableCamera() {
m_is_enabled = true;
}
void EditorCamera::DisableCamera() {
m_is_enabled = false;
}
void EditorCamera::Update() {
// no transposition needed
m_ubo.projection_matrix = _CalculateProjection();
EditorCameraConfiguration &conf = std::get<EditorCameraConfiguration>(m_config);
if(m_is_enabled) {
float delta_step = 0; // conf.zoom_step * delta_time.count() / conf.action_delay;
Libdas::Point2D<int64_t> mouse_delta = m_window.GetMouseDelta();
Libdas::Point2D<float> delta_mousef = { static_cast<float>(mouse_delta.x), static_cast<float>(mouse_delta.y) };
// rotation toggle is activated
if(m_window.IsHidEventActive(conf.rotate_toggle)) {
std::cout << "Rotate toggle active" << std::endl;
m_window.ChangeVCMode(true);
Libdas::Point3D<float> rot = {
-delta_mousef.y * conf.delta_rotate / conf.mouse_rotation_delta,
delta_mousef.x * conf.delta_rotate / conf.mouse_rotation_delta,
0.0f
};
m_rotation += rot;
} else {
m_window.ChangeVCMode(false);
if(m_window.IsHidEventActive(conf.zoom_in) && m_translation.z - conf.zoom_step > 0) {
std::cout << "Zooming in" << std::endl;
delta_step = -conf.zoom_step;
m_translation.z += delta_step;
}
else if(m_window.IsHidEventActive(conf.zoom_out)) {
std::cout << "Zooming out" << std::endl;
delta_step = conf.zoom_step;
m_translation.z += delta_step;
}
}
}
_ConstructViewMatrix();
m_renderer.UpdateUniform(reinterpret_cast<const char*>(&m_ubo), sizeof(ModelCameraUbo), m_ubo_offset);
}
}
| 37.971963 | 125 | 0.578144 | [
"3d"
] |
0d39d0eadeb85874e4d574fd2bba6aefdcaee1d1 | 9,399 | hpp | C++ | src/Algebra.hpp | clauderichard/OptimistRacing | 808ffcef44307c9097035bf5dacdcae8fc7663a7 | [
"MIT"
] | null | null | null | src/Algebra.hpp | clauderichard/OptimistRacing | 808ffcef44307c9097035bf5dacdcae8fc7663a7 | [
"MIT"
] | null | null | null | src/Algebra.hpp | clauderichard/OptimistRacing | 808ffcef44307c9097035bf5dacdcae8fc7663a7 | [
"MIT"
] | null | null | null | /* Copyright (C) 2012 Claude Richard
*
* Optimist Racing is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Optimist Racing is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Optimist Racing. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This file contains the code necessary for all sorts of linear algebra,
* which includes vectors and matrices of varying sizes.
*/
#pragma once
#include <algorithm>
#include <cmath>
//#define M_PI 3.141592653589793
/**
* \brief Represents a vector with 2 entries.
* \details This class includes some operations that you can do with 2D vectors.
* \author Claude Richard
* \date 2012
*/
class Vector2D
{
public:
/**
* \brief Makes a zero vector.
* \details After this constructor is done, both entries in the vector will be zero.
* \post Both entries in the vector are zero.
*/
Vector2D();
/**
* \brief Makes a vector with the entries x and y.
* \details After this constructor is done, the entries in the vector will be x and y, in that order.
* \post The vector's entries are x and y, in that order.
* \param x The 1st value in the vector.
* \param y The 2nd value in the vector.
*/
Vector2D( double x, double y );
/**
* \brief Makes a copy of the vector \a other.
* \details After this constructor is done, the entries in this will match the entries in the vector \a other.
* \post The entries in this vector match the entries in the vector \a other.
* \param other The vector to copy.
*/
Vector2D( const Vector2D& other );
/**
* \brief Makes a copy of the vector \a other.
* \details The entries in this vector will be made to match the entries in the vector \a other.
* \post The entries in this vector match the entries in the vector \a other.
* \param other The vector to copy.
* \return A reference to this.
*/
Vector2D& operator=( const Vector2D& other );
double& operator []( size_t idx );
double operator []( size_t idx ) const;
double euclideanNorm2() const;
double euclideanNorm() const;
/**
* \brief Returns the dot product between this and \a other.
* \details Computes the dot product \f$ \overrightarrow{this} \cdot \overrightarrow{other} \f$.
* \param other The vector to be dot producted with this.
* \return The dot product \f$ \overrightarrow{this} \cdot \overrightarrow{other} \f$.
*/
double dot( const Vector2D& other ) const;
bool normalize();
private:
double mV[2];
};
class Matrix2x2
{
public:
/**
*
*/
Matrix2x2();
/**
*
*/
Matrix2x2( const Matrix2x2& other );
/**
*
*/
Matrix2x2( const Vector2D& row1, const Vector2D& row2 );
/**
*
*/
Matrix2x2( const double* values );
/**
*
*/
Matrix2x2& operator =( const Matrix2x2& other );
/**
*
*/
Vector2D getRow( size_t row ) const;
/**
*
*/
double* getRow( size_t row );
/**
*
*/
Vector2D getColumn( size_t col ) const;
/**
*
*/
Vector2D operator []( size_t row ) const;
/**
*
*/
double* operator []( size_t row );
/**
*
*/
Matrix2x2 transpose() const;
/**
*
*/
Matrix2x2 invert() const;
/**
*
*/
double determinant() const;
/**
*
*/
Vector2D matrixSolve( const Vector2D& b ) const;
/**
*
*/
const double* begin() const;
/**
*
*/
const double* end() const;
private:
double mV[4];
};
class Vector3D
{
public:
/**
*
*/
Vector3D();
/**
*
*/
Vector3D( double x, double y, double z );
/**
*
*/
Vector3D( const Vector3D& other );
/**
*
*/
Vector3D& operator=( const Vector3D& other );
/**
*
*/
double& operator []( size_t idx );
/**
*
*/
double operator []( size_t idx ) const;
/**
*
*/
double euclideanNorm2() const;
/**
*
*/
double euclideanNorm() const;
/**
*
*/
double dot( const Vector3D& other ) const;
/**
*
*/
Vector3D cross( const Vector3D& other ) const;
/**
*
*/
bool normalize();
private:
double mV[3];
};
class Matrix3x3
{
public:
/**
*
*/
Matrix3x3();
/**
*
*/
Matrix3x3( const Matrix3x3& other );
/**
*
*/
Matrix3x3( const Vector3D& row1, const Vector3D& row2, const Vector3D& row3 );
/**
*
*/
Matrix3x3( const double* values );
/**
*
*/
Matrix3x3& operator =( const Matrix3x3& other );
/**
*
*/
Vector3D getRow( size_t row ) const;
/**
*
*/
double* getRow( size_t row );
/**
*
*/
Vector3D getColumn( size_t col ) const;
/**
*
*/
Vector3D operator []( size_t row ) const;
/**
*
*/
double* operator []( size_t row );
/**
*
*/
Matrix3x3 transpose() const;
/**
*
*/
Matrix3x3 invert() const;
/**
*
*/
double determinant() const;
/**
*
*/
Vector3D matrixSolve( const Vector3D& b ) const;
/**
*
*/
const double* begin() const;
/**
*
*/
const double* end() const;
private:
double mV[9];
};
class VectorND
{
public:
/**
*
*/
VectorND( int n );
/**
*
*/
VectorND( int n, const double* x );
/**
*
*/
VectorND( const VectorND& other );
/**
*
*/
~VectorND();
/**
*
*/
VectorND& operator=( const VectorND& other );
/**
*
*/
int getNum() const;
/**
*
*/
double& operator []( size_t idx );
/**
*
*/
double operator []( size_t idx ) const;
/**
*
*/
double euclideanNorm2() const;
/**
*
*/
double euclideanNorm() const;
/**
*
*/
double dot( const VectorND& other ) const;
/**
*
*/
bool normalize();
private:
int mN;
double* mV;
};
class MatrixMxN
{
public:
/**
*
*/
MatrixMxN( int m, int n ); // Creates a zero matrix
/**
*
*/
MatrixMxN( const MatrixMxN& other );
/**
*
*/
MatrixMxN( const MatrixMxN& A, const MatrixMxN& B,
const MatrixMxN& C, const MatrixMxN& D );
/**
*
*/
MatrixMxN( int m, int n, const double* values );
/**
*
*/
~MatrixMxN();
/**
*
*/
MatrixMxN& operator =( const MatrixMxN& other );
/**
*
*/
int getNumRows() const;
/**
*
*/
int getNumCols() const;
/**
*
*/
VectorND getRow( size_t row ) const;
/**
*
*/
double* getRow( size_t row );
/**
*
*/
VectorND getColumn( size_t col ) const;
/**
*
*/
VectorND operator []( size_t row ) const;
/**
*
*/
double* operator []( size_t row );
/**
*
* rowend and colend are immediately AFTER the last row and column of the returned matrix.
*/
MatrixMxN getPiece( int rowstart, int rowend, int colstart, int colend ) const;
/**
*
*/
MatrixMxN transpose() const;
/**
*
*/
MatrixMxN invert() const;
/**
*
*/
MatrixMxN switchVertical() const;
/**
*
*/
MatrixMxN switchHorizontal() const;
/**
*
*/
MatrixMxN invertUpperRight() const;
/**
*
*/
MatrixMxN invertLowerRight() const;
/**
*
*/
MatrixMxN invertUpperLeft() const;
/**
*
*/
MatrixMxN invertLowerLeft() const;
/**
*
*/
MatrixMxN operator +( const MatrixMxN& other ) const;
/**
*
*/
MatrixMxN operator -( const MatrixMxN& other ) const;
/**
*
*/
MatrixMxN operator *( const MatrixMxN& other ) const;
/**
*
*/
MatrixMxN multiplyScalar( double s ) const;
/**
*
*/
MatrixMxN transposeAndMultiply( const MatrixMxN& other ) const;
/**
*
*/
MatrixMxN pointwiseMultiply( const MatrixMxN& other ) const;
/**
*
*/
double dot( const MatrixMxN& other ) const;
/**
*
*/
const double* begin() const;
/**
*
*/
const double* end() const;
private:
int mM;
int mN;
double* mV;
};
// operations in the global scope
/**
*/
Vector2D operator *( double s, const Vector2D& v );
/**
*/
Vector2D operator +( const Vector2D& a, const Vector2D& b );
/**
*/
Vector2D operator -( const Vector2D& a, const Vector2D& b );
/**
*/
Vector3D operator *( double s, const Vector3D& v );
/**
*/
Vector3D operator +( const Vector3D& a, const Vector3D& b );
/**
*/
Vector3D operator -( const Vector3D& a, const Vector3D& b );
/**
*/
VectorND operator *( double s, const VectorND& v );
/**
*/
VectorND operator +( const VectorND& a, const VectorND& b );
/**
*/
VectorND operator -( const VectorND& a, const VectorND& b );
/**
*/
double dot( const Vector2D& a, const Vector2D& b );
/**
*/
double dot( const Vector3D& a, const Vector3D& b );
/**
*/
Vector3D cross( const Vector3D& a, const Vector3D& b );
/**
*/
Matrix2x2 operator *( const Matrix2x2& A, const Matrix2x2& B );
/**
*/
Vector2D operator *( const Matrix2x2& A, const Vector2D& b );
/**
*/
Vector2D matrixSolve( const Matrix2x2& A, const Vector2D& b );
/**
*/
Matrix3x3 operator *( const Matrix3x3& A, const Matrix3x3& B );
/**
*/
Vector3D operator *( const Matrix3x3& A, const Vector3D& b );
/**
*/
Vector3D matrixSolve( const Matrix3x3& a, const Vector3D& b );
/**
*/
VectorND operator *( const MatrixMxN& A, const VectorND& b );
/**
*/
MatrixMxN operator *( double s, const MatrixMxN& A );
/**
*/
double dot( const MatrixMxN& A, const MatrixMxN& B );
| 14.437788 | 112 | 0.597085 | [
"vector"
] |
0d461742d15c295bd7ffd8ef2497cdb41c364635 | 26,943 | hxx | C++ | include/quadruped-walkgen/quadruped_augmented_time.hxx | loco-3d/quadruped-walkgen | d78c205bcfcc69919eacb7cb4b51e426e2bc626f | [
"BSD-2-Clause"
] | null | null | null | include/quadruped-walkgen/quadruped_augmented_time.hxx | loco-3d/quadruped-walkgen | d78c205bcfcc69919eacb7cb4b51e426e2bc626f | [
"BSD-2-Clause"
] | null | null | null | include/quadruped-walkgen/quadruped_augmented_time.hxx | loco-3d/quadruped-walkgen | d78c205bcfcc69919eacb7cb4b51e426e2bc626f | [
"BSD-2-Clause"
] | 1 | 2021-12-06T18:28:31.000Z | 2021-12-06T18:28:31.000Z | #ifndef __quadruped_walkgen_quadruped_augmented_time_hxx__
#define __quadruped_walkgen_quadruped_augmented_time_hxx__
#include "crocoddyl/core/utils/exception.hpp"
namespace quadruped_walkgen {
template <typename Scalar>
ActionModelQuadrupedAugmentedTimeTpl<Scalar>::ActionModelQuadrupedAugmentedTimeTpl()
: crocoddyl::ActionModelAbstractTpl<Scalar>(boost::make_shared<crocoddyl::StateVectorTpl<Scalar> >(21), 12, 33) {
// Model parameters
mu = Scalar(1);
mass = Scalar(2.50000279);
min_fz_in_contact = Scalar(0.0);
max_fz = Scalar(25);
// Relative forces to compute the norm mof the command
relative_forces = false;
uref_.setZero();
// Matrix model initialization
g.setZero();
gI.setZero();
gI.diagonal() << Scalar(0.00578574), Scalar(0.01938108), Scalar(0.02476124);
A.setIdentity();
B.setZero();
lever_arms.setZero();
R.setZero();
// Weight vectors initialization
force_weights_.setConstant(Scalar(0.2));
state_weights_ << Scalar(1.), Scalar(1.), Scalar(150.), Scalar(35.), Scalar(30.), Scalar(8.), Scalar(20.),
Scalar(20.), Scalar(15.), Scalar(4.), Scalar(4.), Scalar(8.);
friction_weight_ = Scalar(10);
heuristicWeights.setConstant(Scalar(1));
last_position_weights_.setConstant(Scalar(1));
pshoulder_ << Scalar(0.1946), Scalar(0.15005), Scalar(0.1946), Scalar(-0.15005), Scalar(-0.1946), Scalar(0.15005),
Scalar(-0.1946), Scalar(-0.15005);
pheuristic_.setZero();
pshoulder_0 << Scalar(0.1946), Scalar(0.1946), Scalar(-0.1946), Scalar(-0.1946), Scalar(0.15005), Scalar(-0.15005),
Scalar(0.15005), Scalar(-0.15005);
pshoulder_tmp.setZero();
pcentrifugal_tmp_1.setZero();
pcentrifugal_tmp_2.setZero();
pcentrifugal_tmp.setZero();
// UpperBound vector
ub.setZero();
for (int i = 0; i < 4; i = i + 1) {
ub(6 * i + 5) = max_fz;
}
// Temporary vector used
Fa_x_u.setZero();
rub_max_.setZero();
Arr.setZero();
r.setZero();
lever_tmp.setZero();
R_tmp.setZero();
gait.setZero();
base_vector_x << Scalar(1.), Scalar(0.), Scalar(0.);
base_vector_y << Scalar(0.), Scalar(1.), Scalar(0.);
base_vector_z << Scalar(0.), Scalar(0.), Scalar(1.);
forces_3d.setZero();
gait_double.setZero();
// bool to add heuristic for foot position
centrifugal_term = true;
symmetry_term = true;
T_gait = Scalar(0.64);
// dt param
rub_max_dt_bool.setZero();
rub_max_dt.setZero();
dt_min_.setConstant(Scalar(0.005));
dt_max_.setConstant(Scalar(0.1));
dt_bound_weight = Scalar(0.);
// Log cost
cost_.setZero();
log_cost = false;
// // Used for shoulder height weight
// pshoulder_0 << Scalar(0.1946) , Scalar(0.1946) , Scalar(-0.1946), Scalar(-0.1946) ,
// Scalar(0.15005) , Scalar(-0.15005) , Scalar(0.15005) , Scalar(-0.15005) ;
sh_hlim = Scalar(0.225);
sh_weight = Scalar(10.);
sh_ub_max_.setZero();
psh.setZero();
}
template <typename Scalar>
ActionModelQuadrupedAugmentedTimeTpl<Scalar>::~ActionModelQuadrupedAugmentedTimeTpl() {}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::calc(
const boost::shared_ptr<crocoddyl::ActionDataAbstractTpl<Scalar> >& data,
const Eigen::Ref<const typename MathBase::VectorXs>& x, const Eigen::Ref<const typename MathBase::VectorXs>& u) {
if (static_cast<std::size_t>(x.size()) != state_->get_nx()) {
throw_pretty("Invalid argument: "
<< "x has wrong dimension (it should be " + std::to_string(state_->get_nx()) + ")");
}
if (static_cast<std::size_t>(u.size()) != nu_) {
throw_pretty("Invalid argument: "
<< "u has wrong dimension (it should be " + std::to_string(nu_) + ")");
}
ActionDataQuadrupedAugmentedTimeTpl<Scalar>* d =
static_cast<ActionDataQuadrupedAugmentedTimeTpl<Scalar>*>(data.get());
A.topRightCorner(6, 6) << Eigen::Matrix<Scalar, 6, 6>::Identity() * x.tail(1)[0];
g[8] = Scalar(-9.81) * x.tail(1)[0];
// Update B :
for (int i = 0; i < 4; i = i + 1) {
lever_tmp.setZero();
if (gait(i, 0) != 0) {
lever_tmp.head(2) = x.block(12 + 2 * i, 0, 2, 1);
lever_tmp += -x.block(0, 0, 3, 1);
R_tmp << Scalar(0.0), -lever_tmp[2], lever_tmp[1], lever_tmp[2], Scalar(0.0), -lever_tmp[0], -lever_tmp[1],
lever_tmp[0], Scalar(0.0);
B.block(9, 3 * i, 3, 3) << x.tail(1)[0] * R * R_tmp;
B.block(6, 3 * i, 3, 3).diagonal() << x.tail(1)[0] / mass, x.tail(1)[0] / mass, x.tail(1)[0] / mass;
// Compute pdistance of the shoulder wrt contact point
psh.block(0, i, 3, 1) << x(0) + pshoulder_0(0, i) - pshoulder_0(1, i) * x(5) - x(12 + 2 * i),
x(1) + pshoulder_0(1, i) + pshoulder_0(0, i) * x(5) - x(12 + 2 * i + 1),
x(2) + pshoulder_0(1, i) * x(3) - pshoulder_0(0, i) * x(4);
} else {
// Compute pdistance of the shoulder wrt contact point
psh.block(0, i, 3, 1).setZero();
// Compute pdistance of the shoulder wrt contact point
// psh.block(0,i,3,1) << x(0) + pshoulder_0(0,i) - pshoulder_0(1,i)*x(5) - x(12+2*i),
// x(1) + pshoulder_0(1,i) + pshoulder_0(0,i)*x(5) - x(12+2*i+1),
// x(2) + pshoulder_0(1,i)*x(3) - pshoulder_0(0,i)*x(4);
}
};
// Discrete dynamic : A*x + B*u + g
d->xnext.template head<12>() = A.diagonal().cwiseProduct(x.block(0, 0, 12, 1)) + g;
d->xnext.template head<6>() =
d->xnext.template head<6>() + A.topRightCorner(6, 6).diagonal().cwiseProduct(x.block(6, 0, 6, 1));
d->xnext.template segment<6>(6) = d->xnext.template segment<6>(6) + B.block(6, 0, 6, 12) * u;
d->xnext.template segment<8>(12) = x.segment(12, 8);
d->xnext.template tail<1>() = x.tail(1);
// Residual cost on the state and force norm
d->r.template head<12>() = state_weights_.cwiseProduct(x.head(12) - xref_);
d->r.template segment<8>(12) =
((heuristicWeights.cwiseProduct(x.segment(12, 8) - pheuristic_)).array() * gait_double.array()).matrix();
// d->r.template segment<1>(20) = 0 (dt)
d->r.template tail<12>() = force_weights_.cwiseProduct(u - uref_);
// Friction cone
for (int i = 0; i < 4; i = i + 1) {
Fa_x_u.segment(6 * i, 6) << u(3 * i) - mu * u(3 * i + 2), -u(3 * i) - mu * u(3 * i + 2),
u(3 * i + 1) - mu * u(3 * i + 2), -u(3 * i + 1) - mu * u(3 * i + 2), -u(3 * i + 2), u(3 * i + 2);
}
rub_max_ = (Fa_x_u - ub).cwiseMax(Scalar(0.));
rub_max_dt << dt_min_ - x.tail(1), x.tail(1) - dt_max_;
rub_max_dt_bool = (rub_max_dt.array() >= Scalar(0.)).matrix().template cast<Scalar>();
rub_max_dt = rub_max_dt.cwiseMax(Scalar(0.));
// Shoulder height weight
sh_ub_max_ << psh.block(0, 0, 3, 1).squaredNorm() - sh_hlim * sh_hlim,
psh.block(0, 1, 3, 1).squaredNorm() - sh_hlim * sh_hlim, psh.block(0, 2, 3, 1).squaredNorm() - sh_hlim * sh_hlim,
psh.block(0, 3, 3, 1).squaredNorm() - sh_hlim * sh_hlim;
sh_ub_max_ = sh_ub_max_.cwiseMax(Scalar(0.));
// Cost computation
d->cost =
Scalar(0.5) * d->r.segment(12, 8).transpose() * d->r.segment(12, 8) +
friction_weight_ * Scalar(0.5) * rub_max_.squaredNorm() +
Scalar(0.5) * ((last_position_weights_.cwiseProduct(x.segment(12, 8) - pref_)).array() * gait_double.array())
.matrix()
.squaredNorm() +
dt_bound_weight * Scalar(0.5) * rub_max_dt.squaredNorm() +
x(20) * Scalar(0.5) * d->r.head(12).transpose() * d->r.head(12) +
x(20) * Scalar(0.5) * d->r.tail(12).transpose() * d->r.tail(12) + sh_weight * Scalar(0.5) * sh_ub_max_.sum();
if (log_cost) {
cost_[0] = x(20) * Scalar(0.5) * d->r.head(12).transpose() * d->r.head(12); // state
cost_[1] = Scalar(0.5) * d->r.segment(12, 8).transpose() * d->r.segment(12, 8); // heuristic
cost_[2] = x(20) * Scalar(0.5) * d->r.tail(12).transpose() * d->r.tail(12); // Force norm
cost_[3] = dt_bound_weight * Scalar(0.5) * rub_max_dt.squaredNorm(); // upper/lower bound limit
cost_[4] =
Scalar(0.5) * ((last_position_weights_.cwiseProduct(x.segment(12, 8) - pref_)).array() * gait_double.array())
.matrix()
.squaredNorm(); // last position weight
cost_[5] = friction_weight_ * Scalar(0.5) * rub_max_.squaredNorm(); // friction weight
}
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::calcDiff(
const boost::shared_ptr<crocoddyl::ActionDataAbstractTpl<Scalar> >& data,
const Eigen::Ref<const typename MathBase::VectorXs>& x, const Eigen::Ref<const typename MathBase::VectorXs>& u) {
if (static_cast<std::size_t>(x.size()) != state_->get_nx()) {
throw_pretty("Invalid argument: "
<< "x has wrong dimension (it should be " + std::to_string(state_->get_nx()) + ")");
}
if (static_cast<std::size_t>(u.size()) != nu_) {
throw_pretty("Invalid argument: "
<< "u has wrong dimension (it should be " + std::to_string(nu_) + ")");
}
ActionDataQuadrupedAugmentedTimeTpl<Scalar>* d =
static_cast<ActionDataQuadrupedAugmentedTimeTpl<Scalar>*>(data.get());
// Cost derivatives : Lx
d->Lx.setZero();
d->Lx.template head<12>() = x(20) * (state_weights_.array() * d->r.template head<12>().array()).matrix();
d->Lx.template segment<8>(12) = (heuristicWeights.array() * d->r.template segment<8>(12).array()).matrix() +
((last_position_weights_.cwiseProduct(x.segment(12, 8) - pref_)).array() *
gait_double.array() * last_position_weights_.array())
.matrix();
d->Lx.template tail<1>() << dt_bound_weight * (-rub_max_dt[0] + rub_max_dt[1]);
// New cost : c = 0.5||x-x_ref||^2*dt
d->Lx.template tail<1>() += Scalar(0.5) * d->r.head(12).transpose() * d->r.head(12) +
Scalar(0.5) * d->r.tail(12).transpose() * d->r.tail(12);
// Cost derivative : Lu
for (int i = 0; i < 4; i = i + 1) {
r = friction_weight_ * rub_max_.segment(6 * i, 6);
d->Lu.block(i * 3, 0, 3, 1) << r(0) - r(1), r(2) - r(3), -mu * (r(0) + r(1) + r(2) + r(3)) - r(4) + r(5);
}
d->Lu = d->Lu + x(20) * (force_weights_.array() * d->r.template tail<12>().array()).matrix();
// Hessian : Lxx
d->Lxx.setZero();
d->Lxx.diagonal().head(12) = x(20) * (state_weights_.array() * state_weights_.array()).matrix();
d->Lxx.diagonal().segment(12, 8) =
(gait_double.array() * heuristicWeights.array() * heuristicWeights.array()).matrix();
d->Lxx.diagonal().segment(12, 8) +=
(gait_double.array() * last_position_weights_.array() * last_position_weights_.array()).matrix();
d->Lxx.diagonal().tail(1) << dt_bound_weight * rub_max_dt_bool[0] + dt_bound_weight * rub_max_dt_bool[1];
// New cost : partial derivatives of 20 and state (0--11)
d->Lxx.col(20).head(12) = (state_weights_.array() * d->r.template head<12>().array()).matrix();
d->Lxx.row(20).head(12) = d->Lxx.col(20).head(12);
for (int j = 0; j < 4; j = j + 1) {
if (sh_ub_max_[j] > Scalar(0.)) {
d->Lx(0, 0) += sh_weight * psh(0, j);
d->Lx(1, 0) += sh_weight * psh(1, j);
d->Lx(2, 0) += sh_weight * psh(2, j);
d->Lx(3, 0) += sh_weight * pshoulder_0(1, j) * psh(2, j);
d->Lx(4, 0) += -sh_weight * pshoulder_0(0, j) * psh(2, j);
d->Lx(5, 0) += sh_weight * (-pshoulder_0(1, j) * psh(0, j) + pshoulder_0(0, j) * psh(1, j));
d->Lx(12 + 2 * j, 0) += -sh_weight * psh(0, j);
d->Lx(12 + 2 * j + 1, 0) += -sh_weight * psh(1, j);
d->Lxx(0, 0) += sh_weight;
d->Lxx(1, 1) += sh_weight;
d->Lxx(2, 2) += sh_weight;
d->Lxx(3, 3) += sh_weight * pshoulder_0(1, j) * pshoulder_0(1, j);
d->Lxx(3, 3) += sh_weight * pshoulder_0(0, j) * pshoulder_0(0, j);
d->Lxx(5, 5) += sh_weight * (pshoulder_0(1, j) * pshoulder_0(1, j) + pshoulder_0(0, j) * pshoulder_0(0, j));
d->Lxx(12 + 2 * j, 12 + 2 * j) += sh_weight;
d->Lxx(12 + 2 * j + 1, 12 + 2 * j + 1) += sh_weight;
d->Lxx(0, 5) += -sh_weight * pshoulder_0(1, j);
d->Lxx(5, 0) += -sh_weight * pshoulder_0(1, j);
d->Lxx(1, 5) += sh_weight * pshoulder_0(0, j);
d->Lxx(5, 1) += sh_weight * pshoulder_0(0, j);
d->Lxx(2, 3) += sh_weight * pshoulder_0(1, j);
d->Lxx(2, 4) += -sh_weight * pshoulder_0(0, j);
d->Lxx(3, 2) += sh_weight * pshoulder_0(1, j);
d->Lxx(4, 2) += -sh_weight * pshoulder_0(0, j);
d->Lxx(3, 4) += -sh_weight * pshoulder_0(1, j) * pshoulder_0(0, j);
d->Lxx(4, 3) += -sh_weight * pshoulder_0(1, j) * pshoulder_0(0, j);
d->Lxx(0, 12 + 2 * j) += -sh_weight;
d->Lxx(12 + 2 * j, 0) += -sh_weight;
d->Lxx(5, 12 + 2 * j) += sh_weight * pshoulder_0(1, j);
d->Lxx(12 + 2 * j, 5) += sh_weight * pshoulder_0(1, j);
d->Lxx(1, 12 + 2 * j + 1) += -sh_weight;
d->Lxx(12 + 2 * j + 1, 1) += -sh_weight;
d->Lxx(5, 12 + 2 * j + 1) += -sh_weight * pshoulder_0(0, j);
d->Lxx(12 + 2 * j + 1, 5) += -sh_weight * pshoulder_0(0, j);
}
}
// Hessian : Luu
// Matrix friction cone hessian (20x12)
Arr.diagonal() = ((Fa_x_u - ub).array() >= Scalar(0.)).matrix().template cast<Scalar>();
for (int i = 0; i < 4; i = i + 1) {
r = friction_weight_ * Arr.diagonal().segment(6 * i, 6);
d->Luu.block(3 * i, 3 * i, 3, 3) << r(0) + r(1), 0.0, mu * (r(1) - r(0)), 0.0, r(2) + r(3), mu * (r(3) - r(2)),
mu * (r(1) - r(0)), mu * (r(3) - r(2)), mu * mu * (r(0) + r(1) + r(2) + r(3)) + r(4) + r(5);
}
d->Luu.diagonal() = d->Luu.diagonal() + x(20) * (force_weights_.array() * force_weights_.array()).matrix();
d->Lxu.row(20) = (force_weights_.array() * d->r.template tail<12>().array()).matrix();
// Dynamic derivatives
d->Fx.setZero();
d->Fx.block(0, 0, 12, 12) << A;
d->Fx.block(12, 12, 8, 8) << Eigen::Matrix<Scalar, 8, 8>::Identity();
d->Fx.block(20, 20, 1, 1) << Scalar(1);
d->Fx.block(8, 20, 1, 1) << -Scalar(9.81);
d->Fx.block(0, 20, 8, 1) << x.segment(6, 6);
for (int i = 0; i < 4; i = i + 1) {
if (gait(i, 0) != 0) {
forces_3d = u.block(3 * i, 0, 3, 1);
d->Fx.block(9, 0, 3, 1) += -x.tail(1)[0] * R * (base_vector_x.cross(forces_3d));
d->Fx.block(9, 1, 3, 1) += -x.tail(1)[0] * R * (base_vector_y.cross(forces_3d));
d->Fx.block(9, 2, 3, 1) += -x.tail(1)[0] * R * (base_vector_z.cross(forces_3d));
d->Fx.block(9, 12 + 2 * i, 3, 1) += x.tail(1)[0] * R * (base_vector_x.cross(forces_3d));
d->Fx.block(9, 12 + 2 * i + 1, 3, 1) += x.tail(1)[0] * R * (base_vector_y.cross(forces_3d));
d->Fx.block(6, 20, 3, 1) += (1 / mass) * forces_3d;
lever_tmp.setZero();
lever_tmp.head(2) = x.block(12 + 2 * i, 0, 2, 1);
lever_tmp += -x.block(0, 0, 3, 1);
R_tmp << Scalar(0.0), -lever_tmp[2], lever_tmp[1], lever_tmp[2], Scalar(0.0), -lever_tmp[0], -lever_tmp[1],
lever_tmp[0], Scalar(0.0);
d->Fx.block(9, 20, 3, 1) += R * R_tmp * forces_3d;
}
}
// d->Fu << Eigen::Matrix<Scalar, 20, 12>::Zero() ;
d->Fu.block(0, 0, 12, 12) << B;
}
template <typename Scalar>
boost::shared_ptr<crocoddyl::ActionDataAbstractTpl<Scalar> >
ActionModelQuadrupedAugmentedTimeTpl<Scalar>::createData() {
return boost::make_shared<ActionDataQuadrupedAugmentedTimeTpl<Scalar> >(this);
}
////////////////////////////////
// get & set parameters ////////
////////////////////////////////
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 12, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_force_weights() const {
return force_weights_;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_force_weights(const typename MathBase::VectorXs& weights) {
if (static_cast<std::size_t>(weights.size()) != 12) {
throw_pretty("Invalid argument: "
<< "Weights vector has wrong dimension (it should be 12)");
}
force_weights_ = weights;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 12, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_state_weights() const {
return state_weights_;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_state_weights(const typename MathBase::VectorXs& weights) {
if (static_cast<std::size_t>(weights.size()) != 12) {
throw_pretty("Invalid argument: "
<< "Weights vector has wrong dimension (it should be 12)");
}
state_weights_ = weights;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 8, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_heuristic_weights()
const {
return heuristicWeights;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_heuristic_weights(const typename MathBase::VectorXs& weights) {
if (static_cast<std::size_t>(weights.size()) != 8) {
throw_pretty("Invalid argument: "
<< "Weights vector has wrong dimension (it should be 8)");
}
heuristicWeights = weights;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 8, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_shoulder_position()
const {
return pshoulder_;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_shoulder_position(const typename MathBase::VectorXs& pos) {
if (static_cast<std::size_t>(pos.size()) != 8) {
throw_pretty("Invalid argument: "
<< "Weights vector has wrong dimension (it should be 8)");
}
pshoulder_ = pos;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 8, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_stop_weights() const {
return last_position_weights_;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_stop_weights(const typename MathBase::VectorXs& weights) {
if (static_cast<std::size_t>(weights.size()) != 8) {
throw_pretty("Invalid argument: "
<< "Weights vector has wrong dimension (it should be 8)");
}
last_position_weights_ = weights;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_friction_weight() const {
return friction_weight_;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_friction_weight(const Scalar& weight) {
friction_weight_ = weight;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_mu() const {
return mu;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_mu(const Scalar& mu_coeff) {
mu = mu_coeff;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_mass() const {
return mass;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_mass(const Scalar& m) {
// The model need to be updated after this changed
mass = m;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_dt_min() const {
return dt_min_[0];
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_dt_min(const Scalar& dt) {
// The model need to be updated after this changed
dt_min_[0] = dt;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_dt_max() const {
return dt_max_[0];
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_dt_max(const Scalar& dt) {
// The model need to be updated after this changed
dt_max_[0] = dt;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 3, 3>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_gI() const {
return gI;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_gI(const typename MathBase::Matrix3s& inertia_matrix) {
// The model need to be updated after this changed
if (static_cast<std::size_t>(inertia_matrix.size()) != 9) {
throw_pretty("Invalid argument: "
<< "gI has wrong dimension : 3x3");
}
gI = inertia_matrix;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_min_fz_contact() const {
// The model need to be updated after this changed
return min_fz_in_contact;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_min_fz_contact(const Scalar& min_fz) {
// The model need to be updated after this changed
min_fz_in_contact = min_fz;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_max_fz_contact() const {
// The model need to be updated after this changed
return max_fz;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_max_fz_contact(const Scalar& max_fz_) {
// The model need to be updated after this changed
max_fz = max_fz_;
for (int i = 0; i < 4; i = i + 1) {
ub(6 * i + 5) = max_fz;
}
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_shoulder_hlim() const {
return sh_hlim;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_shoulder_hlim(const Scalar& hlim) {
// The model need to be updated after this changed
sh_hlim = hlim;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_shoulder_contact_weight() const {
return sh_weight;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_shoulder_contact_weight(const Scalar& weight) {
// The model need to be updated after this changed
sh_weight = weight;
}
////////////////////////////////////////////
// Heuristic position
////////////////////////////////////////////
template <typename Scalar>
const bool& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_symmetry_term() const {
return symmetry_term;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_symmetry_term(const bool& sym_term) {
// The model need to be updated after this changed
symmetry_term = sym_term;
}
template <typename Scalar>
const bool& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_centrifugal_term() const {
return centrifugal_term;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_centrifugal_term(const bool& cent_term) {
// The model need to be updated after this changed
centrifugal_term = cent_term;
}
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_T_gait() const {
// The model need to be updated after this changed
return T_gait;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_T_gait(const Scalar& T_gait_) {
// The model need to be updated after this changed
T_gait = T_gait_;
}
//////////////////////////////////////
// lower/upper bound
//////////////////////////////////////
template <typename Scalar>
const Scalar& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_dt_bound_weight() const {
// The model need to be updated after this changed
return dt_bound_weight;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_dt_bound_weight(const Scalar& weight_) {
// The model need to be updated after this changed
dt_bound_weight = weight_;
}
// Log cost
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 7, 1>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_cost() const {
return cost_;
}
///////////////////////////
//// get A & B matrix /////
///////////////////////////
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 12, 12>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_A() const {
return A;
}
template <typename Scalar>
const typename Eigen::Matrix<Scalar, 12, 12>& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_B() const {
return B;
}
// to modify the cost on the command : || fz - m*g/nb contact ||^2
// --> set to True
template <typename Scalar>
const bool& ActionModelQuadrupedAugmentedTimeTpl<Scalar>::get_relative_forces() const {
return relative_forces;
}
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::set_relative_forces(const bool& rel_forces) {
relative_forces = rel_forces;
uref_.setZero();
if (relative_forces) {
for (int i = 0; i < 4; i = i + 1) {
if (gait[i] == 1) {
uref_[3 * i + 2] = (Scalar(9.81) * mass) / (gait.sum());
}
}
}
}
////////////////////////
// Update current model
////////////////////////
template <typename Scalar>
void ActionModelQuadrupedAugmentedTimeTpl<Scalar>::update_model(
const Eigen::Ref<const typename MathBase::MatrixXs>& l_feet,
const Eigen::Ref<const typename MathBase::MatrixXs>& l_stop,
const Eigen::Ref<const typename MathBase::MatrixXs>& xref,
const Eigen::Ref<const typename MathBase::MatrixXs>& S) {
if (static_cast<std::size_t>(l_feet.size()) != 12) {
throw_pretty("Invalid argument: "
<< "l_feet matrix has wrong dimension (it should be : 3x4)");
}
if (static_cast<std::size_t>(xref.size()) != 12) {
throw_pretty("Invalid argument: "
<< "xref vector has wrong dimension (it should be 12 )");
}
if (static_cast<std::size_t>(S.size()) != 4) {
throw_pretty("Invalid argument: "
<< "S vector has wrong dimension (it should be 4x1)");
}
xref_ = xref;
gait = S;
uref_.setZero();
if (relative_forces) {
for (int i = 0; i < 4; i = i + 1) {
if (gait[i] == 1) {
uref_[3 * i + 2] = (Scalar(9.81) * mass) / (gait.sum());
}
}
}
for (int i = 0; i < 4; i = i + 1) {
gait_double(2 * i, 0) = gait(i, 0);
gait_double(2 * i + 1, 0) = gait(i, 0);
pref_.block(2 * i, 0, 2, 1) = l_stop.block(0, i, 2, 1);
pheuristic_.block(2 * i, 0, 2, 1) = l_feet.block(0, i, 2, 1);
}
R_tmp << cos(xref(5, 0)), -sin(xref(5, 0)), Scalar(0), sin(xref(5, 0)), cos(xref(5, 0)), Scalar(0), Scalar(0),
Scalar(0), Scalar(1.0);
// Centrifual term
// pcentrifugal_tmp_1 = xref.block(6,0,3,1) ;
// pcentrifugal_tmp_2 = xref.block(9,0,3,1) ;
// pcentrifugal_tmp = 0.5*std::sqrt(xref(2,0)/9.81) * pcentrifugal_tmp_1.cross(pcentrifugal_tmp_2) ;
// for (int i=0; i<4; i=i+1){
// pshoulder_tmp.block(0,i,2,1) = R_tmp.block(0,0,2,2)*(pshoulder_0.block(0,i,2,1) + symmetry_term *
// 0.25*T_gait*xref.block(6,0,2,1) + centrifugal_term * pcentrifugal_tmp.block(0,0,2,1) );
// }
R = (R_tmp * gI).inverse(); // I_inv
for (int i = 0; i < 4; i = i + 1) {
// pshoulder_[2*i] = pshoulder_tmp(0,i) + xref(0,0) ;
// pshoulder_[2*i+1] = pshoulder_tmp(1,i) + xref(1,0) ;
if (S(i, 0) != 0) {
// set limit for normal force, (foot in contact with the ground)
ub(6 * i + 4) = -min_fz_in_contact;
} else {
// set limit for normal force at 0.0
ub(6 * i + 4) = Scalar(0.0);
B.block(6, 3 * i, 3, 3).setZero();
B.block(9, 3 * i, 3, 3).setZero();
};
};
}
} // namespace quadruped_walkgen
#endif
| 39.505865 | 119 | 0.629551 | [
"vector",
"model"
] |
0d4b2fdbcf6d507d672d1bda39df8d10d0900ac1 | 5,002 | cpp | C++ | pfcp/pfcptest/pcaps/pcaps.cpp | AustinKnutsonSprint/epctools-1 | 5a1839fe5847a8e7a83362d080abf8af0e53d5fd | [
"Apache-2.0"
] | 1 | 2020-06-17T16:29:50.000Z | 2020-06-17T16:29:50.000Z | pfcp/pfcptest/pcaps/pcaps.cpp | AustinKnutsonSprint/epctools-1 | 5a1839fe5847a8e7a83362d080abf8af0e53d5fd | [
"Apache-2.0"
] | 1 | 2020-07-24T19:32:29.000Z | 2020-07-24T19:32:29.000Z | pfcp/pfcptest/pcaps/pcaps.cpp | AustinKnutsonSprint/epctools-1 | 5a1839fe5847a8e7a83362d080abf8af0e53d5fd | [
"Apache-2.0"
] | 4 | 2020-06-01T20:08:52.000Z | 2020-06-24T12:42:23.000Z | /*
* Copyright (c) 2020 T-Mobile
*
* 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 "pcaps.h"
#include <set>
#include "pfcpr15inl.h"
#include "epctools.h"
#include "eutil.h"
#include "pcpp.h"
#include "test.h"
namespace PFCPTest
{
namespace pcaps
{
void InitTests()
{
// Load pcap tests from disk
std::set<EString> pcapFiles;
{
EString pcapsPath = "./pcaps/originals";
EDirectory pcapsDir;
cpStr pcapFile = pcapsDir.getFirstEntry(pcapsPath, "*.pcap");
while (pcapFile)
{
pcapFiles.emplace(pcapFile);
EString name = EPath::getFileNameWithoutExtension(pcapFile);
std::unique_ptr<Test> pcapTest(new PcapTest(name));
TestSuite::add(name, std::move(pcapTest));
pcapFile = pcapsDir.getNextEntry();
}
}
// Create the results folder if it doesn't exist
EString resultsPath = "./pcaps/results/";
EPath::verify(resultsPath);
// Remove previous results from the results folder
EDirectory dir;
cpStr fn = dir.getFirstEntry(resultsPath, "*");
while (fn)
{
EString file(fn);
if (pcapFiles.count(file) > 0)
{
EString filePath;
EPath::combine(resultsPath, file, filePath);
if (!EUtility::delete_file(filePath))
ELogger::log(LOG_SYSTEM).minor("Couldn't remove file {}", filePath);
}
fn = dir.getNextEntry();
}
}
bool RunPcapTest(Test &test)
{
EString originalPcap = "./pcaps/originals/" + test.name() + ".pcap";
EString baselinePcap = "./pcaps/baselines/" + test.name() + ".pcap";
EString resultPcap = "./pcaps/results/" + test.name() + ".pcap";
// Load each packet from the original pcap, decode and then encode it and
// add it to result packets
pcpp::RawPacketVector originalPackets = GetPackets(originalPcap);
pcpp::RawPacketVector resultPackets;
int packetNumber = 1;
for (auto originalPacket : originalPackets)
{
// Add to result packets (the packet vector owns the packet pointer)
pcpp::RawPacket *resultPacket = new pcpp::RawPacket(*originalPacket);
resultPackets.pushBack(resultPacket);
pcpp::Packet packet(resultPacket);
std::vector<uint8_t> payload = ExtractPFCPPayload(packet);
std::unique_ptr<PFCP::AppMsg> appMsg = DecodeAppMsg(payload);
if (!appMsg)
{
ELogger::log(LOG_TEST).major("Unhandled PFCP message type in packet {}", packetNumber);
++packetNumber;
continue;
}
// Cast it to the proper application layer type
switch (appMsg.get()->msgType())
{
case PFCP_PFD_MGMT_REQ:
{
// PFCP_R15::PfdMgmtReq &pfdMgmtReq = *(static_cast<PFCP_R15::PfdMgmtReq *>(appMsg.get()));
// // TEMP fixup for Application ID spare byte
// pfdMgmtReq.data().header.message_len += 1;
// pfdMgmtReq.data().app_ids_pfds[0].header.len += 1;
// pfdMgmtReq.data().app_ids_pfds[0].pfd_context[0].header.len += 1;
// pfdMgmtReq.data().app_ids_pfds[0].pfd_context[0].pfd_contents[0].header.len += 1;
break;
}
case PFCP_SESS_ESTAB_REQ:
{
// PFCP_R15::SessionEstablishmentReq &sessEstReq = *(static_cast<PFCP_R15::SessionEstablishmentReq *>(appMsg.get()));
break;
}
case PFCP_SESS_ESTAB_RSP:
{
//PFCP_R15::SessionEstablishmentRsp &sessEstRsp = *(static_cast<PFCP_R15::SessionEstablishmentRsp *>(appMsg.get()));
break;
}
default:
//ELogger::log(LOG_PFCP).major("Unhandled PFCP message type {}", appMsg->msgType());
break;
}
std::vector<uint8_t> payloadOut = EncodeAppMsg(appMsg.get());
ReplacePFCPPayload(packet, payloadOut);
++packetNumber;
}
// Write the result pcap
WritePcap(resultPcap, resultPackets);
return ComparePackets(baselinePcap, resultPcap);
}
} // namespace pcaps
} // namespace PFCPTest | 35.225352 | 132 | 0.577169 | [
"vector"
] |
0d4b6b2ba530390d0a4602fa35bf51dc3eb270c8 | 449 | cpp | C++ | DzidzoAndHisSongs.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | DzidzoAndHisSongs.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | DzidzoAndHisSongs.cpp | OrlykM/Algotester | 6d0702b191610795beb959d378ab1feef6191b68 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string s;
cin >> s;
if (s.size() >= 2 && s.size() <= 100)
{
vector<string> pairss;
for (int i = 0; i < s.size(); i++)
{
string temp = "";
temp += s[i];
s.erase(s.begin() + i);
pairss.push_back(s);
s.insert(i, temp);
}
pairss.erase(unique(pairss.begin(), pairss.end()), pairss.end());
cout << pairss.size();
}
return 0;
}
| 17.96 | 67 | 0.561247 | [
"vector"
] |
0d4fc66fafec384a6d707ba1d6438ef9f5663870 | 26,812 | cpp | C++ | tket/src/Transformations/CliffordReductionPass.cpp | NewGitter2017/tket | 6ff81af26280770bf2ca80bfb2140e8fa98182aa | [
"Apache-2.0"
] | null | null | null | tket/src/Transformations/CliffordReductionPass.cpp | NewGitter2017/tket | 6ff81af26280770bf2ca80bfb2140e8fa98182aa | [
"Apache-2.0"
] | null | null | null | tket/src/Transformations/CliffordReductionPass.cpp | NewGitter2017/tket | 6ff81af26280770bf2ca80bfb2140e8fa98182aa | [
"Apache-2.0"
] | null | null | null | // Copyright 2019-2021 Cambridge Quantum Computing
//
// 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 "CliffordReductionPass.hpp"
#include "PauliGraph/ConjugatePauliFunctions.hpp"
namespace tket {
/**
* Finds Clifford circuit C such that
* R[p](a); R[q](b) = C; RZ(a); RZ(b); C^\dagger if p==q or
* C; RZ(a); RY(b); C^\dagger if p!=q
*/
static const std::map<std::pair<Pauli, Pauli>, std::list<OpType>>
mapping_to_zz_or_zy_lut{
{{Pauli::X, Pauli::X}, {OpType::H}},
{{Pauli::X, Pauli::Y}, {OpType::H, OpType::Z}},
{{Pauli::X, Pauli::Z}, {OpType::H, OpType::S}},
{{Pauli::Y, Pauli::X}, {OpType::V, OpType::S}},
{{Pauli::Y, Pauli::Y}, {OpType::V}},
{{Pauli::Y, Pauli::Z}, {OpType::V, OpType::Z}},
{{Pauli::Z, Pauli::X}, {OpType::S}},
{{Pauli::Z, Pauli::Y}, {}},
{{Pauli::Z, Pauli::Z}, {}},
};
static const std::map<Pauli, OpType> pauli_to_pauli_gate_lut{
{Pauli::X, OpType::X},
{Pauli::Y, OpType::Y},
{Pauli::Z, OpType::Z},
};
/**
* Consider an interaction of R[p0, p1](+-0.5); R[q0, q1](+-0.5)
* where p0, p1, q0, q1 in {X, Y, Z}.
* Returns the equivalent replacement circuit with fewer 2qb interactions.
*/
static Circuit interaction_replacement(const InteractionMatch &match) {
const Pauli &p0 = match.point0.p;
const Pauli &p1 = match.point1.p;
const Pauli &q0 = match.rev0.p;
const Pauli &q1 = match.rev1.p;
Circuit replacement(2);
if (match.point0.phase ^ match.point1.phase) {
replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(p0), {0});
replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(p1), {1});
replacement.add_phase(0.5);
}
if (p0 == q0) {
if (p1 == q1) {
// R[p0, p1](1) = R[p0, I](1); R[I, p1](1)
OpType op0 = pauli_to_pauli_gate_lut.at(p0);
OpType op1 = pauli_to_pauli_gate_lut.at(p1);
replacement.add_op<unsigned>(op0, {0});
replacement.add_op<unsigned>(op1, {1});
replacement.add_phase(-0.5);
} else {
// Map to R[Z, Z](0.5); R[Z, Y](0.5)
Circuit basis_change(2);
std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0});
std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1});
for (OpType op : ops0) {
basis_change.add_op<unsigned>(op, {0});
}
for (OpType op : ops1) {
basis_change.add_op<unsigned>(op, {1});
}
replacement.append(basis_change);
replacement.add_op<unsigned>(OpType::V, {1});
replacement.add_op<unsigned>(OpType::ZZMax, {0, 1});
replacement.append(basis_change.dagger());
}
} else {
if (p1 == q1) {
// Map to R[Z, Z](0.5); R[Y, Z](0.5)
Circuit basis_change(2);
std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0});
std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1});
for (OpType op : ops0) {
basis_change.add_op<unsigned>(op, {0});
}
for (OpType op : ops1) {
basis_change.add_op<unsigned>(op, {1});
}
replacement.append(basis_change);
replacement.add_op<unsigned>(OpType::V, {0});
replacement.add_op<unsigned>(OpType::ZZMax, {0, 1});
replacement.append(basis_change.dagger());
} else {
// Map to R[Z, Z](0.5); R[Y, Y](0.5)
Circuit basis_change(2);
std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0});
std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1});
for (OpType op : ops0) {
basis_change.add_op<unsigned>(op, {0});
}
for (OpType op : ops1) {
basis_change.add_op<unsigned>(op, {1});
}
replacement.append(basis_change);
replacement.add_op<unsigned>(OpType::H, {0});
replacement.add_op<unsigned>(OpType::H, {1});
replacement.add_op<unsigned>(OpType::Z, {0});
replacement.add_op<unsigned>(OpType::Z, {1});
replacement.add_op<unsigned>(OpType::ZZMax, {0, 1});
replacement.add_op<unsigned>(OpType::H, {0});
replacement.add_op<unsigned>(OpType::H, {1});
replacement.add_op<unsigned>(OpType::SWAP, {0, 1});
replacement.add_phase(0.25);
replacement.append(basis_change.dagger());
}
}
if (match.rev0.phase ^ match.rev1.phase) {
replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(q0), {0});
replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(q1), {1});
replacement.add_phase(0.5);
}
return replacement;
}
/**
* Given a 2qb Clifford gate, returns just the local operations applied around
* the maximally-entangling gadget.
*/
static Circuit local_cliffords(OpType op) {
Circuit locals(2);
switch (op) {
case OpType::CX: {
locals.add_op<unsigned>(OpType::Sdg, {0});
locals.add_op<unsigned>(OpType::Vdg, {1});
break;
}
case OpType::CZ: {
locals.add_op<unsigned>(OpType::Sdg, {0});
locals.add_op<unsigned>(OpType::Sdg, {1});
locals.add_phase(0.25);
break;
}
case OpType::CY: {
locals.add_op<unsigned>(OpType::Sdg, {0});
locals.add_op<unsigned>(OpType::V, {1});
locals.add_op<unsigned>(OpType::Sdg, {1});
locals.add_op<unsigned>(OpType::Vdg, {1});
locals.add_phase(0.25);
break;
}
case OpType::ZZMax: {
break;
}
default: {
throw CircuitInvalidity(
"Attempting to replace non-Clifford gate with Clifford "
"optimisation");
break;
}
}
return locals;
}
void CliffordReductionPass::insert_interaction_point(InteractionPoint ip) {
itable.insert(ip);
Vertex next = circ.target(ip.e);
port_t next_p = circ.get_target_port(ip.e);
bool commute = true;
while (commute) {
if (v_to_depth.find(next) == v_to_depth.end()) {
commute = false;
continue;
}
Op_ptr op = circ.get_Op_ptr_from_Vertex(next);
if (!op->get_desc().is_gate()) {
commute = false;
continue;
}
OpType type = op->get_type();
switch (type) {
case OpType::H:
case OpType::S:
case OpType::Sdg:
case OpType::V:
case OpType::Vdg:
case OpType::X:
case OpType::Y:
case OpType::Z: {
std::pair<Pauli, bool> new_basis = conjugate_Pauli(type, ip.p, true);
ip.p = new_basis.first;
ip.phase ^= new_basis.second;
break;
}
case OpType::SWAP: {
next_p = 1 - next_p;
break;
}
default: {
if (!op->commutes_with_basis(ip.p, next_p)) {
commute = false;
continue;
}
break;
}
}
ip.e = circ.get_nth_out_edge(next, next_p);
auto inserted = itable.insert(ip);
commute = inserted.second;
if (!commute) {
// Now `inserted.first` points to the element of the table that
// blocked insertion, i.e. had the same source/edge combination.
// Check that its `p` and `phase` are correct: if not, something has
// gone wrong.
auto blocker = inserted.first;
TKET_ASSERT(blocker->p == ip.p && blocker->phase == ip.phase);
}
next = circ.target(ip.e);
next_p = circ.get_target_port(ip.e);
}
}
std::optional<InteractionMatch> CliffordReductionPass::search_back_for_match(
const RevInteractionPoint &rip0, const RevInteractionPoint &rip1) const {
RevInteractionPoint point[2];
point[0] = rip0;
point[1] = rip1;
std::map<Edge, RevInteractionPoint> point_lookup;
IndexMap im = circ.index_map();
// interactions met when commuting back; point lists are in causal order of
// circuit:
std::map<IVertex, std::list<InteractionPoint>> candidates[2];
for (unsigned i = 0; i < 2; ++i) {
// Commute edge i back as far as possible
bool commute = true;
while (commute) {
point_lookup.insert({point[i].e, point[i]});
auto r = itable.get<TagEdge>().equal_range(point[i].e);
for (auto it = r.first; it != r.second; ++it) {
Vertex v = it->source;
candidates[i][{im.at(v), v}].push_front(*it);
}
Vertex pred = circ.source(point[i].e);
port_t pred_port = circ.get_source_port(point[i].e);
Op_ptr pred_op = circ.get_Op_ptr_from_Vertex(pred);
if (!pred_op->get_desc().is_gate()) {
commute = false;
continue;
}
OpType type = pred_op->get_type();
switch (type) {
case OpType::H:
case OpType::S:
case OpType::Sdg:
case OpType::V:
case OpType::Vdg:
case OpType::X:
case OpType::Y:
case OpType::Z: {
std::pair<Pauli, bool> new_basis = conjugate_Pauli(type, point[i].p);
point[i].p = new_basis.first;
point[i].phase ^= new_basis.second;
break;
}
case OpType::SWAP: {
pred_port = 1 - pred_port;
break;
}
default: {
commute = pred_op->commutes_with_basis(point[i].p, pred_port);
break;
}
}
point[i].e = circ.get_nth_in_edge(pred, pred_port);
}
}
// Check for matching interactions
for (const std::pair<const IVertex, std::list<InteractionPoint>> &pair :
candidates[0]) {
auto found = candidates[1].find(pair.first);
if (found != candidates[1].end()) {
std::optional<std::pair<InteractionPoint, InteractionPoint>>
insert_point = valid_insertion_point(pair.second, found->second);
if (insert_point) {
InteractionMatch match = {
insert_point->first, insert_point->second,
point_lookup.at(insert_point->first.e),
point_lookup.at(insert_point->second.e)};
if (!allow_swaps) {
if (match.point0.p != match.rev0.p && match.point1.p != match.rev1.p)
continue;
}
return match;
}
}
}
return std::nullopt;
}
void CliffordReductionPass::process_new_interaction(const Vertex &inter) {
// Process the vertex as well as any new 2qb Cliffords that get inserted
// while doing so (and so on until there are none left to process).
std::list<Vertex> to_process = {inter};
while (!to_process.empty()) {
Vertex v = to_process.front();
to_process.pop_front();
Op_ptr op = circ.get_Op_ptr_from_Vertex(v);
Pauli basis0 = *op->commuting_basis(0);
Pauli basis1 = *op->commuting_basis(1);
EdgeVec ins = circ.get_in_edges(v);
RevInteractionPoint rip0 = {ins.at(0), basis0, false};
RevInteractionPoint rip1 = {ins.at(1), basis1, false};
std::optional<InteractionMatch> match = search_back_for_match(rip0, rip1);
if (match) {
Circuit replacement = interaction_replacement(*match);
Subcircuit site;
site.q_in_hole = site.q_out_hole = {match->point0.e, match->point1.e};
Subcircuit inserted = substitute(replacement, site);
const Vertex &source = match->point0.source;
Circuit source_locals =
local_cliffords(circ.get_OpType_from_Vertex(source));
Subcircuit source_site;
source_site.q_in_hole = circ.get_in_edges(source);
source_site.q_out_hole = {
circ.get_nth_out_edge(source, 0), circ.get_nth_out_edge(source, 1)};
source_site.verts.insert(source);
substitute(source_locals, source_site);
Circuit v_locals = local_cliffords(op->get_type());
Subcircuit v_site;
v_site.q_in_hole = circ.get_in_edges(v);
v_site.q_out_hole = {
circ.get_nth_out_edge(v, 0), circ.get_nth_out_edge(v, 1)};
v_site.verts.insert(v);
substitute(v_locals, v_site);
for (const Vertex &new_v : inserted.verts) {
if (circ.n_in_edges(new_v) == 2 &&
circ.get_OpType_from_Vertex(new_v) != OpType::SWAP) {
to_process.push_back(new_v);
break;
}
}
success = true;
} else {
std::vector<std::optional<Edge>> outs = circ.get_linear_out_edges(v);
InteractionPoint ip0 = {*outs.at(0), v, basis0, false};
insert_interaction_point(ip0);
InteractionPoint ip1 = {*outs.at(1), v, basis1, false};
insert_interaction_point(ip1);
}
}
}
Subcircuit CliffordReductionPass::substitute(
const Circuit &to_insert, const Subcircuit &to_replace) {
unsigned q_width = to_replace.q_in_hole.size();
TKET_ASSERT(q_width == 2);
// Construct tables of predecessors, successors, units, in-edges, out-edges.
// Only quantum circuit replacments here so don't care about classical stuff
std::vector<VertPort> preds(q_width);
std::vector<VertPort> succs(q_width);
std::vector<UnitID> units(q_width);
std::vector<Edge> in_edges(q_width);
std::vector<Edge> out_edges(q_width);
for (unsigned qi = 0; qi < q_width; ++qi) {
const Edge &in = to_replace.q_in_hole.at(qi);
const Edge &out = to_replace.q_out_hole.at(qi);
preds[qi] = {circ.source(in), circ.get_source_port(in)};
succs[qi] = {circ.target(out), circ.get_target_port(out)};
units[qi] = e_to_unit.at(in);
in_edges[qi] = in;
out_edges[qi] = out;
TKET_ASSERT(in == out || circ.target(in) == circ.source(out));
}
// List of points that will be invalidated by the substitution.
std::list<InteractionPoint> invalidated_points;
// Lists of points having the same "in"/"out" edge as the replacement:
// These are all invalidated (though the "in" ones can be replaced later
// with the new edge).
std::vector<std::list<InteractionPoint>> points_with_in(q_width);
std::vector<std::list<InteractionPoint>> points_with_out(q_width);
for (unsigned qi = 0; qi < q_width; ++qi) {
auto r = itable.get<TagEdge>().equal_range(in_edges[qi]);
for (auto it = r.first; it != r.second; it++) {
points_with_in[qi].push_back(*it);
invalidated_points.push_back(*it);
}
r = itable.get<TagEdge>().equal_range(out_edges[qi]);
for (auto it = r.first; it != r.second; it++) {
points_with_out[qi].push_back(*it);
invalidated_points.push_back(*it);
}
}
// For any (e0, v0) in points_with_out, any point (e1, v0) where e1 is in
// the causal future of e0 is also invalidated. Calculate all the future
// edges.
EdgeList future_edges;
VertexSet v_frontier;
for (unsigned qi = 0; qi < q_width; ++qi) {
v_frontier.insert(circ.target(out_edges[qi]));
}
while (!v_frontier.empty()) {
EdgeSet out_edges;
for (auto v : v_frontier) {
if (v_to_depth.find(v) != v_to_depth.end()) {
EdgeVec v_out_edges = circ.get_out_edges_of_type(v, EdgeType::Quantum);
out_edges.insert(v_out_edges.begin(), v_out_edges.end());
}
}
future_edges.insert(future_edges.end(), out_edges.begin(), out_edges.end());
VertexSet new_v_frontier;
for (auto e : out_edges) {
new_v_frontier.insert(circ.target(e));
}
v_frontier = std::move(new_v_frontier);
}
// Invalidate the (e1, v0) as above.
VertexSet invalid_sources;
for (unsigned qi = 0; qi < q_width; ++qi) {
for (auto ip : points_with_out[qi]) {
TKET_ASSERT(ip.e == out_edges[qi]);
invalid_sources.insert(ip.source);
}
}
for (auto e1 : future_edges) {
auto r = itable.get<TagEdge>().equal_range(e1);
for (auto it = r.first; it != r.second; ++it) {
if (invalid_sources.find(it->source) != invalid_sources.end()) {
invalidated_points.push_back(*it);
}
}
}
// Erase the invalidated points from the table.
for (auto ip : invalidated_points) {
itable.erase(ip.key());
}
// Erase edges from e_to_unit
for (unsigned qi = 0; qi < q_width; ++qi) {
e_to_unit.erase(in_edges[qi]);
e_to_unit.erase(out_edges[qi]);
// Depth of to_replace is at most 1, so there are no other edges
}
// Remove replaced vertices from depth and units maps and erase all points
// from the itable that have a replaced vertex as source.
for (const Vertex &v : to_replace.verts) {
v_to_depth.erase(v);
v_to_units.erase(v);
auto r = itable.get<TagSource>().equal_range(v);
for (auto next = r.first; next != r.second; r.first = next) {
++next;
itable.erase(itable.project<TagKey>(r.first));
}
}
circ.substitute(to_insert, to_replace);
// Update the tables of in and out edges, and amend the stored points
for (unsigned qi = 0; qi < q_width; ++qi) {
in_edges[qi] = circ.get_nth_out_edge(preds[qi].first, preds[qi].second);
out_edges[qi] = circ.get_nth_in_edge(succs[qi].first, succs[qi].second);
for (InteractionPoint &ip : points_with_in[qi]) {
ip.e = in_edges[qi];
}
}
// Construct inserted Subcircuit, update e_to_unit and v_to_units, and
// add new vertices to v_to_depth, with (temporary) value 0.
Subcircuit inserted;
for (unsigned qi = 0; qi < q_width; ++qi) {
Edge in = in_edges[qi];
inserted.q_in_hole.push_back(in);
Edge out = out_edges[qi];
inserted.q_out_hole.push_back(out);
while (in != out) {
Vertex next = circ.target(in);
inserted.verts.insert(next);
e_to_unit.insert({in, units[qi]});
v_to_depth.insert({next, 0});
v_to_units[next].insert(units[qi]);
in = circ.get_nth_out_edge(next, circ.get_target_port(in));
}
e_to_unit.insert({in, units[qi]});
}
// Now `v_to_depth` is 0 at all `inserted.verts`. Fix this and propagate
// updates to the depth map into the future cone, ensuring that the depths
// are strictly increasing along wires. Stop when we reach a vertex that
// isn't already in v_to_depth (because we haven't processed it yet).
for (unsigned qi = 0; qi < q_width; ++qi) {
Edge in = in_edges[qi];
Vertex next = circ.target(in);
if (next != succs[qi].first) {
if (v_to_depth.at(preds[qi].first) >= v_to_depth[next]) {
// We may have already set v_to_depth[next] to a higher value
// when tracing another qubit, so the check above is necessary.
v_to_depth[next] = v_to_depth.at(preds[qi].first) + 1;
}
std::function<bool(const Vertex &, const Vertex &)> c =
[&](const Vertex &a, const Vertex &b) {
unsigned deptha = v_to_depth.at(a);
unsigned depthb = v_to_depth.at(b);
if (deptha == depthb) {
unit_set_t unitsa = v_to_units.at(a);
unit_set_t unitsb = v_to_units.at(b);
return unitsa < unitsb;
}
return deptha < depthb;
};
std::set<Vertex> to_search;
to_search.insert(next);
while (!to_search.empty()) {
Vertex v = *std::min_element(to_search.begin(), to_search.end(), c);
to_search.erase(v);
unsigned v_depth = v_to_depth.at(v);
EdgeVec outs = circ.get_all_out_edges(v);
for (const Edge &e : outs) {
Vertex succ = circ.target(e);
std::map<Vertex, unsigned>::iterator succ_it = v_to_depth.find(succ);
if (succ_it != v_to_depth.end()) {
if (succ_it->second <= v_depth) {
succ_it->second = v_depth + 1;
if (v_depth >= current_depth) {
current_depth = v_depth + 1;
}
to_search.insert(succ);
}
}
}
}
}
}
// Re-insert all the interaction points we erased above.
for (unsigned qi = 0; qi < q_width; ++qi) {
for (const InteractionPoint &ip : points_with_in[qi]) {
insert_interaction_point(ip);
}
}
return inserted;
}
std::optional<Edge> CliffordReductionPass::find_earliest_successor(
const Edge &source, const EdgeSet &candidates) const {
typedef std::function<bool(Vertex, Vertex)> Comp;
Comp c = [&](Vertex a, Vertex b) {
unsigned deptha = v_to_depth.at(a);
unsigned depthb = v_to_depth.at(b);
if (deptha == depthb) {
unit_set_t unitsa = v_to_units.at(a);
unit_set_t unitsb = v_to_units.at(b);
return unitsa < unitsb;
}
return deptha < depthb;
};
std::set<Vertex, Comp> to_search(c);
to_search.insert(circ.target(source));
while (!to_search.empty()) {
Vertex v = *to_search.begin();
to_search.erase(to_search.begin());
EdgeVec outs = circ.get_all_out_edges(v);
for (const Edge &e : outs) {
if (candidates.find(e) != candidates.end()) return e;
Vertex succ = circ.target(e);
if (v_to_depth.find(succ) != v_to_depth.end()) to_search.insert(succ);
}
}
return std::nullopt;
}
std::optional<std::pair<InteractionPoint, InteractionPoint>>
CliffordReductionPass::valid_insertion_point(
const std::list<InteractionPoint> &seq0,
const std::list<InteractionPoint> &seq1) const {
// seq0 is chain of edges (in temporal order) from the first qubit
// likewise seq1 for the other qubit
InteractionPoint seq0max = seq0.back();
InteractionPoint seq1max = seq1.back();
if (circ.in_causal_order(
circ.source(seq1max.e), circ.target(seq0max.e), true, v_to_depth,
v_to_units, false)) {
// Search for any points in seq1 from future of seq0max
EdgeSet candidates;
std::map<Edge, InteractionPoint> lookup;
for (const InteractionPoint &ip : seq1) {
candidates.insert(ip.e);
lookup.insert({ip.e, ip});
}
std::optional<Edge> successor =
find_earliest_successor(seq0max.e, candidates);
if (!successor || successor == seq1.front().e) return std::nullopt;
Vertex v = circ.source(*successor);
port_t p = circ.get_source_port(*successor);
if (circ.get_OpType_from_Vertex(v) == OpType::SWAP) p = 1 - p;
return {{seq0max, lookup.at(circ.get_nth_in_edge(v, p))}};
} else if (circ.in_causal_order(
circ.source(seq0max.e), circ.target(seq1max.e), true,
v_to_depth, v_to_units, false)) {
// Search for any points in seq0 from future of seq1max
EdgeSet candidates;
std::map<Edge, InteractionPoint> lookup;
for (const InteractionPoint &ip : seq0) {
candidates.insert(ip.e);
lookup.insert({ip.e, ip});
}
std::optional<Edge> successor =
find_earliest_successor(seq1max.e, candidates);
if (!successor || successor == seq0.front().e) return std::nullopt;
Vertex v = circ.source(*successor);
port_t p = circ.get_source_port(*successor);
if (circ.get_OpType_from_Vertex(v) == OpType::SWAP) p = 1 - p;
return {{lookup.at(circ.get_nth_in_edge(v, p)), seq1max}};
} else {
// seq0max and seq1max are space-like separated
return {{seq0max, seq1max}};
}
}
CliffordReductionPass::CliffordReductionPass(Circuit &c, bool swaps)
: circ(c),
itable(),
v_to_depth(),
success(false),
current_depth(1),
allow_swaps(swaps) {
v_to_units = circ.vertex_unit_map();
e_to_unit = circ.edge_unit_map();
}
bool CliffordReductionPass::reduce_circuit(Circuit &circ, bool allow_swaps) {
CliffordReductionPass context(circ, allow_swaps);
SliceVec slices = circ.get_slices();
for (const Vertex &in : circ.all_inputs()) {
context.v_to_depth.insert({in, 0});
}
// Process all 2qb Clifford vertices.
for (const Slice &sl : slices) {
for (const Vertex &v : sl) {
context.v_to_depth.insert({v, context.current_depth});
Op_ptr op = circ.get_Op_ptr_from_Vertex(v);
if (!op->get_desc().is_gate()) continue;
EdgeVec ins = circ.get_in_edges(v);
std::vector<std::optional<Edge>> outs = circ.get_linear_out_edges(v);
OpType type = op->get_type();
std::list<InteractionPoint> new_points;
switch (type) {
case OpType::H:
case OpType::S:
case OpType::Sdg:
case OpType::V:
case OpType::Vdg:
case OpType::X:
case OpType::Y:
case OpType::Z: {
auto r = context.itable.get<TagEdge>().equal_range(ins[0]);
for (auto it = r.first; it != r.second; ++it) {
InteractionPoint ip = *it;
std::pair<Pauli, bool> new_basis =
conjugate_Pauli(type, ip.p, true);
ip.p = new_basis.first;
ip.phase ^= new_basis.second;
ip.e = *outs[0];
new_points.push_back(ip);
}
break;
}
case OpType::SWAP: {
auto r0 = context.itable.get<TagEdge>().equal_range(ins[0]);
for (auto it = r0.first; it != r0.second; ++it) {
InteractionPoint ip = *it;
ip.e = *outs[1];
new_points.push_back(ip);
}
auto r1 = context.itable.get<TagEdge>().equal_range(ins[1]);
for (auto it = r1.first; it != r1.second; ++it) {
InteractionPoint ip = *it;
ip.e = *outs[0];
new_points.push_back(ip);
}
break;
}
default: {
for (unsigned i = 0; i < ins.size(); ++i) {
auto r = context.itable.get<TagEdge>().equal_range(ins[i]);
for (auto it = r.first; it != r.second; ++it) {
InteractionPoint ip = *it;
if (op->commutes_with_basis(ip.p, i)) {
ip.e = *outs[i];
new_points.push_back(ip);
}
}
}
break;
}
}
for (const InteractionPoint &ip : new_points) {
context.itable.insert(ip);
}
switch (type) {
case OpType::CX:
case OpType::CY:
case OpType::CZ:
case OpType::ZZMax: {
context.process_new_interaction(v);
break;
}
default: {
break;
}
}
}
++context.current_depth;
}
if (allow_swaps) {
circ.replace_SWAPs();
}
return context.success;
}
Transform Transform::clifford_reduction(bool allow_swaps) {
return Transform([=](Circuit &circ) {
return CliffordReductionPass::reduce_circuit(circ, allow_swaps);
});
}
CliffordReductionPassTester::CliffordReductionPassTester(Circuit &circ)
: context(circ, true) {
// populate v_to_depth
for (const Vertex &in : circ.all_inputs()) {
context.v_to_depth.insert({in, 0});
}
SliceVec slices = circ.get_slices();
for (const Slice &sl : slices) {
for (const Vertex &v : sl) {
context.v_to_depth.insert({v, context.current_depth});
}
}
}
std::optional<std::pair<InteractionPoint, InteractionPoint>>
CliffordReductionPassTester::valid_insertion_point(
const std::list<InteractionPoint> &seq0,
const std::list<InteractionPoint> &seq1) const {
return context.valid_insertion_point(seq0, seq1);
}
} // namespace tket
| 34.820779 | 80 | 0.61741 | [
"vector",
"transform"
] |
0d58e5d470f518366b386513ee84e6dc8afe3beb | 8,458 | cpp | C++ | Test/Math.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | 10 | 2018-10-30T14:19:57.000Z | 2021-12-06T07:46:59.000Z | Test/Math.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | null | null | null | Test/Math.cpp | AirGuanZ/Utils | 6ededbd838697682430a2c0746bfd3b36ff14a5b | [
"MIT"
] | 3 | 2019-04-24T13:42:02.000Z | 2021-06-28T08:17:28.000Z | #include <AGZUtils/Utils/Math.h>
#include "Catch.hpp"
using namespace AGZ::Math;
using namespace std;
TEST_CASE("Math")
{
SECTION("Angle")
{
REQUIRE(ApproxEq(PI<Radd>.value, 3.1415926, 1e-5));
REQUIRE(ApproxEq(PI<Degd>.value, 180.0, 1e-7));
REQUIRE(ApproxEq(PI<double>, 3.1415926, 1e-5));
REQUIRE(ApproxEq(Sin(PI<Degd>), 0.0, 1e-5));
REQUIRE(ApproxEq(Cos(PI<Degd>), -1.0, 1e-5));
REQUIRE(ApproxEq(Sin(PI<Degd> / 2.0), 1.0, 1e-5));
REQUIRE(ApproxEq(Sin(PI<Degd> / 2.0 + PI<Degd> / 2.0),
0.0, 1e-5));
}
SECTION("Transform")
{
Vec4d v(1.0, 2.0, 3.0, 1.0);
RM_Mat4d m = RM_Mat4d::Translate({ 3.0, 2.0, 1.0 });
REQUIRE(ApproxEq(m * v, Vec4d(4.0, 4.0, 4.0, 1.0), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
m = RM_Mat4d::Scale({ 1.0, 2.0, 3.0 });
REQUIRE(ApproxEq(m * v, Vec4d(1.0, 4.0, 9.0, 1.0), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
v = Vec4d::UNIT_X();
m = RM_Mat4d::Rotate(Vec3d::UNIT_Z(), Degd(90.0));
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Y(), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
v = Vec4d::UNIT_Y();
m = RM_Mat4d::Rotate(Vec3d::UNIT_X(), PI<Radd> / 2.0);
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Z(), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
v = Vec4d::UNIT_X();
m = RM_Mat4d::RotateZ(Degd(90.0));
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Y(), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
v = Vec4d::UNIT_Y();
m = RM_Mat4d::RotateX(PI<Radd> / 2.0);
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Z(), 1e-5));
REQUIRE(ApproxEq(Inverse(m) * m * v, v, 1e-5));
}
SECTION("Proj")
{
RM_Mat4d proj = RM_Mat4d::Perspective(Degd(60.0), 640.0 / 480.0, 0.1, 100.0);
REQUIRE((proj * Vec4d(0.0, 0.0, 0.0, 1.0)).z < 0.0);
REQUIRE(ApproxEq(Homogenize(proj * Vec4d(0.0, 10.0 / Sqrt(3.0), 10.0, 1.0)).y,
1.0, 1e-5));
REQUIRE(ApproxEq(Homogenize(proj * Vec4d(10.0 / Sqrt(3.0) * 640.0 / 480.0, 0.0, 10.0, 1.0)).x,
1.0, 1e-5));
}
SECTION("CM_Transform")
{
Vec4d v(1.0, 2.0, 3.0, 1.0);
CM_Mat4d m = CM_Mat4d::Translate({ 3.0, 2.0, 1.0 });
REQUIRE(ApproxEq(m * v, Vec4d(4.0, 4.0, 4.0, 1.0), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
m = CM_Mat4d::Scale({ 1.0, 2.0, 3.0 });
REQUIRE(ApproxEq(m * v, Vec4d(1.0, 4.0, 9.0, 1.0), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
v = Vec4d::UNIT_X();
m = CM_Mat4d::Rotate(Vec3d::UNIT_Z(), Degd(90.0));
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Y(), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
v = Vec4d::UNIT_Y();
m = CM_Mat4d::Rotate(Vec3d::UNIT_X(), PI<Radd> / 2.0);
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Z(), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
v = Vec4d::UNIT_X();
m = CM_Mat4d::RotateZ(Degd(90.0));
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Y(), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
v = Vec4d::UNIT_Y();
m = CM_Mat4d::RotateX(PI<Radd> / 2.0);
REQUIRE(ApproxEq(m * v, Vec4d::UNIT_Z(), 1e-5));
REQUIRE(ApproxEq(m.Inverse() * m * v, v, 1e-5));
}
SECTION("CM_Proj")
{
CM_Mat4d proj = CM_Mat4d::Perspective(Degd(60.0), 640.0 / 480.0, 0.1, 100.0);
REQUIRE((proj * Vec4d(0.0, 0.0, 0.0, 1.0)).z < 0.0);
REQUIRE(ApproxEq(Homogenize(proj * Vec4d(0.0, 10.0 / Sqrt(3.0), 10.0, 1.0)).y,
1.0, 1e-5));
REQUIRE(ApproxEq(Homogenize(proj * Vec4d(10.0 / Sqrt(3.0) * 640.0 / 480.0, 0.0, 10.0, 1.0)).x,
1.0, 1e-5));
}
SECTION("Vec")
{
REQUIRE(ApproxEq(Cross(Vec3d::UNIT_X(), Vec3d::UNIT_Y()), Vec3d::UNIT_Z(), 1e-5));
REQUIRE(ApproxEq(Cross(Vec3d::UNIT_Y(), Vec3d::UNIT_Z()), Vec3d::UNIT_X(), 1e-5));
REQUIRE(ApproxEq(Cross(Vec3d::UNIT_Z(), Vec3d::UNIT_X()), Vec3d::UNIT_Y(), 1e-5));
REQUIRE(ApproxEq(Dot(Vec4d::UNIT_X(), Vec4d::UNIT_Z()), 0.0, 1e-7));
REQUIRE(ApproxEq(Dot(RM_Mat4d::RotateY(Degd(90.0)) * Vec4d(1.0, 0.0, 4.0, 0.0),
Vec4d(1.0, 0.0, 4.0, 0.0)),
0.0, 1e-7));
REQUIRE(ApproxEq(2.f * Vec2f(1.0, 2.0) + Vec2f(2.0, 3.0), Vec2f(4.0, 7.0), 1e-5f));
REQUIRE(ApproxEq(Vec3f(1.0, 2.0, 3.0) * Vec3f(2.0, 3.0, 4.0),
Vec3f(2.0, 6.0, 12.0), 1e-5f));
REQUIRE(ApproxEq(Vec4d(1.0, 2.0, 3.0, 4.0).abgr(), Vec4d(4.0, 3.0, 2.0, 1.0), 1e-10));
REQUIRE(ApproxEq(Vec4d(1.0, 2.0, 3.0, 4.0).xxz(), Vec3d(1.0, 1.0, 3.0), 1e-10));
REQUIRE(ApproxEq(Vec4d(1.0, 2.0, 3.0, 4.0).um(), Vec2d(1.0, 3.0), 1e-10));
}
SECTION("Color")
{
REQUIRE(ApproxEq((Color4f)COLOR::VOIDC, Color4f(0.f, 0.f, 0.f, 0.f), 1e-10f));
REQUIRE(ApproxEq((Color4f)COLOR::RED, Color4f(1.f, 0.f, 0.f, 1.f), 1e-10f));
REQUIRE(ApproxEq((Color4f)COLOR::GREEN, Color4f(0.f, 1.f, 0.f, 1.f), 1e-10f));
REQUIRE(ApproxEq(Clamp(Color4d(-4.0, 8.0, 0.0, 1.0), 0.0, 1.0),
Color4d(0.f, 1.f, 0.f, 1.f), 1e-10));
REQUIRE(ApproxEq(2.0 * Color3d(-4.0, 8.0, 0.0) + Color3d(8.0, -15.0, 1.0),
Color3d(0.f, 1.f, 1.f), 1e-7));
}
SECTION("F32x4")
{
F32x4 a(1.0f, 2.0f, 3.0f, 4.0f);
F32x4 b(2.0f, 3.0f, 4.0f, 5.0f);
REQUIRE(ApproxEq(a + b, F32x4(3.0, 5.0, 7.0, 9.0), 1e-5f));
REQUIRE(ApproxEq(Sqrt(F32x4(4.0f, 3.0f, 2.0f, 1.0f)).AsVec(),
Vec4f(4.0f, 3.0f, 2.0f, 1.0f).Map(
[](float x) { return Sqrt(x); }),
1e-5f));
}
#if defined(AGZ_USE_AVX)
SECTION("D64x4")
{
D64x4 a(1.0, 2.0, 3.0, 4.0);
D64x4 b(2.0, 3.0, 4.0, 5.0);
REQUIRE(ApproxEq(a + b, D64x4(3.0, 5.0, 7.0, 9.0), 1e-7));
REQUIRE(ApproxEq(Sqrt(D64x4(4.0, 3.0, 2.0, 1.0)).AsVec(),
Vec4d(4.0, 3.0, 2.0, 1.0).Map(
[](double x) { return Sqrt(x); }),
1e-5));
}
#endif
SECTION("Quaternion")
{
REQUIRE(ApproxEq(Apply(Quaterniond::Rotate(Vec3d(0.0, 0.0, 1.0),
PI<Radd> / 2.0),
Vec3d(1.0, 0.0, 0.0)),
Vec3d(0.0, 1.0, 0.0), 1e-5));
}
SECTION("FP")
{
REQUIRE(ApproxEq(Float(2.0f), Float(1.0f + 1.0f)));
REQUIRE(ApproxEq(Float(1.0f), Float(0.1f * 10.0f)));
REQUIRE(!ApproxEq(Float(1.0f), Float(0.11f * 10.0f)));
}
SECTION("Vec")
{
{
Vec<2, float> v(1.0f, 2.0f);
static_assert(Vec<2, float>::Dim == 2);
REQUIRE((v[0] == 1.0f && v[1] == 2.0f));
}
{
Vec<10, float> v(5.0f);
REQUIRE((v[3] == v[5] && v[5] == v[7] && v[7] == 5.0f));
}
REQUIRE(Vec<3, float>(5.0f) == Vec<3, float>(5.0f));
REQUIRE(Vec<3, float>(5.0f) != Vec<3, float>(4.0f));
REQUIRE(Vec<3, int>(5).Product() == 125);
REQUIRE(Vec<3, int>(4).EachElemLessThan(Vec<3, int>(5)));
REQUIRE(!Vec<3, int>(4, 5, 6).EachElemLessThan(Vec<3, int>(6)));
REQUIRE(Vec<2, int>(1, 2) != Vec<2, int>(3, 4));
}
SECTION("Mat3")
{
ApproxEq(RM_Mat3d(1.0, 3.0, 5.0,
7.0, 9.0, 11.0,
2.0, 4.0, 6.0)
.Determinant(),
0.0, 1e-5);
ApproxEq(RM_Mat3d(1.0, 3.0, 5.0,
8.0, 9.0, 10.0,
4.0, 6.0, 1.0)
.Determinant(),
105.0, 1e-5);
}
SECTION("Permute")
{
std::vector<int> data = {
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11, 12
};
Vec<3, int> newShape;
Permute<3>(data.data(), { 2, 2, 3 }, { 2, 0, 1 }, &newShape);
REQUIRE(data == std::vector<int>{
1, 4,
7, 10,
2, 5,
8, 11,
3, 6,
9, 12
});
REQUIRE(newShape == Vec<3, int>(3, 2, 2));
}
}
| 34.382114 | 102 | 0.461693 | [
"vector",
"transform"
] |
0d688d23cddda9f4bac6e477cb3171d6fa5b94c0 | 680 | cpp | C++ | 327.count-of-range-sum.cpp | bsmsnd/LeetCode-CharlieChen | db72f0a3463c9e723aac800cdbe38218b36aa639 | [
"MIT"
] | null | null | null | 327.count-of-range-sum.cpp | bsmsnd/LeetCode-CharlieChen | db72f0a3463c9e723aac800cdbe38218b36aa639 | [
"MIT"
] | null | null | null | 327.count-of-range-sum.cpp | bsmsnd/LeetCode-CharlieChen | db72f0a3463c9e723aac800cdbe38218b36aa639 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=327 lang=cpp
*
* [327] Count of Range Sum
*/
class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
multiset<long long> sums;
int size = nums.size();
sums.insert(0);
int ans = 0;
long long sum = 0;
for (int i = 0;i<size;i++)
{
sum += nums[i];
// Note that lower_bound(v) gives the value that is less or equal to v, while upper_bound(v) gives the value that is greater than v
ans += distance(sums.lower_bound(sum - upper), sums.upper_bound(sum - lower));
sums.insert(sum);
}
return ans;
}
};
| 27.2 | 143 | 0.55 | [
"vector"
] |
0d6b57c3c7e3d93dc9d1f6d2831913e08adb1409 | 4,904 | cpp | C++ | TAO/orbsvcs/examples/Notify/Lanes/Supplier.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/examples/Notify/Lanes/Supplier.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/examples/Notify/Lanes/Supplier.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: Supplier.cpp 91672 2010-09-08 18:44:58Z johnnyw $
#include "Supplier.h"
#include "tao/ORB_Core.h"
TAO_Notify_Lanes_Supplier::TAO_Notify_Lanes_Supplier (TAO_Notify_ORB_Objects& orb_objects)
: orb_objects_ (orb_objects)
, proxy_consumer_id_ (0)
, expected_consumer_count_ (2)
, consumers_connected_ (lock_)
, consumer_count_ (0)
{
}
TAO_Notify_Lanes_Supplier::~TAO_Notify_Lanes_Supplier ()
{
}
void
TAO_Notify_Lanes_Supplier::init (CosNotifyChannelAdmin::SupplierAdmin_var& admin, int expected_consumer_count)
{
// First initialize the class members.
this->admin_ = admin;
this->expected_consumer_count_ = expected_consumer_count;
this->connect ();
}
void
TAO_Notify_Lanes_Supplier::run (void)
{
// The Priority at which we send the first event to the first consumer.
RTCORBA::Priority priority = 1;
{
ACE_GUARD (TAO_SYNCH_MUTEX, mon, this->lock_);
ACE_DEBUG ((LM_DEBUG, "(%P, %t) Waiting for %d consumers to connect...\n", this->expected_consumer_count_));
// Wait till the consumers are ready to go.
while (this->consumer_count_ != this->expected_consumer_count_)
this->consumers_connected_.wait ();
}
// Send an event each to each consumer.
// Each Consumer expects a different priority.
for (int i = 0; i < this->expected_consumer_count_; ++i, ++priority)
{
// Set this threads priority.
this->orb_objects_.current_->the_priority (priority);
// Make sure the priority was set, get the priority of the current thread.
RTCORBA::Priority thread_priority =
this->orb_objects_.current_->the_priority ();
// We will send this event.
CosNotification::StructuredEvent event;
// Populate the Priority field so that the consumer can deduce the suppliers priority
// to do a sanity check when it receives the event.
CosNotification::PropertySeq& opt = event.header.variable_header;
opt.length (1);
CORBA::Any buffer;
buffer <<= (CORBA::Short) thread_priority;
opt[0].name = CORBA::string_dup (CosNotification::Priority);
opt[0].value = buffer;
// Set the domain and type nams in the event's fixed header.
char type[BUFSIZ];
ACE_OS::sprintf (type, "TEST_TYPE_%d", thread_priority);
event.header.fixed_header.event_type.domain_name = CORBA::string_dup("TEST_DOMAIN");
event.header.fixed_header.event_type.type_name = CORBA::string_dup(type);
ACE_DEBUG ((LM_DEBUG,
"(%P, %t) Supplier is sending an event of type %s at priority %d\n", type, thread_priority));
// send the event
this->send_event (event);
} // repeat for the next consumer at the next priority.
// Disconnect from the EC
this->disconnect ();
// Deactivate this object.
this->deactivate ();
// we're done. shutdown the ORB to exit the process.
this->orb_objects_.orb_->shutdown (1);
}
void
TAO_Notify_Lanes_Supplier::connect (void)
{
// Activate the supplier object.
CosNotifyComm::StructuredPushSupplier_var objref = this->_this ();
// Obtain the proxy.
CosNotifyChannelAdmin::ProxyConsumer_var proxyconsumer =
this->admin_->obtain_notification_push_consumer (CosNotifyChannelAdmin::STRUCTURED_EVENT
, proxy_consumer_id_);
ACE_ASSERT (!CORBA::is_nil (proxyconsumer.in ()));
// narrow
this->proxy_consumer_ =
CosNotifyChannelAdmin::StructuredProxyPushConsumer::_narrow (proxyconsumer.in ());
ACE_ASSERT (!CORBA::is_nil (proxy_consumer_.in ()));
// connect to the proxyconsumer.
proxy_consumer_->connect_structured_push_supplier (objref.in ());
}
void
TAO_Notify_Lanes_Supplier::disconnect (void)
{
ACE_ASSERT (!CORBA::is_nil (this->proxy_consumer_.in ()));
this->proxy_consumer_->disconnect_structured_push_consumer();
}
void
TAO_Notify_Lanes_Supplier::deactivate (void)
{
PortableServer::POA_var poa (this->_default_POA ());
PortableServer::ObjectId_var id (poa->servant_to_id (this));
poa->deactivate_object (id.in());
}
void
TAO_Notify_Lanes_Supplier::subscription_change (const CosNotification::EventTypeSeq & added,
const CosNotification::EventTypeSeq & /*removed */
)
{
ACE_GUARD (TAO_SYNCH_MUTEX, mon, this->lock_);
// Count the number of consumers connect and signal the supplier thread when the expected count have connected.
if (added.length () > 0)
{
if (++this->consumer_count_ == this->expected_consumer_count_)
this->consumers_connected_.signal ();
}
}
void
TAO_Notify_Lanes_Supplier::send_event (const CosNotification::StructuredEvent& event)
{
ACE_ASSERT (!CORBA::is_nil (this->proxy_consumer_.in ()));
proxy_consumer_->push_structured_event (event);
}
void
TAO_Notify_Lanes_Supplier::disconnect_structured_push_supplier (void)
{
this->deactivate ();
}
| 29.542169 | 113 | 0.699837 | [
"object"
] |
0d6e67957443f721a4b9267b8a1617f5e1c7af65 | 525 | hh | C++ | src/BGL/BGLCommon.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 17 | 2015-01-07T10:32:06.000Z | 2021-07-06T11:00:38.000Z | src/BGL/BGLCommon.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2017-08-17T17:44:42.000Z | 2018-06-14T23:39:04.000Z | src/BGL/BGLCommon.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2015-01-07T10:32:06.000Z | 2019-03-22T16:56:51.000Z | //
// BGLCommon.hh
// Part of the Belfry Geometry Library
//
// Created by GM on 10/13/10.
// Copyright 2010 Belfry Software. All rights reserved.
//
#ifndef BGL_COMMON_H
#define BGL_COMMON_H
namespace BGL {
extern double EPSILON;
extern double CLOSEENOUGH;
typedef enum {
USED = 0,
OUTSIDE = 1,
INSIDE = 2,
SHARED = 4,
UNSHARED = 8
} Relation;
typedef enum {
VALID = 0,
INVALID = 1,
CONSECUTIVELY_INVALID = 2
} Validity;
}
#endif
// vim: set ts=4 sw=4 nowrap expandtab: settings
| 14.189189 | 56 | 0.655238 | [
"geometry"
] |
0d7f8e546b299f6d9d389a5b2c9bfe266ce9dd8a | 687 | hpp | C++ | week3-exercise3/drawable.hpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | week3-exercise3/drawable.hpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | week3-exercise3/drawable.hpp | jakah/hu-v1oopc-exercises | 74d830fa150525705306bcb59652cc9baa991985 | [
"MIT"
] | null | null | null | #ifndef DRAWABLE_HPP
#define DRAWABLE_HPP
#include <ostream>
#include "window.hpp"
#include "vector.hpp"
class drawable {
protected:
window w;
vector location;
vector size;
vector bounce;
public:
drawable( window & w, const vector & location, const vector & size, const vector & bounce = vector(1,1) );
bool overlaps( const drawable & other );
virtual void draw() = 0;
virtual void update(){}
virtual void interact( drawable & other ){}
void set_bounce(const vector &value);
vector get_bounce();
std::ostream & print( std::ostream & out ) const;
};
std::ostream & operator<<( std::ostream & lhs, const drawable & rhs );
#endif // DRAWABLE_HPP
| 24.535714 | 113 | 0.676856 | [
"vector"
] |
0d80e66121ef1bf5c2f2fc4732540ffdc5a98a73 | 12,427 | cc | C++ | src/board.cc | hiro-dot-exe/gunjin-shogi | 0dd2302c6a325333e7c5aaa498ef0a30502f1d04 | [
"MIT"
] | null | null | null | src/board.cc | hiro-dot-exe/gunjin-shogi | 0dd2302c6a325333e7c5aaa498ef0a30502f1d04 | [
"MIT"
] | null | null | null | src/board.cc | hiro-dot-exe/gunjin-shogi | 0dd2302c6a325333e7c5aaa498ef0a30502f1d04 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2016 @hirodotexe. All rights reserved.
//-----------------------------------------------------------------------------
// Information on this class is described in "board.h".
//-----------------------------------------------------------------------------
#include "board.h"
#include <cmath>
#include <cassert>
const Point Board::kEntrances[kNumEntrances] = {
{3, 1}, {3, 4}, {4, 1}, {4, 4}};
const Point Board::kHeadquarters[kNumPlayers][2] = {
{{0, kWidth / 2 - 1}, {0, kWidth / 2}},
{{kHeight - 1, kWidth / 2 - 1}, {kHeight - 1, kWidth / 2}}};
const int Board::kNumEachPiece[Piece::kNumKindPieces] = {
1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 1};
const Board::BattleResult Board::kBattleTable
[Piece::kNumKindPieces - 1][Piece::kNumKindPieces - 1] = {
{kD, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kL, kL},
{kL, kD, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kD, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kD, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW, kW},
{kL, kL, kL, kL, kD, kW, kW, kW, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kD, kW, kW, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kD, kW, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kL, kD, kW, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kL, kL, kD, kW, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kL, kL, kL, kD, kW, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kD, kW, kW, kW, kL},
{kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kD, kL, kW, kW},
{kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kW, kD, kW, kL},
{kW, kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kL, kD, kL},
{kW, kW, kW, kL, kW, kW, kW, kW, kW, kW, kW, kL, kW, kW, kD}};
void Board::Initialize() {
// Sequence pieces.
int count_each_piece[Piece::kNumKindPieces]; // For mapping.
for (int y = 0; y < kHeight; ++y) {
// Initialize map.
if (y % (kHeight / 2) == 0)
memset(count_each_piece, 0, sizeof(count_each_piece));
for (int x = 0; x < kWidth; ++x) {
// Create a piece randomly.
Piece piece;
piece.characters_id = y / (kHeight / 2);
piece.supposition = Piece::kNone;
// Set a kind of the piece.
bool y_is_in_range = (y == 0 || y == kHeight - 1);
bool x_is_in_range = (x == kWidth / 2);
bool is_dummy_headquarters = (y_is_in_range && x_is_in_range);
if (is_dummy_headquarters) {
piece.piece = Piece::kDummyHeadquarters;
} else {
// Create a random kind of piece.
do {
piece.piece = static_cast<Piece::KindPiece>(
rand() % Piece::kNumKindPieces);
} while (kNumEachPiece[piece.piece] <=
count_each_piece[piece.piece]);
++count_each_piece[piece.piece];
}
// Place the piece.
board_[y][x] = piece;
}
}
// If the board is invalid.
for (int id = 0; id < kNumPlayers; ++id) {
std::vector<Point> error;
while (!IsValid(id, &error)) {
for (int i = 0; i < static_cast<int>(error.size()); ++i) {
Move move;
move.src = error[i];
DeterminePointRandomly(id, &move.dest);
Swap(move);
}
}
}
}
void Board::Battle(const Move &move) {
const Piece kSrcPiece = board(move.src);
const Piece kDestPiece = board(move.dest);
// Log.
add_log(move);
// Check which piece is stronger.
BattleResult result = kW;
switch (kDestPiece.piece) {
// If the strong of the piece is depend on one at the back of.
case Piece::kFlag: {
// Check a piece at the back of the flag.
bool back_flag_is_existed = false;
Piece back_flag;
if (kDestPiece.characters_id == 0 && 0 < move.dest.y) {
back_flag = board({move.dest.y - 1, move.dest.x});
back_flag_is_existed = true;
} else if (kDestPiece.characters_id == 1 && move.dest.y < kHeight - 1) {
back_flag = board({move.dest.y + 1, move.dest.x});
back_flag_is_existed = true;
}
// Check the result of the battle.
if (back_flag_is_existed && back_flag.IsPiece() &&
back_flag.characters_id == kDestPiece.characters_id) {
result = kBattleTable[kSrcPiece.piece][back_flag.piece];
if (back_flag.piece == Piece::kMine)
Delete(move.dest);
}
break;
}
case Piece::kNone: {
result = kW;
break;
}
default: {
result = kBattleTable[kSrcPiece.piece][kDestPiece.piece];
break;
}
}
// Delete pieces.
Delete(move.src);
switch (result) {
case kL: if (kDestPiece.piece == Piece::kMine) Delete(move.dest); break;
case kW: set_board(kSrcPiece, move.dest); break;
case kD: Delete(move.dest); break;
default: assert(true);
}
}
bool Board::IsValid(int characters_id, std::vector<Point> *error) const {
bool is_available = true;
// Check whether both mines and a flag aren't placed at entrances.
int first_entrance = (characters_id == 0) ? 0 : kNumEntrances / 2;
int last_entrance = (characters_id == 0) ? kNumEntrances / 2 : kNumEntrances;
for (int i = first_entrance; i < last_entrance; ++i) {
Piece piece = board(kEntrances[i]);
if (piece.IsNotMovable()) {
error->push_back(kEntrances[i]);
is_available = false;
}
}
// NOTE: A rule is unclearly about one below.
// Check whether a mine is placed at headquarters.
//Point headquarters;
//headquarters.y = (characters_id == 0) ? 0 : kHeight - 1;
//headquarters.x = kWidth / 2;
//if (Piece::kMine == board(headquarters).piece) {
// error->push_back(headquarters);
// is_available = false;
//}
return is_available;
}
bool Board::IsMoveValid(const Move &move) const {
const Piece kSrcPiece = board(move.src);
const Piece kDestPiece = board(move.dest);
// Check whether the piece at source is movable.
if (!kSrcPiece.IsMovable())
return false;
// Check whether pieces at destination and source
// belong to same characters.
if (kSrcPiece.characters_id == kDestPiece.characters_id &&
kDestPiece.IsPiece()) {
return false;
}
// Calculate differencial vector.
Point difference = move.dest.Subtract(move.src);
// If a board was rotated 180 degrees.
if (kSrcPiece.characters_id == 0)
difference = difference.Inverse();
// If the piece moves diagonally or doesn't move.
if ((difference.y != 0 && difference.x != 0) ||
(difference.y == 0 && difference.x == 0)) {
return false;
}
bool piece_hits_obstacle = IsPieceHittingObstacle(move);
bool y_is_in_range = (abs(difference.y) == 1);
bool x_is_in_range = (abs(difference.x) == 1);
switch (kSrcPiece.piece) {
case Piece::kTank: // front:2, others:1
case Piece::kCavaly:
y_is_in_range |= (difference.y == -2);
return ((y_is_in_range && !piece_hits_obstacle) || x_is_in_range);
case Piece::kEngineer: // all:*
return (!piece_hits_obstacle);
break;
case Piece::kPlane: // front&back:*, others:1
y_is_in_range = (difference.y != 0);
return (y_is_in_range || x_is_in_range);
default: // all:1
return ((y_is_in_range && !piece_hits_obstacle) || x_is_in_range);
}
}
bool Board::IsEnd(int *winners_id, bool *game_was_drawn) const {
// Check which character win.
*game_was_drawn = false;
bool winners_id_is_initialized = true;
for (int id = 0; id < kNumPlayers; ++id) {
int opponents_id = 1 - id;
// If opponent's piece is ranked between shosa ~ taisho, end the game.
Piece headquarters = board(kHeadquarters[id][0]);
if (headquarters.characters_id == opponents_id &&
(headquarters.IsShokan() || headquarters.IsSakan())) {
*winners_id = opponents_id;
return true;
}
// Check whether there is no piece which can be moved.
bool has_no_movable_piece = true;
Point p;
for (p.y = 0; p.y < kHeight && has_no_movable_piece; ++p.y) {
for (p.x = 0; p.x < kWidth && has_no_movable_piece; ++p.x) {
Piece piece = board(p);
if (piece.characters_id == id && piece.IsMovable())
has_no_movable_piece = false;
}
}
if (has_no_movable_piece) {
if (winners_id_is_initialized) {
*winners_id = opponents_id;
winners_id_is_initialized = false;
} else {
*game_was_drawn = true;
return true;
}
}
}
if (!winners_id_is_initialized)
return true;
return false;
}
bool Board::IsPieceHittingObstacle(const Move &move) const {
const Point kDifference = move.dest.Subtract(move.src);
Point current = move.src;
int prev_y = move.src.y;
do {
// Move a piece.
if (kDifference.y != 0)
current.y += abs(kDifference.y) / kDifference.y;
else
current.x += abs(kDifference.x) / kDifference.x;
// If there is a piece.
if (board(current).piece != Piece::kNone && !current.Equals(move.dest))
return true;
// If there is wall.
double average_y = 0.5 * (current.y + prev_y);
if (average_y == 0.5 * (kHeight - 1) &&
current.x != 1 && current.x != kWidth - 1 - 1) {
return true;
}
prev_y = current.y;
} while (!current.Equals(move.dest));
return false;
}
int Board::CountNumPieces(int characters_id) const {
// Count the number of player's pieces.
int num_pieces = 0;
Point p;
for (p.y = 0; p.y < kHeight; ++p.y) {
for (p.x = 0; p.x < kWidth; ++p.x) {
Piece piece = board(p);
if (piece.characters_id == characters_id && piece.IsPiece())
++num_pieces;
}
}
return num_pieces;
}
int Board::CountNumPlaceableSquares(const Point &src) const {
Move move;
move.src = src;
// Count the number of placeable squares.
int num_placeable_squares = 0;
for (move.dest.y = 0; move.dest.y < kHeight; ++move.dest.y) {
for (move.dest.x = 0; move.dest.x < kWidth; ++move.dest.x) {
bool is_current_piece_not_dummy_headquarters =
(board(move.dest).piece != Piece::kDummyHeadquarters);
if (is_current_piece_not_dummy_headquarters && IsMoveValid(move))
++num_placeable_squares;
}
}
return num_placeable_squares;
}
void Board::DeterminePointRandomly(int id, Point *point) const {
point->y = rand() % (Board::kHeight / 2);
point->y += (id == 1) ? Board::kHeight / 2 : 0;
point->x = rand() % Board::kWidth;
}
void Board::SupposeBattle(int supposer_id, const Move &move) {
const Piece kSrcPiece = board(move.src);
const Piece kDestPiece = board(move.dest);
const Piece::KindPiece kSrcKindPiece =
(kSrcPiece.characters_id == supposer_id) ?
kSrcPiece.piece : kSrcPiece.supposition;
const Piece::KindPiece kDestKindPiece =
(kDestPiece.characters_id == supposer_id) ?
kDestPiece.piece : kDestPiece.supposition;
// Log.
add_log(move);
// Check which piece is stronger.
BattleResult result = kW;
switch (kDestKindPiece) {
case Piece::kNone:
result = kW;
break;
default:
result = kBattleTable[kSrcKindPiece][kDestKindPiece];
break;
}
// Delete pieces.
Delete(move.src);
switch (result) {
case kL: break;
case kW: set_board(kSrcPiece, move.dest); break;
case kD: Delete(move.dest); break;
default: assert(true);
}
}
int Board::MeasureDistanceToHeadquartersOf(int id, const Point &p) {
// Measure distance to headquarters of id.
// Determine the shortest distance as.
int shorter_distance_to_headquarters = INT_MAX;
for (int i = 0; i < 2; ++i) {
Point difference = kHeadquarters[id][i].Subtract(p);
int distance_to_headquarters = abs(difference.y) + abs(difference.x);
if (distance_to_headquarters < shorter_distance_to_headquarters)
shorter_distance_to_headquarters = distance_to_headquarters;
}
// Add distance to through an entrance.
bool must_add_distance_y = (id != p.y / (kHeight / 2));
bool must_add_distance_x = (p.x == kWidth / 2 - 1 || p.x == kWidth / 2);
if (must_add_distance_y && must_add_distance_x)
shorter_distance_to_headquarters += 2;
return shorter_distance_to_headquarters;
} | 33.495957 | 80 | 0.592017 | [
"vector"
] |
0d84793a50214c21ea8e1b20177ae57be285e0b9 | 1,496 | hpp | C++ | Source/Entity.hpp | LepusM42/OrionEngine | b8c43d0d8473c19b840cc60cf1b6cc8bc9cbe37b | [
"MIT"
] | null | null | null | Source/Entity.hpp | LepusM42/OrionEngine | b8c43d0d8473c19b840cc60cf1b6cc8bc9cbe37b | [
"MIT"
] | 11 | 2021-04-28T23:48:00.000Z | 2021-12-28T06:33:28.000Z | Source/Entity.hpp | LepusM42/OrionEngine | b8c43d0d8473c19b840cc60cf1b6cc8bc9cbe37b | [
"MIT"
] | null | null | null | /*!*****************************************************************************
* \file Entity.hpp
* \author Lepus
* \brief This is a stub file, used as a template for all other files.
*******************************************************************************/
#pragma once
#include <vector>
#include <string>
namespace Orion
{
class Component;
/*!*************************************************************************
* \class Entity
* \brief Used to represent an object in gamespace. Structurally, it's little
* more than an aggregation of one or more Components.
***************************************************************************/
class Entity
{
public:
//! Does nothing.
template <typename ComponentType>
ComponentType* Get()
{
for (Component* comp : m_components)
{
if (ComponentType* cast = dynamic_cast<ComponentType*>(comp))
{
return cast;
}
}
return nullptr;
}
//! Does nothing.
void Add(Component* component);
//! Does nothing.
void Start();
//! Does nothing.
void Update(float dt);
//! Does nothing.
void Stop();
//! Mark for destruction
void Destroy();
//! Mark for destruction
bool MarkedForDestruction();
//! Remove all components
void ClearComponents();
//! Name of the object
std::string m_name;
private:
//! Map of all components, accessed using each component's unique ID.
std::vector<Component*> m_components;
//! Used by manager to delete
bool m_marked{ false };
};
} | 27.2 | 80 | 0.530749 | [
"object",
"vector"
] |
0d896d42e19b9327a81377a2481318a1dd61ac65 | 3,163 | cpp | C++ | system/zombie/pogo.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2022-03-29T23:49:55.000Z | 2022-03-29T23:49:55.000Z | system/zombie/pogo.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 2 | 2021-03-10T18:17:07.000Z | 2021-05-11T13:59:22.000Z | system/zombie/pogo.cpp | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2021-10-18T18:29:47.000Z | 2021-10-18T18:29:47.000Z | #include "zombie.h"
#include "system/util.h"
namespace pvz_emulator::system {
using namespace pvz_emulator::object;
void zombie_pogo::remove_stick(zombie& z) {
if (!z.has_item_or_walk_left) {
return;
}
z.action = zombie_action::falling;
z.status = zombie_status::walking;
reanim.update_status(z);
z.hit_box.x = 36;
z.hit_box.y = 17;
z.hit_box.width = 42;
z.hit_box.height = 115;
z.attack_box.x = 20;
z.attack_box.y = 17;
z.attack_box.width = 50;
z.attack_box.height = 115;
z.accessory_2.type = zombie_accessories_type_2::none;
z.accessory_2.hp = 0;
z.has_item_or_walk_left = false;
}
void zombie_pogo::update(object::zombie& z) {
if (z.is_dead ||
z.has_death_status() ||
z.countdown.freeze > 0 ||
z.countdown.butter > 0 ||
z.status < zombie_status::pogo_with_stick ||
static_cast<int>(z.status) > 28 ||
static_cast<int>(z.action) == 8)
{
return;
}
int b = 40;
if (z.status < zombie_status::pogo_idle_before_target ||
static_cast<int>(z.status) > 26)
{
if (z.status == zombie_status::pogo_jump_across) {
b = 90;
} else if (static_cast<int>(z.status) == 28) {
b = 170;
}
} else {
b = (static_cast<int>(z.status) -
static_cast<int>(zombie_status::pogo_idle_before_target)) * 20 + 50;
}
float dy = 1 - fabs(1.0f - 2.0f * ((80.0f - z.countdown.action) / 80.0f));
dy = 2 * dy - dy * dy;
dy = b * dy + 9;
z.dy = dy;
if (z.countdown.action == 7) {
z.reanim.progress = 0;
z.reanim.type = reanim_type::once;
}
if (z.status == zombie_status::pogo_jump_across &&
z.countdown.action == 70)
{
auto target = find_target(z, zombie_attack_type::jump);
if (target && target->type == plant_type::tallnut) {
remove_stick(z);
return;
}
}
if (z.countdown.action == 0) {
if (auto target = find_target(z, zombie_attack_type::jump)) {
if (z.status == zombie_status::pogo_idle_before_target) {
z.status = zombie_status::pogo_jump_across;
z.countdown.action = 80;
z.dx = (z.int_x - z.x + 60) / 80;
} else {
z.status = zombie_status::pogo_idle_before_target;
z.dx = 0;
z.countdown.action = 80;
}
} else {
z.status = zombie_status::pogo_with_stick;
reanim.update_dx(z);
z.countdown.action = 80;
}
}
}
void zombie_pogo::init(zombie &z, unsigned int row) {
z._ground = _ground.data();
zombie_base::init(z, zombie_type::pogo, row);
z.hp = 500;
z.status = zombie_status::pogo_with_stick;
z.countdown.action = rng.randint(80) + 1;
z.attack_box.x = 10;
z.attack_box.y = 0;
z.attack_box.width = 30;
z.attack_box.height = 115;
z.has_item_or_walk_left = true;
reanim.set(z, zombie_reanim_name::anim_pogo, reanim_type::once, 40);
z.reanim.progress = 1;
set_common_fields(z);
}
}
| 25.103175 | 80 | 0.564338 | [
"object"
] |
0d8dbe10f6aaac420f5e7afad32d8127f266332d | 13,147 | cpp | C++ | ColliderBit/src/analyses/Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-09-17T22:53:26.000Z | 2021-09-17T22:53:26.000Z | ColliderBit/src/analyses/Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 3 | 2021-07-22T11:23:48.000Z | 2021-08-22T17:24:41.000Z | ColliderBit/src/analyses/Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-08-14T10:31:41.000Z | 2021-08-14T10:31:41.000Z | //
// Created by dsteiner on 31/07/18.
// Amended by Martin White on 08/03/19.
//
// Based on https://atlas.web.cern.ch/Atlas/GROUPS/PHYSICS/PAPERS/SUSY-2012-10/ (arXiv:1209.2102)
//#include <gambit/ColliderBit/colliders/SpecializablePythia.hpp>
#include "gambit/ColliderBit/analyses/Analysis.hpp"
#include "gambit/ColliderBit/analyses/Cutflow.hpp"
#include <gambit/ColliderBit/ATLASEfficiencies.hpp>
#include "gambit/ColliderBit/analyses/AnalysisUtil.hpp"
namespace Gambit {
namespace ColliderBit {
using namespace std;
using namespace HEPUtils;
class Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb : public Analysis {
public:
// Required detector sim
static constexpr const char* detector = "ATLAS";
#define CUTFLOWMAP(X) \
X(Total_events) \
X(electron_eq_4_jets) \
X(electron_met_gt_40) \
X(electron_eq_2_bjets) \
X(electron_sr) \
X(muon_eq_4_jets) \
X(muon_met_gt_40) \
X(muon_eq_2_bjets) \
X(muon_sr) \
X(twoLep_met_gt_40) \
X(twoLep_gt_1_bjet) \
X(mll_lt_81) \
X(mll_gt_30_lt_81) \
X(num_2lsr1) \
X(num_2lsr2)
#define f(x) x,
#define g(x) #x,
const std::vector<std::string> cutflowNames = {CUTFLOWMAP(g)};
enum cutflowEnum {CUTFLOWMAP(f)};
#undef g
#undef f
#undef CUTFLOWMAP
#define VARMAP(X) \
X(mTopHad) \
X(oneLepSqrtS) \
X(mllKey) \
X(twoLepSqrtS)
#define f(x) x,
#define g(x) #x,
const std::vector<std::string> varNames = {VARMAP(g)};
enum varEnum {VARMAP(f)};
#undef g
#undef f
#undef VARMAP
std::map<std::string, std::vector<double>> varResults;
std::map<std::string, int> cutflows;
double num1LSR=0;
double num2LSR1=0;
double num2LSR2=0;
std::vector<double> calcNuPz(double Mw, P4 metMom, P4 lepMom)
{
double mu = sqr(Mw) / 2.0 + metMom.px() * lepMom.px() + metMom.py() * lepMom.py();
double denom = lepMom.E2() - lepMom.pz2();
double a = mu * lepMom.pz() / denom;
double a2 = sqr(a);
double b = (lepMom.E2() * metMom.E2() - sqr(mu)) / denom;
double delta = a2 - b;
if (delta < 0)
{
return {a};
}
else
{
return {a + std::sqrt(delta), a - std::sqrt(delta)};
}
}
P4 getBestHadronicTop(
std::vector<const Jet *> bJets,
std::vector<const Jet *> lightJets,
const P4& leptonMom,
const P4& metMom,
double width,
double mean
)
{
// gaussian probability density function
auto prob = [&width, &mean](P4 particle) {
return 1 - std::erf(1.0 * std::abs(particle.m() - mean) / (std::sqrt(2.0) * width));
};
double pTotal = 0.0;
P4 bestHadronicTop;
std::vector<double> nuPzChoices = calcNuPz(80.0, metMom, leptonMom);
P4 nu;
for (double nuPz : nuPzChoices)
{
double nuE = std::sqrt(sqr(metMom.px()) + sqr(metMom.py()) + sqr(nuPz));
nu.setPE(metMom.px(), metMom.py(), nuPz, nuE);
P4 WLep = leptonMom + nu;
// go through every bJet
for (const Jet* firstBJet : bJets)
{
for (const Jet* secondBJet : bJets)
{
if (firstBJet == secondBJet)
{
continue;
}
P4 topLep = *firstBJet + WLep;
// go through every combination of two light jets
for (const Jet* firstLightJet : lightJets)
{
for (const Jet* secondLightJet : lightJets)
{
// don't want to use a light jet with itself
if (firstLightJet == secondLightJet)
{
continue;
}
P4 WHad = *firstLightJet + *secondLightJet;
P4 topHad = *secondBJet + WHad;
// calculate a new probability
double newPTotal = prob(topHad) * prob(WHad) * prob(topLep) * prob(WLep);
if (newPTotal > pTotal)
{
// update the best values
pTotal = newPTotal;
bestHadronicTop = topHad;
}
}
}
}
}
}
return bestHadronicTop;
}
double calcMt(P4 metVec, P4 lepVec)
{
double Met = metVec.pT();
double pTLep = lepVec.pT();
return std::sqrt(2 * pTLep * Met - 2 * AnalysisUtil::dot2D(lepVec, metVec));
}
double calcSqrtSSubMin(P4 visibleSubsystem, P4 invisbleSubsystem)
{
double visiblePart = std::sqrt(sqr(visibleSubsystem.m()) + sqr(visibleSubsystem.pT()));
double invisiblePart = invisbleSubsystem.pT();
double twoDimensionalVecSum =
sqr(visibleSubsystem.px() + invisbleSubsystem.px())
+ sqr(visibleSubsystem.py() + invisbleSubsystem.py());
return std::sqrt(sqr(visiblePart + invisiblePart) - twoDimensionalVecSum);
}
void getBJets(
std::vector<const Jet*>& jets,
std::vector<const Jet*>* bJets,
std::vector<const Jet*>* lightJets)
{
/// @note We assume that b jets have previously been 100% tagged
const std::vector<double> a = {0, 10.};
const std::vector<double> b = {0, 10000.};
const std::vector<double> c = {0.60};
BinnedFn2D<double> _eff2d(a,b,c);
for (const Jet* jet : jets)
{
bool hasTag = has_tag(_eff2d, jet->eta(), jet->pT());
if(jet->btag() && hasTag && jet->abseta() < 2.5)
{
bJets->push_back(jet);
}
else
{
lightJets->push_back(jet);
}
}
}
/**
* The constructor that should initialize some variables
*/
Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb()
{
set_analysis_name("ATLAS_7TeV_1OR2LEPStop_4_7invfb");
set_luminosity(4.7);
}
/**
* Performs the main part of the analysis
* @param event an event contain particle and jet information
*/
void run(const HEPUtils::Event* event)
{
// TODO: take log of plots and constrain the plot range
//HEPUtilsAnalysis::analyze(event);
//cout << "Event number: " << num_events() << endl;
incrementCut(Total_events);
std::vector<const Particle*> electrons = event->electrons();
std::vector<const Particle*> muons = event->muons();
std::vector<const Jet*> jets = event->jets();
electrons = AnalysisUtil::filterPtEta(electrons, 20, 2.47);
muons = AnalysisUtil::filterPtEta(muons, 10, 2.4);
jets = AnalysisUtil::filterPtEta(jets, 20, 4.5);
std::vector<const Jet*> bJets, lightJets;
getBJets(jets, &bJets, &lightJets);
jets = AnalysisUtil::jetLeptonOverlapRemoval(jets, electrons, 0.2);
electrons = AnalysisUtil::leptonJetOverlapRemoval(electrons, jets, 0.4);
muons = AnalysisUtil::leptonJetOverlapRemoval(muons, jets, 0.4);
jets = AnalysisUtil::filterMaxEta(jets, 2.5);
ATLAS::applyTightIDElectronSelection(electrons);
std::vector<const Particle*> leptons = AnalysisUtil::getSortedLeptons({electrons, muons});
std::sort(electrons.begin(), electrons.end(), AnalysisUtil::sortParticlesByPt);
std::sort(muons.begin(), muons.end(), AnalysisUtil::sortParticlesByPt);
std::sort(jets.begin(), jets.end(), AnalysisUtil::sortJetsByPt);
std::sort(bJets.begin(), bJets.end(), AnalysisUtil::sortJetsByPt);
std::sort(lightJets.begin(), lightJets.end(), AnalysisUtil::sortJetsByPt);
size_t
nLeptons = leptons.size(),
nJets = jets.size(),
nBJets = bJets.size(),
nLightJets = lightJets.size();
double Met = event->met();
const P4& metVec = event->missingmom();
if (nLeptons == 1)
{
if (!AnalysisUtil::muonFilter7TeV(muons) && muons.size() == 1)
{
return;
}
cutflowEnum a, b, c;
if (electrons.size() == 1) a = electron_eq_4_jets, b = electron_met_gt_40, c = electron_eq_2_bjets;
if (muons.size() == 1) a = muon_eq_4_jets, b = muon_met_gt_40, c = muon_eq_2_bjets;
if (nJets == 4)
{
incrementCut(a);
{
if (Met > 40)
{
incrementCut(b);
if (nBJets == 2)
{
incrementCut(c);
}
}
}
}
}
// minimal selection requirements for single lepton
if (nLeptons == 1 && nBJets >= 2 && nLightJets >= 2 && Met > 40)
{
double mT = calcMt(metVec, leptons[0]->mom());
auto isValidTop = [](double mean, double width, double mass) {return mass < mean - 0.5 * width;};
if (mT > 30)
{
double mean = 0.0, width = 0.0;
P4 hadronicTop;
P4 visibleSubsystem = *leptons[0] + *lightJets[0] + *lightJets[1] + *bJets[0] + *bJets[1];
double sqrtSsubMin = calcSqrtSSubMin(visibleSubsystem, metVec);
bool isOneLep = false;
// e-channel
if (electrons.size() == 1 && electrons[0]->pT() > 25)
{
mean = 168.4, width = 18.0;
hadronicTop = getBestHadronicTop(bJets, lightJets, *electrons[0], metVec, width, mean);
isOneLep = true;
}
// mu-channel
if (muons.size() == 1 && muons[0]->pT() > 20)
{
mean = 168.2, width = 18.6;
hadronicTop = getBestHadronicTop(bJets, lightJets, *muons[0], metVec, width, mean);
isOneLep = true;
}
bool validTop = isValidTop(mean, width, hadronicTop.m());
if (isOneLep)
{
varResults[varNames[mTopHad]].push_back(hadronicTop.m());
varResults[varNames[oneLepSqrtS]].push_back(sqrtSsubMin);
}
// check if we are in the 1LSR signal region
if (isOneLep && validTop && sqrtSsubMin < 250)
{
num1LSR += event->weight();
if (electrons.size() == 1) incrementCut(electron_sr);
if (muons.size() == 1) incrementCut(muon_sr);
}
}
}
if (nLeptons == 2 && Met > 40 && AnalysisUtil::oppositeSign(leptons[0], leptons[1]) && nJets >= 2)
{
P4 ll = *leptons[0] + *leptons[1];
double mll = ll.m();
incrementCut(twoLep_met_gt_40);
{
if (nBJets >= 1)
{
incrementCut(twoLep_gt_1_bjet);
if (mll < 81)
{
incrementCut(mll_lt_81);
}
if (mll < 81 && mll > 30)
{
incrementCut(mll_gt_30_lt_81);
}
}
}
}
if (nLeptons == 2 && AnalysisUtil::oppositeSign(leptons[0], leptons[1]) && Met > 40 && nJets >= 2 && nBJets >= 1)
{
P4 ll = *leptons[0] + *leptons[1];
double mll = ll.m();
P4 visibleSubsystem = *leptons[0] + *leptons[1] + *jets[0] + *jets[1];
double sqrtSsubMin = calcSqrtSSubMin(visibleSubsystem, metVec);
double mlljj = visibleSubsystem.m();
varResults[varNames[mllKey]].push_back(mll);
if (mll > 30 && mll < 81)
{
bool isTwoLeptonEvent = false;
// ee channel
if (electrons.size() == 2 && electrons[0]->pT() > 25)
{
isTwoLeptonEvent = true;
}
// mu-mu channel
if (muons.size() == 2 && muons[0]->pT() > 20)
{
isTwoLeptonEvent = true;
}
// e-mu channel
if (electrons.size() == 1 && muons.size() == 1 && (electrons[0]->pT() > 25 || muons[0]->pT() > 20))
{
isTwoLeptonEvent = true;
}
if (isTwoLeptonEvent)
{
varResults[varNames[twoLepSqrtS]].push_back(sqrtSsubMin);
if (sqrtSsubMin < 225)
{
num2LSR1 += event->weight();
incrementCut(num_2lsr1);
}
if (sqrtSsubMin < 235 && mlljj < 140)
{
num2LSR2 += event->weight();
incrementCut(num_2lsr2);
}
}
}
}
}
/**
* Adds results from other threads if OMP_NUM_THREAD != 1
* @param other results from another thread
*/
/// Combine the variables of another copy of this analysis (typically on another thread) into this one.
void combine(const Analysis* other)
{
const Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb* specificOther = dynamic_cast<const Analysis_ATLAS_7TeV_1OR2LEPStop_4_7invfb*>(other);
num1LSR += specificOther->num1LSR;
num2LSR1 += specificOther->num2LSR1;
num2LSR2 += specificOther->num2LSR2;
}
void collect_results()
{
//saveCutFlow();
add_result(SignalRegionData("1LSR", 50, {num1LSR, 0.}, {38., 7.}));
add_result(SignalRegionData("2LSR1", 123, {num2LSR1, 0.}, {115., 15.}));
add_result(SignalRegionData("2LSR2", 47, {num2LSR2, 0.}, {46., 7.}));
//cout << "1LSR: " << num1LSR << ", 2LSR1: " << num2LSR1 << ", 2LSR2: " << num2LSR2 << endl;
/*for (std::pair<std::string, std::vector<double>> entry : varResults)
{
cout << "SAVE_START:" << entry.first << endl;
for (double value : entry.second)
{
cout << value << endl;
}
cout << "SAVE_END" << endl;
}*/
}
protected:
void analysis_specific_reset()
{
num1LSR = 0;
num2LSR1 = 0;
num2LSR2 = 0;
for (std::string varName : varNames)
{
varResults[varName] = {};
}
}
/*void scale(double factor)
{
HEPUtilsAnalysis::scale(factor);
cout << "SAVE_XSEC:" << xsec() << endl;
auto save = [](double value, std::string name)
{
cout << "SAVE_START:" << name << endl;
cout << value << endl;
cout << "SAVE_END" << endl;
};
save(num1LSR, "num1LSR");
save(num2LSR1, "num2LSR1");
save(num2LSR2, "num2LSR2");
}*/
void incrementCut(int cutIndex)
{
cutflows[cutflowNames[cutIndex]]++;
}
void saveCutFlow()
{
double scale_by = 1.0;
cout << "SAVE_START:cuts" << endl;
cout << "CUT;RAW;SCALED;%" << endl;
double initialCut = cutflows[cutflowNames[Total_events]];
double thisCut;
for (std::string name : cutflowNames) {
thisCut = cutflows[name];
cout << name.c_str() << ";"
<< thisCut << ";"
<< thisCut * scale_by << ";"
<< 100. * thisCut / initialCut
<< endl;
}
cout << "SAVE_END" << endl;
}
};
DEFINE_ANALYSIS_FACTORY(ATLAS_7TeV_1OR2LEPStop_4_7invfb)
}
}
| 26.775967 | 135 | 0.609873 | [
"vector"
] |
0d948da8662828a36727ea07b9fb9ec73e217399 | 2,640 | hpp | C++ | AirLib/include/vehicles/plane/UFRotorParams.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | AirLib/include/vehicles/plane/UFRotorParams.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | AirLib/include/vehicles/plane/UFRotorParams.hpp | artemopolus/AirSim-1 | 4a741e79c0197acf3cb6f3397bc55ea1d267f8c8 | [
"MIT"
] | null | null | null | #ifndef msr_airlib_UFRotorParams_hpp
#define msr_airlib_UFRotorParams_hpp
#include "UniForceParams.hpp"
namespace msr {
namespace airlib {
class UFRotorParams : public UniForceParams
{
public:
UFRotorParams()
{
initialize();
}
virtual void calculateMaxThrust() {
revolutions_per_second = max_rpm / 60;
max_speed = revolutions_per_second * 2 * M_PIf; // radians / sec
max_speed_square = pow(max_speed, 2.0f);
real_T nsquared = revolutions_per_second * revolutions_per_second;
max_thrust = C_T * air_density * nsquared * pow(propeller_diameter, 4);
max_torque = C_P * air_density * nsquared * pow(propeller_diameter, 5) / (2 * M_PIf);
}
virtual void calculateMaxThrust( real_T value) {
max_rpm = value;
calculateMaxThrust();
}
virtual void calculateMaxThrust( real_T datamass[] ) {
max_rpm = datamass[0];
air_density = datamass[2];
calculateMaxThrust();
}
virtual void calculateMaxThrust( std::vector<float>( datamass) )
{
if (datamass.size() != 6)
return;
max_rpm = datamass[0];
propeller_diameter = datamass[1];
air_density = datamass[2];
C_T = datamass[3];
C_P = datamass[4];
multiR = datamass[5];
calculateMaxThrust();
}
real_T getMultiResistance() const
{
return multiR;
}
private:
void initialize() override
{
/*
Ref: http://physics.stackexchange.com/a/32013/14061
force in Newton = C_T * \rho * n^2 * D^4
torque in N.m = C_P * \rho * n^2 * D^5 / (2*pi)
where,
\rho = air density (1.225 kg/m^3)
n = radians per sec
D = propeller diameter in meters
C_T, C_P = dimensionless constants available at
propeller performance database http://m-selig.ae.illinois.edu/props/propDB.html
We use values for GWS 9X5 propeller for which,
C_T = 0.109919, C_P = 0.040164 @ 6396.667 RPM
*/
C_T = 0.109919f; // the thrust co-efficient @ 6396.667 RPM, measured by UIUC.
C_P = 0.040164f; // the torque co-efficient at @ 6396.667 RPM, measured by UIUC.
air_density = 1.225f; // kg/m^3
max_rpm = 6396.667f; // revolutions per minute
propeller_diameter = 0.2286f; //diameter in meters, default is for DJI Phantom 2
propeller_height = 1 / 100.0f; //height of cylindrical area when propeller rotates, 1 cm
control_signal_filter_tc = 0.005f; //time constant for low pass filter
max_thrust = 4.179446268f; //computed from above formula for the given constants
max_torque = 0.055562f; //computed from above formula
calculateMaxThrust();
multiR = 0.000005f;
}
private:
real_T multiR;
};
}
}
#endif | 31.807229 | 94 | 0.669697 | [
"vector"
] |
0d94a23d361f7465614c3c10d317ad35632656c5 | 1,578 | hpp | C++ | src/lib/reseau_graphe/machine/Ordinateur.hpp | uvsq21603504/in608-tcp_ip_simulation | 95cedcbe7dab5991b84e182297b6ada3ae24679b | [
"MIT"
] | null | null | null | src/lib/reseau_graphe/machine/Ordinateur.hpp | uvsq21603504/in608-tcp_ip_simulation | 95cedcbe7dab5991b84e182297b6ada3ae24679b | [
"MIT"
] | null | null | null | src/lib/reseau_graphe/machine/Ordinateur.hpp | uvsq21603504/in608-tcp_ip_simulation | 95cedcbe7dab5991b84e182297b6ada3ae24679b | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <deque>
#include "Machine.hpp"
#include "../../../include/ParamInterface.hpp"
#include "../../protocole_tcp_ip/transport/Transport.hpp"
#include "../../../include/ElementControleCongestion.hpp"
class Ordinateur : public Machine {
private:
// Attributs
static uint8_t m_NbrOrdinateur;
uint8_t m_IdOrdinateur;
std::vector<ElementControleCongestion> m_ControleCongestion;
std::map<uint16_t, double> m_TempsTraitementPaquet;
public:
// Constructeurs
Ordinateur();
// // Ordinateur(const std::string& nom);
// Destructeur
~Ordinateur();
// Getters
const uint8_t& getNbrOrdinateur() const;
const uint8_t& getIdOrdinateur() const;
const std::vector<ElementControleCongestion>&
getControleCongestion() const;
const ElementControleCongestion& getControleCongestion(
const int& position
) const;
const std::map<uint16_t, double>
getTempsTraitementPaquet() const;
double getTempsTraitementPaquet(
const uint16_t& cle
) const;
// Methodes
void remplirFileDonnees(
const ParamInterface& config,
const MAC& destination
);
void synchroniser();
void finDeSession();
void envoyer();
void recevoir();
void traitement(std::stack<std::bitset<16>> &donnee, MAC nouvelleDest);
}; | 28.178571 | 79 | 0.589354 | [
"vector"
] |
0d97bbcbed19d6d6542d90189f19f017f260be8a | 5,626 | cpp | C++ | src/main.cpp | superman-t/BinaryTreePacker | 6860064d0eaf27375d9fb75d3f7fc53ac368ab6c | [
"MIT"
] | 2 | 2019-05-31T11:05:18.000Z | 2021-01-22T08:58:04.000Z | src/main.cpp | superman-t/BinaryTreePacker | 6860064d0eaf27375d9fb75d3f7fc53ac368ab6c | [
"MIT"
] | null | null | null | src/main.cpp | superman-t/BinaryTreePacker | 6860064d0eaf27375d9fb75d3f7fc53ac368ab6c | [
"MIT"
] | null | null | null | #include "nanogui.h"
#include <iostream>
#include <string>
#include <cstdint>
#include <memory>
#include <utility>
#include "BinPack.h"
#include <random>
#include <queue>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::pair;
using std::to_string;
using namespace BP;
class MyGLCanvas : public nanogui::GLCanvas
{
public:
MyGLCanvas( Widget *parent ) : nanogui::GLCanvas( parent )
{
generateData(20);
refresh( "maxside" );
}
~MyGLCanvas()
{
}
void refresh( const std::string& sortname)
{
std::sort( mBlockVector.begin(), mBlockVector.end(), [&]( const Block& lhs, const Block& rhs )
{
auto func = mBlockSort.SortComp( sortname );
return (mBlockSort.*func)(lhs, rhs);
} );
mPacker.reset();
mPacker.fit( mBlockVector );
}
void generateData( int count)
{
std::random_device lrandom;
std::default_random_engine el( lrandom() );
std::uniform_int_distribution<int> uniform_dist( 10, 100 );
mBlockVector.reserve( count );
mBlockVector.clear();
size_t threshold = count;
for( auto i = 0; i < threshold; ++i )
{
int w = uniform_dist( el );
int h = uniform_dist( el );
auto block = Block( w, h, NodeColor( uniform_dist( el ), uniform_dist( el ), uniform_dist( el ), 255 ) );
//std::cout << w << "x" << h << std::endl;
mBlockVector.emplace_back( block );
}
}
virtual void drawGL() override
{
renderWireframe();
renderRect();
}
void renderWireframe()
{
using namespace nanogui;
std::queue<NodePtr> que;
que.emplace( mPacker.getRoot() );
while( !que.empty() )
{
auto node = que.front();
que.pop();
auto x = node->x;
auto y = node->y;
auto w = node->w;
auto h = node->h;
nvgBeginPath( this->screen()->nvgContext() );
nvgRect( this->screen()->nvgContext(), x, y, w, h );
nvgStrokeColor( this->screen()->nvgContext(), Color( 0, 255 ) );
nvgStroke( this->screen()->nvgContext() );
if( node->down ) que.emplace( node->down );
if( node->right ) que.emplace( node->right );
}
}
void renderRect()
{
using namespace nanogui;
for( auto i = 0; i < mBlockVector.size(); ++i )
{
auto block = mBlockVector[i];
if( block.fit )
{
auto x = block.fit->x;
auto y = block.fit->y;
auto w = block.w;
auto h = block.h;
nvgBeginPath( this->screen()->nvgContext() );
nvgRect( this->screen()->nvgContext(), x, y, w, h );
auto color = Color( block.color.r, block.color.g, block.color.b, block.color.a );
nvgFillColor( this->screen()->nvgContext(), color );
nvgFill( this->screen()->nvgContext() );
nvgStrokeColor( this->screen()->nvgContext(), Color( 0, 255 ) );
nvgStroke( this->screen()->nvgContext() );
}
}
}
private:
Packer mPacker;
BlockVector mBlockVector;
BlockSort mBlockSort;
};
class ExampleApplication : public nanogui::Screen
{
public:
ExampleApplication() : nanogui::Screen( Eigen::Vector2i( 1024, 768 ), "BinaryTreePacker", false )
{
using namespace nanogui;
static int index = 0;
mCanvas = new MyGLCanvas( this );
//mCanvas->setBackgroundColor( { 73, 73, 73, 125 } );
mCanvas->setSize( { 1024, 768 } );
FormHelper* gui = new FormHelper( this );
ref<Window> window = gui->addWindow( Eigen::Vector2i( 720, 0 ), "Control Algorithm" );
enum AlgorithmEnum
{
maxside,
area,
width,
height
};
gui->addGroup( "Generate" );
auto label = std::string( "Count" );
auto default = 20;
auto countLabel = gui->addVariable( label, default );
countLabel->setEditable( true );
auto generate = gui->addButton( "Generate", [&, countLabel] {
auto count = countLabel->value() > 0 ? countLabel->value() : 20;
countLabel->setValue( count );
mCanvas->generateData( count );
switch( index )
{
case 0:
mCanvas->refresh( "maxside" );
break;
case 1:
mCanvas->refresh( "area" );
break;
case 2:
mCanvas->refresh( "width" );
break;
case 3:
mCanvas->refresh( "height" );
break;
default:
break;
}
} );
AlgorithmEnum algorithm = maxside;
gui->addGroup( "Algorithm" );
auto algoEnum = gui->addVariable( "Sort", algorithm, true );
algoEnum->setItems( { "maxside", "area", "width", "height" } );
algoEnum->setCallback( [&]( int id )
{
index = 0;
switch( id )
{
case 0:
mCanvas->refresh( "maxside" );
break;
case 1:
mCanvas->refresh( "area" );
break;
case 2:
mCanvas->refresh( "width" );
break;
case 3:
mCanvas->refresh( "height" );
break;
default:
break;
}
} );
performLayout();
}
virtual bool keyboardEvent( int key, int scancode, int action, int modifiers )
{
if( Screen::keyboardEvent( key, scancode, action, modifiers ) )
return true;
if( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS )
{
setVisible( false );
return true;
}
return false;
}
virtual void draw( NVGcontext *ctx )
{
/* Draw the user interface */
Screen::draw( ctx );
}
private:
MyGLCanvas *mCanvas;
};
int main( int /* argc */, char ** /* argv */ )
{
try
{
nanogui::init();
/* scoped variables */
{
nanogui::ref<ExampleApplication> app = new ExampleApplication();
app->drawAll();
app->setVisible( true );
nanogui::mainloop();
}
nanogui::shutdown();
}
catch( const std::runtime_error &e )
{
std::string error_msg = std::string( "Caught a fatal error: " ) + std::string( e.what() );
#if defined(_WIN32)
MessageBoxA( nullptr, error_msg.c_str(), NULL, MB_ICONERROR | MB_OK );
#else
std::cerr << error_msg << endl;
#endif
return -1;
}
return 0;
}
| 21.310606 | 108 | 0.616779 | [
"vector"
] |
31020d92e4b268a5e5b0c14583c485d9b993599b | 1,289 | hpp | C++ | framework/sphere.hpp | caixiaoniweimar/programmiersprachen-raytracer | 98b5e9bcf89bbc81c18160221a2c7c34a130cf35 | [
"MIT"
] | null | null | null | framework/sphere.hpp | caixiaoniweimar/programmiersprachen-raytracer | 98b5e9bcf89bbc81c18160221a2c7c34a130cf35 | [
"MIT"
] | null | null | null | framework/sphere.hpp | caixiaoniweimar/programmiersprachen-raytracer | 98b5e9bcf89bbc81c18160221a2c7c34a130cf35 | [
"MIT"
] | null | null | null | #ifndef SPHERE_HPP
#define SPHERE_HPP
#include <glm/vec3.hpp>
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
#include "shape.hpp"
#include <string>
#include "material.hpp"
using namespace std;
// Mittelpunkt und einen Radius
// Konstruktor; get-Methoden; Methoden area und volume
class Sphere : public Shape{
public:
// Aufgabe 5.2
Sphere();
Sphere(glm::vec3 const& mittelpunkt, double radius);
//Sphere(glm::vec3 const& mittelpunkt, double radius=1.0f);
// Dafault Werte um die Groesse des Sphere zu setzen, aehnlich wie Standardkonstruktor
Sphere(string const& name, shared_ptr<Material> const& material, glm::vec3 const& mittelpunkt, double radius);
~Sphere();
//double area() const override; // area(),volume() 在hpp写override, 在cpp不需要
//double volume() const override;
glm::vec3 get_mittelpunkt() const; // get_Methode() 为const
double get_radius() const;
shared_ptr<Material> get_Material() const;
// Aufgabe 5.5
ostream& print(ostream& os) const override;
// Aufgabe 5.6
bool intersect (Ray const& ray, float& t) const override;
intersectionResult istIntersect(Ray const& ray,float& t) const override;
glm::vec3 getNormal(intersectionResult const& schnittpunkt) const override;
glm::vec3 mittelpunkt_;
double radius_;
};
#endif
| 26.306122 | 111 | 0.734678 | [
"shape"
] |
310bd408a229ac82e07508945e9ed37773dfbe5b | 2,068 | cpp | C++ | src/DotNet/DNSequence.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 198 | 2015-04-26T08:06:18.000Z | 2022-03-13T01:31:50.000Z | src/DotNet/DNSequence.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 15 | 2015-07-07T19:47:08.000Z | 2022-02-04T05:56:51.000Z | src/DotNet/DNSequence.cpp | divyang4481/quickfast | 339c78e96a1f63b74c139afa1a3c9a07afff7b5f | [
"BSD-3-Clause"
] | 96 | 2015-04-24T15:19:43.000Z | 2022-03-28T13:15:11.000Z | // Copyright (c) 2009, 2010 Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#include "QuickFASTDotNetPch.h"
#include "DNSequence.h"
#include <DotNet/ImplSequence.h>
#include <DotNet/DNFieldSet.h>
#include <DotNet/StringConversion.h>
using namespace QuickFAST;
using namespace DotNet;
DNSequence::DNSequence(ImplSequence & impl)
: impl_(&impl)
{
}
DNSequence::~DNSequence()
{
}
System::String ^
DNSequence::LengthName::get()
{
return string_cast(impl_->lengthName());
}
System::String ^
DNSequence::LengthNamespace::get()
{
return string_cast(impl_->lengthNamespace());
}
System::String ^
DNSequence::LengthId::get()
{
return string_cast(impl_->lengthId());
}
int
DNSequence::Count::get()
{
return static_cast<int>(impl_->size());
}
DNFieldSet ^
DNSequence::entry(int index)
{
return gcnew DNFieldSet(impl_->operator[] (size_t(index)));
}
System::Collections::IEnumerator^ DNSequence::GetEnumerator()
{
return gcnew DNSequenceEnumerator(impl_, this);
}
System::Collections::Generic::IEnumerator<DNFieldSet^>^ DNSequence::GetSpecializedEnumerator()
{
return gcnew DNSequenceEnumerator(impl_, this);
}
DNSequence::DNSequenceEnumerator::DNSequenceEnumerator(ImplSequence * impl, DNSequence^ parent)
: parent_(parent)
, impl_(impl)
, position_(size_t(-1))
, size_(impl_->size())
{
}
DNSequence::DNSequenceEnumerator::~DNSequenceEnumerator()
{
}
bool
DNSequence::DNSequenceEnumerator::MoveNext()
{
if(position_ < size_)
{
++position_;
}
else if (position_ == size_t(-1))
{
position_ = 0;
}
return position_ < size_;
}
void
DNSequence::DNSequenceEnumerator::Reset()
{
position_ = size_t(-1);
}
DNFieldSet^
DNSequence::DNSequenceEnumerator::GenericCurrent::get()
{
if(position_ < size_)
{
return gcnew DNFieldSet(impl_->operator[] (position_));
}
return nullptr;
}
System::Object^
DNSequence::DNSequenceEnumerator::Current::get()
{
if(position_ < size_)
{
return gcnew DNFieldSet(impl_->operator[] (position_));
}
return nullptr;
}
| 17.982609 | 95 | 0.717602 | [
"object"
] |
310bda735ab0942df3ed0be7eed483812e69a93a | 3,032 | hpp | C++ | include/LiteNetLib/Utils/NetPacketProcessor_SubscribeDelegate.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/LiteNetLib/Utils/NetPacketProcessor_SubscribeDelegate.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/LiteNetLib/Utils/NetPacketProcessor_SubscribeDelegate.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: LiteNetLib.Utils.NetPacketProcessor
#include "LiteNetLib/Utils/NetPacketProcessor.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: LiteNetLib::Utils
namespace LiteNetLib::Utils {
// Forward declaring type: NetDataReader
class NetDataReader;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
// Type namespace: LiteNetLib.Utils
namespace LiteNetLib::Utils {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: LiteNetLib.Utils.NetPacketProcessor/SubscribeDelegate
class NetPacketProcessor::SubscribeDelegate : public System::MulticastDelegate {
public:
// Creating value type constructor for type: SubscribeDelegate
SubscribeDelegate() noexcept {}
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x23C610C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static NetPacketProcessor::SubscribeDelegate* New_ctor(::Il2CppObject* object, System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("LiteNetLib::Utils::NetPacketProcessor::SubscribeDelegate::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<NetPacketProcessor::SubscribeDelegate*, creationType>(object, method)));
}
// public System.Void Invoke(LiteNetLib.Utils.NetDataReader reader, System.Object userData)
// Offset: 0x23C5D24
void Invoke(LiteNetLib::Utils::NetDataReader* reader, ::Il2CppObject* userData);
// public System.IAsyncResult BeginInvoke(LiteNetLib.Utils.NetDataReader reader, System.Object userData, System.AsyncCallback callback, System.Object object)
// Offset: 0x23C611C
System::IAsyncResult* BeginInvoke(LiteNetLib::Utils::NetDataReader* reader, ::Il2CppObject* userData, System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Void EndInvoke(System.IAsyncResult result)
// Offset: 0x23C614C
void EndInvoke(System::IAsyncResult* result);
}; // LiteNetLib.Utils.NetPacketProcessor/SubscribeDelegate
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(LiteNetLib::Utils::NetPacketProcessor::SubscribeDelegate*, "LiteNetLib.Utils", "NetPacketProcessor/SubscribeDelegate");
| 51.389831 | 164 | 0.743734 | [
"object"
] |
310d9b01ac0489610598cc16219d16565ebfaa72 | 50,736 | cpp | C++ | src/ConstraintSolver/SolverFunctions.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | 1 | 2022-03-01T09:03:40.000Z | 2022-03-01T09:03:40.000Z | src/ConstraintSolver/SolverFunctions.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | null | null | null | src/ConstraintSolver/SolverFunctions.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | 1 | 2022-03-01T09:03:42.000Z | 2022-03-01T09:03:42.000Z | /*
Copyright (c) 2006-2014, Michael Greminger
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF A
DVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cmath>
#include "SolverFunctions.h"
using namespace std;
SolverFunctionsBasePointer SolverFunctionsFactory(std::string solver_function_name, std::vector<DOFPointer> dof_list)
{
SolverFunctionsBasePointer new_solver_function;
if(solver_function_name == "distance_point_2d")
new_solver_function.reset(new distance_point_2d(dof_list));
else if (solver_function_name == "angle_line_2d_interior")
new_solver_function.reset(new angle_line_2d_interior(dof_list));
else if (solver_function_name == "angle_line_2d_exterior")
new_solver_function.reset(new angle_line_2d_exterior(dof_list));
else if (solver_function_name == "tangent_edge_2d")
new_solver_function.reset(new tangent_edge_2d(dof_list));
else if (solver_function_name == "parallel_line_2d")
new_solver_function.reset(new parallel_line_2d(dof_list));
else if (solver_function_name == "arc2d_point_s")
new_solver_function.reset(new arc2d_point_s(dof_list));
else if (solver_function_name == "arc2d_point_t")
new_solver_function.reset(new arc2d_point_t(dof_list));
else if (solver_function_name == "arc2d_tangent_s")
new_solver_function.reset(new arc2d_tangent_s(dof_list));
else if (solver_function_name == "arc2d_tangent_t")
new_solver_function.reset(new arc2d_tangent_t(dof_list));
else if (solver_function_name == "point2d_tangent1_s")
new_solver_function.reset(new point2d_tangent1_s(dof_list));
else if (solver_function_name == "point2d_tangent1_t")
new_solver_function.reset(new point2d_tangent1_t(dof_list));
else if (solver_function_name == "point2d_tangent2_s")
new_solver_function.reset(new point2d_tangent2_s(dof_list));
else if (solver_function_name == "point2d_tangent2_t")
new_solver_function.reset(new point2d_tangent2_t(dof_list));
else if (solver_function_name == "distance_point_line_2d")
new_solver_function.reset(new distance_point_line_2d(dof_list));
else if (solver_function_name == "hori_vert_2d")
new_solver_function.reset(new hori_vert_2d(dof_list));
else
throw SolverFunctionsException("SolverFunctionsFactory: Requested solver function name not found.");
return new_solver_function;
}
distance_point_2d::distance_point_2d(DOFPointer point1s, DOFPointer point1t, DOFPointer point2s, DOFPointer point2t, DOFPointer distance)
{
AddDOF(point1s);
AddDOF(point1t);
AddDOF(point2s);
AddDOF(point2t);
AddDOF(distance);
}
distance_point_2d::distance_point_2d(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 5)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction distance_point_2d did not contain exactly 5 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double distance_point_2d::GetValue() const
{
double point1s = GetDOF(0)->GetValue();
double point1t = GetDOF(1)->GetValue();
double point2s = GetDOF(2)->GetValue();
double point2t = GetDOF(3)->GetValue();
double distance = GetDOF(4)->GetValue();
return -distance + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
double distance_point_2d::GetValueSelf(const mmcMatrix ¶ms) const
{
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
double distance = params(4,0);
return -distance + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
mmcMatrix distance_point_2d::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
double distance = params(4,0);
result(0,0) = (point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(1,0) = (point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(2,0) = (point2s - point1s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(3,0) = (point2t - point1t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(4,0) = -1;
return result;
}
angle_line_2d_interior::angle_line_2d_interior(DOFPointer line1_point1s, DOFPointer line1_point1t, DOFPointer line1_point2s, DOFPointer line1_point2t, DOFPointer line2_point1s, DOFPointer line2_point1t, DOFPointer line2_point2s, DOFPointer line2_point2t, DOFPointer angle)
{
AddDOF(line1_point1s);
AddDOF(line1_point1t);
AddDOF(line1_point2s);
AddDOF(line1_point2t);
AddDOF(line2_point1s);
AddDOF(line2_point1t);
AddDOF(line2_point2s);
AddDOF(line2_point2t);
AddDOF(angle);
}
angle_line_2d_interior::angle_line_2d_interior(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 9)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction angle_line_2d_interior did not contain exactly 9 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double angle_line_2d_interior::GetValue() const
{
double line1_point1s = GetDOF(0)->GetValue();
double line1_point1t = GetDOF(1)->GetValue();
double line1_point2s = GetDOF(2)->GetValue();
double line1_point2t = GetDOF(3)->GetValue();
double line2_point1s = GetDOF(4)->GetValue();
double line2_point1t = GetDOF(5)->GetValue();
double line2_point2s = GetDOF(6)->GetValue();
double line2_point2t = GetDOF(7)->GetValue();
double angle = GetDOF(8)->GetValue();
return -cos(angle) + ((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
}
double angle_line_2d_interior::GetValueSelf(const mmcMatrix ¶ms) const
{
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
double angle = params(8,0);
return -cos(angle) + ((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
}
mmcMatrix angle_line_2d_interior::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
double angle = params(8,0);
result(0,0) = (line2_point1s - line2_point2s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point2s - line1_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(1,0) = (line2_point1t - line2_point2t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point2t - line1_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(2,0) = (line2_point2s - line2_point1s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point1s - line1_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(3,0) = (line2_point2t - line2_point1t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point1t - line1_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(4,0) = (line1_point1s - line1_point2s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point2s - line2_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(5,0) = (line1_point1t - line1_point2t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point2t - line2_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(6,0) = (line1_point2s - line1_point1s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point1s - line2_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(7,0) = (line1_point2t - line1_point1t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point1t - line2_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(8,0) = sin(angle);
return result;
}
angle_line_2d_exterior::angle_line_2d_exterior(DOFPointer line1_point1s, DOFPointer line1_point1t, DOFPointer line1_point2s, DOFPointer line1_point2t, DOFPointer line2_point1s, DOFPointer line2_point1t, DOFPointer line2_point2s, DOFPointer line2_point2t, DOFPointer angle)
{
AddDOF(line1_point1s);
AddDOF(line1_point1t);
AddDOF(line1_point2s);
AddDOF(line1_point2t);
AddDOF(line2_point1s);
AddDOF(line2_point1t);
AddDOF(line2_point2s);
AddDOF(line2_point2t);
AddDOF(angle);
}
angle_line_2d_exterior::angle_line_2d_exterior(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 9)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction angle_line_2d_exterior did not contain exactly 9 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double angle_line_2d_exterior::GetValue() const
{
double line1_point1s = GetDOF(0)->GetValue();
double line1_point1t = GetDOF(1)->GetValue();
double line1_point2s = GetDOF(2)->GetValue();
double line1_point2t = GetDOF(3)->GetValue();
double line2_point1s = GetDOF(4)->GetValue();
double line2_point1t = GetDOF(5)->GetValue();
double line2_point2s = GetDOF(6)->GetValue();
double line2_point2t = GetDOF(7)->GetValue();
double angle = GetDOF(8)->GetValue();
return ((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + cos(angle);
}
double angle_line_2d_exterior::GetValueSelf(const mmcMatrix ¶ms) const
{
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
double angle = params(8,0);
return ((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + cos(angle);
}
mmcMatrix angle_line_2d_exterior::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
double angle = params(8,0);
result(0,0) = (line2_point1s - line2_point2s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point2s - line1_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(1,0) = (line2_point1t - line2_point2t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point2t - line1_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(2,0) = (line2_point2s - line2_point1s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point1s - line1_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(3,0) = (line2_point2t - line2_point1t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line1_point1t - line1_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(3.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0)));
result(4,0) = (line1_point1s - line1_point2s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point2s - line2_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(5,0) = (line1_point1t - line1_point2t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point2t - line2_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(6,0) = (line1_point2s - line1_point1s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point1s - line2_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(7,0) = (line1_point2t - line1_point1t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(1.0/2.0))) + (line2_point1t - line2_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),(1.0/2.0))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),(3.0/2.0)));
result(8,0) = -sin(angle);
return result;
}
tangent_edge_2d::tangent_edge_2d(DOFPointer s1, DOFPointer t1, DOFPointer s2, DOFPointer t2)
{
AddDOF(s1);
AddDOF(t1);
AddDOF(s2);
AddDOF(t2);
}
tangent_edge_2d::tangent_edge_2d(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 4)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction tangent_edge_2d did not contain exactly 4 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double tangent_edge_2d::GetValue() const
{
double s1 = GetDOF(0)->GetValue();
double t1 = GetDOF(1)->GetValue();
double s2 = GetDOF(2)->GetValue();
double t2 = GetDOF(3)->GetValue();
return -1 + pow((s1*s2 + t1*t2),2);
}
double tangent_edge_2d::GetValueSelf(const mmcMatrix ¶ms) const
{
double s1 = params(0,0);
double t1 = params(1,0);
double s2 = params(2,0);
double t2 = params(3,0);
return -1 + pow((s1*s2 + t1*t2),2);
}
mmcMatrix tangent_edge_2d::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double s1 = params(0,0);
double t1 = params(1,0);
double s2 = params(2,0);
double t2 = params(3,0);
result(0,0) = 2*s2*(s1*s2 + t1*t2);
result(1,0) = 2*t2*(s1*s2 + t1*t2);
result(2,0) = 2*s1*(s1*s2 + t1*t2);
result(3,0) = 2*t1*(s1*s2 + t1*t2);
return result;
}
parallel_line_2d::parallel_line_2d(DOFPointer line1_point1s, DOFPointer line1_point1t, DOFPointer line1_point2s, DOFPointer line1_point2t, DOFPointer line2_point1s, DOFPointer line2_point1t, DOFPointer line2_point2s, DOFPointer line2_point2t)
{
AddDOF(line1_point1s);
AddDOF(line1_point1t);
AddDOF(line1_point2s);
AddDOF(line1_point2t);
AddDOF(line2_point1s);
AddDOF(line2_point1t);
AddDOF(line2_point2s);
AddDOF(line2_point2t);
}
parallel_line_2d::parallel_line_2d(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 8)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction parallel_line_2d did not contain exactly 8 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double parallel_line_2d::GetValue() const
{
double line1_point1s = GetDOF(0)->GetValue();
double line1_point1t = GetDOF(1)->GetValue();
double line1_point2s = GetDOF(2)->GetValue();
double line1_point2t = GetDOF(3)->GetValue();
double line2_point1s = GetDOF(4)->GetValue();
double line2_point1t = GetDOF(5)->GetValue();
double line2_point2s = GetDOF(6)->GetValue();
double line2_point2t = GetDOF(7)->GetValue();
return -1 + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
}
double parallel_line_2d::GetValueSelf(const mmcMatrix ¶ms) const
{
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
return -1 + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
}
mmcMatrix parallel_line_2d::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double line1_point1s = params(0,0);
double line1_point1t = params(1,0);
double line1_point2s = params(2,0);
double line1_point2t = params(3,0);
double line2_point1s = params(4,0);
double line2_point1t = params(5,0);
double line2_point2s = params(6,0);
double line2_point2t = params(7,0);
result(0,0) = (-2*line2_point2s + 2*line2_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line1_point1s + 2*line1_point2s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),2)*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
result(1,0) = (-2*line2_point2t + 2*line2_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line1_point1t + 2*line1_point2t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),2)*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
result(2,0) = (-2*line2_point1s + 2*line2_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line1_point2s + 2*line1_point1s)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),2)*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
result(3,0) = (-2*line2_point1t + 2*line2_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line1_point2t + 2*line1_point1t)/(pow((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2)),2)*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)));
result(4,0) = (-2*line1_point2s + 2*line1_point1s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line2_point1s + 2*line2_point2s)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),2));
result(5,0) = (-2*line1_point2t + 2*line1_point1t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line2_point1t + 2*line2_point2t)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),2));
result(6,0) = (-2*line1_point1s + 2*line1_point2s)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line2_point2s + 2*line2_point1s)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),2));
result(7,0) = (-2*line1_point1t + 2*line1_point2t)*((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t))/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*(pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2))) + pow(((line1_point1s - line1_point2s)*(line2_point1s - line2_point2s) + (line1_point1t - line1_point2t)*(line2_point1t - line2_point2t)),2)*(-2*line2_point2t + 2*line2_point1t)/((pow((line1_point1s - line1_point2s),2) + pow((line1_point1t - line1_point2t),2))*pow((pow((line2_point1s - line2_point2s),2) + pow((line2_point1t - line2_point2t),2)),2));
return result;
}
arc2d_point_s::arc2d_point_s(DOFPointer s_center, DOFPointer radius, DOFPointer theta)
{
AddDOF(s_center);
AddDOF(radius);
AddDOF(theta);
}
arc2d_point_s::arc2d_point_s(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 3)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction arc2d_point_s did not contain exactly 3 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double arc2d_point_s::GetValue() const
{
double s_center = GetDOF(0)->GetValue();
double radius = GetDOF(1)->GetValue();
double theta = GetDOF(2)->GetValue();
return s_center + radius*cos(theta);
}
double arc2d_point_s::GetValueSelf(const mmcMatrix ¶ms) const
{
double s_center = params(0,0);
double radius = params(1,0);
double theta = params(2,0);
return s_center + radius*cos(theta);
}
mmcMatrix arc2d_point_s::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double s_center = params(0,0);
double radius = params(1,0);
double theta = params(2,0);
result(0,0) = 1;
result(1,0) = cos(theta);
result(2,0) = -radius*sin(theta);
return result;
}
arc2d_point_t::arc2d_point_t(DOFPointer t_center, DOFPointer radius, DOFPointer theta)
{
AddDOF(t_center);
AddDOF(radius);
AddDOF(theta);
}
arc2d_point_t::arc2d_point_t(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 3)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction arc2d_point_t did not contain exactly 3 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double arc2d_point_t::GetValue() const
{
double t_center = GetDOF(0)->GetValue();
double radius = GetDOF(1)->GetValue();
double theta = GetDOF(2)->GetValue();
return t_center + radius*sin(theta);
}
double arc2d_point_t::GetValueSelf(const mmcMatrix ¶ms) const
{
double t_center = params(0,0);
double radius = params(1,0);
double theta = params(2,0);
return t_center + radius*sin(theta);
}
mmcMatrix arc2d_point_t::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double t_center = params(0,0);
double radius = params(1,0);
double theta = params(2,0);
result(0,0) = 1;
result(1,0) = sin(theta);
result(2,0) = radius*cos(theta);
return result;
}
arc2d_tangent_s::arc2d_tangent_s(DOFPointer theta)
{
AddDOF(theta);
}
arc2d_tangent_s::arc2d_tangent_s(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 1)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction arc2d_tangent_s did not contain exactly 1 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double arc2d_tangent_s::GetValue() const
{
double theta = GetDOF(0)->GetValue();
return sin(theta);
}
double arc2d_tangent_s::GetValueSelf(const mmcMatrix ¶ms) const
{
double theta = params(0,0);
return sin(theta);
}
mmcMatrix arc2d_tangent_s::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double theta = params(0,0);
result(0,0) = cos(theta);
return result;
}
arc2d_tangent_t::arc2d_tangent_t(DOFPointer theta)
{
AddDOF(theta);
}
arc2d_tangent_t::arc2d_tangent_t(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 1)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction arc2d_tangent_t did not contain exactly 1 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double arc2d_tangent_t::GetValue() const
{
double theta = GetDOF(0)->GetValue();
return -cos(theta);
}
double arc2d_tangent_t::GetValueSelf(const mmcMatrix ¶ms) const
{
double theta = params(0,0);
return -cos(theta);
}
mmcMatrix arc2d_tangent_t::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double theta = params(0,0);
result(0,0) = sin(theta);
return result;
}
point2d_tangent1_s::point2d_tangent1_s(DOFPointer point1s, DOFPointer point1t, DOFPointer point2s, DOFPointer point2t)
{
AddDOF(point1s);
AddDOF(point1t);
AddDOF(point2s);
AddDOF(point2t);
}
point2d_tangent1_s::point2d_tangent1_s(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 4)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction point2d_tangent1_s did not contain exactly 4 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double point2d_tangent1_s::GetValue() const
{
double point1s = GetDOF(0)->GetValue();
double point1t = GetDOF(1)->GetValue();
double point2s = GetDOF(2)->GetValue();
double point2t = GetDOF(3)->GetValue();
return (point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
double point2d_tangent1_s::GetValueSelf(const mmcMatrix ¶ms) const
{
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
return (point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
mmcMatrix point2d_tangent1_s::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
result(0,0) = (point2s - point1s)*(point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(-1.0/2.0));
result(1,0) = (point2t - point1t)*(point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(2,0) = pow((point1s - point2s),2)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) - 1/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(3,0) = (point1s - point2s)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
return result;
}
point2d_tangent1_t::point2d_tangent1_t(DOFPointer point1s, DOFPointer point1t, DOFPointer point2s, DOFPointer point2t)
{
AddDOF(point1s);
AddDOF(point1t);
AddDOF(point2s);
AddDOF(point2t);
}
point2d_tangent1_t::point2d_tangent1_t(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 4)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction point2d_tangent1_t did not contain exactly 4 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double point2d_tangent1_t::GetValue() const
{
double point1s = GetDOF(0)->GetValue();
double point1t = GetDOF(1)->GetValue();
double point2s = GetDOF(2)->GetValue();
double point2t = GetDOF(3)->GetValue();
return (point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
double point2d_tangent1_t::GetValueSelf(const mmcMatrix ¶ms) const
{
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
return (point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
mmcMatrix point2d_tangent1_t::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
result(0,0) = (point2s - point1s)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(1,0) = (point2t - point1t)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(-1.0/2.0));
result(2,0) = (point1s - point2s)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(3,0) = pow((point1t - point2t),2)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) - 1/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
return result;
}
point2d_tangent2_s::point2d_tangent2_s(DOFPointer point1s, DOFPointer point1t, DOFPointer point2s, DOFPointer point2t)
{
AddDOF(point1s);
AddDOF(point1t);
AddDOF(point2s);
AddDOF(point2t);
}
point2d_tangent2_s::point2d_tangent2_s(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 4)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction point2d_tangent2_s did not contain exactly 4 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double point2d_tangent2_s::GetValue() const
{
double point1s = GetDOF(0)->GetValue();
double point1t = GetDOF(1)->GetValue();
double point2s = GetDOF(2)->GetValue();
double point2t = GetDOF(3)->GetValue();
return (point2s - point1s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
double point2d_tangent2_s::GetValueSelf(const mmcMatrix ¶ms) const
{
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
return (point2s - point1s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
mmcMatrix point2d_tangent2_s::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
result(0,0) = pow((point2s - point1s),2)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) - 1/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(1,0) = (point2s - point1s)*(point2t - point1t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(2,0) = (point2s - point1s)*(point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(-1.0/2.0));
result(3,0) = (point2s - point1s)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
return result;
}
point2d_tangent2_t::point2d_tangent2_t(DOFPointer point1s, DOFPointer point1t, DOFPointer point2s, DOFPointer point2t)
{
AddDOF(point1s);
AddDOF(point1t);
AddDOF(point2s);
AddDOF(point2t);
}
point2d_tangent2_t::point2d_tangent2_t(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 4)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction point2d_tangent2_t did not contain exactly 4 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double point2d_tangent2_t::GetValue() const
{
double point1s = GetDOF(0)->GetValue();
double point1t = GetDOF(1)->GetValue();
double point2s = GetDOF(2)->GetValue();
double point2t = GetDOF(3)->GetValue();
return (point2t - point1t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
double point2d_tangent2_t::GetValueSelf(const mmcMatrix ¶ms) const
{
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
return (point2t - point1t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
}
mmcMatrix point2d_tangent2_t::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point1s = params(0,0);
double point1t = params(1,0);
double point2s = params(2,0);
double point2t = params(3,0);
result(0,0) = (point2s - point1s)*(point2t - point1t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(1,0) = pow((point2t - point1t),2)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) - 1/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(1.0/2.0));
result(2,0) = (point2t - point1t)*(point1s - point2s)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0));
result(3,0) = (point2t - point1t)*(point1t - point2t)/pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(3.0/2.0)) + pow((pow((point1s - point2s),2) + pow((point1t - point2t),2)),(-1.0/2.0));
return result;
}
distance_point_line_2d::distance_point_line_2d(DOFPointer point_s, DOFPointer point_t, DOFPointer line_point1s, DOFPointer line_point1t, DOFPointer line_point2s, DOFPointer line_point2t, DOFPointer distance)
{
AddDOF(point_s);
AddDOF(point_t);
AddDOF(line_point1s);
AddDOF(line_point1t);
AddDOF(line_point2s);
AddDOF(line_point2t);
AddDOF(distance);
}
distance_point_line_2d::distance_point_line_2d(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 7)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction distance_point_line_2d did not contain exactly 7 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double distance_point_line_2d::GetValue() const
{
double point_s = GetDOF(0)->GetValue();
double point_t = GetDOF(1)->GetValue();
double line_point1s = GetDOF(2)->GetValue();
double line_point1t = GetDOF(3)->GetValue();
double line_point2s = GetDOF(4)->GetValue();
double line_point2t = GetDOF(5)->GetValue();
double distance = GetDOF(6)->GetValue();
return -pow(distance,2) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2));
}
double distance_point_line_2d::GetValueSelf(const mmcMatrix ¶ms) const
{
double point_s = params(0,0);
double point_t = params(1,0);
double line_point1s = params(2,0);
double line_point1t = params(3,0);
double line_point2s = params(4,0);
double line_point2t = params(5,0);
double distance = params(6,0);
return -pow(distance,2) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2));
}
mmcMatrix distance_point_line_2d::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double point_s = params(0,0);
double point_t = params(1,0);
double line_point1s = params(2,0);
double line_point1t = params(3,0);
double line_point2s = params(4,0);
double line_point2t = params(5,0);
double distance = params(6,0);
result(0,0) = (-2*line_point1t + 2*line_point2t)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2));
result(1,0) = (-2*line_point2s + 2*line_point1s)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2));
result(2,0) = (-2*line_point2t + 2*point_t)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)*(-2*line_point1s + 2*line_point2s)/pow((pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)),2);
result(3,0) = (-2*point_s + 2*line_point2s)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)*(-2*line_point1t + 2*line_point2t)/pow((pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)),2);
result(4,0) = (-2*point_t + 2*line_point1t)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)*(-2*line_point2s + 2*line_point1s)/pow((pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)),2);
result(5,0) = (-2*line_point1s + 2*point_s)*((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t))/(pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)) + pow(((line_point1t - point_t)*(line_point2s - line_point1s) - (line_point1s - point_s)*(line_point2t - line_point1t)),2)*(-2*line_point2t + 2*line_point1t)/pow((pow((line_point2s - line_point1s),2) + pow((line_point2t - line_point1t),2)),2);
result(6,0) = -2*distance;
return result;
}
hori_vert_2d::hori_vert_2d(DOFPointer dof1, DOFPointer dof2)
{
AddDOF(dof1);
AddDOF(dof2);
}
hori_vert_2d::hori_vert_2d(std::vector<DOFPointer> dof_list)
{
// Check to make sure the correct number of parameters have been provided
if(dof_list.size() != 2)
throw SolverFunctionsException("The DOF vector for the constructor of SolverFunction hori_vert_2d did not contain exactly 2 DOF's");
for(int i=0; i<dof_list.size(); i++)
AddDOF(dof_list[i]);
}
double hori_vert_2d::GetValue() const
{
double dof1 = GetDOF(0)->GetValue();
double dof2 = GetDOF(1)->GetValue();
return dof1 - dof2;
}
double hori_vert_2d::GetValueSelf(const mmcMatrix ¶ms) const
{
double dof1 = params(0,0);
double dof2 = params(1,0);
return dof1 - dof2;
}
mmcMatrix hori_vert_2d::GetGradientSelf(const mmcMatrix ¶ms) const
{
mmcMatrix result(GetNumDOFs(),1);
double dof1 = params(0,0);
double dof2 = params(1,0);
result(0,0) = 1;
result(1,0) = -1;
return result;
}
| 54.321199 | 704 | 0.70246 | [
"vector"
] |
310db9ca4092f6a78dc7559e780e18c3c0041c4d | 3,913 | cc | C++ | media/cast/logging/simple_event_subscriber_unittest.cc | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | media/cast/logging/simple_event_subscriber_unittest.cc | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | media/cast/logging/simple_event_subscriber_unittest.cc | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/tick_clock.h"
#include "media/cast/cast_environment.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/logging/simple_event_subscriber.h"
#include "media/cast/test/fake_single_thread_task_runner.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
namespace cast {
class SimpleEventSubscriberTest : public ::testing::Test {
protected:
SimpleEventSubscriberTest()
: testing_clock_(new base::SimpleTestTickClock()),
task_runner_(new test::FakeSingleThreadTaskRunner(testing_clock_)),
cast_environment_(new CastEnvironment(
scoped_ptr<base::TickClock>(testing_clock_).Pass(), task_runner_,
task_runner_, task_runner_, task_runner_, task_runner_,
task_runner_, GetLoggingConfigWithRawEventsAndStatsEnabled())) {
cast_environment_->Logging()->AddRawEventSubscriber(&event_subscriber_);
}
virtual ~SimpleEventSubscriberTest() {
cast_environment_->Logging()->RemoveRawEventSubscriber(&event_subscriber_);
}
base::SimpleTestTickClock* testing_clock_; // Owned by CastEnvironment.
scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_;
scoped_refptr<CastEnvironment> cast_environment_;
SimpleEventSubscriber event_subscriber_;
};
TEST_F(SimpleEventSubscriberTest, GetAndResetEvents) {
// Log some frame events.
cast_environment_->Logging()->InsertFrameEventWithSize(
testing_clock_->NowTicks(), kAudioFrameEncoded, /*rtp_timestamp*/ 100u,
/*frame_id*/ 0u, /*frame_size*/ 123);
cast_environment_->Logging()->InsertFrameEventWithDelay(
testing_clock_->NowTicks(), kAudioPlayoutDelay, /*rtp_timestamp*/ 100u,
/*frame_id*/ 0u, /*delay*/ base::TimeDelta::FromMilliseconds(100));
cast_environment_->Logging()->InsertFrameEvent(
testing_clock_->NowTicks(), kAudioFrameDecoded, /*rtp_timestamp*/ 200u,
/*frame_id*/ 0u);
// Log some packet events.
cast_environment_->Logging()->InsertPacketEvent(
testing_clock_->NowTicks(), kAudioPacketReceived, /*rtp_timestamp*/ 200u,
/*frame_id*/ 0u, /*packet_id*/ 1u, /*max_packet_id*/ 5u, /*size*/ 100u);
cast_environment_->Logging()->InsertPacketEvent(
testing_clock_->NowTicks(), kVideoFrameDecoded, /*rtp_timestamp*/ 200u,
/*frame_id*/ 0u, /*packet_id*/ 1u, /*max_packet_id*/ 5u, /*size*/ 100u);
cast_environment_->Logging()->InsertPacketEvent(
testing_clock_->NowTicks(), kVideoFrameDecoded, /*rtp_timestamp*/ 300u,
/*frame_id*/ 0u, /*packet_id*/ 1u, /*max_packet_id*/ 5u, /*size*/ 100u);
// Log some generic events.
cast_environment_->Logging()->InsertGenericEvent(testing_clock_->NowTicks(),
kRttMs, /*value*/ 150);
std::vector<FrameEvent> frame_events;
event_subscriber_.GetFrameEventsAndReset(&frame_events);
EXPECT_EQ(3u, frame_events.size());
std::vector<PacketEvent> packet_events;
event_subscriber_.GetPacketEventsAndReset(&packet_events);
EXPECT_EQ(3u, packet_events.size());
std::vector<GenericEvent> generic_events;
event_subscriber_.GetGenericEventsAndReset(&generic_events);
EXPECT_EQ(1u, generic_events.size());
// Calling this function again should result in empty vector because no events
// were logged since last call.
event_subscriber_.GetFrameEventsAndReset(&frame_events);
event_subscriber_.GetPacketEventsAndReset(&packet_events);
event_subscriber_.GetGenericEventsAndReset(&generic_events);
EXPECT_TRUE(frame_events.empty());
EXPECT_TRUE(packet_events.empty());
EXPECT_TRUE(generic_events.empty());
}
} // namespace cast
} // namespace media
| 43 | 80 | 0.743419 | [
"vector"
] |
310e910ae398e1d5ebc24bdde116b1937b439798 | 6,541 | cpp | C++ | bindings/ruby/sfml-audio/audio/SoundBufferRecorder.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | bindings/ruby/sfml-audio/audio/SoundBufferRecorder.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | bindings/ruby/sfml-audio/audio/SoundBufferRecorder.cpp | yoyonel/sflm2-custom | 1ebeabe7cfe6605590b341f7b415b24bed1f50d1 | [
"Zlib"
] | null | null | null | /* rbSFML - Copyright (c) 2010 Henrik Valter Vogelius Hansson - groogy@groogy.se
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but
* is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any
* source distribution.
*/
#include "SoundBufferRecorder.hpp"
#include "main.hpp"
#include <SFML/Audio/SoundBufferRecorder.hpp>
VALUE globalSoundBufferRecorderClass;
/* External classes */
extern VALUE globalSoundRecorderClass;
extern VALUE globalSoundBufferClass;
class rbSoundBufferRecorder : public sf::SoundBufferRecorder
{
public:
rbSoundBufferRecorder()
{
}
void Init( VALUE rubySelf )
{
mySelf = rubySelf;
myOnStartID = rb_intern( "onStart" );
myOnStopID = rb_intern( "onStop" );
myOnProcessSamplesID = rb_intern( "onProcessSamples" );
}
protected:
virtual bool OnStart()
{
if( rb_respond_to( mySelf, myOnStartID ) == 0 )
{
return true;
}
else
{
if( rb_funcall( mySelf, myOnStartID, 0 ) == Qfalse )
{
return false;
}
else
{
return true;
}
}
}
virtual void OnStop()
{
if( rb_respond_to( mySelf, myOnStopID ) != 0 )
{
rb_funcall( mySelf, myOnStopID, 0 );
}
}
virtual bool OnProcessSamples( const sf::Int16 *someSamples, std::size_t someCount )
{
VALUE samples = rb_ary_new2( someCount );
for(unsigned long index = 0; index < someCount; index++)
{
rb_ary_store( samples, index, INT2FIX( someSamples[index] ) );
}
if( rb_funcall( mySelf, myOnProcessSamplesID, 2, samples, INT2FIX( someCount ) ) == Qfalse )
{
return false;
}
else
{
return true;
}
}
VALUE mySelf;
ID myOnStartID;
ID myOnStopID;
ID myOnProcessSamplesID;
};
static void SoundBufferRecorder_Free( rbSoundBufferRecorder * anObject )
{
delete anObject;
}
/* call-seq:
* sound_buffer_recorder.getBuffer() -> sound_buffer
*
* Get the sound buffer containing the captured audio data.
*
* The sound buffer is valid only after the capture has ended. This function provides a read-only access to the internal
* sound buffer, but it can be copied if you need to make any modification to it.
*/
static VALUE SoundBufferRecorder_GetBuffer( VALUE self )
{
sf::SoundBufferRecorder *object = NULL;
Data_Get_Struct( self, sf::SoundBufferRecorder, object );
const sf::SoundBuffer &buffer = object->GetBuffer();
VALUE rbData = Data_Wrap_Struct( globalSoundBufferClass, 0, 0, const_cast< sf::SoundBuffer * >( &buffer ) );
rb_iv_set( rbData, "@__owner_ref", self );
return rbData;
}
/* call-seq:
* SoundBufferRecorder.new() -> sound_buffer_recorder
*
* Creates a sound buffer recorder instance for us.
*/
static VALUE SoundBufferRecorder_Alloc( VALUE aKlass )
{
rbSoundBufferRecorder *object = new rbSoundBufferRecorder();
return Data_Wrap_Struct( aKlass, 0, SoundBufferRecorder_Free, object );
}
void Init_SoundBufferRecorder( void )
{
/* SFML namespace which contains the classes of this module. */
VALUE sfml = rb_define_module( "SFML" );
/* Abstract base class for capturing sound data.
*
* SFML::SoundRecorder provides a simple interface to access the audio recording capabilities of the computer
* (the microphone).
*
* As an abstract base class, it only cares about capturing sound samples, the task of making something useful with
* them is left to the derived class. Note that SFML provides a built-in specialization for saving the captured data
* to a sound buffer (see sf::SoundBufferRecorder).
*
* A derived class has only one virtual function to override:
*
* - onProcessSamples provides the new chunks of audio samples while the capture happens
*
* Moreover, two additionnal virtual functions can be overriden as well if necessary:
*
* - onStart is called before the capture happens, to perform custom initializations
* - onStop is called after the capture ends, to perform custom cleanup
*
* The audio capture feature may not be supported or activated on every platform, thus it is recommended to check
* its availability with the isAvailable() function. If it returns false, then any attempt to use an audio recorder
* will fail.
*
* It is important to note that the audio capture happens in a separate thread, so that it doesn't block the rest of
* the program. In particular, the OnProcessSamples and OnStop virtual functions (but not OnStart) will be called from
* this separate thread. It is important to keep this in mind, because you may have to take care of synchronization
* issues if you share data between threads.
*
* Usage example:
*
* class CustomRecorder < SFML::SoundRecorder
* def onStart() # optional
* # Initialize whatever has to be done before the capture starts
* ...
*
* # Return true to start playing
* return true
* end
*
* def onProcessSamples( samples, samplesCount )
* # Do something with the new chunk of samples (store them, send them, ...)
* ...
*
* # Return true to continue playing
* return true
* end
*
* def onStop() # optional
* # Clean up whatever has to be done after the capture ends
* ...
* end
* end
*
* # Usage
* if CustomRecorder.isAvailable()
* recorder = CustomRecorder.new
* recorder.start()
* ...
* recorder.stop()
* end
*/
globalSoundBufferRecorderClass = rb_define_class_under( sfml, "SoundBufferRecorder", globalSoundRecorderClass );
// Class methods
//rb_define_singleton_method( globalSoundBufferRecorderClass, "new", SoundBufferRecorder_New, -1 );
rb_define_alloc_func( globalSoundBufferRecorderClass, SoundBufferRecorder_Alloc );
// Instance methods
rb_define_method( globalSoundRecorderClass, "getBuffer", SoundBufferRecorder_GetBuffer, 0 );
// Instance Aliases
rb_define_alias( globalSoundRecorderClass, "buffer", "getBuffer" );
}
| 31 | 121 | 0.717169 | [
"object"
] |
3112bd6e96937f68e79b6ce201c7f4a97aa818b7 | 20,338 | cpp | C++ | wdbecmbd/IexWdbe/JobWdbeIexPrj.cpp | mpsitech/wdbe-WhizniumDBE | 27360ce6569dc55098a248b8a0a4b7e3913a6ce6 | [
"MIT"
] | 4 | 2020-10-27T14:33:25.000Z | 2021-08-07T20:55:42.000Z | wdbecmbd/IexWdbe/JobWdbeIexPrj.cpp | mpsitech/wdbe-WhizniumDBE | 27360ce6569dc55098a248b8a0a4b7e3913a6ce6 | [
"MIT"
] | null | null | null | wdbecmbd/IexWdbe/JobWdbeIexPrj.cpp | mpsitech/wdbe-WhizniumDBE | 27360ce6569dc55098a248b8a0a4b7e3913a6ce6 | [
"MIT"
] | null | null | null | /**
* \file JobWdbeIexPrj.cpp
* job handler for job JobWdbeIexPrj (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#ifdef WDBECMBD
#include <Wdbecmbd.h>
#else
#include <Wdbed.h>
#endif
#include "JobWdbeIexPrj.h"
#include "JobWdbeIexPrj_blks.cpp"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
// IP ns.cust --- INSERT
using namespace IexWdbePrj;
/******************************************************************************
class JobWdbeIexPrj
******************************************************************************/
JobWdbeIexPrj::JobWdbeIexPrj(
XchgWdbe* xchg
, DbsWdbe* dbswdbe
, const ubigint jrefSup
, const uint ixWdbeVLocale
) :
JobWdbe(xchg, VecWdbeVJob::JOBWDBEIEXPRJ, jrefSup, ixWdbeVLocale)
{
jref = xchg->addJob(dbswdbe, this, jrefSup);
// IP constructor.cust1 --- INSERT
// IP constructor.cust2 --- INSERT
changeStage(dbswdbe, VecVSge::IDLE);
// IP constructor.cust3 --- INSERT
};
JobWdbeIexPrj::~JobWdbeIexPrj() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
void JobWdbeIexPrj::reset(
DbsWdbe* dbswdbe
) {
if (ixVSge != VecVSge::IDLE) changeStage(dbswdbe, VecVSge::IDLE);
};
void JobWdbeIexPrj::parseFromFile(
DbsWdbe* dbswdbe
, const string& _fullpath
, const bool _xmlNotTxt
, const string& _rectpath
) {
if (ixVSge == VecVSge::IDLE) {
fullpath = _fullpath;
xmlNotTxt = _xmlNotTxt;
rectpath = _rectpath;
changeStage(dbswdbe, VecVSge::PARSE);
};
};
void JobWdbeIexPrj::import(
DbsWdbe* dbswdbe
) {
if (ixVSge == VecVSge::PRSDONE) changeStage(dbswdbe, VecVSge::IMPORT);
};
void JobWdbeIexPrj::reverse(
DbsWdbe* dbswdbe
) {
if (ixVSge == VecVSge::IMPERR) changeStage(dbswdbe, VecVSge::REVERSE);
};
void JobWdbeIexPrj::collect(
DbsWdbe* dbswdbe
, const map<uint,uint>& _icsWdbeVIop
) {
if (ixVSge == VecVSge::IDLE) {
icsWdbeVIop = _icsWdbeVIop;
changeStage(dbswdbe, VecVSge::COLLECT);
};
};
void JobWdbeIexPrj::exportToFile(
DbsWdbe* dbswdbe
, const string& _fullpath
, const bool _xmlNotTxt
, const bool _shorttags
) {
if ((ixVSge == VecVSge::IDLE) || (ixVSge == VecVSge::CLTDONE)) {
fullpath = _fullpath;
xmlNotTxt = _xmlNotTxt;
shorttags = _shorttags;
changeStage(dbswdbe, VecVSge::EXPORT);
};
};
void JobWdbeIexPrj::handleRequest(
DbsWdbe* dbswdbe
, ReqWdbe* req
) {
if (req->ixVBasetype == ReqWdbe::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
};
};
void JobWdbeIexPrj::changeStage(
DbsWdbe* dbswdbe
, uint _ixVSge
) {
bool reenter = true;
do {
if (ixVSge != _ixVSge) {
switch (ixVSge) {
case VecVSge::IDLE: leaveSgeIdle(dbswdbe); break;
case VecVSge::PARSE: leaveSgeParse(dbswdbe); break;
case VecVSge::PRSERR: leaveSgePrserr(dbswdbe); break;
case VecVSge::PRSDONE: leaveSgePrsdone(dbswdbe); break;
case VecVSge::IMPORT: leaveSgeImport(dbswdbe); break;
case VecVSge::IMPERR: leaveSgeImperr(dbswdbe); break;
case VecVSge::REVERSE: leaveSgeReverse(dbswdbe); break;
case VecVSge::COLLECT: leaveSgeCollect(dbswdbe); break;
case VecVSge::CLTDONE: leaveSgeCltdone(dbswdbe); break;
case VecVSge::EXPORT: leaveSgeExport(dbswdbe); break;
case VecVSge::DONE: leaveSgeDone(dbswdbe); break;
};
setStage(dbswdbe, _ixVSge);
reenter = false;
// IP changeStage.refresh1 --- INSERT
};
switch (_ixVSge) {
case VecVSge::IDLE: _ixVSge = enterSgeIdle(dbswdbe, reenter); break;
case VecVSge::PARSE: _ixVSge = enterSgeParse(dbswdbe, reenter); break;
case VecVSge::PRSERR: _ixVSge = enterSgePrserr(dbswdbe, reenter); break;
case VecVSge::PRSDONE: _ixVSge = enterSgePrsdone(dbswdbe, reenter); break;
case VecVSge::IMPORT: _ixVSge = enterSgeImport(dbswdbe, reenter); break;
case VecVSge::IMPERR: _ixVSge = enterSgeImperr(dbswdbe, reenter); break;
case VecVSge::REVERSE: _ixVSge = enterSgeReverse(dbswdbe, reenter); break;
case VecVSge::COLLECT: _ixVSge = enterSgeCollect(dbswdbe, reenter); break;
case VecVSge::CLTDONE: _ixVSge = enterSgeCltdone(dbswdbe, reenter); break;
case VecVSge::EXPORT: _ixVSge = enterSgeExport(dbswdbe, reenter); break;
case VecVSge::DONE: _ixVSge = enterSgeDone(dbswdbe, reenter); break;
};
// IP changeStage.refresh2 --- INSERT
} while (ixVSge != _ixVSge);
};
string JobWdbeIexPrj::getSquawk(
DbsWdbe* dbswdbe
) {
string retval;
// IP getSquawk --- RBEGIN
if ( (ixVSge == VecVSge::PARSE) || (ixVSge == VecVSge::PRSDONE) || (ixVSge == VecVSge::IMPORT) || (ixVSge == VecVSge::REVERSE) || (ixVSge == VecVSge::COLLECT) || (ixVSge == VecVSge::CLTDONE) || (ixVSge == VecVSge::EXPORT) ) {
if (ixWdbeVLocale == VecWdbeVLocale::ENUS) {
if (ixVSge == VecVSge::PARSE) retval = "parsing projects and versions";
else if (ixVSge == VecVSge::PRSDONE) retval = "projects and versions parsed";
else if (ixVSge == VecVSge::IMPORT) retval = "importing projects and versions (" + to_string(impcnt) + " records added)";
else if (ixVSge == VecVSge::REVERSE) retval = "reversing projects and versions import";
else if (ixVSge == VecVSge::COLLECT) retval = "collecting projects and versions for export";
else if (ixVSge == VecVSge::CLTDONE) retval = "projects and versions collected for export";
else if (ixVSge == VecVSge::EXPORT) retval = "exporting projects and versions";
};
} else if ( (ixVSge == VecVSge::PRSERR) || (ixVSge == VecVSge::IMPERR) ) {
retval = lasterror;
} else {
retval = VecVSge::getSref(ixVSge);
};
// IP getSquawk --- REND
return retval;
};
uint JobWdbeIexPrj::enterSgeIdle(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::IDLE;
fullpath = "";
xmlNotTxt = false;
rectpath = "";
lineno = 0;
impcnt = 0;
icsWdbeVIop.clear();
imeimproject.clear();
return retval;
};
void JobWdbeIexPrj::leaveSgeIdle(
DbsWdbe* dbswdbe
) {
// IP leaveSgeIdle --- INSERT
};
uint JobWdbeIexPrj::enterSgeParse(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::PRSDONE;
retval = nextIxVSgeSuccess;
nextIxVSgeFailure = VecVSge::PRSERR;
try {
IexWdbePrj::parseFromFile(fullpath, xmlNotTxt, rectpath, imeimproject);
} catch (SbeException& e) {
if (e.ix == SbeException::PATHNF) e.vals["path"] = "<hidden>";
lasterror = e.getSquawk(VecWdbeVError::getIx, VecWdbeVError::getTitle, ixWdbeVLocale);
retval = nextIxVSgeFailure;
};
return retval;
};
void JobWdbeIexPrj::leaveSgeParse(
DbsWdbe* dbswdbe
) {
// IP leaveSgeParse --- INSERT
};
uint JobWdbeIexPrj::enterSgePrserr(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::PRSERR;
// IP enterSgePrserr --- INSERT
return retval;
};
void JobWdbeIexPrj::leaveSgePrserr(
DbsWdbe* dbswdbe
) {
// IP leaveSgePrserr --- INSERT
};
uint JobWdbeIexPrj::enterSgePrsdone(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::PRSDONE;
// IP enterSgePrsdone --- INSERT
return retval;
};
void JobWdbeIexPrj::leaveSgePrsdone(
DbsWdbe* dbswdbe
) {
// IP leaveSgePrsdone --- INSERT
};
uint JobWdbeIexPrj::enterSgeImport(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::DONE;
retval = nextIxVSgeSuccess;
nextIxVSgeFailure = VecVSge::IMPERR;
ImeitemIMProject* prj = NULL;
ImeitemIMVersion* ver = NULL;
ImeitemIRMPersonMProject* prsRprj = NULL;
ImeitemIJMVersionState* verJste = NULL;
ImeitemIMRelease* rls = NULL;
ImeitemIRMLibraryMVersion* libRver = NULL;
uint num1;
// IP enterSgeImport.prep --- IBEGIN
WdbeMProject* prj_r = NULL;
ubigint grp;
grp = xchg->getRefPreset(VecWdbeVPreset::PREWDBEGROUP, jref);
ubigint own;
own = xchg->getRefPreset(VecWdbeVPreset::PREWDBEOWNER, jref);
vector<ubigint> refs;
map<string,ubigint> refsMchs; // by hsref
dbswdbe->loadRefsBySQL("SELECT ref FROM TblWdbeMMachine", false, refs);
for (unsigned int i = 0; i < refs.size(); i++) refsMchs[StubWdbe::getStubMchStd(dbswdbe, refs[i])] = refs[i];
time_t rawtime;
time(&rawtime);
vector<string> ss;
// IP enterSgeImport.prep --- IEND
try {
// IP enterSgeImport.traverse --- RBEGIN
// -- ImeIMProject
for (unsigned int ix0 = 0; ix0 < imeimproject.nodes.size(); ix0++) {
prj = imeimproject.nodes[ix0];
prj->grp = grp;
prj->own = own;
//prj->refWdbeMVersion: SUB
//prj->Short: TBL
//prj->Title: TBL
//prj->Easy: TBL
//prj->Giturl: TBL
//prj->Comment: TBL
if (dbswdbe->tblwdbemproject->loadRecBySQL("SELECT * FROM TblWdbeMProject WHERE Short = '" + prj->Short + "'", &prj_r)) {
prj->ref = prj_r->ref;
prj->grp = prj_r->grp;
prj->own = prj_r->own;
prj->refWdbeMVersion = prj_r->refWdbeMVersion;
prj->Short = prj_r->Short;
prj->Title = prj_r->Title;
prj->Easy = prj_r->Easy;
prj->Giturl = prj_r->Giturl;
prj->Comment = prj_r->Comment;
delete prj_r;
};
if (prj->ref == 0) {
dbswdbe->tblwdbemproject->insertRec(prj);
impcnt++;
};
num1 = 1;
for (unsigned int ix1 = 0; ix1 < prj->imeimversion.nodes.size(); ix1++) {
ver = prj->imeimversion.nodes[ix1];
ver->grp = grp;
ver->own = own;
ver->prjRefWdbeMProject = prj->ref;
ver->prjNum = num1++;
//ver->Major: TBL
//ver->Minor: TBL
//ver->Sub: TBL
//ver->refJState: SUB
if (ver->srefIxVState == "") ver->srefIxVState = "newimp";
ver->ixVState = VecWdbeVMVersionState::getIx(ver->srefIxVState);
if (ver->ixVState == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",ver->srefIxVState}, {"iel","srefIxVState"}, {"lineno",to_string(ver->lineno)}});
//ver->About: TBL
//ver->Comment: TBL
dbswdbe->tblwdbemversion->insertRec(ver);
impcnt++;
if (((ver->srefIxVState != "")) && ver->imeijmversionstate.nodes.empty()) {
verJste = new ImeitemIJMVersionState();
ver->imeijmversionstate.nodes.push_back(verJste);
verJste->refWdbeMVersion = ver->ref;
verJste->srefIxVState = ver->srefIxVState;
};
if (ix1 == 0) {
prj->refWdbeMVersion = ver->ref;
dbswdbe->tblwdbemproject->updateRec(prj);
};
for (unsigned int ix2 = 0; ix2 < ver->imeijmversionstate.nodes.size(); ix2++) {
verJste = ver->imeijmversionstate.nodes[ix2];
verJste->refWdbeMVersion = ver->ref;
verJste->x1Start = Ftm::invstamp("&now;");
verJste->ixVState = VecWdbeVMVersionState::getIx(verJste->srefIxVState);
if (verJste->ixVState == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",verJste->srefIxVState}, {"iel","srefIxVState"}, {"lineno",to_string(verJste->lineno)}});
dbswdbe->tblwdbejmversionstate->insertRec(verJste);
impcnt++;
if (ix2 == 0) {
ver->refJState = verJste->ref;
ver->ixVState = verJste->ixVState;
dbswdbe->tblwdbemversion->updateRec(ver);
};
};
for (unsigned int ix2 = 0; ix2 < ver->imeirmlibrarymversion.nodes.size(); ix2++) {
libRver = ver->imeirmlibrarymversion.nodes[ix2];
//libRver->refWdbeMLibrary: CUSTSQL
dbswdbe->tblwdbemlibrary->loadRefBySrf(libRver->srefRefWdbeMLibrary, libRver->refWdbeMLibrary);
if (libRver->refWdbeMLibrary == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",libRver->srefRefWdbeMLibrary}, {"iel","srefRefWdbeMLibrary"}, {"lineno",to_string(libRver->lineno)}});
libRver->refWdbeMVersion = ver->ref;
dbswdbe->tblwdbermlibrarymversion->insertRec(libRver);
impcnt++;
};
for (unsigned int ix2 = 0; ix2 < ver->imeimrelease.nodes.size(); ix2++) {
rls = ver->imeimrelease.nodes[ix2];
rls->ixVBasetype = VecWdbeVMReleaseBasetype::getIx(rls->srefIxVBasetype);
if (rls->ixVBasetype == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",rls->srefIxVBasetype}, {"iel","srefIxVBasetype"}, {"lineno",to_string(rls->lineno)}});
rls->refWdbeMVersion = ver->ref;
//rls->refWdbeMMachine: CUST
if (rls->hsrefRefWdbeMMachine != "") {
auto it = refsMchs.find(rls->hsrefRefWdbeMMachine);
if (it != refsMchs.end()) rls->refWdbeMMachine = it->second;
else throw SbeException(SbeException::IEX_TSREF, {{"tsref",rls->hsrefRefWdbeMMachine}, {"iel","hsrefRefWdbeMMachine"}, {"lineno",to_string(rls->lineno)}});
};
//rls->sref: TBL
//rls->srefsKOption: TBL
//rls->Comment: TBL
dbswdbe->tblwdbemrelease->insertRec(rls);
impcnt++;
};
};
for (unsigned int ix1 = 0; ix1 < prj->imeirmpersonmproject.nodes.size(); ix1++) {
prsRprj = prj->imeirmpersonmproject.nodes[ix1];
//prsRprj->refWdbeMPerson: THINT ; look for any person, format StubWdbePrsStd
StrMod::stringToVector(prsRprj->hintRefWdbeMPerson, ss, ' ');
if (ss.size() == 2) dbswdbe->loadRefBySQL("SELECT ref FROM TblWdbeMPerson WHERE Lastname = '" + StrMod::esc(ss[1]) + "' AND Firstname = '" + StrMod::esc(ss[0]) + "'", prsRprj->refWdbeMPerson);
prsRprj->refWdbeMProject = prj->ref;
//prsRprj->srefKFunction: TBL
dbswdbe->tblwdbermpersonmproject->insertRec(prsRprj);
impcnt++;
};
};
// IP enterSgeImport.traverse --- REND
// IP enterSgeImport.ppr --- INSERT
} catch (SbeException& e) {
lasterror = e.getSquawk(VecWdbeVError::getIx, VecWdbeVError::getTitle, ixWdbeVLocale);
retval = nextIxVSgeFailure;
};
return retval;
};
void JobWdbeIexPrj::leaveSgeImport(
DbsWdbe* dbswdbe
) {
// IP leaveSgeImport --- INSERT
};
uint JobWdbeIexPrj::enterSgeImperr(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::IMPERR;
// IP enterSgeImperr --- INSERT
return retval;
};
void JobWdbeIexPrj::leaveSgeImperr(
DbsWdbe* dbswdbe
) {
// IP leaveSgeImperr --- INSERT
};
uint JobWdbeIexPrj::enterSgeReverse(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::IDLE;
retval = nextIxVSgeSuccess;
ImeitemIMProject* prj = NULL;
ImeitemIMVersion* ver = NULL;
ImeitemIRMPersonMProject* prsRprj = NULL;
ImeitemIJMVersionState* verJste = NULL;
ImeitemIMRelease* rls = NULL;
ImeitemIRMLibraryMVersion* libRver = NULL;
// -- ImeIMProject
for (unsigned int ix0 = 0; ix0 < imeimproject.nodes.size(); ix0++) {
prj = imeimproject.nodes[ix0];
if (prj->ref != 0) dbswdbe->tblwdbemproject->removeRecByRef(prj->ref);
for (unsigned int ix1 = 0; ix1 < prj->imeimversion.nodes.size(); ix1++) {
ver = prj->imeimversion.nodes[ix1];
if (ver->ref != 0) dbswdbe->tblwdbemversion->removeRecByRef(ver->ref);
for (unsigned int ix2 = 0; ix2 < ver->imeijmversionstate.nodes.size(); ix2++) {
verJste = ver->imeijmversionstate.nodes[ix2];
if (verJste->ref != 0) dbswdbe->tblwdbejmversionstate->removeRecByRef(verJste->ref);
};
for (unsigned int ix2 = 0; ix2 < ver->imeimrelease.nodes.size(); ix2++) {
rls = ver->imeimrelease.nodes[ix2];
if (rls->ref != 0) dbswdbe->tblwdbemrelease->removeRecByRef(rls->ref);
};
for (unsigned int ix2 = 0; ix2 < ver->imeirmlibrarymversion.nodes.size(); ix2++) {
libRver = ver->imeirmlibrarymversion.nodes[ix2];
if (libRver->ref != 0) dbswdbe->tblwdbermlibrarymversion->removeRecByRef(libRver->ref);
};
};
for (unsigned int ix1 = 0; ix1 < prj->imeirmpersonmproject.nodes.size(); ix1++) {
prsRprj = prj->imeirmpersonmproject.nodes[ix1];
if (prsRprj->ref != 0) dbswdbe->tblwdbermpersonmproject->removeRecByRef(prsRprj->ref);
};
};
return retval;
};
void JobWdbeIexPrj::leaveSgeReverse(
DbsWdbe* dbswdbe
) {
// IP leaveSgeReverse --- INSERT
};
uint JobWdbeIexPrj::enterSgeCollect(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::CLTDONE;
retval = nextIxVSgeSuccess;
ImeitemIMProject* prj = NULL;
ImeitemIMVersion* ver = NULL;
ImeitemIRMPersonMProject* prsRprj = NULL;
ImeitemIJMVersionState* verJste = NULL;
ImeitemIMRelease* rls = NULL;
ImeitemIRMLibraryMVersion* libRver = NULL;
uint ixWdbeVIop;
vector<ubigint> refs;
Stcch* stcch = new Stcch(false);
// IP enterSgeCollect.traverse --- BEGIN
// -- ImeIMProject
for (unsigned int ix0 = 0; ix0 < imeimproject.nodes.size(); ix0++) {
prj = imeimproject.nodes[ix0];
if (prj->ref != 0) {
};
if (getIxWdbeVIop(icsWdbeVIop, VecVIme::IMEIMVERSION, ixWdbeVIop)) {
dbswdbe->tblwdbemversion->loadRefsByPrj(prj->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) prj->imeimversion.nodes.push_back(new ImeitemIMVersion(dbswdbe, refs[i]));
};
for (unsigned int ix1 = 0; ix1 < prj->imeimversion.nodes.size(); ix1++) {
ver = prj->imeimversion.nodes[ix1];
if (ver->ref != 0) {
};
if (getIxWdbeVIop(icsWdbeVIop, VecVIme::IMEIJMVERSIONSTATE, ixWdbeVIop)) {
dbswdbe->tblwdbejmversionstate->loadRefsByVer(ver->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) if (refs[i] == ver->refJState) {refs[i] = refs[0]; refs[0] = ver->refJState; break;};
for (unsigned int i = 0; i < refs.size(); i++) ver->imeijmversionstate.nodes.push_back(new ImeitemIJMVersionState(dbswdbe, refs[i]));
};
for (unsigned int ix2 = 0; ix2 < ver->imeijmversionstate.nodes.size(); ix2++) {
verJste = ver->imeijmversionstate.nodes[ix2];
if (verJste->ref != 0) {
};
};
if (getIxWdbeVIop(icsWdbeVIop, VecVIme::IMEIMRELEASE, ixWdbeVIop)) {
dbswdbe->tblwdbemrelease->loadRefsByVer(ver->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) ver->imeimrelease.nodes.push_back(new ImeitemIMRelease(dbswdbe, refs[i]));
};
for (unsigned int ix2 = 0; ix2 < ver->imeimrelease.nodes.size(); ix2++) {
rls = ver->imeimrelease.nodes[ix2];
if (rls->ref != 0) {
rls->hsrefRefWdbeMMachine = StubWdbe::getStubMchStd(dbswdbe, rls->refWdbeMMachine, ixWdbeVLocale, Stub::VecVNonetype::VOID, stcch);
};
};
if (getIxWdbeVIop(icsWdbeVIop, VecVIme::IMEIRMLIBRARYMVERSION, ixWdbeVIop)) {
dbswdbe->tblwdbermlibrarymversion->loadRefsByVer(ver->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) ver->imeirmlibrarymversion.nodes.push_back(new ImeitemIRMLibraryMVersion(dbswdbe, refs[i]));
};
for (unsigned int ix2 = 0; ix2 < ver->imeirmlibrarymversion.nodes.size(); ix2++) {
libRver = ver->imeirmlibrarymversion.nodes[ix2];
if (libRver->ref != 0) {
libRver->srefRefWdbeMLibrary = StubWdbe::getStubLibSref(dbswdbe, libRver->refWdbeMLibrary, ixWdbeVLocale, Stub::VecVNonetype::VOID, stcch);
};
};
};
if (getIxWdbeVIop(icsWdbeVIop, VecVIme::IMEIRMPERSONMPROJECT, ixWdbeVIop)) {
dbswdbe->tblwdbermpersonmproject->loadRefsByPrj(prj->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) prj->imeirmpersonmproject.nodes.push_back(new ImeitemIRMPersonMProject(dbswdbe, refs[i]));
};
for (unsigned int ix1 = 0; ix1 < prj->imeirmpersonmproject.nodes.size(); ix1++) {
prsRprj = prj->imeirmpersonmproject.nodes[ix1];
if (prsRprj->ref != 0) {
prsRprj->hintRefWdbeMPerson = StubWdbe::getStubPrsStd(dbswdbe, prsRprj->refWdbeMPerson, ixWdbeVLocale, Stub::VecVNonetype::VOID, stcch);
};
};
};
// IP enterSgeCollect.traverse --- END
// IP enterSgeCollect.ppr --- INSERT
delete stcch;
return retval;
};
void JobWdbeIexPrj::leaveSgeCollect(
DbsWdbe* dbswdbe
) {
// IP leaveSgeCollect --- INSERT
};
uint JobWdbeIexPrj::enterSgeCltdone(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::CLTDONE;
// IP enterSgeCltdone --- INSERT
return retval;
};
void JobWdbeIexPrj::leaveSgeCltdone(
DbsWdbe* dbswdbe
) {
// IP leaveSgeCltdone --- INSERT
};
uint JobWdbeIexPrj::enterSgeExport(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::DONE;
retval = nextIxVSgeSuccess;
IexWdbePrj::exportToFile(fullpath, xmlNotTxt, shorttags, imeimproject);
return retval;
};
void JobWdbeIexPrj::leaveSgeExport(
DbsWdbe* dbswdbe
) {
// IP leaveSgeExport --- INSERT
};
uint JobWdbeIexPrj::enterSgeDone(
DbsWdbe* dbswdbe
, const bool reenter
) {
uint retval = VecVSge::DONE;
// IP enterSgeDone --- INSERT
return retval;
};
void JobWdbeIexPrj::leaveSgeDone(
DbsWdbe* dbswdbe
) {
// IP leaveSgeDone --- INSERT
};
| 28.325905 | 226 | 0.673763 | [
"vector"
] |
31171953ef8fdbbe3ab67c1390ff5e9e73ca3c94 | 29,996 | cpp | C++ | Common/Drawer/ssplayer_render_gl.cpp | SpriteStudio/SpriteStudio6-SDK | f2ad84c8e3ca9d189904da9c3d1114bb4044eecb | [
"BSD-3-Clause"
] | 18 | 2017-11-08T05:14:20.000Z | 2022-03-29T01:18:50.000Z | Common/Drawer/ssplayer_render_gl.cpp | SpriteStudio/SpriteStudio6-SDK | f2ad84c8e3ca9d189904da9c3d1114bb4044eecb | [
"BSD-3-Clause"
] | 29 | 2017-11-14T03:28:34.000Z | 2022-03-15T11:18:29.000Z | Common/Drawer/ssplayer_render_gl.cpp | SpriteStudio/SpriteStudio6-SDK | f2ad84c8e3ca9d189904da9c3d1114bb4044eecb | [
"BSD-3-Clause"
] | 11 | 2017-11-08T05:11:12.000Z | 2021-04-02T22:20:40.000Z | #include <stdio.h>
#include <cstdlib>
#include "ssOpenGLSetting.h"
#include <map>
#include <memory>
#include "../Helper/OpenGL/SSTextureGL.h"
#include "../Animator/ssplayer_animedecode.h"
#include "../Animator/ssplayer_matrix.h"
#include "ssplayer_render_gl.h"
#include "ssplayer_shader_gl.h"
#include "ssplayer_cellmap.h"
#include "ssplayer_mesh.h"
#define SPRITESTUDIO6SDK_PROGRAMABLE_SHADER_ON (1)
namespace spritestudio6
{
//ISsRenderer* SsCurrentRenderer::m_currentrender = 0;
static const char* glshader_sprite_vs =
#include "GLSL/sprite.vs";
static const char* glshader_sprite_fs =
#include "GLSL/sprite.fs";
static const char* glshader_sprite_fs_pot =
#include "GLSL/sprite_pot.fs";
class SSOpenGLProgramObject;
struct ShaderSetting
{
char* name;
char* vs;
char* fs;
};
//MEMO: 現在デストラクト時に(定義リソースが)自動解放されることを期待しています。
// ※明示的な解放タイミングが見当たらないため。
static std::map<SsString, std::unique_ptr<SSOpenGLProgramObject>> s_DefaultShaderMap;
static const ShaderSetting glshader_default[] =
{
{
"system::default",
#include "GLSL/default.vs"
#include "GLSL/default.fs"
},
{
"ss-blur",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-blur.fs"
},
{
"ss-bmask",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-bmask.fs"
},
{
"ss-circle",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-circle.fs"
},
{
"ss-hsb",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-hsb.fs"
},
{
"ss-move",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-move.fs"
},
{
"ss-noise",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-noise.fs"
},
{
"ss-outline",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-outline.fs"
},
{
"ss-pix",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-pix.fs"
},
{
"ss-scatter",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-scatter.fs"
},
{
"ss-sepia",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-sepia.fs"
},
{
"ss-spot",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-spot.fs"
},
{
"ss-step",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-step.fs"
},
{
"ss-wave",
#include "GLSL/ss-common.vs"
#include "GLSL/ss-wave.fs"
},
{
NULL,
NULL,
NULL,
},
};
//bool SsRender::m_isInit = false;
enum{
PG_SHADER_NPOT,
PG_SHADER_POT,
};
//6.2対応
//パーツカラー、ミックス、頂点
/// カラー値を byte(0~255) -> float(0.0~1.0) に変換する。
inline float __fastcall floatFromByte_(u8 color8)
{
return static_cast<float>(color8) / 255.f;
}
/// RGBA の各値を byte(0~255) -> float(0.0~1.0) に変換し、配列 dest の[0,1,2,3] に設定する。
inline void __fastcall rgbaByteToFloat_(float* dest, const SsColorBlendValue& src)
{
const SsColor* srcColor = &src.rgba;
dest[0] = floatFromByte_((u8)srcColor->r);
dest[1] = floatFromByte_((u8)srcColor->g);
dest[2] = floatFromByte_((u8)srcColor->b);
dest[3] = floatFromByte_((u8)srcColor->a);
}
struct ShaderVArg;
static int s_iVArgCount = 0;
static ShaderVArg* s_pVArg = NULL;
/// // RGB=100%テクスチャ、A=テクスチャx頂点カラーの設定にする。
static void __fastcall setupTextureCombinerTo_NoBlendRGB_MultiplyAlpha_()
{
// カラーは100%テクスチャ
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0);
// αだけ合成
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
}
/**
ブレンドタイプに応じたテクスチャコンバイナの設定を行う (パーツカラー用)
rateOrAlpha ミックス時のみ参照される。単色では Rate に、頂点単位では Alpha になる。
target ミックス時のみ参照される。
参考:http://www.opengl.org/sdk/docs/man/xhtml/glTexEnv.xml
*/
static void __fastcall setupSimpleTextureCombiner_for_PartsColor_(SsBlendType::_enum type, float rateOrAlpha, SsColorBlendTarget::_enum target)
{
//static const float oneColor[4] = {1.f,1.f,1.f,1.f};
float constColor[4] = { 0.5f,0.5f,0.5f,rateOrAlpha };
static const GLuint funcs[] = { GL_INTERPOLATE, GL_MODULATE, GL_ADD, GL_SUBTRACT };
GLuint func = funcs[(int)type];
GLuint srcRGB = GL_TEXTURE0;
GLuint dstRGB = GL_PRIMARY_COLOR;
// true: 頂点αをブレンドする。
// false: constColor のαをブレンドする。
bool combineAlpha = true;
switch (type)
{
case SsBlendType::mix:
case SsBlendType::mul:
case SsBlendType::add:
case SsBlendType::sub:
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
// rgb
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, func);
// mix の場合、特殊
if (type == SsBlendType::mix)
{
if (target == SsColorBlendTarget::whole)
{
// 全体なら、const 値で補間する
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_CONSTANT);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, constColor);
}
else
{
// 頂点カラーのアルファをテクスチャに対する頂点カラーの割合にする。
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_PRIMARY_COLOR);
combineAlpha = false;
}
// 強度なので 1 に近付くほど頂点カラーが濃くなるよう SOURCE0 を頂点カラーにしておく。
std::swap(srcRGB, dstRGB);
}
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, srcRGB);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, dstRGB);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
break;
case SsBlendType::screen:
case SsBlendType::exclusion:
case SsBlendType::invert:
default:
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_CONSTANT);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
break;
}
if (combineAlpha)
{
// alpha は常に掛け算
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
}
else
{
#if 1
// 浮いた const 値を頂点αの代わりにブレンドする。v6.2.0+ 2018/06/21 endo
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_CONSTANT);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, constColor);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
#else
// ミックス+頂点単位の場合αブレンドはできない。
// αはテクスチャを100%使えれば最高だが、そうはいかない。
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
#endif
}
}
static SSOpenGLProgramObject* createProgramObject( const SsString& name, const SsString& vs, const SsString& fs )
{
SSOpenGLVertexShader* pVs = new SSOpenGLVertexShader( name, vs );
SSOpenGLFragmentShader* pFs = new SSOpenGLFragmentShader( name, fs );
SSOpenGLProgramObject* pPo = new SSOpenGLProgramObject();
pPo->Attach( pVs );
pPo->Attach( pFs );
if ( pPo->Link() != 0 ) {
if ( pVs )
delete pVs;
if ( pVs )
delete pFs;
if ( pPo )
delete pPo;
pVs = nullptr;
pFs = nullptr;
pPo = nullptr;
}
return pPo;
}
void SsRenderGL::clearShaderCache()
{
if ( s_pVArg ) free( s_pVArg );
s_iVArgCount = 0;
s_pVArg = NULL;
}
void SsRenderGL::initialize()
{
// if ( m_isInit ) return ;
SSOpenGLShaderMan::Create();
SSOpenGLVertexShader* vs = new SSOpenGLVertexShader( "basic_vs" , glshader_sprite_vs );
SSOpenGLFragmentShader* fs1 = new SSOpenGLFragmentShader( "normal_fs" , glshader_sprite_fs );
SSOpenGLFragmentShader* fs2 = new SSOpenGLFragmentShader( "pot_fs" ,glshader_sprite_fs_pot );
SSOpenGLProgramObject* pgo1 = new SSOpenGLProgramObject();
SSOpenGLProgramObject* pgo2 = new SSOpenGLProgramObject();
pgo1->Attach( vs );
pgo1->Attach( fs1 );
pgo1->Link();
SSOpenGLShaderMan::PushPgObject( pgo1 );
pgo2->Attach( vs );
pgo2->Attach( fs2 );
pgo2->Link();
SSOpenGLShaderMan::PushPgObject( pgo2 );
s_DefaultShaderMap.clear();
for ( int i = 0; glshader_default[i].name != nullptr; i++ ) {
s_DefaultShaderMap[glshader_default[i].name].reset( createProgramObject( glshader_default[i].name, glshader_default[i].vs, glshader_default[i].fs ) );
}
// m_isInit = true;
}
void SsRenderGL::renderSetup()
{
glDisableClientState( GL_COLOR_ARRAY );
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0 );
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.0);
glBlendEquation( GL_FUNC_ADD );
/*
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.0);
*/
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void SsRenderGL::SetAlphaBlendMode(SsBlendType::_enum type)
{
glBlendEquation( GL_FUNC_ADD );
switch ( type )
{
case SsBlendType::mix: //< 0 ブレンド(ミックス)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case SsBlendType::mul: //< 1 乗算
glBlendFunc(GL_ZERO, GL_SRC_COLOR);
break;
case SsBlendType::add: //< 2 加算
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case SsBlendType::sub: //< 3 減算
// TODO SrcAlpha を透明度として使えない
glBlendEquation( GL_FUNC_REVERSE_SUBTRACT );
#if USE_GLEW
glBlendFuncSeparateEXT( GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_DST_ALPHA );
#else
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_DST_ALPHA);
#endif
break;
case SsBlendType::mulalpha: //< 4 α乗算
glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA);
break;
case SsBlendType::screen: //< 5 スクリーン
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
break;
case SsBlendType::exclusion: //< 6 除外
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR);
break;
case SsBlendType::invert: //< 7 反転
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
break;
}
}
void SsRenderGL::renderSpriteSimple( float matrix[16],
int width, int height,
SsVector2& pivot ,
SsVector2 uv1, SsVector2 uv2,
const SsFColor& color )
{
glPushMatrix();
// update で計算しておいた行列をロード
glLoadMatrixf(matrix);
float w = width / 2.0f ;
float h = height / 2.0f ;
glColor4f(color.r, color.g, color.b, color.a);
float vtx[8];
vtx[0] = -w - pivot.x;
vtx[1] = h - pivot.y;
vtx[2] = -w - pivot.x;
vtx[3] = -h - pivot.y;
vtx[4] = w - pivot.x;
vtx[5] = -h - pivot.y;
vtx[6] = w - pivot.x;
vtx[7] = h - pivot.y;
glVertexPointer(2, GL_FLOAT, 0, vtx);
float tuv[8];
tuv[0] = uv1.x; tuv[1] = uv1.y;
tuv[2] = uv1.x; tuv[3] = uv2.y;
tuv[4] = uv2.x; tuv[5] = uv2.y;
tuv[6] = uv2.x; tuv[7] = uv1.y;
glTexCoordPointer(2, GL_FLOAT, 0, tuv);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
}
void SsRenderGL::SetTexture( SsCellValue* cellvalue )
{
int gl_target = GL_TEXTURE_2D;
bool texture_is_pow2 = true;
if ( cellvalue == 0 ){
return ;
}
SsCell * cell = cellvalue->cell;
if ( cell == 0 ){
return ;
}
ISSTexture* texture = cellvalue->texture;
if ( texture == 0 ){
return ;
}
SsPoint2 texturePixelSize;
texturePixelSize.x = cellvalue->texture->getWidth();
texturePixelSize.y = cellvalue->texture->getHeight();
if (texture)
{
// テクスチャのサイズが2のべき乗かチェック
if ( texture->isPow2() )
{
// 2のべき乗
texture_is_pow2 = true;
gl_target = GL_TEXTURE_2D;
}
else
{
// 2のべき乗ではない:NPOTテクスチャ
texture_is_pow2 = false;
#if USE_GLEW
gl_target = GL_TEXTURE_RECTANGLE_ARB;
#else
gl_target = GL_TEXTURE_RECTANGLE;
#endif
}
glEnable(gl_target);
SSTextureGL* tex_gl = (SSTextureGL*)texture;
glBindTexture(gl_target, tex_gl->tex);
}
}
void SsRenderGL::clearMask()
{
glClear( GL_STENCIL_BUFFER_BIT );
enableMask(false);
}
void SsRenderGL::enableMask(bool flag)
{
if (flag)
{
glEnable(GL_STENCIL_TEST);
}else{
glDisable(GL_STENCIL_TEST);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
}
void SsRenderGL::execMask(SsPartState* state)
{
glEnable(GL_STENCIL_TEST);
if (state->partType == SsPartType::mask)
//if(0)
{
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
if (!(state->maskInfluence )) { //マスクが有効では無い=重ね合わせる
glStencilFunc(GL_ALWAYS, 1, ~0); //常に通過
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
//描画部分を1へ
}
else {
glStencilFunc(GL_ALWAYS, 1, ~0); //常に通過
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
}
glEnable(GL_ALPHA_TEST);
//この設定だと
//1.0fでは必ず抜けないため非表示フラグなし(=1.0f)のときの挙動は考えたほうがいい
//不透明度からマスク閾値へ変更
float mask_alpha = (float)(255 - state->masklimen ) / 255.0f;
glAlphaFunc(GL_GREATER, mask_alpha);
;
state->alpha = 1.0f;
}
else {
if ((state->maskInfluence )) //パーツに対してのマスクが有効か否か
{
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_NOTEQUAL, 0x1, 0x1); //1と等しい
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
}
else {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDisable(GL_STENCIL_TEST);
}
// 常に無効
glDisable(GL_ALPHA_TEST);
}
}
/**
中央頂点(index=4)のRGBA%値の計算
[in/out] colors, rates の [0~3] の平均値を [4] に入れる。
*/
inline void __fastcall calcCenterVertexColor(float* colors, float* rates, float* vertexID)
{
float a, r, g, b, rate;
a = r = g = b = rate = 0;
for (int i = 0; i < 4; i++)
{
int idx = i * 4;
a += colors[idx++];
r += colors[idx++];
g += colors[idx++];
b += colors[idx++];
rate += rates[i];
}
//きれいな頂点変形への対応
vertexID[4 * 2] = 4;
vertexID[4 * 2 + 1] = 4;
int idx = 4 * 4;
colors[idx++] = a / 4.0f;
colors[idx++] = r / 4.0f;
colors[idx++] = g / 4.0f;
colors[idx++] = b / 4.0f;
rates[4] = rate / 4.0f;
}
struct ShaderVArg
{
float fSrcRatio;
float fDstRatio;
float fDstSrcRatio;
float fReserved;
};
struct ShaderFArg
{
float fTexW;
float fTexH;
float fPixTX;
float fPixTY;
float fCoordLU;
float fCoordTV;
float fCoordCU;
float fCoordCV;
float fCoordRU;
float fCoordBV;
float fPMA;
float fReserved1;
float fReserved2;
float fReserved3;
float fReserved4;
float fReserved5;
};
void SsRenderGL::renderMesh(SsMeshPart* mesh , float alpha )
{
if (mesh == 0)return;
glPushMatrix();
if (alpha == 0.0f)
{
return;
}
glMatrixMode(GL_MODELVIEW);
if (mesh->isBind)
{
//glLoadMatrixf(mesh->myPartState->matrix);
glLoadIdentity();
}
else {
glLoadMatrixf(mesh->myPartState->matrixLocal);
}
bool texture_is_pow2 = true;
int gl_target = GL_TEXTURE_2D;
if (mesh->targetTexture)
{
// テクスチャのサイズが2のべき乗かチェック
if (mesh->targetTexture->isPow2())
{
// 2のべき乗
texture_is_pow2 = true;
gl_target = GL_TEXTURE_2D;
}
else
{
// 2のべき乗ではない:NPOTテクスチャ
texture_is_pow2 = false;
#if USE_GLEW
gl_target = GL_TEXTURE_RECTANGLE_ARB;
#else
gl_target = GL_TEXTURE_RECTANGLE;
#endif
}
glEnable(gl_target);
SSTextureGL* tex_gl = (SSTextureGL*)mesh->targetTexture;
glBindTexture(gl_target, tex_gl->tex);
}
SsPartState* state = mesh->myPartState;
// パーツカラーの指定
std::vector<float>& colorsRaw = *(mesh->colors.get());
if (state->is_parts_color)
{
// パーツカラーがある時だけブレンド計算する
float setcol[4];
if (state->partsColorValue.target == SsColorBlendTarget::whole)
{
// 単色
const SsColorBlendValue& cbv = state->partsColorValue.color;
setupSimpleTextureCombiner_for_PartsColor_(state->partsColorValue.blendType, cbv.rate, state->partsColorValue.target);
rgbaByteToFloat_(setcol, cbv);
}
else
{
//4頂点はとりあえず左上のRGBAと Rate
const SsColorBlendValue& cbv = state->partsColorValue.colors[0];
// コンバイナの設定は常に単色として行う。
setupSimpleTextureCombiner_for_PartsColor_(state->partsColorValue.blendType, cbv.rate, SsColorBlendTarget::whole);
rgbaByteToFloat_(setcol, cbv);
if (state->partsColorValue.blendType == SsBlendType::mix)
{
setcol[3] = 1; // ミックス-頂点単位では A に Rate が入っておりアルファは無効なので1にしておく。
}
}
for (size_t i = 0; i < mesh->ver_size; i++)
{
colorsRaw[i * 4 + 0] = setcol[0];
colorsRaw[i * 4 + 1] = setcol[1];
colorsRaw[i * 4 + 2] = setcol[2];
colorsRaw[i * 4 + 3] = setcol[3] *alpha; // 不透明度を適用する。
}
}
else {
//WaitColor;
//ウェイトカラーの合成色を頂点カラーとして使用(パーセント円の流用
for (size_t i = 0; i < mesh->ver_size; i++)
{
colorsRaw[i * 4 + 0] = 1.0f;
colorsRaw[i * 4 + 1] = 1.0f;
colorsRaw[i * 4 + 2] = 1.0f;
colorsRaw[i * 4 + 3] = alpha;
}
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0);
// αだけ合成
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
}
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
// UV 配列を指定する
glTexCoordPointer(2, GL_FLOAT, 0, (GLvoid *)((mesh->uvs.get())->data()));
// 頂点色を指定する
glColorPointer(4, GL_FLOAT, 0, (GLvoid *)((mesh->colors.get())->data()));
// 頂点バッファの設定
glVertexPointer(3, GL_FLOAT, 0, (GLvoid *)((mesh->draw_vertices.get())->data()));
glDrawElements(GL_TRIANGLES, mesh->tri_size * 3, GL_UNSIGNED_SHORT, (mesh->indices.get())->data());
glPopMatrix();
if (texture_is_pow2 == false)
{
glDisable(gl_target);
}
glDisable(GL_TEXTURE_2D);
//ブレンドモード 減算時の設定を戻す
glBlendEquation(GL_FUNC_ADD);
}
void SsRenderGL::renderPart( SsPartState* state )
{
bool texture_is_pow2 = true;
bool color_blend_v4 = false;
float fTexW = 16.0f;
float fTexH = 16.0f;
float fPixTX = 1.0f;
float fPixTY = 1.0f;
float fCoordLU = 0.0f;
float fCoordTV = 0.0f;
float fCoordCU = 0.0f;
float fCoordCV = 0.0f;
float fCoordRU = 0.0f;
float fCoordBV = 0.0f;
float vertexID[10];
// bool colorBlendEnabled = false;
bool partsColorEnabled = false;
bool alphaBlendMix = false;
int gl_target = GL_TEXTURE_2D;
float rates[5];
SSOpenGLProgramObject* pPrgObject = nullptr;
if ( state->hide ) return ; //非表示なので処理をしない
SsCell * cell = state->cellValue.cell;
if ( cell == 0 ) return ;
ISSTexture* texture = state->cellValue.texture;
if ( texture == 0 ) return ;
SsPoint2 texturePixelSize;
texturePixelSize.x = state->cellValue.texture->getWidth();
texturePixelSize.y = state->cellValue.texture->getHeight();
execMask(state);
//Ver6 ローカル不透明度対応
float alpha = state->alpha;
if (state->localalpha != 1.0f)
{
alpha = state->localalpha;
}
if (cell)
{
for ( int i = 0 ; i < 5 ; i++ ) rates[i] = 0.0f;
}else{
for ( int i = 0 ; i < 5 ; i++ ) rates[i] = 1.0f;
}
if (cell)
{
// テクスチャのサイズが2のべき乗かチェック
if ( texture->isPow2() )
{
// 2のべき乗
texture_is_pow2 = true;
gl_target = GL_TEXTURE_2D;
}
else
{
// 2のべき乗ではない:NPOTテクスチャ
texture_is_pow2 = false;
#if USE_GLEW
gl_target = GL_TEXTURE_RECTANGLE_ARB;
#else
gl_target = GL_TEXTURE_RECTANGLE;
#endif
}
glEnable(gl_target);
#if SPRITESTUDIO6SDK_PROGRAMABLE_SHADER_ON
if ( state->is_shader ) {
std::map<SsString, std::unique_ptr<SSOpenGLProgramObject>>::const_iterator it = s_DefaultShaderMap.find( state->shaderValue.id );
if ( it != s_DefaultShaderMap.end() ) {
pPrgObject = s_DefaultShaderMap[state->shaderValue.id].get();
}
}
if ( !pPrgObject ) {
std::map<SsString, std::unique_ptr<SSOpenGLProgramObject>>::const_iterator it = s_DefaultShaderMap.find( "system::default" );
if ( it != s_DefaultShaderMap.end() ) {
pPrgObject = s_DefaultShaderMap["system::default"].get();
}
}
// if ( glpgObject )
if ( pPrgObject )
{
glActiveTexture(GL_TEXTURE0);
}
#endif
SSTextureGL* tex_gl = (SSTextureGL*)texture;
glBindTexture(gl_target, tex_gl->tex);
// フィルタ
GLint filterMode;
SsTexFilterMode::_enum fmode = state->cellValue.filterMode;
SsTexWrapMode::_enum wmode = state->cellValue.wrapMode;
switch (fmode)
{
default:
case SsTexFilterMode::nearlest:
filterMode = GL_NEAREST;
break;
case SsTexFilterMode::linear:
filterMode = GL_LINEAR;
break;
}
glTexParameteri(gl_target, GL_TEXTURE_MIN_FILTER, filterMode);
glTexParameteri(gl_target, GL_TEXTURE_MAG_FILTER, filterMode);
// ラップモード
GLint wrapMode;
switch (wmode)
{
default:
case SsTexWrapMode::clamp:
wrapMode = GL_CLAMP_TO_EDGE;
if (texture_is_pow2 == false)
{
wrapMode = GL_CLAMP;
}
break;
case SsTexWrapMode::repeat:
wrapMode = GL_REPEAT; // TODO 要動作確認
break;
case SsTexWrapMode::mirror:
wrapMode = GL_MIRRORED_REPEAT; // TODO 要動作確認
break;
}
glTexParameteri(gl_target, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(gl_target, GL_TEXTURE_WRAP_T, wrapMode);
// セルが持つUV値をまず設定
std::memcpy( state->uvs, state->cellValue.uvs, sizeof( state->uvs ));
// UV アニメの適用
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
float uvw = state->cellValue.uvs[3].x + state->cellValue.uvs[0].x;
float uvh = state->cellValue.uvs[3].y + state->cellValue.uvs[0].y;
SsVector2 uv_trans;
if (texture_is_pow2)
{
uv_trans.x = state->uvTranslate.x;
uv_trans.y = state->uvTranslate.y;
fTexW = texturePixelSize.x;
fTexH = texturePixelSize.y;
}
else
{
uv_trans.x = state->uvTranslate.x * texturePixelSize.x;
uv_trans.y = state->uvTranslate.y * texturePixelSize.y;
//中心座標を計算
uvw*= texturePixelSize.x;
uvh*= texturePixelSize.y;
fTexW = texturePixelSize.x;
fTexH = texturePixelSize.y;
}
uvw/=2.0f;
uvh/=2.0f;
glTranslatef( uvw + uv_trans.x , uvh + uv_trans.y , 0 );
glRotatef( state->uvRotation, 0.0, 0.0, 1.0);
float uvsh = state->uvScale.x;
float uvsv = state->uvScale.y;
if ( state->imageFlipH ) uvsh*=-1;
if ( state->imageFlipV ) uvsv*=-1;
glScalef( uvsh , uvsv , 0.0);
glTranslatef( -uvw , -uvh , 0 );
glMatrixMode(GL_MODELVIEW);
// オリジナルUVをまず指定する
// 左下が 0,0 Z字順
static const int sUvOrders[][4] = {
{0, 1, 2, 3}, // フリップなし
{1, 0, 3, 2}, // 水平フリップ
{2, 3, 0, 1}, // 垂直フリップ
{3, 2, 1, 0}, // 両方フリップ
};
//memset( state->uvs , 0 , sizeof(float) * 10 );
// イメージのみのフリップ対応
int order = ( state->hFlip == true ? 1 : 0 ) + ( state->vFlip == true ? 1 :0 ) * 2;
float uvs[10];
memset(uvs, 0, sizeof(float) * 10);
const int * uvorder = &sUvOrders[order][0];
if (texture_is_pow2)
{
fPixTX = 1.0f / texturePixelSize.x;
fPixTY = 1.0f / texturePixelSize.y;
}
fCoordCU = 0.0f;
fCoordCV = 0.0f;
for (int i = 0; i < 4; ++i)
{
int idx = *uvorder;
if (texture_is_pow2 == false)
{
// GL_TEXTURE_RECTANGLE_ARBではuv座標系が0~1ではなくピクセルになるので変換
uvs[idx * 2] = state->cellValue.uvs[i].x * texturePixelSize.x;
uvs[idx * 2 + 1] = state->cellValue.uvs[i].y * texturePixelSize.y;
#if SPRITESTUDIO6SDK_USE_TRIANGLE_FIN
//きれいな頂点変形への対応
uvs[4 * 2] += uvs[idx * 2];
uvs[4 * 2 + 1] += uvs[idx * 2 + 1];
#endif
}
else
{
uvs[idx * 2] = state->cellValue.uvs[i].x;
uvs[idx * 2 + 1] = state->cellValue.uvs[i].y;
#if SPRITESTUDIO6SDK_USE_TRIANGLE_FIN
//きれいな頂点変形への対応
uvs[4 * 2] += uvs[idx * 2];
uvs[4 * 2 + 1] += uvs[idx * 2 + 1];
#endif
}
if ( i == 0 ) {
fCoordLU = uvs[idx * 2];
fCoordTV = uvs[idx * 2 + 1];
fCoordRU = uvs[idx * 2];
fCoordBV = uvs[idx * 2 + 1];
}else{
fCoordLU = fCoordLU > uvs[idx * 2] ? uvs[idx * 2] : fCoordLU;
fCoordTV = fCoordTV > uvs[idx * 2 + 1] ? uvs[idx * 2 + 1] : fCoordTV;
fCoordRU = fCoordRU < uvs[idx * 2] ? uvs[idx * 2] : fCoordRU;
fCoordBV = fCoordBV < uvs[idx * 2 + 1] ? uvs[idx * 2 + 1] : fCoordBV;
}
fCoordCU += uvs[idx * 2];
fCoordCV += uvs[idx * 2 + 1];
++uvorder;
}
#if SPRITESTUDIO6SDK_USE_TRIANGLE_FIN
//きれいな頂点変形への対応
uvs[4*2]/=4.0f;
uvs[4*2+1]/=4.0f;
#endif
fCoordCU *= 0.25f;
fCoordCV *= 0.25f;
// UV 配列を指定する
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, (GLvoid *)uvs);
}else{
//セルがない状態というのは本当は有効な状態ではないような気がするがNANが入るので何かを入れる
for ( int i =0 ; i < 10 ; i ++ ) state->uvs[i] = 0;
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, (GLvoid *)state->uvs);
//テクスチャのバインドを解除する 状況が不定になるため
glBindTexture(gl_target, 0);
}
// αブレンドの設定
SetAlphaBlendMode( state->alphaBlendType );
//メッシュの場合描画
if (state->partType == SsPartType::mesh)
{
this->renderMesh(state->meshPart.get() , alpha );
return;
}
// パーツカラーの指定
if (state->is_parts_color)
{
partsColorEnabled = true;
//6.2対応 パーツカラー、頂点、ミックス時に不透明度を適用する
// パーツカラーがある時だけブレンド計算する
if (state->partsColorValue.target == SsColorBlendTarget::whole)
{
// 単色
const SsColorBlendValue& cbv = state->partsColorValue.color;
setupSimpleTextureCombiner_for_PartsColor_(state->partsColorValue.blendType, cbv.rate, state->partsColorValue.target);
rgbaByteToFloat_(state->colors, cbv);
state->colors[0 + 3] *= alpha; // 不透明度を掛ける
rates[0] = 1.0f;
vertexID[0] = 0;
// 残り3つは先頭のをコピー
for (int i = 1; i < 5; ++i)
{
memcpy(state->colors + i * 4, state->colors, sizeof(state->colors[0]) * 4);
rates[i] = 1.0f;
vertexID[i * 2] = 0;
vertexID[i * 2 + 1] = 0;
//vertexID[i] = 0;
}
}
else
{
// 頂点単位
setupSimpleTextureCombiner_for_PartsColor_(state->partsColorValue.blendType, alpha, state->partsColorValue.target); // ミックス用に const に不透明度を入れておく。
for (int i = 0; i < 4; ++i)
{
const SsColorBlendValue& cbv = state->partsColorValue.colors[i];
rgbaByteToFloat_(state->colors + i * 4, cbv);
// 不透明度も掛ける (ミックスの場合、Rate として扱われるので不透明度を掛けてはいけない)
if (state->partsColorValue.blendType != SsBlendType::mix)
{
state->colors[i * 4 + 3] *= alpha;
}
rates[i] = 1.0f;
vertexID[i * 2] = i;
vertexID[i * 2 + 1] = i;
}
#if SPRITESTUDIO6SDK_USE_TRIANGLE_FIN
// 中央頂点(index=4)のRGBA%値の計算
calcCenterVertexColor(state->colors, rates, vertexID);
#else
// クリアしとく
state->colors[4 * 4 + 0] = 0;
state->colors[4 * 4 + 1] = 0;
state->colors[4 * 4 + 2] = 0;
state->colors[4 * 4 + 3] = 0;
rates[4] = 0;
#endif
}
}
else
{
// パーツカラー無し
for (int i = 0; i < 5; ++i)
state->colors[i * 4 + 3] = alpha;
// RGB=100%テクスチャ、A=テクスチャx頂点カラーの設定にする。
setupTextureCombinerTo_NoBlendRGB_MultiplyAlpha_();
}
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, 0, (GLvoid *)state->colors);
// 頂点バッファの設定
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, (GLvoid *)state->vertices);
glPushMatrix();
// update で計算しておいた行列をロード
glMatrixMode(GL_MODELVIEW);
// glLoadMatrixf(state->matrix);
glLoadMatrixf(state->matrixLocal); //Ver6 ローカルスケール対応
GLint VertexLocation = -1;
if (state->noCells)
{
//セルが無いので描画を行わない
}else{
#if SPRITESTUDIO6SDK_PROGRAMABLE_SHADER_ON
if ( state->is_shader )
{
// if ( glpgObject )
if ( pPrgObject )
{
GLint uid;
int type = (int)state->partsColorValue.blendType;
if ( state->meshPart && cell && cell->ismesh )
{
int iCount = state->meshPart->targetCell->meshPointList.size();
if ( s_iVArgCount < iCount ) {
clearShaderCache();
s_pVArg = (ShaderVArg*)malloc( sizeof( ShaderVArg ) * iCount );
s_iVArgCount = iCount;
}
for ( int i = 0; i < iCount; i++ ) {
s_pVArg[i].fSrcRatio = type <= 1 ? 1.0f - rates[0] : 1.0f;
s_pVArg[i].fDstRatio = type == 3 ? -rates[0] : rates[0];
s_pVArg[i].fDstSrcRatio = type == 1 ? 1.0f : 0.0f;
s_pVArg[i].fReserved = 0.0f;
}
}else{
int iCount = 5;
if ( s_iVArgCount < iCount ) {
clearShaderCache();
s_pVArg = (ShaderVArg*)malloc( sizeof( ShaderVArg ) * iCount );
s_iVArgCount = iCount;
}
for ( int i = 0; i < iCount; i++ ) {
s_pVArg[i].fSrcRatio = type <= 1 ? 1.0f - rates[i] : 1.0f;
s_pVArg[i].fDstRatio = type == 3 ? -rates[i] : rates[i];
s_pVArg[i].fDstSrcRatio = type == 1 ? 1.0f : 0.0f;
s_pVArg[i].fReserved = 0.0f;
}
}
VertexLocation = pPrgObject->GetAttribLocation( "varg" );
if ( VertexLocation >= 0 ) {
glVertexAttribPointer( VertexLocation , 4 , GL_FLOAT , GL_FALSE, 0, s_pVArg);//GL_FALSE→データを正規化しない
glEnableVertexAttribArray(VertexLocation);//有効化
}
//シェーダのセットアップ
pPrgObject->Enable();
uid = pPrgObject->GetUniformLocation( "args" );
if ( uid >= 0 ) {
ShaderFArg args;
args.fTexW = fTexW;
args.fTexH = fTexH;
args.fPixTX = fPixTX;
args.fPixTY = fPixTY;
args.fCoordLU = fCoordLU;
args.fCoordTV = fCoordTV;
args.fCoordCU = fCoordCU;
args.fCoordCV = fCoordCV;
args.fCoordRU = fCoordRU;
args.fCoordBV = fCoordBV;
args.fPMA = 0.0f;
args.fReserved1 = 0.0f;
args.fReserved2 = 0.0f;
args.fReserved3 = 0.0f;
args.fReserved4 = 0.0f;
args.fReserved5 = 0.0f;
if (
( !state->cellValue.texture )
) {
memset( &args, 0, sizeof( args ) );
}
glUniform1fv( uid, sizeof( args ) / sizeof( float ), (float*)&args );
}
uid = pPrgObject->GetUniformLocation( "params" );
if ( uid >= 0 ) {
glUniform1fv( uid, sizeof( state->shaderValue.param ) / sizeof( float ), state->shaderValue.param );
}
}
}
#endif
#if SPRITESTUDIO6SDK_USE_TRIANGLE_FIN
if ( state->is_vertex_transform || state->is_parts_color)
{
static const GLubyte indices[] = { 4 , 3, 1, 0, 2 , 3};
glDrawElements(GL_TRIANGLE_FAN, 6, GL_UNSIGNED_BYTE, indices);
}else{
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
#else
// 頂点配列を描画
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
#endif
}
#if SPRITESTUDIO6SDK_PROGRAMABLE_SHADER_ON
// if ( glpgObject )
{
if ( state->is_shader )
{
// if ( glpgObject )
if ( pPrgObject )
{
if ( VertexLocation >= 0 ) {
glDisableVertexAttribArray(VertexLocation);//無効化
}
pPrgObject->Disable();
}
}
}
#endif
glPopMatrix();
if (texture_is_pow2 == false)
{
glDisable(gl_target);
}
glDisable(GL_TEXTURE_2D);
//ブレンドモード 減算時の設定を戻す
glBlendEquation( GL_FUNC_ADD );
}
} // namespace spritestudio6
| 22.89771 | 152 | 0.678124 | [
"mesh",
"vector"
] |
311e28cf293497dfc33abe18555129d1f463e024 | 2,323 | hpp | C++ | CanteraPFR/include/CanteraPFR/ConstAreaPFR.hpp | waltermateriais/CanteraPFR | 46437e39793ad45897c658dd2cd5aaf8d9e9c04c | [
"Unlicense"
] | 8 | 2019-12-29T20:52:45.000Z | 2021-11-10T08:38:17.000Z | CanteraPFR/include/CanteraPFR/ConstAreaPFR.hpp | waltermateriais/CanteraPFR | 46437e39793ad45897c658dd2cd5aaf8d9e9c04c | [
"Unlicense"
] | null | null | null | CanteraPFR/include/CanteraPFR/ConstAreaPFR.hpp | waltermateriais/CanteraPFR | 46437e39793ad45897c658dd2cd5aaf8d9e9c04c | [
"Unlicense"
] | 2 | 2019-04-22T21:28:35.000Z | 2022-02-21T15:36:45.000Z | // ***************************************************************************
// Provides a generic constant area plug-flow reactor model.
//
// Author : Walter Dal'Maz Silva
// Date : December 30th 2018
// ***************************************************************************
#ifndef __CONSTAREAPFR_HPP__
#define __CONSTAREAPFR_HPP__
#include "CanteraPFR/CanteraPFR.hpp"
namespace Cantera
{
class ConstAreaPFR : public CanteraPFR
{
public:
ConstAreaPFR(std::string const& mech,
std::string phase,
doublereal Di,
doublereal T0,
doublereal p0,
std::string X0,
doublereal Q0,
unsigned neqs_extra_)
: CanteraPFR{mech, phase, T0, p0, X0, neqs_extra_},
m_Ac{circleArea(Di)},
m_u0{setVelocity(Q0)}
{}
virtual int getInitialConditions(const doublereal t0,
doublereal *const y,
doublereal *const ydot) = 0;
virtual int evalResidNJ(const doublereal t,
const doublereal delta_t,
const doublereal* const y,
const doublereal* const ydot,
doublereal* const resid,
const ResidEval_Type_Enum evalType = Base_ResidEval,
const int id_x = -1,
const doublereal delta_x = 0.0) = 0;
//! Compute inlet velocity.
virtual const doublereal setVelocity(doublereal Q0) const
{
return (m_rho_ref / m_gas->density()) * sccmTocmps(Q0) / m_Ac;
}
//! Pressure drop model of viscous loss.
virtual const doublereal viscousLoss(doublereal u) const
{
// TODO Re number test.
return 8 * m_mu() * u * Cantera::Pi / m_Ac;
}
protected:
//! Reactor cross-sectional area.
const doublereal m_Ac = 0.0;
//! Inlet velocity.
const doublereal m_u0 = 0.0;
}; // (class ConstAreaPFR)
} // (namespace Cantera)
#endif // (__CONSTAREAPFR_HPP__)
// ***************************************************************************
// EOF
// ***************************************************************************
| 31.391892 | 80 | 0.470512 | [
"model"
] |
311e3d4648ac5aada90b58d8687196b7a81e1b8b | 1,289 | cpp | C++ | week27/I.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | 3 | 2020-05-31T08:41:56.000Z | 2020-09-27T15:14:03.000Z | week27/I.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | null | null | null | week27/I.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | null | null | null | #pragma comment(linker, "/stack:247474112")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
template<typename T=int>
inline void oo(const string &str, T val) { cerr << str << val << endl; }
template<typename T=int>
inline T read() {
T x;
cin >> x;
return x;
}
#define endl '\n'
#define FOR(i, x, y) for (decay<decltype(y)>::type i = (x), _##i = (y); i < _##i; ++i)
#define FORD(i, x, y) for (decay<decltype(x)>::type i = (x), _##i = (y); i > _##i; --i)
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
for (vector<int> v(3); cin >> v[0] >> v[1] >> v[2];) {
//if (all_of(v.begin(), v.end(), [](int x) ->bool{return x == -1;}))
if (count(v.begin(), v.end(), -1) == 3)
break;
auto pos = find_if(v.begin(), v.end(), [](int x) -> bool { return x <= 168; });
if (pos == v.end()) {
cout << "NO CRASH" << endl;
} else {
cout << "CRASH " << *pos << endl;
}
}
return 0;
}
/**
* 1. all_of(start,end,predict) 从[start,end)都满足谓词predict
* 2. count
* 3. find(start,end,k)顺序查找关键字k,返回k首次出现的位置,如果找不到返回v.end()
* 4. find_if(start,end,predict) 顺序查找关键字k 满足谓词predict(k)=true,返回k首次出现的位置,如果找不到返回v.end()
*/ | 27.425532 | 87 | 0.541505 | [
"vector"
] |
31210a8c0a46018b74b72f23489e78419031da3c | 18,555 | cpp | C++ | includes/visualization/plot_model.cpp | Biehrer/ecg-analyzer | b72ce81e8834ed0aec4c5ecb08dae02bde5cd25a | [
"Apache-2.0"
] | 4 | 2020-04-14T06:28:14.000Z | 2021-02-22T03:10:43.000Z | includes/visualization/plot_model.cpp | Biehrer/ecg-analyzer | b72ce81e8834ed0aec4c5ecb08dae02bde5cd25a | [
"Apache-2.0"
] | 31 | 2020-04-03T10:09:16.000Z | 2020-10-23T11:55:30.000Z | includes/visualization/plot_model.cpp | Biehrer/ecg-analyzer | b72ce81e8834ed0aec4c5ecb08dae02bde5cd25a | [
"Apache-2.0"
] | 1 | 2021-09-03T14:55:11.000Z | 2021-09-03T14:55:11.000Z | #include "plot_model.h"
#include "plot_model.h"
PlotModel_C::PlotModel_C(QObject* parent)
:/*QAbstractItemModel(parent)*/ QAbstractTableModel(parent)
{
//setIndexWidget(index, new QLineEdit);
}
PlotModel_C::~PlotModel_C()
{
}
// Sets the first row and determines the layout ( with #COLS items)
QVariant
PlotModel_C::headerData(int section, Qt::Orientation orientation, int role) const
{
if ( role == Qt::DisplayRole && orientation == Qt::Horizontal ) {
switch ( section ) {
case 0:
return QString("PlotID");
case 1:
return QString("Label");
case 2:
return QString("Time range (ms)");
case 3:
return QString("y-max");
case 4:
return QString("y-min");
case 5:
return QString("Maj-tick x-axes");
case 6:
return QString("Maj-tick y-axes");
case 7:
return QString("Min-tick x-axes");
case 8:
return QString("Min-tick y-axes");
}
}
return QVariant();
}
Qt::ItemFlags PlotModel_C::flags(const QModelIndex &index) const
{
return Qt::ItemIsEditable | QAbstractTableModel::flags(index); /*QAbstractItemModel::flags(index);*/
}
bool PlotModel_C::setData(const QModelIndex &index, const QVariant &value, int role)
{
if ( role == Qt::EditRole ) {
if ( !index.isValid() ) {
return false;
}
int row = index.row();
switch ( index.column() ) {
case OGLPlotProperty_TP::ID:
emit NewChangeRequest(row, OGLPlotProperty_TP::ID, value.toInt());
break;
case OGLPlotProperty_TP::LABEL:
emit NewChangeRequest(row, OGLPlotProperty_TP::LABEL, value.toString());
break;
case OGLPlotProperty_TP::TIMERANGE:
emit NewChangeRequest(row, OGLPlotProperty_TP::TIMERANGE, value.toDouble());
break;
case OGLPlotProperty_TP::YMAX:
emit NewChangeRequest(row, OGLPlotProperty_TP::YMAX, value.toDouble());
break;
case OGLPlotProperty_TP::YMIN:
emit NewChangeRequest(row, OGLPlotProperty_TP::YMIN, value.toDouble());
break;
case OGLPlotProperty_TP::MAJOR_TICK_X:
emit NewChangeRequest(row, OGLPlotProperty_TP::MAJOR_TICK_X, value.toDouble());
break;
case OGLPlotProperty_TP::MAJOR_TICK_Y:
emit NewChangeRequest(row, OGLPlotProperty_TP::MAJOR_TICK_Y, value.toDouble());
break;
case OGLPlotProperty_TP::MINOR_TICK_X:
emit NewChangeRequest(row, OGLPlotProperty_TP::MINOR_TICK_X, value.toDouble());
break;
case OGLPlotProperty_TP::MINOR_TICK_Y:
emit NewChangeRequest(row, OGLPlotProperty_TP::MINOR_TICK_Y, value.toDouble());
break;
}
return true;
}
return false;
}
int PlotModel_C::rowCount(const QModelIndex & parent) const
{
return _plots.size();
}
int PlotModel_C::columnCount(const QModelIndex & parent) const
{
return COLS;
}
QVariant
PlotModel_C::data(const QModelIndex & index, int role) const
{
uint32_t row = index.row();
uint32_t col = index.column();
if ( row > _plots.size() ) {
return QVariant();
}
switch ( role ) {
case Qt::DisplayRole:
switch ( col )
{
case OGLPlotProperty_TP::ID:
return _plots[row]->GetID();
case OGLPlotProperty_TP::LABEL:
return QString::fromStdString(_plots[row]->GetLabel());
case OGLPlotProperty_TP::TIMERANGE:
return _plots[row]->GetTimerangeMs();
case OGLPlotProperty_TP::YMAX:
return _plots[row]->GetMaxValueYAxes();
case OGLPlotProperty_TP::YMIN:
return _plots[row]->GetMinValueYAxes();
case OGLPlotProperty_TP::MAJOR_TICK_X:
return _plots[row]->GetMajorTickValueXAxes();
case OGLPlotProperty_TP::MAJOR_TICK_Y:
return _plots[row]->GetMajorTickValueYAxes();
case OGLPlotProperty_TP::MINOR_TICK_X:
return _plots[row]->GetMinorTickValueXAxes();
case OGLPlotProperty_TP::MINOR_TICK_Y:
return _plots[row]->GetMinorTickValueYAxes();
}
//case Qt::FontRole:
// if ( row == 0 && col == 0 ) { //change font only for cell(0,0)
// QFont boldFont;
// boldFont.setBold(true);
// return boldFont;
// }
// break;
}
return QVariant();
}
void
PlotModel_C::SetGain(const float gain)
{
for ( auto& plot : _plots ) {
plot->SetGain(gain);
}
}
void
PlotModel_C::SetTimeRangeWritingSpeed(WritingSpeed_TP w_speed)
{
for ( auto& plot : _plots ) {
plot->SetTimerangeWritingSpeed(w_speed);
}
}
void
PlotModel_C::ClearPlotSurfaces()
{
for ( auto& plot : _plots ) {
plot->Clear();
}
}
void
PlotModel_C::RemovePlot(unsigned int plot_id)
{
//for ( auto plot_it = _plots.begin(); plot_it != _plots.end(); ++plot_it ) {
// if ( plot_it->GetID() == plot_id ) {
// // beginRemoveRows()
// plot_it = _plots.erase(plot_it);
// // endRemoveRows()
// }
//}
}
bool
PlotModel_C::InitializePlots(int number_of_plots,
int view_width,
int view_height,
int time_range_ms,
const std::vector<std::pair<ModelDataType_TP, ModelDataType_TP>>& y_ranges)
{
DEBUG("initialize plots");
// Cleanup old plots before reinitialization
if ( _plots.size() > 0 ) {
// delete
for ( uint32_t plot_id = 0; plot_id < _plots.size(); ++plot_id ) {
delete _plots[plot_id];
}
_plots.clear();
}
// Chart properties
//RingBufferSize_TP chart_buffer_size = RingBufferSize_TP::Size65536;
RingBufferSize_TP chart_buffer_size = RingBufferSize_TP::Size1048576;
if ( y_ranges.size() != number_of_plots ) {
throw std::invalid_argument("Y-Ranges vector is not correct");
}
// WIth 2 plots -> 0.05 and 0.15 is ok...but with many plots its too much
// -> so choose this factor dependent on num plots AND screenheight/width
//int offset_x = static_cast<double>(view_width) * 0.05;
//int offset_y = static_cast<double>(view_height) * 0.15;
// Reduce the viewport by 5% on the x axes and 15% on the
// y axis so the plots don't reach the outter surface of the screen
int offset_x = static_cast<double>(view_width) * 0.05;
int offset_y = static_cast<double>(view_height) * 0.15;
int chart_width = view_width - offset_x;
int chart_height = (view_height - offset_y) / number_of_plots;
// Chart is aligned at the left side of the screen
// define some variablrs for position 'finetuning'
int chart_pos_x = 10;
int chart_to_chart_offset_S = 10;
int chart_offset_from_origin_S = 4;
// Create plots
for ( int chart_idx = 0; chart_idx < number_of_plots; ++chart_idx ) {
int chart_pos_y = chart_idx * (chart_height + chart_to_chart_offset_S) +
chart_offset_from_origin_S;
OGLChartGeometry_C geometry(chart_pos_x, chart_pos_y, chart_width, chart_height);
_plots.push_back(new OGLSweepChart_C<ModelDataType_TP >(time_range_ms, // TODO: Push_back can throw a exception(e.g no mem left) and the then we loose memory -> use unique ptr or shared ptr
chart_buffer_size,
/*max_y*/y_ranges[chart_idx].second,
/*min_y*/y_ranges[chart_idx].first,
geometry,
*this));
}
QVector3D series_color(0.0f, 1.0f, 0.0f); // green
QVector3D axes_color(1.0f, 1.0f, 1.0f); //white
QVector3D lead_line_color(1.0f, 0.01f, 0.0f); // red
QVector3D surface_grid_color(static_cast<float>(235.0f / 255.0f), //yellow-ish
static_cast<float>(225.0f / 255.0f),
static_cast<float>(27.0f / 255.0f));
QVector3D bounding_box_color(1.0f, 1.0f, 1.0f); // white
QVector3D text_color(1.0f, 1.0f, 1.0f); // white
QVector3D fiducial_mark_color(0.0f, 0.0f, 1.0f); // blue
unsigned int row_id = 1;
for ( auto& plot : _plots ) {
beginInsertRows(QModelIndex(), row_id, row_id);
plot->SetID(row_id - 1);
QString label = QString("plot #" + QString::fromStdString(std::to_string(row_id)));
plot->SetLabel(label.toStdString());
plot->SetTimerangeMs(time_range_ms);
plot->SetMaxValueYAxes(static_cast<double>(y_ranges[row_id - 1].second));
plot->SetMinValueYAxes(static_cast<double>(y_ranges[row_id - 1].first));
// Divide through 4 to create 4 horizontal and 4 vertical lines
plot->SetMajorTickValueYAxes(static_cast<double>( (y_ranges[row_id - 1].second - y_ranges[row_id - 1].first) / 4) );
plot->SetMajorTickValueXAxes(static_cast<double>(time_range_ms / 4));
endInsertRows();
// Setup colors
plot->SetSeriesColor(series_color);
plot->SetAxesColor(axes_color);
plot->SetTextColor(text_color);
plot->SetBoundingBoxColor(bounding_box_color);
plot->SetLeadLineColor(lead_line_color);
plot->SetSurfaceGridColor(surface_grid_color);
plot->SetFiducialMarkColor(fiducial_mark_color);
// Set chart type
plot->SetChartType(DrawingStyle_TP::LINE_SERIES);
// Initialize
plot->Initialize();
++row_id;
}
//emit a signal to make the view reread identified data
emit dataChanged(createIndex(0, 0), // top left table index
createIndex(number_of_plots, COLS), // bottom right table index
{ Qt::DisplayRole });
return true;
}
bool
PlotModel_C::InitializePlotsWithOverlap(int number_of_plots,
int view_width,
int view_height,
int time_range_ms,
const std::vector<std::pair<ModelDataType_TP, ModelDataType_TP>>& y_ranges)
{
DEBUG("initialize plots");
// Calculate the x and y overlap we need to give each plot at leat 15 % of the screen width
// given: num_plots, view_height, view width
// Cleanup old plots before reinitialization
if ( _plots.size() > 0 ) {
// delete
for ( uint32_t plot_id = 0; plot_id < _plots.size(); ++plot_id ) {
delete _plots[plot_id];
}
_plots.clear();
}
// Chart properties
RingBufferSize_TP chart_buffer_size = RingBufferSize_TP::Size1048576;
if ( y_ranges.size() != number_of_plots ) {
throw std::invalid_argument("Y-Ranges vector is not correct");
}
bool overlap = true;
// 25% of the chart from above will show into the chart in the middle
// and 25% of the chart from below will show into the chart in the middle
float overlap_factor = 0.5f;
// Reduce the viewport by 5% on the x axes and 15% on the
// y axis so the plots don't reach the outter surface of the screen
float viewport_width = view_width - (static_cast<double>(view_width) * 0.05);
float viewport_height = view_height - (static_cast<double>(view_height) * 0.15);
unsigned int chart_width = viewport_width;
float chart_height_minimum = 100.0; // viewport_height / 7;
unsigned int chart_height = std::max(chart_height_minimum, (viewport_height / number_of_plots));// +chart_height_overlap;
unsigned int chart_height_overlap = chart_height * overlap_factor;
// Chart is aligned at the left side of the screen
// define some variablrs for position 'finetuning'
int chart_pos_x = 10;
//int chart_to_chart_offset_S = 10;
int chart_to_chart_offset_S = 1;
int chart_offset_from_origin_S = 4;
// Create plots
for ( int chart_idx = 0; chart_idx < number_of_plots; ++chart_idx ) {
// Todo - overlap factor at ther place
// This is shit, because above i add the factor, and here i remove it again!
unsigned int chart_pos_y = chart_idx * (chart_height + chart_to_chart_offset_S-chart_height_overlap) +
chart_offset_from_origin_S/* - chart_height_overlap*/;
OGLChartGeometry_C geometry(chart_pos_x, chart_pos_y, chart_width, chart_height+chart_height_overlap);
_plots.push_back(new OGLSweepChart_C<ModelDataType_TP >(time_range_ms,
chart_buffer_size,
/*max_y*/y_ranges[chart_idx].second,
/*min_y*/y_ranges[chart_idx].first,
geometry,
*this));
}
QVector3D series_color(0.0f, 1.0f, 0.0f); // green
QVector3D axes_color(1.0f, 1.0f, 1.0f); //white
QVector3D lead_line_color(1.0f, 0.01f, 0.0f); // red
QVector3D surface_grid_color(static_cast<float>(235.0f / 255.0f), //yellow-ish
static_cast<float>(225.0f / 255.0f),
static_cast<float>(27.0f / 255.0f));
QVector3D bounding_box_color(1.0f, 1.0f, 1.0f); // white
QVector3D text_color(1.0f, 1.0f, 1.0f); // white
QVector3D fiducial_mark_color(0.0f, 0.0f, 1.0f); // blue
unsigned int row_id = 1;
for ( auto& plot : _plots ) {
beginInsertRows(QModelIndex(), row_id, row_id);
plot->SetID(row_id - 1);
QString label = QString("plot #" + QString::fromStdString(std::to_string(row_id)));
plot->SetLabel(label.toStdString());
plot->SetTimerangeMs(time_range_ms);
plot->SetMaxValueYAxes(static_cast<double>(y_ranges[row_id - 1].second));
plot->SetMinValueYAxes(static_cast<double>(y_ranges[row_id - 1].first));
// Divide through 4 to create 4 horizontal and 4 vertical lines
plot->SetMajorTickValueYAxes(static_cast<double>((y_ranges[row_id - 1].second - y_ranges[row_id - 1].first) / 4));
plot->SetMajorTickValueXAxes(static_cast<double>(time_range_ms / 4));
endInsertRows();
// Setup colors
plot->SetSeriesColor(series_color);
plot->SetAxesColor(axes_color);
plot->SetTextColor(text_color);
plot->SetBoundingBoxColor(bounding_box_color);
plot->SetLeadLineColor(lead_line_color);
plot->SetSurfaceGridColor(surface_grid_color);
plot->SetFiducialMarkColor(fiducial_mark_color);
// Set chart type
plot->SetChartType(DrawingStyle_TP::LINE_SERIES);
// Initialize
plot->Initialize();
++row_id;
}
//emit a signal to make the view reread identified data
emit dataChanged(createIndex(0, 0), // top left table index
createIndex(number_of_plots, COLS), // bottom right table index
{ Qt::DisplayRole });
return true;
}
OGLSweepChart_C<ModelDataType_TP>*
PlotModel_C::GetPlotPtr(unsigned int plot_idx)
{
if ( plot_idx < _plots.size() ) {
return _plots[plot_idx];
}
return nullptr;
}
OGLSweepChart_C<ModelDataType_TP>*
PlotModel_C::GetPlotPtr(const std::string & plot_label) {
if ( _plots.empty() ) {
return nullptr;
}
for ( const auto& plot : _plots ) {
if ( plot_label == plot->GetLabel() ) {
return plot;
}
}
//for ( auto plot_it = _plots.begin(); plot_it != _plots.end(); ++plot_it ) {
// if ( plot_label == plot_it->GetLabel() ) {
// return (plot_it)._Ptr;
// }
//}
return nullptr;
}
const
std::vector<OGLSweepChart_C<ModelDataType_TP>*>&
PlotModel_C::constData() const
{
return _plots;
}
std::vector<OGLSweepChart_C<ModelDataType_TP>*>&
PlotModel_C::Data()
{
return _plots;
}
void PlotModel_C::AddPlot(const PlotDescription_TP& plot_info)
{
int number_of_plots = _plots.size();
// Create plot
_plots.push_back(new OGLSweepChart_C<ModelDataType_TP>(plot_info._time_range_ms,
plot_info._input_buffer_size,
plot_info._max_y,
plot_info._min_y,
plot_info._geometry,
*this));
auto* plot = (*_plots.end() - 1);
plot->SetLabel(plot_info._label);
plot->SetID(plot_info._id);
// Setup colors
plot->SetSeriesColor(plot_info._colors._series);
plot->SetAxesColor(plot_info._colors._axes);
plot->SetTextColor(plot_info._colors._text);
plot->SetBoundingBoxColor(plot_info._colors._bounding_box);
plot->SetLeadLineColor(plot_info._colors._lead_line);
plot->SetSurfaceGridColor(plot_info._colors._surface_grid);
// Set up axes
plot->SetMajorTickValueXAxes(plot_info._maj_tick_x);
plot->SetMajorTickValueYAxes(plot_info._maj_tick_y);
// Set chart type ( Point or Line series )
plot->SetChartType(plot_info._chart_type);
// Initialize
plot->Initialize();
//emit a signal to make the view reread identified data
emit dataChanged(createIndex(number_of_plots, 0), // top left table index
createIndex(number_of_plots + 1, COLS), // bottom right table index
{ Qt::DisplayRole });
}
void
PlotModel_C::AddPlot(OGLSweepChart_C<ModelDataType_TP>& plot)
{
int number_of_plots = _plots.size();
// Create plot
_plots.push_back(new OGLSweepChart_C<ModelDataType_TP>(static_cast<int>(plot.GetTimerangeMs()),
plot.GetInputBufferSize(),
plot.GetMaxValueYAxes(),
plot.GetMinValueYAxes(),
plot.GetBoundingBox(),
*this));
auto* plot_new = (*_plots.end() - 1);
//auto* plot_new = *(_plots.end() - 1);
plot_new->SetLabel(plot.GetLabel());
plot_new->SetID(plot.GetID());
// Set up axes
plot_new->SetMajorTickValueXAxes(plot.GetMajorTickValueXAxes());
plot_new->SetMajorTickValueYAxes(plot.GetMajorTickValueYAxes());
// Set chart type ( Point or Line series )
plot_new->SetChartType(plot.GetChartType());
// Initialize
plot_new->Initialize();
//emit a signal to make the view reread identified data
emit dataChanged(createIndex(number_of_plots, 0), // top left table index
createIndex(number_of_plots + 1, COLS), // bottom right table index
{ Qt::DisplayRole });
}
unsigned
int
PlotModel_C::GetNumberOfPlots()
{
return _plots.size();
}
bool
PlotModel_C::RemovePlot(const std::string & label)
{
for ( auto plot_it = _plots.begin(); plot_it != /*<*/ _plots.end(); ++plot_it ) {
if ( label == (*plot_it)->GetLabel() ) {
// match
_plots.erase(plot_it);
return true;
}
}
return false;
}
| 34.108456 | 197 | 0.631258 | [
"geometry",
"vector"
] |
3129a8b6f3ab61c459167c6f226f9cc0a72be007 | 9,030 | cpp | C++ | miniProj/temp/SudokuMain.cpp | yongsenliu/cxxBootCamp2021 | 95adfe1a0ec0dc16448dcc44590b3e9d1f00f186 | [
"MIT"
] | null | null | null | miniProj/temp/SudokuMain.cpp | yongsenliu/cxxBootCamp2021 | 95adfe1a0ec0dc16448dcc44590b3e9d1f00f186 | [
"MIT"
] | 1 | 2021-11-08T12:44:38.000Z | 2021-11-10T00:04:10.000Z | miniProj/temp/SudokuMain.cpp | yongsenliu/cxxBootCamp2021 | 95adfe1a0ec0dc16448dcc44590b3e9d1f00f186 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#define N 9
using namespace std;
/**************************************************************
// Two dimentional array for passing numbers to sovler one by one
**************************************************************/
int sudoku[N][N] = {
{3, 1, 0, 5, 0, 8, 3, 0, 2},
{5, 0, 5, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}
};
/********************************
// Declaration of class 'Possible'
*********************************/
class Possible {
// Create an array of 9 for boolens
vector<bool> _boolens;
public:
Possible();
int countTrueInPossibles() const;
bool isTrueForValueInPossibles(int i) const;
void eliminatefromPossiblesOfValue(int i);
int valueOfFirstTrueInPossibles() const;
string getString(int width) const;
};
/*************************************
// Implementations of class 'Possible'
*************************************/
Possible::Possible() : _boolens(9, true) {};
int Possible::countTrueInPossibles() const {
//FIXME....
return count(_boolens.begin(), _boolens.end(), true);
};
//get boolen value
bool Possible::isTrueForValueInPossibles(int i) const {
return _boolens[i-1];
};
//eliminate one possilbe by setting false
void Possible::eliminatefromPossiblesOfValue(int i) {
_boolens[i-1] = false;
};
// Returns an iterator to the first element in the range [first,last)
//that compares equal to val. If no such element is found, the function
//returns last.
int Possible::valueOfFirstTrueInPossibles() const {
auto it = find(_boolens.begin(), _boolens.end(), true);
return (it != _boolens.end() ? 1 + (it - _boolens.begin()) : -1);
};
string Possible::getString(int width) const {
string s(width, ' ');
int k = 0;
for (int i = 1; i <= 9; i++) {
if (isTrueForValueInPossibles(i)) {
s[k++] = '0' + i;
}
}
return s;
};
/*****************************
// Declaration of class 'Grid'
*****************************/
class Grid {
vector<Possible> _squares;
vector<vector<int>> _unit, _peers, _unitsOf;
public:
Possible possible(int k) const { return _squares[k]; }
Grid();
void init();
bool isSolved() const;
int getIndexOfSquareWithLeastCountOfTrues() const;
void print(ostream & s) const;
// eliminate a possible from a square, 'value' is par for eliminating,
//'k' is the index
bool eliminatePossibleFromSquare (int k, int value);
bool assign(int k, int value);
};
// vector<vector<int>> Grid :: _unit(27), _unitsOf(81), _peers(81);
// void Grid::Grid(int **arry) : _squares(81) {
// int k = 0;
// for (int i = 0; i < 9; i++) {
// for (int j = 0; j < 9; j++) {
// if (!assign(k, arry[i][j])) {
// cerr << "error" << endl;
// return;
// }
// k++;
// }
// k++;
// }
// }
/*****************************
// Implementation of class 'Grid'
*****************************/
void Grid::init() {
// this->_peers.resize();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
const int k = i*9 + j;
const int x[3] = {i, 9 + j, 18 + (i/3)*3 + j/3};
for (int g = 0; g < 3; g++) {
auto & refvec = _unit[x[g]];
refvec.push_back(k);
_unitsOf[k].push_back(x[g]);
}
}
}
for (int k = 0; k < _peers.size(); k++) {
for (int x = 0; x < _unitsOf[k].size(); x++) {
for (int j = 0; j < 9; j++) {
int k2 = _unit[_unitsOf[k][x]][j];
if (k2 != k) _peers[k].push_back(k2);
}
}
}
};
/*
void Grid::init() {
// this->_peers.resize();
//vector<Possible> _squares(81);
//vector<vector<int>> _unit(27), _unitsOf(81), _peers(81);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
const int k = i*9 + j;
const int x[3] = {i, 9 + j, 18 + (i/3)*3 + j/3};
for (int g = 0; g < 3; g++) {
auto & refvec = _unit[x[g]];
refvec.push_back(k);
_unitsOf[k].push_back(x[g]);
}
}
}
for (int k = 0; k < _peers.size(); k++) {
for (int x = 0; x < _unitsOf[k].size(); x++) {
for (int j = 0; j < 9; j++) {
int k2 = _unit[_unitsOf[k][x]][j];
if (k2 != k) _peers[k].push_back(k2);
}
}
}
};
*/
bool Grid::isSolved() const {
for (int k = 0; k < _squares.size(); k++) {
if (_squares[k].countTrueInPossibles() != 1) {
return false;
}
}
return true;
};
int Grid::getIndexOfSquareWithLeastCountOfTrues() const {
int k = -1;
int min;
for (int i = 0; i< _squares.size(); i++) {
int m = _squares[i].countTrueInPossibles();
if (m > 1 && (k == -1 || m < min)) {
min = m;
k = i;
}
}
return k;
};
void Grid::print(ostream & s) const{
int width = 1;
for (int k = 0; k < _squares.size(); k++) {
width = max(width, 1 + _squares[k].countTrueInPossibles());
}
string str(3*width, '-');
for (int i = 0; i < 9; i++) {
if (i == 3 || i == 6) {
s << str << "+-" << str << "+" << str << endl;
}
for (int j = 0; j < 9; j++) {
if (j == 3 || j == 6) s << "| ";
s << _squares[i*9 + j].getString(width);
}
s << endl;
}
};
bool Grid::eliminatePossibleFromSquare (int k, int value) {
// if the value has already been eliminated, return true i.e. successful.
if (!_squares[k].isTrueForValueInPossibles(value)) {
return true;
}
// set possible for index k as 'false' for the value
_squares[k].eliminatefromPossiblesOfValue(value);
// if no possibles exist in index k, it means no solution, return 'false' to the function
if (_squares[k].countTrueInPossibles() == 0) {
return false;
} else if (_squares[k].countTrueInPossibles() == 1) {// only one possible value
int v = _squares[k].valueOfFirstTrueInPossibles();
for (int i = 0; i < _peers[k].size(); i++) {
if (!eliminatePossibleFromSquare(_peers[k][i], v)) {
return false;
}
}
}
for (int i = 0; i < _unitsOf[k].size(); i++) {
int x = _unitsOf[k][i];
int n = 0, ks;
for (int j = 0; j < 9; j++) {
int p = _unit[k][i];
if (_squares[p].isTrueForValueInPossibles(value)) {
n++;
ks = p;
}
}
if (n == 0) {
return false;
} else if (n == 1) {
if (!assign(ks, value)) {
return false;
}
}
}
return true;
};
bool Grid::assign(int k, int value) {
for (int i = 1; i <= 9; i++) {
if (i != value) {
if (!eliminatePossibleFromSquare(k, i)) {
return false;
}
}
}
return true;
};
// Grid::Grid() : _squares(81) {
// vector<vector<int>> _unit(27), _unitsOf(81), _peers(81);
// for (int i = 0; i < 81; i++) {
// if (!assign(i, 0)) {
// cerr << "error" << endl;
// return;
// }
// }
// };
Grid::Grid() : _squares(81) {
_unit = vector<vector<int>>(27,vector<int>());
_unitsOf = vector<vector<int>>(81, vector<int>());
_peers = vector<vector<int>>(81, vector<int>());
init();
int k = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!assign(k, sudoku[i][j])) {
cerr << "error" << endl;
return;
}
k++;
}
}
};
// unique_ptr<Grid> solve(unique_ptr<Grid> S) {
// if (S == nullptr || S->isSolved()) {
// return S;
// }
// int k = S->leastCount();
// Possible p = S->possible(k);
// for (int i = 1; i <= 9; i++) {
// if (p.isTrue(i)) {
// unique_ptr<Grid> S1(new Grid(*S));
// if (S1->assign(k, i)) {
// if (auto S2 = solve(std::move(S1))) {
// return S2;
// }
// }
// }
// }
// return {};
// }
/*****************
//main entry point
*****************/
int main() {
std::cout << "---------------" << std::endl;
Grid grid;
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
grid.print(cout);
int k = sudoku[i][j];
grid.eliminatePossibleFromSquare(i*j, k);
grid.print(cout);
}
}
std::cout << "++++++++++++++++++" << std::endl;
return 0;
} | 27.035928 | 93 | 0.447619 | [
"vector"
] |
3131fa6e4ea598084d359cc8fab1590279d30221 | 4,431 | cpp | C++ | MIRZA/1/src/MIRZA.cpp | zavolanlab/Dockerfiles | 4457207fd584e84b1ab7f7589da5816bb99b647e | [
"Apache-2.0"
] | 6 | 2018-11-02T10:51:17.000Z | 2022-01-04T15:50:47.000Z | MIRZA/1/src/MIRZA.cpp | zavolanlab/Dockerfiles | 4457207fd584e84b1ab7f7589da5816bb99b647e | [
"Apache-2.0"
] | 36 | 2018-10-10T11:45:59.000Z | 2021-04-09T15:13:21.000Z | MIRZA/1/src/MIRZA.cpp | zavolanlab/Dockerfiles | 4457207fd584e84b1ab7f7589da5816bb99b647e | [
"Apache-2.0"
] | 2 | 2018-11-23T20:51:47.000Z | 2019-02-05T14:34:29.000Z | // ===========================================================================
// Name : MIRZA.cpp
// Author : Mohsen Khorshid
// Copyright : University of Basel, 2010
// Description : Alignment model miRNA to mRNA target
// ===========================================================================
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "Hybridize.h"
#include <stdlib.h>
#include <string>
#include <math.h>
#include <time.h>
#define miRNA_FIXED_LENGTH 21
#define NUMBER_OF_ENERGY_PARAMETER_LENGTH 6
#define NOISE 0.05
#define ENERGY_SCALE 20
using namespace std;
//The Hybridizer
Hybridize Hybridizer = Hybridize();
int main(int argc, char* argv[]) {
int mRNAlength = atoi(argv[4]);
int updatePriors = 0;
string PriorUpdate_ARGUMENT = argv[5];
if(!(PriorUpdate_ARGUMENT.compare("update"))){updatePriors = 1;}
//Initialize the Hybridizer and allocate the necessary memory
Hybridizer.mRNA_Length = mRNAlength;
Hybridizer.updatePriors = updatePriors;
Hybridizer.Initialize();
//microRNA expression levels
string miRNA_expression_file = argv[1];
//set the file Names for Hybridizer
string my_mRNA_file = argv[2];
string my_miRNA_file = argv[3];
Hybridizer.Read_mRNA_fasta_file(my_mRNA_file);
//Estimate the base content fractions in the mRNA sequences
Hybridizer.Params.Initialize();
cerr << "__________________________________________________" << endl;
Hybridizer.Read_miRNA_fasta_file(my_miRNA_file);
cerr << "__________________________________________________" << endl;
//Setting the initial miRNA expression levels in the sample
Hybridizer.Read_miRNA_expressions(miRNA_expression_file);
cerr << "__________________________________________________" << endl;
Hybridizer.Gaussian_Penalty = 0;
// These are the parameters of the hybridization model
double parameters[miRNA_FIXED_LENGTH + NUMBER_OF_ENERGY_PARAMETER_LENGTH] = {0};
cout << "Setting the Energy Parameters of the Hybridizer with the following values: " << endl;
parameters[0]= 2.38714;
parameters[1]= 2.39491;
parameters[2]= -3.61813;
parameters[3]= -0.285659;
parameters[4]= 1.01614;
parameters[5]= 1.03229;
//These are the 21 positional parameters
parameters[6]= -3.24074;
parameters[7]= -0.249397;
parameters[8]= 3.45158;
parameters[9]= 3.59005;
parameters[10]= 0.609733;
parameters[11]= 2.46235;
parameters[12]= -0.0431051;
parameters[13]= -0.815238;
parameters[14]= -4.25303;
parameters[15]= -3.08829;
parameters[16]= -1.84676;
parameters[17]= -4.55569;
parameters[18]= -1.75914;
parameters[19]= -1.53761;
parameters[20]= -1.78762;
parameters[21]= -1.46246;
parameters[22]= -4.20649;
parameters[23]= -1.79764;
parameters[24]= -2.24505;
parameters[25]= -4.15307;
parameters[26]= -3.82612;
for (unsigned int i = 0; i < miRNA_FIXED_LENGTH + NUMBER_OF_ENERGY_PARAMETER_LENGTH; i++) {
cout << "init[" << i << "] = " << parameters[i] << ";" << endl;
Hybridizer.Gaussian_Penalty += (parameters[i] / ENERGY_SCALE) * (parameters[i] / ENERGY_SCALE);
}
//Initialize the looping energies
Hybridizer.eE_OPEN=0;
Hybridizer.eE_SYM=0;
Hybridizer.eE_mRNA_Assymetric_loops=0;
Hybridizer.eE_miRNA_Assymetric_loops=0;
//Initializing the miRNA priors relative to their expression in the cell
Hybridizer.Initialize_miRNA_priors();
//Initialize mRNA versus miRNA likelihood ratios
Hybridizer.Initialize_miRNA_mRNA_likelihood_ratios();
//Initialaize the values mRNA likelihood ratios
Hybridizer.Initialize_mRNA_log_likelihood_ratios();
//Set the energy parameters [with length of ENERGY_PARAMETER_LENGTH] that are being optimized and Calculate the Exponentials and Coefficients
Hybridizer.Initialize_Global_Parameters_and_Prepare(parameters);
//Start the calculation
Hybridizer.Calculate_data_log_likelihood_ratio();
return 0;
}
| 31.425532 | 142 | 0.723313 | [
"model"
] |
31367b1028d93377c8305f27060a9278d6d293d7 | 7,140 | cpp | C++ | module-sys/SystemManager/tests/test-DependencyGraph.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-sys/SystemManager/tests/test-DependencyGraph.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-sys/SystemManager/tests/test-DependencyGraph.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <catch2/catch.hpp>
#include "Service/ServiceCreator.hpp"
#include "SystemManager/DependencyGraph.hpp"
#include "SystemManager/graph/TopologicalSort.hpp"
using namespace sys;
using graph::TopologicalSort;
class MockedServiceCreator : public BaseServiceCreator
{
public:
using BaseServiceCreator::BaseServiceCreator;
std::shared_ptr<Service> create() const override
{
return nullptr;
}
};
ServiceManifest createManifest(ServiceManifest::ServiceName name, std::vector<ServiceManifest::ServiceName> deps)
{
ServiceManifest manifest;
manifest.name = std::move(name);
manifest.dependencies = std::move(deps);
return manifest;
}
TEST_CASE("Given Dependency Graph When topological sort empty graph then verify if result is empty")
{
DependencyGraph graph{{}, std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted.empty());
}
TEST_CASE("Given Dependency Graph When topological sort without dependencies then verify order")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S4", {})));
// Graph:
// S1 S2 S3 S4
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted[0].get().getName() == "S1");
REQUIRE(sorted[1].get().getName() == "S2");
REQUIRE(sorted[2].get().getName() == "S3");
REQUIRE(sorted[3].get().getName() == "S4");
}
TEST_CASE("Given Dependency Graph When topological sort simple case then verify order")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {"S2"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {"S3"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {"S4"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S4", {})));
// Graph:
// S1 -> S2 -> S3 -> S4
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted[0].get().getName() == "S4");
REQUIRE(sorted[1].get().getName() == "S3");
REQUIRE(sorted[2].get().getName() == "S2");
REQUIRE(sorted[3].get().getName() == "S1");
}
TEST_CASE("Given Dependency Graph When topological sort all depending on one then verify order")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {"S2"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {"S2"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S4", {"S2"})));
// Graph:
// S1 -> S2
// / ^
// S3 |
// S4
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted[0].get().getName() == "S2");
REQUIRE(sorted[1].get().getName() == "S1");
REQUIRE(sorted[2].get().getName() == "S3");
REQUIRE(sorted[3].get().getName() == "S4");
}
TEST_CASE("Given Dependency Graph When topological sort advanced case then verify order 1")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {"S2", "S3"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {"S4"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {"S5"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S4", {"S6"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S5", {"S6"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S6", {})));
// Graph:
// -> S2 -> S4 -->
// S1 -> S3 -> S5 -> S6
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted[0].get().getName() == "S6");
REQUIRE(sorted[1].get().getName() == "S4");
REQUIRE(sorted[2].get().getName() == "S2");
REQUIRE(sorted[3].get().getName() == "S5");
REQUIRE(sorted[4].get().getName() == "S3");
REQUIRE(sorted[5].get().getName() == "S1");
}
TEST_CASE("Given Dependency Graph When topological sort advanced case then verify order 2")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {"S2", "S3", "S4"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {"S5", "S6"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S4", {"S6"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S5", {})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S6", {})));
// Graph:
// --> S4 ---\>
// / ----> S6
// / /
// S1 -> S3 -> S5
// \-> S2
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
REQUIRE(sorted[0].get().getName() == "S2");
REQUIRE(sorted[1].get().getName() == "S5");
REQUIRE(sorted[2].get().getName() == "S6");
REQUIRE(sorted[3].get().getName() == "S3");
REQUIRE(sorted[4].get().getName() == "S4");
REQUIRE(sorted[5].get().getName() == "S1");
}
TEST_CASE("Given Dependency Graph When topological sort on directed cyclic graph then verify order")
{
std::vector<std::unique_ptr<BaseServiceCreator>> services;
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S1", {"S2"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S2", {"S3"})));
services.push_back(std::make_unique<MockedServiceCreator>(createManifest("S3", {"S1"})));
// Graph:
// S1 -> S2 -> S3
// \---------/
DependencyGraph graph{graph::nodesFrom(services), std::make_unique<TopologicalSort>()};
const auto &sorted = graph.sort();
// The order is not correct. Dependency Graph doesn't handle cyclic graphs properly
REQUIRE(sorted[0].get().getName() == "S3");
REQUIRE(sorted[1].get().getName() == "S2");
REQUIRE(sorted[2].get().getName() == "S1");
}
| 40.568182 | 113 | 0.67465 | [
"vector"
] |
313737e5d255562877d970cb27ef7f278a2ce67d | 3,108 | cc | C++ | plugins/devtools/bridge/inspector/protocol/scope.cc | devjiangzhou/kraken | d7b48100f8a017a9ccb9ea1628e319d8f1159c91 | [
"Apache-2.0"
] | 4,465 | 2020-12-04T08:56:15.000Z | 2022-03-31T19:04:00.000Z | plugins/devtools/bridge/inspector/protocol/scope.cc | devjiangzhou/kraken | d7b48100f8a017a9ccb9ea1628e319d8f1159c91 | [
"Apache-2.0"
] | 796 | 2021-01-05T08:21:00.000Z | 2022-03-31T13:31:28.000Z | plugins/devtools/bridge/inspector/protocol/scope.cc | devjiangzhou/kraken | d7b48100f8a017a9ccb9ea1628e319d8f1159c91 | [
"Apache-2.0"
] | 261 | 2020-12-04T11:32:42.000Z | 2022-03-31T03:34:47.000Z | /*
* Copyright (C) 2020 Alibaba Inc. All rights reserved.
* Author: Kraken Team.
*/
#include "scope.h"
namespace kraken {
namespace debugger {
const char *Scope::TypeEnum::Global = "global";
const char *Scope::TypeEnum::Local = "local";
const char *Scope::TypeEnum::With = "with";
const char *Scope::TypeEnum::Closure = "closure";
const char *Scope::TypeEnum::Catch = "catch";
const char *Scope::TypeEnum::Block = "block";
const char *Scope::TypeEnum::Script = "script";
const char *Scope::TypeEnum::Eval = "eval";
const char *Scope::TypeEnum::Module = "module";
std::unique_ptr<Scope> Scope::fromValue(rapidjson::Value *value, kraken::debugger::ErrorSupport *errors) {
if (!value || !value->IsObject()) {
errors->addError("object expected");
return nullptr;
}
std::unique_ptr<Scope> result(new Scope());
errors->push();
if (value->HasMember("type") && (*value)["type"].IsString()) {
result->m_type = (*value)["type"].GetString();
} else {
errors->setName("type");
errors->addError("type not found");
}
if (value->HasMember("object") && (*value)["object"].IsObject()) {
rapidjson::Value obj = rapidjson::Value((*value)["object"].GetObject());
result->m_object = RemoteObject::fromValue(&obj, errors);
} else {
errors->setName("object");
errors->addError("object not found");
}
if (value->HasMember("name")) {
errors->setName("name");
if ((*value)["name"].IsString()) {
result->m_name = (*value)["name"].GetString();
} else {
errors->addError("name shoud be string");
}
}
if (value->HasMember("startLocation")) {
errors->setName("startLocation");
if ((*value)["startLocation"].IsObject()) {
rapidjson::Value start_loc = rapidjson::Value((*value)["startLocation"].GetObject());
result->m_startLocation = Location::fromValue(&start_loc, errors);
} else {
errors->addError("startLocation should be object");
}
}
if (value->HasMember("endLocation")) {
errors->setName("startLocation");
if ((*value)["endLocation"].IsObject()) {
rapidjson::Value end_loc = rapidjson::Value((*value)["endLocation"].GetObject());
result->m_endLocation = Location::fromValue(&end_loc, errors);
} else {
errors->addError("endLocation should be object");
}
}
errors->pop();
if (errors->hasErrors()) return nullptr;
return result;
}
rapidjson::Value Scope::toValue(rapidjson::Document::AllocatorType &allocator) const {
rapidjson::Value result = rapidjson::Value(rapidjson::kObjectType);
result.SetObject();
result.AddMember("type", m_type, allocator);
result.AddMember("object", m_object->toValue(allocator), allocator);
if (m_name.isJust()) {
result.AddMember("name", m_name.fromJust(), allocator);
}
if (m_startLocation.isJust()) {
result.AddMember("startLocation", m_startLocation.fromJust()->toValue(allocator), allocator);
}
if (m_endLocation.isJust()) {
result.AddMember("endLocation", m_endLocation.fromJust()->toValue(allocator), allocator);
}
return result;
}
} // namespace debugger
} // namespace kraken
| 31.393939 | 106 | 0.659588 | [
"object"
] |
313918aa8fdf3a8807679115edc794b29966347a | 2,699 | hpp | C++ | src/base/rmg/internal/object2d_shader.hpp | khantkyawkhaung/robot-monitor-graphics | 2d365b3f3537e141cd1ec82f840c300abd79082b | [
"MIT"
] | 2 | 2020-06-16T14:47:11.000Z | 2020-07-09T15:34:55.000Z | src/base/rmg/internal/object2d_shader.hpp | khantkyawkhaung/robot-monitor-graphics | 2d365b3f3537e141cd1ec82f840c300abd79082b | [
"MIT"
] | null | null | null | src/base/rmg/internal/object2d_shader.hpp | khantkyawkhaung/robot-monitor-graphics | 2d365b3f3537e141cd1ec82f840c300abd79082b | [
"MIT"
] | null | null | null | /**
* @file object2d_shader.hpp
* @brief Displays 2D objects like sprites and texts
*
* @copyright Copyright (c) 2020 Khant Kyaw Khaung
*
* @license{This project is released under the MIT License.}
*/
#pragma once
#ifndef __RMG_OBJECT2D_SHADER_H__
#define __RMG_OBJECT2D_SHADER_H__
#ifndef RMG_API
#ifdef _WIN32
#ifdef RMG_EXPORT
#define RMG_API __declspec(dllexport)
#else
#define RMG_API __declspec(dllimport)
#endif
#else
#define RMG_API
#endif
#endif
#include <map>
#include "shader.hpp"
#include "../sprite.hpp"
#include "../text2d.hpp"
namespace rmg {
namespace internal {
/**
* @brief Displays 2D sprites
*/
class RMG_API SpriteShader: public Shader {
private:
uint32_t idMVP;
uint32_t idColor;
uint32_t quadVertexArrayID = 0;
uint32_t quadVertexBuffer = 0;
public:
/**
* @brief Default constructor
*/
SpriteShader() = default;
/**
* @brief Destructor
*/
virtual ~SpriteShader();
/**
* @brief Compile, link and assign program parameters
*/
void load() override;
/**
* @brief Renders a sprite image on 2D panel
*
* @param sprite The sprite image to render
* @param VP The combination of view matrix and projection matrix
*/
void render(Sprite2D* sprite, const Mat3 &VP);
};
/**
* @brief Displays 2D texts
*/
class RMG_API Text2DShader: public Shader {
private:
uint32_t idModel;
uint32_t idColor;
public:
/**
* @brief Default constructor
*/
Text2DShader() = default;
/**
* @brief Compile, link and assign program parameters
*/
void load() override;
/**
* @brief Renders a 2D text on 2D panel
*
* @param txt The 2D text object to render
* @param VP The combination of view matrix and projection matrix
*/
void render(Text2D* txt, const Mat3 &VP);
};
/**
* @brief Displays 2D objects like sprites and texts
*/
class RMG_API Object2DShader {
private:
SpriteShader spriteShader;
Text2DShader text2dShader;
Mat3 projectionMatrix;
uint16_t width;
uint16_t height;
public:
/**
* @brief Default constructor
*/
Object2DShader();
/**
* @brief Compile, link and assign program parameters
*/
void load();
/**
* @brief Sets OpenGL viewport size
*
* @param w Viewport width
* @param h Viewport height
*/
void setContextSize(uint16_t w, uint16_t h);
/**
* @brief Renders the given list of 2D objects
*
* @param list List of 2D objects
*/
void render(const std::map<uint64_t, Object2D*> &list);
};
}}
#endif
| 18.874126 | 69 | 0.626528 | [
"render",
"object"
] |
3140aaedc2d3a11f5a608ba66744298f10c5f0bc | 2,211 | cpp | C++ | Source/Scene.cpp | maxattack/Trinket | b989bc88800ac858f0a150858e1c9670b88d4aad | [
"Unlicense"
] | 1 | 2020-06-11T21:31:25.000Z | 2020-06-11T21:31:25.000Z | Source/Scene.cpp | maxattack/Trinket | b989bc88800ac858f0a150858e1c9670b88d4aad | [
"Unlicense"
] | null | null | null | Source/Scene.cpp | maxattack/Trinket | b989bc88800ac858f0a150858e1c9670b88d4aad | [
"Unlicense"
] | null | null | null | // Trinket Game Engine
// (C) 2020 Max Kaufmann <max.kaufmann@gmail.com>
#include "Scene.h"
#include <shared_mutex>
Scene::Scene()
: mgr(false)
{
mgr.ReserveCompact(1024);
CreateSublevel("Default Level");
}
Scene::~Scene() {
}
ObjectID Scene::CreateObject(Name name) {
return mgr.CreateObject(name);
}
ObjectID Scene::CreateSublevel(Name name) {
let id = CreateObject(name);
let pHierarchy = NewObjectComponent<Hierarchy>(id);
pHierarchy->AddListener(this);
sublevels.TryAppendObject(id, pHierarchy);
return id;
}
void Scene::TryReleaseObject(ObjectID id) {
if (!mgr.GetPool().Contains(id))
return;
// TODO: make this suckless?
// TODO: multithreaded locks?
static eastl::vector<ObjectID> destroySet;
destroySet.clear();
destroySet.push_back(id);
if (sublevels.Contains(id)) {
// removing a whole sublevel
// TODO
return;
//
}
let ownerID = GetSublevel(id);
if (!ownerID.IsNil()) {
sceneObjects.TryReleaseObject_Swap(id);
let pHierarchy = GetSublevelHierarchyFor(ownerID);
for (HierarchyDescendentIterator di(pHierarchy, id); di.MoveNext();)
destroySet.push_back(di.GetObject());
pHierarchy->TryRelease(id);
}
for(auto it : destroySet) {
for(auto listener : listeners)
listener->Scene_WillReleaseObject(this, it);
mgr.ReleaseObject(id);
}
}
void Scene::TryRename(ObjectID id, Name name) {
if (let pName = mgr.TryGetComponent<C_NAME>(id))
*pName = name;
}
Name Scene::GetName(ObjectID id) const {
let pName = mgr.GetPool().TryGetComponent<C_NAME>(id);
return pName ? *pName : Name(ForceInit::Default);
}
ObjectID Scene::FindObject(Name name) const {
let pNames = mgr.GetPool().GetComponentData<C_NAME>();
let n = mgr.GetPool().Count();
for(int it=0; it<n; ++it) {
if (name == pNames[it])
return *mgr.GetPool().GetComponentByIndex<C_HANDLE>(it);
}
return OBJECT_NIL;
}
void Scene::Hierarchy_DidAddObject(Hierarchy* hierarchy, ObjectID id) {
sceneObjects.TryAppendObject(id, hierarchy);
}
void Scene::Hierarchy_WillRemoveObject(Hierarchy* hierarchy, ObjectID id) {
sceneObjects.TryReleaseObject_Swap(id);
}
void Scene::SanityCheck() {
for (auto it = 0; it < GetSublevelCount(); ++it)
GetHierarchyByIndex(it)->SanityCheck();
}
| 23.273684 | 75 | 0.715966 | [
"vector"
] |
3144da783190bc12cff0f6d0e3a69cd7b88cadf7 | 2,016 | cpp | C++ | src/NextionIf.cpp | jyberg/ITEADLIB_Arduino_Nextion | 3448d5beeb49b11aeb1d791929f845e435d8516c | [
"MIT"
] | 42 | 2019-04-29T11:35:14.000Z | 2022-02-22T18:55:37.000Z | src/NextionIf.cpp | jyberg/ITEADLIB_Arduino_Nextion | 3448d5beeb49b11aeb1d791929f845e435d8516c | [
"MIT"
] | 26 | 2019-11-18T14:12:16.000Z | 2022-03-09T16:44:20.000Z | src/NextionIf.cpp | jyberg/ITEADLIB_Arduino_Nextion | 3448d5beeb49b11aeb1d791929f845e435d8516c | [
"MIT"
] | 24 | 2019-07-04T10:47:23.000Z | 2022-01-20T05:33:19.000Z | /**
* @file NextionIf.cpp
*
* Implementation of class NextionIf
*
* @author Jyrki Berg 11/23/2019 (https://github.com/jyberg)
*
* @copyright 2020 Jyrki Berg
*
**/
#include "NextionIf.h"
#include "NexHardware.h"
NextionIf::NextionIf(Nextion *nextion):m_nextion{nextion}
{}
NextionIf::~NextionIf()
{}
bool NextionIf::recvRetNumber(uint32_t *number, size_t timeout)
{
return m_nextion->recvRetNumber(number, timeout);
}
bool NextionIf::recvRetNumber(int32_t *number, size_t timeout)
{
return m_nextion->recvRetNumber(number, timeout);
}
bool NextionIf::recvRetString(String &str, size_t timeout, bool start_flag)
{
return m_nextion->recvRetString(str, timeout, start_flag);
}
bool NextionIf::recvRetString(char *buffer, uint16_t &len, size_t timeout, bool start_flag)
{
return m_nextion->recvRetString(buffer, len, timeout, start_flag);
}
void NextionIf::sendCommand(const char* cmd)
{
return m_nextion->sendCommand(cmd);
}
#ifdef ESP8266
void NextionIf::sendRawData(const std::vector<uint8_t> &data)
{
return m_nextion->sendRawData(data);
}
#endif
void NextionIf::sendRawData(const uint8_t *buf, uint16_t len)
{
return m_nextion->sendRawData(buf, len);
}
void NextionIf::sendRawByte(const uint8_t byte)
{
return m_nextion->sendRawByte(byte);
}
size_t NextionIf::readBytes(uint8_t* buffer, size_t size, size_t timeout)
{
return m_nextion->readBytes(buffer, size, timeout);
}
bool NextionIf::recvCommand(const uint8_t command, size_t timeout)
{
return m_nextion->recvCommand(command, timeout);
}
bool NextionIf::recvRetCommandFinished(size_t timeout)
{
return m_nextion->recvRetCommandFinished(timeout);
}
bool NextionIf::RecvTransparendDataModeReady(size_t timeout)
{
return m_nextion->RecvTransparendDataModeReady(timeout);
}
bool NextionIf::RecvTransparendDataModeFinished(size_t timeout)
{
return m_nextion->RecvTransparendDataModeFinished(timeout);
}
uint32_t NextionIf::GetCurrentBaud()
{
return m_nextion->GetCurrentBaud();
}
| 21.221053 | 91 | 0.750992 | [
"vector"
] |
314c864c13c7a81c557cb59dd4e9bf705070aeb6 | 2,360 | cpp | C++ | src/CollapsedBayesEngine.cpp | arunchaganty/ctm-cvb | 3e0fd5afe904b3e205ebfa422b6a1f677cee75c0 | [
"BSD-3-Clause"
] | 2 | 2019-11-24T02:58:21.000Z | 2020-02-29T14:31:58.000Z | src/CollapsedBayesEngine.cpp | arunchaganty/ctm-cvb | 3e0fd5afe904b3e205ebfa422b6a1f677cee75c0 | [
"BSD-3-Clause"
] | null | null | null | src/CollapsedBayesEngine.cpp | arunchaganty/ctm-cvb | 3e0fd5afe904b3e205ebfa422b6a1f677cee75c0 | [
"BSD-3-Clause"
] | null | null | null | /*
* ctm-cvb
*
* Collapsed Variational Bayes Inference Engine
*/
#include <iostream>
#include <limits>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
#include "ctm.h"
#include "util.h"
#include "ctm-data.h"
#include "CollapsedBayesEngine.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
namespace ctm
{
// Model
CollapsedBayesEngine::Model::Model( int D, int K, int V )
{
mu = gsl_vector_alloc( K );
cov = gsl_matrix_alloc( K, K );
inv_cov = gsl_matrix_alloc( K, K );
log_beta = gsl_matrix_alloc( K, V );
// TODO
gamma = 1;
log_det_inv_cov = 0;
}
CollapsedBayesEngine::Model::~Model()
{
gsl_vector_free( mu );
gsl_matrix_free( cov );
gsl_matrix_free( inv_cov );
gsl_matrix_free( log_beta );
}
// CollectedData
CollapsedBayesEngine::CollectedData::CollectedData( int D, int K, int V )
{
n_ij = gsl_matrix_alloc( D, K );
n_jk = gsl_matrix_alloc( K, V );
ndata = 0;
}
CollapsedBayesEngine::CollectedData::~CollectedData()
{
gsl_matrix_free( n_ij );
gsl_matrix_free( n_jk );
}
// Parameters
CollapsedBayesEngine::Parameters::Parameters( int K, int V )
{
// Re-used semi-sparse
phi = gsl_matrix_alloc( K, V );
log_phi = gsl_matrix_alloc( K, V );
lhood = 0;
}
CollapsedBayesEngine::Parameters::~Parameters()
{
gsl_matrix_free( phi );
gsl_matrix_free( log_phi );
}
CollapsedBayesEngine::CollapsedBayesEngine( InferenceOptions& options )
: InferenceEngine( options ), model( NULL )
{
}
void CollapsedBayesEngine::init( string filename ) {}
void CollapsedBayesEngine::save( string filename ) {}
double CollapsedBayesEngine::infer( Corpus& data )
{
return infer( data, NULL );
}
double CollapsedBayesEngine::infer( Corpus& data, CollectedData* cd )
{
// With CVB, only the \phi_{inj} have to be updated.
double lhood = 0;
double convergence = numeric_limits<double>::infinity();
do
{
} while( convergence > options.var_convergence );
return lhood;
}
void CollapsedBayesEngine::estimate( Corpus& data ) { }
};
| 22.056075 | 77 | 0.600424 | [
"model"
] |
315772fa66ca41c02e6ded987c757106b8de616a | 430 | cpp | C++ | Algorithms/0877.Stone_Game.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0877.Stone_Game.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0877.Stone_Game.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
bool stoneGame(vector<int>& ar) {
int n = ar.size();
int dp[n][n];
for( int i = 0 ; i < n ; i++ )
dp[i][i] = ar[i];
for( int len = 2 ; len <= n ; len++ )
for( int i = 0 ; i <= n-len ; i++ ) {
int j = i+len-1;
dp[i][j] = max(ar[i]-dp[i+1][j],ar[j]-dp[i][j-1]);
}
return dp[0][n-1] > 0;
}
}; | 28.666667 | 66 | 0.355814 | [
"vector"
] |
315c79cb7f527032f1e7f9337bfcb134eec7eab4 | 333,575 | cpp | C++ | test/tailoring_rule_test_zh_pinyin_004.cpp | jan-moeller/text | c61e51c82dfb0ae6e74200c01ce040fa6db730c4 | [
"BSL-1.0"
] | null | null | null | test/tailoring_rule_test_zh_pinyin_004.cpp | jan-moeller/text | c61e51c82dfb0ae6e74200c01ce040fa6db730c4 | [
"BSL-1.0"
] | 1 | 2021-03-05T12:56:59.000Z | 2021-03-05T13:11:53.000Z | test/tailoring_rule_test_zh_pinyin_004.cpp | jan-moeller/text | c61e51c82dfb0ae6e74200c01ce040fa6db730c4 | [
"BSL-1.0"
] | 3 | 2019-10-30T18:38:15.000Z | 2021-03-05T12:10:13.000Z |
// Warning! This file is autogenerated.
#include <boost/text/collation_table.hpp>
#include <boost/text/collate.hpp>
#include <boost/text/data/all.hpp>
#ifndef LIMIT_TESTING_FOR_CI
#include <boost/text/save_load_table.hpp>
#include <boost/filesystem.hpp>
#endif
#include <gtest/gtest.h>
using namespace boost::text;
auto const error = [](string const & s) { std::cout << s; };
auto const warning = [](string const & s) {};
collation_table make_save_load_table()
{
#ifdef LIMIT_TESTING_FOR_CI
string const table_str(data::zh::pinyin_collation_tailoring());
return tailored_collation_table(
table_str,
"zh::pinyin_collation_tailoring()", error, warning);
#else
if (!exists(boost::filesystem::path("zh_pinyin.table"))) {
string const table_str(data::zh::pinyin_collation_tailoring());
collation_table table = tailored_collation_table(
table_str,
"zh::pinyin_collation_tailoring()", error, warning);
save_table(table, "zh_pinyin.table.4");
boost::filesystem::rename("zh_pinyin.table.4", "zh_pinyin.table");
}
return load_table("zh_pinyin.table");
#endif
}
collation_table const & table()
{
static collation_table retval = make_save_load_table();
return retval;
}
TEST(tailoring, zh_pinyin_003_000)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x950b);
auto const rel = std::vector<uint32_t>(1, 0x6953);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6953);
auto const rel = std::vector<uint32_t>(1, 0x728e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x728e);
auto const rel = std::vector<uint32_t>(1, 0x8702);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8702);
auto const rel = std::vector<uint32_t>(1, 0x760b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x760b);
auto const rel = std::vector<uint32_t>(1, 0x78b8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x78b8);
auto const rel = std::vector<uint32_t>(1, 0x50fc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x50fc);
auto const rel = std::vector<uint32_t>(1, 0x7bc8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7bc8);
auto const rel = std::vector<uint32_t>(1, 0x9137);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9137);
auto const rel = std::vector<uint32_t>(1, 0x92d2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x92d2);
auto const rel = std::vector<uint32_t>(1, 0x6a92);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a92);
auto const rel = std::vector<uint32_t>(1, 0x95cf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95cf);
auto const rel = std::vector<uint32_t>(1, 0x8c50);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8c50);
auto const rel = std::vector<uint32_t>(1, 0x93bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x93bd);
auto const rel = std::vector<uint32_t>(1, 0x93e0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x93e0);
auto const rel = std::vector<uint32_t>(1, 0x9146);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9146);
auto const rel = std::vector<uint32_t>(1, 0x5bf7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5bf7);
auto const rel = std::vector<uint32_t>(1, 0x7043);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7043);
auto const rel = std::vector<uint32_t>(1, 0x8634);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8634);
auto const rel = std::vector<uint32_t>(1, 0x973b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x973b);
auto const rel = std::vector<uint32_t>(1, 0x882d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x882d);
auto const rel = std::vector<uint32_t>(1, 0x974a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x974a);
auto const rel = std::vector<uint32_t>(1, 0x98cc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x98cc);
auto const rel = std::vector<uint32_t>(1, 0x9eb7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9eb7);
auto const rel = std::vector<uint32_t>(1, 0x51af);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51af);
auto const rel = std::vector<uint32_t>(1, 0x5906);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5906);
auto const rel = std::vector<uint32_t>(1, 0x6340);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6340);
auto const rel = std::vector<uint32_t>(1, 0x6d72);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6d72);
auto const rel = std::vector<uint32_t>(1, 0x9022);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9022);
auto const rel = std::vector<uint32_t>(1, 0x5838);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5838);
auto const rel = std::vector<uint32_t>(1, 0x6e84);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e84);
auto const rel = std::vector<uint32_t>(1, 0x99ae);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x99ae);
auto const rel = std::vector<uint32_t>(1, 0x6453);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6453);
auto const rel = std::vector<uint32_t>(1, 0x6f28);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f28);
auto const rel = std::vector<uint32_t>(1, 0x7d98);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d98);
auto const rel = std::vector<uint32_t>(1, 0x8242);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8242);
auto const rel = std::vector<uint32_t>(1, 0x8982);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8982);
auto const rel = std::vector<uint32_t>(1, 0x552a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x552a);
auto const rel = std::vector<uint32_t>(1, 0x8af7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8af7);
auto const rel = std::vector<uint32_t>(1, 0x51e4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51e4);
auto const rel = std::vector<uint32_t>(1, 0x8bbd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8bbd);
auto const rel = std::vector<uint32_t>(1, 0x5949);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5949);
auto const rel = std::vector<uint32_t>(1, 0x752e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x752e);
auto const rel = std::vector<uint32_t>(1, 0x4ff8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4ff8);
auto const rel = std::vector<uint32_t>(1, 0x6e57);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e57);
auto const rel = std::vector<uint32_t>(1, 0x7128);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7128);
auto const rel = std::vector<uint32_t>(1, 0x7148);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7148);
auto const rel = std::vector<uint32_t>(1, 0x7f1d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f1d);
auto const rel = std::vector<uint32_t>(1, 0x8d57);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d57);
auto const rel = std::vector<uint32_t>(1, 0x9cef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cef);
auto const rel = std::vector<uint32_t>(1, 0x9cf3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cf3);
auto const rel = std::vector<uint32_t>(1, 0x9d0c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_001)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d0c);
auto const rel = std::vector<uint32_t>(1, 0x7e2b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7e2b);
auto const rel = std::vector<uint32_t>(1, 0x8cf5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8cf5);
auto const rel = std::vector<uint32_t>(1, 0x8985);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8985);
auto const rel = std::vector<uint32_t>(1, 0x4ecf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4ecf);
auto const rel = std::vector<uint32_t>(1, 0x5772);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5772);
auto const rel = std::vector<uint32_t>(1, 0x68bb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x68bb);
auto const rel = std::vector<uint32_t>(1, 0x7d11);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d11);
auto const rel = std::vector<uint32_t>(1, 0x88e6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88e6);
auto const rel = std::vector<uint32_t>(1, 0x7f36);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f36);
auto const rel = std::vector<uint32_t>(1, 0x5426);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5426);
auto const rel = std::vector<uint32_t>(1, 0x599a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x599a);
auto const rel = std::vector<uint32_t>(1, 0x7f39);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f39);
auto const rel = std::vector<uint32_t>(1, 0x7f3b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f3b);
auto const rel = std::vector<uint32_t>(1, 0x6b95);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6b95);
auto const rel = std::vector<uint32_t>(1, 0x96ec);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x96ec);
auto const rel = std::vector<uint32_t>(1, 0x9d00);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d00);
auto const rel = std::vector<uint32_t>(1, 0x592b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x592b);
auto const rel = std::vector<uint32_t>(1, 0x4f15);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f15);
auto const rel = std::vector<uint32_t>(1, 0x909e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x909e);
auto const rel = std::vector<uint32_t>(1, 0x544b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x544b);
auto const rel = std::vector<uint32_t>(1, 0x598b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x598b);
auto const rel = std::vector<uint32_t>(1, 0x59c7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59c7);
auto const rel = std::vector<uint32_t>(1, 0x739e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x739e);
auto const rel = std::vector<uint32_t>(1, 0x80a4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80a4);
auto const rel = std::vector<uint32_t>(1, 0x6024);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6024);
auto const rel = std::vector<uint32_t>(1, 0x67ce);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67ce);
auto const rel = std::vector<uint32_t>(1, 0x7806);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7806);
auto const rel = std::vector<uint32_t>(1, 0x8342);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8342);
auto const rel = std::vector<uint32_t>(1, 0x886d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x886d);
auto const rel = std::vector<uint32_t>(1, 0x57ba);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x57ba);
auto const rel = std::vector<uint32_t>(1, 0x5a10);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5a10);
auto const rel = std::vector<uint32_t>(1, 0x5c03);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c03);
auto const rel = std::vector<uint32_t>(1, 0x8374);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8374);
auto const rel = std::vector<uint32_t>(1, 0x65c9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x65c9);
auto const rel = std::vector<uint32_t>(1, 0x7d28);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d28);
auto const rel = std::vector<uint32_t>(1, 0x8dba);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8dba);
auto const rel = std::vector<uint32_t>(1, 0x9eb8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9eb8);
auto const rel = std::vector<uint32_t>(1, 0x75e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x75e1);
auto const rel = std::vector<uint32_t>(1, 0x7a03);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a03);
auto const rel = std::vector<uint32_t>(1, 0x8dd7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8dd7);
auto const rel = std::vector<uint32_t>(1, 0x9207);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9207);
auto const rel = std::vector<uint32_t>(1, 0x7b5f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b5f);
auto const rel = std::vector<uint32_t>(1, 0x7d92);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d92);
auto const rel = std::vector<uint32_t>(1, 0x911c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x911c);
auto const rel = std::vector<uint32_t>(1, 0x5b75);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b75);
auto const rel = std::vector<uint32_t>(1, 0x8c67);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8c67);
auto const rel = std::vector<uint32_t>(1, 0x6577);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6577);
auto const rel = std::vector<uint32_t>(1, 0x819a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x819a);
auto const rel = std::vector<uint32_t>(1, 0x9cfa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cfa);
auto const rel = std::vector<uint32_t>(1, 0x9ea9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ea9);
auto const rel = std::vector<uint32_t>(1, 0x7cd0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_002)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7cd0);
auto const rel = std::vector<uint32_t>(1, 0x9eac);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9eac);
auto const rel = std::vector<uint32_t>(1, 0x9eb1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9eb1);
auto const rel = std::vector<uint32_t>(1, 0x61ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x61ef);
auto const rel = std::vector<uint32_t>(1, 0x4e40);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e40);
auto const rel = std::vector<uint32_t>(1, 0x5dff);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5dff);
auto const rel = std::vector<uint32_t>(1, 0x5f17);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f17);
auto const rel = std::vector<uint32_t>(1, 0x4f0f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f0f);
auto const rel = std::vector<uint32_t>(1, 0x51eb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51eb);
auto const rel = std::vector<uint32_t>(1, 0x7536);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7536);
auto const rel = std::vector<uint32_t>(1, 0x4f5b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f5b);
auto const rel = std::vector<uint32_t>(1, 0x51b9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51b9);
auto const rel = std::vector<uint32_t>(1, 0x521c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x521c);
auto const rel = std::vector<uint32_t>(1, 0x5b5a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b5a);
auto const rel = std::vector<uint32_t>(1, 0x6276);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6276);
auto const rel = std::vector<uint32_t>(1, 0x8299);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8299);
auto const rel = std::vector<uint32_t>(1, 0x82a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82a3);
auto const rel = std::vector<uint32_t>(1, 0x5488);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5488);
auto const rel = std::vector<uint32_t>(1, 0x5caa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5caa);
auto const rel = std::vector<uint32_t>(1, 0x5f7f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f7f);
auto const rel = std::vector<uint32_t>(1, 0x602b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x602b);
auto const rel = std::vector<uint32_t>(1, 0x62c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x62c2);
auto const rel = std::vector<uint32_t>(1, 0x670d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x670d);
auto const rel = std::vector<uint32_t>(1, 0x678e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x678e);
auto const rel = std::vector<uint32_t>(1, 0x6ced);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6ced);
auto const rel = std::vector<uint32_t>(1, 0x7ec2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ec2);
auto const rel = std::vector<uint32_t>(1, 0x7ecb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ecb);
auto const rel = std::vector<uint32_t>(1, 0x82fb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82fb);
auto const rel = std::vector<uint32_t>(1, 0x8300);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8300);
auto const rel = std::vector<uint32_t>(1, 0x4fd8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4fd8);
auto const rel = std::vector<uint32_t>(1, 0x5798);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5798);
auto const rel = std::vector<uint32_t>(1, 0x67eb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67eb);
auto const rel = std::vector<uint32_t>(1, 0x6c1f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c1f);
auto const rel = std::vector<uint32_t>(1, 0x6d11);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6d11);
auto const rel = std::vector<uint32_t>(1, 0x70a5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x70a5);
auto const rel = std::vector<uint32_t>(1, 0x73b8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x73b8);
auto const rel = std::vector<uint32_t>(1, 0x7549);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7549);
auto const rel = std::vector<uint32_t>(1, 0x7550);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7550);
auto const rel = std::vector<uint32_t>(1, 0x7953);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7953);
auto const rel = std::vector<uint32_t>(1, 0x7f58);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f58);
auto const rel = std::vector<uint32_t>(1, 0x832f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x832f);
auto const rel = std::vector<uint32_t>(1, 0x90db);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90db);
auto const rel = std::vector<uint32_t>(1, 0x97e8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97e8);
auto const rel = std::vector<uint32_t>(1, 0x54f9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54f9);
auto const rel = std::vector<uint32_t>(1, 0x683f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x683f);
auto const rel = std::vector<uint32_t>(1, 0x6d6e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6d6e);
auto const rel = std::vector<uint32_t>(1, 0x7829);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7829);
auto const rel = std::vector<uint32_t>(1, 0x83a9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83a9);
auto const rel = std::vector<uint32_t>(1, 0x86a8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86a8);
auto const rel = std::vector<uint32_t>(1, 0x5310);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5310);
auto const rel = std::vector<uint32_t>(1, 0x6874);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6874);
auto const rel = std::vector<uint32_t>(1, 0x6daa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_003)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6daa);
auto const rel = std::vector<uint32_t>(1, 0x70f0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x70f0);
auto const rel = std::vector<uint32_t>(1, 0x7408);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7408);
auto const rel = std::vector<uint32_t>(1, 0x7b26);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b26);
auto const rel = std::vector<uint32_t>(1, 0x7b30);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b30);
auto const rel = std::vector<uint32_t>(1, 0x7d31);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d31);
auto const rel = std::vector<uint32_t>(1, 0x7d3c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d3c);
auto const rel = std::vector<uint32_t>(1, 0x7fc7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7fc7);
auto const rel = std::vector<uint32_t>(1, 0x8274);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8274);
auto const rel = std::vector<uint32_t>(1, 0x83d4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83d4);
auto const rel = std::vector<uint32_t>(1, 0x8659);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8659);
auto const rel = std::vector<uint32_t>(1, 0x88b1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88b1);
auto const rel = std::vector<uint32_t>(1, 0x5e45);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e45);
auto const rel = std::vector<uint32_t>(1, 0x68f4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x68f4);
auto const rel = std::vector<uint32_t>(1, 0x7d65);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d65);
auto const rel = std::vector<uint32_t>(1, 0x7f66);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f66);
auto const rel = std::vector<uint32_t>(1, 0x844d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x844d);
auto const rel = std::vector<uint32_t>(1, 0x798f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x798f);
auto const rel = std::vector<uint32_t>(1, 0x7cb0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7cb0);
auto const rel = std::vector<uint32_t>(1, 0x7d8d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d8d);
auto const rel = std::vector<uint32_t>(1, 0x8240);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8240);
auto const rel = std::vector<uint32_t>(1, 0x8709);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8709);
auto const rel = std::vector<uint32_t>(1, 0x8f90);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f90);
auto const rel = std::vector<uint32_t>(1, 0x9258);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9258);
auto const rel = std::vector<uint32_t>(1, 0x925c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x925c);
auto const rel = std::vector<uint32_t>(1, 0x98ab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x98ab);
auto const rel = std::vector<uint32_t>(1, 0x9ce7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ce7);
auto const rel = std::vector<uint32_t>(1, 0x6991);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6991);
auto const rel = std::vector<uint32_t>(1, 0x7a2a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a2a);
auto const rel = std::vector<uint32_t>(1, 0x7b99);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b99);
auto const rel = std::vector<uint32_t>(1, 0x97cd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97cd);
auto const rel = std::vector<uint32_t>(1, 0x5e5e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e5e);
auto const rel = std::vector<uint32_t>(1, 0x6f93);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f93);
auto const rel = std::vector<uint32_t>(1, 0x8760);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8760);
auto const rel = std::vector<uint32_t>(1, 0x9af4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9af4);
auto const rel = std::vector<uint32_t>(1, 0x9d14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d14);
auto const rel = std::vector<uint32_t>(1, 0x8ae8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ae8);
auto const rel = std::vector<uint32_t>(1, 0x8e3e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8e3e);
auto const rel = std::vector<uint32_t>(1, 0x8f3b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f3b);
auto const rel = std::vector<uint32_t>(1, 0x9b84);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b84);
auto const rel = std::vector<uint32_t>(1, 0x7641);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7641);
auto const rel = std::vector<uint32_t>(1, 0x8946);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8946);
auto const rel = std::vector<uint32_t>(1, 0x9bb2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9bb2);
auto const rel = std::vector<uint32_t>(1, 0x9efb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9efb);
auto const rel = std::vector<uint32_t>(1, 0x8965);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8965);
auto const rel = std::vector<uint32_t>(1, 0x9d69);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d69);
auto const rel = std::vector<uint32_t>(1, 0x9d9d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d9d);
auto const rel = std::vector<uint32_t>(1, 0x5452);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5452);
auto const rel = std::vector<uint32_t>(1, 0x629a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x629a);
auto const rel = std::vector<uint32_t>(1, 0x752b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x752b);
auto const rel = std::vector<uint32_t>(1, 0x4e76);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e76);
auto const rel = std::vector<uint32_t>(1, 0x5e9c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_004)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e9c);
auto const rel = std::vector<uint32_t>(1, 0x5f23);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f23);
auto const rel = std::vector<uint32_t>(1, 0x62ca);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x62ca);
auto const rel = std::vector<uint32_t>(1, 0x65a7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x65a7);
auto const rel = std::vector<uint32_t>(1, 0x4fcc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4fcc);
auto const rel = std::vector<uint32_t>(1, 0x4fdb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4fdb);
auto const rel = std::vector<uint32_t>(1, 0x80d5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80d5);
auto const rel = std::vector<uint32_t>(1, 0x90d9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90d9);
auto const rel = std::vector<uint32_t>(1, 0x9cec);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cec);
auto const rel = std::vector<uint32_t>(1, 0x4fef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4fef);
auto const rel = std::vector<uint32_t>(1, 0x91dc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x91dc);
auto const rel = std::vector<uint32_t>(1, 0x91e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x91e1);
auto const rel = std::vector<uint32_t>(1, 0x636c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x636c);
auto const rel = std::vector<uint32_t>(1, 0x8f85);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f85);
auto const rel = std::vector<uint32_t>(1, 0x6928);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6928);
auto const rel = std::vector<uint32_t>(1, 0x7124);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7124);
auto const rel = std::vector<uint32_t>(1, 0x76d9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76d9);
auto const rel = std::vector<uint32_t>(1, 0x8151);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8151);
auto const rel = std::vector<uint32_t>(1, 0x6ecf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6ecf);
auto const rel = std::vector<uint32_t>(1, 0x8705);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8705);
auto const rel = std::vector<uint32_t>(1, 0x8150);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8150);
auto const rel = std::vector<uint32_t>(1, 0x8f14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f14);
auto const rel = std::vector<uint32_t>(1, 0x5638);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5638);
auto const rel = std::vector<uint32_t>(1, 0x64a8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x64a8);
auto const rel = std::vector<uint32_t>(1, 0x64ab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x64ab);
auto const rel = std::vector<uint32_t>(1, 0x982b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x982b);
auto const rel = std::vector<uint32_t>(1, 0x9b34);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b34);
auto const rel = std::vector<uint32_t>(1, 0x7c20);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7c20);
auto const rel = std::vector<uint32_t>(1, 0x9efc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9efc);
auto const rel = std::vector<uint32_t>(1, 0x961d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x961d);
auto const rel = std::vector<uint32_t>(1, 0x7236);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7236);
auto const rel = std::vector<uint32_t>(1, 0x8ba3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ba3);
auto const rel = std::vector<uint32_t>(1, 0x4ed8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4ed8);
auto const rel = std::vector<uint32_t>(1, 0x5987);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5987);
auto const rel = std::vector<uint32_t>(1, 0x8d1f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d1f);
auto const rel = std::vector<uint32_t>(1, 0x9644);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9644);
auto const rel = std::vector<uint32_t>(1, 0x5490);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5490);
auto const rel = std::vector<uint32_t>(1, 0x577f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x577f);
auto const rel = std::vector<uint32_t>(1, 0x7ace);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ace);
auto const rel = std::vector<uint32_t>(1, 0x961c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x961c);
auto const rel = std::vector<uint32_t>(1, 0x9a78);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9a78);
auto const rel = std::vector<uint32_t>(1, 0x590d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x590d);
auto const rel = std::vector<uint32_t>(1, 0x5cca);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5cca);
auto const rel = std::vector<uint32_t>(1, 0x7954);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7954);
auto const rel = std::vector<uint32_t>(1, 0x8a03);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a03);
auto const rel = std::vector<uint32_t>(1, 0x8ca0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ca0);
auto const rel = std::vector<uint32_t>(1, 0x8d74);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d74);
auto const rel = std::vector<uint32_t>(1, 0x86a5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86a5);
auto const rel = std::vector<uint32_t>(1, 0x889d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x889d);
auto const rel = std::vector<uint32_t>(1, 0x965a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x965a);
auto const rel = std::vector<uint32_t>(1, 0x5069);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5069);
auto const rel = std::vector<uint32_t>(1, 0x51a8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_005)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51a8);
auto const rel = std::vector<uint32_t>(1, 0x526f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x526f);
auto const rel = std::vector<uint32_t>(1, 0x5a66);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5a66);
auto const rel = std::vector<uint32_t>(1, 0x86b9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86b9);
auto const rel = std::vector<uint32_t>(1, 0x5085);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5085);
auto const rel = std::vector<uint32_t>(1, 0x5a8d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5a8d);
auto const rel = std::vector<uint32_t>(1, 0x5bcc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5bcc);
auto const rel = std::vector<uint32_t>(1, 0x5fa9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5fa9);
auto const rel = std::vector<uint32_t>(1, 0x79ff);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x79ff);
auto const rel = std::vector<uint32_t>(1, 0x842f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x842f);
auto const rel = std::vector<uint32_t>(1, 0x86d7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86d7);
auto const rel = std::vector<uint32_t>(1, 0x8984);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8984);
auto const rel = std::vector<uint32_t>(1, 0x8a42);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a42);
auto const rel = std::vector<uint32_t>(1, 0x8d4b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d4b);
auto const rel = std::vector<uint32_t>(1, 0x6931);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6931);
auto const rel = std::vector<uint32_t>(1, 0x7f1a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f1a);
auto const rel = std::vector<uint32_t>(1, 0x8179);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8179);
auto const rel = std::vector<uint32_t>(1, 0x9c8b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c8b);
auto const rel = std::vector<uint32_t>(1, 0x79a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x79a3);
auto const rel = std::vector<uint32_t>(1, 0x8907);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8907);
auto const rel = std::vector<uint32_t>(1, 0x8914);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8914);
auto const rel = std::vector<uint32_t>(1, 0x8d59);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d59);
auto const rel = std::vector<uint32_t>(1, 0x7dee);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7dee);
auto const rel = std::vector<uint32_t>(1, 0x8567);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8567);
auto const rel = std::vector<uint32_t>(1, 0x875c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x875c);
auto const rel = std::vector<uint32_t>(1, 0x876e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x876e);
auto const rel = std::vector<uint32_t>(1, 0x8ce6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ce6);
auto const rel = std::vector<uint32_t>(1, 0x99d9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x99d9);
auto const rel = std::vector<uint32_t>(1, 0x5b14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b14);
auto const rel = std::vector<uint32_t>(1, 0x7e1b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7e1b);
auto const rel = std::vector<uint32_t>(1, 0x8f39);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f39);
auto const rel = std::vector<uint32_t>(1, 0x9b92);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b92);
auto const rel = std::vector<uint32_t>(1, 0x8cfb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8cfb);
auto const rel = std::vector<uint32_t>(1, 0x9351);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9351);
auto const rel = std::vector<uint32_t>(1, 0x9362);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9362);
auto const rel = std::vector<uint32_t>(1, 0x9cc6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cc6);
auto const rel = std::vector<uint32_t>(1, 0x8986);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8986);
auto const rel = std::vector<uint32_t>(1, 0x99a5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x99a5);
auto const rel = std::vector<uint32_t>(1, 0x9c12);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c12);
auto const rel = std::vector<uint32_t>(1, 0x915c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x915c);
auto const rel = std::vector<uint32_t>{0xfdd0, 0x0047};
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>{0xfdd0, 0x0047};
auto const rel = std::vector<uint32_t>(1, 0x65ee);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x65ee);
auto const rel = std::vector<uint32_t>(1, 0x5477);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5477);
auto const rel = std::vector<uint32_t>(1, 0x560e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x560e);
auto const rel = std::vector<uint32_t>(1, 0x5620);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5620);
auto const rel = std::vector<uint32_t>(1, 0x9486);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9486);
auto const rel = std::vector<uint32_t>(1, 0x5c1c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c1c);
auto const rel = std::vector<uint32_t>(1, 0x5676);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5676);
auto const rel = std::vector<uint32_t>(1, 0x9337);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9337);
auto const rel = std::vector<uint32_t>(1, 0x5c15);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c15);
auto const rel = std::vector<uint32_t>(1, 0x738d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x738d);
auto const rel = std::vector<uint32_t>(1, 0x5c2c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_006)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c2c);
auto const rel = std::vector<uint32_t>(1, 0x9b40);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b40);
auto const rel = std::vector<uint32_t>(1, 0x4f85);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f85);
auto const rel = std::vector<uint32_t>(1, 0x8be5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8be5);
auto const rel = std::vector<uint32_t>(1, 0x90c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90c2);
auto const rel = std::vector<uint32_t>(1, 0x9654);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9654);
auto const rel = std::vector<uint32_t>(1, 0x5793);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5793);
auto const rel = std::vector<uint32_t>(1, 0x59df);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59df);
auto const rel = std::vector<uint32_t>(1, 0x5cd0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5cd0);
auto const rel = std::vector<uint32_t>(1, 0x8344);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8344);
auto const rel = std::vector<uint32_t>(1, 0x6650);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6650);
auto const rel = std::vector<uint32_t>(1, 0x8d45);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d45);
auto const rel = std::vector<uint32_t>(1, 0x7561);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7561);
auto const rel = std::vector<uint32_t>(1, 0x7974);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7974);
auto const rel = std::vector<uint32_t>(1, 0x7d6f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d6f);
auto const rel = std::vector<uint32_t>(1, 0x8a72);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a72);
auto const rel = std::vector<uint32_t>(1, 0x8c65);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8c65);
auto const rel = std::vector<uint32_t>(1, 0x8cc5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8cc5);
auto const rel = std::vector<uint32_t>(1, 0x8ccc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ccc);
auto const rel = std::vector<uint32_t>(1, 0x5fcb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5fcb);
auto const rel = std::vector<uint32_t>(1, 0x6539);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6539);
auto const rel = std::vector<uint32_t>(1, 0x7d60);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d60);
auto const rel = std::vector<uint32_t>(1, 0x4e10);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e10);
auto const rel = std::vector<uint32_t>(1, 0x4e62);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e62);
auto const rel = std::vector<uint32_t>(1, 0x5303);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5303);
auto const rel = std::vector<uint32_t>(1, 0x5304);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5304);
auto const rel = std::vector<uint32_t>(1, 0x9623);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9623);
auto const rel = std::vector<uint32_t>(1, 0x675a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x675a);
auto const rel = std::vector<uint32_t>(1, 0x9499);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9499);
auto const rel = std::vector<uint32_t>(1, 0x76d6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76d6);
auto const rel = std::vector<uint32_t>(1, 0x6461);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6461);
auto const rel = std::vector<uint32_t>(1, 0x6e89);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e89);
auto const rel = std::vector<uint32_t>(1, 0x8462);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8462);
auto const rel = std::vector<uint32_t>(1, 0x9223);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9223);
auto const rel = std::vector<uint32_t>(1, 0x9691);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9691);
auto const rel = std::vector<uint32_t>(1, 0x6224);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6224);
auto const rel = std::vector<uint32_t>(1, 0x6982);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6982);
auto const rel = std::vector<uint32_t>(1, 0x69e9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69e9);
auto const rel = std::vector<uint32_t>(1, 0x84cb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x84cb);
auto const rel = std::vector<uint32_t>(1, 0x6f11);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f11);
auto const rel = std::vector<uint32_t>(1, 0x69ea);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69ea);
auto const rel = std::vector<uint32_t>(1, 0x74c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x74c2);
auto const rel = std::vector<uint32_t>(1, 0x7518);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7518);
auto const rel = std::vector<uint32_t>(1, 0x5fd3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5fd3);
auto const rel = std::vector<uint32_t>(1, 0x8289);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8289);
auto const rel = std::vector<uint32_t>(1, 0x8fc0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8fc0);
auto const rel = std::vector<uint32_t>(1, 0x653c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x653c);
auto const rel = std::vector<uint32_t>(1, 0x6746);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6746);
auto const rel = std::vector<uint32_t>(1, 0x7395);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7395);
auto const rel = std::vector<uint32_t>(1, 0x809d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x809d);
auto const rel = std::vector<uint32_t>(1, 0x5769);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5769);
auto const rel = std::vector<uint32_t>(1, 0x6cd4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_007)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6cd4);
auto const rel = std::vector<uint32_t>(1, 0x77f8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x77f8);
auto const rel = std::vector<uint32_t>(1, 0x82f7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82f7);
auto const rel = std::vector<uint32_t>(1, 0x4e79);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e79);
auto const rel = std::vector<uint32_t>(1, 0x67d1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67d1);
auto const rel = std::vector<uint32_t>(1, 0x7aff);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7aff);
auto const rel = std::vector<uint32_t>(1, 0x75b3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x75b3);
auto const rel = std::vector<uint32_t>(1, 0x9150);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9150);
auto const rel = std::vector<uint32_t>(1, 0x4e7e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e7e);
auto const rel = std::vector<uint32_t>(1, 0x7c93);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7c93);
auto const rel = std::vector<uint32_t>(1, 0x4e81);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e81);
auto const rel = std::vector<uint32_t>(1, 0x51f2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51f2);
auto const rel = std::vector<uint32_t>(1, 0x5c32);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c32);
auto const rel = std::vector<uint32_t>(1, 0x5c34);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c34);
auto const rel = std::vector<uint32_t>(1, 0x7b78);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b78);
auto const rel = std::vector<uint32_t>(1, 0x6f27);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f27);
auto const rel = std::vector<uint32_t>(1, 0x9cf1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cf1);
auto const rel = std::vector<uint32_t>(1, 0x5c36);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c36);
auto const rel = std::vector<uint32_t>(1, 0x5c37);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c37);
auto const rel = std::vector<uint32_t>(1, 0x9b50);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b50);
auto const rel = std::vector<uint32_t>(1, 0x4ee0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4ee0);
auto const rel = std::vector<uint32_t>(1, 0x625e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x625e);
auto const rel = std::vector<uint32_t>(1, 0x76af);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76af);
auto const rel = std::vector<uint32_t>(1, 0x79c6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x79c6);
auto const rel = std::vector<uint32_t>(1, 0x8866);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8866);
auto const rel = std::vector<uint32_t>(1, 0x8d76);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d76);
auto const rel = std::vector<uint32_t>(1, 0x6562);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6562);
auto const rel = std::vector<uint32_t>(1, 0x687f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x687f);
auto const rel = std::vector<uint32_t>(1, 0x7b34);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b34);
auto const rel = std::vector<uint32_t>(1, 0x7a08);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a08);
auto const rel = std::vector<uint32_t>(1, 0x611f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x611f);
auto const rel = std::vector<uint32_t>(1, 0x6f89);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f89);
auto const rel = std::vector<uint32_t>(1, 0x8d95);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d95);
auto const rel = std::vector<uint32_t>(1, 0x6a44);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a44);
auto const rel = std::vector<uint32_t>(1, 0x64c0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x64c0);
auto const rel = std::vector<uint32_t>(1, 0x7c33);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7c33);
auto const rel = std::vector<uint32_t>(1, 0x9c14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c14);
auto const rel = std::vector<uint32_t>(1, 0x9ce1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ce1);
auto const rel = std::vector<uint32_t>(1, 0x9c64);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c64);
auto const rel = std::vector<uint32_t>(1, 0x5e72);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e72);
auto const rel = std::vector<uint32_t>(1, 0x65f0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x65f0);
auto const rel = std::vector<uint32_t>(1, 0x6c75);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c75);
auto const rel = std::vector<uint32_t>(1, 0x76f0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76f0);
auto const rel = std::vector<uint32_t>(1, 0x7ec0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ec0);
auto const rel = std::vector<uint32_t>(1, 0x501d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x501d);
auto const rel = std::vector<uint32_t>(1, 0x51ce);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51ce);
auto const rel = std::vector<uint32_t>(1, 0x6de6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6de6);
auto const rel = std::vector<uint32_t>(1, 0x7d3a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d3a);
auto const rel = std::vector<uint32_t>(1, 0x8a4c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a4c);
auto const rel = std::vector<uint32_t>(1, 0x9aad);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9aad);
auto const rel = std::vector<uint32_t>(1, 0x5e79);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e79);
auto const rel = std::vector<uint32_t>(1, 0x69a6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_008)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69a6);
auto const rel = std::vector<uint32_t>(1, 0x6a8a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a8a);
auto const rel = std::vector<uint32_t>(1, 0x8d11);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d11);
auto const rel = std::vector<uint32_t>(1, 0x8d63);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d63);
auto const rel = std::vector<uint32_t>(1, 0x8d1b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d1b);
auto const rel = std::vector<uint32_t>(1, 0x7068);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7068);
auto const rel = std::vector<uint32_t>(1, 0x5188);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5188);
auto const rel = std::vector<uint32_t>(1, 0x7f53);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f53);
auto const rel = std::vector<uint32_t>(1, 0x51ae);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51ae);
auto const rel = std::vector<uint32_t>(1, 0x521a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x521a);
auto const rel = std::vector<uint32_t>(1, 0x6760);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6760);
auto const rel = std::vector<uint32_t>(1, 0x7eb2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7eb2);
auto const rel = std::vector<uint32_t>(1, 0x809b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x809b);
auto const rel = std::vector<uint32_t>(1, 0x5ca1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5ca1);
auto const rel = std::vector<uint32_t>(1, 0x7268);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7268);
auto const rel = std::vector<uint32_t>(1, 0x7598);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7598);
auto const rel = std::vector<uint32_t>(1, 0x77fc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x77fc);
auto const rel = std::vector<uint32_t>(1, 0x7f38);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f38);
auto const rel = std::vector<uint32_t>(1, 0x94a2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x94a2);
auto const rel = std::vector<uint32_t>(1, 0x525b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x525b);
auto const rel = std::vector<uint32_t>(1, 0x7f61);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f61);
auto const rel = std::vector<uint32_t>(1, 0x5808);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5808);
auto const rel = std::vector<uint32_t>(1, 0x6386);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6386);
auto const rel = std::vector<uint32_t>(1, 0x91ed);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x91ed);
auto const rel = std::vector<uint32_t>(1, 0x68e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x68e1);
auto const rel = std::vector<uint32_t>(1, 0x7285);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7285);
auto const rel = std::vector<uint32_t>(1, 0x583d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x583d);
auto const rel = std::vector<uint32_t>(1, 0x7db1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7db1);
auto const rel = std::vector<uint32_t>(1, 0x7f41);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f41);
auto const rel = std::vector<uint32_t>(1, 0x92fc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x92fc);
auto const rel = std::vector<uint32_t>(1, 0x93a0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x93a0);
auto const rel = std::vector<uint32_t>(1, 0x5c97);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c97);
auto const rel = std::vector<uint32_t>(1, 0x5d17);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5d17);
auto const rel = std::vector<uint32_t>(1, 0x6e2f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e2f);
auto const rel = std::vector<uint32_t>(1, 0x7135);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7135);
auto const rel = std::vector<uint32_t>(1, 0x7139);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7139);
auto const rel = std::vector<uint32_t>(1, 0x7b7b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b7b);
auto const rel = std::vector<uint32_t>(1, 0x69d3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69d3);
auto const rel = std::vector<uint32_t>(1, 0x6205);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6205);
auto const rel = std::vector<uint32_t>(1, 0x6206);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6206);
auto const rel = std::vector<uint32_t>(1, 0x768b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x768b);
auto const rel = std::vector<uint32_t>(1, 0x7f94);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f94);
auto const rel = std::vector<uint32_t>(1, 0x7f99);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f99);
auto const rel = std::vector<uint32_t>(1, 0x9ad8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ad8);
auto const rel = std::vector<uint32_t>(1, 0x7690);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7690);
auto const rel = std::vector<uint32_t>(1, 0x9ad9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ad9);
auto const rel = std::vector<uint32_t>(1, 0x81ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81ef);
auto const rel = std::vector<uint32_t>(1, 0x6edc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6edc);
auto const rel = std::vector<uint32_t>(1, 0x69d4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69d4);
auto const rel = std::vector<uint32_t>(1, 0x777e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x777e);
auto const rel = std::vector<uint32_t>(1, 0x818f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x818f);
auto const rel = std::vector<uint32_t>(1, 0x69f9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_009)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69f9);
auto const rel = std::vector<uint32_t>(1, 0x6a70);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a70);
auto const rel = std::vector<uint32_t>(1, 0x7bd9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7bd9);
auto const rel = std::vector<uint32_t>(1, 0x7cd5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7cd5);
auto const rel = std::vector<uint32_t>(1, 0x993b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x993b);
auto const rel = std::vector<uint32_t>(1, 0x6adc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6adc);
auto const rel = std::vector<uint32_t>(1, 0x97df);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97df);
auto const rel = std::vector<uint32_t>(1, 0x9dce);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9dce);
auto const rel = std::vector<uint32_t>(1, 0x9f1b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f1b);
auto const rel = std::vector<uint32_t>(1, 0x9df1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9df1);
auto const rel = std::vector<uint32_t>(1, 0x5930);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5930);
auto const rel = std::vector<uint32_t>(1, 0x6772);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6772);
auto const rel = std::vector<uint32_t>(1, 0x83d2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83d2);
auto const rel = std::vector<uint32_t>(1, 0x7a01);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a01);
auto const rel = std::vector<uint32_t>(1, 0x641e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x641e);
auto const rel = std::vector<uint32_t>(1, 0x7f1f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f1f);
auto const rel = std::vector<uint32_t>(1, 0x66a0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x66a0);
auto const rel = std::vector<uint32_t>(1, 0x69c0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69c0);
auto const rel = std::vector<uint32_t>(1, 0x69c1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69c1);
auto const rel = std::vector<uint32_t>(1, 0x7a3e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a3e);
auto const rel = std::vector<uint32_t>(1, 0x7a3f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a3f);
auto const rel = std::vector<uint32_t>(1, 0x9550);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9550);
auto const rel = std::vector<uint32_t>(1, 0x7e1e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7e1e);
auto const rel = std::vector<uint32_t>(1, 0x85c1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x85c1);
auto const rel = std::vector<uint32_t>(1, 0x6aba);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6aba);
auto const rel = std::vector<uint32_t>(1, 0x85f3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x85f3);
auto const rel = std::vector<uint32_t>(1, 0x543f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x543f);
auto const rel = std::vector<uint32_t>(1, 0x544a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x544a);
auto const rel = std::vector<uint32_t>(1, 0x52c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x52c2);
auto const rel = std::vector<uint32_t>(1, 0x8bf0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8bf0);
auto const rel = std::vector<uint32_t>(1, 0x90dc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90dc);
auto const rel = std::vector<uint32_t>(1, 0x5cfc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5cfc);
auto const rel = std::vector<uint32_t>(1, 0x796e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x796e);
auto const rel = std::vector<uint32_t>(1, 0x7970);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7970);
auto const rel = std::vector<uint32_t>(1, 0x9506);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9506);
auto const rel = std::vector<uint32_t>(1, 0x7b76);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b76);
auto const rel = std::vector<uint32_t>(1, 0x799e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x799e);
auto const rel = std::vector<uint32_t>(1, 0x8aa5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8aa5);
auto const rel = std::vector<uint32_t>(1, 0x92ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x92ef);
auto const rel = std::vector<uint32_t>(1, 0x6208);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6208);
auto const rel = std::vector<uint32_t>(1, 0x4ee1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4ee1);
auto const rel = std::vector<uint32_t>(1, 0x572a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x572a);
auto const rel = std::vector<uint32_t>(1, 0x72b5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x72b5);
auto const rel = std::vector<uint32_t>(1, 0x7ea5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ea5);
auto const rel = std::vector<uint32_t>(1, 0x6213);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6213);
auto const rel = std::vector<uint32_t>(1, 0x8090);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8090);
auto const rel = std::vector<uint32_t>(1, 0x726b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x726b);
auto const rel = std::vector<uint32_t>(1, 0x7599);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7599);
auto const rel = std::vector<uint32_t>(1, 0x54af);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54af);
auto const rel = std::vector<uint32_t>(1, 0x7271);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7271);
auto const rel = std::vector<uint32_t>(1, 0x54e5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54e5);
auto const rel = std::vector<uint32_t>(1, 0x80f3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_010)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80f3);
auto const rel = std::vector<uint32_t>(1, 0x88bc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88bc);
auto const rel = std::vector<uint32_t>(1, 0x9e3d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e3d);
auto const rel = std::vector<uint32_t>(1, 0x5272);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5272);
auto const rel = std::vector<uint32_t>(1, 0x6401);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6401);
auto const rel = std::vector<uint32_t>(1, 0x5f41);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f41);
auto const rel = std::vector<uint32_t>(1, 0x6ed2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6ed2);
auto const rel = std::vector<uint32_t>(1, 0x6228);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6228);
auto const rel = std::vector<uint32_t>(1, 0x6b4c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6b4c);
auto const rel = std::vector<uint32_t>(1, 0x9d10);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d10);
auto const rel = std::vector<uint32_t>(1, 0x9d1a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d1a);
auto const rel = std::vector<uint32_t>(1, 0x64f1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x64f1);
auto const rel = std::vector<uint32_t>(1, 0x8b0c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8b0c);
auto const rel = std::vector<uint32_t>(1, 0x9d3f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d3f);
auto const rel = std::vector<uint32_t>(1, 0x93b6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x93b6);
auto const rel = std::vector<uint32_t>(1, 0x5444);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5444);
auto const rel = std::vector<uint32_t>(1, 0x4f6e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f6e);
auto const rel = std::vector<uint32_t>(1, 0x530c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x530c);
auto const rel = std::vector<uint32_t>(1, 0x630c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x630c);
auto const rel = std::vector<uint32_t>(1, 0x8316);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8316);
auto const rel = std::vector<uint32_t>(1, 0x9601);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9601);
auto const rel = std::vector<uint32_t>(1, 0x9769);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9769);
auto const rel = std::vector<uint32_t>(1, 0x654b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x654b);
auto const rel = std::vector<uint32_t>(1, 0x683c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x683c);
auto const rel = std::vector<uint32_t>(1, 0x9b32);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b32);
auto const rel = std::vector<uint32_t>(1, 0x6105);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6105);
auto const rel = std::vector<uint32_t>(1, 0x81f5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81f5);
auto const rel = std::vector<uint32_t>(1, 0x845b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x845b);
auto const rel = std::vector<uint32_t>(1, 0x86d2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86d2);
auto const rel = std::vector<uint32_t>(1, 0x88d3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88d3);
auto const rel = std::vector<uint32_t>(1, 0x9694);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9694);
auto const rel = std::vector<uint32_t>(1, 0x55dd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x55dd);
auto const rel = std::vector<uint32_t>(1, 0x5865);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5865);
auto const rel = std::vector<uint32_t>(1, 0x6ec6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6ec6);
auto const rel = std::vector<uint32_t>(1, 0x89e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89e1);
auto const rel = std::vector<uint32_t>(1, 0x643f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x643f);
auto const rel = std::vector<uint32_t>(1, 0x69c5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69c5);
auto const rel = std::vector<uint32_t>(1, 0x8188);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8188);
auto const rel = std::vector<uint32_t>(1, 0x95a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95a3);
auto const rel = std::vector<uint32_t>(1, 0x95a4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95a4);
auto const rel = std::vector<uint32_t>(1, 0x7366);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7366);
auto const rel = std::vector<uint32_t>(1, 0x9549);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9549);
auto const rel = std::vector<uint32_t>(1, 0x9788);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9788);
auto const rel = std::vector<uint32_t>(1, 0x97d0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97d0);
auto const rel = std::vector<uint32_t>(1, 0x9abc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9abc);
auto const rel = std::vector<uint32_t>(1, 0x8afd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8afd);
auto const rel = std::vector<uint32_t>(1, 0x8f35);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f35);
auto const rel = std::vector<uint32_t>(1, 0x9baf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9baf);
auto const rel = std::vector<uint32_t>(1, 0x6aca);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6aca);
auto const rel = std::vector<uint32_t>(1, 0x97da);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97da);
auto const rel = std::vector<uint32_t>(1, 0x8f55);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f55);
auto const rel = std::vector<uint32_t>(1, 0x97b7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_011)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97b7);
auto const rel = std::vector<uint32_t>(1, 0x9a14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9a14);
auto const rel = std::vector<uint32_t>(1, 0x54ff);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54ff);
auto const rel = std::vector<uint32_t>(1, 0x8238);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8238);
auto const rel = std::vector<uint32_t>(1, 0x55f0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x55f0);
auto const rel = std::vector<uint32_t>(1, 0x4e2a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e2a);
auto const rel = std::vector<uint32_t>(1, 0x5404);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5404);
auto const rel = std::vector<uint32_t>(1, 0x867c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x867c);
auto const rel = std::vector<uint32_t>(1, 0x500b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x500b);
auto const rel = std::vector<uint32_t>(1, 0x784c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x784c);
auto const rel = std::vector<uint32_t>(1, 0x94ec);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x94ec);
auto const rel = std::vector<uint32_t>(1, 0x7b87);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b87);
auto const rel = std::vector<uint32_t>(1, 0x7ed9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ed9);
auto const rel = std::vector<uint32_t>(1, 0x7d66);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d66);
auto const rel = std::vector<uint32_t>(1, 0x6839);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6839);
auto const rel = std::vector<uint32_t>(1, 0x8ddf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ddf);
auto const rel = std::vector<uint32_t>(1, 0x54cf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54cf);
auto const rel = std::vector<uint32_t>(1, 0x826e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x826e);
auto const rel = std::vector<uint32_t>(1, 0x4e98);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e98);
auto const rel = std::vector<uint32_t>(1, 0x4e99);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e99);
auto const rel = std::vector<uint32_t>(1, 0x831b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x831b);
auto const rel = std::vector<uint32_t>(1, 0x63ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x63ef);
auto const rel = std::vector<uint32_t>(1, 0x6404);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6404);
auto const rel = std::vector<uint32_t>(1, 0x522f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x522f);
auto const rel = std::vector<uint32_t>(1, 0x5e9a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e9a);
auto const rel = std::vector<uint32_t>(1, 0x754a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x754a);
auto const rel = std::vector<uint32_t>(1, 0x6d6d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6d6d);
auto const rel = std::vector<uint32_t>(1, 0x8015);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8015);
auto const rel = std::vector<uint32_t>(1, 0x83ee);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83ee);
auto const rel = std::vector<uint32_t>(1, 0x6929);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6929);
auto const rel = std::vector<uint32_t>(1, 0x713f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x713f);
auto const rel = std::vector<uint32_t>(1, 0x7d5a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d5a);
auto const rel = std::vector<uint32_t>(1, 0x8d53);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d53);
auto const rel = std::vector<uint32_t>(1, 0x9e52);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e52);
auto const rel = std::vector<uint32_t>(1, 0x7dea);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7dea);
auto const rel = std::vector<uint32_t>(1, 0x7e06);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7e06);
auto const rel = std::vector<uint32_t>(1, 0x7fae);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7fae);
auto const rel = std::vector<uint32_t>(1, 0x8ce1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ce1);
auto const rel = std::vector<uint32_t>(1, 0x7fb9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7fb9);
auto const rel = std::vector<uint32_t>(1, 0x9d8a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d8a);
auto const rel = std::vector<uint32_t>(1, 0x90e0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90e0);
auto const rel = std::vector<uint32_t>(1, 0x54fd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54fd);
auto const rel = std::vector<uint32_t>(1, 0x57c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x57c2);
auto const rel = std::vector<uint32_t>(1, 0x5cfa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5cfa);
auto const rel = std::vector<uint32_t>(1, 0x632d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x632d);
auto const rel = std::vector<uint32_t>(1, 0x7ee0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ee0);
auto const rel = std::vector<uint32_t>(1, 0x803f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x803f);
auto const rel = std::vector<uint32_t>(1, 0x8384);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8384);
auto const rel = std::vector<uint32_t>(1, 0x6897);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6897);
auto const rel = std::vector<uint32_t>(1, 0x7d86);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d86);
auto const rel = std::vector<uint32_t>(1, 0x9ca0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ca0);
auto const rel = std::vector<uint32_t>(1, 0x9abe);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_012)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9abe);
auto const rel = std::vector<uint32_t>(1, 0x9bc1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9bc1);
auto const rel = std::vector<uint32_t>(1, 0x66f4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x66f4);
auto const rel = std::vector<uint32_t>(1, 0x5829);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5829);
auto const rel = std::vector<uint32_t>(1, 0x6685);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6685);
auto const rel = std::vector<uint32_t>(1, 0x5de5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5de5);
auto const rel = std::vector<uint32_t>(1, 0x5f13);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f13);
auto const rel = std::vector<uint32_t>(1, 0x516c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x516c);
auto const rel = std::vector<uint32_t>(1, 0x53b7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x53b7);
auto const rel = std::vector<uint32_t>(1, 0x529f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x529f);
auto const rel = std::vector<uint32_t>(1, 0x653b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x653b);
auto const rel = std::vector<uint32_t>(1, 0x675b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x675b);
auto const rel = std::vector<uint32_t>(1, 0x4f9b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f9b);
auto const rel = std::vector<uint32_t>(1, 0x7cfc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7cfc);
auto const rel = std::vector<uint32_t>(1, 0x80b1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80b1);
auto const rel = std::vector<uint32_t>(1, 0x5bab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5bab);
auto const rel = std::vector<uint32_t>(1, 0x5bae);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5bae);
auto const rel = std::vector<uint32_t>(1, 0x606d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x606d);
auto const rel = std::vector<uint32_t>(1, 0x86a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86a3);
auto const rel = std::vector<uint32_t>(1, 0x8eac);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8eac);
auto const rel = std::vector<uint32_t>(1, 0x9f9a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f9a);
auto const rel = std::vector<uint32_t>(1, 0x5311);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5311);
auto const rel = std::vector<uint32_t>(1, 0x5868);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5868);
auto const rel = std::vector<uint32_t>(1, 0x5e4a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e4a);
auto const rel = std::vector<uint32_t>(1, 0x6129);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6129);
auto const rel = std::vector<uint32_t>(1, 0x89e5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89e5);
auto const rel = std::vector<uint32_t>(1, 0x8eb3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8eb3);
auto const rel = std::vector<uint32_t>(1, 0x7195);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7195);
auto const rel = std::vector<uint32_t>(1, 0x5314);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5314);
auto const rel = std::vector<uint32_t>(1, 0x78bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x78bd);
auto const rel = std::vector<uint32_t>(1, 0x9af8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9af8);
auto const rel = std::vector<uint32_t>(1, 0x89f5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89f5);
auto const rel = std::vector<uint32_t>(1, 0x9f8f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f8f);
auto const rel = std::vector<uint32_t>(1, 0x9f94);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f94);
auto const rel = std::vector<uint32_t>(1, 0x5efe);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5efe);
auto const rel = std::vector<uint32_t>(1, 0x5de9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5de9);
auto const rel = std::vector<uint32_t>(1, 0x6c5e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c5e);
auto const rel = std::vector<uint32_t>(1, 0x62f1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x62f1);
auto const rel = std::vector<uint32_t>(1, 0x62f2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x62f2);
auto const rel = std::vector<uint32_t>(1, 0x6831);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6831);
auto const rel = std::vector<uint32_t>(1, 0x73d9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x73d9);
auto const rel = std::vector<uint32_t>(1, 0x8f01);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f01);
auto const rel = std::vector<uint32_t>(1, 0x978f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x978f);
auto const rel = std::vector<uint32_t>(1, 0x5171);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5171);
auto const rel = std::vector<uint32_t>(1, 0x8d21);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d21);
auto const rel = std::vector<uint32_t>(1, 0x7fbe);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7fbe);
auto const rel = std::vector<uint32_t>(1, 0x551d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x551d);
auto const rel = std::vector<uint32_t>(1, 0x8ca2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ca2);
auto const rel = std::vector<uint32_t>(1, 0x83bb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83bb);
auto const rel = std::vector<uint32_t>(1, 0x6150);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6150);
auto const rel = std::vector<uint32_t>(1, 0x52fe);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x52fe);
auto const rel = std::vector<uint32_t>(1, 0x4f5d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_013)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f5d);
auto const rel = std::vector<uint32_t>(1, 0x6c9f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c9f);
auto const rel = std::vector<uint32_t>(1, 0x94a9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x94a9);
auto const rel = std::vector<uint32_t>(1, 0x88a7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88a7);
auto const rel = std::vector<uint32_t>(1, 0x7f11);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f11);
auto const rel = std::vector<uint32_t>(1, 0x920e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x920e);
auto const rel = std::vector<uint32_t>(1, 0x6e9d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e9d);
auto const rel = std::vector<uint32_t>(1, 0x9264);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9264);
auto const rel = std::vector<uint32_t>(1, 0x7df1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7df1);
auto const rel = std::vector<uint32_t>(1, 0x8920);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8920);
auto const rel = std::vector<uint32_t>(1, 0x7bdd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7bdd);
auto const rel = std::vector<uint32_t>(1, 0x7c3c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7c3c);
auto const rel = std::vector<uint32_t>(1, 0x97b2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97b2);
auto const rel = std::vector<uint32_t>(1, 0x97dd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x97dd);
auto const rel = std::vector<uint32_t>(1, 0x82b6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82b6);
auto const rel = std::vector<uint32_t>(1, 0x5ca3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5ca3);
auto const rel = std::vector<uint32_t>(1, 0x72d7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x72d7);
auto const rel = std::vector<uint32_t>(1, 0x82df);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82df);
auto const rel = std::vector<uint32_t>(1, 0x67b8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67b8);
auto const rel = std::vector<uint32_t>(1, 0x73bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x73bd);
auto const rel = std::vector<uint32_t>(1, 0x8007);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8007);
auto const rel = std::vector<uint32_t>(1, 0x8009);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8009);
auto const rel = std::vector<uint32_t>(1, 0x7b31);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b31);
auto const rel = std::vector<uint32_t>(1, 0x8008);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8008);
auto const rel = std::vector<uint32_t>(1, 0x86bc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86bc);
auto const rel = std::vector<uint32_t>(1, 0x8c7f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8c7f);
auto const rel = std::vector<uint32_t>(1, 0x5778);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5778);
auto const rel = std::vector<uint32_t>(1, 0x6784);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6784);
auto const rel = std::vector<uint32_t>(1, 0x8bdf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8bdf);
auto const rel = std::vector<uint32_t>(1, 0x8d2d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d2d);
auto const rel = std::vector<uint32_t>(1, 0x57a2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x57a2);
auto const rel = std::vector<uint32_t>(1, 0x59e4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59e4);
auto const rel = std::vector<uint32_t>(1, 0x8329);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8329);
auto const rel = std::vector<uint32_t>(1, 0x5193);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5193);
auto const rel = std::vector<uint32_t>(1, 0x591f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x591f);
auto const rel = std::vector<uint32_t>(1, 0x5920);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5920);
auto const rel = std::vector<uint32_t>(1, 0x8a3d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a3d);
auto const rel = std::vector<uint32_t>(1, 0x5abe);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5abe);
auto const rel = std::vector<uint32_t>(1, 0x5f40);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f40);
auto const rel = std::vector<uint32_t>(1, 0x6406);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6406);
auto const rel = std::vector<uint32_t>(1, 0x8a6c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a6c);
auto const rel = std::vector<uint32_t>(1, 0x9058);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9058);
auto const rel = std::vector<uint32_t>(1, 0x96ca);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x96ca);
auto const rel = std::vector<uint32_t>(1, 0x69cb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69cb);
auto const rel = std::vector<uint32_t>(1, 0x7179);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7179);
auto const rel = std::vector<uint32_t>(1, 0x89cf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89cf);
auto const rel = std::vector<uint32_t>(1, 0x6480);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6480);
auto const rel = std::vector<uint32_t>(1, 0x89af);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89af);
auto const rel = std::vector<uint32_t>(1, 0x8cfc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8cfc);
auto const rel = std::vector<uint32_t>(1, 0x4f30);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f30);
auto const rel = std::vector<uint32_t>(1, 0x5471);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5471);
auto const rel = std::vector<uint32_t>(1, 0x5495);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_014)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5495);
auto const rel = std::vector<uint32_t>(1, 0x59d1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59d1);
auto const rel = std::vector<uint32_t>(1, 0x5b64);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b64);
auto const rel = std::vector<uint32_t>(1, 0x6cbd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6cbd);
auto const rel = std::vector<uint32_t>(1, 0x6cd2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6cd2);
auto const rel = std::vector<uint32_t>(1, 0x82fd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x82fd);
auto const rel = std::vector<uint32_t>(1, 0x67e7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67e7);
auto const rel = std::vector<uint32_t>(1, 0x8f71);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f71);
auto const rel = std::vector<uint32_t>(1, 0x5502);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5502);
auto const rel = std::vector<uint32_t>(1, 0x7f5b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f5b);
auto const rel = std::vector<uint32_t>(1, 0x9e2a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e2a);
auto const rel = std::vector<uint32_t>(1, 0x7b1f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b1f);
auto const rel = std::vector<uint32_t>(1, 0x83c7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83c7);
auto const rel = std::vector<uint32_t>(1, 0x83f0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x83f0);
auto const rel = std::vector<uint32_t>(1, 0x86c4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86c4);
auto const rel = std::vector<uint32_t>(1, 0x89da);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89da);
auto const rel = std::vector<uint32_t>(1, 0x8ef1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ef1);
auto const rel = std::vector<uint32_t>(1, 0x8ef2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ef2);
auto const rel = std::vector<uint32_t>(1, 0x8f9c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f9c);
auto const rel = std::vector<uint32_t>(1, 0x9164);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9164);
auto const rel = std::vector<uint32_t>(1, 0x9232);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9232);
auto const rel = std::vector<uint32_t>(1, 0x7b8d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b8d);
auto const rel = std::vector<uint32_t>(1, 0x7b9b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b9b);
auto const rel = std::vector<uint32_t>(1, 0x5af4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5af4);
auto const rel = std::vector<uint32_t>(1, 0x7bd0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7bd0);
auto const rel = std::vector<uint32_t>(1, 0x6a6d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a6d);
auto const rel = std::vector<uint32_t>(1, 0x9b95);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b95);
auto const rel = std::vector<uint32_t>(1, 0x9d23);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d23);
auto const rel = std::vector<uint32_t>(1, 0x9dbb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9dbb);
auto const rel = std::vector<uint32_t>(1, 0x5903);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5903);
auto const rel = std::vector<uint32_t>(1, 0x53e4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x53e4);
auto const rel = std::vector<uint32_t>(1, 0x6262);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6262);
auto const rel = std::vector<uint32_t>(1, 0x6c69);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c69);
auto const rel = std::vector<uint32_t>(1, 0x8bc2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8bc2);
auto const rel = std::vector<uint32_t>(1, 0x8c37);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8c37);
auto const rel = std::vector<uint32_t>(1, 0x80a1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80a1);
auto const rel = std::vector<uint32_t>(1, 0x726f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x726f);
auto const rel = std::vector<uint32_t>(1, 0x9aa8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9aa8);
auto const rel = std::vector<uint32_t>(1, 0x5503);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5503);
auto const rel = std::vector<uint32_t>(1, 0x7f5f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f5f);
auto const rel = std::vector<uint32_t>(1, 0x7f96);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f96);
auto const rel = std::vector<uint32_t>(1, 0x9027);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9027);
auto const rel = std::vector<uint32_t>(1, 0x94b4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x94b4);
auto const rel = std::vector<uint32_t>(1, 0x50a6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x50a6);
auto const rel = std::vector<uint32_t>(1, 0x5552);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5552);
auto const rel = std::vector<uint32_t>(1, 0x6dc8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6dc8);
auto const rel = std::vector<uint32_t>(1, 0x8135);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8135);
auto const rel = std::vector<uint32_t>(1, 0x86ca);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86ca);
auto const rel = std::vector<uint32_t>(1, 0x86cc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86cc);
auto const rel = std::vector<uint32_t>(1, 0x5c33);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5c33);
auto const rel = std::vector<uint32_t>(1, 0x6132);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6132);
auto const rel = std::vector<uint32_t>(1, 0x84c7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_015)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x84c7);
auto const rel = std::vector<uint32_t>(1, 0x8a41);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a41);
auto const rel = std::vector<uint32_t>(1, 0x9989);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9989);
auto const rel = std::vector<uint32_t>(1, 0x9e44);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e44);
auto const rel = std::vector<uint32_t>(1, 0x69be);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69be);
auto const rel = std::vector<uint32_t>(1, 0x6bc2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6bc2);
auto const rel = std::vector<uint32_t>(1, 0x9237);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9237);
auto const rel = std::vector<uint32_t>(1, 0x9f13);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f13);
auto const rel = std::vector<uint32_t>(1, 0x9f14);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f14);
auto const rel = std::vector<uint32_t>(1, 0x560f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x560f);
auto const rel = std::vector<uint32_t>(1, 0x6996);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6996);
auto const rel = std::vector<uint32_t>(1, 0x76b7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76b7);
auto const rel = std::vector<uint32_t>(1, 0x9e58);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e58);
auto const rel = std::vector<uint32_t>(1, 0x7a40);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a40);
auto const rel = std::vector<uint32_t>(1, 0x7e0e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7e0e);
auto const rel = std::vector<uint32_t>(1, 0x7cd3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7cd3);
auto const rel = std::vector<uint32_t>(1, 0x85a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x85a3);
auto const rel = std::vector<uint32_t>(1, 0x6ff2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6ff2);
auto const rel = std::vector<uint32_t>(1, 0x76bc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76bc);
auto const rel = std::vector<uint32_t>(1, 0x81cc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81cc);
auto const rel = std::vector<uint32_t>(1, 0x8f42);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f42);
auto const rel = std::vector<uint32_t>(1, 0x9936);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9936);
auto const rel = std::vector<uint32_t>(1, 0x7014);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7014);
auto const rel = std::vector<uint32_t>(1, 0x76ec);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76ec);
auto const rel = std::vector<uint32_t>(1, 0x77bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x77bd);
auto const rel = std::vector<uint32_t>(1, 0x8831);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8831);
auto const rel = std::vector<uint32_t>(1, 0x56fa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x56fa);
auto const rel = std::vector<uint32_t>(1, 0x6545);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6545);
auto const rel = std::vector<uint32_t>(1, 0x51c5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51c5);
auto const rel = std::vector<uint32_t>(1, 0x987e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x987e);
auto const rel = std::vector<uint32_t>(1, 0x580c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x580c);
auto const rel = std::vector<uint32_t>(1, 0x5d13);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5d13);
auto const rel = std::vector<uint32_t>(1, 0x5d2e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5d2e);
auto const rel = std::vector<uint32_t>(1, 0x688f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x688f);
auto const rel = std::vector<uint32_t>(1, 0x727f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x727f);
auto const rel = std::vector<uint32_t>(1, 0x68dd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x68dd);
auto const rel = std::vector<uint32_t>(1, 0x797b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x797b);
auto const rel = std::vector<uint32_t>(1, 0x96c7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x96c7);
auto const rel = std::vector<uint32_t>(1, 0x75fc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x75fc);
auto const rel = std::vector<uint32_t>(1, 0x7a12);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a12);
auto const rel = std::vector<uint32_t>(1, 0x9522);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9522);
auto const rel = std::vector<uint32_t>(1, 0x50f1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x50f1);
auto const rel = std::vector<uint32_t>(1, 0x932e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x932e);
auto const rel = std::vector<uint32_t>(1, 0x9cb4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9cb4);
auto const rel = std::vector<uint32_t>(1, 0x9bdd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9bdd);
auto const rel = std::vector<uint32_t>(1, 0x9867);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9867);
auto const rel = std::vector<uint32_t>(1, 0x74dc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x74dc);
auto const rel = std::vector<uint32_t>(1, 0x522e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x522e);
auto const rel = std::vector<uint32_t>(1, 0x80cd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80cd);
auto const rel = std::vector<uint32_t>(1, 0x681d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x681d);
auto const rel = std::vector<uint32_t>(1, 0x9e39);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e39);
auto const rel = std::vector<uint32_t>(1, 0x6b44);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_016)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6b44);
auto const rel = std::vector<uint32_t>(1, 0x7171);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7171);
auto const rel = std::vector<uint32_t>(1, 0x8052);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8052);
auto const rel = std::vector<uint32_t>(1, 0x98aa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x98aa);
auto const rel = std::vector<uint32_t>(1, 0x8d8f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d8f);
auto const rel = std::vector<uint32_t>(1, 0x5280);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5280);
auto const rel = std::vector<uint32_t>(1, 0x7dfa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7dfa);
auto const rel = std::vector<uint32_t>(1, 0x8e3b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8e3b);
auto const rel = std::vector<uint32_t>(1, 0x92bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x92bd);
auto const rel = std::vector<uint32_t>(1, 0x98b3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x98b3);
auto const rel = std::vector<uint32_t>(1, 0x9d30);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9d30);
auto const rel = std::vector<uint32_t>(1, 0x9a27);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9a27);
auto const rel = std::vector<uint32_t>(1, 0x518e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x518e);
auto const rel = std::vector<uint32_t>(1, 0x53e7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x53e7);
auto const rel = std::vector<uint32_t>(1, 0x5250);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5250);
auto const rel = std::vector<uint32_t>(1, 0x526e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x526e);
auto const rel = std::vector<uint32_t>(1, 0x5be1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5be1);
auto const rel = std::vector<uint32_t>(1, 0x5366);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5366);
auto const rel = std::vector<uint32_t>(1, 0x576c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x576c);
auto const rel = std::vector<uint32_t>(1, 0x8bd6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8bd6);
auto const rel = std::vector<uint32_t>(1, 0x6302);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6302);
auto const rel = std::vector<uint32_t>(1, 0x5569);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5569);
auto const rel = std::vector<uint32_t>(1, 0x639b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x639b);
auto const rel = std::vector<uint32_t>(1, 0x7f63);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f63);
auto const rel = std::vector<uint32_t>(1, 0x7d53);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7d53);
auto const rel = std::vector<uint32_t>(1, 0x7f6b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f6b);
auto const rel = std::vector<uint32_t>(1, 0x8902);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8902);
auto const rel = std::vector<uint32_t>(1, 0x8a7f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a7f);
auto const rel = std::vector<uint32_t>(1, 0x4e56);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e56);
auto const rel = std::vector<uint32_t>(1, 0x63b4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x63b4);
auto const rel = std::vector<uint32_t>(1, 0x6451);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6451);
auto const rel = std::vector<uint32_t>(1, 0x62d0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x62d0);
auto const rel = std::vector<uint32_t>(1, 0x67b4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67b4);
auto const rel = std::vector<uint32_t>(1, 0x67fa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x67fa);
auto const rel = std::vector<uint32_t>(1, 0x7b89);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b89);
auto const rel = std::vector<uint32_t>(1, 0x592c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x592c);
auto const rel = std::vector<uint32_t>(1, 0x53cf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x53cf);
auto const rel = std::vector<uint32_t>(1, 0x602a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x602a);
auto const rel = std::vector<uint32_t>(1, 0x6060);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6060);
auto const rel = std::vector<uint32_t>(1, 0x5173);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5173);
auto const rel = std::vector<uint32_t>(1, 0x89c2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89c2);
auto const rel = std::vector<uint32_t>(1, 0x5b98);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b98);
auto const rel = std::vector<uint32_t>(1, 0x51a0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x51a0);
auto const rel = std::vector<uint32_t>(1, 0x898c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x898c);
auto const rel = std::vector<uint32_t>(1, 0x500c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x500c);
auto const rel = std::vector<uint32_t>(1, 0x68fa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x68fa);
auto const rel = std::vector<uint32_t>(1, 0x8484);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8484);
auto const rel = std::vector<uint32_t>(1, 0x7aa4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7aa4);
auto const rel = std::vector<uint32_t>(1, 0x95a2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95a2);
auto const rel = std::vector<uint32_t>(1, 0x761d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x761d);
auto const rel = std::vector<uint32_t>(1, 0x764f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x764f);
auto const rel = std::vector<uint32_t>(1, 0x89b3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_017)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89b3);
auto const rel = std::vector<uint32_t>(1, 0x95d7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95d7);
auto const rel = std::vector<uint32_t>(1, 0x9ccf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ccf);
auto const rel = std::vector<uint32_t>(1, 0x95dc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95dc);
auto const rel = std::vector<uint32_t>(1, 0x9c25);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c25);
auto const rel = std::vector<uint32_t>(1, 0x89c0);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89c0);
auto const rel = std::vector<uint32_t>(1, 0x9c5e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c5e);
auto const rel = std::vector<uint32_t>(1, 0x839e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x839e);
auto const rel = std::vector<uint32_t>(1, 0x9986);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9986);
auto const rel = std::vector<uint32_t>(1, 0x742f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x742f);
auto const rel = std::vector<uint32_t>(1, 0x75ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x75ef);
auto const rel = std::vector<uint32_t>(1, 0x7b66);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7b66);
auto const rel = std::vector<uint32_t>(1, 0x7ba1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7ba1);
auto const rel = std::vector<uint32_t>(1, 0x8f28);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f28);
auto const rel = std::vector<uint32_t>(1, 0x8218);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8218);
auto const rel = std::vector<uint32_t>(1, 0x9327);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9327);
auto const rel = std::vector<uint32_t>(1, 0x9928);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9928);
auto const rel = std::vector<uint32_t>(1, 0x9ce4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ce4);
auto const rel = std::vector<uint32_t>(1, 0x6bcc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6bcc);
auto const rel = std::vector<uint32_t>(1, 0x4e31);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e31);
auto const rel = std::vector<uint32_t>(1, 0x8d2f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8d2f);
auto const rel = std::vector<uint32_t>(1, 0x6cf4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6cf4);
auto const rel = std::vector<uint32_t>(1, 0x60ba);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x60ba);
auto const rel = std::vector<uint32_t>(1, 0x60ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x60ef);
auto const rel = std::vector<uint32_t>(1, 0x63bc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x63bc);
auto const rel = std::vector<uint32_t>(1, 0x6dab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6dab);
auto const rel = std::vector<uint32_t>(1, 0x8cab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8cab);
auto const rel = std::vector<uint32_t>(1, 0x60b9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x60b9);
auto const rel = std::vector<uint32_t>(1, 0x797c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x797c);
auto const rel = std::vector<uint32_t>(1, 0x6163);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6163);
auto const rel = std::vector<uint32_t>(1, 0x645c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x645c);
auto const rel = std::vector<uint32_t>(1, 0x6f45);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6f45);
auto const rel = std::vector<uint32_t>(1, 0x9066);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9066);
auto const rel = std::vector<uint32_t>(1, 0x6a0c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6a0c);
auto const rel = std::vector<uint32_t>(1, 0x76e5);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x76e5);
auto const rel = std::vector<uint32_t>(1, 0x7f46);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f46);
auto const rel = std::vector<uint32_t>(1, 0x96da);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x96da);
auto const rel = std::vector<uint32_t>(1, 0x8e80);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8e80);
auto const rel = std::vector<uint32_t>(1, 0x93c6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x93c6);
auto const rel = std::vector<uint32_t>(1, 0x704c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x704c);
auto const rel = std::vector<uint32_t>(1, 0x721f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x721f);
auto const rel = std::vector<uint32_t>(1, 0x74d8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x74d8);
auto const rel = std::vector<uint32_t>(1, 0x77d4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x77d4);
auto const rel = std::vector<uint32_t>(1, 0x7936);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7936);
auto const rel = std::vector<uint32_t>(1, 0x9e73);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e73);
auto const rel = std::vector<uint32_t>(1, 0x7f50);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7f50);
auto const rel = std::vector<uint32_t>(1, 0x9475);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9475);
auto const rel = std::vector<uint32_t>(1, 0x9c79);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c79);
auto const rel = std::vector<uint32_t>(1, 0x9e1b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9e1b);
auto const rel = std::vector<uint32_t>(1, 0x5149);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5149);
auto const rel = std::vector<uint32_t>(1, 0x706e);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x706e);
auto const rel = std::vector<uint32_t>(1, 0x4f8a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_018)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f8a);
auto const rel = std::vector<uint32_t>(1, 0x7097);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7097);
auto const rel = std::vector<uint32_t>(1, 0x709a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x709a);
auto const rel = std::vector<uint32_t>(1, 0x709b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x709b);
auto const rel = std::vector<uint32_t>(1, 0x54a3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x54a3);
auto const rel = std::vector<uint32_t>(1, 0x5799);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5799);
auto const rel = std::vector<uint32_t>(1, 0x59ef);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59ef);
auto const rel = std::vector<uint32_t>(1, 0x6d38);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6d38);
auto const rel = std::vector<uint32_t>(1, 0x832a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x832a);
auto const rel = std::vector<uint32_t>(1, 0x6844);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6844);
auto const rel = std::vector<uint32_t>(1, 0x70e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x70e1);
auto const rel = std::vector<uint32_t>(1, 0x80f1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80f1);
auto const rel = std::vector<uint32_t>(1, 0x50d9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x50d9);
auto const rel = std::vector<uint32_t>(1, 0x8f04);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f04);
auto const rel = std::vector<uint32_t>(1, 0x92a7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x92a7);
auto const rel = std::vector<uint32_t>(1, 0x9ec6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9ec6);
auto const rel = std::vector<uint32_t>(1, 0x5e7f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e7f);
auto const rel = std::vector<uint32_t>(1, 0x5e83);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e83);
auto const rel = std::vector<uint32_t>(1, 0x72b7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x72b7);
auto const rel = std::vector<uint32_t>(1, 0x5ee3);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5ee3);
auto const rel = std::vector<uint32_t>(1, 0x7377);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7377);
auto const rel = std::vector<uint32_t>(1, 0x81e9);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81e9);
auto const rel = std::vector<uint32_t>(1, 0x4fc7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4fc7);
auto const rel = std::vector<uint32_t>(1, 0x73d6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x73d6);
auto const rel = std::vector<uint32_t>(1, 0x901b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x901b);
auto const rel = std::vector<uint32_t>(1, 0x81e6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81e6);
auto const rel = std::vector<uint32_t>(1, 0x6497);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6497);
auto const rel = std::vector<uint32_t>(1, 0x6b1f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6b1f);
auto const rel = std::vector<uint32_t>(1, 0x5f52);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5f52);
auto const rel = std::vector<uint32_t>(1, 0x572d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x572d);
auto const rel = std::vector<uint32_t>(1, 0x59ab);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59ab);
auto const rel = std::vector<uint32_t>(1, 0x9f9f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f9f);
auto const rel = std::vector<uint32_t>(1, 0x89c4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89c4);
auto const rel = std::vector<uint32_t>(1, 0x90bd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90bd);
auto const rel = std::vector<uint32_t>(1, 0x7688);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7688);
auto const rel = std::vector<uint32_t>(1, 0x8325);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8325);
auto const rel = std::vector<uint32_t>(1, 0x95fa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95fa);
auto const rel = std::vector<uint32_t>(1, 0x5e30);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e30);
auto const rel = std::vector<uint32_t>(1, 0x73ea);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x73ea);
auto const rel = std::vector<uint32_t>(1, 0x80ff);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x80ff);
auto const rel = std::vector<uint32_t>(1, 0x4e80);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4e80);
auto const rel = std::vector<uint32_t>(1, 0x5080);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5080);
auto const rel = std::vector<uint32_t>(1, 0x7845);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7845);
auto const rel = std::vector<uint32_t>(1, 0x7a90);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7a90);
auto const rel = std::vector<uint32_t>(1, 0x88bf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x88bf);
auto const rel = std::vector<uint32_t>(1, 0x898f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x898f);
auto const rel = std::vector<uint32_t>(1, 0x5aaf);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5aaf);
auto const rel = std::vector<uint32_t>(1, 0x5ec6);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5ec6);
auto const rel = std::vector<uint32_t>(1, 0x691d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x691d);
auto const rel = std::vector<uint32_t>(1, 0x7470);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7470);
auto const rel = std::vector<uint32_t>(1, 0x90cc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x90cc);
auto const rel = std::vector<uint32_t>(1, 0x5ae2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
TEST(tailoring, zh_pinyin_004_019)
{
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5ae2);
auto const rel = std::vector<uint32_t>(1, 0x646b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x646b);
auto const rel = std::vector<uint32_t>(1, 0x95a8);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x95a8);
auto const rel = std::vector<uint32_t>(1, 0x9c91);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9c91);
auto const rel = std::vector<uint32_t>(1, 0x5b00);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b00);
auto const rel = std::vector<uint32_t>(1, 0x69fb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69fb);
auto const rel = std::vector<uint32_t>(1, 0x69fc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x69fc);
auto const rel = std::vector<uint32_t>(1, 0x879d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x879d);
auto const rel = std::vector<uint32_t>(1, 0x749d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x749d);
auto const rel = std::vector<uint32_t>(1, 0x81ad);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x81ad);
auto const rel = std::vector<uint32_t>(1, 0x9bad);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9bad);
auto const rel = std::vector<uint32_t>(1, 0x9f9c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9f9c);
auto const rel = std::vector<uint32_t>(1, 0x5dc2);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5dc2);
auto const rel = std::vector<uint32_t>(1, 0x6b78);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6b78);
auto const rel = std::vector<uint32_t>(1, 0x9b36);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b36);
auto const rel = std::vector<uint32_t>(1, 0x9a29);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9a29);
auto const rel = std::vector<uint32_t>(1, 0x74cc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x74cc);
auto const rel = std::vector<uint32_t>(1, 0x9b39);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b39);
auto const rel = std::vector<uint32_t>(1, 0x6af7);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6af7);
auto const rel = std::vector<uint32_t>(1, 0x5b84);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5b84);
auto const rel = std::vector<uint32_t>(1, 0x6c3f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6c3f);
auto const rel = std::vector<uint32_t>(1, 0x6739);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6739);
auto const rel = std::vector<uint32_t>(1, 0x8f68);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8f68);
auto const rel = std::vector<uint32_t>(1, 0x5e8b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5e8b);
auto const rel = std::vector<uint32_t>(1, 0x4f79);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x4f79);
auto const rel = std::vector<uint32_t>(1, 0x5326);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5326);
auto const rel = std::vector<uint32_t>(1, 0x8be1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8be1);
auto const rel = std::vector<uint32_t>(1, 0x9652);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9652);
auto const rel = std::vector<uint32_t>(1, 0x579d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x579d);
auto const rel = std::vector<uint32_t>(1, 0x59fd);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x59fd);
auto const rel = std::vector<uint32_t>(1, 0x6051);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6051);
auto const rel = std::vector<uint32_t>(1, 0x6531);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6531);
auto const rel = std::vector<uint32_t>(1, 0x7678);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7678);
auto const rel = std::vector<uint32_t>(1, 0x8ecc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8ecc);
auto const rel = std::vector<uint32_t>(1, 0x9b3c);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x9b3c);
auto const rel = std::vector<uint32_t>(1, 0x5eaa);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x5eaa);
auto const rel = std::vector<uint32_t>(1, 0x796a);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x796a);
auto const rel = std::vector<uint32_t>(1, 0x532d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x532d);
auto const rel = std::vector<uint32_t>(1, 0x6677);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6677);
auto const rel = std::vector<uint32_t>(1, 0x6e40);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6e40);
auto const rel = std::vector<uint32_t>(1, 0x86eb);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x86eb);
auto const rel = std::vector<uint32_t>(1, 0x89e4);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x89e4);
auto const rel = std::vector<uint32_t>(1, 0x8a6d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x8a6d);
auto const rel = std::vector<uint32_t>(1, 0x53ac);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x53ac);
auto const rel = std::vector<uint32_t>(1, 0x77a1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x77a1);
auto const rel = std::vector<uint32_t>(1, 0x7c0b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x7c0b);
auto const rel = std::vector<uint32_t>(1, 0x87e1);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x87e1);
auto const rel = std::vector<uint32_t>(1, 0x6530);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x6530);
auto const rel = std::vector<uint32_t>(1, 0x523d);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x523d);
auto const rel = std::vector<uint32_t>(1, 0x523f);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x523f);
auto const rel = std::vector<uint32_t>(1, 0x660b);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
{
// greater than (or equal to, for =) preceeding cps
auto const res = std::vector<uint32_t>(1, 0x660b);
auto const rel = std::vector<uint32_t>(1, 0x67dc);
EXPECT_EQ(collate(
res.begin(), res.end(),
rel.begin(), rel.end(),
table(), collation_strength::primary),
-1);
}
}
| 32.310635 | 74 | 0.564068 | [
"vector"
] |
315fd3e37d2d7d63d956a20b3d07d996c9d522bd | 4,089 | cpp | C++ | Computer Graphics Principles/tests/performanceTest.cpp | xstupi00/SchoolProject | 00e79c05105b48a64f918bd26da262516158572c | [
"MIT"
] | null | null | null | Computer Graphics Principles/tests/performanceTest.cpp | xstupi00/SchoolProject | 00e79c05105b48a64f918bd26da262516158572c | [
"MIT"
] | null | null | null | Computer Graphics Principles/tests/performanceTest.cpp | xstupi00/SchoolProject | 00e79c05105b48a64f918bd26da262516158572c | [
"MIT"
] | null | null | null | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
#include <student/linearAlgebra.h>
#include <student/mouseCamera.h>
#include <student/student_cpu.h>
#include <student/globals.h>
#include <tests/performanceTest.h>
void runPerformanceTest() {
int32_t windowWidth = 500;
int32_t windowHeight = 500;
char const* applicationName = "izgProjekt2017 performance test";
// enable logging
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
// initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init fail: %s\n",
SDL_GetError());
exit(1);
}
// create window
SDL_Window* window = SDL_CreateWindow(applicationName, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, windowWidth,
windowHeight, SDL_WINDOW_SHOWN);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow fail: %s\n",
SDL_GetError());
exit(1);
}
// create surface
SDL_Surface* surface = SDL_GetWindowSurface(window);
if (!surface) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_GetWindowSurface fail: %s\n", SDL_GetError());
exit(1);
}
// create renderer
SDL_Renderer* renderer = SDL_CreateSoftwareRenderer(surface);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_CreateSoftwareRenderer: %s\n", SDL_GetError());
exit(1);
}
phong_onInit(500, 500);
viewMatrix.column[0].data[0] = +1.0000000000e+00f;
viewMatrix.column[0].data[1] = +0.0000000000e+00f;
viewMatrix.column[0].data[2] = +0.0000000000e+00f;
viewMatrix.column[0].data[3] = +0.0000000000e+00f;
viewMatrix.column[1].data[0] = +0.0000000000e+00f;
viewMatrix.column[1].data[1] = +1.0000000000e+00f;
viewMatrix.column[1].data[2] = +0.0000000000e+00f;
viewMatrix.column[1].data[3] = +0.0000000000e+00f;
viewMatrix.column[2].data[0] = +0.0000000000e+00f;
viewMatrix.column[2].data[1] = +0.0000000000e+00f;
viewMatrix.column[2].data[2] = +1.0000000000e+00f;
viewMatrix.column[2].data[3] = +0.0000000000e+00f;
viewMatrix.column[3].data[0] = +0.0000000000e+00f;
viewMatrix.column[3].data[1] = +0.0000000000e+00f;
viewMatrix.column[3].data[2] = -1.8800077438e+00f;
viewMatrix.column[3].data[3] = +1.0000000000e+00f;
projectionMatrix.column[0].data[0] = +1.0000000000e+00f;
projectionMatrix.column[0].data[1] = +0.0000000000e+00f;
projectionMatrix.column[0].data[2] = +0.0000000000e+00f;
projectionMatrix.column[0].data[3] = +0.0000000000e+00f;
projectionMatrix.column[1].data[0] = +0.0000000000e+00f;
projectionMatrix.column[1].data[1] = +1.0000000000e+00f;
projectionMatrix.column[1].data[2] = +0.0000000000e+00f;
projectionMatrix.column[1].data[3] = +0.0000000000e+00f;
projectionMatrix.column[2].data[0] = +0.0000000000e+00f;
projectionMatrix.column[2].data[1] = +0.0000000000e+00f;
projectionMatrix.column[2].data[2] = -1.0000199080e+00f;
projectionMatrix.column[2].data[3] = -1.0000000000e+00f;
projectionMatrix.column[3].data[0] = +0.0000000000e+00f;
projectionMatrix.column[3].data[1] = +0.0000000000e+00f;
projectionMatrix.column[3].data[2] = -2.0000198483e-01f;
projectionMatrix.column[3].data[3] = +0.0000000000e+00f;
SDL_LockSurface(surface);
size_t const framesPerMeasurement = 10;
auto start = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < framesPerMeasurement; ++i) phong_onDraw(surface);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> elapsed = end - start;
float const time = elapsed.count() / float(framesPerMeasurement);
std::cout << "Seconds per frame: " << std::scientific << std::setprecision(10)
<< time << std::endl;
SDL_UnlockSurface(surface);
SDL_UpdateWindowSurface(window);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
phong_onExit();
}
| 36.508929 | 80 | 0.686965 | [
"vector"
] |
31671e777b5f7b97714723b7257aa8635fc393d3 | 12,202 | cpp | C++ | src/ui/selection/SelectionControl.cpp | danielroth1/CAE | 7eaa096e45fd32f55bd6de94c30dcf706c6f2093 | [
"MIT"
] | 5 | 2019-04-20T17:48:10.000Z | 2022-01-06T01:39:33.000Z | src/ui/selection/SelectionControl.cpp | danielroth1/CAE | 7eaa096e45fd32f55bd6de94c30dcf706c6f2093 | [
"MIT"
] | null | null | null | src/ui/selection/SelectionControl.cpp | danielroth1/CAE | 7eaa096e45fd32f55bd6de94c30dcf706c6f2093 | [
"MIT"
] | 2 | 2020-08-04T20:21:00.000Z | 2022-03-16T15:01:04.000Z | #include "SelectionControl.h"
#include "Selection.h"
#include "SelectionRectangle.h"
#include "SelectionRectangleModel.h"
#include "SelectionSceneData.h"
#include "SelectionSceneDataModel.h"
#include "SelectionVertices.h"
#include "SelectionVerticesModel.h"
#include "SelectionListener.h"
#include <rendering/ViewFrustum.h>
#include <ApplicationControl.h>
#include <scene/data/GeometricData.h>
#include <scene/scene_graph/SGTraverserFactory.h>
#include <iostream>
SelectionControl::SelectionControl(
ApplicationControl* ac,
ViewFrustum& viewFrustum)
{
mAc = ac;
mSelectionRectangle =
std::make_unique<SelectionRectangle>();
mSelectionRectangleModel =
std::make_unique<SelectionRectangleModel>(
*mSelectionRectangle.get(),
&viewFrustum);
mSelectionVertices =
std::make_unique<SelectionVertices>();
mSelectionVerticesModel =
std::make_unique<SelectionVerticesModel>(*mSelectionVertices.get());
mSelectionSceneData =
std::make_unique<SelectionSceneData>();
mSelectionSceneDataModel =
std::make_unique<SelectionSceneDataModel>(*mSelectionSceneData.get());
mSelectionType = UNDEFINED;
changeSelectionType(SELECT_VERTICES);
mSelectionMode = RECTANGLE;
}
void SelectionControl::init(Renderer* renderer)
{
mSelectionSceneDataModel->addToRenderer(renderer);
mSelectionVerticesModel->addToRenderer(renderer);
mSelectionRectangleModel->addToRenderer(renderer);
}
void SelectionControl::changeSelectionType(SelectionControl::SelectionType type)
{
if (mSelectionType == type)
return;
mSelectionType = type;
switch(type)
{
case SELECT_SCENE_NODES:
mSelectionSceneData->setActive(true);
mSelectionVertices->setActive(false);
break;
case SELECT_VERTICES:
mSelectionSceneData->setActive(false);
mSelectionVertices->setActive(true);
break;
case UNDEFINED:
break;
}
updateModels();
}
void SelectionControl::initiateNewSelection(int x, int y)
{
switch (mSelectionMode)
{
case RAY:
initiateNewSelectionRay(x, y);
break;
case RECTANGLE:
initiateNewSelectionRectangle(x, y);
break;
}
}
void SelectionControl::updateSelection(int x, int y)
{
switch (mSelectionMode)
{
case RAY:
updateSelectionRay(x, y);
break;
case RECTANGLE:
updateSelectionRectangle(x, y);
break;
}
}
void SelectionControl::clearSelection()
{
switch(mSelectionType)
{
case SELECT_SCENE_NODES:
mSelectionSceneData->clear();
break;
case SELECT_VERTICES:
mSelectionVertices->clear();
break;
case UNDEFINED:
break;
}
}
void SelectionControl::clearSelectionMode()
{
switch (mSelectionMode)
{
case RAY:
// mSelectionRay->clear();
break;
case RECTANGLE:
mSelectionRectangle->setActive(false);
break;
}
}
void SelectionControl::selectSceneNode(SGNode* node)
{
std::set<std::shared_ptr<SceneData>> sceneDatas;
VertexCollection vc;
SGTraverser traverser = SGTraverserFactory::createDefaultSGTraverser(node);
class Visitor : public SGNodeVisitor
{
public:
Visitor(SelectionControl& _sc,
std::set<std::shared_ptr<SceneData>>& _sd,
VertexCollection& _vc)
: sc(_sc)
, sceneDatas(_sd)
, vc(_vc)
{
}
virtual void visit(SGChildrenNode* /*childrenNode*/)
{
}
virtual void visit(SGLeafNode* leafNode)
{
std::shared_ptr<SceneLeafData> data = leafNode->getData();
switch (sc.mSelectionType)
{
case SELECT_SCENE_NODES:
sceneDatas.insert(data);
break;
case SELECT_VERTICES:
{
GeometricData* gd = data->getGeometricDataRaw();
for (ID i = 0; i < gd->getSize(); ++i)
{
vc.addVertex(data, i);
}
break;
}
case UNDEFINED:
break;
}
for (auto it : sc.mSelectionListeners)
it->onSceneNodeSelected(data);
}
SelectionControl& sc;
std::set<std::shared_ptr<SceneData>>& sceneDatas;
VertexCollection& vc;
} visitor(*this, sceneDatas, vc);
traverser.traverse(visitor);
updateSelection(visitor.sceneDatas, visitor.vc);
updateModels();
}
void SelectionControl::selectSceneNodes(const std::vector<SGNode*>& nodes)
{
std::set<std::shared_ptr<SceneData>> nodesSet;
for (SGNode* node : nodes)
{
if (node->isLeaf())
nodesSet.insert(static_cast<SGLeafNode*>(node)->getData());
else
nodesSet.insert(static_cast<SGChildrenNode*>(node)->getData());
}
updateSelection(nodesSet, VertexCollection());
updateModels();
}
void SelectionControl::setSceneNodeSelection(const std::vector<SGNode*>& nodes)
{
std::set<std::shared_ptr<SceneData>> nodesSet;
for (SGNode* node : nodes)
{
if (node->isLeaf())
nodesSet.insert(static_cast<SGLeafNode*>(node)->getData());
else
nodesSet.insert(static_cast<SGChildrenNode*>(node)->getData());
}
updateSelection(nodesSet);
updateModels();
}
void SelectionControl::setVertexSelection(VertexCollection& vc)
{
updateSelection(vc);
updateModels();
}
SelectionControl::SelectionType SelectionControl::getSelectionType() const
{
return mSelectionType;
}
SelectionSceneData* SelectionControl::getSelectionSceneData()
{
return mSelectionSceneData.get();
}
SelectionVertices* SelectionControl::getSelectionVertices()
{
return mSelectionVertices.get();
}
const std::set<std::shared_ptr<SceneData>>& SelectionControl::getSelectedSceneData()
{
return mSelectionSceneData->getSceneData();
}
std::vector<std::shared_ptr<SceneLeafData>> SelectionControl::retrieveSelectedSceneLeafData()
{
std::vector<std::shared_ptr<SceneLeafData>> sceneLeafData;
for (const std::shared_ptr<SceneData>& sd : getSelectedSceneData())
{
if (sd->isLeafData())
{
sceneLeafData.push_back(std::static_pointer_cast<SceneLeafData>(sd));
}
}
return sceneLeafData;
}
void SelectionControl::initiateNewSelectionRectangle(int x, int y)
{
mSelectionRectangle->setRectangle(x, y, x, y);
mSelectionRectangle->setActive(true);
mSelectionRectangleModel->update();
}
void SelectionControl::updateSelectionRectangle(int xEnd, int yEnd)
{
mSelectionRectangle->setRectangle(
mSelectionRectangle->getXStart(),
mSelectionRectangle->getYStart(),
xEnd,
yEnd);
mSelectionRectangleModel->update();
}
void SelectionControl::cancelSelectionRectangle()
{
mSelectionRectangle->setActive(false);
}
void SelectionControl::initiateNewSelectionRay(int /*x*/, int /*y*/)
{
}
void SelectionControl::updateSelectionRay(int /*x*/, int /*y*/)
{
}
void SelectionControl::cancelSelectionRay()
{
}
const SelectionRectangle* SelectionControl::getSelectionRectangle() const
{
return mSelectionRectangle.get();
}
void SelectionControl::finalizeSelection(ViewFrustum& viewFrustum)
{
std::set<std::shared_ptr<SceneData>> sceneDatas;
VertexCollection vc;
// update selected vertices
// Iterate over the whole scene graph and
// -> If SelectionType == SELECT_VERTICES: finds out which vertices are
// within the given viewFrustum. Stores them in the VertexCollection.
// -> If SelectionType == SELECT_SCENE_NODES: finds out which scene nodes
// are within the given viewFrustum. Stores them in the sceneDatas.
SGTraverser traverser = mAc->getSGControl()->createSceneGraphTraverser();
class SelectionVisitor : public SGNodeVisitorImpl
{
public:
SelectionVisitor(SelectionControl& _sc,
ViewFrustum& _viewFrustum,
std::set<std::shared_ptr<SceneData>>& _sceneDatas,
VertexCollection& _vc)
: sc(_sc)
, viewFrustum(_viewFrustum)
, sceneDatas(_sceneDatas)
, vc(_vc)
{
}
void visit(SGLeafNode* leafNode)
{
sc.finalizeSelection(leafNode->getData(), viewFrustum, sceneDatas, vc);
}
SelectionControl& sc;
ViewFrustum& viewFrustum;
std::set<std::shared_ptr<SceneData>>& sceneDatas;
VertexCollection& vc;
} visitor(*this, viewFrustum, sceneDatas, vc);
traverser.traverse(visitor);
updateSelection(sceneDatas, vc);
// Disable selection rectangle
switch (mSelectionMode)
{
case RAY:
// mSelectionRay->setActive(false);
break;
case RECTANGLE:
mSelectionRectangle->setActive(false);
break;
}
updateModels();
}
void SelectionControl::updateModels()
{
mSelectionVerticesModel->update();
mSelectionSceneDataModel->update();
mSelectionRectangleModel->update();
}
void SelectionControl::addListener(SelectionListener* listener)
{
if (std::find(mSelectionListeners.begin(),
mSelectionListeners.end(), listener) ==
mSelectionListeners.end())
{
mSelectionListeners.push_back(listener);
}
}
void SelectionControl::removeListener(SelectionListener* listener)
{
auto it = std::find(mSelectionListeners.begin(),
mSelectionListeners.end(), listener);
if (it != mSelectionListeners.end())
{
mSelectionListeners.erase(it);
}
}
void SelectionControl::updateSelection(
const std::set<std::shared_ptr<SceneData> >& sceneDatas,
const VertexCollection& vc)
{
switch (mSelectionType)
{
case SELECT_SCENE_NODES:
updateSelection(sceneDatas);
break;
case SELECT_VERTICES:
updateSelection(vc);
break;
case UNDEFINED:
break;
}
}
void SelectionControl::updateSelection(const std::set<std::shared_ptr<SceneData> >& sceneDatas)
{
mSelectionSceneData->updateSelection(sceneDatas);
for (auto it : mSelectionListeners)
{
it->onSelectedSceneNodesChanged(mSelectionSceneData->getSceneData());
}
}
void SelectionControl::updateSelection(const VertexCollection& vc)
{
mSelectionVertices->updateSelectedVertices(vc);
for (auto it : mSelectionListeners)
{
it->onSelectedVerticesChanged(
mSelectionVertices->getDataVectorsMap());
}
}
void SelectionControl::finalizeSelection(
const std::shared_ptr<SceneLeafData>& leafData,
ViewFrustum& viewFrustum,
std::set<std::shared_ptr<SceneData>>& sceneDatas,
VertexCollection& vc)
{
switch(mSelectionType)
{
case SELECT_SCENE_NODES:
switch (mSelectionMode)
{
case RECTANGLE:
mSelectionSceneData->calculateSelectionByRectangle(
leafData, &viewFrustum, *mSelectionRectangle.get(),
sceneDatas);
break;
case RAY:
mSelectionSceneData->calculateSelectionByRay(
leafData, &viewFrustum,
mSelectionRectangle->getXEnd(),
mSelectionRectangle->getYEnd(),
sceneDatas);
break;
}
break;
case SELECT_VERTICES:
switch (mSelectionMode)
{
case RECTANGLE:
mSelectionVertices->calculateSelectionByRectangle(
leafData, &viewFrustum, *mSelectionRectangle.get(), vc);
break;
case RAY:
mSelectionVertices->calculateSelectionByRay(
leafData, &viewFrustum,
mSelectionRectangle->getXEnd(),
mSelectionRectangle->getYEnd(), vc);
break;
}
break;
case UNDEFINED:
break;
}
}
| 26.184549 | 95 | 0.634814 | [
"vector"
] |
3167a18897db0cb3f08abe861554157d59390c9e | 6,521 | cpp | C++ | source/game/OLDGameView.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | source/game/OLDGameView.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | source/game/OLDGameView.cpp | WarzesProject/2dgame | 7c398505bd02f9c519f2968bceb3ba87ac26a6a5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "OLDGameView.h"
#include "Application.h"
#include "TileSheet.h"
#include "GLSLProgram.h"
#include "SpriteBatch.h"
//-----------------------------------------------------------------------------
void OLDGameView::OnEntry()
{
const int screenWidth = m_app->GetScreenWidth();
const int screenHeight = m_app->GetScreenHeight();
m_screenSize = glm::vec2(screenWidth, screenHeight);
m_camera.Init(screenWidth, screenHeight);
m_camera.SetScale(0.9);
m_debuger.Init();
m_spriteBatch.Init();
m_textureProgram.CompileShadersFromFile("../test/Shaders/color.vert", "../test/Shaders/color.frag");
m_textureProgram.AddAttribute("vertexPosition");
m_textureProgram.AddAttribute("vertexColor");
m_textureProgram.AddAttribute("vertexUV");
m_textureProgram.LinkShaders();
m_bgm = ResourceManager::GetMusic("../test/Sound/Battleship.ogg");
m_bgm.SetVolume(50);
m_bgm.Play();
initLevel();
}
//-----------------------------------------------------------------------------
void OLDGameView::OnExit()
{
for ( auto &it : m_monsters )
delete it;
m_monsters.clear();
for ( auto &it :m_items )
delete it;
m_items.clear();
m_level.release();
m_textureProgram.Dispose();
m_spriteBatch.Dispose();
m_debuger.Dispose();
if ( m_player )
m_player->SetReachedState(false);
}
//-----------------------------------------------------------------------------
void OLDGameView::Update()
{
m_camera.SetPosition(m_level->GetCameraPos(m_player->GetPosition(), m_screenSize, m_camera.GetScale()));
m_camera.Update();
if ( m_app->GetEventHandler()->IsKeyPressed(SDLK_d) )
m_isDebugMode = !m_isDebugMode;
updateObject();
}
//-----------------------------------------------------------------------------
void OLDGameView::Draw()
{
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(195.0 / 255.0, 195.0 / 255.0, 195.0 / 255.0, 1.0);
m_textureProgram.Use();
const GLint textureUniform = m_textureProgram.GetUniformLocation("samplerUniform");
glUniform1i(textureUniform, 0);
glActiveTexture(GL_TEXTURE0);
const glm::mat4 projectionMatrix = m_camera.GetCameraMatrix();
const GLint pUniform = m_textureProgram.GetUniformLocation("projectionMatrix");
glUniformMatrix4fv(pUniform, 1, GL_FALSE, &(projectionMatrix[0][0]));
m_level->Draw();
m_spriteBatch.Begin();
{
for ( auto &it : m_items )
{
if ( m_camera.IsBoxInView(it->GetPosition(), it->GetSize()) )
it->Draw(m_spriteBatch);
}
m_player->Draw(m_spriteBatch);
for ( auto &it : m_monsters )
{
if ( m_camera.IsBoxInView(it->GetPosition(), it->GetSize()) )
it->Draw(m_spriteBatch);
}
}
m_spriteBatch.End();
m_spriteBatch.RenderBatch();
m_textureProgram.Unuse();
if ( m_isDebugMode )
DrawDebug(projectionMatrix);
}
//-----------------------------------------------------------------------------
int OLDGameView::GetNextViewIndex() const
{
return -1;
}
//-----------------------------------------------------------------------------
int OLDGameView::GetPreviousViewIndex() const
{
return -1;
}
//-----------------------------------------------------------------------------
void OLDGameView::initLevel()
{
m_level = std::make_unique<Level>("../test/Levels/testLevel.txt");
std::mt19937 randomEngine((unsigned int)time(nullptr));
const std::uniform_int_distribution<int> randomMonsterNum(10, 10);
const std::uniform_int_distribution<int> randomMovement(0, 1000);
const std::uniform_int_distribution<int> yPos(3, m_level->GetHeight() - 3);
const std::uniform_int_distribution<int> xPos(3, m_level->GetWidth() - 3);
const std::uniform_int_distribution<int> randomItemNum(1, 10);
const std::uniform_int_distribution<int> randomItemKind(0, 3);
int i = 0;
int count = 2;
const int numMonster = randomMonsterNum(randomEngine);
m_monsters.reserve(numMonster);
while ( i < numMonster )
{
const int x = xPos(randomEngine);
const int y = yPos(randomEngine);
const int movement = ((randomMovement(randomEngine) * count) % MAX_MOVEMENT + count / 2);
if ( m_level->GetSymbol(x, y) == '.' )
{
glm::vec2 pos = glm::vec2(x * TILE_WIDTH, y * TILE_WIDTH);
m_monsters.push_back(new Skeleton);
m_monsters.back()->Init(2, 3, pos, 20);
i++;
}
count++;
}
const int numItem = randomItemNum(randomEngine);
int j = 0;
while ( j < numItem )
{
const int typeItem = randomItemKind(randomEngine);
const int x = xPos(randomEngine);
const int y = yPos(randomEngine);
if ( m_level->GetSymbol(x, y) == '.' )
{
glm::vec2 pos = glm::vec2(x * TILE_WIDTH, y * TILE_WIDTH);
switch ( typeItem )
{
case 0:
m_items.push_back(new BigPotion);
break;
case 1:
m_items.push_back(new SmallPotion);
break;
case 2:
m_items.push_back(new AttPotion);
break;
case 3:
m_items.push_back(new SpeedPotion);
break;
default:
Throw("Not ID item");
break;
}
m_items.back()->Init(pos);
j++;
}
}
m_player = Player::GetInstance();
m_player->Init(m_level->GetStartPlayerPosition(), PLAYER_SPEED);
}
//-----------------------------------------------------------------------------
void OLDGameView::DrawDebug(const glm::mat4 &projectionMatrix)
{
glm::vec4 destRect;
for ( auto &it : m_monsters )
it->DrawDebug(m_debuger);
for ( auto &it : m_items )
it->DrawDebug(m_debuger);
m_player->DrawDebug(m_debuger);
m_debuger.End();
m_debuger.Render(projectionMatrix, 2.0);
}
//-----------------------------------------------------------------------------
void OLDGameView::updateObject()
{
auto eventHandler = m_app->GetEventHandler();
m_player->Update(*eventHandler, m_level->GetLevelData());
if ( m_player->IsPlayerDead() )
m_player->Recreate(m_level->GetStartPlayerPosition());
for ( size_t i = 0; i < m_monsters.size(); i++ )
{
if ( m_monsters[i]->IsDead() )
{
delete m_monsters[i];
m_monsters[i] = m_monsters.back();
m_monsters.pop_back();
i--;
}
}
for ( size_t i = 0; i < m_items.size(); i++ )
{
if ( m_items[i]->IsDisappeared() )
{
delete m_items[i];
m_items[i] = m_items.back();
m_items.pop_back();
i--;
}
}
m_player->CollideWithMonsters(m_monsters);
m_player->CollideWithItems(m_items);
for ( auto &it : m_monsters )
it->Update(m_level->GetLevelData(), m_player->GetPosition());
for ( size_t i = 0; i < m_monsters.size(); i++ )
{
m_monsters[i]->CollideWithMonsters(m_monsters, i);
m_monsters[i]->CollideWithItems(m_items);
}
}
//----------------------------------------------------------------------------- | 27.058091 | 105 | 0.611103 | [
"render"
] |
3178d3deaa6551e7b3715cffd52ae4923f812914 | 15,493 | cc | C++ | core/common/src/common/rss/rss_checker.cc | GallopWind/epsilon-learn | 74dc723fbc9797f3bd05bee30f6f9b9acceeec17 | [
"MIT"
] | 186 | 2020-09-22T10:57:57.000Z | 2022-03-30T15:52:15.000Z | core/common/src/common/rss/rss_checker.cc | Yufei-Wei/EPSILON | 155f1b1c4dae3ae29287d5b0b967d7d6ce230c73 | [
"MIT"
] | 16 | 2020-10-19T02:55:49.000Z | 2022-01-14T08:17:06.000Z | core/common/src/common/rss/rss_checker.cc | Yufei-Wei/EPSILON | 155f1b1c4dae3ae29287d5b0b967d7d6ce230c73 | [
"MIT"
] | 66 | 2020-09-28T01:51:57.000Z | 2022-03-25T08:39:04.000Z | #include "common/rss/rss_checker.h"
namespace common {
ErrorType RssChecker::CalculateSafeLongitudinalDistance(
const decimal_t ego_vel, const decimal_t other_vel,
const LongitudinalDirection& direction, const RssConfig& config,
decimal_t* distance) {
decimal_t ret = 0.0;
decimal_t ego_vel_abs = fabs(ego_vel);
decimal_t other_vel_abs = fabs(other_vel);
decimal_t ego_vel_at_response_time =
ego_vel_abs + config.longitudinal_acc_max * config.response_time;
decimal_t other_vel_at_response_time =
other_vel_abs + config.longitudinal_acc_max * config.response_time;
decimal_t ego_distance_driven, other_distance_driven;
if (direction == Front) {
ego_distance_driven =
(ego_vel_abs + ego_vel_at_response_time) / 2.0 * config.response_time +
ego_vel_at_response_time * ego_vel_at_response_time /
(2 * config.longitudinal_brake_min);
if (ego_vel >= 0.0 && other_vel >= 0.0) {
// ego vehicle ==> other vehicle ->
other_distance_driven =
(other_vel_abs * other_vel_abs) / (2 * config.longitudinal_brake_max);
ret = ego_distance_driven - other_distance_driven;
} else if (ego_vel >= 0.0 && other_vel <= 0.0) {
// ego vehicle ==> <-- other vehicle
other_distance_driven = (other_vel_abs + other_vel_at_response_time) /
2.0 * config.response_time +
other_vel_at_response_time *
other_vel_at_response_time /
(2 * config.longitudinal_brake_min);
ret = ego_distance_driven + other_distance_driven;
} else {
// printf("[RssChecker]Currently do not support rear gear %lf.\n",
// ego_vel);
ret = 0.0;
}
} else if (direction == Rear) {
ego_distance_driven =
ego_vel_abs * ego_vel_abs / (2 * config.longitudinal_brake_max);
if (ego_vel >= 0.0 && other_vel >= 0.0) {
// other car --> ego car ==>
other_distance_driven = (other_vel_abs + other_vel_at_response_time) /
2.0 * config.response_time +
other_vel_at_response_time *
other_vel_at_response_time /
(2 * config.longitudinal_brake_min);
ret = other_distance_driven - ego_distance_driven;
} else if (ego_vel >= 0.0 && other_vel <= 0.0) {
ret = 0.0;
} else {
// printf("[RssChecker]Currently do not support rear gear %lf.\n",
// ego_vel);
ret = 0.0;
}
}
*distance = ret > 0.0 ? ret : 0.0;
return kSuccess;
}
ErrorType RssChecker::CalculateSafeLongitudinalVelocity(
const decimal_t other_vel, const LongitudinalDirection& direction,
const decimal_t& lon_distance_abs, const RssConfig& config,
decimal_t* ego_vel_low, decimal_t* ego_vel_upp) {
decimal_t other_vel_abs = fabs(other_vel);
decimal_t other_vel_at_response_time =
other_vel_abs + config.longitudinal_acc_max * config.response_time;
decimal_t other_distance_driven;
if (direction == Front) {
if (other_vel >= 0.0) {
// ego ---->(lon_distance) other --->
// other hard brake
other_distance_driven =
(other_vel_abs * other_vel_abs) / (2 * config.longitudinal_brake_max);
// ego has vel upp
decimal_t a = 1.0 / (2.0 * config.longitudinal_brake_min);
decimal_t b = config.response_time +
(config.longitudinal_acc_max * config.response_time /
config.longitudinal_brake_min);
decimal_t c = 0.5 *
(config.longitudinal_acc_max +
pow(config.longitudinal_acc_max, 2) /
config.longitudinal_brake_min) *
pow(config.response_time, 2) -
other_distance_driven - lon_distance_abs;
*ego_vel_upp = (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
*ego_vel_low = 0.0;
} else {
// ego ----> <---- other
other_distance_driven = (other_vel_abs + other_vel_at_response_time) /
2.0 * config.response_time +
other_vel_at_response_time *
other_vel_at_response_time /
(2 * config.longitudinal_brake_min);
if (other_distance_driven > lon_distance_abs) {
*ego_vel_upp = 0.0;
*ego_vel_low = 0.0;
} else {
decimal_t a = 1.0 / (2.0 * config.longitudinal_brake_min);
decimal_t b = config.response_time +
(config.longitudinal_acc_max * config.response_time /
config.longitudinal_brake_min);
decimal_t c = 0.5 *
(config.longitudinal_acc_max +
pow(config.longitudinal_acc_max, 2) /
config.longitudinal_brake_min) *
pow(config.response_time, 2) -
(lon_distance_abs - other_distance_driven);
*ego_vel_upp = (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
*ego_vel_low = 0.0;
}
}
} else {
if (other_vel >= 0.0) {
// other ---> ego--->
other_distance_driven = (other_vel_abs + other_vel_at_response_time) /
2.0 * config.response_time +
other_vel_at_response_time *
other_vel_at_response_time /
(2 * config.longitudinal_brake_min);
if (other_distance_driven < lon_distance_abs) {
*ego_vel_upp = kInf;
*ego_vel_low = 0.0;
} else {
*ego_vel_upp = kInf;
*ego_vel_low = sqrt(2 * config.longitudinal_brake_max *
(other_distance_driven - lon_distance_abs));
}
} else {
// <----other ego-->
*ego_vel_upp = kInf;
*ego_vel_low = 0.0;
}
}
return kSuccess;
}
ErrorType RssChecker::CalculateSafeLateralDistance(
const decimal_t ego_vel, const decimal_t other_vel,
const LateralDirection& direction, const RssConfig& config,
decimal_t* distance) {
decimal_t ret = 0.0;
decimal_t ego_lat_vel_abs = fabs(ego_vel);
decimal_t other_lat_vel_abs = fabs(other_vel);
decimal_t distance_correction = config.lateral_miu;
decimal_t ego_lat_vel_at_response_time =
ego_lat_vel_abs + config.response_time * config.lateral_acc_max;
decimal_t other_lat_vel_at_response_time =
other_lat_vel_abs + config.response_time * config.lateral_acc_max;
decimal_t ego_active_brake_distance =
ego_lat_vel_abs * ego_lat_vel_abs / (2 * config.lateral_brake_max);
decimal_t ego_passive_brake_distance =
(ego_lat_vel_abs + ego_lat_vel_at_response_time) / 2.0 *
config.response_time +
ego_lat_vel_at_response_time * ego_lat_vel_at_response_time /
(2 * config.lateral_brake_min);
decimal_t other_active_brake_distance =
other_lat_vel_abs * other_lat_vel_abs / (2 * config.lateral_brake_max);
decimal_t other_passive_brake_distance =
(other_lat_vel_abs + other_lat_vel_at_response_time) / 2.0 *
config.response_time +
other_lat_vel_at_response_time * other_lat_vel_at_response_time /
(2 * config.lateral_brake_min);
if (direction == Right) {
if (ego_vel >= 0.0 && other_vel >= 0.0) {
// -------------------------------
// ego ^^^^^^^^
// -------------------------------
// other ^^^^^^^^
// -------------------------------
ret = other_passive_brake_distance - ego_active_brake_distance;
} else if (ego_vel >= 0.0 && other_vel < 0.0) {
// -------------------------------
// ego ^^^^^^^^
// -------------------------------
// other vvvvvvvv
// -------------------------------
ret = 0.0;
} else if (ego_vel < 0.0 && other_vel < 0.0) {
// -------------------------------
// ego vvvvvvvv
// -------------------------------
// other vvvvvvvv
// -------------------------------
ret = ego_passive_brake_distance - other_active_brake_distance;
} else if (ego_vel < 0.0 && other_vel >= 0.0) {
// -------------------------------
// ego vvvvvvvv
// -------------------------------
// other ^^^^^^^^
// -------------------------------
ret = ego_passive_brake_distance + other_passive_brake_distance;
} else {
// printf("[RssChecker]Lat Error configuration.\n");
// assert(false);
ret = 0.0;
}
} else if (direction == Left) {
if (ego_vel >= 0.0 && other_vel >= 0.0) {
// -------------------------------
// other ^^^^^^^^
// -------------------------------
// ego ^^^^^^^^
// -------------------------------
ret = ego_passive_brake_distance - other_active_brake_distance;
} else if (ego_vel >= 0.0 && other_vel < 0.0) {
// -------------------------------
// other vvvvvvvv
// -------------------------------
// ego ^^^^^^^^
// -------------------------------
ret = ego_passive_brake_distance + other_passive_brake_distance;
} else if (ego_vel < 0.0 && other_vel < 0.0) {
// -------------------------------
// other vvvvvvvv
// -------------------------------
// ego vvvvvvvv
// -------------------------------
ret = other_passive_brake_distance - ego_active_brake_distance;
} else if (ego_vel < 0.0 && other_vel >= 0.0) {
// -------------------------------
// other ^^^^^^^^
// -------------------------------
// ego vvvvvvvv
// -------------------------------
ret = 0.0;
} else {
// printf("[RssChecker]Lat Error configuration.\n");
// assert(false);
ret = 0.0;
}
}
ret = ret > 0.0 ? ret : 0.0;
ret += distance_correction;
*distance = ret;
return kSuccess;
}
ErrorType RssChecker::CalculateRssSafeDistances(
const std::vector<decimal_t>& ego_vels,
const std::vector<decimal_t>& other_vels,
const LongitudinalDirection& lon_direct, const LateralDirection& lat_direct,
const RssConfig& config, std::vector<decimal_t>* safe_distances) {
safe_distances->clear();
decimal_t safe_long_distance, safe_lat_distance;
CalculateSafeLongitudinalDistance(ego_vels[0], other_vels[0], lon_direct,
config, &safe_long_distance);
CalculateSafeLateralDistance(ego_vels[1], other_vels[1], lat_direct, config,
&safe_lat_distance);
safe_distances->push_back(safe_long_distance);
safe_distances->push_back(safe_lat_distance);
return kSuccess;
}
ErrorType RssChecker::RssCheck(const FrenetState& ego_fs,
const FrenetState& other_fs,
const RssConfig& config, bool* is_safe) {
LongitudinalDirection lon_direct;
LateralDirection lat_direct;
if (ego_fs.vec_s[0] >= other_fs.vec_s[0]) {
lon_direct = Rear;
} else {
lon_direct = Front;
}
if (ego_fs.vec_dt[0] >= other_fs.vec_dt[0]) {
lat_direct = Right;
} else {
lat_direct = Left;
}
std::vector<decimal_t> ego_vels{ego_fs.vec_s[1], ego_fs.vec_dt[1]};
std::vector<decimal_t> other_vels{other_fs.vec_s[1], other_fs.vec_dt[1]};
std::vector<decimal_t> safe_distances;
CalculateRssSafeDistances(ego_vels, other_vels, lon_direct, lat_direct,
config, &safe_distances);
if (fabs(ego_fs.vec_s[0] - other_fs.vec_s[0]) < safe_distances[0] &&
fabs(ego_fs.vec_dt[0] - other_fs.vec_dt[0]) < safe_distances[1]) {
*is_safe = false;
} else {
*is_safe = true;
}
return kSuccess;
}
ErrorType RssChecker::RssCheck(const Vehicle& ego_vehicle,
const Vehicle& other_vehicle,
const StateTransformer& stf, const RssConfig& config,
bool* is_safe, LongitudinalViolateType* lon_type,
decimal_t* rss_vel_low, decimal_t* rss_vel_up) {
FrenetState ego_fs, other_fs;
// TODO(lu.zhang): construct stf is a little bit heavy
// StateTransformer stf(ref_lane);
if (stf.GetFrenetStateFromState(ego_vehicle.state(), &ego_fs) != kSuccess) {
printf("[RssChecker]ego not on ref lane.\n");
return kWrongStatus;
}
if (stf.GetFrenetStateFromState(other_vehicle.state(), &other_fs) !=
kSuccess) {
printf("[RssChecker]other %d not on ref lane.\n", other_vehicle.id());
return kWrongStatus;
}
LongitudinalDirection lon_direct;
LateralDirection lat_direct;
if (ego_fs.vec_s[0] >= other_fs.vec_s[0]) {
lon_direct = Rear;
} else {
lon_direct = Front;
}
if (ego_fs.vec_dt[0] >= other_fs.vec_dt[0]) {
lat_direct = Right;
} else {
lat_direct = Left;
}
if (ego_fs.vec_s[1] < 0.0) {
*is_safe = true;
*lon_type = LongitudinalViolateType::Legal;
*rss_vel_up = 0.0;
*rss_vel_low = 0.0;
return kSuccess;
}
decimal_t safe_lat_distance;
CalculateSafeLateralDistance(ego_fs.vec_dt[1], other_fs.vec_dt[1], lat_direct,
config, &safe_lat_distance);
safe_lat_distance +=
0.5 * (ego_vehicle.param().width() + other_vehicle.param().width());
if (fabs(ego_fs.vec_dt[0] - other_fs.vec_dt[0]) > safe_lat_distance) {
*is_safe = true;
*lon_type = LongitudinalViolateType::Legal;
*rss_vel_up = 0.0;
*rss_vel_low = 0.0;
return kSuccess;
}
decimal_t lon_distance_abs, ego_vel_low, ego_vel_upp;
if (lon_direct == Rear) {
decimal_t other_rear_wheel_to_front_bump =
0.5 * other_vehicle.param().length() + other_vehicle.param().d_cr();
decimal_t ego_rear_wheel_to_back_bump =
fabs(0.5 * ego_vehicle.param().length() - ego_vehicle.param().d_cr());
lon_distance_abs = fabs(ego_fs.vec_s[0] - other_fs.vec_s[0]) -
other_rear_wheel_to_front_bump -
ego_rear_wheel_to_back_bump;
} else if (lon_direct == Front) {
decimal_t ego_rear_wheel_to_front_bump =
0.5 * ego_vehicle.param().length() + ego_vehicle.param().d_cr();
decimal_t other_rear_wheel_to_back_bump = fabs(
0.5 * other_vehicle.param().length() - other_vehicle.param().d_cr());
lon_distance_abs = fabs(ego_fs.vec_s[0] - other_fs.vec_s[0]) -
ego_rear_wheel_to_front_bump -
other_rear_wheel_to_back_bump;
}
if (lon_distance_abs < 0.0 && lon_direct == Front) {
*is_safe = false;
*lon_type = LongitudinalViolateType::TooFast;
*rss_vel_up = 0.0;
*rss_vel_low = 0.0;
return kSuccess;
}
CalculateSafeLongitudinalVelocity(other_fs.vec_s[1], lon_direct,
lon_distance_abs, config, &ego_vel_low,
&ego_vel_upp);
if (ego_fs.vec_s[1] > ego_vel_upp + kEPS) {
*is_safe = false;
*lon_type = LongitudinalViolateType::TooFast;
*rss_vel_up = ego_vel_upp;
*rss_vel_low = ego_vel_low;
} else if (ego_fs.vec_s[1] < ego_vel_low - kEPS) {
*is_safe = false;
*lon_type = LongitudinalViolateType::TooSlow;
*rss_vel_up = ego_vel_upp;
*rss_vel_low = ego_vel_low;
} else {
*is_safe = true;
*lon_type = LongitudinalViolateType::Legal;
*rss_vel_up = 0.0;
*rss_vel_low = 0.0;
}
return kSuccess;
}
} // namespace common
| 39.222785 | 84 | 0.575421 | [
"vector"
] |
317ebdde987b6f629816b864d5b4e965548eefde | 589 | cpp | C++ | leetcode/34. Search for a Range/s1.cpp | joycse06/LeetCode-1 | ad105bd8c5de4a659c2bbe6b19f400b926c82d93 | [
"Fair"
] | 1 | 2021-02-11T01:23:10.000Z | 2021-02-11T01:23:10.000Z | leetcode/34. Search for a Range/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | null | null | null | leetcode/34. Search for a Range/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 1 | 2021-03-25T17:11:14.000Z | 2021-03-25T17:11:14.000Z | // OJ: https://leetcode.com/problems/search-for-a-range
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int L = 0, R = nums.size() - 1;
while (L <= R) {
int M = (L + R) / 2;
if (nums[M] < target) ++L;
else --R;
}
if (L >= nums.size() || nums[L] != target) return {-1, -1};
int left = L;
L = 0, R = nums.size() - 1;
while (L <= R) {
int M = (L + R) / 2;
if (nums[M] <= target) ++L;
else --R;
}
return { left, R };
}
}; | 24.541667 | 63 | 0.478778 | [
"vector"
] |
31859873fbadf6c5003540ed767a8647143ae6c5 | 1,431 | cpp | C++ | lib/assets/main.cpp | Honeyman-Applications/commandline_or_gui_windows | ee4ff70bbaadafee8c00f74a482a0f50db71141b | [
"MIT"
] | null | null | null | lib/assets/main.cpp | Honeyman-Applications/commandline_or_gui_windows | ee4ff70bbaadafee8c00f74a482a0f50db71141b | [
"MIT"
] | null | null | null | lib/assets/main.cpp | Honeyman-Applications/commandline_or_gui_windows | ee4ff70bbaadafee8c00f74a482a0f50db71141b | [
"MIT"
] | null | null | null | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
// ******* ADDED *******
#include "win32_window.h" // where flag to hide gui is added
#pragma comment(linker, "/subsystem:console") // tells the linker to use console subsystem
/*
New main, because the app is now a console app
*/
int main(int argc, char *argv[])
{
// if any arguments are passed run in commandline mode
if (argc > 1)
{
H_HIDE_WINDOW = true;
}
else
{
::ShowWindow(::GetConsoleWindow(), SW_HIDE);
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
// change string to show a different title
if (!window.CreateAndShow(L"commandline_or_gui_windows_example", origin, size))
{
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
| 24.254237 | 90 | 0.686932 | [
"vector"
] |
31950184abe5252ec4cb9d706fe6dc3143359d43 | 12,544 | cpp | C++ | melodic/src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiandottest.cpp | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T12:33:55.000Z | 2021-11-21T07:14:13.000Z | melodic/src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiandottest.cpp | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | melodic/src/orocos_kinematics_dynamics/orocos_kdl/tests/jacobiandottest.cpp | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | #include "jacobiandottest.hpp"
CPPUNIT_TEST_SUITE_REGISTRATION(JacobianDotTest);
using namespace KDL;
void JacobianDotTest::setUp(){}
void JacobianDotTest::tearDown(){}
namespace KDL{
static const double L0 = 1.0;
static const double L1 = 0.5;
static const double L2 = 0.4;
static const double L3 = 0;
static const double L4 = 0;
static const double L5 = 0;
Chain d2(){
Chain d2;
d2.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(L0,0,0))));
d2.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(L1,0,0))));
return d2;
}
Chain d6(){
Chain d6;
d6.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(L0,0,0))));
d6.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(L1,0,0))));
d6.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(L2,0,0))));
d6.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(L3,0,0))));
d6.addSegment(Segment(Joint(Joint::RotX),Frame(Vector(L4,0,0))));
d6.addSegment(Segment(Joint(Joint::RotZ),Frame(Vector(L5,0,0))));
return d6;
}
Chain KukaLWR_DHnew(){
Chain kukaLWR_DHnew;
//joint 0
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::None),
Frame::DH_Craig1989(0.0, 0.0, 0.31, 0.0)
));
//joint 1
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, 1.5707963, 0.0, 0.0),
Frame::DH_Craig1989(0.0, 1.5707963, 0.0, 0.0).Inverse()*RigidBodyInertia(2,
Vector::Zero(),
RotationalInertia(0.0,0.0,0.0115343,0.0,0.0,0.0))));
//joint 2
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, -1.5707963, 0.4, 0.0),
Frame::DH_Craig1989(0.0, -1.5707963, 0.4, 0.0).Inverse()*RigidBodyInertia(2,
Vector(0.0,-0.3120511,-0.0038871),
RotationalInertia(-0.5471572,-0.0000302,-0.5423253,0.0,0.0,0.0018828))));
//joint 3
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, -1.5707963, 0.0, 0.0),
Frame::DH_Craig1989(0.0, -1.5707963, 0.0, 0.0).Inverse()*RigidBodyInertia(2,
Vector(0.0,-0.0015515,0.0),
RotationalInertia(0.0063507,0.0,0.0107804,0.0,0.0,-0.0005147))));
//joint 4
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, 1.5707963, 0.39, 0.0),
Frame::DH_Craig1989(0.0, 1.5707963, 0.39, 0.0).Inverse()*RigidBodyInertia(2,
Vector(0.0,0.5216809,0.0),
RotationalInertia(-1.0436952,0.0,-1.0392780,0.0,0.0,0.0005324))));
//joint 5
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, 1.5707963, 0.0, 0.0),
Frame::DH_Craig1989(0.0, 1.5707963, 0.0, 0.0).Inverse()*RigidBodyInertia(2,
Vector(0.0,0.0119891,0.0),
RotationalInertia(0.0036654,0.0,0.0060429,0.0,0.0,0.0004226))));
//joint 6
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::DH_Craig1989(0.0, -1.5707963, 0.0, 0.0),
Frame::DH_Craig1989(0.0, -1.5707963, 0.0, 0.0).Inverse()*RigidBodyInertia(2,
Vector(0.0,0.0080787,0.0),
RotationalInertia(0.0010431,0.0,0.0036376,0.0,0.0,0.0000101))));
//joint 7
kukaLWR_DHnew.addSegment(Segment(Joint(Joint::RotZ),
Frame::Identity(),
RigidBodyInertia(2,
Vector::Zero(),
RotationalInertia(0.000001,0.0,0.0001203,0.0,0.0,0.0))));
return kukaLWR_DHnew;
}
}
void changeRepresentation(Jacobian& J,const Frame& F_bs_ee,const int& representation)
{
switch(representation)
{
case ChainJntToJacDotSolver::HYBRID:
break;
case ChainJntToJacDotSolver::BODYFIXED:
// Ref Frame {ee}, Ref Point {ee}
J.changeBase(F_bs_ee.M.Inverse());
break;
case ChainJntToJacDotSolver::INTERTIAL:
// Ref Frame {bs}, Ref Point {bs}
J.changeRefPoint(-F_bs_ee.p);
break;
}
}
void Jdot_diff(const Jacobian& J_q,
const Jacobian& J_qdt,
const double& dt,
Jacobian& Jdot)
{
assert(J_q.columns() == J_qdt.columns());
assert(J_q.columns() == Jdot.columns());
for(int l=0;l<6;l++)
for(int c=0;c<J_q.columns();c++)
Jdot(l,c) = (J_qdt(l,c) - J_q(l,c))/dt;
}
Jacobian Jdot_d2_symbolic(const JntArray& q,const JntArray& qdot)
{
// Returns Jdot for the simple 2DOF arm
Jacobian Jdot(q.rows());
SetToZero(Jdot);
Jdot(0,0) = -L1 * (qdot(0) + qdot(1))*cos(q(0)+q(1))-L0*cos(q(0))*qdot(0);
Jdot(0,1) = -L1 * (qdot(0) + qdot(1))*cos(q(0)+q(1));
Jdot(1,0) = -L1 * (qdot(0) + qdot(1))*sin(q(0)+q(1))-L0*sin(q(0))*qdot(0);
Jdot(1,1) = -L1 * (qdot(0) + qdot(1))*sin(q(0)+q(1));
return Jdot;
}
Jacobian J_d2_symbolic(const JntArray& q,const JntArray& qdot)
{
// Returns J for the simple 2DOF arm
Jacobian J(q.rows());
SetToZero(J);
J(0,0) = -L1 * sin(q(0)+q(1))-L0*sin(q(0));
J(0,1) = -L1 * sin(q(0)+q(1));
J(1,0) = L1 * cos(q(0)+q(1))+L0*cos(q(0));
J(1,1) = L1 * cos(q(0)+q(1));
J(5,0) = J(5,1) = 1;
return J;
}
JntArray diff(const JntArray& q,const JntArray& qdot,const double& dt)
{
JntArray q_qdqt(q);
for(int i=0; i<q.rows(); i++)
q_qdqt(i) += dt*qdot(i);
return q_qdqt;
}
void random(JntArray& q)
{
for(int i=0; i<q.rows(); i++)
random(q(i));
}
double compare_Jdot_Diff_vs_Solver(const Chain& chain,const double& dt,const int& representation,bool verbose)
{
// This test verifies if the solvers gives approx. the same result as [ J(q+qdot*dot) - J(q) ]/dot
JntArray q(chain.getNrOfJoints());
JntArray qdot(chain.getNrOfJoints());
JntArray q_dqdt(chain.getNrOfJoints());
random(q);
random(qdot);
q_dqdt = diff(q,qdot,dt);
ChainJntToJacDotSolver jdot_solver(chain);
ChainJntToJacSolver j_solver(chain);
ChainFkSolverPos_recursive fk_solver(chain);
Frame F_bs_ee_q,F_bs_ee_q_dqdt;
Jacobian jac_q(chain.getNrOfJoints()),
jac_q_dqdt(chain.getNrOfJoints()),
jdot_by_diff(chain.getNrOfJoints());
j_solver.JntToJac(q,jac_q);
j_solver.JntToJac(q_dqdt,jac_q_dqdt);
fk_solver.JntToCart(q,F_bs_ee_q);
fk_solver.JntToCart(q_dqdt,F_bs_ee_q_dqdt);
changeRepresentation(jac_q,F_bs_ee_q,representation);
changeRepresentation(jac_q_dqdt,F_bs_ee_q_dqdt,representation);
Jdot_diff(jac_q,jac_q_dqdt,dt,jdot_by_diff);
Jacobian jdot_by_solver(chain.getNrOfJoints());
jdot_solver.setRepresentation(representation);
jdot_solver.JntToJacDot(JntArrayVel(q_dqdt,qdot),jdot_by_solver);
Twist jdot_qdot_by_solver;
MultiplyJacobian(jdot_by_solver,qdot,jdot_qdot_by_solver);
Twist jdot_qdot_by_diff;
MultiplyJacobian(jdot_by_diff,qdot,jdot_qdot_by_diff);
if(verbose){
std::cout << "Jdot diff : \n" << jdot_by_diff<<std::endl;
std::cout << "Jdot solver:\n"<<jdot_by_solver<<std::endl;
std::cout << "Error : " <<jdot_qdot_by_diff-jdot_qdot_by_solver<<q<<qdot<<std::endl;
}
double err = jdot_qdot_by_diff.vel.Norm() - jdot_qdot_by_solver.vel.Norm()
+ jdot_qdot_by_diff.rot.Norm() - jdot_qdot_by_solver.rot.Norm();
return std::abs(err);
}
double compare_d2_Jdot_Symbolic_vs_Solver(bool verbose)
{
Chain chain=d2();
JntArray q(chain.getNrOfJoints());
JntArray qdot(chain.getNrOfJoints());
random(q);
random(qdot);
ChainJntToJacDotSolver jdot_solver(chain);
Jacobian jdot_sym = Jdot_d2_symbolic(q,qdot);
Jacobian jdot_by_solver(chain.getNrOfJoints());
jdot_solver.JntToJacDot(JntArrayVel(q,qdot),jdot_by_solver);
Twist jdot_qdot_by_solver;
MultiplyJacobian(jdot_by_solver,qdot,jdot_qdot_by_solver);
Twist jdot_qdot_sym;
MultiplyJacobian(jdot_sym,qdot,jdot_qdot_sym);
if(verbose){
std::cout << "Jdot symbolic : \n" << jdot_sym<<std::endl;
std::cout << "Jdot solver:\n"<<jdot_by_solver<<std::endl;
std::cout << "Error : " <<jdot_qdot_sym-jdot_qdot_by_solver<<q<<qdot<<std::endl;
}
double err = jdot_qdot_sym.vel.Norm() - jdot_qdot_by_solver.vel.Norm()
+ jdot_qdot_sym.rot.Norm() - jdot_qdot_by_solver.rot.Norm();
return std::abs(err);
}
bool runTest(const Chain& chain,const int& representation)
{
bool success=true;
bool verbose = false;
double err;
bool print_err = false;
for(double dt=1e-6;dt<0.1;dt*=10)
{
double eps_diff_vs_solver = 3.0*dt; // Apparently :)
for(int i=0;i<100;i++)
{
err = compare_Jdot_Diff_vs_Solver(chain,dt,representation,verbose);
success &= err<=eps_diff_vs_solver;
if(!success || print_err){
std::cout<<" dt:"<< dt<<" err:"<<err
<<" eps_diff_vs_solver:"<<eps_diff_vs_solver
<<std::endl;
if(!success)
break;
}
}
}
return success;
}
void JacobianDotTest::testD2DiffHybrid(){
CPPUNIT_ASSERT(runTest(d2(),0));
}
void JacobianDotTest::testD6DiffHybrid(){
CPPUNIT_ASSERT(runTest(d6(),0));
}
void JacobianDotTest::testKukaDiffHybrid(){
CPPUNIT_ASSERT(runTest(KukaLWR_DHnew(),0));
}
void JacobianDotTest::testD2DiffInertial(){
CPPUNIT_ASSERT(runTest(d2(),2));
}
void JacobianDotTest::testD6DiffInertial(){
CPPUNIT_ASSERT(runTest(d6(),2));
}
void JacobianDotTest::testKukaDiffInertial(){
CPPUNIT_ASSERT(runTest(KukaLWR_DHnew(),2));
}
void JacobianDotTest::testD2DiffBodyFixed(){
CPPUNIT_ASSERT(runTest(d2(),1));
}
void JacobianDotTest::testD6DiffBodyFixed(){
CPPUNIT_ASSERT(runTest(d6(),1));
}
void JacobianDotTest::testKukaDiffBodyFixed(){
CPPUNIT_ASSERT(runTest(KukaLWR_DHnew(),1));
}
void JacobianDotTest::testD2Symbolic(){
// This test verifies if the solvers gives the same result as the symbolic Jdot (Hybrid only)
bool success=true;
bool verbose = false;
double err_d2_sym;
bool print_err = false;
double eps_sym_vs_solver = 1e-10;
for(int i=0;i<100;i++)
{
err_d2_sym = compare_d2_Jdot_Symbolic_vs_Solver(verbose);
success &= err_d2_sym<=eps_sym_vs_solver;
if(!success || print_err){
std::cout <<" err_d2_sym:"<<err_d2_sym
<<" eps_sym_vs_solver:"<<eps_sym_vs_solver<<std::endl;
if(!success)
break;
}
}
CPPUNIT_ASSERT(success);
}
| 38.012121 | 172 | 0.527583 | [
"vector"
] |
31981e6b6ddf792605ccc4073719c6ec06954cd7 | 813 | cpp | C++ | C++/n-ary-tree-postorder-traversal.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/n-ary-tree-postorder-traversal.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/n-ary-tree-postorder-traversal.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(h)
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
if (!root) {
return {};
}
vector<int> result;
vector<Node*> stack{root};
while (!stack.empty()) {
auto node = stack.back(); stack.pop_back();
result.emplace_back(node->val);
for (const auto& child : node->children) {
if (child) {
stack.emplace_back(child);
}
}
}
reverse(result.begin(), result.end());
return result;
}
};
| 20.325 | 55 | 0.474785 | [
"vector"
] |
31a0f6e8d8b8e6bd53088b5585069bbc6d2a6645 | 1,549 | cpp | C++ | mergesort.cpp | bjadamson/jobprep | d1a155e89b64ef6763fa800159fa4311eb1fc219 | [
"Unlicense"
] | null | null | null | mergesort.cpp | bjadamson/jobprep | d1a155e89b64ef6763fa800159fa4311eb1fc219 | [
"Unlicense"
] | null | null | null | mergesort.cpp | bjadamson/jobprep | d1a155e89b64ef6763fa800159fa4311eb1fc219 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
void print(int const*const a, int n)
{
int i = 0;
while(i < n){
std::cout << a[i] << ",";
i++;
}
std::cout << "\ndone\n";
}
// uses twice the space to implement
std::vector<int> merge(std::vector<int> left, std::vector<int> right) {
std::vector<int> r;
// push values onto result vector
while (!left.empty() && !right.empty()) {
auto &t = (left.front() <= right.front()) ? left : right;
r.push_back(*t.begin());
t.erase(t.begin());
}
// now handle extra elements (vectors not same size)
while (!left.empty()) {
r.push_back(left.front());
left.erase(left.begin());
}
while (!right.empty()) {
r.push_back(right.front());
right.erase(right.begin());
}
return r;
}
// 1) A list of lenth one is sorted
std::vector<int> mergesort(std::vector<int> const& list) {
// base case, length 1 means sorted
if (list.size() <= 1) {
return list;
}
// sort two halves
std::vector<int> a, b;
auto const half = list.size() / 2;
for(auto i = 0u; i < list.size(); ++i) {
auto &v = (i < half) ? a : b;
v.push_back(list[i]);
}
auto r = mergesort(a);
auto r2 = mergesort(b);
return merge(r, r2);
}
int main() {
std::vector<int> const list = {3, 4, 6, 7, 2, 45, 4, 233, 12, 33, 17};
print(list.data(), list.size());
auto const l2 = mergesort(list);
print(l2.data(), l2.size());
return 0;
}
| 23.830769 | 74 | 0.535184 | [
"vector"
] |
b3b67ca7d9f2979b517dfdf7fc389a71545f001a | 30,383 | hpp | C++ | pr2_cartesian_controllers/include/pr2_cartesian_controllers/controller_template.hpp | diogoalmeida/pr2_controller_framework | 852240638d8da439485d69fb1f627db5845c6820 | [
"MIT"
] | null | null | null | pr2_cartesian_controllers/include/pr2_cartesian_controllers/controller_template.hpp | diogoalmeida/pr2_controller_framework | 852240638d8da439485d69fb1f627db5845c6820 | [
"MIT"
] | null | null | null | pr2_cartesian_controllers/include/pr2_cartesian_controllers/controller_template.hpp | diogoalmeida/pr2_controller_framework | 852240638d8da439485d69fb1f627db5845c6820 | [
"MIT"
] | null | null | null | #ifndef __CONTROLLER_TEMPLATE__
#define __CONTROLLER_TEMPLATE__
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <boost/thread.hpp>
#include <urdf/model.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <eigen_conversions/eigen_msg.h>
#include <eigen_conversions/eigen_kdl.h>
#include <kdl_conversions/kdl_msg.h>
// #include <kdl/chainiksolvervel_wdls.hpp>
#include <kdl/chainiksolvervel_pinv_nso.hpp>
#include <kdl/chainiksolverpos_lma.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include <kdl/chainfksolvervel_recursive.hpp>
#include <kdl_parser/kdl_parser.hpp>
#include <kdl/kdl.hpp>
#include <kdl/frames.hpp>
#include <geometry_msgs/WrenchStamped.h>
#include <visualization_msgs/Marker.h>
#include <actionlib/server/simple_action_server.h>
#include <utils/TwistController.hpp>
#define NUM_ARMS 2
namespace cartesian_controllers{
/**
Defines the basic cartesian controller interface to be instantiated in the
joint controller level.
**/
class ControllerBase
{
public:
ControllerBase(){}
virtual ~ControllerBase(){}
/**
Method for computing the desired joint states given the control algorithm.
@param current_state Current joint states.
@param dt Elapsed time since last control loop.
@return Desired joint states.
**/
virtual sensor_msgs::JointState updateControl(const sensor_msgs::JointState ¤t_state, ros::Duration dt) = 0;
};
/**
Defines the interface for all the cartesian controllers, allowing for
an easier embedding in the PR2 realtime loop.
**/
template <class ActionClass, class ActionFeedback, class ActionResult>
class ControllerTemplate : public ControllerBase
{
public:
ControllerTemplate();
virtual ~ControllerTemplate()
{
}
protected:
/**
Return the last controlled joint state. If the controller does not have
an active actionlib goal, it will set the references of the joint controller
to the last desired position (and null velocity).
@param current The current joint state.
@return The last commanded joint state before the actionlib goal was
preempted or completed.
**/
sensor_msgs::JointState lastState(const sensor_msgs::JointState ¤t);
/**
Return the last controlled joint state for the joints that are not in the given arm.
If the controller does not have an active actionlib goal, it will set the references of the joint controller
to the last desired position (and null velocity). The current joint state will only be
changed for the given arm.
@param current The current joint state.
@param arm The index of the joint chain to be considered.
@return The last commanded joint state before the actionlib goal was
preempted or completed.
**/
sensor_msgs::JointState lastState(const sensor_msgs::JointState ¤t, int arm);
/**
Initialize the kinematic chain and joint arrays for an arm defined by its end-effector link.
The kinematic chain is assumed to start at chain_base_link_.
@param end_effector_link The final link of the kinematic chain.
@param chain The kinematic chain to be initialized.
@param joint_positions The joint positions array of the kinematic chain.
@param joint_velocities The joint velocities array of the kinematic chain.
@param actuated_joint_names The list of joint names of the kinematic chain.
**/
void initializeArm(std::string end_effector_link, KDL::Chain &chain, KDL::JntArray &joint_positions, KDL::JntArrayVel &joint_velocities, std::vector<std::string> &actuated_joint_names);
/**
Initialize the kinematic solvers to be used with a kinematic chain.
@param The chain for which we want to initialized the solvers.
@param fkpos Positional forward kinematics solver.
@param fkvel Velocity forward kinematics solver.
@param ikpos Positional inverse kinematics solver.
@param ikvel Velocity inverse kinematics solver.
@param jac_solver The jacobian solver.
**/
void initializeSolvers(const KDL::Chain &chain, boost::shared_ptr<KDL::ChainFkSolverPos_recursive> &fkpos, boost::shared_ptr<KDL::ChainFkSolverVel_recursive> &fkvel, boost::shared_ptr<KDL::ChainIkSolverVel_pinv_nso> &ikvel, boost::shared_ptr<KDL::ChainIkSolverPos_LMA> &ikpos, boost::shared_ptr<KDL::ChainJntToJacSolver> &jac_solver);
/**
Initializes the wrench vector, subscriber and publisher for a given wrench topic.
@param measured_wrench The eigen vector where the six-dimensional wrench is going to be stored.
@param ft_sub The ros subscriber for the sensor.
@param ft_pub The ros publisher that allows for modified measurements to be published. The ros publisher will publish in ft_topic_name/corrected.
@param ft_topic_name The ros topic where the original wrench measurements are published.
**/
void initializeWrenchComms(Eigen::Matrix<double, 6, 1> &measured_wrench, ros::Subscriber &ft_sub, ros::Publisher &ft_pub, std::string ft_topic_name);
/**
Initializes the twist controller by translating the desired gains from the given frame id to the base link.
@param comp_gains The gains in frame_id.
@param base_link The base link name.
@param frame_id The frame where the gains are expressed.
**/
void initTwistController(const std::vector<double> &comp_gains, const std::string &base_link, const std::string &frame_id);
/**
Provides access to the measured wrench in a given frame.
@param arm_index The index of the arm measuring the wrench.
@param frame The desired wrench frame.
@return The wrench in the given frame
**/
Eigen::Matrix<double, 6, 1> wrenchInFrame(int arm_index, const std::string &frame);
/**
Goal callback method to be implemented in the cartesian controllers.
**/
virtual void goalCB() = 0;
/**
Preempt callback method to be implemented in the cartesian controllers.
**/
virtual void preemptCB() = 0;
/**
Method that manages the starting of the actionlib server of each cartesian
controller.
**/
void startActionlib();
/**
Load the parameters that are common to all the cartesian controllers.
@return False if an error occurs, True otherwise.
**/
bool loadGenericParams();
/**
Method to be implemented in the cartesian controllers that loads controller
specific parameters.
**/
virtual bool loadParams() = 0;
/**
Obtains wrench measurments for a force torque sensor.
@param msg The force torque message from the sensor node.
**/
void forceTorqueCB(const geometry_msgs::WrenchStamped::ConstPtr &msg);
/**
Gets the actuated joint limits from the URDF description of the robot
for a given kinematic chain.
@param chain The kinematic chain for which the limits are going to be found.
@param min_limits The minimum position limits of the joint.
@param max_limits The maximum position limits of the joint.
**/
void getJointLimits(const KDL::Chain &chain, KDL::JntArray &min_limits, KDL::JntArray &max_limits);
/**
Check if a chain has the given joint_name.
@param chain The kinematic chain where to look for the joint.
@param joint_name The joint name we wish to check.
**/
bool hasJoint(const KDL::Chain &chain, const std::string &joint_name);
/**
Fills in the joint arrays with the state of a given kinematic chain.
The joint state might include joints outside of the kinematic chain, so there is
the need to process it.
@param current_state The robot joint state.
@param chain The target kinematic chain.
@param positions The joint positions of the kinematic chain.
@param velocities The joint velocities of the kinematic chain.
@return True if the full joint chain was found in the current state, false otherwise.
**/
bool getChainJointState(const sensor_msgs::JointState ¤t_state, const KDL::Chain &chain, KDL::JntArray &positions, KDL::JntArrayVel &velocities);
/**
Get the value for indexing the joint positions for the given joint name.
@param joint_names The vector with the available joint names.
@param name The name of the query joint.
@return the index of the queried joint in the joint names vector.
@throws logic_error if the name does not exist in the joint_names vector.
**/
int getJointIndex(const std::vector<std::string> &joint_names, const std::string &name);
/**
Fills a marker with the given initial and end point. Clears existing points.
@param initial_point Initial marker point.
@param final_point Final marker point.
@param marker The marker object.
**/
void getMarkerPoints(const Eigen::Vector3d &initial_point, const Eigen::Vector3d &final_point, visualization_msgs::Marker &marker);
/**
Convert a geometry msgs vector to an std vector.
@param in The geometry msgs vector.
@param out The converted std vector.
**/
void vectorMsgToStd(const geometry_msgs::Vector3 &in, std::vector<double> &out);
/**
Convert an std vector to a geometry msgs vector.
@param in The std vector.
@param out The converted geometry msgs vector.
**/
void vectorStdToMsg(const std::vector<double> &in, geometry_msgs::Vector3 &out);
/**
Wraps the ROS NodeHandle getParam method with an error message.
@param param_name The name of the parameter address in the parameter server.
@param var The variable where to store the parameter.
**/
bool getParam(const std::string ¶m_name, std::string &var);
bool getParam(const std::string ¶m_name, double &var);
bool getParam(const std::string ¶m_name, std::vector<double> &var);
bool getParam(const std::string ¶m_name, int &var);
bool getParam(const std::string ¶m_name, bool &var);
protected:
// Robot related
sensor_msgs::JointState robot_state;
std::vector<KDL::JntArray> joint_positions_;
std::vector<KDL::JntArrayVel> joint_velocities_;
std::vector<std::vector<std::string> > actuated_joint_names_; // list of actuated joints per arm
// KDL::ChainIkSolverVel_wdls *ikvel_;
std::vector<boost::shared_ptr<KDL::ChainIkSolverVel_pinv_nso> > ikvel_;
std::vector<boost::shared_ptr<KDL::ChainIkSolverPos_LMA> > ikpos_;
std::vector<boost::shared_ptr<KDL::ChainFkSolverPos_recursive> > fkpos_;
std::vector<boost::shared_ptr<KDL::ChainFkSolverVel_recursive> > fkvel_;
std::vector<boost::shared_ptr<KDL::ChainJntToJacSolver> > jac_solver_;
std::vector<KDL::Chain> chain_;
urdf::Model model_;
std::vector<std::string> end_effector_link_;
std::vector<std::string> ft_topic_name_;
std::vector<std::string> ft_frame_id_;
std::vector<std::string> ft_sensor_frame_;
std::string base_link_, chain_base_link_;
double eps_; // ikSolverVel epsilon
double alpha_; // ikSolverVel alpha
int maxiter_; // ikSolverVel maxiter
double nso_weights_;
double feedback_hz_;
bool has_state_;
sensor_msgs::JointState last_state_;
//Actionlib
boost::shared_ptr<actionlib::SimpleActionServer<ActionClass> > action_server_;
ActionFeedback feedback_;
ActionResult result_;
std::string action_name_;
boost::thread feedback_thread_;
boost::mutex reference_mutex_;
// ROS
ros::NodeHandle nh_;
std::vector<ros::Subscriber> ft_sub_;
std::vector<ros::Publisher> ft_pub_;
tf::TransformListener listener_;
std::vector<Eigen::Matrix<double, 6, 1> > measured_wrench_;
double force_d_;
boost::shared_ptr<TwistController> twist_controller_;
tf::TransformBroadcaster broadcaster_;
};
// Implementing the template class in its header file saves some headaches
// later on: http://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor
template <class ActionClass, class ActionFeedback, class ActionResult>
ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::ControllerTemplate() :
joint_positions_(NUM_ARMS),
joint_velocities_(NUM_ARMS),
ikvel_(NUM_ARMS),
ikpos_(NUM_ARMS),
fkpos_(NUM_ARMS),
fkvel_(NUM_ARMS),
jac_solver_(NUM_ARMS),
chain_(NUM_ARMS),
end_effector_link_(NUM_ARMS),
ft_topic_name_(NUM_ARMS),
ft_frame_id_(NUM_ARMS),
ft_sensor_frame_(NUM_ARMS),
ft_sub_(NUM_ARMS),
ft_pub_(NUM_ARMS),
actuated_joint_names_(NUM_ARMS),
measured_wrench_(NUM_ARMS)
{
nh_ = ros::NodeHandle("~");
if(!loadGenericParams())
{
ros::shutdown();
exit(0);
}
for (int i = 0; i < NUM_ARMS; i++)
{
initializeArm(end_effector_link_[i], chain_[i], joint_positions_[i], joint_velocities_[i], actuated_joint_names_[i]);
initializeSolvers(chain_[i], fkpos_[i], fkvel_[i], ikvel_[i], ikpos_[i], jac_solver_[i]);
initializeWrenchComms(measured_wrench_[i], ft_sub_[i], ft_pub_[i], ft_topic_name_[i]);
}
has_state_ = false;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::initializeArm(std::string end_effector_link, KDL::Chain &chain, KDL::JntArray &joint_positions, KDL::JntArrayVel &joint_velocities, std::vector<std::string> &actuated_joint_names)
{
KDL::Tree tree;
KDL::Joint kdl_joint;
kdl_parser::treeFromUrdfModel(model_, tree); // convert URDF description of the robot into a KDL tree
tree.getChain(chain_base_link_, end_effector_link, chain);
joint_positions.resize(chain.getNrOfJoints());
joint_velocities.q.resize(chain.getNrOfJoints());
joint_velocities.qdot.resize(chain.getNrOfJoints());
for (unsigned int i = 0; i < chain.getNrOfSegments(); i++)
{
kdl_joint = chain.getSegment(i).getJoint();
if (kdl_joint.getTypeName() == "None")
{
continue;
}
actuated_joint_names.push_back(kdl_joint.getName());
}
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::initializeSolvers(const KDL::Chain &chain, boost::shared_ptr<KDL::ChainFkSolverPos_recursive> &fkpos, boost::shared_ptr<KDL::ChainFkSolverVel_recursive> &fkvel, boost::shared_ptr<KDL::ChainIkSolverVel_pinv_nso> &ikvel, boost::shared_ptr<KDL::ChainIkSolverPos_LMA> &ikpos, boost::shared_ptr<KDL::ChainJntToJacSolver> &jac_solver)
{
KDL::JntArray min_limits, max_limits;
KDL::JntArray optimal_values, weights;
getJointLimits(chain, min_limits, max_limits);
ROS_DEBUG("Min limits rows: %d, min limits columns: %d", min_limits.rows(), min_limits.columns());
optimal_values.resize(chain.getNrOfJoints());
weights.resize(chain.getNrOfJoints());
ROS_DEBUG("Joint limits: ");
for (unsigned int i = 0; i < chain.getNrOfJoints(); i++) // define the optimal joint values as the one that's as far away from joint limits as possible
{
optimal_values(i) = (min_limits(i) + max_limits(i))/2;
ROS_DEBUG("Joint: %d, min_limit: %.2f, max_limit: %.2f, optimal_value: %.2f", i, min_limits(i), max_limits(i), optimal_values(i));
if (min_limits(i) == max_limits(i)) // Do not weight in joints with no limits in the nullspace optimization method
{
weights(i) = 0;
}
else
{
weights(i) = nso_weights_;
}
ROS_DEBUG("Weight: %.2f\n\n", weights(i));
}
fkpos.reset(new KDL::ChainFkSolverPos_recursive(chain));
fkvel.reset(new KDL::ChainFkSolverVel_recursive(chain));
// ikvel = new KDL::ChainIkSolverVel_wdls(chain, eps_);
// ikvel = new KDL::ChainIkSolverVel_pinv_nso(chain, eps_);
ikvel.reset(new KDL::ChainIkSolverVel_pinv_nso(chain, optimal_values, weights, eps_, maxiter_, alpha_));
ikpos.reset(new KDL::ChainIkSolverPos_LMA(chain));
jac_solver.reset(new KDL::ChainJntToJacSolver(chain));
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getJointLimits(const KDL::Chain &chain, KDL::JntArray &min_limits, KDL::JntArray &max_limits)
{
KDL::Joint kdl_joint;
boost::shared_ptr<const urdf::Joint> urdf_joint;
int j = 0;
min_limits.resize(chain.getNrOfJoints());
max_limits.resize(chain.getNrOfJoints());
for (unsigned int i = 0; i < chain.getNrOfSegments(); i++) // get joint limits
{
kdl_joint = chain.getSegment(i).getJoint();
if (kdl_joint.getTypeName() == "None")
{
continue;
}
urdf_joint = model_.getJoint(kdl_joint.getName());
min_limits(j) = urdf_joint->limits->lower;
max_limits(j) = urdf_joint->limits->upper;
j++;
}
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getChainJointState(const sensor_msgs::JointState ¤t_state, const KDL::Chain &chain, KDL::JntArray &positions, KDL::JntArrayVel &velocities)
{
unsigned int processed_joints = 0;
for (unsigned long i = 0; i < current_state.name.size(); i++)
{
if (hasJoint(chain, current_state.name[i]))
{
positions(processed_joints) = current_state.position[i];
velocities.q(processed_joints) = current_state.position[i];
velocities.qdot(processed_joints) = current_state.velocity[i];
processed_joints++;
}
}
if (processed_joints != chain.getNrOfJoints())
{
ROS_ERROR("Failed to acquire chain joint state");
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::initializeWrenchComms(Eigen::Matrix<double, 6, 1> &measured_wrench, ros::Subscriber &ft_sub, ros::Publisher &ft_pub, std::string ft_topic_name)
{
// Subscribe to force and torque measurements
measured_wrench << 0, 0, 0, 0, 0, 0;
ft_sub = nh_.subscribe(ft_topic_name, 1, &ControllerTemplate::forceTorqueCB, this); // we will pass the topic name to the subscriber to allow the proper wrench vector to be filled.
ft_pub = nh_.advertise<geometry_msgs::WrenchStamped>(ft_topic_name + "/converted", 1);
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::initTwistController(const std::vector<double> &comp_gains, const std::string &base_link, const std::string &frame_id)
{
std::vector<double> linear_gains(3), ang_gains(3);
for (int i = 0; i < 3; i++)
{
linear_gains[i] = comp_gains[i];
ang_gains[i] = comp_gains[i + 3];
}
geometry_msgs::Vector3Stamped lin_gains_msg, ang_gains_msg;
vectorStdToMsg(linear_gains, lin_gains_msg.vector);
vectorStdToMsg(ang_gains, ang_gains_msg.vector);
lin_gains_msg.header.frame_id = frame_id;
// ang_gains_msg.header.frame_id = ft_frame_id_[surface_arm_];
try
{
lin_gains_msg.header.stamp = ros::Time(0);
ang_gains_msg.header.stamp = ros::Time(0);
listener_.transformVector(base_link, lin_gains_msg, lin_gains_msg);
vectorMsgToStd(lin_gains_msg.vector, linear_gains);
Eigen::Matrix<double, 6, 1> gains;
for (int i = 0; i < 3; i++)
{
gains[i] = linear_gains[i];
gains[i + 3] = ang_gains[i];
}
twist_controller_.reset(new TwistController(gains));
}
catch (tf::TransformException ex)
{
ROS_ERROR("TF exception in %s: %s", action_name_.c_str(), ex.what());
action_server_->setAborted();
return;
}
}
template <class ActionClass, class ActionFeedback, class ActionResult>
sensor_msgs::JointState ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::lastState(const sensor_msgs::JointState ¤t, int arm)
{
sensor_msgs::JointState temp_state;
temp_state = last_state_;
for (unsigned long j = 0; j < temp_state.velocity.size(); j++)
{
if (hasJoint(chain_[arm], temp_state.name[j]))
{
temp_state.position[j] = current.position[j];
temp_state.velocity[j] = current.velocity[j];
}
}
return temp_state;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
sensor_msgs::JointState ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::lastState(const sensor_msgs::JointState ¤t)
{
if(!has_state_)
{
last_state_ = current;
for (unsigned long i = 0; i < last_state_.velocity.size(); i++)
{
last_state_.velocity[i] = 0.0;
}
has_state_ = true;
}
return last_state_;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::forceTorqueCB(const geometry_msgs::WrenchStamped::ConstPtr &msg)
{
KDL::Wrench wrench_kdl;
KDL::Frame sensor_to_grasp_frame_kdl, sensor_frame_kdl, desired_kdl;
geometry_msgs::PoseStamped sensor_to_grasp_frame, sensor_frame, desired;
geometry_msgs::WrenchStamped converted_wrench;
tf::Transform converted_wrench_frame;
int sensor_num = -1;
boost::lock_guard<boost::mutex> guard(reference_mutex_);
tf::wrenchMsgToKDL(msg->wrench, wrench_kdl);
for (int i = 0; i < NUM_ARMS; i++)
{
if (msg->header.frame_id == ft_sensor_frame_[i])
{
sensor_num = i;
break;
}
}
if (sensor_num == -1)
{
ROS_ERROR("Got wrench message from sensor %s, which was not defined in the config file.", msg->header.frame_id.c_str());
return;
}
converted_wrench = *msg;
sensor_to_grasp_frame.header.frame_id = msg->header.frame_id;
sensor_to_grasp_frame.header.stamp = ros::Time(0); // To enable transform with the latest ft data available
sensor_to_grasp_frame.pose.position.x = 0;
sensor_to_grasp_frame.pose.position.y = 0;
sensor_to_grasp_frame.pose.position.z = 0;
sensor_to_grasp_frame.pose.orientation.x = 0;
sensor_to_grasp_frame.pose.orientation.y = 0;
sensor_to_grasp_frame.pose.orientation.z = 0;
sensor_to_grasp_frame.pose.orientation.w = 1;
converted_wrench.header.frame_id = ft_frame_id_[sensor_num];
try
{
// obtain a vector from the wrench frame id to the desired ft frame
listener_.transformPose(ft_frame_id_[sensor_num], sensor_to_grasp_frame, sensor_to_grasp_frame);
// listener_.transformPose(base_link_, sensor_frame, sensor_frame);
}
catch (tf::TransformException ex)
{
ROS_ERROR("TF exception in %s: %s", action_name_.c_str(), ex.what());
}
tf::poseMsgToKDL(sensor_to_grasp_frame.pose, sensor_to_grasp_frame_kdl);
wrench_kdl = sensor_to_grasp_frame_kdl*wrench_kdl;
tf::wrenchKDLToMsg(wrench_kdl, converted_wrench.wrench);
tf::wrenchKDLToEigen(wrench_kdl, measured_wrench_[sensor_num]);
ft_pub_[sensor_num].publish(converted_wrench);
// HACK: PR2 had a broken force torque sensor. To allow dual-arm operations to
// work smoothly, I'm doing this =x
measured_wrench_[0] = measured_wrench_[sensor_num];
measured_wrench_[1] = measured_wrench_[sensor_num];
}
template <class ActionClass, class ActionFeedback, class ActionResult>
Eigen::Matrix<double, 6, 1> ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::wrenchInFrame(int arm_index, const std::string &frame)
{
KDL::Wrench wrench_kdl;
geometry_msgs::PoseStamped sensor_to_desired_frame, desired_frame_to_base;
KDL::Frame sensor_to_desired_frame_kdl, desired_frame_to_base_kdl;
Eigen::Matrix<double, 6, 1> converted_wrench;
// HACK: Always use arm 0, as arm 1 has a broken sensor
tf::wrenchEigenToKDL(measured_wrench_[0], wrench_kdl);
sensor_to_desired_frame.header.frame_id = ft_frame_id_[0];
sensor_to_desired_frame.header.stamp = ros::Time(0);
sensor_to_desired_frame.pose.position.x = 0;
sensor_to_desired_frame.pose.position.y = 0;
sensor_to_desired_frame.pose.position.z = 0;
sensor_to_desired_frame.pose.orientation.x = 0;
sensor_to_desired_frame.pose.orientation.y = 0;
sensor_to_desired_frame.pose.orientation.z = 0;
sensor_to_desired_frame.pose.orientation.w = 1;
desired_frame_to_base = sensor_to_desired_frame;
desired_frame_to_base.header.frame_id = frame;
try
{
// obtain a vector from the wrench frame id to the desired ft frame
listener_.transformPose(frame, sensor_to_desired_frame, sensor_to_desired_frame);
listener_.transformPose(base_link_, desired_frame_to_base, desired_frame_to_base);
}
catch (tf::TransformException ex)
{
ROS_ERROR("TF exception in %s: %s", action_name_.c_str(), ex.what());
}
tf::poseMsgToKDL(sensor_to_desired_frame.pose, sensor_to_desired_frame_kdl);
tf::poseMsgToKDL(desired_frame_to_base.pose, desired_frame_to_base_kdl);
wrench_kdl = sensor_to_desired_frame_kdl*wrench_kdl;
// wrench_kdl = desired_frame_to_base_kdl.M*(sensor_to_desired_frame_kdl*wrench_kdl);
tf::wrenchKDLToEigen(wrench_kdl, converted_wrench);
return converted_wrench;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::startActionlib()
{
// Initialize actionlib server
action_server_ = boost::shared_ptr<actionlib::SimpleActionServer<ActionClass> >(new actionlib::SimpleActionServer<ActionClass>(nh_, action_name_, false));
// Register callbacks
action_server_->registerGoalCallback(boost::bind(&ControllerTemplate::goalCB, this));
action_server_->registerPreemptCallback(boost::bind(&ControllerTemplate::preemptCB, this));
action_server_->start();
ROS_INFO("%s initialized successfully!", action_name_.c_str());
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::hasJoint(const KDL::Chain &chain, const std::string &joint_name)
{
for (unsigned int i = 0; i < chain.getNrOfSegments(); i++)
{
if(chain.segments[i].getJoint().getName() == joint_name)
{
return true;
}
}
return false;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
int ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getJointIndex(const std::vector<std::string> &joint_names, const std::string &name)
{
for (unsigned long i = 0; i < joint_names.size(); i++)
{
if (joint_names[i] == name)
{
return i;
}
}
throw std::logic_error("getJointIndex: Tried to query a joint name that is not present in the joint names vector.");
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getMarkerPoints(const Eigen::Vector3d &initial_point, const Eigen::Vector3d &final_point, visualization_msgs::Marker &marker)
{
geometry_msgs::Point point;
marker.points.clear();
tf::pointEigenToMsg(initial_point, point);
marker.points.push_back(point);
tf::pointEigenToMsg(final_point, point);
marker.points.push_back(point);
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::vectorMsgToStd(const geometry_msgs::Vector3 &in, std::vector<double> &out)
{
if (out.size() != 3)
{
throw std::logic_error("vectorMsgToStd: out must be dimension 3");
}
out[0] = in.x;
out[1] = in.y;
out[2] = in.z;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
void ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::vectorStdToMsg(const std::vector<double> &in, geometry_msgs::Vector3 &out)
{
if (in.size() != 3)
{
throw std::logic_error("vectorStdToMsg: in must be dimension 3");
}
out.x = in[0];
out.y = in[1];
out.z = in[2];
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getParam(const std::string ¶m_name, std::string &var)
{
if (!nh_.getParam(param_name, var))
{
ROS_ERROR("Missing ROS parameter %s!", param_name.c_str());
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getParam(const std::string ¶m_name, double &var)
{
if (!nh_.getParam(param_name, var))
{
ROS_ERROR("Missing ROS parameter %s!", param_name.c_str());
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getParam(const std::string ¶m_name, std::vector<double> &var)
{
if (!nh_.getParam(param_name, var))
{
ROS_ERROR("Missing ROS parameter %s!", param_name.c_str());
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getParam(const std::string ¶m_name, int &var)
{
if (!nh_.getParam(param_name, var))
{
ROS_ERROR("Missing ROS parameter %s!", param_name.c_str());
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::getParam(const std::string ¶m_name, bool &var)
{
if (!nh_.getParam(param_name, var))
{
ROS_ERROR("Missing ROS parameter %s!", param_name.c_str());
return false;
}
return true;
}
template <class ActionClass, class ActionFeedback, class ActionResult>
bool ControllerTemplate<ActionClass, ActionFeedback, ActionResult>::loadGenericParams()
{
for (int i = 0; i < NUM_ARMS; i++)
{
if(!getParam("/common/end_effector_link_name/arm_" + std::to_string(i + 1), end_effector_link_[i]))
{
return false;
}
if (!getParam("/common/force_torque_frame/arm_" + std::to_string(i + 1), ft_frame_id_[i])) // this is the frame where we want to transform the force/torque data
{
return false;
}
if (!getParam("/common/force_torque_sensor_frame/arm_" + std::to_string(i + 1), ft_sensor_frame_[i]))
{
return false;
}
if (!getParam("/common/force_torque_topic/arm_" + std::to_string(i + 1), ft_topic_name_[i]))
{
return false;
}
}
if (!getParam("/common/base_link_name", base_link_))
{
return false;
}
if (!getParam("/common/chain_base_link_name", chain_base_link_))
{
return false;
}
if (!getParam("/common/solver/epsilon", eps_))
{
return false;
}
if (!getParam("/common/solver/alpha", alpha_))
{
return false;
}
if (!getParam("/common/solver/maxiter", maxiter_))
{
return false;
}
if (!getParam("/common/solver/nso_weights", nso_weights_))
{
return false;
}
if (!getParam("/common/feedback_rate", feedback_hz_))
{
return false;
}
if(!model_.initParam("/robot_description")){
ROS_ERROR("ERROR getting robot description (/robot_description)");
return false;
}
return true;
}
}
#endif
| 35.370198 | 396 | 0.738768 | [
"geometry",
"object",
"vector",
"model",
"transform"
] |
b3b752a718215f4bdcab343556f9c9fbf6923b81 | 9,312 | cpp | C++ | objects.cpp | finley03/glTests | 18baf0572ef876cd70b35fda7de61dffa423c319 | [
"MIT"
] | null | null | null | objects.cpp | finley03/glTests | 18baf0572ef876cd70b35fda7de61dffa423c319 | [
"MIT"
] | null | null | null | objects.cpp | finley03/glTests | 18baf0572ef876cd70b35fda7de61dffa423c319 | [
"MIT"
] | null | null | null | //#define _CRTDBG_MAP_ALLOC
#include <glad/glad.h>
#include <iostream>
#include <vector>
#include <chrono>
#include <ctime>
#include <ratio>
#include <iomanip>
#include "terminalColors.h""
#include "objects.h"
#include "obj.h"
Objects::Objects() {
glGenVertexArrays(1, &VAO); // generate vertex array object
glBindVertexArray(VAO); // bind vertex array
// the program is currently only capable of working with
// one vertex array object
//int textureUnits;
//glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &textureUnits);
//std::cout << "Max " << textureUnits << " texture units" << std::endl;
//shaderProgram = shaderProgram;
}
int Objects::createFromFile(std::string filePath, std::string name) {
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::cout << std::endl;
Data object; // create object struct
object.name = name;
glGenBuffers(1, &object.VBO); // generate VBO, store ID in variable in struct
std::vector<float> mesh;
int meshSuccess;
mesh = genMeshFromFile(filePath, meshSuccess, object.size);
if (!meshSuccess) std::cout << color::error << "Mesh for \"" << name << "\" could not be generated" << color::std << std::endl;
std::vector<OBJmaterial> matData = getMatData(filePath, meshSuccess); // get material data
for (int i = 0; i < matData.size(); ++i) {
Material mat;
mat.ambient[0] = matData[i].ambient[0];
mat.ambient[1] = matData[i].ambient[1];
mat.ambient[2] = matData[i].ambient[2];
mat.diffuse[0] = matData[i].diffuse[0];
mat.diffuse[1] = matData[i].diffuse[1];
mat.diffuse[2] = matData[i].diffuse[2];
mat.specular[0] = matData[i].specular[0];
mat.specular[1] = matData[i].specular[1];
mat.specular[2] = matData[i].specular[2];
mat.smoothness = matData[i].smoothness;
mat.texture = matData[i].texture;
//object.texture = matData[i].texture;
//std::cout << "Texture?" << matData[i].texture << std::endl;
if (!matData[i].ambientFile.empty()) {
textures->newTexture(matData[i].ambientFile.c_str(), matData[i].ambientFile, 0, GL_REPEAT, GL_NEAREST);
mat.ambientTextureName = matData[i].ambientFile;
}
if (!matData[i].diffuseFile.empty()) {
textures->newTexture(matData[i].diffuseFile.c_str(), matData[i].diffuseFile, 0, GL_REPEAT, GL_NEAREST);
//std::cout << "Texture " << matData[i].diffuseFile.c_str() << std::endl;
mat.diffuseTextureName = matData[i].diffuseFile;
//std::cout << "Creating texture " << matData[i].diffuseFile << std::endl;
}
if (!matData[i].specularFile.empty()) {
textures->newTexture(matData[i].specularFile.c_str(), matData[i].specularFile, 1, GL_REPEAT, GL_NEAREST);
mat.specularTextureName = matData[i].specularFile;
//std::cout << "Creating texture " << matData[i].specularFile << std::endl;
}
object.materials.push_back(mat);
}
std::cout << "Getting material indexes for " << color::file << "\"" << filePath << "\"" << color::std << std::endl;
object.index = getMatIndexes(filePath, meshSuccess); // get material indexes
std::cout << color::process << "Buffering data" << color::std << std::endl;
glBindBuffer(GL_ARRAY_BUFFER, object.VBO); // bind VBO
glBufferData(GL_ARRAY_BUFFER, mesh.size() * sizeof(float), &mesh[0], GL_STATIC_DRAW); // Buffer mesh in VBO
shapeMap[name] = shapes.size(); // add object to shape map
shapes.push_back(object); // add object to shapes struct
// clean up memory
mesh.clear();
mesh.shrink_to_fit();
std::cout << color::success << "Finished loading file " << color::file << "\"" << filePath << "\"" << color::std << std::endl;
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> time_span = std::chrono::duration_cast<std::chrono::duration<float>>(t2 - t1);
std::cout << "Time: " << color::value << std::fixed << std::setprecision(4) << time_span.count() << " seconds" << color::std << std::endl;
return true;
}
void Objects::draw(std::string name) {
//glBindBuffer(GL_ARRAY_BUFFER, shapes[shapeMap[name]].VBO); // bind vbo of shape
//glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // vertex attribute pointer
//glEnableVertexAttribArray(0);
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); // vertex normal attribute pointer
//glEnableVertexAttribArray(1);
//glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); // texture attribute pointer
//glEnableVertexAttribArray(2);
//int totalVertices = 0;
for (int i = 0; i < shapes[shapeMap[name]].index.size(); i += 2) { // there are two indexes for each material, [startIndex, materialIndex]
int startVertex = shapes[shapeMap[name]].index[i] * 3; // indexes are for triangles, start index must be in vertexes
int nrVertexes;
if (i + 2 >= shapes[shapeMap[name]].index.size()) { // check if i is out of bounds
nrVertexes = shapes[shapeMap[name]].size - shapes[shapeMap[name]].index[i] * 3;
}
else {
nrVertexes = shapes[shapeMap[name]].index[i + 2] * 3 - shapes[shapeMap[name]].index[i] * 3;
}
// set uniforms
if (!shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].texture) {
objectShader->use();
glBindBuffer(GL_ARRAY_BUFFER, shapes[shapeMap[name]].VBO); // bind vbo of shape
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // vertex attribute pointer
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); // vertex normal attribute pointer
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); // texture attribute pointer
glEnableVertexAttribArray(2);
objectShader->vec3("material.ambient", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].ambient);
objectShader->vec3("material.diffuse", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].diffuse);
objectShader->vec3("material.specular", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].specular);
objectShader->setFloat("material.smoothness", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].smoothness);
//objectShader->setFloat("light.a", 0.1f);
}
else {
//std::cout << "a";
textureShader->use();
glBindBuffer(GL_ARRAY_BUFFER, shapes[shapeMap[name]].VBO); // bind vbo of shape
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // vertex attribute pointer
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); // vertex normal attribute pointer
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); // texture attribute pointer
glEnableVertexAttribArray(2);
textures->bind(shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].diffuseTextureName.c_str(), 0);
////std::cout << "TexName " << shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].diffuseTextureName.c_str() << std::endl;
textures->bind(shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].specularTextureName.c_str(), 1);
//textures->bind("assets/container2.png", 0);
textureShader->vec3("material.ambient", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].ambient);
textureShader->vec3("material.diffuse", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].diffuse);
textureShader->vec3("material.specular", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].specular);
textureShader->setFloat("material.smoothness", shapes[shapeMap[name]].materials[shapes[shapeMap[name]].index[i + 1]].smoothness);
textureShader->setInt("material.diffusetex", 0);
textureShader->setInt("material.speculartex", 1);
}
glDrawArrays(GL_TRIANGLES, startVertex, nrVertexes);
//totalVertices += nrVertexes;
}
/*glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);*/
//glDrawArrays(GL_TRIANGLES, 0, shapes[shapeMap[name]].size); // 36
}
void Objects::drawLight(std::string name) {
glBindBuffer(GL_ARRAY_BUFFER, shapes[shapeMap[name]].VBO); // bind vbo of shape
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // vertex attribute pointer
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); // vertex normal attribute pointer
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); // texture attribute pointer
glEnableVertexAttribArray(2);
glDrawArrays(GL_TRIANGLES, 0, shapes[shapeMap[name]].size); // 36
}
void Objects::destroy(std::string name) {
glDeleteBuffers(1, &shapes[shapeMap[name]].VBO);
}
void Objects::terminate() {
glDeleteBuffers(1, &VAO);
}
| 39.291139 | 145 | 0.679553 | [
"mesh",
"object",
"shape",
"vector"
] |
b3bb86875d8698048cc9d5a82ec0a0061630e277 | 6,440 | cpp | C++ | tiny.cpp | chisaipete/gamedev | 437684e858d24891ecd982001fed461631487b4d | [
"MIT"
] | null | null | null | tiny.cpp | chisaipete/gamedev | 437684e858d24891ecd982001fed461631487b4d | [
"MIT"
] | null | null | null | tiny.cpp | chisaipete/gamedev | 437684e858d24891ecd982001fed461631487b4d | [
"MIT"
] | null | null | null | #include "tiny.h"
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
Timer fps_timer;
std::stringstream fpsText;
Texture t_fps;
RawTexture image;
Model* model = NULL;
const int SCREEN_WIDTH = 200;
const int SCREEN_HEIGHT = 200;
bool init() {
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO) != 0){
logSDLError(std::cout, "SDL_Init");
success = false;
} else {
if (TTF_Init() != 0){ //Future: do we need to call IMG_Init, it seems to work without it...is speed a factor? IMG_GetError might be needed
logSDLError(std::cout, "TTF_Init");
success = false;
} else {
window = SDL_CreateWindow("Tiny Renderer", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
// window = SDL_CreateWindow("Leaper", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, LEVEL_WIDTH, LEVEL_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr){
logSDLError(std::cout, "SDL_CreateWindow");
success = false;
} else {
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
logSDLError(std::cout, "SDL_CreateRenderer");
success = false;
}
}
}
}
return success;
}
bool load() {
bool success = true;
font = TTF_OpenFont("res/cc.ttf", 12);
if (font == nullptr){
logSDLError(std::cout, "TTF_OpenFont");
success = false;
}
// model = new Model("res/african_head.obj");
if (!t_fps.load_from_rendered_text("_", RED)) {
success = false;
}
if (!image.initialize(SCREEN_WIDTH, SCREEN_HEIGHT)) {
success = false;
}
return success;
}
bool close() {
t_fps.free();
image.free();
if (model != nullptr) { delete model; }
if (font != nullptr) { TTF_CloseFont(font); font = NULL; }
if (renderer != nullptr) { SDL_DestroyRenderer(renderer); renderer = NULL; }
if (window != nullptr) { SDL_DestroyWindow(window); window = NULL; }
TTF_Quit();
SDL_Quit();
return true;
}
void line(int x0, int y0, int x1, int y1, RawTexture &i, SDL_Color c) {
// TODO: Why does this work?
bool steep = false;
if (std::abs(x0-x1) < std::abs(y0-y1)) { //if the line is steep, transpose
std::swap(x0, y0);
std::swap(x1, y1);
steep = true;
}
if (x0>x1) { //make it left to right
std::swap(x0, x1);
std::swap(y0, y1);
}
int dx = x1-x0;
int dy = y1-y0;
int derror2 = std::abs(dy)*2;
int error2 = 0;
int y = y0;
for (int x = x0; x <= x1; x++) {
if (steep) {
i.set(y, x, c); //if transposed, de-transpose
} else {
i.set(x, y, c);
}
error2 += derror2;
if (error2 > dx) {
y += (y1 > y0 ? 1 : -1);
error2 -= dx*2;
}
}
}
void line(v2i p0, v2i p1, RawTexture &i, SDL_Color c) {
line(p0.u, p0.v, p1.u, p1.v, i, c);
}
void triangle(v2i p0, v2i p1, v2i p2, RawTexture &i, SDL_Color c) {
line(p0, p1, image, c);
line(p1, p2, image, c);
line(p2, p0, image, c);
}
void render() {
image.lock_texture();
// pixel
// image.set(52, 41, RED);
// line
// line(13, 20, 80, 40, image, WHITE);
// line(20, 13, 40, 80, image, RED);
// line(80, 40, 13, 20, image, RED);
// wireframe
// for (int i = 0; i < model->num_faces(); i++) {
// std::vector<int> face = model->face(i);
// for (int j = 0; j < 3; j++) {
// v3f v0 = model->vertex(face[j]);
// v3f v1 = model->vertex(face[(j+1)%3]);
// int x0 = (v0.x+1.)*SCREEN_WIDTH/2.0;
// int y0 = (v0.y+1.)*SCREEN_HEIGHT/2.0;
// int x1 = (v1.x+1.)*SCREEN_WIDTH/2.0;
// int y1 = (v1.y+1.)*SCREEN_HEIGHT/2.0;
// line(x0, y0, x1, y1, image, WHITE);
// }
// }
// triangles
v2i t0[3] = {v2i(10, 70), v2i(50, 160), v2i(70, 80)};
v2i t1[3] = {v2i(180, 50), v2i(150, 1), v2i(70, 180)};
v2i t2[3] = {v2i(180, 150), v2i(120, 160), v2i(130, 180)};
triangle(t0[0], t0[1], t0[2], image, RED);
triangle(t1[0], t1[1], t1[2], image, WHITE);
triangle(t2[0], t2[1], t2[2], image, GREEN);
image.unlock_texture();
}
int main(int argc, char **argv) {
if (!init()) {
std::cout << "Initialization Failed" << std::endl;
} else {
if (!load()) {
std::cout << "Loading Failed" << std::endl;
} else {
bool quit = false;
bool fps_on = false;
int frame_count = 0;
float avgFPS = 0.0;
fps_timer.start();
while (!quit) {
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) {
quit = true;
}
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE ) {
quit = true;
}
if (event.type == SDL_KEYDOWN && event.key.repeat == 0) {
switch (event.key.keysym.sym) {
case SDLK_1:
fps_on = !fps_on;
break;
}
}
}
render();
SDL_SetRenderDrawColor(renderer, BLACK.r, BLACK.g, BLACK.b, BLACK.a); //black
SDL_RenderClear(renderer);
image.render(0, 0, nullptr, 0, nullptr, SDL_FLIP_VERTICAL);
if (fps_on) {
// calculate and render FPS
avgFPS = frame_count / (fps_timer.get_ticks() / 1000.0);
if (avgFPS > 2000000) {
avgFPS = 0;
}
fpsText.str("");
fpsText << (int)avgFPS << " fps";
t_fps.load_from_rendered_text(fpsText.str(), RED);
t_fps.render(SCREEN_WIDTH-t_fps.get_width(), 0);
}
SDL_RenderPresent(renderer);
frame_count++;
}
}
}
close();
return 0;
} | 30.666667 | 150 | 0.489441 | [
"render",
"vector",
"model"
] |
b3be3892cf2e8fcb1722d94e15ba420813a44912 | 2,513 | cpp | C++ | CodingTool/examples/search.cpp | Deadlyelder/Crypto-Tools | 6529d800dd10e291e1453fc7909bf830d62240a0 | [
"Unlicense"
] | 158 | 2017-05-14T00:03:16.000Z | 2022-03-30T07:13:49.000Z | CodingTool/examples/search.cpp | hadipourh/Tools-for-Cryptanalysis | 6a93eb92794d6176e6d6a2802a86735634107315 | [
"Unlicense"
] | 2 | 2019-10-13T12:06:54.000Z | 2020-06-24T19:39:15.000Z | CodingTool/examples/search.cpp | hadipourh/Tools-for-Cryptanalysis | 6a93eb92794d6176e6d6a2802a86735634107315 | [
"Unlicense"
] | 41 | 2017-07-04T10:00:22.000Z | 2022-03-30T07:13:50.000Z | /*!
\file search.cpp
\author Tomislav Nad, Tomislav.Nad@iaik.tugraz.at
\version 0.9
\brief Example for finding low Hamming weight words.
*/
// Copyright (c) 2010 Graz University of Technology (IAIK) <http://www.iaik.tugraz.at>
//
// This file is part of the CodingTool.
//
// The CodingTool is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CodingTool is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with CodingTool. If not, see <http://www.gnu.org/licenses/>.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "LowWeightSearch.h"
#include "InputHandler.h"
#include "types.h"
using namespace std;
/*! \example search.cpp
This is an example how to read a code matrix from
a file and applies a low Hamming weight search.
If the matrix was previously created from
the SHA1 message expansion example, the algorithm
should find the Hamming weight of 25 after few iterations.
Using the argument "-pc 1" which enables random permutaion
of the columns, results in feewer needed iterations.
\see sha1me.cpp
*/
int main(int argc, const char* argv[]) {
// create an empty generator matrix
CodeMatrix oGenerator;
// create an empty code word
CodeWord oCodeWord;
// create parameters
Parameters oParameters;
// create an input handler
InputHandler oInputHandler(oParameters);
// create the low weight search object
LowWeightSearch oLowWS;
string sCMFile = "";
// parse the command line arguments
// example: ./search -i 100 -cm matrix.cm -pc 1
if(oInputHandler.ParseSettings(argc, argv))
exit(-1);
// get the file name of the code matrix
sCMFile = oParameters.GetStringParameter(Parameters::CMFILE);
// read data from the file
oGenerator.ReadFromFile(sCMFile);
// start the search
oCodeWord = oLowWS.CanteautChabaud(oGenerator,oParameters);
// print the code word and the Hamming weight
oCodeWord.Print64();
cout << "Hamming weight is " << oCodeWord.GetHammingWeight() << endl;
exit(1);
}
| 30.277108 | 87 | 0.71548 | [
"object"
] |
b3c71bc0f3afb8930b85754e9c1a957c99bed8c2 | 1,320 | cpp | C++ | icpcarchive.ecs.baylor.edu/Sums.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | icpcarchive.ecs.baylor.edu/Sums.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | icpcarchive.ecs.baylor.edu/Sums.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4941
Name: Sums
Date: 20/02/2015
*/
#include <bits/stdc++.h>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 100005
using namespace std;
typedef long long ll;
typedef pair<int, int> ii; typedef pair<int, ii> iii;
typedef vector<int> vi; typedef vector<ii> vii;
ll n, sqr, ans, m;
int main () {
ios_base::sync_with_stdio(0);
//cout << fixed << setprecision(10);
int TC, i, j;
cin>>TC;
while (TC--) {
cin>>n;
sqr = sqrt(n * 2ll) + 10ll;
for (ans=2ll; ans <= sqr; ans++) {
m = (n / ans) - (ans / 2ll);
if (ans % 2ll == 0ll) m++;
if (m <= 0ll) {
ans = sqr + 1ll;
break;
} else if ((((m+ans-1ll) * (m+ans) / 2ll) - (m * (m - 1ll) / 2ll)) == n) break;
}
if (ans > sqr) cout<<"IMPOSSIBLE"<<endl;
else {
cout<<n<<" =";
bool first = true;
for (i=0; i<ans; i++) {
cout<<" ";
if (first) first = false;
else cout<<"+ ";
cout<<i+m;
}
cout<<endl;
}
}
return 0;
}
| 22.372881 | 122 | 0.556061 | [
"vector"
] |
b3c7540b739aa34199e1ac5b9fbe80a9067b953a | 1,441 | cpp | C++ | platform/nutekt-digital/osc_template/kick.cpp | roybossofpesto/nts1 | 492dcc8908247d7fc06a34ec9e7713b7e084eb83 | [
"BSD-3-Clause"
] | null | null | null | platform/nutekt-digital/osc_template/kick.cpp | roybossofpesto/nts1 | 492dcc8908247d7fc06a34ec9e7713b7e084eb83 | [
"BSD-3-Clause"
] | null | null | null | platform/nutekt-digital/osc_template/kick.cpp | roybossofpesto/nts1 | 492dcc8908247d7fc06a34ec9e7713b7e084eb83 | [
"BSD-3-Clause"
] | null | null | null | #include "userosc.h"
#include <array>
#include <chrono>
#include <vector>
#include <cstdlib>
#include <tuple>
using namespace std::literals::chrono_literals;
using Note = uint8_t;
struct Osc {
float phi = 0.f;
void update(const float ww);
};
void Osc::update(const float ww)
{
phi += ww;
phi -= static_cast<uint32_t>(phi);
}
struct State {
size_t index = 0;
float time = 0.f;
Osc osc0;
// Osc osc1;
};
static State state;
void OSC_INIT(uint32_t /*platform*/, uint32_t /*api*/)
{
state = State();
}
void OSC_CYCLE(
const user_osc_param_t* const params,
int32_t* yy_,
const uint32_t frames)
{
const Note in_note = (params->pitch >> 8) % 152;
const auto w0 = osc_w0f_for_note(in_note, 0);
auto yy = static_cast<q31_t*>(yy_);
auto yy_end = yy + frames;
float sig_hosho = 0.f;
for (; yy < yy_end; yy++) {
const float sig_master = osc_sinf(state.osc0.phi);
*yy = f32_to_q31(sig_master);
state.time += k_samplerate_recipf;
state.osc0.update(w0);
// state.osc1.update(w1);
}
}
void OSC_NOTEON(
const user_osc_param_t* const /*params*/)
{
state.index ++;
if (state.index >= 4) {
state = State();
}
}
void OSC_NOTEOFF(
const user_osc_param_t* const /*params*/)
{
// state.vol0 = 0.f;
}
void OSC_PARAM(uint16_t index, uint16_t value)
{
switch (index) {
case k_user_osc_param_id1:
// state.master_hosho_mbira_mix = value / 99.f;
break;
}
}
| 16.563218 | 54 | 0.646079 | [
"vector"
] |
b3c972be2f7eaced743f514fbf0efc039c525d5a | 1,371 | cpp | C++ | 126/wordLadderII.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | 1 | 2018-06-24T13:58:07.000Z | 2018-06-24T13:58:07.000Z | 126/wordLadderII.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | 126/wordLadderII.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
#include <climits>
using namespace std;
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
vector<vector<string>> res;
unordered_set<string>dict(wordList.begin(), wordList.end());
vector<string>temp{beginWord};
queue<vector<string>>paths;
paths.push(temp);
int level = 1, minLevel = INT_MAX;
unordered_set<string>words;
while(!paths.empty()){
auto t = paths.front();
paths.pop();
if(t.size() > level){
for(string w:words) dict.erase(w);
words.clear();
level = t.size();
if(level > minLevel) break;
}
string last = t.back();
for(int i = 0;i < last.size();i++){
string newLast = last;
for(char ch = 'a'; ch <= 'z';ch++){
newLast[i] = ch;
if(!dict.count(newLast)) continue;
words.insert(newLast);
vector<string>nextPath = t;
nextPath.push_back(newLast);
if (newLast == endWord) {
res.push_back(nextPath);
minLevel = level;
} else paths.push(nextPath);
}
}
}
return res;
}
int main(){
string beginWord = "hit", endWord = "cog";
vector<string>wordList = {"hot","dot","dog","lot","log","cog"};
vector<vector<string>>res = findLadders(beginWord, endWord, wordList);
for(auto a : res){
for(auto b:a)
cout<<b<<" ";
cout<<endl;
}
}
| 25.388889 | 96 | 0.639679 | [
"vector"
] |
b3ca416f5a8c2511a76c13f38e0a6cb3b17accaf | 3,386 | hh | C++ | Kaskade/utilities/factory2.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 3 | 2019-07-03T14:03:31.000Z | 2021-12-19T10:18:49.000Z | Kaskade/utilities/factory2.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 6 | 2020-02-17T12:01:30.000Z | 2021-12-09T22:02:33.000Z | Kaskade/utilities/factory2.hh | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 2 | 2020-12-03T04:41:18.000Z | 2021-01-11T21:44:42.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the library KASKADE 7 */
/* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */
/* */
/* Copyright (C) 2002-2011 Zuse Institute Berlin */
/* */
/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
/* see $KASKADE/academic.txt */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef FACTORY_2_HH
#define FACTORY_2_HH
#include <map>
#include <memory>
#include <string>
#include <boost/lexical_cast.hpp>
#include "utilities/functor.hh"
namespace Kaskade
{
/**
* \brief A pluggable factory.
*
* Allows to create objects of type AbstractProduct. The concrete object is determined by
* an identifier that is associated with a creator functor or function pointer. If the functor
* or function pointer take arguments specify their types with the variadic template parameter
* Arguments.
*
*/
template
<
class Identifier,
class AbstractProduct,
typename... Arguments
>
class Factory2
{
/// Exception for the case that an entry is not found.
class Exception : public std::exception
{
public:
explicit Exception(Identifier const& id_) : id(id_){}
const char* what()
{
std::string message("No entry with id \"");
message += boost::lexical_cast<std::string>(id);
message += "\" found in factory.\n";
return message.c_str();
}
private:
Identifier const& id;
};
public:
// Store creator in functor (creation via functor and function pointer possible)
typedef Functor<AbstractProduct*,Arguments...> ProductCreator;
private:
// Associative container
typedef std::map<Identifier,ProductCreator> Map;
public:
/// Add entry to factory.
/**
* \param id unique identifier associated with creator
* \param creator functor or function pointer realizing the creation of AbstractProduct
*
* \param false if id already exists (in this case creator is not added to the factory)
*/
bool add(Identifier const& id, ProductCreator creator)
{
return map.insert(typename Map::value_type(id,creator)).second;
}
/// Remove entry from factory.
/**
* \param id unique identifier associated with the entry to be deleted.
* \return true if entry was deleted, false if no entry corresponding to id has been found
*/
bool remove(Identifier const& id)
{
return map.erase(id)==1;
}
std::unique_ptr<AbstractProduct> create(Identifier const& id, Arguments... args)
{
typename Map::iterator i = map.find(id);
if(i != map.end()) return std::unique_ptr<AbstractProduct>(i->second(args...));
else throw Exception(id);
return std::unique_ptr<AbstractProduct>(nullptr);
}
private:
Map map;
};
} // namespace Kaskade
#endif
| 31.351852 | 96 | 0.548435 | [
"object"
] |
b3d2785bf1ede2a6f9c13baf3564bf160947e492 | 4,868 | cc | C++ | Geometry/CaloGeometry/src/IdealZPrism.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Geometry/CaloGeometry/src/IdealZPrism.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Geometry/CaloGeometry/src/IdealZPrism.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "Geometry/CaloGeometry/interface/IdealZPrism.h"
#include <cmath>
#include <memory>
typedef IdealZPrism::CCGFloat CCGFloat;
typedef IdealZPrism::Pt3D Pt3D;
typedef IdealZPrism::Pt3DVec Pt3DVec;
IdealZPrism::IdealZPrism() : CaloCellGeometry() {}
namespace {
// magic numbers determined by ParticleFlow
constexpr float EMDepthCorrection = 22.;
constexpr float HADDepthCorrection = 25.;
GlobalPoint correct(GlobalPoint const& ori, IdealZPrism::DEPTH depth) {
if (depth == IdealZPrism::None)
return ori;
float zcorr = depth == IdealZPrism::EM ? EMDepthCorrection : HADDepthCorrection;
if (ori.z() < 0)
zcorr = -zcorr;
return ori + GlobalVector(0., 0., zcorr);
}
} // namespace
IdealZPrism::IdealZPrism(const IdealZPrism& idzp) : CaloCellGeometry(idzp) {
if (idzp.forPF())
m_geoForPF = std::make_unique<IdealZPrism>(*idzp.forPF());
}
IdealZPrism& IdealZPrism::operator=(const IdealZPrism& idzp) {
if (&idzp != this) {
CaloCellGeometry::operator=(idzp);
if (idzp.forPF())
m_geoForPF = std::make_unique<IdealZPrism>(*idzp.forPF());
}
return *this;
}
IdealZPrism::IdealZPrism(const GlobalPoint& faceCenter, CornersMgr* mgr, const CCGFloat* parm, IdealZPrism::DEPTH depth)
: CaloCellGeometry(faceCenter, mgr, parm),
m_geoForPF(depth == None ? nullptr : new IdealZPrism(correct(faceCenter, depth), mgr, parm, None)) {
initSpan();
}
IdealZPrism::~IdealZPrism() {}
CCGFloat IdealZPrism::dEta() const { return param()[IdealZPrism::k_dEta]; }
CCGFloat IdealZPrism::dPhi() const { return param()[IdealZPrism::k_dPhi]; }
CCGFloat IdealZPrism::dz() const { return param()[IdealZPrism::k_dZ]; }
CCGFloat IdealZPrism::eta() const { return param()[IdealZPrism::k_Eta]; }
CCGFloat IdealZPrism::z() const { return param()[IdealZPrism::k_Z]; }
void IdealZPrism::vocalCorners(Pt3DVec& vec, const CCGFloat* pv, Pt3D& ref) const { localCorners(vec, pv, ref); }
GlobalPoint IdealZPrism::etaPhiR(float eta, float phi, float rad) {
return GlobalPoint(rad * cosf(phi) / coshf(eta), rad * sinf(phi) / coshf(eta), rad * tanhf(eta));
}
GlobalPoint IdealZPrism::etaPhiPerp(float eta, float phi, float perp) {
return GlobalPoint(perp * cosf(phi), perp * sinf(phi), perp * sinhf(eta));
}
GlobalPoint IdealZPrism::etaPhiZ(float eta, float phi, float z) {
return GlobalPoint(z * cosf(phi) / sinhf(eta), z * sinf(phi) / sinhf(eta), z);
}
void IdealZPrism::localCorners(Pt3DVec& lc, const CCGFloat* pv, Pt3D& ref) {
assert(8 == lc.size());
assert(nullptr != pv);
const CCGFloat dEta(pv[IdealZPrism::k_dEta]);
const CCGFloat dPhi(pv[IdealZPrism::k_dPhi]);
const CCGFloat dz(pv[IdealZPrism::k_dZ]);
const CCGFloat eta(pv[IdealZPrism::k_Eta]);
const CCGFloat z(pv[IdealZPrism::k_Z]);
std::vector<GlobalPoint> gc(8, GlobalPoint(0, 0, 0));
const GlobalPoint p(etaPhiZ(eta, 0, z));
const float z_near(z);
const float z_far(z * (1 - 2 * dz / p.mag()));
gc[0] = etaPhiZ(eta + dEta, +dPhi, z_near); // (+,+,near)
gc[1] = etaPhiZ(eta + dEta, -dPhi, z_near); // (+,-,near)
gc[2] = etaPhiZ(eta - dEta, -dPhi, z_near); // (-,-,near)
gc[3] = etaPhiZ(eta - dEta, +dPhi, z_near); // (-,+,far)
gc[4] = GlobalPoint(gc[0].x(), gc[0].y(), z_far); // (+,+,far)
gc[5] = GlobalPoint(gc[1].x(), gc[1].y(), z_far); // (+,-,far)
gc[6] = GlobalPoint(gc[2].x(), gc[2].y(), z_far); // (-,-,far)
gc[7] = GlobalPoint(gc[3].x(), gc[3].y(), z_far); // (-,+,far)
for (unsigned int i(0); i != 8; ++i) {
lc[i] = Pt3D(gc[i].x(), gc[i].y(), gc[i].z());
}
ref = 0.25 * (lc[0] + lc[1] + lc[2] + lc[3]);
}
void IdealZPrism::initCorners(CaloCellGeometry::CornersVec& co) {
if (co.uninitialized()) {
CornersVec& corners(co);
const GlobalPoint p(getPosition());
const CCGFloat z_near(p.z());
const CCGFloat z_far(z_near + 2 * dz() * p.z() / fabs(p.z()));
const CCGFloat eta(p.eta());
const CCGFloat phi(p.phi());
corners[0] = etaPhiZ(eta + dEta(), phi + dPhi(), z_near); // (+,+,near)
corners[1] = etaPhiZ(eta + dEta(), phi - dPhi(), z_near); // (+,-,near)
corners[2] = etaPhiZ(eta - dEta(), phi - dPhi(), z_near); // (-,-,near)
corners[3] = etaPhiZ(eta - dEta(), phi + dPhi(), z_near); // (-,+,near)
corners[4] = GlobalPoint(corners[0].x(), corners[0].y(), z_far); // (+,+,far)
corners[5] = GlobalPoint(corners[1].x(), corners[1].y(), z_far); // (+,-,far)
corners[6] = GlobalPoint(corners[2].x(), corners[2].y(), z_far); // (-,-,far)
corners[7] = GlobalPoint(corners[3].x(), corners[3].y(), z_far); // (-,+,far)
}
}
std::ostream& operator<<(std::ostream& s, const IdealZPrism& cell) {
s << "Center: " << cell.getPosition() << std::endl;
s << "dEta = " << cell.dEta() << ", dPhi = " << cell.dPhi() << ", dz = " << cell.dz() << std::endl;
return s;
}
| 37.160305 | 120 | 0.624281 | [
"geometry",
"vector"
] |
b3dee0885a23c2667d8f963570aa0a1c33d03276 | 13,899 | hpp | C++ | src/search_engine/relja_retrival/external/dkmeans_relja/dkmeans_relja/jp_nn_kdtree.hpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | null | null | null | src/search_engine/relja_retrival/external/dkmeans_relja/dkmeans_relja/jp_nn_kdtree.hpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | null | null | null | src/search_engine/relja_retrival/external/dkmeans_relja/dkmeans_relja/jp_nn_kdtree.hpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 5 | 2019-09-02T14:54:16.000Z | 2021-01-13T17:36:01.000Z | /**
* James Philbin <philbinj@gmail.com>
* Engineering Department
* University of Oxford
* Copyright (C) 2006. All rights reserved.
*
* Use and modify all you like, but do NOT redistribute. No warranty is
* expressed or implied. No liability or responsibility is assumed.
*/
/**
* Implementation of randomized kd-tree's.
*
* Example:
* jp_nn_kdtree<float> kdt(data_ptr, npoints, ndims, ntrees); - Build the trees.
* pair<size_t, float> nns[num_nns+1]; - Must be num_nns+1 big.
* kdt.search(pnt_ptr, num_nns, nns, nchecks); - Search the trees, saving the results in nns.
*/
#ifndef __JP_NN_KDTREE_HPP
#define __JP_NN_KDTREE_HPP
#include <cassert>
#include <algorithm>
#include <queue>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <vector>
#include <jp_dist2.hpp>
#include <jp_stats.hpp>
static const unsigned jp_pool_fixed_size_sz = 16384;
template<class T>
struct
jp_pool_fixed_size
{
unsigned end;
//unsigned char data[jp_pool_fixed_size_sz*sizeof(T)];
T data[jp_pool_fixed_size_sz];
jp_pool_fixed_size()
: end(0)
{ }
inline
void* get_ptr()
{
//end++;
return (void*)&data[end++];
//return (void*)&data[(end-1)*sizeof(T)];
}
};
template<class T>
struct
jp_pool
{
std::list<jp_pool_fixed_size<T>*> lst;
public:
inline
void*
allocate()
{
if (lst.begin() == lst.end() || lst.back()->end == jp_pool_fixed_size_sz ) {
lst.push_back( new jp_pool_fixed_size<T>() );
}
return (*lst.rbegin())->get_ptr();
}
void
free()
{
for (typename std::list<jp_pool_fixed_size<T>*>::iterator it = lst.begin();
it != lst.end();
++it)
{
delete *it;
}
}
size_t
size()
{
return lst.size() * jp_pool_fixed_size_sz * sizeof(T);
}
};
namespace jp_nn_kdtree_internal {
template<class Float>
class kdtree_node;
template<class Float>
class kdtree_types
{
public:
typedef Float DiscFloat; // Discriminant dimension type.
typedef Float DistFloat; // Distance type.
};
template<>
class kdtree_types<unsigned char>
{
public:
typedef float DiscFloat;
typedef uint32_t DistFloat;
};
template<class Float>
class
kdtree_node
{
typedef kdtree_node<Float> this_type;
public:
typedef typename kdtree_types<Float>::DiscFloat DiscFloat;
typedef typename kdtree_types<Float>::DistFloat DistFloat;
typedef std::priority_queue< std::pair<DiscFloat, kdtree_node<Float>*>,
std::vector< std::pair<DiscFloat, kdtree_node<Float>*> >,
std::greater< std::pair<DiscFloat, kdtree_node<Float>*> > > BPQ;
public:
//static boost::pool_allocator<this_type> allocator;
// static void
// free()
// {
// (jp_pool<this_type>::get_instance())->free();
// //boost::singleton_pool<boost::pool_allocator_tag, sizeof(this_type)>::release_memory();
// }
this_type* left_; // ==0 if this is a leaf.
//this_type* right_;
DiscFloat disc_;
unsigned disc_dim_; // I this is a leaf, disc_dim_ = ind, else discriminant dimension.
std::pair<size_t, DiscFloat>
choose_split(const Float* pnts, const size_t* inds, size_t N, size_t D)
{
// Find mean & variance.
std::vector< jp_stats_mean_var<DiscFloat> > dim_stats(D);
for (size_t n=0; n<std::min(N, (size_t)100); ++n) {
for (size_t d=0; d<D; ++d) {
dim_stats[d](pnts[inds[n]*D + d]);
}
}
// Find most variant dimension and mean.
std::vector< std::pair< DiscFloat, uint32_t> > var_dim(D); // Apparently this makes an enormous difference!!
for (size_t d=0; d<D; ++d) {
var_dim[d].first = dim_stats[d].variance();
var_dim[d].second = (uint32_t)d;
}
// Partial sort makes a BIG difference to the build time.
static const uint32_t nrand = D>5 ? 5 : D;
std::partial_sort(var_dim.begin(), var_dim.begin() + nrand, var_dim.end(), std::greater<std::pair<DiscFloat, uint32_t> >());
uint32_t randd = var_dim[(int)(drand48() * nrand)].second;
// static const uint32_t nnrand = 10;
// std::partial_sort(var_dim.begin(), var_dim.begin() + nnrand, var_dim.end(), std::greater<std::pair<DiscFloat, uint32_t> >());
// size_t nrand = 1;
// while (nrand < nnrand && nrand < D &&
// dim_stats[var_dim[nrand].second].variance()/dim_stats[var_dim[0].second].variance() > 0.90f) nrand++;
// uint32_t randd = var_dim[(int)(drand48() * nrand)].second;
return std::make_pair(randd, dim_stats[randd].mean());
}
void
split_points(const Float* pnts, size_t* inds, size_t N, size_t D, jp_pool<this_type>& pool)
{
std::pair<size_t, DiscFloat> spl = choose_split(pnts, inds, N, D);
disc_dim_ = spl.first;
disc_ = spl.second;
size_t l = 0;
size_t r = N;
while (l!=r) {
if (pnts[inds[l]*D + disc_dim_] < disc_) l++;
else {
r--;
std::swap(inds[l], inds[r]);
}
}
// If either partition is empty -> vectors identical!
if (l==0 || l==N) { l = N/2; } // The vectors are identical, so keep nlogn performance.
left_ = (this_type*)(pool.allocate());
this_type* right_ = (this_type*)(pool.allocate());
assert((right_ - left_)==1);
new (left_) this_type(pnts, inds, l, D, pool);
new (right_) this_type(pnts, &inds[l], N-l, D, pool);
}
public:
kdtree_node() : left_(0)/*, right_(0)*/ { }
kdtree_node(const Float* pnts, size_t* inds, size_t N, unsigned D, jp_pool<this_type>& pool)
: left_(0)/*, right_(0)*/
{
if (N>1) {
split_points(pnts, inds, N, D, pool);
}
else if (N==1) {
disc_dim_ = inds[0];
}
else {
assert(0);
}
}
void
search(const Float* pnt,
BPQ& pri_branch,
const unsigned numnn,
std::pair<size_t, DistFloat>* nns,
std::vector<bool>& seen,
const Float* pnts,
unsigned D,
DiscFloat mindsq,
unsigned ndists,
unsigned nchecks)
{
this_type* cur = this;
this_type* follow = 0;
this_type* other = 0;
while (cur->left_) {
DiscFloat diff = pnt[cur->disc_dim_] - cur->disc_;
if (diff < 0) {
follow = cur->left_;
//other = cur->right_;
other = cur->left_+1;
}
else {
//follow = cur->right_;
follow = cur->left_+1;
other = cur->left_;
}
pri_branch.push(std::make_pair(mindsq + diff*diff, other)); // 36 %
cur = follow;
}
if (seen[cur->disc_dim_]) return;
seen[cur->disc_dim_] = true;
DistFloat dsq = jp_dist_l2(pnt, &pnts[cur->disc_dim_*D], D); // 31%
if (dsq > nns[numnn-1].second) return;
unsigned i;
for (i = numnn; i>0 && nns[i-1].second > dsq; --i) {
nns[i] = nns[i-1];
}
nns[i] = std::make_pair(cur->disc_dim_, dsq);
}
};
}
template<class Float>
class
jp_nn_kdtree
{
typedef jp_nn_kdtree_internal::kdtree_node<Float> node_type;
typedef typename node_type::DiscFloat DiscFloat;
typedef typename node_type::DistFloat DistFloat;
typedef typename node_type::BPQ BPQ;
std::vector< node_type* > trees_;
size_t N_;
unsigned D_;
const Float* pnts_;
jp_pool<node_type> pool;
public:
jp_nn_kdtree(const Float* pnts, size_t N, unsigned D, unsigned ntrees = 8, unsigned seed=42)
: N_(N), D_(D), pnts_(pnts)
{
srand(seed);
srand48(seed);
// Create inds.
std::vector<size_t> inds(N);
for (size_t n=0; n<N; ++n) inds[n] = n;
// Need to randomize the inds for the sampled mean and variance.
std::random_shuffle(inds.begin(), inds.end());
// Create trees.
for (unsigned t=0; t<ntrees; ++t) {
//node_type* n = (node_type*)(pool.allocate());
//new (n) node_type(pnts, &inds[0], N, D, pool);
trees_.push_back(new node_type(pnts, &inds[0], N, D, pool));
}
}
void
cache_fix()
{
// Crawl the leaves in order and record the order of the indices.
// Then, shuffle the point data such that the points are contiguous.
// Then, crawl back over the leaves and fix the indices.
// We only do this for the first tree, but need to fix the rest.
Float* pnts = const_cast<Float*>(pnts_); // Should only do this if we own pnts_.
// 1. Find the order.
std::vector<unsigned> inds_in_order;
std::queue<node_type*> nodes_to_visit; nodes_to_visit.push(trees_[0]);
while (nodes_to_visit.size()) {
node_type* cur = nodes_to_visit.front(); nodes_to_visit.pop();
if (cur->left_==0) {
// It's a leaf.
inds_in_order.push_back(cur->disc_dim_);
}
else {
// BFS.
nodes_to_visit.push(cur->left_);
nodes_to_visit.push(cur->left_+1);
}
}
// 2. Do a shuffle.
std::map<unsigned, unsigned> ind_map;
Float* tmp_pnts = new Float[N_*D_]; // This is inefficient, BUT, it's bug-free.
for (size_t i=0; i<inds_in_order.size(); ++i) {
ind_map[inds_in_order[i]] = i;
for (unsigned d=0; d<D_; ++d) {
tmp_pnts[i*D_ + d] = pnts_[inds_in_order[i]*D_ + d];
}
}
std::copy(tmp_pnts, tmp_pnts+N_*D_, pnts);
delete[] tmp_pnts;
// 3. Rejig the trees.
for (size_t t=0; t<trees_.size(); ++t) {
std::queue<node_type*> nodes_to_visit; nodes_to_visit.push(trees_[t]);
while (nodes_to_visit.size()) {
node_type* cur = nodes_to_visit.front(); nodes_to_visit.pop();
if (cur->left_==0) {
cur->disc_dim_ = ind_map[cur->disc_dim_];
}
else {
nodes_to_visit.push(cur->left_);
nodes_to_visit.push(cur->left_+1);
}
}
}
}
size_t
size()
{
return pool.size();
}
~jp_nn_kdtree()
{
pool.free();
//node_type::free();
while (trees_.size()>0) {
delete trees_.back();
trees_.pop_back();
}
}
void
search(const Float* pnt, unsigned numnn, std::pair<size_t, DistFloat>* nns, unsigned nchecks, const Float* pnts = 0) const
{
if (pnts == 0) pnts = pnts_;
BPQ pri_branch;
for (unsigned i=0; i<numnn; ++i) { nns[i] = std::make_pair(-1, std::numeric_limits<DistFloat>::max()); }
std::vector<bool> seen(N_, false);
// Search each tree at least once.
for (size_t t=0; t<trees_.size(); ++t) {
trees_[t]->search(pnt, pri_branch, numnn, nns, seen, pnts, D_, DiscFloat(), 0, nchecks);
}
unsigned num_dists = 0;
// Carry on searching until we've computed nchecks_ distances.
while(pri_branch.size() && num_dists < nchecks) {
std::pair<DiscFloat, node_type* > pr = pri_branch.top();
pri_branch.pop();
pr.second->search(pnt, pri_branch, numnn, nns, seen, pnts, D_, pr.first, num_dists, nchecks);
num_dists++;
}
}
};
extern "C" void* jp_nn_kdtree_f4_new(float* y, unsigned y_sz,
unsigned ndims,
unsigned ntrees,
unsigned seed)
{
void* ret = (void*)(new jp_nn_kdtree<float>(y, y_sz, ndims, ntrees, seed));
return ret;
}
extern "C" void jp_nn_kdtree_f4_del(void* tree)
{
delete (jp_nn_kdtree<float>*)tree;
}
extern "C" void jp_nn_kdtree_f4_search(void* tree,
float* x, unsigned x_sz,
unsigned ndims, unsigned nchecks,
unsigned* inds, float* dsqs)
{
jp_nn_kdtree<float>* kdt = (jp_nn_kdtree<float>*)tree;
std::pair<size_t, float> nns[2];
for (unsigned i=0; i<x_sz; ++i) {
kdt->search(&x[i*ndims], 1, nns, nchecks);
inds[i] = nns[0].first;
dsqs[i] = nns[0].second;
}
}
extern "C" void jp_nn_kdtree_f4_search_knn(void* tree,
float* x, unsigned x_sz,
unsigned ndims, unsigned nchecks,
unsigned* inds, float* dsqs,
unsigned knn)
{
jp_nn_kdtree<float>* kdt = (jp_nn_kdtree<float>*)tree;
std::vector< std::pair<size_t,float> > nns(knn+1);
for (unsigned i=0; i<x_sz; ++i) {
kdt->search(&x[i*ndims], knn, &nns[0], nchecks);
for (unsigned j=0; j<knn; ++j) {
inds[knn*i + j] = nns[j].first;
dsqs[knn*i + j] = nns[j].second;
}
}
}
extern "C" void* jp_nn_kdtree_f8_new(double* y, unsigned y_sz,
unsigned ndims,
unsigned ntrees,
unsigned seed)
{
void* ret = (void*)(new jp_nn_kdtree<double>(y, y_sz, ndims, ntrees, seed));
return ret;
}
extern "C" void jp_nn_kdtree_f8_del(void* tree)
{
delete (jp_nn_kdtree<double>*)tree;
}
extern "C" void jp_nn_kdtree_f8_search(void* tree,
double* x, unsigned x_sz,
unsigned ndims, unsigned nchecks,
unsigned* inds, double* dsqs)
{
jp_nn_kdtree<double>* kdt = (jp_nn_kdtree<double>*)tree;
std::pair<size_t, double> nns[2];
for (unsigned i=0; i<x_sz; ++i) {
kdt->search(&x[i*ndims], 1, nns, nchecks);
inds[i] = nns[0].first;
dsqs[i] = nns[0].second;
}
}
extern "C" void jp_nn_kdtree_f8_search_knn(void* tree,
double* x, unsigned x_sz,
unsigned ndims, unsigned nchecks,
unsigned* inds, double* dsqs,
unsigned knn)
{
jp_nn_kdtree<double>* kdt = (jp_nn_kdtree<double>*)tree;
std::vector< std::pair<size_t,double> > nns(knn);
for (unsigned i=0; i<x_sz; ++i) {
kdt->search(&x[i*ndims], knn, &nns[0], nchecks);
for (unsigned j=0; j<knn; ++j) {
inds[knn*i + j] = nns[j].first;
dsqs[knn*i + j] = nns[j].second;
}
}
}
#endif
| 28.022177 | 131 | 0.58184 | [
"vector"
] |
b3efeffa7e5dba3d7c1b9734e714a19c17565feb | 36,583 | cpp | C++ | thirdparty/AngelCode/sdk/angelscript/source/as_module.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | 1 | 2021-07-25T15:10:39.000Z | 2021-07-25T15:10:39.000Z | thirdparty/AngelCode/sdk/angelscript/source/as_module.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | thirdparty/AngelCode/sdk/angelscript/source/as_module.cpp | kcat/XLEngine | 0e735ad67fa40632add3872e0cbe5a244689cbe5 | [
"MIT"
] | null | null | null | /*
AngelCode Scripting Library
Copyright (c) 2003-2011 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_module.cpp
//
// A class that holds a script module
//
#include "as_config.h"
#include "as_module.h"
#include "as_builder.h"
#include "as_context.h"
#include "as_texts.h"
BEGIN_AS_NAMESPACE
// internal
asCModule::asCModule(const char *name, asCScriptEngine *engine)
{
this->name = name;
this->engine = engine;
builder = 0;
isGlobalVarInitialized = false;
}
// internal
asCModule::~asCModule()
{
InternalReset();
if( builder )
{
asDELETE(builder,asCBuilder);
builder = 0;
}
// Remove the module from the engine
if( engine )
{
if( engine->lastModule == this )
engine->lastModule = 0;
engine->scriptModules.RemoveValue(this);
}
}
// interface
asIScriptEngine *asCModule::GetEngine() const
{
return engine;
}
// interface
void asCModule::SetName(const char *name)
{
this->name = name;
}
// interface
const char *asCModule::GetName() const
{
return name.AddressOf();
}
// interface
int asCModule::AddScriptSection(const char *name, const char *code, size_t codeLength, int lineOffset)
{
if( !builder )
builder = asNEW(asCBuilder)(engine, this);
return builder->AddCode(name, code, (int)codeLength, lineOffset, (int)engine->GetScriptSectionNameIndex(name ? name : ""), engine->ep.copyScriptSections);
}
// internal
void asCModule::JITCompile()
{
for (unsigned int i = 0; i < scriptFunctions.GetLength(); i++)
{
scriptFunctions[i]->JITCompile();
}
}
// interface
int asCModule::Build()
{
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = engine->RequestBuild();
if( r < 0 )
return r;
engine->PrepareEngine();
if( engine->configFailed )
{
engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
InternalReset();
if( !builder )
{
engine->BuildCompleted();
return asSUCCESS;
}
// Compile the script
r = builder->Build();
asDELETE(builder,asCBuilder);
builder = 0;
if( r < 0 )
{
// Reset module again
InternalReset();
engine->BuildCompleted();
return r;
}
JITCompile();
engine->PrepareEngine();
engine->BuildCompleted();
// Initialize global variables
if( r >= 0 && engine->ep.initGlobalVarsAfterBuild )
r = ResetGlobalVars(0);
return r;
}
// interface
int asCModule::ResetGlobalVars(asIScriptContext *ctx)
{
if( isGlobalVarInitialized )
CallExit();
return CallInit(ctx);
}
// interface
int asCModule::GetFunctionIdByIndex(asUINT index) const
{
if( index >= globalFunctions.GetLength() )
return asNO_FUNCTION;
return globalFunctions[index]->id;
}
// internal
int asCModule::CallInit(asIScriptContext *myCtx)
{
if( isGlobalVarInitialized )
return asERROR;
// Each global variable needs to be cleared individually
asUINT n;
for( n = 0; n < scriptGlobals.GetLength(); n++ )
{
if( scriptGlobals[n] )
{
memset(scriptGlobals[n]->GetAddressOfValue(), 0, sizeof(asDWORD)*scriptGlobals[n]->type.GetSizeOnStackDWords());
}
}
// Call the init function for each of the global variables
asIScriptContext *ctx = myCtx;
int r = asEXECUTION_FINISHED;
for( n = 0; n < scriptGlobals.GetLength() && r == asEXECUTION_FINISHED; n++ )
{
if( scriptGlobals[n]->GetInitFunc() )
{
if( ctx == 0 )
{
r = engine->CreateContext(&ctx, true);
if( r < 0 )
break;
}
r = ctx->Prepare(scriptGlobals[n]->GetInitFunc()->id);
if( r >= 0 )
{
r = ctx->Execute();
if( r != asEXECUTION_FINISHED )
{
asCString msg;
msg.Format(TXT_FAILED_TO_INITIALIZE_s, scriptGlobals[n]->name.AddressOf());
asCScriptFunction *func = scriptGlobals[n]->GetInitFunc();
engine->WriteMessage(func->scriptSectionIdx >= 0 ? engine->scriptSectionNames[func->scriptSectionIdx]->AddressOf() : "",
func->GetLineNumber(0) & 0xFFFFF,
func->GetLineNumber(0) >> 20,
asMSGTYPE_ERROR,
msg.AddressOf());
if( r == asEXECUTION_EXCEPTION )
{
int funcId = ctx->GetExceptionFunction();
const asIScriptFunction *function = engine->GetFunctionDescriptorById(funcId);
msg.Format(TXT_EXCEPTION_s_IN_s, ctx->GetExceptionString(), function->GetDeclaration());
engine->WriteMessage(function->GetScriptSectionName(),
ctx->GetExceptionLineNumber(),
0,
asMSGTYPE_INFORMATION,
msg.AddressOf());
}
}
}
}
}
if( ctx && !myCtx )
{
ctx->Release();
ctx = 0;
}
// Even if the initialization failed we need to set the
// flag that the variables have been initialized, otherwise
// the module won't free those variables that really were
// initialized.
isGlobalVarInitialized = true;
if( r != asEXECUTION_FINISHED )
return asINIT_GLOBAL_VARS_FAILED;
return asSUCCESS;
}
// internal
void asCModule::CallExit()
{
if( !isGlobalVarInitialized ) return;
for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
{
if( scriptGlobals[n]->type.IsObject() )
{
void **obj = (void**)scriptGlobals[n]->GetAddressOfValue();
if( *obj )
{
asCObjectType *ot = scriptGlobals[n]->type.GetObjectType();
if( ot->beh.release )
engine->CallObjectMethod(*obj, ot->beh.release);
else
{
if( ot->beh.destruct )
engine->CallObjectMethod(*obj, ot->beh.destruct);
engine->CallFree(*obj);
}
// Set the address to 0 as someone might try to access the variable afterwards
*obj = 0;
}
}
}
isGlobalVarInitialized = false;
}
// internal
void asCModule::InternalReset()
{
CallExit();
size_t n;
// Release all global functions
for( n = 0; n < globalFunctions.GetLength(); n++ )
{
if( globalFunctions[n] )
globalFunctions[n]->Release();
}
globalFunctions.SetLength(0);
// First release all compiled functions
for( n = 0; n < scriptFunctions.GetLength(); n++ )
{
if( scriptFunctions[n] )
{
// Remove the module reference in the functions
scriptFunctions[n]->module = 0;
scriptFunctions[n]->Release();
}
}
scriptFunctions.SetLength(0);
// Release the global properties declared in the module
for( n = 0; n < scriptGlobals.GetLength(); n++ )
scriptGlobals[n]->Release();
scriptGlobals.SetLength(0);
UnbindAllImportedFunctions();
// Free bind information
for( n = 0; n < bindInformations.GetLength(); n++ )
{
asUINT id = bindInformations[n]->importedFunctionSignature->id & 0xFFFF;
engine->importedFunctions[id] = 0;
engine->freeImportedFunctionIdxs.PushLast(id);
asDELETE(bindInformations[n]->importedFunctionSignature, asCScriptFunction);
asDELETE(bindInformations[n], sBindInfo);
}
bindInformations.SetLength(0);
// Free declared types, including classes, typedefs, and enums
for( n = 0; n < classTypes.GetLength(); n++ )
classTypes[n]->Release();
classTypes.SetLength(0);
for( n = 0; n < enumTypes.GetLength(); n++ )
enumTypes[n]->Release();
enumTypes.SetLength(0);
for( n = 0; n < typeDefs.GetLength(); n++ )
typeDefs[n]->Release();
typeDefs.SetLength(0);
// Free funcdefs
for( n = 0; n < funcDefs.GetLength(); n++ )
{
// TODO: funcdefs: These may be shared between modules, so we can't just remove them
engine->funcDefs.RemoveValue(funcDefs[n]);
funcDefs[n]->Release();
}
funcDefs.SetLength(0);
}
// interface
int asCModule::GetFunctionIdByName(const char *name) const
{
// TODO: optimize: Improve linear search
// Find the function id
int id = -1;
for( size_t n = 0; n < globalFunctions.GetLength(); n++ )
{
if( globalFunctions[n]->name == name )
{
if( id == -1 )
id = globalFunctions[n]->id;
else
return asMULTIPLE_FUNCTIONS;
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
// interface
asUINT asCModule::GetImportedFunctionCount() const
{
return (asUINT)bindInformations.GetLength();
}
// interface
int asCModule::GetImportedFunctionIndexByDecl(const char *decl) const
{
asCBuilder bld(engine, const_cast<asCModule*>(this));
asCScriptFunction func(engine, const_cast<asCModule*>(this), asFUNC_DUMMY);
bld.ParseFunctionDeclaration(0, decl, &func, false);
// TODO: optimize: Improve linear search
// Search script functions for matching interface
int id = -1;
for( asUINT n = 0; n < bindInformations.GetLength(); ++n )
{
if( func.name == bindInformations[n]->importedFunctionSignature->name &&
func.returnType == bindInformations[n]->importedFunctionSignature->returnType &&
func.parameterTypes.GetLength() == bindInformations[n]->importedFunctionSignature->parameterTypes.GetLength() )
{
bool match = true;
for( asUINT p = 0; p < func.parameterTypes.GetLength(); ++p )
{
if( func.parameterTypes[p] != bindInformations[n]->importedFunctionSignature->parameterTypes[p] )
{
match = false;
break;
}
}
if( match )
{
if( id == -1 )
id = n;
else
return asMULTIPLE_FUNCTIONS;
}
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
// interface
asUINT asCModule::GetFunctionCount() const
{
return (asUINT)globalFunctions.GetLength();
}
// interface
int asCModule::GetFunctionIdByDecl(const char *decl) const
{
asCBuilder bld(engine, const_cast<asCModule*>(this));
asCScriptFunction func(engine, const_cast<asCModule*>(this), asFUNC_DUMMY);
int r = bld.ParseFunctionDeclaration(0, decl, &func, false);
if( r < 0 )
return asINVALID_DECLARATION;
// TODO: optimize: Improve linear search
// Search script functions for matching interface
int id = -1;
for( size_t n = 0; n < globalFunctions.GetLength(); ++n )
{
if( globalFunctions[n]->objectType == 0 &&
func.name == globalFunctions[n]->name &&
func.returnType == globalFunctions[n]->returnType &&
func.parameterTypes.GetLength() == globalFunctions[n]->parameterTypes.GetLength() )
{
bool match = true;
for( size_t p = 0; p < func.parameterTypes.GetLength(); ++p )
{
if( func.parameterTypes[p] != globalFunctions[n]->parameterTypes[p] )
{
match = false;
break;
}
}
if( match )
{
if( id == -1 )
id = globalFunctions[n]->id;
else
return asMULTIPLE_FUNCTIONS;
}
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
// interface
asUINT asCModule::GetGlobalVarCount() const
{
return (asUINT)scriptGlobals.GetLength();
}
// interface
int asCModule::GetGlobalVarIndexByName(const char *name) const
{
// Find the global var id
int id = -1;
for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
{
if( scriptGlobals[n]->name == name )
{
id = (int)n;
break;
}
}
if( id == -1 ) return asNO_GLOBAL_VAR;
return id;
}
// interface
int asCModule::RemoveGlobalVar(asUINT index)
{
if( index >= scriptGlobals.GetLength() )
return asINVALID_ARG;
scriptGlobals[index]->Release();
scriptGlobals.RemoveIndex(index);
return 0;
}
// interface
asIScriptFunction *asCModule::GetFunctionDescriptorByIndex(asUINT index) const
{
if( index >= globalFunctions.GetLength() )
return 0;
return globalFunctions[index];
}
// interface
asIScriptFunction *asCModule::GetFunctionDescriptorById(int funcId) const
{
return engine->GetFunctionDescriptorById(funcId);
}
// interface
int asCModule::GetGlobalVarIndexByDecl(const char *decl) const
{
asCBuilder bld(engine, const_cast<asCModule*>(this));
asCObjectProperty gvar;
bld.ParseVariableDeclaration(decl, &gvar);
// TODO: optimize: Improve linear search
// Search script functions for matching interface
int id = -1;
for( size_t n = 0; n < scriptGlobals.GetLength(); ++n )
{
if( gvar.name == scriptGlobals[n]->name &&
gvar.type == scriptGlobals[n]->type )
{
id = (int)n;
break;
}
}
if( id == -1 ) return asNO_GLOBAL_VAR;
return id;
}
// interface
void *asCModule::GetAddressOfGlobalVar(asUINT index)
{
if( index >= scriptGlobals.GetLength() )
return 0;
// TODO: value types shouldn't need dereferencing
// For object variables it's necessary to dereference the pointer to get the address of the value
if( scriptGlobals[index]->type.IsObject() && !scriptGlobals[index]->type.IsObjectHandle() )
return *(void**)(scriptGlobals[index]->GetAddressOfValue());
return (void*)(scriptGlobals[index]->GetAddressOfValue());
}
// interface
const char *asCModule::GetGlobalVarDeclaration(asUINT index) const
{
if( index >= scriptGlobals.GetLength() )
return 0;
asCGlobalProperty *prop = scriptGlobals[index];
asASSERT(threadManager);
asCString *tempString = &threadManager->GetLocalData()->string;
*tempString = prop->type.Format();
*tempString += " " + prop->name;
return tempString->AddressOf();
}
// interface
int asCModule::GetGlobalVar(asUINT index, const char **name, int *typeId, bool *isConst) const
{
if( index >= scriptGlobals.GetLength() )
return asINVALID_ARG;
asCGlobalProperty *prop = scriptGlobals[index];
if( name )
*name = prop->name.AddressOf();
if( typeId )
*typeId = engine->GetTypeIdFromDataType(prop->type);
if( isConst )
*isConst = prop->type.IsReadOnly();
return asSUCCESS;
}
// interface
asUINT asCModule::GetObjectTypeCount() const
{
return (asUINT)classTypes.GetLength();
}
// interface
asIObjectType *asCModule::GetObjectTypeByIndex(asUINT index) const
{
if( index >= classTypes.GetLength() )
return 0;
return classTypes[index];
}
// interface
int asCModule::GetTypeIdByDecl(const char *decl) const
{
asCDataType dt;
asCBuilder bld(engine, const_cast<asCModule*>(this));
int r = bld.ParseDataType(decl, &dt);
if( r < 0 )
return asINVALID_TYPE;
return engine->GetTypeIdFromDataType(dt);
}
// interface
asUINT asCModule::GetEnumCount() const
{
return (asUINT)enumTypes.GetLength();
}
// interface
const char *asCModule::GetEnumByIndex(asUINT index, int *enumTypeId) const
{
if( index >= enumTypes.GetLength() )
return 0;
if( enumTypeId )
*enumTypeId = GetTypeIdByDecl(enumTypes[index]->name.AddressOf());
return enumTypes[index]->name.AddressOf();
}
// interface
int asCModule::GetEnumValueCount(int enumTypeId) const
{
const asCDataType *dt = engine->GetDataTypeFromTypeId(enumTypeId);
asCObjectType *t = dt->GetObjectType();
if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
return asINVALID_TYPE;
return (int)t->enumValues.GetLength();
}
// interface
const char *asCModule::GetEnumValueByIndex(int enumTypeId, asUINT index, int *outValue) const
{
const asCDataType *dt = engine->GetDataTypeFromTypeId(enumTypeId);
asCObjectType *t = dt->GetObjectType();
if( t == 0 || !(t->GetFlags() & asOBJ_ENUM) )
return 0;
if( index >= t->enumValues.GetLength() )
return 0;
if( outValue )
*outValue = t->enumValues[index]->value;
return t->enumValues[index]->name.AddressOf();
}
// interface
asUINT asCModule::GetTypedefCount() const
{
return (asUINT)typeDefs.GetLength();
}
// interface
const char *asCModule::GetTypedefByIndex(asUINT index, int *typeId) const
{
if( index >= typeDefs.GetLength() )
return 0;
if( typeId )
*typeId = GetTypeIdByDecl(typeDefs[index]->name.AddressOf());
return typeDefs[index]->name.AddressOf();
}
// internal
int asCModule::GetNextImportedFunctionId()
{
// TODO: multithread: This will break if one thread if freeing a module, while another is being compiled
if( engine->freeImportedFunctionIdxs.GetLength() )
return FUNC_IMPORTED | (asUINT)engine->freeImportedFunctionIdxs[engine->freeImportedFunctionIdxs.GetLength()-1];
return FUNC_IMPORTED | (asUINT)engine->importedFunctions.GetLength();
}
// internal
int asCModule::AddScriptFunction(int sectionIdx, int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, asCString **defaultArgs, int paramCount, bool isInterface, asCObjectType *objType, bool isConstMethod, bool isGlobalFunction, bool isPrivate)
{
asASSERT(id >= 0);
// Store the function information
asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, isInterface ? asFUNC_INTERFACE : asFUNC_SCRIPT);
func->name = name;
func->id = id;
func->returnType = returnType;
func->scriptSectionIdx = sectionIdx;
for( int n = 0; n < paramCount; n++ )
{
func->parameterTypes.PushLast(params[n]);
func->inOutFlags.PushLast(inOutFlags[n]);
func->defaultArgs.PushLast(defaultArgs[n]);
}
func->objectType = objType;
func->isReadOnly = isConstMethod;
func->isPrivate = isPrivate;
// The script function's refCount was initialized to 1
scriptFunctions.PushLast(func);
engine->SetScriptFunction(func);
// Compute the signature id
if( objType )
func->ComputeSignatureId();
// Add reference
if( isGlobalFunction )
{
globalFunctions.PushLast(func);
func->AddRef();
}
return 0;
}
// internal
int asCModule::AddScriptFunction(asCScriptFunction *func)
{
scriptFunctions.PushLast(func);
func->AddRef();
engine->SetScriptFunction(func);
return 0;
}
// internal
int asCModule::AddImportedFunction(int id, const char *name, const asCDataType &returnType, asCDataType *params, asETypeModifiers *inOutFlags, int paramCount, const asCString &moduleName)
{
asASSERT(id >= 0);
// Store the function information
asCScriptFunction *func = asNEW(asCScriptFunction)(engine, this, asFUNC_IMPORTED);
func->name = name;
func->id = id;
func->returnType = returnType;
for( int n = 0; n < paramCount; n++ )
{
func->parameterTypes.PushLast(params[n]);
func->inOutFlags.PushLast(inOutFlags[n]);
}
func->objectType = 0;
sBindInfo *info = asNEW(sBindInfo);
info->importedFunctionSignature = func;
info->boundFunctionId = -1;
info->importFromModule = moduleName;
bindInformations.PushLast(info);
// Add the info to the array in the engine
if( engine->freeImportedFunctionIdxs.GetLength() )
engine->importedFunctions[engine->freeImportedFunctionIdxs.PopLast()] = info;
else
engine->importedFunctions.PushLast(info);
return 0;
}
// internal
asCScriptFunction *asCModule::GetImportedFunction(int index) const
{
return bindInformations[index]->importedFunctionSignature;
}
// interface
int asCModule::BindImportedFunction(asUINT index, int sourceId)
{
// First unbind the old function
int r = UnbindImportedFunction(index);
if( r < 0 ) return r;
// Must verify that the interfaces are equal
asCScriptFunction *dst = GetImportedFunction(index);
if( dst == 0 ) return asNO_FUNCTION;
asCScriptFunction *src = engine->GetScriptFunction(sourceId);
if( src == 0 )
return asNO_FUNCTION;
// Verify return type
if( dst->returnType != src->returnType )
return asINVALID_INTERFACE;
if( dst->parameterTypes.GetLength() != src->parameterTypes.GetLength() )
return asINVALID_INTERFACE;
for( size_t n = 0; n < dst->parameterTypes.GetLength(); ++n )
{
if( dst->parameterTypes[n] != src->parameterTypes[n] )
return asINVALID_INTERFACE;
}
bindInformations[index]->boundFunctionId = sourceId;
engine->scriptFunctions[sourceId]->AddRef();
return asSUCCESS;
}
// interface
int asCModule::UnbindImportedFunction(asUINT index)
{
if( index >= bindInformations.GetLength() )
return asINVALID_ARG;
// Remove reference to old module
int oldFuncID = bindInformations[index]->boundFunctionId;
if( oldFuncID != -1 )
{
bindInformations[index]->boundFunctionId = -1;
engine->scriptFunctions[oldFuncID]->Release();
}
return asSUCCESS;
}
// interface
const char *asCModule::GetImportedFunctionDeclaration(asUINT index) const
{
asCScriptFunction *func = GetImportedFunction(index);
if( func == 0 ) return 0;
asASSERT(threadManager);
asCString *tempString = &threadManager->GetLocalData()->string;
*tempString = func->GetDeclarationStr();
return tempString->AddressOf();
}
// interface
const char *asCModule::GetImportedFunctionSourceModule(asUINT index) const
{
if( index >= bindInformations.GetLength() )
return 0;
return bindInformations[index]->importFromModule.AddressOf();
}
// inteface
int asCModule::BindAllImportedFunctions()
{
bool notAllFunctionsWereBound = false;
// Bind imported functions
int c = GetImportedFunctionCount();
for( int n = 0; n < c; ++n )
{
asCScriptFunction *func = GetImportedFunction(n);
if( func == 0 ) return asERROR;
asCString str = func->GetDeclarationStr();
// Get module name from where the function should be imported
const char *moduleName = GetImportedFunctionSourceModule(n);
if( moduleName == 0 ) return asERROR;
asCModule *srcMod = engine->GetModule(moduleName, false);
int funcId = -1;
if( srcMod )
funcId = srcMod->GetFunctionIdByDecl(str.AddressOf());
if( funcId < 0 )
notAllFunctionsWereBound = true;
else
{
if( BindImportedFunction(n, funcId) < 0 )
notAllFunctionsWereBound = true;
}
}
if( notAllFunctionsWereBound )
return asCANT_BIND_ALL_FUNCTIONS;
return asSUCCESS;
}
// interface
int asCModule::UnbindAllImportedFunctions()
{
asUINT c = GetImportedFunctionCount();
for( asUINT n = 0; n < c; ++n )
UnbindImportedFunction(n);
return asSUCCESS;
}
// internal
asCObjectType *asCModule::GetObjectType(const char *type)
{
size_t n;
// TODO: optimize: Improve linear search
for( n = 0; n < classTypes.GetLength(); n++ )
if( classTypes[n]->name == type )
return classTypes[n];
for( n = 0; n < enumTypes.GetLength(); n++ )
if( enumTypes[n]->name == type )
return enumTypes[n];
for( n = 0; n < typeDefs.GetLength(); n++ )
if( typeDefs[n]->name == type )
return typeDefs[n];
return 0;
}
// internal
asCGlobalProperty *asCModule::AllocateGlobalProperty(const char *name, const asCDataType &dt)
{
asCGlobalProperty *prop = engine->AllocateGlobalProperty();
prop->name = name;
// Allocate the memory for this property based on its type
prop->type = dt;
prop->AllocateMemory();
// Store the variable in the module scope (the reference count is already set to 1)
scriptGlobals.PushLast(prop);
return prop;
}
// internal
void asCModule::ResolveInterfaceIds(asCArray<void*> *substitutions)
{
// For each of the interfaces declared in the script find identical interface in the engine.
// If an identical interface was found then substitute the current id for the identical interface's id,
// then remove this interface declaration. If an interface was modified by the declaration, then
// retry the detection of identical interface for it since it may now match another.
// For an interface to be equal to another the name and methods must match. If the interface
// references another interface, then that must be checked as well, which can lead to circular references.
// Example:
//
// interface A { void f(B@); }
// interface B { void f(A@); void f(C@); }
// interface C { void f(A@); }
//
// A1 equals A2 if and only if B1 equals B2
// B1 equals B2 if and only if A1 equals A2 and C1 equals C2
// C1 equals C2 if and only if A1 equals A2
unsigned int i;
// The interface can only be equal to interfaces declared in other modules.
// Interfaces registered by the application will conflict with this one if it has the same name.
// This means that we only need to look for the interfaces in the engine->classTypes, but not in engine->objectTypes.
asCArray<sObjectTypePair> equals;
for( i = 0; i < classTypes.GetLength(); i++ )
{
asCObjectType *intf1 = classTypes[i];
if( !intf1->IsInterface() )
continue;
// The interface may have been determined to be equal to another already
bool found = false;
for( unsigned int e = 0; e < equals.GetLength(); e++ )
{
if( equals[e].a == intf1 )
{
found = true;
break;
}
}
if( found )
continue;
for( unsigned int n = 0; n < engine->classTypes.GetLength(); n++ )
{
// Don't compare against self
if( engine->classTypes[n] == intf1 )
continue;
asCObjectType *intf2 = engine->classTypes[n];
// Assume the interface are equal, then validate this
sObjectTypePair pair = {intf1,intf2};
equals.PushLast(pair);
if( AreInterfacesEqual(intf1, intf2, equals) )
break;
// Since they are not equal, remove them from the list again
equals.PopLast();
}
}
// For each of the interfaces that have been found to be equal we need to
// remove the new declaration and instead have the module use the existing one.
for( i = 0; i < equals.GetLength(); i++ )
{
// Substitute the old object type from the module's class types
unsigned int c;
for( c = 0; c < classTypes.GetLength(); c++ )
{
if( classTypes[c] == equals[i].a )
{
if( substitutions )
{
substitutions->PushLast(equals[i].a);
substitutions->PushLast(equals[i].b);
}
classTypes[c] = equals[i].b;
equals[i].b->AddRef();
break;
}
}
// Remove the old object type from the engine's class types
engine->classTypes.RemoveValue(equals[i].a);
// Substitute all uses of this object type
// Only interfaces in the module is using the type so far
for( c = 0; c < classTypes.GetLength(); c++ )
{
if( classTypes[c]->IsInterface() )
{
asCObjectType *intf = classTypes[c];
for( asUINT m = 0; m < intf->GetMethodCount(); m++ )
{
asCScriptFunction *func = engine->GetScriptFunction(intf->methods[m]);
if( func )
{
if( func->returnType.GetObjectType() == equals[i].a )
func->returnType.SetObjectType(equals[i].b);
for( asUINT p = 0; p < func->GetParamCount(); p++ )
{
if( func->parameterTypes[p].GetObjectType() == equals[i].a )
func->parameterTypes[p].SetObjectType(equals[i].b);
}
}
}
}
}
// Substitute all interface methods in the module. Delete all methods for the old interface
for( unsigned int m = 0; m < equals[i].a->methods.GetLength(); m++ )
{
for( c = 0; c < scriptFunctions.GetLength(); c++ )
{
if( scriptFunctions[c]->id == equals[i].a->methods[m] )
{
if( substitutions )
substitutions->PushLast(scriptFunctions[c]);
scriptFunctions[c]->Release();
scriptFunctions[c] = engine->GetScriptFunction(equals[i].b->methods[m]);
scriptFunctions[c]->AddRef();
if( substitutions )
substitutions->PushLast(scriptFunctions[c]);
}
}
}
// Deallocate the object type
asDELETE(equals[i].a, asCObjectType);
}
}
// internal
bool asCModule::AreInterfacesEqual(asCObjectType *a, asCObjectType *b, asCArray<sObjectTypePair> &equals)
{
// An interface is considered equal to another if the following criterias apply:
//
// - The interface names are equal
// - The number of methods is equal
// - All the methods are equal
// - The order of the methods is equal
// - If a method returns or takes an interface by handle or reference, both interfaces must be equal
// ------------
// TODO: Study the possiblity of allowing interfaces where methods are declared in different orders to
// be considered equal. The compiler and VM can handle this, but it complicates the comparison of interfaces
// where multiple methods take different interfaces as parameters (or return values). Example:
//
// interface A
// {
// void f(B, C);
// void f(B);
// void f(C);
// }
//
// If 'void f(B)' in module A is compared against 'void f(C)' in module B, then the code will assume
// interface B in module A equals interface C in module B. Thus 'void f(B, C)' in module A won't match
// 'void f(C, B)' in module B.
// ------------
// Are both interfaces?
if( !a->IsInterface() || !b->IsInterface() )
return false;
// Are the names equal?
if( a->name != b->name )
return false;
// Are the number of methods equal?
if( a->methods.GetLength() != b->methods.GetLength() )
return false;
// Keep the number of equals in the list so we can restore it later if necessary
int prevEquals = (int)equals.GetLength();
// Are the methods equal to each other?
bool match = true;
for( unsigned int n = 0; n < a->methods.GetLength(); n++ )
{
match = false;
asCScriptFunction *funcA = (asCScriptFunction*)engine->GetFunctionDescriptorById(a->methods[n]);
asCScriptFunction *funcB = (asCScriptFunction*)engine->GetFunctionDescriptorById(b->methods[n]);
// funcB can be null if the module that created the interface has been
// discarded but the type has not yet been released by the engine.
if( funcB == 0 )
break;
// The methods must have the same name and the same number of parameters
if( funcA->name != funcB->name ||
funcA->parameterTypes.GetLength() != funcB->parameterTypes.GetLength() )
break;
// The return types must be equal. If the return type is an interface the interfaces must match.
if( !AreTypesEqual(funcA->returnType, funcB->returnType, equals) )
break;
match = true;
for( unsigned int p = 0; p < funcA->parameterTypes.GetLength(); p++ )
{
if( !AreTypesEqual(funcA->parameterTypes[p], funcB->parameterTypes[p], equals) ||
funcA->inOutFlags[p] != funcB->inOutFlags[p] )
{
match = false;
break;
}
}
if( !match )
break;
}
// For each of the new interfaces that we're assuming to be equal, we need to validate this
if( match )
{
for( unsigned int n = prevEquals; n < equals.GetLength(); n++ )
{
if( !AreInterfacesEqual(equals[n].a, equals[n].b, equals) )
{
match = false;
break;
}
}
}
if( !match )
{
// The interfaces doesn't match.
// Restore the list of previous equals before we go on, so
// the caller can continue comparing with another interface
equals.SetLength(prevEquals);
}
return match;
}
// internal
bool asCModule::AreTypesEqual(const asCDataType &a, const asCDataType &b, asCArray<sObjectTypePair> &equals)
{
if( !a.IsEqualExceptInterfaceType(b) )
return false;
asCObjectType *ai = a.GetObjectType();
asCObjectType *bi = b.GetObjectType();
if( ai && ai->IsInterface() )
{
// If the interface is in the equals list, then the pair must match the pair in the list
bool found = false;
unsigned int e;
for( e = 0; e < equals.GetLength(); e++ )
{
if( equals[e].a == ai )
{
found = true;
break;
}
}
if( found )
{
// Do the pairs match?
if( equals[e].b != bi )
return false;
}
else
{
// Assume they are equal from now on
sObjectTypePair pair = {ai, bi};
equals.PushLast(pair);
}
}
return true;
}
// interface
int asCModule::SaveByteCode(asIBinaryStream *out) const
{
if( out == 0 ) return asINVALID_ARG;
asCRestore rest(const_cast<asCModule*>(this), out, engine);
return rest.Save();
}
// interface
int asCModule::LoadByteCode(asIBinaryStream *in)
{
if( in == 0 ) return asINVALID_ARG;
// Only permit loading bytecode if no other thread is currently compiling
// TODO: It should be possible to have multiple threads perform compilations
int r = engine->RequestBuild();
if( r < 0 )
return r;
asCRestore rest(this, in, engine);
r = rest.Restore();
JITCompile();
engine->BuildCompleted();
return r;
}
// interface
int asCModule::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset)
{
// Validate arguments
if( code == 0 )
return asINVALID_ARG;
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = engine->RequestBuild();
if( r < 0 )
return r;
// Prepare the engine
engine->PrepareEngine();
if( engine->configFailed )
{
engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
// Compile the global variable and add it to the module scope
asCBuilder builder(engine, this);
asCString str = code;
r = builder.CompileGlobalVar(sectionName, str.AddressOf(), lineOffset);
engine->BuildCompleted();
// Initialize the variable
if( r >= 0 && engine->ep.initGlobalVarsAfterBuild )
{
// Clear the memory
asCGlobalProperty *prop = scriptGlobals[scriptGlobals.GetLength()-1];
memset(prop->GetAddressOfValue(), 0, sizeof(asDWORD)*prop->type.GetSizeOnStackDWords());
if( prop->GetInitFunc() )
{
// Call the init function for the global variable
asIScriptContext *ctx = 0;
int r = engine->CreateContext(&ctx, true);
if( r < 0 )
return r;
r = ctx->Prepare(prop->GetInitFunc()->id);
if( r >= 0 )
r = ctx->Execute();
ctx->Release();
}
}
return r;
}
// interface
int asCModule::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asIScriptFunction **outFunc)
{
asASSERT(outFunc == 0 || *outFunc == 0);
// Validate arguments
if( code == 0 ||
(compileFlags != 0 && compileFlags != asCOMP_ADD_TO_MODULE) )
return asINVALID_ARG;
// Only one thread may build at one time
// TODO: It should be possible to have multiple threads perform compilations
int r = engine->RequestBuild();
if( r < 0 )
return r;
// Prepare the engine
engine->PrepareEngine();
if( engine->configFailed )
{
engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_INVALID_CONFIGURATION);
engine->BuildCompleted();
return asINVALID_CONFIGURATION;
}
// Compile the single function
asCBuilder builder(engine, this);
asCString str = code;
asCScriptFunction *func = 0;
r = builder.CompileFunction(sectionName, str.AddressOf(), lineOffset, compileFlags, &func);
engine->BuildCompleted();
if( r >= 0 && outFunc )
{
// Return the function to the caller
*outFunc = func;
func->AddRef();
}
// Release our reference to the function
if( func )
func->Release();
return r;
}
// interface
int asCModule::RemoveFunction(int funcId)
{
// Find the global function
for( asUINT n = 0; n < globalFunctions.GetLength(); n++ )
{
if( globalFunctions[n] && globalFunctions[n]->id == funcId )
{
asCScriptFunction *func = globalFunctions[n];
globalFunctions.RemoveIndex(n);
func->Release();
scriptFunctions.RemoveValue(func);
func->Release();
return 0;
}
}
return asNO_FUNCTION;
}
// internal
int asCModule::AddFuncDef(const char *name)
{
asCScriptFunction *func = asNEW(asCScriptFunction)(engine, 0, asFUNC_FUNCDEF);
func->name = name;
funcDefs.PushLast(func);
engine->funcDefs.PushLast(func);
func->id = engine->GetNextScriptFunctionId();
engine->SetScriptFunction(func);
return (int)funcDefs.GetLength()-1;
}
END_AS_NAMESPACE
| 25.690309 | 299 | 0.662357 | [
"object"
] |
b3fc4ee58f8daa1b1191399b86b7f56bf1151a70 | 1,147 | cpp | C++ | source/lib/oglplus/text.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | source/lib/oglplus/text.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | source/lib/oglplus/text.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /**
* .file lib/oglplus/text.cpp
* .brief Text rendering utility functions
*
* @author Matus Chochlik
*
* Copyright 2010-2019 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "prologue.ipp"
#if GL_VERSION_4_1 || GL_ARB_separate_shader_objects || \
GL_EXT_direct_state_access
#include <oglplus/buffer.hpp>
#include <oglplus/context.hpp>
#include <oglplus/error/glfunc.hpp>
#include <oglplus/error/limit.hpp>
#include <oglplus/images/image.hpp>
#include <oglplus/object/desc.hpp>
#include <oglplus/program.hpp>
#include <oglplus/shader.hpp>
#include <oglplus/string/def.hpp>
#include <oglplus/string/empty.hpp>
#include <oglplus/string/utf8.hpp>
#include <oglplus/texture.hpp>
#include <oglplus/uniform.hpp>
#include <oglplus/vertex_attrib.hpp>
#include "implement.ipp"
#include <oglplus/text/bitmap_glyph.hpp>
#include <oglplus/text/stb_truetype.hpp>
#include <oglplus/text/unicode.hpp>
#if OGLPLUS_PANGO_CAIRO_FOUND
#include <oglplus/text/pango_cairo.hpp>
#endif
#endif
#include "epilogue.ipp"
| 26.674419 | 68 | 0.76286 | [
"object"
] |
b3fefc971657930abccf0d5b7480c18741601b31 | 9,613 | cpp | C++ | src/vision_methods.cpp | derpicated/articated_research | 86d82a07df20f991f407a0ac3347bf6a8bd8bc9a | [
"MIT"
] | 1 | 2018-10-07T21:42:55.000Z | 2018-10-07T21:42:55.000Z | src/vision_methods.cpp | derpicated/articated_research | 86d82a07df20f991f407a0ac3347bf6a8bd8bc9a | [
"MIT"
] | null | null | null | src/vision_methods.cpp | derpicated/articated_research | 86d82a07df20f991f407a0ac3347bf6a8bd8bc9a | [
"MIT"
] | null | null | null | #include "vision_methods.hpp"
#include "movement3d.hpp"
#include <opencv2/opencv.hpp>
#include <string>
namespace cv {
// needed for map usage
bool operator< (const KeyPoint& point, const KeyPoint& other_point) {
bool ans = false;
if (point.pt.x < other_point.pt.x) {
ans = true;
} else if (point.pt.x == other_point.pt.x && point.pt.y < other_point.pt.y) {
ans = true;
}
return ans;
}
bool operator!= (const KeyPoint& point, const KeyPoint& other_point) {
bool ans = true;
if (point.pt.x == other_point.pt.x && point.pt.y == other_point.pt.y) {
ans = false;
}
return ans;
}
}
vision_methods::vision_methods () {
}
vision_methods::~vision_methods () {
}
cv::Mat vision_methods::preprocessing (const cv::Mat& image_in) {
cv::Mat image_out;
cvtColor (image_in, image_out, CV_BGR2GRAY);
cv::GaussianBlur (image_out, image_out, cv::Size (_ksize_x, _ksize_y), _sigma_x, _sigma_y);
return image_out;
}
cv::Mat vision_methods::segmentation (const cv::Mat& image_in) {
cv::Mat image_out;
cv::threshold (image_in, image_out, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
return image_out;
}
cv::Mat vision_methods::extraction (const cv::Mat& image_in,
std::map<unsigned int, cv::Point2f>& markers) {
std::vector<cv::KeyPoint> key_points;
cv::Mat image_out (image_in.rows, image_in.cols, CV_8UC1, cv::Scalar (0));
// blob detector creation
cv::SimpleBlobDetector::Params blob_detector_params;
blob_detector_params.filterByArea = true;
blob_detector_params.maxArea = 10000.0;
blob_detector_params.minArea = 10.0;
cv::Ptr<cv::SimpleBlobDetector> blob_detector =
cv::SimpleBlobDetector::create (blob_detector_params);
// blob detection
blob_detector->detect (image_in, key_points);
// marker extraction
std::vector<std::vector<cv::KeyPoint>> potential_markers;
extract_groups (key_points, potential_markers);
extract_markers (potential_markers, markers);
// debug image construction
for (cv::KeyPoint point : key_points) {
circle (image_out, point.pt, point.size * 2, cv::Scalar (255), -1);
}
for (auto marker : markers) {
putText (image_out, std::to_string (marker.first), marker.second,
cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar (0));
}
return image_out;
}
void vision_methods::extract_groups (std::vector<cv::KeyPoint> key_points,
std::vector<std::vector<cv::KeyPoint>>& potential_markers) {
// group keypoints into markers by proximity
std::map<cv::KeyPoint, std::vector<cv::KeyPoint>> neighbours;
// get all neighbours for each blob
for (cv::KeyPoint point : key_points) {
float range = point.size * _BLOB_SIZE_RATIO;
float x = point.pt.x;
float y = point.pt.y;
for (cv::KeyPoint other_point : key_points) {
if (point != other_point) {
float dx = x - other_point.pt.x;
float dy = y - other_point.pt.y;
float distance = sqrt ((dx * dx) + (dy * dy));
// if other_point is in range, group it with point
if (distance < range) {
neighbours[point].push_back (other_point);
}
}
}
}
// recursively link all neighbours into groups
while (!neighbours.empty ()) {
std::vector<cv::KeyPoint> potential_marker;
extract_groups_link (neighbours, potential_marker, neighbours.begin ()->first);
potential_markers.push_back (potential_marker);
}
}
void vision_methods::extract_groups_link (
std::map<cv::KeyPoint, std::vector<cv::KeyPoint>>& neighbours,
std::vector<cv::KeyPoint>& potential_marker,
const cv::KeyPoint& point) {
// if the point hasnt been processed yet
if (neighbours.find (point) != neighbours.end ()) {
// add the point to the markert
// get its neighbours
// and remove the from the unprocessed lis
potential_marker.push_back (point);
std::vector<cv::KeyPoint> neighbour_list = neighbours[point];
neighbours.erase (point);
for (cv::KeyPoint neighbour_point : neighbour_list) {
// link all the neighbours neighbours
extract_groups_link (neighbours, potential_marker, neighbour_point);
}
}
}
void vision_methods::extract_markers (std::vector<std::vector<cv::KeyPoint>>& potential_markers,
std::map<unsigned int, cv::Point2f>& markers) {
// calculate marker properties (id, size, location)
for (std::vector<cv::KeyPoint> marker_points : potential_markers) {
const unsigned int marker_id = marker_points.size ();
if (_MIN_MARKER_ID <= marker_id && marker_id <= _MAX_MARKER_ID) {
cv::Point2f marker_pos;
float average_x = 0;
float average_y = 0;
for (cv::KeyPoint key_point : marker_points) {
// average_size += key_point.size;
average_x += key_point.pt.x;
average_y += key_point.pt.y;
}
// average_size /= marker_id;
marker_pos.x = average_x / marker_id;
marker_pos.y = average_y / marker_id;
markers[marker_id] = marker_pos;
}
}
}
std::map<unsigned int, cv::Point2f> vision_methods::set_reference (
const cv::Mat& image_reference) {
cv::Mat preprocessed, segmented;
preprocessed = preprocessing (image_reference);
segmented = segmentation (preprocessed);
std::map<unsigned int, cv::Point2f> marker_points;
extraction (segmented, marker_points);
set_reference (marker_points);
return _reference_markers;
}
std::map<unsigned int, cv::Point2f> vision_methods::set_reference (
const std::map<unsigned int, cv::Point2f>& marker_points) {
if (marker_points.size () < _minimal_ref_points) {
throw std::length_error ("too few reference points; found " +
std::to_string (marker_points.size ()) + " need " +
std::to_string (_minimal_ref_points));
}
_reference_markers = marker_points;
return _reference_markers;
}
movement3d vision_methods::classification (const cv::Mat& image) {
movement3d movement;
cv::Mat preprocessed, segmented;
preprocessed = preprocessing (image);
segmented = segmentation (preprocessed);
std::map<unsigned int, cv::Point2f> marker_points;
extraction (segmented, marker_points);
movement = classification (marker_points);
return movement;
}
movement3d vision_methods::classification (
const std::map<unsigned int, cv::Point2f>& marker_points) {
movement3d movement;
std::vector<cv::Point2f> ref_points, mark_points;
// convert reference and markers to matching vectors
for (auto const& marker : _reference_markers) {
if (marker_points.find (marker.first) != marker_points.end ()) {
ref_points.push_back (_reference_markers.at (marker.first));
mark_points.push_back (marker_points.at (marker.first));
}
}
// check size
if (ref_points.size () < _minimal_ref_points || mark_points.size () < _minimal_ref_points) {
throw std::length_error (
"too few match points; found " + std::to_string (ref_points.size ()));
}
// find homography between points
cv::Mat H = cv::findHomography (ref_points, mark_points);
// decompose and find information that is in the transformation matrix
std::vector<cv::Mat> rotations, translations, normals;
cv::decomposeHomographyMat (H, _K, rotations, translations, cv::noArray ());
// convert to floats
H.convertTo (H, CV_32F);
for (auto rotation : rotations) {
rotation.convertTo (rotation, CV_32F);
}
for (auto translation : translations) {
translation.convertTo (translation, CV_32F);
}
for (auto normal : normals) {
normal.convertTo (normal, CV_32F);
}
// make H available
// a b c
// H: d e f
// 0 0 1
float Ha = H.at<float> (cv::Point (0, 0));
float Hb = H.at<float> (cv::Point (1, 0));
float Hc = H.at<float> (cv::Point (2, 0));
float Hd = H.at<float> (cv::Point (0, 1));
float He = H.at<float> (cv::Point (1, 1));
float Hf = H.at<float> (cv::Point (2, 0));
// set x, y, z if available
// clang-format off
float default_rot_val[9] = {
1, 0, 0,
0, 1, 0,
0, 0, 1
};
// clang-format on
cv::Mat default_rot_mat = cv::Mat (3, 3, CV_32F, default_rot_val);
// x
if (rotations.size () >= 1) {
movement.rot_x (rotations[0]);
} else {
movement.rot_x (default_rot_mat);
}
// y
if (rotations.size () >= 2) {
movement.rot_y (rotations[1]);
} else {
movement.rot_y (default_rot_mat);
}
// z
if (rotations.size () >= 3) {
movement.rot_z (rotations[2]);
} else {
movement.rot_z (default_rot_mat);
}
// set translation
// a b c c: Tx
// H: d e f f: Ty
// 0 0 1
// x:
movement.trans_x (Hc);
// y:
movement.trans_y (Hf);
// set scale
// a b c a: Sx (also contains 2D rot, so not optimal)
// H: d e f e: Sy (also contains 2D rot, so not optimal)
// 0 0 1
// Sx: sqrt(a^2+b^2)
// Sy: (a*e - b*d) / ( sqrt(a^2+b^2) )
//
float Sx = sqrt (pow (Ha, 2) + pow (Hb, 2));
float Sy = ((Ha * He - Hb * Hd) / (Sx));
(void)Sy;
// is fluctuating a lot, so better to keep this one steady
// movement.scale (Sx);
movement.scale (1);
return movement;
}
| 33.262976 | 96 | 0.62249 | [
"vector"
] |
b601646a583f17cf1255a119008f6f689539f402 | 3,854 | cpp | C++ | plugins/dirlist.cpp | xinhaoyuan/dlauncher | 2a5295d2c2408fc28bb8effe6753cb3c14fb4117 | [
"MIT"
] | null | null | null | plugins/dirlist.cpp | xinhaoyuan/dlauncher | 2a5295d2c2408fc28bb8effe6753cb3c14fb4117 | [
"MIT"
] | null | null | null | plugins/dirlist.cpp | xinhaoyuan/dlauncher | 2a5295d2c2408fc28bb8effe6753cb3c14fb4117 | [
"MIT"
] | null | null | null | #include "dirlist.hpp"
#include <spawn.h>
#include <stdio.h>
#include <unistd.h>
#include <cstring>
#include <cstdio>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <utime.h>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#define CACHE_HEAD "DIRLIST_CACHE"
using namespace std;
static int
read_utf8_string(string &s, FILE *f) {
ostringstream oss;
oss.str("");
while (!feof(f)) {
int c = fgetc(f);
if (c < 0) return 1;
if (c == 0) break;
oss << (char)c;
}
s = oss.str();
return 0;
}
static void
write_utf8_string(const string &s, FILE *f) {
fwrite(s.c_str(), s.length(), 1, f);
fputc(0, f);
}
static void
encode_path(string &result, const string &path) {
ostringstream oss;
for (int i = 0; i < path.length(); ++ i) {
if (path[i] != '/' && path[i] != '_') {
oss << path[i];
}
else if (path[i] != '/' || i != path.length() - 1)
{
oss << '_' << (path[i] == '/' ? '1' : '2');
}
}
result = oss.str();
}
static void
decode_path(string &result, const string &epath) {
ostringstream oss;
int e = 0;
for (int i = 0; i < epath.length(); ++ i) {
if (epath[i] == '_')
e = 1;
else if (e) {
oss << (epath[i] == '1' ? '/' : '_');
e = 0;
} else oss << epath[i];
}
result = oss.str();
}
int
dirlist(const string &dirname, vector<string> &r, const string &cache_file_prefix) {
int cached = 0;
string edirname;
string cachename;
ostringstream oss;
encode_path(edirname, dirname);
oss << cache_file_prefix << edirname;
cachename = oss.str();
time_t dir_time, cache_time;
struct stat statbuf;
if (stat(dirname.c_str(), &statbuf)) goto failed;
if (!S_ISDIR(statbuf.st_mode)) goto failed;
dir_time = statbuf.st_mtime;
if (stat(cachename.c_str(), &statbuf) == 0) {
// Assume the cache file is hold by plugin
cache_time = statbuf.st_mtime;
if (dir_time <= cache_time) cached = 1;
}
again:
r.clear();
if (cached) {
// read the cache
FILE *f = fopen(cachename.c_str(), "rb");
if (f == NULL) { cached = 0; goto again; }
string s;
if (read_utf8_string(s, f) || s != CACHE_HEAD) {
fclose(f);
cached = 0;
goto again;
}
while (!feof(f)) {
if (read_utf8_string(s, f))
{
if (feof(f)) break;
else { fclose(f); cached = 0; goto again; }
}
r.push_back(s);
}
fclose(f);
} else {
fprintf(stderr, "Building cache for %s\n", dirname.c_str());
// build the cache
DIR *dir = opendir(dirname.c_str());
if (dir == NULL) goto failed;
struct dirent *ent;
while ((ent = readdir(dir)) != NULL)
{
if (strcmp(ent->d_name, ".") == 0) continue;
if (strcmp(ent->d_name, "..") == 0) continue;
r.push_back(ent->d_name);
}
// Using '\0' as the delimeter. We are using UTF-8 so no problem! +_+
FILE *f = fopen(cachename.c_str(), "wb");
if (f != NULL) {
write_utf8_string(CACHE_HEAD, f);
for (int i = 0; i < r.size(); ++ i)
write_utf8_string(r[i], f);
fclose(f);
// set time stamp
struct utimbuf times;
times.actime = dir_time;
times.modtime = dir_time;
utime(cachename.c_str(), ×);
}
else
{
fprintf(stderr, "Cannot open file %s as the dir list cache\n", cachename.c_str());
}
}
return 0;
failed:
return 1;
}
| 23.937888 | 94 | 0.502854 | [
"vector"
] |
b6023fcb43dcf8fdef7db5ecd0a062e464d5bdca | 13,788 | cpp | C++ | src/apps/feature_performance/main.cpp | JonasToth/depth-conversions | 5c8338276565d846c07673e83f94f6841006872b | [
"BSD-3-Clause"
] | 2 | 2021-09-30T07:09:49.000Z | 2022-03-14T09:14:35.000Z | src/apps/feature_performance/main.cpp | JonasToth/depth-conversions | 5c8338276565d846c07673e83f94f6841006872b | [
"BSD-3-Clause"
] | null | null | null | src/apps/feature_performance/main.cpp | JonasToth/depth-conversions | 5c8338276565d846c07673e83f94f6841006872b | [
"BSD-3-Clause"
] | null | null | null | #include "keypoint_distribution.h"
#include "matching.h"
#include "min_dist.h"
#include "recognition_performance.h"
#include <CLI/CLI.hpp>
#include <boost/histogram.hpp>
#include <opencv2/core/base.hpp>
#include <sens_loc/util/console.h>
#include <sens_loc/util/correctness_util.h>
#include <stdexcept>
#include <string>
#include <util/batch_visitor.h>
#include <util/colored_parse.h>
#include <util/common_structures.h>
#include <util/tool_macro.h>
#include <util/version_printer.h>
static cv::NormTypes str_to_norm(std::string_view n) {
#define SWITCH_CV_NORM(NORM_NAME) \
if (n == #NORM_NAME) \
return cv::NormTypes::NORM_##NORM_NAME;
SWITCH_CV_NORM(L1)
SWITCH_CV_NORM(L2)
SWITCH_CV_NORM(L2SQR)
SWITCH_CV_NORM(HAMMING2)
SWITCH_CV_NORM(HAMMING)
#undef SWITCH_CV_NORM
UNREACHABLE("unexpected norm type"); // LCOV_EXCL_LINE
}
MAIN_HEAD("Determine Statistical Characteristica of the Descriptors") {
// Explicitly disable threading from OpenCV functions, as the
// parallelization is done at a higher level.
// That means, that each filter application is not multithreaded, but each
// image modification is. This is necessary as "TaskFlow" does not play
// nice with OpenCV threading and they introduce data races in the program
// because of that.
cv::setNumThreads(0);
// Require exactly one subcommand.
app.require_subcommand(1);
string feature_file_input_pattern;
app.add_option("-i,--input", feature_file_input_pattern,
"Define file-pattern for the feature files to be plotted")
->required();
int start_idx = 0;
app.add_option("-s,--start", start_idx, "Start index for processing.")
->required();
int end_idx = 0;
app.add_option("-e,--end", end_idx, "End index for processing.")
->required();
optional<string> statistics_file;
app.add_option(
"-o,--output", statistics_file,
"Write the result of the analysis into a yaml-file instead to stdout");
CLI::App* cmd_keypoint_dist = app.add_subcommand(
"keypoint-distribution",
"Determine the keypoint distribution over all images");
unsigned int image_width = 0;
cmd_keypoint_dist
->add_option("--image-width", image_width,
"The width of the original input images in pixel (check "
"the intrinsic!")
->required()
->check(CLI::Range(65'535));
unsigned int image_height = 0;
cmd_keypoint_dist
->add_option("--image-height", image_height,
"The height of the original input images in pixel (check "
"the intrinsic!")
->required()
->check(CLI::Range(65'535));
optional<string> response_histo;
cmd_keypoint_dist->add_option(
"--response-histo", response_histo,
"Filepath where the keypoint response histogram shall be written to.");
optional<string> size_histo;
cmd_keypoint_dist->add_option(
"--size-histo", size_histo,
"Filepath where the keypoint size histogram shall be written to.");
optional<string> kp_distance_histo;
cmd_keypoint_dist->add_option(
"--kp-distance-histo", kp_distance_histo,
"Filepath where the histogram of the distance to the nearest neighbour "
"of the keypoints shall be written to.");
optional<string> kp_distribution_histo;
cmd_keypoint_dist->add_option(
"--kp-distribution-histo", kp_distribution_histo,
"Filepath where the histogram of the distribution of the keypoints "
"shall be written to.");
CLI::App* cmd_min_dist = app.add_subcommand(
"min-distance", "Calculate the minimum distance of descriptors within "
"one image and analyze that.");
string norm_name = "L2";
cmd_min_dist->add_set("-n,--norm", norm_name,
{"L1", "L2", "L2SQR", "HAMMING", "HAMMING2"},
"Set the norm that shall be used as distance measure",
/*defaulted=*/true);
optional<string> min_distance_histo;
cmd_min_dist->add_option(
"--min-distance-histo", min_distance_histo,
"Write the histogram of minimal descriptor distance to this file");
CLI::App* cmd_matcher = app.add_subcommand(
"matching",
"Analyze the matchability of the descriptors with consecutive images.");
cmd_matcher->add_set("-d,--distance-norm", norm_name,
{"L1", "L2", "L2SQR", "HAMMING", "HAMMING2"},
"Set the norm that shall be used as distance measure",
/*defaulted=*/true);
bool no_crosscheck = false;
cmd_matcher->add_flag("--no-crosscheck", no_crosscheck,
"Disable crosschecking");
optional<string> match_output;
CLI::Option* match_output_opt = cmd_matcher->add_option(
"--match-output", match_output,
"Provide a filename for drawing the matches onto an image.");
optional<string> original_images;
CLI::Option* orig_imgs_opt =
cmd_matcher
->add_option("--original-images", original_images,
"Provide the file pattern for the original image "
"the features were calculated on. Must be provided "
"for plotting.")
->needs(match_output_opt);
match_output_opt->needs(orig_imgs_opt);
optional<string> matched_distance_histo;
cmd_matcher->add_option(
"--matched-distance-histo", matched_distance_histo,
"Write histogram data of the descriptor distance of matches");
CLI::App* cmd_rec_perf = app.add_subcommand(
"recognition-performance",
"Calculate precision and recall for consecutive image matching");
string depth_image_path;
cmd_rec_perf
->add_option("--depth-image", depth_image_path,
"File pattern for the original depth images")
->required();
string pose_file_pattern;
cmd_rec_perf
->add_option("--pose-file", pose_file_pattern,
"File pattern for the poses of each camera-idx.")
->required();
string intrinsic_file;
cmd_rec_perf
->add_option("--intrinsic", intrinsic_file,
"File path to the intrinsic - currently only pinhole!")
->required();
optional<string> mask_file;
cmd_rec_perf->add_option(
"--mask", mask_file,
"Image-mask with intrinsic dimenstion. Every black pixel "
"means the camera has no vision there. White means, the "
"camera sees these pixels. Use for distortion masking."
"(8-bit grayscale png!)");
cmd_rec_perf->add_set("-d,--match-norm", norm_name,
{"L1", "L2", "L2SQR", "HAMMING", "HAMMING2"},
"Set the norm that shall be used as distance measure",
/*defaulted=*/true);
float keypoint_distance_threshold = 3.0F;
cmd_rec_perf->add_option("--keypoint-distance-threshold",
keypoint_distance_threshold,
"Threshold for the reprojection error of "
"keypoints to be considered a correspondence",
/*defaulted=*/true);
optional<string> backproject_pattern;
CLI::Option* backproject_opt = cmd_rec_perf->add_option(
"--backprojection", backproject_pattern,
"Provide a file-pattern to optionally print the "
"backprojection for matched keypoints");
CLI::Option* orig_imgs =
cmd_rec_perf
->add_option("--orig-images", original_images,
"Provide the file pattern for the original image "
"the features were calculated on. Must be provided "
"for plotting.")
->needs(backproject_opt);
backproject_opt->needs(orig_imgs);
unsigned int tp_strength = 6;
cmd_rec_perf
->add_option("--true-positive-strength", tp_strength,
"Line strength to connect two true positive keypoints",
/*defaulted=*/true)
->needs(backproject_opt);
std::vector<unsigned char> tp_rgb{65U, 117U, 5U};
cmd_rec_perf
->add_option("--true-positive-rgb", tp_rgb,
"RGB values [0-255] for true positive line color",
/*defaulted=*/true)
->expected(3)
->needs(backproject_opt);
unsigned int fn_strength = 6;
cmd_rec_perf
->add_option("--false-negative-strength", fn_strength,
"Line strength to connect two false negative keypoints",
/*defaulted=*/true)
->needs(backproject_opt);
std::vector<unsigned char> fn_rgb{144U, 19U, 254U};
cmd_rec_perf
->add_option("--false-negative-rgb", fn_rgb,
"RGB values [0-255] for false negative line color",
/*defaulted=*/true)
->expected(3)
->needs(backproject_opt);
unsigned int fp_strength = 1;
cmd_rec_perf
->add_option("--false-positive-strength", fn_strength,
"Line strength to connect two false positive keypoints",
/*defaulted=*/true)
->needs(backproject_opt);
std::vector<unsigned char> fp_rgb{245U, 166U, 35U};
cmd_rec_perf
->add_option("--false-positive-rgb", fp_rgb,
"RGB values [0-255] for false positive line color",
/*defaulted=*/true)
->expected(3)
->needs(backproject_opt);
optional<string> backprojection_selected_histo;
cmd_rec_perf->add_option("--backprojection-selected-histo",
backprojection_selected_histo,
"File for the histogram of the backprojection "
"error of the selected elements");
optional<string> relevant_histo;
cmd_rec_perf->add_option(
"--relevant-elements-histo", relevant_histo,
"File for the histogram for the number of relevant elements per frame");
optional<string> true_positive_histo;
cmd_rec_perf->add_option(
"--true-positive-histo", true_positive_histo,
"File for the histogram for the number of true positives per frame.");
optional<string> false_positive_histo;
cmd_rec_perf->add_option(
"--false-positive-histo", false_positive_histo,
"File for the histogram for the number of false postives per frame.");
optional<string> true_positive_distance_histo;
cmd_rec_perf->add_option("--true-positive-distance-histo",
true_positive_distance_histo,
"File for the histogram of the descriptor "
"distance for true positives.");
optional<string> false_positive_distance_histo;
cmd_rec_perf->add_option("--false-positive-distance-histo",
false_positive_distance_histo,
"File for the histogram of the descriptor "
"distance for false positives.");
COLORED_APP_PARSE(app, argc, argv);
util::processing_input in{feature_file_input_pattern, start_idx, end_idx};
if (*cmd_min_dist) {
return analyze_min_distance(in, str_to_norm(norm_name), statistics_file,
min_distance_histo);
}
if (*cmd_keypoint_dist)
return analyze_keypoint_distribution(
in, image_width, image_height, statistics_file, response_histo,
size_histo, kp_distance_histo, kp_distribution_histo);
if (*cmd_matcher)
return analyze_matching(in, str_to_norm(norm_name), !no_crosscheck,
statistics_file, matched_distance_histo,
match_output, original_images);
if (*cmd_rec_perf) {
recognition_analysis_input rec_in{
/*depth_image_pattern=*/depth_image_path,
/*pose_file_pattern=*/pose_file_pattern,
/*intrinsic_file=*/intrinsic_file,
/*mask_file=*/mask_file,
/*matching_norm=*/str_to_norm(norm_name),
/*keypoint_distance_threshold=*/keypoint_distance_threshold};
recognition_analysis_output_options out_opts{
/*backproject_pattern=*/backproject_pattern,
/*original_files=*/original_images,
/*stat_file=*/statistics_file,
/*backprojection_selected_histo=*/backprojection_selected_histo,
/*relevant_histo=*/relevant_histo,
/*true_positive_histo=*/true_positive_histo,
/*false_positive_histo=*/false_positive_histo,
/*true_positive_distance_histo=*/true_positive_distance_histo,
/*false_positive_distance_histo=*/false_positive_distance_histo};
backproject_style tp_style(tp_rgb[0], tp_rgb[1], tp_rgb[2],
gsl::narrow<int>(tp_strength));
backproject_style fn_style(fn_rgb[0], fn_rgb[1], fn_rgb[2],
gsl::narrow<int>(fn_strength));
backproject_style fp_style(fp_rgb[0], fp_rgb[1], fp_rgb[2],
gsl::narrow<int>(fp_strength));
return analyze_recognition_performance(in, rec_in, out_opts,
{tp_style, fn_style, fp_style});
}
UNREACHABLE("Expected to end program with " // LCOV_EXCL_LINE
"subcommand processing"); // LCOV_EXCL_LINE
}
MAIN_TAIL
| 44.766234 | 80 | 0.615753 | [
"vector"
] |
b603a2ddd5fe7cf81fcaf66c0b700924b25adef7 | 6,788 | cpp | C++ | Sources/HelloWindow/MainWindow.cpp | maxagon/dx12-sandbox | 88bdfa59e23bb637043694af9f42256b0559f233 | [
"MIT"
] | null | null | null | Sources/HelloWindow/MainWindow.cpp | maxagon/dx12-sandbox | 88bdfa59e23bb637043694af9f42256b0559f233 | [
"MIT"
] | null | null | null | Sources/HelloWindow/MainWindow.cpp | maxagon/dx12-sandbox | 88bdfa59e23bb637043694af9f42256b0559f233 | [
"MIT"
] | null | null | null | #include <memory>
#include <DebugCheck.h>
#include <ShaderCompiler.h>
#include <DeviceConfig.h>
#include <ResourceUploader.h>
#include <CmdListRecording.h>
#include <SDL.h>
#include <d3d12.h>
#include <d3dx12.h>
#include "WindowDX12.h"
class TriangleRenderer : public ICmdListSubRecorder
{
private:
CComPtr<ID3D12PipelineState> mTrianglePso;
CComPtr<ID3D12Resource> mVertexResource;
D3D12_VERTEX_BUFFER_VIEW mVertexView{};
CComPtr<ID3D12Device> mDevice;
std::shared_ptr<DeviceConfig> mDeviceConfig;
public:
TriangleRenderer(CComPtr<ID3D12Device> device, std::shared_ptr<DeviceConfig> deviceConfig)
: mDevice(device)
, mDeviceConfig(deviceConfig)
{}
void CreateResources(IResourceUploader* resourceUploader, ShaderCompiler* shaderCompiler)
{
auto testShaderSource = shaderCompiler->GetShader(L"shaders/TestShader.hlsl");
auto vsBytecode = shaderCompiler->Compile(L"TestShader.hlsl", testShaderSource, ShaderType::VS, L"MainVS");
auto psBytecode = shaderCompiler->Compile(L"TestShader.hlsl", testShaderSource, ShaderType::PS, L"MainPS");
D3D12_INPUT_ELEMENT_DESC geometryFormat[1] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc{};
psoDesc.pRootSignature = mDeviceConfig->GetDefaultRootSig();
psoDesc.VS = CD3DX12_SHADER_BYTECODE(vsBytecode->GetBufferPointer(), vsBytecode->GetBufferSize());
psoDesc.PS = CD3DX12_SHADER_BYTECODE(psBytecode->GetBufferPointer(), psBytecode->GetBufferSize());
psoDesc.InputLayout = { geometryFormat, _countof(geometryFormat) };
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = false;
psoDesc.DepthStencilState.StencilEnable = false;
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.SampleDesc.Count = 1;
DCHECK_COM(mDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mTrianglePso)));
// vertex data
float vertexData[] = {
0.0f, -1.0f, 1.0f,
-1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
auto vertexBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(vertexData));
auto vertexHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
DCHECK_COM(mDevice->CreateCommittedResource(&vertexHeapProperties, D3D12_HEAP_FLAG_NONE,
&vertexBufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&mVertexResource)));
resourceUploader->UploadImmidiate(mVertexResource, vertexData, sizeof(vertexData));
mVertexView.BufferLocation = mVertexResource->GetGPUVirtualAddress();
mVertexView.SizeInBytes = sizeof(vertexData);
mVertexView.StrideInBytes = sizeof(float) * 3;
}
// ICmdListSubRecorder
void Record(ID3D12GraphicsCommandList* destination) override
{
D3D12_RESOURCE_BARRIER barrier;
destination->IASetVertexBuffers(0, 1, &mVertexView);
destination->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
destination->SetGraphicsRootSignature(mDeviceConfig->GetDefaultRootSig());
//float resolution[] = { (float)dx12Window->GetWindowRect().right, (float)dx12Window->GetWindowRect().bottom };
//destination->SetGraphicsRoot32BitConstants(0, 2, resolution, 0);
destination->SetPipelineState(mTrianglePso);
destination->DrawInstanced(3, 1, 0, 0);
}
};
int SDL_main(int argc, char *argv[])
{
DCHECK(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) == 0);
constexpr int32_t screenSizeX = 1024;
constexpr int32_t screenSizeY = 768;
SDL_Window* window = SDL_CreateWindow(
"hello",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
screenSizeX, screenSizeY,
SDL_WINDOW_SHOWN
);
DCHECK(window);
CComPtr<ID3D12Device> device;
DCHECK_COM(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)));
CComPtr<ID3D12Device4> device4;
DCHECK_COM(device->QueryInterface(IID_PPV_ARGS(&device4)));
static constexpr uint32_t backbufferCount = 2;
auto dx12Window = std::make_shared<WindowDX12>(GetActiveWindow(), device, backbufferCount);
auto scheduler = std::make_shared<CmdListScheduler>(device, dx12Window->GetRenderQueue(), backbufferCount);
auto shaderCompiler = std::make_shared<ShaderCompiler>();
auto deviceConfig = std::make_shared<DeviceConfig>(device);
auto resourceUploader = std::make_shared<SimpleResourceUploader>(device4);
TriangleRenderer triangleRenderer(device, deviceConfig);
triangleRenderer.CreateResources(resourceUploader.get(), shaderCompiler.get());
LambdaSubRecorder beginRender([dx12Window](ID3D12GraphicsCommandList* destination)
{
destination->RSSetScissorRects(1, &dx12Window->GetWindowRect());
destination->RSSetViewports(1, &dx12Window->GetViewport());
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(dx12Window->GetCurrentBackbuffer(),
D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
destination->ResourceBarrier(1, &barrier);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = dx12Window->GetCurrentRtvHandle();
destination->OMSetRenderTargets(1, &rtvHandle, false, nullptr);
float clearRGB[] = { 1.0f, 0.3f, 0.1f, 1.0f };
destination->ClearRenderTargetView(rtvHandle, clearRGB, 0, nullptr);
});
LambdaSubRecorder endRender([dx12Window](ID3D12GraphicsCommandList* destination)
{
D3D12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(dx12Window->GetCurrentBackbuffer(),
D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
destination->ResourceBarrier(1, &barrier);
});
std::vector<ICmdListSubRecorder*> renderSequence = { &beginRender, &triangleRenderer, &endRender };
CmdListRecorder recorder(device, renderSequence);
while (true)
{
SDL_Event sdlEvent{};
if (SDL_PollEvent(&sdlEvent))
{
if (sdlEvent.type == SDL_QUIT)
{
break;
}
}
dx12Window->WaitForNextFrame();
scheduler->NewFrame(dx12Window->GetCurrentFrameIndex());
scheduler->Submit(&recorder);
dx12Window->SubmitNextFrame();
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
| 39.929412 | 119 | 0.712876 | [
"vector"
] |
b60b57eea8c8f34902b832724c7c725c3f12382f | 4,661 | cc | C++ | CondFormats/DTObjects/src/DTRangeT0.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CondFormats/DTObjects/src/DTRangeT0.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CondFormats/DTObjects/src/DTRangeT0.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /*
* See header file for a description of this class.
*
* \author Paolo Ronchese INFN Padova
*
*/
//----------------------
// This Class' Header --
//----------------------
#include "CondFormats/DTObjects/interface/DTRangeT0.h"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "CondFormats/DTObjects/interface/DTBufferTree.h"
//---------------
// C++ Headers --
//---------------
#include <iostream>
#include <sstream>
//-------------------
// Initializations --
//-------------------
//----------------
// Constructors --
//----------------
DTRangeT0::DTRangeT0():
dataVersion( " " ),
dBuf(new DTBufferTree<int,int>) {
dataList.reserve( 1000 );
}
DTRangeT0::DTRangeT0( const std::string& version ):
dataVersion( version ),
dBuf(new DTBufferTree<int,int>) {
dataList.reserve( 1000 );
}
DTRangeT0Id::DTRangeT0Id() :
wheelId( 0 ),
stationId( 0 ),
sectorId( 0 ),
slId( 0 ) {
}
DTRangeT0Data::DTRangeT0Data() :
t0min( 0 ),
t0max( 0 ) {
}
//--------------
// Destructor --
//--------------
DTRangeT0::~DTRangeT0() {
}
DTRangeT0Id::~DTRangeT0Id() {
}
DTRangeT0Data::~DTRangeT0Data() {
}
//--------------
// Operations --
//--------------
int DTRangeT0::get( int wheelId,
int stationId,
int sectorId,
int slId,
int& t0min,
int& t0max ) const {
t0min =
t0max = 0;
std::vector<int> chanKey;
chanKey.reserve(4);
chanKey.push_back( wheelId );
chanKey.push_back( stationId );
chanKey.push_back( sectorId );
chanKey.push_back( slId );
int ientry;
//Guarantee const correctness for thread-safety
const DTBufferTree<int,int>* constDBuf = dBuf;
int searchStatus = constDBuf->find( chanKey.begin(), chanKey.end(), ientry );
if ( !searchStatus ) {
const DTRangeT0Data& data( dataList[ientry].second );
t0min = data.t0min;
t0max = data.t0max;
}
return searchStatus;
}
int DTRangeT0::get( const DTSuperLayerId& id,
int& t0min,
int& t0max ) const {
return get( id.wheel(),
id.station(),
id.sector(),
id.superLayer(),
t0min, t0max );
}
const
std::string& DTRangeT0::version() const {
return dataVersion;
}
std::string& DTRangeT0::version() {
return dataVersion;
}
void DTRangeT0::clear() {
dataList.clear();
initialize();
return;
}
int DTRangeT0::set( int wheelId,
int stationId,
int sectorId,
int slId,
int t0min,
int t0max ) {
std::vector<int> chanKey;
chanKey.reserve(4);
chanKey.push_back( wheelId );
chanKey.push_back( stationId );
chanKey.push_back( sectorId );
chanKey.push_back( slId );
int ientry;
int searchStatus = dBuf->find( chanKey.begin(), chanKey.end(), ientry );
if ( !searchStatus ) {
DTRangeT0Data& data( dataList[ientry].second );
data.t0min = t0min;
data.t0max = t0max;
return -1;
}
else {
DTRangeT0Id key;
key. wheelId = wheelId;
key.stationId = stationId;
key. sectorId = sectorId;
key. slId = slId;
DTRangeT0Data data;
data.t0min = t0min;
data.t0max = t0max;
ientry = dataList.size();
dataList.push_back( std::pair<DTRangeT0Id,DTRangeT0Data>( key, data ) );
dBuf->insert( chanKey.begin(), chanKey.end(), ientry );
return 0;
}
return 99;
}
int DTRangeT0::set( const DTSuperLayerId& id,
int t0min,
int t0max ) {
return set( id.wheel(),
id.station(),
id.sector(),
id.superLayer(),
t0min, t0max );
}
DTRangeT0::const_iterator DTRangeT0::begin() const {
return dataList.begin();
}
DTRangeT0::const_iterator DTRangeT0::end() const {
return dataList.end();
}
std::string DTRangeT0::mapName() const {
std::stringstream name;
name << dataVersion << "_map_RangeT0" << this;
return name.str();
}
void DTRangeT0::initialize() {
dBuf->clear();
int entryNum = 0;
int entryMax = dataList.size();
std::vector<int> chanKey;
chanKey.reserve(4);
while ( entryNum < entryMax ) {
const DTRangeT0Id& chan = dataList[entryNum].first;
chanKey.clear();
chanKey.push_back( chan. wheelId );
chanKey.push_back( chan.stationId );
chanKey.push_back( chan. sectorId );
chanKey.push_back( chan. slId );
dBuf->insert( chanKey.begin(), chanKey.end(), entryNum++ );
}
return;
}
| 20.353712 | 79 | 0.552457 | [
"vector"
] |
b60dba68514a44caccc323a78127cf330cbdeb6a | 1,198 | hpp | C++ | engine/source/gom/source/src/Creator.hpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 5 | 2019-02-12T07:23:55.000Z | 2020-06-22T15:03:36.000Z | engine/source/gom/source/src/Creator.hpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | null | null | null | engine/source/gom/source/src/Creator.hpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 2 | 2019-06-17T05:04:21.000Z | 2020-04-22T09:05:57.000Z | #ifndef _CREATOR_HPP
#define _CREATOR_HPP
#include <cstddef>
#include <stdint.h>
/* Creator: this class is used with the Game_object_factory class, to be able to dynamically create objects at runtime
* Every class that wants to register itself with the factory, should have a correspoding Creator class, i.e
* the Zombie class should have a Creator_zombie that inherits from the Creator
*/
namespace math { struct vec3; }
namespace gom { class Game_object; }
namespace physics_2d {struct Body_2d_def; }
class Object;
namespace gom {
class Creator {
public:
Creator() : m_pbody_def(nullptr) {}
virtual ~Creator();
virtual Game_object *create(const Object & pobj_description) = 0;
void set_obj_type(const uint32_t type) { m_obj_type = type; }
uint32_t get_obj_type() const { return m_obj_type; }
void set_obj_tag(const uint32_t tag) { m_obj_tag = tag; }
uint32_t get_obj_tag() const { return m_obj_tag; }
protected:
physics_2d::Body_2d_def *m_pbody_def; // used to create Body_2d for game objects that need physics simulation
uint32_t m_obj_type;
uint32_t m_obj_tag;
};
}
#endif // !_CREATOR_HPP
| 34.228571 | 119 | 0.710351 | [
"object"
] |
b6131dc71990f64d726363414cc47bcc5dfe5069 | 15,742 | cpp | C++ | src/typeset_text.cpp | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | 10 | 2021-11-13T12:39:06.000Z | 2022-03-19T13:40:05.000Z | src/typeset_text.cpp | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | 22 | 2021-11-13T12:57:10.000Z | 2022-03-15T21:42:05.000Z | src/typeset_text.cpp | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | null | null | null | #include "typeset_text.h"
#include "hope_unicode.h"
#include "typeset_construct.h"
#include "typeset_line.h"
#include "typeset_selection.h"
#include "typeset_subphrase.h"
#ifndef HOPE_TYPESET_HEADLESS
#include "typeset_painter.h"
#endif
#include <algorithm>
#include <cassert>
namespace Hope {
namespace Typeset {
#ifdef TYPESET_MEMORY_DEBUG
HOPE_UNORDERED_SET<Text*> Text::all;
Text::Text() {
all.insert(this);
}
Text::~Text() {
all.erase(this);
}
#endif
void Text::setParent(Phrase* p) noexcept{
parent = p;
}
void Text::writeString(std::string& out, size_t& curr) const noexcept {
memcpy(&out[curr], str.data(), numChars());
curr += numChars();
}
void Text::writeString(std::string& out, size_t& curr, size_t pos) const noexcept {
writeString(out, curr, pos, numChars()-pos);
}
void Text::writeString(std::string& out, size_t& curr, size_t pos, size_t len) const noexcept {
memcpy(&out[curr], &str[pos], len);
curr += len;
}
bool Text::isTopLevel() const noexcept{
return parent->isLine();
}
bool Text::isNested() const noexcept{
return !isTopLevel();
}
size_t Text::numChars() const noexcept{
return str.size();
}
bool Text::empty() const noexcept{
return str.empty();
}
void Text::setString(std::string_view str) noexcept {
this->str = str;
}
void Text::setString(const char* ch, size_t sze) noexcept{
str = std::string_view(ch, sze);
}
void Text::append(std::string_view appended) noexcept{
str += appended;
}
void Text::prependSpaces(size_t num_spaces) alloc_except {
#ifndef HOPE_TYPESET_HEADLESS
assert(scriptDepth() == 0);
#endif
str.insert(0, num_spaces, ' ');
}
void Text::removeLeadingSpaces(size_t num_spaces) noexcept {
#ifndef HOPE_TYPESET_HEADLESS
assert(scriptDepth() == 0);
#endif
assert(str.substr(0, num_spaces) == std::string(num_spaces, ' '));
str.erase(0, num_spaces);
}
void Text::overwrite(size_t start, const std::string& in) alloc_except {
str.resize(start + in.size());
std::memcpy(str.data() + start, in.data(), in.size());
}
void Text::overwrite(size_t start, std::string_view in) noexcept{
str.resize(start + in.size());
std::memcpy(str.data() + start, in.data(), in.size());
}
void Text::insert(size_t start, const std::string& in) noexcept{
str.insert(start, in);
}
void Text::erase(size_t start, const std::string& out) noexcept{
assert(view(start, out.size()) == out);
str.erase(start, out.size());
}
std::string_view Text::from(size_t index) const noexcept{
assert(index <= str.size());
return std::string_view(str.data()+index, str.size()-index);
}
std::string_view Text::view(size_t start, size_t sze) const noexcept{
return std::string_view(str.data()+start, sze);
}
const std::string& Text::getString() const noexcept{
return str;
}
char Text::charAt(size_t index) const noexcept{
return str[index];
}
std::string_view Text::codepointAt(size_t index) const noexcept{
return std::string_view(str.data()+index, codepointSize(charAt(index)));
}
std::string_view Text::graphemeAt(size_t index) const noexcept{
return std::string_view(str.data()+index, numBytesInGrapheme(str, index));
}
size_t Text::leadingSpaces() const noexcept{
for(size_t i = 0; i < numChars(); i++)
if(charAt(i) != ' ') return i;
return numChars();
}
std::string_view Text::checkKeyword(size_t iR) const noexcept{
auto slash = str.rfind('\\', iR);
return slash == std::string::npos ?
std::string_view() :
std::string_view(str.data()+slash+1, iR-(slash+1));
}
static constexpr bool notEqual(char a, char b, bool use_case) noexcept{
return a != b && (use_case ||
((a < 'a' || a > 'z' || a - ('a'-'A') != b) &&
(b < 'a' || b > 'z' || b - ('a'-'A') != a)));
}
static constexpr bool alpha(char a) noexcept{
return (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || a == '_';
}
static constexpr bool alphaNumeric(char a) noexcept{
return (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || a == '_' || (a >= '0' && a <= '9');
}
static bool equal(const std::string& target, const std::string& candidate, size_t offset, bool use_case) noexcept {
assert(offset < candidate.size());
assert(target.size() <= candidate.size()-offset);
for(size_t i = target.size(); i-->0;)
if(notEqual(target[i], candidate[i+offset], use_case))
return false;
return true;
}
static bool isWordEnd(const std::string& str, size_t index) noexcept {
return index >= str.size() || !alphaNumeric(str[index]);
}
void Text::search(const std::string& target, std::vector<Selection>& hits, size_t start, size_t end, bool use_case, bool word){
assert(end >= start);
assert(end <= numChars());
assert(!target.empty());
if(target.size() > end-start) return;
size_t stop = end-target.size();
bool word_front = word && alpha(target.front());
bool word_back = word && alphaNumeric(target.back());
//Go to first word
if(word_front && !alpha(str[start])) do{ start++; } while(start <= stop && !alpha(str[start]));
while(start <= stop){
if((!word_back || isWordEnd(str, start+target.size())) && equal(target, str, start, use_case)){
hits.push_back( Selection(this, start, start+target.size()) );
//Go to after the hit
start += target.size();
}else if(word_front){
//Go to the next word
do{ start++; } while(start <= stop && alpha(str[start]));
do{ start++; } while(start <= stop && !alpha(str[start]));
}else{
//Go to the next character
start++;
}
}
}
void Text::search(const std::string& target, std::vector<Selection>& hits, bool use_case, bool word){
return search(target, hits, 0, numChars(), use_case, word);
}
bool Text::precedes(Text* other) const noexcept{
assert(getModel() == other->getModel());
if(parent == other->parent) return id < other->id;
size_t depth = parent->nestingDepth();
size_t other_depth = other->parent->nestingDepth();
while(other_depth > depth){
Construct* c = static_cast<Subphrase*>(other->parent)->parent;
other = c->parent->text(c->id);
other_depth--;
}
if(other->parent == parent) return id <= other->id;
const Text* t = this;
while(depth > other_depth){
Construct* c = static_cast<Subphrase*>(t->parent)->parent;
t = c->parent->text(c->id);
depth--;
}
if(other->parent == t->parent) return t->id < other->id;
while(depth){
Construct* c = static_cast<Subphrase*>(t->parent)->parent;
Construct* other_c = static_cast<Subphrase*>(other->parent)->parent;
if(c == other_c) return t->parent->id < other->parent->id;
t = c->parent->text(c->id);
other = c->parent->text(c->id);
if(other->parent == t->parent) return t->id < other->id;
depth--;
}
return t->parent->id < other->parent->id;
}
const char* Text::data() const noexcept{
return str.data();
}
Phrase* Text::getParent() const noexcept{
//Not great to expose this detail, but I can't find a better way, and it should be stable
return parent;
}
Line* Text::getLine() const noexcept{
Phrase* p = parent;
while(!p->isLine()) p = static_cast<Subphrase*>(p)->parent->parent;
return static_cast<Line*>(p);
}
Model* Text::getModel() const noexcept{
return getLine()->parent;
}
Text* Text::nextTextInPhrase() const noexcept{
return parent->nextTextInPhrase(this);
}
Text* Text::prevTextInPhrase() const noexcept{
return parent->prevTextInPhrase(this);
}
Construct* Text::nextConstructInPhrase() const noexcept{
return parent->nextConstructInPhrase(this);
}
Construct* Text::prevConstructInPhrase() const noexcept{
return parent->prevConstructInPhrase(this);
}
Text* Text::nextTextAsserted() const noexcept{
return parent->nextTextAsserted(this);
}
Text* Text::prevTextAsserted() const noexcept{
return parent->prevTextAsserted(this);
}
Construct* Text::nextConstructAsserted() const noexcept{
return parent->nextConstructAsserted(this);
}
Construct* Text::prevConstructAsserted() const noexcept{
return parent->prevConstructAsserted(this);
}
SemanticType Text::getTypeLeftOf(size_t index) const noexcept{
if(tags.empty() || tags.front().index > index){
return getTypePrev();
}else{
for(auto tag = tags.rbegin(); tag != tags.rend(); tag++)
if(tag->index <= index) return tag->type;
assert(false);
return SEM_DEFAULT;
}
}
SemanticType Text::getTypePrev() const noexcept{
for(Text* t = prevTextInPhrase(); t != nullptr; t = t->prevTextInPhrase()){
assert(t->parent == parent);
if(!t->tags.empty())
return t->tags.back().type;
}
return SEM_DEFAULT;
}
void Text::tag(SemanticType type, size_t start, size_t stop) alloc_except {
assert(std::is_sorted(tags.begin(), tags.end(), [](auto& a, auto& b){return a.index < b.index;}));
SemanticType type_after = getTypeLeftOf(stop);
auto it = std::remove_if(
tags.begin(),
tags.end(),
[start, stop](const SemanticTag& tag) {
return tag.index >= start && tag.index <= stop;
}
);
tags.erase(it, tags.end());
assert(std::is_sorted(tags.begin(), tags.end(), [](auto& a, auto& b){return a.index < b.index;}));
it = tags.begin();
while(it != tags.end() && it->index < start) it++;
tags.insert(it, {SemanticTag(start, type), SemanticTag(stop, type_after)});
assert(std::is_sorted(tags.begin(), tags.end(), [](auto& a, auto& b){return a.index < b.index;}));
}
void Text::tagBack(SemanticType type) alloc_except {
assert(tags.empty() || tags.back().index != numChars());
tags.push_back( SemanticTag(numChars(), type) );
}
#ifdef HOPE_SEMANTIC_DEBUGGING
std::string Text::toSerialWithSemanticTags() const{
size_t start = 0;
std::string out;
for(const SemanticTag& tag : tags){
out += str.substr(start, tag.index-start);
out += "<tag|" + std::to_string(tag.type) + ">";
start = tag.index;
}
out += str.substr(start);
return out;
}
#endif
#ifndef HOPE_TYPESET_HEADLESS
double Text::aboveCenter() const noexcept {
return ABOVE_CENTER[scriptDepth()];
}
double Text::underCenter() const noexcept {
return UNDER_CENTER[scriptDepth()];
}
double Text::height() const noexcept {
return CHARACTER_HEIGHTS[scriptDepth()];
}
double Text::xLocal(size_t index) const noexcept {
return CHARACTER_WIDTHS[scriptDepth()] * countGraphemes(std::string_view(str.data(), index));
}
double Text::xPhrase(size_t index) const{
double left = xLocal(index);
const Text* t = this;
while(Construct* c = t->prevConstructInPhrase()){
left += c->width;
t = c->prev();
left += t->getWidth();
}
return left;
}
double Text::xGlobal(size_t index) const{
return x + xLocal(index);
}
double Text::xRight() const noexcept{
return x + getWidth();
}
double Text::yBot() const noexcept{
return y + height();
}
double Text::getWidth() const noexcept {
return width;
}
void Text::updateWidth() noexcept {
width = CHARACTER_WIDTHS[scriptDepth()] * countGraphemes(str);
}
uint8_t Text::scriptDepth() const noexcept {
return parent->script_level;
}
size_t Text::charIndexNearest(double x_in) const noexcept {
return charIndexLeft(x_in + CHARACTER_WIDTHS[scriptDepth()]/2);
}
size_t Text::charIndexLeft(double x_in) const noexcept {
double grapheme_index = (x_in-x) / CHARACTER_WIDTHS[scriptDepth()];
if(grapheme_index < 0) return 0;
size_t index = 0;
for(size_t i = 0; i < static_cast<size_t>(grapheme_index) && index < numChars(); i++)
index += numBytesInGrapheme(str, index);
return index;
}
void Text::paint(Painter& painter, bool forward) const {
size_t start = 0;
double x = this->x;
double char_width = CHARACTER_WIDTHS[scriptDepth()];
for(const SemanticTag& tag : tags){
std::string_view substr(&str[start], tag.index-start);
painter.drawText(x, y, substr, forward);
x += char_width * countGraphemes(substr);
start = tag.index;
painter.setType(tag.type);
}
painter.drawText(x, y, std::string_view(&str[start], numChars()-start), forward);
}
void Text::paintUntil(Painter& painter, size_t stop, bool forward) const {
size_t start = 0;
double x = this->x;
double char_width = CHARACTER_WIDTHS[scriptDepth()];
for(const SemanticTag& tag : tags){
if(tag.index >= stop) break;
std::string_view substr(&str[start], tag.index-start);
painter.drawText(x, y, substr, forward);
x += char_width * countGraphemes(substr);
start = tag.index;
painter.setType(tag.type);
}
painter.drawText(x, y, std::string_view(&str[start], stop-start), forward);
}
void Text::paintAfter(Painter& painter, size_t start, bool forward) const {
double x = this->x + xLocal(start);
painter.setType(getTypeLeftOf(start));
double char_width = CHARACTER_WIDTHS[scriptDepth()];
for(const SemanticTag& tag : tags){
if(tag.index > start){
std::string_view substr(&str[start], tag.index-start);
painter.drawText(x, y, substr, forward);
x += char_width * countGraphemes(substr);
start = tag.index;
painter.setType(tag.type);
}
}
painter.drawText(x, y, std::string_view(&str[start], numChars()-start), forward);
}
void Text::paintMid(Painter& painter, size_t start, size_t stop, bool forward) const {
painter.setScriptLevel(scriptDepth());
double x = this->x + xLocal(start);
painter.setType(getTypeLeftOf(start));
double char_width = CHARACTER_WIDTHS[scriptDepth()];
for(const SemanticTag& tag : tags){
if(tag.index > start){
if(tag.index >= stop) break;
std::string_view substr(&str[start], tag.index-start);
painter.drawText(x, y, substr, forward);
x += char_width * countGraphemes(substr);
start = tag.index;
painter.setType(tag.type);
}
}
painter.drawText(x, y, std::string_view(&str[start], stop-start), forward);
}
void Text::paintGrouping(Painter& painter, size_t start) const {
assert(start < numChars());
size_t stop = start + codepointSize(str[start]);
painter.setScriptLevel(scriptDepth());
double x = this->x + xLocal(start);
painter.setType(getTypeLeftOf(start));
double char_width = CHARACTER_WIDTHS[scriptDepth()];
for(const SemanticTag& tag : tags){
if(tag.index > start){
if(tag.index >= stop) break;
std::string_view substr(&str[start], tag.index-start);
double width = char_width * countGraphemes(substr);
painter.drawHighlightedGrouping(x, y, width, substr);
x += width;
start = tag.index;
painter.setType(tag.type);
}
}
std::string_view substr(&str[start], stop-start);
double width = char_width * countGraphemes(substr);
painter.drawHighlightedGrouping(x, y, width, substr);
}
bool Text::containsX(double x_test) const noexcept {
return (x_test >= x) & (x_test <= x + getWidth());
}
bool Text::containsY(double y_test) const noexcept {
return (y_test >= y) & (y_test <= y + height());
}
bool Text::containsXInBounds(double x_test, size_t start, size_t stop) const noexcept {
return x_test >= xGlobal(start) && x_test <= xGlobal(stop);
}
#endif
}
}
| 29.424299 | 127 | 0.633846 | [
"vector",
"model"
] |
b6164990179220110c52b736dc63765074cbb1bd | 6,387 | hpp | C++ | inference-engine/tests_deprecated/unit/shape_infer/built_in_shape_infer_general_test.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/tests_deprecated/unit/shape_infer/built_in_shape_infer_general_test.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/tests_deprecated/unit/shape_infer/built_in_shape_infer_general_test.hpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <gtest/gtest.h>
#include <blob_factory.hpp>
#include <shape_infer/built-in/ie_built_in_holder.hpp>
#include <utility>
#include <ie_format_parser.h>
#include <xml_helper.hpp>
#include <single_layer_common.hpp>
#include <tests_common.hpp>
#include "common_test_utils/xml_net_builder/xml_net_builder.hpp"
namespace IE = InferenceEngine;
struct param_size {
// dimensions order: x, y, z, ...
std::vector<unsigned> dims;
param_size() {}
// param_size(const std::vector<unsigned>& dims) {
// this->dims = dims;
// }
param_size(std::initializer_list<unsigned> dims) {
this->dims = dims;
}
bool empty() {
return dims.empty();
}
friend std::ostream &operator<<(std::ostream &os, param_size const ¶mSize) {
auto d_size = paramSize.dims.size();
if (d_size > 0) {
os << "dims[" << std::to_string(0) << "]=" << std::to_string(paramSize.dims[0]);
for (int i = 1; i < paramSize.dims.size(); i++)
os << ", dims[" << std::to_string(i) << "]=" << std::to_string(paramSize.dims[i]);
}
return os;
};
std::string toSeparetedRow(const char *separator) {
auto d_size = dims.size();
std::string res;
if (d_size > 0) {
res = std::to_string(dims[d_size - 1]);
for (int i = d_size - 2; i >= 0; i--) {
res += separator + std::to_string(dims[i]);
}
}
return res;
}
};
PRETTY_PARAM(kernel, param_size);
PRETTY_PARAM(stride, param_size);
PRETTY_PARAM(pad, param_size);
PRETTY_PARAM(pad_end, param_size);
PRETTY_PARAM(auto_pad, std::string);
PRETTY_PARAM(out_channels, unsigned);
PRETTY_PARAM(group, unsigned);
PRETTY_PARAM(dilation_factor, param_size);
PRETTY_PARAM(pool_type, std::string);
PRETTY_PARAM(exclude_pad, bool);
PRETTY_PARAM(LayerType, std::string)
PRETTY_PARAM(LayerDataName, std::string)
PRETTY_PARAM(InOutShapes, CommonTestUtils::InOutShapes)
PRETTY_PARAM(NewInOutShapes, CommonTestUtils::InOutShapes)
PRETTY_PARAM(MapParams, MapStrStr)
PRETTY_PARAM(CanInfer, bool);
PRETTY_PARAM(IsTransposed, bool);
PRETTY_PARAM(TopologyPath, std::string);
PRETTY_PARAM(ModelPath, std::string);
static size_t BATCH = 100;
class BuiltInShapeInferCommon : public TestsCommon {
protected:
void SetUp() override {
holder = std::make_shared<IE::ShapeInfer::BuiltInShapeInferHolder>();
}
IE::IShapeInferImpl::Ptr getShapeInferImpl(const std::string &type) {
IE::IShapeInferImpl::Ptr impl;
sts = holder->getShapeInferImpl(impl, type.c_str(), &resp);
if (sts != IE::StatusCode::OK) THROW_IE_EXCEPTION << resp.msg;
return impl;
}
protected:
IE::StatusCode sts = IE::StatusCode::GENERAL_ERROR;
IE::ResponseDesc resp;
std::shared_ptr<IE::IShapeInferExtension> holder;
};
template<class T>
class BuiltInShapeInferTestWithParam : public BuiltInShapeInferCommon,
public testing::WithParamInterface<T> {
protected:
static std::vector<IE::Blob::CPtr> getBlobs(const std::vector<IE::SizeVector>& shapes) {
std::vector<IE::Blob::CPtr> inBlobs;
for (auto const& dims : shapes) {
IE::TensorDesc desc(IE::Precision::FP32, dims, IE::TensorDesc::getLayoutByDims(dims));
auto blob = make_blob_with_precision(desc);
inBlobs.push_back(blob);
}
return inBlobs;
}
static IE::ICNNNetwork::InputShapes
setInputShapes(const IE::ICNNNetwork &cnnNetwork,
const std::vector<IE::SizeVector> &shapesToSet) {
IE::ICNNNetwork::InputShapes inputShapes;
IE::InputsDataMap inputs;
cnnNetwork.getInputsInfo(inputs);
for (const auto &pair : inputs) {
auto info = pair.second;
if (info) {
auto data = info->getInputData();
if (data) {
inputShapes[data->getName()] = data->getTensorDesc().getDims();
}
}
}
int i = 0;
for (auto &pair : inputShapes) {
pair.second = shapesToSet[i++];
}
return inputShapes;
}
static void checkNetworkInOut(const IE::ICNNNetwork &network,
const CommonTestUtils::InOutShapes &inOutData) {
IE::InputsDataMap inputsDataMap;
IE::OutputsDataMap outputsDataMap;
network.getInputsInfo(inputsDataMap);
network.getOutputsInfo(outputsDataMap);
int i = 0;
for (auto pair : inputsDataMap) {
ASSERT_EQ(inOutData.inDims[i++], pair.second->getTensorDesc().getDims());
}
i = 0;
for (auto pair : outputsDataMap) {
ASSERT_EQ(inOutData.outDims[i++], pair.second->getDims());
}
}
template<int Version = 3>
static IE::details::CNNNetworkImplPtr
buildSingleLayerNetwork(const std::string &layerType,
const CommonTestUtils::InOutShapes &inOutShapes,
std::map<std::string, std::string> *params,
const std::string &layerDataName = "data") {
auto *parser = new IE::details::FormatParser(Version);
return buildSingleLayerNetworkCommon<Version>(parser, layerType, inOutShapes, params, layerDataName);
}
protected:
std::vector<IE::SizeVector> outShapes;
std::map<std::string, std::string> params;
std::map<std::string, IE::Blob::Ptr> blobs;
};
class BuiltInShapeInferImplTest
: public BuiltInShapeInferTestWithParam<std::tuple<LayerType, InOutShapes, NewInOutShapes, MapParams, LayerDataName, CanInfer>> {
protected:
void SetUp() override {
BuiltInShapeInferCommon::SetUp();
auto params = GetParam();
type = std::get<0>(params);
inOutShapes = std::get<1>(params);
newInOutShapes = std::get<2>(params);
layerParams = std::get<3>(params);
layerDataName = std::get<4>(params);
canInfer = std::get<5>(params);
}
protected:
std::string type;
CommonTestUtils::InOutShapes inOutShapes;
CommonTestUtils::InOutShapes newInOutShapes;
MapStrStr layerParams;
std::string layerDataName;
bool canInfer{};
};
| 30.706731 | 137 | 0.626585 | [
"vector"
] |
b6171780da69093c8a15c4e08e34e3a3e4ebde64 | 1,678 | hpp | C++ | code/source/util/arrayview.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/util/arrayview.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/util/arrayview.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #ifndef CLOVER_UTIL_ARRAYVIEW_HPP
#define CLOVER_UTIL_ARRAYVIEW_HPP
#include "build.hpp"
#include "util/class_preproc.hpp"
#include "util/ensure.hpp"
#include "util/traits.hpp"
namespace clover {
namespace util {
/// Non-owning slice of contiguous data
/// Use this instead of 'const std::vector<T>&', because
/// that causes problems with different allocators
template <typename T>
class ArrayView {
public:
ArrayView(T* const begin, T* const end)
: beginPtr(begin)
, endPtr(end){
}
ArrayView(T* const ptr, SizeType size)
: beginPtr(ptr)
, endPtr(ptr + size){
}
DEFAULT_COPY(ArrayView);
DEFAULT_MOVE(ArrayView);
T* begin() const { return beginPtr; }
T* end() const { return endPtr; }
T& operator[](SizeType i) const {
debug_ensure(i < size() || (i == 0 && size() == 0));
return beginPtr[i];
}
bool empty() const { return beginPtr == endPtr; }
SizeType size() const { return endPtr - beginPtr; }
operator ArrayView<const T>() const {
return ArrayView<const T>{beginPtr, endPtr};
}
template <typename U= T, typename= EnableIf<isPtr<U>()>>
operator ArrayView<const RemovePtr<T>*>() const {
return ArrayView<const RemovePtr<T>*>{beginPtr, endPtr};
}
template <typename U= T, typename= EnableIf<isPtr<U>()>>
operator ArrayView<const RemovePtr<T>* const>() const {
return ArrayView<const RemovePtr<T>* const>{beginPtr, endPtr};
}
private:
T* beginPtr;
T* endPtr;
};
template <typename T>
auto asArrayView(const T& t) ->
decltype(ArrayView<RemoveRef<decltype(*t.data())>>(t.data(), t.size())){
return ArrayView<RemoveRef<decltype(*t.data())>>(t.data(), t.size());
}
} // util
} // clover
#endif // CLOVER_UTIL_ARRAYVIEW_HPP
| 23.633803 | 72 | 0.689511 | [
"vector"
] |
b620a0f1380e663617e3b6e3b8fb21809f3a3019 | 1,982 | ipp | C++ | implement/oglplus/enums/hint_option_class.ipp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | implement/oglplus/enums/hint_option_class.ipp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | implement/oglplus/enums/hint_option_class.ipp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | // File implement/oglplus/enums/hint_option_class.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/hint_option.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// 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
//
namespace enums {
template <typename Base, template<HintOption> class Transform>
class EnumToClass<Base, HintOption, Transform>
: public Base
{
private:
Base& _base() { return *this; }
public:
#if defined GL_FASTEST
# if defined Fastest
# pragma push_macro("Fastest")
# undef Fastest
Transform<HintOption::Fastest> Fastest;
# pragma pop_macro("Fastest")
# else
Transform<HintOption::Fastest> Fastest;
# endif
#endif
#if defined GL_NICEST
# if defined Nicest
# pragma push_macro("Nicest")
# undef Nicest
Transform<HintOption::Nicest> Nicest;
# pragma pop_macro("Nicest")
# else
Transform<HintOption::Nicest> Nicest;
# endif
#endif
#if defined GL_DONT_CARE
# if defined DontCare
# pragma push_macro("DontCare")
# undef DontCare
Transform<HintOption::DontCare> DontCare;
# pragma pop_macro("DontCare")
# else
Transform<HintOption::DontCare> DontCare;
# endif
#endif
EnumToClass() { }
EnumToClass(Base&& base)
: Base(std::move(base))
#if defined GL_FASTEST
# if defined Fastest
# pragma push_macro("Fastest")
# undef Fastest
, Fastest(_base())
# pragma pop_macro("Fastest")
# else
, Fastest(_base())
# endif
#endif
#if defined GL_NICEST
# if defined Nicest
# pragma push_macro("Nicest")
# undef Nicest
, Nicest(_base())
# pragma pop_macro("Nicest")
# else
, Nicest(_base())
# endif
#endif
#if defined GL_DONT_CARE
# if defined DontCare
# pragma push_macro("DontCare")
# undef DontCare
, DontCare(_base())
# pragma pop_macro("DontCare")
# else
, DontCare(_base())
# endif
#endif
{ }
};
} // namespace enums
| 22.022222 | 62 | 0.725025 | [
"transform"
] |
b62a5a771cec53cdb6323d4de3ea638122980d01 | 2,401 | cpp | C++ | src/engine/video/vulkan/sdl_window.cpp | spencer-melnick/subspace | db91e0c93aeab8053eecddeb70396c6831990013 | [
"MIT"
] | null | null | null | src/engine/video/vulkan/sdl_window.cpp | spencer-melnick/subspace | db91e0c93aeab8053eecddeb70396c6831990013 | [
"MIT"
] | 3 | 2018-06-15T02:57:39.000Z | 2018-06-16T04:37:21.000Z | src/engine/video/vulkan/sdl_window.cpp | spencer-melnick/subspace | db91e0c93aeab8053eecddeb70396c6831990013 | [
"MIT"
] | null | null | null | #include "sdl_window.hpp"
// STL includes
#include <exception>
// Project includes
#include "engine/util/logger.hpp"
using namespace std;
using namespace subspace;
SdlVulkanWindow::SdlVulkanWindow(const std::string& name, unsigned displayNum, unsigned width,
unsigned height, uint32_t flags) :
name_(name), displayNum_(displayNum), width_(width), height_(height)
{
handle_ = SDL_CreateWindow(name.c_str(),
SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayNum), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayNum),
width, height, flags);
if (handle_ == nullptr) {
logger.logError("SDL error: {}", SDL_GetError());
throw std::runtime_error("Unable to create SDL window");
}
logger.logVerbose("Created SDL window - {}", name_);
}
SdlVulkanWindow::~SdlVulkanWindow() {
SDL_DestroyWindow(handle_);
logger.logVerbose("Destroyed SDL window - {}", name_);
}
SdlVulkanWindow::operator SDL_Window*() const {
return handle_;
}
vector<const char*> SdlVulkanWindow::listRequiredExtensions() const {
unsigned numExtensions;
vector<const char*> extensions;
if (SDL_Vulkan_GetInstanceExtensions(handle_, &numExtensions, nullptr) != SDL_TRUE) {
logger.logError("Cannot get number of required Vulkan extensions - {}", SDL_GetError());
throw std::runtime_error("Failed to get required instance extensions");
}
extensions.resize(numExtensions);
if (SDL_Vulkan_GetInstanceExtensions(handle_, &numExtensions, extensions.data()) != SDL_TRUE) {
logger.logError("Cannot get number of required Vulkan extensions - {}", SDL_GetError());
throw std::runtime_error("Failed to get required instance extensions");
}
for (auto& i : extensions) {
logger.logVerbose("Required extension: {}", i);
}
return extensions;
}
vk::SurfaceKHR SdlVulkanWindow::createSurface(const vk::Instance& instance) const {
VkSurfaceKHR surface;
if (SDL_Vulkan_CreateSurface(handle_, instance, &surface) != SDL_TRUE) {
logger.logError("SDL Error: {}", SDL_GetError());
throw std::runtime_error("Failed to create window surface");
}
return vk::SurfaceKHR(surface);
}
const std::string& SdlVulkanWindow::getName() const {
return name_;
}
unsigned SdlVulkanWindow::getWidth() const {
return width_;
}
unsigned SdlVulkanWindow::getHeight() const {
return height_;
}
| 29.280488 | 99 | 0.702624 | [
"vector"
] |
b62a9cba9f668d61961c0330371497e4a70973f3 | 624 | cc | C++ | cses/1653.cc | kamal1316/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | cses/1653.cc | diegordzr/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | cses/1653.cc | diegordzr/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://cses.fi/problemset/task/1653
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
int n, x;
cin >> n >> x;
vector<int> w(n);
for (int i = 0; i < n; i++) cin >> w[i];
vector<pair<int, int>> best(1 << n, {n + 1, 0});
best[0] = {1, 0};
for (int s = 1; s < (1 << n); s++)
for (int p = 0; p < n; p++)
if (s & (1 << p)) {
auto b = best[s ^ (1 << p)];
if (b.second + w[p] <= x) b.second += w[p];
else
b = {b.first + 1, w[p]};
best[s] = min(best[s], b);
}
cout << best[(1 << n) - 1].first << '\n';
}
| 24.96 | 51 | 0.432692 | [
"vector"
] |
b62b79e74edd7c52bc925617ef54b7db6c6e8c22 | 9,755 | cpp | C++ | src/modules/socket/server/handler.cpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 20 | 2019-12-04T01:28:52.000Z | 2022-03-17T14:09:34.000Z | src/modules/socket/server/handler.cpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 115 | 2020-02-04T21:29:54.000Z | 2022-02-17T13:33:51.000Z | src/modules/socket/server/handler.cpp | DerangedMonkeyNinja/openperf | cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16 | [
"Apache-2.0"
] | 16 | 2019-12-03T16:41:18.000Z | 2021-11-06T04:44:11.000Z | #include "api/api_route_handler.hpp"
#include "api/api_utils.hpp"
#include "config/op_config_utils.hpp"
#include "core/op_core.h"
#include "core/op_uuid.hpp"
#include "framework/utils/overloaded_visitor.hpp"
#include "socket/server/lwip_utils.hpp"
#include "socket/server/pcb_utils.hpp"
#include "lwip/tcpbase.h"
#include <arpa/inet.h>
#include "swagger/v1/model/SocketStats.h"
using namespace swagger::v1::model;
namespace openperf::socket::api {
class handler : public openperf::api::route::handler::registrar<handler>
{
public:
handler(void* context, Pistache::Rest::Router& router);
using request_type = Pistache::Rest::Request;
using response_type = Pistache::Http::ResponseWriter;
void list_socket_stats(const request_type& request, response_type response);
void get_socket_stats(const request_type& request, response_type response);
};
handler::handler(void*, Pistache::Rest::Router& router)
{
using namespace Pistache::Rest::Routes;
Get(router, "/sockets", bind(&handler::list_socket_stats, this));
Get(router, "/sockets/:id", bind(&handler::get_socket_stats, this));
}
using namespace Pistache;
static std::string json_error(int code, std::string_view message)
{
return (
nlohmann::json({{"code", code}, {"message", message.data()}}).dump());
}
/**
* Encode the PCB address as a UUID string.
*/
static std::string encode_pcb_id(const void* pcb)
{
std::array<uint8_t, 16> bytes{};
auto val = reinterpret_cast<uintptr_t>(pcb);
for (int i = bytes.size() - 1; i >= 0 && val; --i, val >>= 8) {
bytes[i] = val & 0xff;
}
return to_string(core::uuid(bytes.data()));
}
/**
* Decode the PCB address from the UUID string.
*/
void* decode_pcb_id(std::string_view id)
{
auto u = core::uuid(id);
uintptr_t pcb_addr = 0;
for (int i = 16 - sizeof(pcb_addr); i < 16; ++i) {
pcb_addr <<= 8;
pcb_addr |= u[i];
}
return reinterpret_cast<void*>(pcb_addr);
}
std::unique_ptr<SocketStats>
make_swagger_socket_stats(const socket::server::socket_pcb_stats& src)
{
auto dst = std::make_unique<SocketStats>();
if (src.id.pid != 0 || src.id.sid != 0) {
dst->setPid(src.id.pid);
dst->setSid(src.id.sid);
}
dst->setId(encode_pcb_id(src.pcb));
dst->setRxqBytes(src.channel_stats.rxq_len);
dst->setTxqBytes(src.channel_stats.txq_len);
const char* ip_str;
char ip_buf[INET_ADDRSTRLEN];
std::visit(utils::overloaded_visitor(
[&](const std::monostate&) { dst->setProtocol("raw"); },
[&](const socket::server::ip_pcb_stats& stats) {
dst->setProtocol("ip");
dst->setIfIndex(stats.if_index);
ip_str = inet_ntop(stats.ip_address_family,
stats.local_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setLocalIpAddress(ip_str);
ip_str = inet_ntop(stats.ip_address_family,
stats.remote_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setRemoteIpAddress(ip_str);
},
[&](const socket::server::tcp_pcb_stats& stats) {
dst->setProtocol("tcp");
dst->setIfIndex(stats.if_index);
ip_str = inet_ntop(stats.ip_address_family,
stats.local_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setLocalIpAddress(ip_str);
ip_str = inet_ntop(stats.ip_address_family,
stats.remote_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setRemoteIpAddress(ip_str);
dst->setLocalPort(stats.local_port);
dst->setRemotePort(stats.remote_port);
dst->setSendQueueLength(stats.snd_queuelen);
dst->setState(tcp_debug_state_str(
static_cast<tcp_state>(stats.state)));
},
[&](const socket::server::udp_pcb_stats& stats) {
dst->setProtocol("udp");
dst->setIfIndex(stats.if_index);
ip_str = inet_ntop(stats.ip_address_family,
stats.local_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setLocalIpAddress(ip_str);
ip_str = inet_ntop(stats.ip_address_family,
stats.remote_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setRemoteIpAddress(ip_str);
dst->setLocalPort(stats.local_port);
dst->setRemotePort(stats.remote_port);
},
[&](const socket::server::raw_pcb_stats& stats) {
dst->setProtocol("raw");
dst->setIfIndex(stats.if_index);
ip_str = inet_ntop(stats.ip_address_family,
stats.local_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setLocalIpAddress(ip_str);
ip_str = inet_ntop(stats.ip_address_family,
stats.remote_ip.data(),
ip_buf,
sizeof(ip_buf))
? ip_buf
: "<?>";
dst->setRemoteIpAddress(ip_str);
dst->setProtocolId(stats.protocol);
},
[&](const socket::server::packet_pcb_stats& stats) {
dst->setProtocol("packet");
dst->setIfIndex(stats.if_index);
dst->setProtocolId(stats.protocol);
}),
src.pcb_stats);
return (dst);
}
void handler::list_socket_stats(const request_type&, response_type response)
{
std::vector<socket::server::socket_pcb_stats> socket_stats;
// PCBs/Sockets need to be accessed from the TCP thread
auto result = socket::server::do_tcpip_call([&socket_stats]() {
socket_stats = socket::server::get_all_socket_pcb_stats();
return ERR_OK;
});
if (result != ERR_OK) {
response.send(
Http::Code::Internal_Server_Error,
json_error(static_cast<int>(result), lwip_strerr(result)));
return;
}
auto sockets = nlohmann::json::array();
std::transform(socket_stats.begin(),
socket_stats.end(),
std::back_inserter(sockets),
[](const auto& stats) {
auto swagger_stats = make_swagger_socket_stats(stats);
return (swagger_stats->toJson());
});
openperf::api::utils::send_chunked_response(
std::move(response), Http::Code::Ok, sockets);
}
void handler::get_socket_stats(const request_type& request,
response_type response)
{
auto id = request.param(":id").as<std::string>();
if (auto res = config::op_config_validate_id_string(id); !res) {
response.send(Http::Code::Not_Found, res.error());
return;
}
void* target_pcb = nullptr;
try {
target_pcb = decode_pcb_id(id);
} catch (const std::exception& e) {
response.send(Http::Code::Bad_Request, e.what());
return;
}
if (!target_pcb) {
response.send(Http::Code::Bad_Request, "");
return;
}
std::vector<socket::server::socket_pcb_stats> socket_stats;
// PCBs/Sockets need to be accessed from the TCP thread
auto result = socket::server::do_tcpip_call([&]() {
socket_stats = socket::server::get_matching_socket_pcb_stats(
[&](auto pcb) { return (pcb == target_pcb); });
return ERR_OK;
});
if (result != ERR_OK) {
response.send(
Http::Code::Internal_Server_Error,
json_error(static_cast<int>(result), lwip_strerr(result)));
return;
}
if (socket_stats.empty()) {
response.send(Http::Code::Not_Found, "");
return;
}
auto swagger_stats = make_swagger_socket_stats(socket_stats[0]);
response.setMime(MIME(Application, Json));
response.send(Http::Code::Ok, swagger_stats->toJson().dump());
}
} // namespace openperf::socket::api
| 38.710317 | 80 | 0.489493 | [
"vector",
"model",
"transform"
] |
b630d9f51c1a079e5ccbc0ef39f4e025db2e1676 | 582 | hpp | C++ | include/libderp/prime1/MREA.hpp | Pwootage/libderp | b6568766dea7509266b0baa34cc96de47c804bfe | [
"MIT"
] | 1 | 2022-03-19T02:44:21.000Z | 2022-03-19T02:44:21.000Z | include/libderp/prime1/MREA.hpp | Pwootage/libderp | b6568766dea7509266b0baa34cc96de47c804bfe | [
"MIT"
] | null | null | null | include/libderp/prime1/MREA.hpp | Pwootage/libderp | b6568766dea7509266b0baa34cc96de47c804bfe | [
"MIT"
] | null | null | null | #ifndef LIBDERP_PRIME1MREA_HPP_HPP
#define LIBDERP_PRIME1MREA_HPP_HPP
#include <libderp/IBinarySerializable.hpp>
#include <libderp/IDataStream.hpp>
#include <cstdint>
#include <glm/mat4x3.hpp>
#include <glm/vec3.hpp>
namespace libderp {
namespace prime1 {
class MREA : public IBinarySerializable {
public:
static constexpr uint32_t MAGIC = 0xDEADBEEF;
static constexpr uint32_t VERSION = 0xF;
MREA(IDataStream &stream);
glm::mat4x3 transform;
// Read/write methods
void writeTo(IDataStream &f) override;
};
}
}
#endif //LIBDERP_PRIME1MREA_HPP_HPP
| 17.636364 | 49 | 0.750859 | [
"transform"
] |
ac0e697d09c0328d7f2e24e86bcb6605a180a2ff | 10,807 | cpp | C++ | runtime/src/atn/SemanticContext.cpp | BlockLink/link-antlr-cpp | 287014e8f51a9243b2ec6de7c89b92cc474a4802 | [
"MIT"
] | null | null | null | runtime/src/atn/SemanticContext.cpp | BlockLink/link-antlr-cpp | 287014e8f51a9243b2ec6de7c89b92cc474a4802 | [
"MIT"
] | null | null | null | runtime/src/atn/SemanticContext.cpp | BlockLink/link-antlr-cpp | 287014e8f51a9243b2ec6de7c89b92cc474a4802 | [
"MIT"
] | null | null | null | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "misc/MurmurHash.h"
#include "support/CPPUtils.h"
#include "support/Arrays.h"
#include "SemanticContext.h"
using namespace antlr4;
using namespace antlr4::atn;
using namespace antlrcpp;
//------------------ Predicate -----------------------------------------------------------------------------------------
SemanticContext::Predicate::Predicate() : Predicate(INVALID_INDEX, INVALID_INDEX, false) {
}
SemanticContext::Predicate::Predicate(size_t ruleIndex, size_t predIndex, bool isCtxDependent)
: ruleIndex(ruleIndex), predIndex(predIndex), isCtxDependent(isCtxDependent) {
}
bool SemanticContext::Predicate::eval(Recognizer *parser, RuleContext *parserCallStack) {
RuleContext *localctx = nullptr;
if (isCtxDependent)
localctx = parserCallStack;
return parser->sempred(localctx, ruleIndex, predIndex);
}
size_t SemanticContext::Predicate::hashCode() const {
size_t hashCode = misc::MurmurHash::initialize();
hashCode = misc::MurmurHash::update(hashCode, ruleIndex);
hashCode = misc::MurmurHash::update(hashCode, predIndex);
hashCode = misc::MurmurHash::update(hashCode, isCtxDependent ? 1 : 0);
hashCode = misc::MurmurHash::finish(hashCode, 3);
return hashCode;
}
bool SemanticContext::Predicate::operator == (const SemanticContext &other) const {
if (this == &other)
return true;
const Predicate *p = dynamic_cast<const Predicate*>(&other);
if (p == nullptr)
return false;
return ruleIndex == p->ruleIndex && predIndex == p->predIndex && isCtxDependent == p->isCtxDependent;
}
std::string SemanticContext::Predicate::toString() const {
return std::string("{") + std::to_string(ruleIndex) + std::string(":") + std::to_string(predIndex) + std::string("}?");
}
//------------------ PrecedencePredicate -------------------------------------------------------------------------------
SemanticContext::PrecedencePredicate::PrecedencePredicate() : precedence(0) {
}
SemanticContext::PrecedencePredicate::PrecedencePredicate(int precedence) : precedence(precedence) {
}
bool SemanticContext::PrecedencePredicate::eval(Recognizer *parser, RuleContext *parserCallStack) {
return parser->precpred(parserCallStack, precedence);
}
Ref<SemanticContext> SemanticContext::PrecedencePredicate::evalPrecedence(Recognizer *parser,
RuleContext *parserCallStack) {
if (parser->precpred(parserCallStack, precedence)) {
return SemanticContext::NONE;
}
else {
return nullptr;
}
}
int SemanticContext::PrecedencePredicate::compareTo(PrecedencePredicate *o) {
return precedence - o->precedence;
}
size_t SemanticContext::PrecedencePredicate::hashCode() const {
size_t hashCode = 1;
hashCode = 31 * hashCode + (size_t)precedence;
return hashCode;
}
bool SemanticContext::PrecedencePredicate::operator == (const SemanticContext &other) const {
if (this == &other)
return true;
const PrecedencePredicate *predicate = dynamic_cast<const PrecedencePredicate *>(&other);
if (predicate == nullptr)
return false;
return precedence == predicate->precedence;
}
std::string SemanticContext::PrecedencePredicate::toString() const {
return "{" + std::to_string(precedence) + ">=prec}?";
}
//------------------ AND -----------------------------------------------------------------------------------------------
SemanticContext::S_AND::S_AND(Ref<SemanticContext> const& a, Ref<SemanticContext> const& b) {
Set operands;
if (is<S_AND>(a)) {
for (auto operand : std::dynamic_pointer_cast<S_AND>(a)->opnds) {
operands.insert(operand);
}
} else {
operands.insert(a);
}
if (is<S_AND>(b)) {
for (auto operand : std::dynamic_pointer_cast<S_AND>(b)->opnds) {
operands.insert(operand);
}
} else {
operands.insert(b);
}
std::vector<Ref<PrecedencePredicate>> precedencePredicates = filterPrecedencePredicates(operands);
if (!precedencePredicates.empty()) {
// interested in the transition with the lowest precedence
auto predicate = [](Ref<PrecedencePredicate> const& a, Ref<PrecedencePredicate> const& b) {
return a->precedence < b->precedence;
};
auto reduced = std::min_element(precedencePredicates.begin(), precedencePredicates.end(), predicate);
operands.insert(*reduced);
}
std::copy(operands.begin(), operands.end(), std::back_inserter(opnds));
}
std::vector<Ref<SemanticContext>> SemanticContext::S_AND::getOperands() const {
return opnds;
}
bool SemanticContext::S_AND::operator == (const SemanticContext &other) const {
if (this == &other)
return true;
const S_AND *context = dynamic_cast<const S_AND *>(&other);
if (context == nullptr)
return false;
return Arrays::equals(opnds, context->opnds);
}
size_t SemanticContext::S_AND::hashCode() const {
return misc::MurmurHash::hashCode(opnds, typeid(S_AND).hash_code());
}
bool SemanticContext::S_AND::eval(Recognizer *parser, RuleContext *parserCallStack) {
for (auto opnd : opnds) {
if (!opnd->eval(parser, parserCallStack)) {
return false;
}
}
return true;
}
Ref<SemanticContext> SemanticContext::S_AND::evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) {
bool differs = false;
std::vector<Ref<SemanticContext>> operands;
for (auto context : opnds) {
Ref<SemanticContext> evaluated = context->evalPrecedence(parser, parserCallStack);
differs |= (evaluated != context);
if (evaluated == nullptr) {
// The AND context is false if any element is false.
return nullptr;
} else if (evaluated != NONE) {
// Reduce the result by skipping true elements.
operands.push_back(evaluated);
}
}
if (!differs) {
return shared_from_this();
}
if (operands.empty()) {
// All elements were true, so the AND context is true.
return NONE;
}
Ref<SemanticContext> result = operands[0];
for (size_t i = 1; i < operands.size(); ++i) {
result = SemanticContext::And(result, operands[i]);
}
return result;
}
std::string SemanticContext::S_AND::toString() const {
std::string tmp;
for (auto var : opnds) {
tmp += var->toString() + " && ";
}
return tmp;
}
//------------------ OR ------------------------------------------------------------------------------------------------
SemanticContext::S_OR::S_OR(Ref<SemanticContext> const& a, Ref<SemanticContext> const& b) {
Set operands;
if (is<S_OR>(a)) {
for (auto operand : std::dynamic_pointer_cast<S_OR>(a)->opnds) {
operands.insert(operand);
}
} else {
operands.insert(a);
}
if (is<S_OR>(b)) {
for (auto operand : std::dynamic_pointer_cast<S_OR>(b)->opnds) {
operands.insert(operand);
}
} else {
operands.insert(b);
}
std::vector<Ref<PrecedencePredicate>> precedencePredicates = filterPrecedencePredicates(operands);
if (!precedencePredicates.empty()) {
// interested in the transition with the highest precedence
auto predicate = [](Ref<PrecedencePredicate> const& a, Ref<PrecedencePredicate> const& b) {
return a->precedence < b->precedence;
};
auto reduced = std::max_element(precedencePredicates.begin(), precedencePredicates.end(), predicate);
operands.insert(*reduced);
}
std::copy(operands.begin(), operands.end(), std::back_inserter(opnds));
}
std::vector<Ref<SemanticContext>> SemanticContext::S_OR::getOperands() const {
return opnds;
}
bool SemanticContext::S_OR::operator == (const SemanticContext &other) const {
if (this == &other)
return true;
const S_OR *context = dynamic_cast<const S_OR *>(&other);
if (context == nullptr)
return false;
return Arrays::equals(opnds, context->opnds);
}
size_t SemanticContext::S_OR::hashCode() const {
return misc::MurmurHash::hashCode(opnds, typeid(S_OR).hash_code());
}
bool SemanticContext::S_OR::eval(Recognizer *parser, RuleContext *parserCallStack) {
for (auto opnd : opnds) {
if (opnd->eval(parser, parserCallStack)) {
return true;
}
}
return false;
}
Ref<SemanticContext> SemanticContext::S_OR::evalPrecedence(Recognizer *parser, RuleContext *parserCallStack) {
bool differs = false;
std::vector<Ref<SemanticContext>> operands;
for (auto context : opnds) {
Ref<SemanticContext> evaluated = context->evalPrecedence(parser, parserCallStack);
differs |= (evaluated != context);
if (evaluated == NONE) {
// The OR context is true if any element is true.
return NONE;
} else if (evaluated != nullptr) {
// Reduce the result by skipping false elements.
operands.push_back(evaluated);
}
}
if (!differs) {
return shared_from_this();
}
if (operands.empty()) {
// All elements were false, so the OR context is false.
return nullptr;
}
Ref<SemanticContext> result = operands[0];
for (size_t i = 1; i < operands.size(); ++i) {
result = SemanticContext::Or(result, operands[i]);
}
return result;
}
std::string SemanticContext::S_OR::toString() const {
std::string tmp;
for(auto var : opnds) {
tmp += var->toString() + " || ";
}
return tmp;
}
//------------------ SemanticContext -----------------------------------------------------------------------------------
const Ref<SemanticContext> SemanticContext::NONE = std::make_shared<Predicate>(INVALID_INDEX, INVALID_INDEX, false);
bool SemanticContext::operator != (const SemanticContext &other) const {
return !(*this == other);
}
Ref<SemanticContext> SemanticContext::evalPrecedence(Recognizer * /*parser*/, RuleContext * /*parserCallStack*/) {
return shared_from_this();
}
Ref<SemanticContext> SemanticContext::And(Ref<SemanticContext> const& a, Ref<SemanticContext> const& b) {
if (!a || a == NONE) {
return b;
}
if (!b || b == NONE) {
return a;
}
Ref<S_AND> result = std::make_shared<S_AND>(a, b);
if (result->opnds.size() == 1) {
return result->opnds[0];
}
return result;
}
Ref<SemanticContext> SemanticContext::Or(Ref<SemanticContext> const& a, Ref<SemanticContext> const& b) {
if (!a) {
return b;
}
if (!b) {
return a;
}
if (a == NONE || b == NONE) {
return NONE;
}
Ref<S_OR> result = std::make_shared<S_OR>(a, b);
if (result->opnds.size() == 1) {
return result->opnds[0];
}
return result;
}
std::vector<Ref<SemanticContext::PrecedencePredicate>> SemanticContext::filterPrecedencePredicates(const Set &collection) {
std::vector<Ref<SemanticContext::PrecedencePredicate>> result;
for (auto context : collection) {
if (antlrcpp::is<PrecedencePredicate>(context)) {
result.push_back(std::dynamic_pointer_cast<PrecedencePredicate>(context));
}
}
return result;
}
| 29.287263 | 123 | 0.658185 | [
"vector"
] |
ac1768d2b3942daba1cdd8221bdc9ca1c55b1c30 | 37,698 | cxx | C++ | main/slideshow/source/engine/slideview.cxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/slideshow/source/engine/slideview.cxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/slideshow/source/engine/slideview.cxx | Alan-love/openoffice | 09be380f1ebba053dbf269468ff884f5d26ce1e4 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <canvas/canvastools.hxx>
#include "eventqueue.hxx"
#include "eventmultiplexer.hxx"
#include "slideview.hxx"
#include "delayevent.hxx"
#include "unoview.hxx"
#include <rtl/instance.hxx>
#include <cppuhelper/basemutex.hxx>
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <comphelper/make_shared_from_uno.hxx>
#include <cppcanvas/spritecanvas.hxx>
#include <cppcanvas/customsprite.hxx>
#include <cppcanvas/vclfactory.hxx>
#include <cppcanvas/basegfxfactory.hxx>
#include <tools/debug.hxx>
#include <basegfx/range/b1drange.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <com/sun/star/presentation/XSlideShow.hpp>
#include <boost/noncopyable.hpp>
#include <boost/bind.hpp>
#include <boost/weak_ptr.hpp>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace com::sun::star;
namespace slideshow {
namespace internal {
namespace {
struct StaticUnitRectPoly : public rtl::StaticWithInit<basegfx::B2DPolygon, StaticUnitRectPoly>
{
basegfx::B2DPolygon operator()()
{
return basegfx::tools::createUnitPolygon();
}
};
/** Sprite entry, to store sprite plus priority
The operator<() defines a strict weak ordering of sprites, sort
key is the sprite priority.
*/
struct SpriteEntry
{
SpriteEntry( const cppcanvas::CustomSpriteSharedPtr& rSprite,
double nPrio ) :
mpSprite( rSprite ),
mnPriority( nPrio )
{
}
bool operator<(const SpriteEntry& rRHS) const
{
return mnPriority < rRHS.mnPriority;
}
boost::weak_ptr< cppcanvas::CustomSprite > mpSprite;
double mnPriority;
};
typedef std::vector< SpriteEntry > SpriteVector;
/** Create a clip polygon for slide views
@param rClip
Clip to set (can be empty)
@param rCanvas
Canvas to create the clip polygon for
@param rUserSize
The size of the view. Note that the returned clip will
<em>always</em> clip to at least the rect defined herein.
@return the view clip polygon, in view coordinates, which is
guaranteed to at least clip to the view size.
*/
basegfx::B2DPolyPolygon createClipPolygon( const basegfx::B2DPolyPolygon& rClip,
const cppcanvas::CanvasSharedPtr& /*rCanvas*/,
const basegfx::B2DSize& rUserSize )
{
// setup canvas clipping
// =====================
// AW: Simplified
const basegfx::B2DRange aClipRange(0, 0, rUserSize.getX(), rUserSize.getY());
if(rClip.count())
{
return basegfx::tools::clipPolyPolygonOnRange(rClip, aClipRange, true, false);
}
else
{
return basegfx::B2DPolyPolygon(basegfx::tools::createPolygonFromRect(aClipRange));
}
}
/** Prepare given clip polygon to be stored as the current clip
Note that this is separate from createClipPolygon(), to allow
SlideView implementations to store this intermediate result
(createClipPolygon() has to be called every time the view size
changes)
*/
basegfx::B2DPolyPolygon prepareClip( const basegfx::B2DPolyPolygon& rClip )
{
basegfx::B2DPolyPolygon aClip( rClip );
// TODO(P2): unnecessary, once XCanvas is correctly handling this
// AW: Should be no longer necessary; tools are now bezier-safe
if( aClip.areControlPointsUsed() )
aClip = basegfx::tools::adaptiveSubdivideByAngle( aClip );
// normalize polygon, preparation for clipping
// in updateCanvas()
aClip = basegfx::tools::correctOrientations(aClip);
aClip = basegfx::tools::solveCrossovers(aClip);
aClip = basegfx::tools::stripNeutralPolygons(aClip);
aClip = basegfx::tools::stripDispensablePolygons(aClip, false);
return aClip;
}
void clearRect( ::cppcanvas::CanvasSharedPtr const& pCanvas,
basegfx::B2IRange const& rArea )
{
// convert clip polygon to device coordinate system
::basegfx::B2DPolyPolygon const* pClipPoly( pCanvas->getClip() );
if( pClipPoly )
{
::basegfx::B2DPolyPolygon aClipPoly( *pClipPoly );
aClipPoly.transform( pCanvas->getTransformation() );
pCanvas->setClip( aClipPoly );
}
// set transformation to identity (->device pixel)
pCanvas->setTransformation( ::basegfx::B2DHomMatrix() );
// #i42440# Fill the _full_ background in
// black. Since we had to extend the bitmap by one
// pixel, and the bitmap is initialized white,
// depending on the slide content a one pixel wide
// line will show to the bottom and the right.
const ::basegfx::B2DPolygon aPoly(
::basegfx::tools::createPolygonFromRect(
basegfx::B2DRange(rArea)));
::cppcanvas::PolyPolygonSharedPtr pPolyPoly(
::cppcanvas::BaseGfxFactory::getInstance().createPolyPolygon( pCanvas,
aPoly ) );
if( pPolyPoly )
{
pPolyPoly->setCompositeOp( cppcanvas::CanvasGraphic::SOURCE );
pPolyPoly->setRGBAFillColor( 0x00000000U );
pPolyPoly->draw();
}
#if defined(VERBOSE) && defined(DBG_UTIL)
::cppcanvas::CanvasSharedPtr pCliplessCanvas( pCanvas->clone() );
pCliplessCanvas->setClip();
if( pCanvas->getClip() )
{
::cppcanvas::PolyPolygonSharedPtr pPolyPoly2(
::cppcanvas::BaseGfxFactory::getInstance().createPolyPolygon( pCliplessCanvas,
*(pCanvas->getClip()) ));
if( pPolyPoly2 )
{
pPolyPoly2->setRGBALineColor( 0x008000FFU );
pPolyPoly2->draw();
}
}
#endif
}
/** Get bounds in pixel
@param rLayerBounds
Bound rect, in user space coordinates
@param rTransformation
User space to device pixel transformation
@return the layer bounds in pixel, extended by one pixel to the
right and bottom
*/
basegfx::B2IRange getLayerBoundsPixel( basegfx::B2DRange const& rLayerBounds,
basegfx::B2DHomMatrix const& rTransformation )
{
::basegfx::B2DRange aTmpRect;
::canvas::tools::calcTransformedRectBounds( aTmpRect,
rLayerBounds,
rTransformation );
if( aTmpRect.isEmpty() )
return ::basegfx::B2IRange();
// #i42440# Returned layer size is one pixel too small, as
// rendering happens one pixel to the right and below the
// actual bound rect.
return ::basegfx::B2IRange( ::basegfx::fround(aTmpRect.getMinX()),
::basegfx::fround(aTmpRect.getMinY()),
::basegfx::fround(aTmpRect.getMaxX()) + 1,
::basegfx::fround(aTmpRect.getMaxY()) + 1 );
}
// ----------------------------------------------------------------
/** Container class for sprites issued by a ViewLayer
This class handles the sprite prioritization issues, that are
needed for layer sprites (e.g. the need to re-prioritize sprites
when the layer changes prio).
*/
class LayerSpriteContainer
{
/** Max fill level of maSprites, before we try to prune it from
deceased sprites
*/
enum{ SPRITE_ULLAGE=256 };
/** All sprites that have been issued by this container (pruned
from time to time, for invalid references). This vector is
kept sorted with increasing sprite priority.
*/
SpriteVector maSprites;
// Priority of this layer, relative to other view layers
basegfx::B1DRange maLayerPrioRange;
double getSpritePriority( std::size_t nSpriteNum ) const
{
// divide the available layer range equally between all
// sprites, assign upper bound of individual sprite range as
// sprite prio (the layer itself gets assigned the lower bound
// of sprite 0's individual range):
//
// | layer 0 | layer 1 | ...
// | sprite 0 | sprite 1 | sprite 0 | sprite 1 | ...
return maLayerPrioRange.getMinimum() + maLayerPrioRange.getRange()*(nSpriteNum+1)/(maSprites.size()+1);
}
/** Rescan sprite vector, and remove deceased sprites (and reset
sprite prio)
@param aBegin
Iterator to the first entry to rescan
*/
void updateSprites()
{
SpriteVector aValidSprites;
// check all sprites for validity and set new priority
SpriteVector::iterator aCurrSprite( maSprites.begin() );
const SpriteVector::iterator aEnd( maSprites.end() );
while( aCurrSprite != aEnd )
{
cppcanvas::CustomSpriteSharedPtr pCurrSprite( aCurrSprite->mpSprite.lock() );
if( pCurrSprite )
{
// only copy still valid sprites over to the refreshed
// sprite vector.
aValidSprites.push_back( *aCurrSprite );
pCurrSprite->setPriority(
getSpritePriority( aValidSprites.size()-1 ));
}
++aCurrSprite;
}
// replace sprite list with pruned one
maSprites.swap( aValidSprites );
}
public:
LayerSpriteContainer() :
maSprites(),
maLayerPrioRange()
{
}
basegfx::B1DRange getLayerPriority() const
{
return maLayerPrioRange;
}
void setLayerPriority( const basegfx::B1DRange& rRange )
{
if( rRange != maLayerPrioRange )
{
maLayerPrioRange = rRange;
// prune and recalc sprite prios
updateSprites();
}
}
void addSprite( const cppcanvas::CustomSpriteSharedPtr& pSprite,
double nPriority )
{
if( !pSprite )
return;
SpriteEntry aEntry( pSprite,nPriority );
// insert new sprite, such that vector stays sorted
SpriteVector::iterator aInsertPos(
maSprites.insert(
std::lower_bound( maSprites.begin(),
maSprites.end(),
aEntry ),
aEntry ));
const std::size_t nNumSprites( maSprites.size() );
if( nNumSprites > SPRITE_ULLAGE ||
maSprites.end() - aInsertPos > 1 )
{
// updateSprites() also updates all sprite prios
updateSprites();
}
else
{
// added sprite to the end, and not too many sprites in
// vector - perform optimized update (only need to set
// prio). This basically caters for the common case of
// iterated character animations, which generate lots of
// sprites, all added to the end.
pSprite->setPriority(
getSpritePriority( nNumSprites-1 ));
}
}
void clear()
{
maSprites.clear();
}
};
// ----------------------------------------------------------------
/** This class provides layers for a slide view
Layers are used to render animations with the correct z order -
because sprites are always in front of the static canvas
background, shapes that must appear <em<before</em> an animation
must also be displayed as a sprite.
Each layer has a priority assigned to it (valid range [0,1]), which
also affects all sprites created for this specific layer - i.e. if
the layer priority changes, the sprites change z order together
with their parent.
*/
class SlideViewLayer : public ViewLayer,
private boost::noncopyable
{
// Smart container for all sprites issued by this layer
mutable LayerSpriteContainer maSpriteContainer;
// Bounds of this layer in user space coordinates
basegfx::B2DRange maLayerBounds;
// Bounds of this layer in device pixel
mutable basegfx::B2IRange maLayerBoundsPixel;
// Current clip polygon in user coordinates
basegfx::B2DPolyPolygon maClip;
// Current size of the view in user coordinates
basegfx::B2DSize maUserSize;
// Current overall view transformation
basegfx::B2DHomMatrix maTransformation;
// 'parent' canvas, this viewlayer is associated with
const cppcanvas::SpriteCanvasSharedPtr mpSpriteCanvas;
/** output surface (necessarily a sprite, won't otherwise be able
to display anything <em>before</em> other sprites)
*/
mutable cppcanvas::CustomSpriteSharedPtr mpSprite;
// actual output canvas retrieved from a sprite
mutable cppcanvas::CanvasSharedPtr mpOutputCanvas;
// ptr back to owning view. needed for isOnView() method
View const* const mpParentView;
public:
/** Create a new layer
@param pCanvas
Sprite canvas to create the layer on
@param rTransform
Initial overall canvas transformation
@param rLayerBounds
Initial layer bounds, in view coordinate system
*/
SlideViewLayer( const cppcanvas::SpriteCanvasSharedPtr& pCanvas,
const basegfx::B2DHomMatrix& rTransform,
const basegfx::B2DRange& rLayerBounds,
const basegfx::B2DSize& rUserSize,
View const* const pParentView) :
maSpriteContainer(),
maLayerBounds(rLayerBounds),
maLayerBoundsPixel(),
maClip(),
maUserSize(rUserSize),
maTransformation(rTransform),
mpSpriteCanvas(pCanvas),
mpSprite(),
mpOutputCanvas(),
mpParentView(pParentView)
{
}
void updateView( const basegfx::B2DHomMatrix& rMatrix,
const basegfx::B2DSize& rUserSize )
{
maTransformation = rMatrix;
maUserSize = rUserSize;
// limit layer bounds to visible screen
maLayerBounds.intersect( basegfx::B2DRange(0.0,
0.0,
maUserSize.getX(),
maUserSize.getY()) );
basegfx::B2IRange const& rNewLayerPixel(
getLayerBoundsPixel(maLayerBounds,
maTransformation) );
if( rNewLayerPixel != maLayerBoundsPixel )
{
// re-gen sprite with new size
mpOutputCanvas.reset();
mpSprite.reset();
}
}
private:
// ViewLayer interface
// ----------------------------------------------
virtual cppcanvas::CustomSpriteSharedPtr createSprite(
const ::basegfx::B2DSize& rSpriteSizePixel,
double nPriority ) const
{
cppcanvas::CustomSpriteSharedPtr pSprite(
mpSpriteCanvas->createCustomSprite( rSpriteSizePixel ) );
maSpriteContainer.addSprite( pSprite,
nPriority );
return pSprite;
}
virtual void setPriority( const basegfx::B1DRange& rRange )
{
OSL_ENSURE( !rRange.isEmpty() &&
rRange.getMinimum() >= 1.0,
"SlideViewLayer::setPriority(): prio MUST be larger than 1.0 (because "
"the background layer already lies there)" );
maSpriteContainer.setLayerPriority( rRange );
if( mpSprite )
mpSprite->setPriority( rRange.getMinimum() );
}
virtual basegfx::B2DHomMatrix getTransformation() const
{
// Offset given transformation by left, top border of given
// range (after transformation through given transformation)
basegfx::B2DRectangle aTmpRect;
canvas::tools::calcTransformedRectBounds( aTmpRect,
maLayerBounds,
maTransformation );
basegfx::B2DHomMatrix aMatrix( maTransformation );
// Add translation according to the origin of aTmpRect. Ignore the
// translation when aTmpRect was not properly initialized.
if ( ! aTmpRect.isEmpty())
{
aMatrix.translate( -basegfx::fround(aTmpRect.getMinX()),
-basegfx::fround(aTmpRect.getMinY()) );
}
return aMatrix;
}
virtual basegfx::B2DHomMatrix getSpriteTransformation() const
{
return maTransformation;
}
virtual void clear() const
{
// keep layer clip
clearRect(getCanvas()->clone(),
maLayerBoundsPixel);
}
virtual void clearAll() const
{
::cppcanvas::CanvasSharedPtr pCanvas( getCanvas()->clone() );
// clear layer clip, to clear whole area
pCanvas->setClip();
clearRect(pCanvas,
maLayerBoundsPixel);
}
virtual bool isOnView(boost::shared_ptr<View> const& rView) const
{
return rView.get() == mpParentView;
}
virtual cppcanvas::CanvasSharedPtr getCanvas() const
{
if( !mpOutputCanvas )
{
if( !mpSprite )
{
maLayerBoundsPixel = getLayerBoundsPixel(maLayerBounds,
maTransformation);
// HACK: ensure at least 1x1 pixel size. clients might
// need an actual canvas (e.g. for bound rect
// calculations) without rendering anything. Better
// solution: introduce something like a reference
// canvas for ViewLayers, which is always available.
if( maLayerBoundsPixel.isEmpty() )
maLayerBoundsPixel = basegfx::B2IRange(0,0,1,1);
const basegfx::B2I64Tuple& rSpriteSize(maLayerBoundsPixel.getRange());
mpSprite = mpSpriteCanvas->createCustomSprite(
basegfx::B2DVector(sal::static_int_cast<sal_Int32>(rSpriteSize.getX()),
sal::static_int_cast<sal_Int32>(rSpriteSize.getY())) );
mpSprite->setPriority(
maSpriteContainer.getLayerPriority().getMinimum() );
#if defined(VERBOSE) && defined(DBG_UTIL)
mpSprite->movePixel(
basegfx::B2DPoint(maLayerBoundsPixel.getMinimum()) +
basegfx::B2DPoint(10,10) );
mpSprite->setAlpha(0.5);
#else
mpSprite->movePixel(
basegfx::B2DPoint(maLayerBoundsPixel.getMinimum()) );
mpSprite->setAlpha(1.0);
#endif
mpSprite->show();
}
ENSURE_OR_THROW( mpSprite,
"SlideViewLayer::getCanvas(): no layer sprite" );
mpOutputCanvas = mpSprite->getContentCanvas();
ENSURE_OR_THROW( mpOutputCanvas,
"SlideViewLayer::getCanvas(): sprite doesn't yield a canvas" );
// new canvas retrieved - setup transformation and clip
mpOutputCanvas->setTransformation( getTransformation() );
mpOutputCanvas->setClip(
createClipPolygon( maClip,
mpOutputCanvas,
maUserSize ));
}
return mpOutputCanvas;
}
virtual void setClip( const basegfx::B2DPolyPolygon& rClip )
{
basegfx::B2DPolyPolygon aNewClip = prepareClip( rClip );
if( aNewClip != maClip )
{
maClip = aNewClip;
if(mpOutputCanvas )
mpOutputCanvas->setClip(
createClipPolygon( maClip,
mpOutputCanvas,
maUserSize ));
}
}
virtual bool resize( const ::basegfx::B2DRange& rArea )
{
const bool bRet( maLayerBounds != rArea );
maLayerBounds = rArea;
updateView( maTransformation,
maUserSize );
return bRet;
}
};
// ---------------------------------------------------------
typedef cppu::WeakComponentImplHelper2<
::com::sun::star::util::XModifyListener,
::com::sun::star::awt::XPaintListener> SlideViewBase;
/** SlideView class
This class implements the View interface, encapsulating
<em>one</em> view a slideshow is displayed on.
*/
class SlideView : private cppu::BaseMutex,
public SlideViewBase,
public UnoView
{
public:
SlideView( const uno::Reference<presentation::XSlideShowView>& xView,
EventQueue& rEventQueue,
EventMultiplexer& rEventMultiplexer );
void updateCanvas();
private:
// View:
virtual ViewLayerSharedPtr createViewLayer( const basegfx::B2DRange& rLayerBounds ) const;
virtual bool updateScreen() const;
virtual bool paintScreen() const;
virtual void setViewSize( const ::basegfx::B2DSize& );
virtual void setCursorShape( sal_Int16 nPointerShape );
// ViewLayer interface
virtual bool isOnView(boost::shared_ptr<View> const& rView) const;
virtual void clear() const;
virtual void clearAll() const;
virtual cppcanvas::CanvasSharedPtr getCanvas() const;
virtual cppcanvas::CustomSpriteSharedPtr createSprite( const ::basegfx::B2DSize& rSpriteSizePixel,
double nPriority ) const;
virtual void setPriority( const basegfx::B1DRange& rRange );
virtual ::basegfx::B2DHomMatrix getTransformation() const;
virtual basegfx::B2DHomMatrix getSpriteTransformation() const;
virtual void setClip( const ::basegfx::B2DPolyPolygon& rClip );
virtual bool resize( const ::basegfx::B2DRange& rArea );
// UnoView:
virtual void _dispose();
virtual uno::Reference<presentation::XSlideShowView> getUnoView()const;
virtual void setIsSoundEnabled (const bool bValue);
virtual bool isSoundEnabled (void) const;
// XEventListener:
virtual void SAL_CALL disposing( lang::EventObject const& evt )
throw (uno::RuntimeException);
// XModifyListener:
virtual void SAL_CALL modified( const lang::EventObject& aEvent )
throw (uno::RuntimeException);
// XPaintListener:
virtual void SAL_CALL windowPaint( const awt::PaintEvent& e )
throw (uno::RuntimeException);
// WeakComponentImplHelperBase:
virtual void SAL_CALL disposing();
void updateClip();
private:
typedef std::vector< boost::weak_ptr<SlideViewLayer> > ViewLayerVector;
// Prune viewlayers from deceased ones, optionally update them
void pruneLayers( bool bWithViewLayerUpdate=false ) const;
/** Max fill level of maViewLayers, before we try to prune it from
deceased layers
*/
enum{ LAYER_ULLAGE=8 };
uno::Reference<presentation::XSlideShowView> mxView;
cppcanvas::SpriteCanvasSharedPtr mpCanvas;
EventMultiplexer& mrEventMultiplexer;
EventQueue& mrEventQueue;
mutable LayerSpriteContainer maSprites;
mutable ViewLayerVector maViewLayers;
basegfx::B2DPolyPolygon maClip;
basegfx::B2DHomMatrix maViewTransform;
basegfx::B2DSize maUserSize;
bool mbIsSoundEnabled;
};
SlideView::SlideView( const uno::Reference<presentation::XSlideShowView>& xView,
EventQueue& rEventQueue,
EventMultiplexer& rEventMultiplexer ) :
SlideViewBase( m_aMutex ),
mxView( xView ),
mpCanvas(),
mrEventMultiplexer( rEventMultiplexer ),
mrEventQueue( rEventQueue ),
maSprites(),
maViewLayers(),
maClip(),
maViewTransform(),
maUserSize( 1.0, 1.0 ), // default size: one-by-one rectangle
mbIsSoundEnabled(true)
{
// take care not constructing any UNO references to this _inside_
// ctor, shift that code to createSlideView()!
ENSURE_OR_THROW( mxView.is(),
"SlideView::SlideView(): Invalid view" );
mpCanvas = cppcanvas::VCLFactory::getInstance().createSpriteCanvas(
xView->getCanvas() );
ENSURE_OR_THROW( mpCanvas,
"Could not create cppcanvas" );
geometry::AffineMatrix2D aViewTransform(
xView->getTransformation() );
if( basegfx::fTools::equalZero(
basegfx::B2DVector(aViewTransform.m00,
aViewTransform.m10).getLength()) ||
basegfx::fTools::equalZero(
basegfx::B2DVector(aViewTransform.m01,
aViewTransform.m11).getLength()) )
{
OSL_ENSURE( false,
"SlideView::SlideView(): Singular matrix!" );
canvas::tools::setIdentityAffineMatrix2D(aViewTransform);
}
basegfx::unotools::homMatrixFromAffineMatrix(
maViewTransform, aViewTransform );
// once and forever: set fixed prio to this 'layer' (we're always
// the background layer)
maSprites.setLayerPriority( basegfx::B1DRange(0.0,1.0) );
}
void SlideView::disposing()
{
osl::MutexGuard aGuard( m_aMutex );
maViewLayers.clear();
maSprites.clear();
mpCanvas.reset();
// additionally, also de-register from XSlideShowView
if (mxView.is())
{
mxView->removeTransformationChangedListener( this );
mxView->removePaintListener( this );
mxView.clear();
}
}
ViewLayerSharedPtr SlideView::createViewLayer( const basegfx::B2DRange& rLayerBounds ) const
{
osl::MutexGuard aGuard( m_aMutex );
ENSURE_OR_THROW( mpCanvas,
"SlideView::createViewLayer(): Disposed" );
const std::size_t nNumLayers( maViewLayers.size() );
// avoid filling up layer vector with lots of deceased layer weak
// ptrs
if( nNumLayers > LAYER_ULLAGE )
pruneLayers();
boost::shared_ptr<SlideViewLayer> pViewLayer( new SlideViewLayer(mpCanvas,
getTransformation(),
rLayerBounds,
maUserSize,
this) );
maViewLayers.push_back( pViewLayer );
return pViewLayer;
}
bool SlideView::updateScreen() const
{
osl::MutexGuard aGuard( m_aMutex );
ENSURE_OR_RETURN_FALSE( mpCanvas.get(),
"SlideView::updateScreen(): Disposed" );
return mpCanvas->updateScreen( false );
}
bool SlideView::paintScreen() const
{
osl::MutexGuard aGuard( m_aMutex );
ENSURE_OR_RETURN_FALSE( mpCanvas.get(),
"SlideView::paintScreen(): Disposed" );
return mpCanvas->updateScreen( true );
}
void SlideView::clear() const
{
osl::MutexGuard aGuard( m_aMutex );
OSL_ENSURE( mxView.is() && mpCanvas,
"SlideView::clear(): Disposed" );
if( !mxView.is() || !mpCanvas )
return;
// keep layer clip
clearRect(getCanvas()->clone(),
getLayerBoundsPixel(
basegfx::B2DRange(0,0,
maUserSize.getX(),
maUserSize.getY()),
getTransformation()));
}
void SlideView::clearAll() const
{
osl::MutexGuard aGuard( m_aMutex );
OSL_ENSURE( mxView.is() && mpCanvas,
"SlideView::clear(): Disposed" );
if( !mxView.is() || !mpCanvas )
return;
// clear whole view
mxView->clear();
}
void SlideView::setViewSize( const basegfx::B2DSize& rSize )
{
osl::MutexGuard aGuard( m_aMutex );
maUserSize = rSize;
updateCanvas();
}
void SlideView::setCursorShape( sal_Int16 nPointerShape )
{
osl::MutexGuard const guard( m_aMutex );
if (mxView.is())
mxView->setMouseCursor( nPointerShape );
}
bool SlideView::isOnView(boost::shared_ptr<View> const& rView) const
{
return rView.get() == this;
}
cppcanvas::CanvasSharedPtr SlideView::getCanvas() const
{
osl::MutexGuard aGuard( m_aMutex );
ENSURE_OR_THROW( mpCanvas,
"SlideView::getCanvas(): Disposed" );
return mpCanvas;
}
cppcanvas::CustomSpriteSharedPtr SlideView::createSprite(
const basegfx::B2DSize& rSpriteSizePixel,
double nPriority ) const
{
osl::MutexGuard aGuard( m_aMutex );
ENSURE_OR_THROW( mpCanvas, "SlideView::createSprite(): Disposed" );
cppcanvas::CustomSpriteSharedPtr pSprite(
mpCanvas->createCustomSprite( rSpriteSizePixel ) );
maSprites.addSprite( pSprite,
nPriority );
return pSprite;
}
void SlideView::setPriority( const basegfx::B1DRange& /*rRange*/ )
{
osl::MutexGuard aGuard( m_aMutex );
OSL_ENSURE( false,
"SlideView::setPriority() is a NOOP for slide view - "
"content will always be shown in the background" );
}
basegfx::B2DHomMatrix SlideView::getTransformation() const
{
osl::MutexGuard aGuard( m_aMutex );
basegfx::B2DHomMatrix aMatrix;
aMatrix.scale( 1.0/maUserSize.getX(), 1.0/maUserSize.getY() );
return maViewTransform * aMatrix;
}
basegfx::B2DHomMatrix SlideView::getSpriteTransformation() const
{
return getTransformation();
}
void SlideView::setClip( const basegfx::B2DPolyPolygon& rClip )
{
osl::MutexGuard aGuard( m_aMutex );
basegfx::B2DPolyPolygon aNewClip = prepareClip( rClip );
if( aNewClip != maClip )
{
maClip = aNewClip;
updateClip();
}
}
bool SlideView::resize( const ::basegfx::B2DRange& /*rArea*/ )
{
osl::MutexGuard aGuard( m_aMutex );
OSL_ENSURE( false,
"SlideView::resize(): ignored for the View, can't change size "
"effectively, anyway" );
return false;
}
uno::Reference<presentation::XSlideShowView> SlideView::getUnoView() const
{
osl::MutexGuard aGuard( m_aMutex );
return mxView;
}
void SlideView::setIsSoundEnabled (const bool bValue)
{
mbIsSoundEnabled = bValue;
}
bool SlideView::isSoundEnabled (void) const
{
return mbIsSoundEnabled;
}
void SlideView::_dispose()
{
dispose();
}
// XEventListener
void SlideView::disposing( lang::EventObject const& evt )
throw (uno::RuntimeException)
{
(void)evt;
// no deregistration necessary anymore, XView has left:
osl::MutexGuard const guard( m_aMutex );
if (mxView.is())
{
OSL_ASSERT( evt.Source == mxView );
mxView.clear();
}
dispose();
}
// XModifyListener
void SlideView::modified( const lang::EventObject& /*aEvent*/ )
throw (uno::RuntimeException)
{
osl::MutexGuard const guard( m_aMutex );
OSL_ENSURE( mxView.is(), "SlideView::modified(): "
"Disposed, but event received from XSlideShowView?!");
if( !mxView.is() )
return;
geometry::AffineMatrix2D aViewTransform(
mxView->getTransformation() );
if( basegfx::fTools::equalZero(
basegfx::B2DVector(aViewTransform.m00,
aViewTransform.m10).getLength()) ||
basegfx::fTools::equalZero(
basegfx::B2DVector(aViewTransform.m01,
aViewTransform.m11).getLength()) )
{
OSL_ENSURE( false,
"SlideView::modified(): Singular matrix!" );
canvas::tools::setIdentityAffineMatrix2D(aViewTransform);
}
// view transformation really changed?
basegfx::B2DHomMatrix aNewTransform;
basegfx::unotools::homMatrixFromAffineMatrix(
aNewTransform,
aViewTransform );
if( aNewTransform == maViewTransform )
return; // No change, nothing to do
maViewTransform = aNewTransform;
updateCanvas();
// notify view change. Don't call EventMultiplexer directly, this
// might not be the main thread!
mrEventQueue.addEvent(
makeEvent( boost::bind( (bool (EventMultiplexer::*)(
const uno::Reference<presentation::XSlideShowView>&))
&EventMultiplexer::notifyViewChanged,
boost::ref(mrEventMultiplexer), mxView ),
"EventMultiplexer::notifyViewChanged"));
}
// XPaintListener
void SlideView::windowPaint( const awt::PaintEvent& /*e*/ )
throw (uno::RuntimeException)
{
osl::MutexGuard aGuard( m_aMutex );
OSL_ENSURE( mxView.is() && mpCanvas, "Disposed, but event received?!" );
// notify view clobbering. Don't call EventMultiplexer directly,
// this might not be the main thread!
mrEventQueue.addEvent(
makeEvent( boost::bind( &EventMultiplexer::notifyViewClobbered,
boost::ref(mrEventMultiplexer), mxView ),
"EventMultiplexer::notifyViewClobbered") );
}
void SlideView::updateCanvas()
{
OSL_ENSURE( mpCanvas,
"SlideView::updateCanvasTransform(): Disposed" );
if( !mpCanvas || !mxView.is())
return;
mpCanvas->clear(); // this is unnecessary, strictly speaking. but
// it makes the SlideView behave exactly like a
// sprite-based SlideViewLayer, because those
// are created from scratch after a resize
clearAll();
mpCanvas->setTransformation( getTransformation() );
mpCanvas->setClip(
createClipPolygon( maClip,
mpCanvas,
maUserSize ));
// forward update to viewlayers
pruneLayers( true );
}
void SlideView::updateClip()
{
OSL_ENSURE( mpCanvas,
"SlideView::updateClip(): Disposed" );
if( !mpCanvas )
return;
mpCanvas->setClip(
createClipPolygon( maClip,
mpCanvas,
maUserSize ));
pruneLayers( false );
}
void SlideView::pruneLayers( bool bWithViewLayerUpdate ) const
{
ViewLayerVector aValidLayers;
const basegfx::B2DHomMatrix& rCurrTransform(
getTransformation() );
// check all layers for validity, and retain only the live ones
ViewLayerVector::const_iterator aCurr( maViewLayers.begin() );
const ViewLayerVector::const_iterator aEnd( maViewLayers.end() );
while( aCurr != aEnd )
{
boost::shared_ptr< SlideViewLayer > pCurrLayer( aCurr->lock() );
if( pCurrLayer )
{
aValidLayers.push_back( pCurrLayer );
if( bWithViewLayerUpdate )
pCurrLayer->updateView( rCurrTransform,
maUserSize );
}
++aCurr;
}
// replace layer list with pruned one
maViewLayers.swap( aValidLayers );
}
} // anonymous namespace
UnoViewSharedPtr createSlideView( uno::Reference< presentation::XSlideShowView> const& xView,
EventQueue& rEventQueue,
EventMultiplexer& rEventMultiplexer )
{
boost::shared_ptr<SlideView> const that(
comphelper::make_shared_from_UNO(
new SlideView(xView,
rEventQueue,
rEventMultiplexer)));
// register listeners with XSlideShowView
xView->addTransformationChangedListener( that.get() );
xView->addPaintListener( that.get() );
// set new transformation
that->updateCanvas();
return that;
}
} // namespace internal
} // namespace slideshow
| 31.572864 | 111 | 0.594673 | [
"geometry",
"render",
"vector",
"transform"
] |
ac213eef6644eab76f5f1df6f81e9a74db20b94e | 7,909 | cpp | C++ | src/Plugins/OpenGL/Window/GLWindow.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | 2 | 2021-07-14T06:05:48.000Z | 2021-07-14T18:07:18.000Z | src/Plugins/OpenGL/Window/GLWindow.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | src/Plugins/OpenGL/Window/GLWindow.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
// The MIT License (MIT)
// This source file is part of LORE
// ( Lightweight Object-oriented Rendering Engine )
//
// Copyright (c) 2017-2021 Jordan Sparks
//
// 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 "GLWindow.h"
#include "CallbackHandler.h"
#include "imgui.h"
#include <LORE/Core/APIVersion.h>
#include <LORE/Core/NotificationCenter.h>
#include <LORE/UI/UI.h>
#include <Plugins/OpenGL/Resource/GLResourceController.h>
#include <Plugins/OpenGL/Resource/GLStockResource.h>
#include <UI/imgui_impl_glfw.h>
#include <UI/imgui_impl_opengl3.h>
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
using namespace Lore::OpenGL;
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
GLWindow::GLWindow()
: _window( nullptr )
{
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
GLWindow::~GLWindow()
{
glfwDestroyWindow( _window );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::init( const string& title,
const int width,
const int height,
const Lore::RendererType rendererTypeMask )
{
_title = title;
Window::setDimensions( width, height );
_window = glfwCreateWindow( _dimensions.width,
_dimensions.height,
_title.c_str(),
nullptr,
nullptr );
// Store user pointer to Lore Window class for callbacks.
glfwSetWindowUserPointer( _window, reinterpret_cast< void* >( this ) );
// Store frame buffer size.
glfwGetFramebufferSize( _window, &_frameBufferWidth, &_frameBufferHeight );
_aspectRatio = static_cast< float >( _frameBufferWidth ) / _frameBufferHeight;
// Setup callbacks.
glfwSetWindowSizeCallback( _window, WindowCallbackHandler::Size );
// Create a resource controller for each window.
_controller = std::make_unique<GLResourceController>();
// Create stock resources as well (make this window's context active
// and then restore the previous one).
GLFWwindow* currentContext = glfwGetCurrentContext();
glfwMakeContextCurrent( _window );
_stockController = std::make_unique<GLStockResourceController>();
_stockController->createStockResources();
// Create stock resources needed for this window given the expected renderer type(s).
// TODO: Use configuration setting to initialize renderer type(s).
_stockController->createRendererStockResources( RendererType::Forward2D );
_stockController->createRendererStockResources( RendererType::Forward3D );
glfwMakeContextCurrent( currentContext );
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL( _window, false );
const string glsl_version = "#version " +
std::to_string( APIVersion::GetMajor() ) + std::to_string( APIVersion::GetMinor() ) + "0" +
" core\n";
ImGui_ImplOpenGL3_Init( glsl_version.c_str() );
#ifdef LORE_DEBUG_UI
_debugUI->setImGuiContext( ImGui::GetCurrentContext() );
#endif
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::renderFrame()
{
if ( glfwWindowShouldClose( _window ) ) {
// Post window closed event.
WindowEventNotification n;
n.event = WindowEventNotification::Event::Closed;
n.window = this;
NotificationCenter::Post<WindowEventNotification>( n );
return;
}
// Render each Scene with the corresponding RenderView data.
for ( const RenderView& rv : _renderViews ) {
RendererPtr renderer = rv.scene->getRenderer();
renderer->present( rv, this );
}
// TODO: Custom UIs.
#ifdef LORE_DEBUG_UI
// Start the Dear ImGui frame
if ( _debugUI->getEnabled() ) {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
_debugUI->render( ImGui::GetCurrentContext() );
ImGui::Render();
glfwMakeContextCurrent( _window );
ImGui_ImplOpenGL3_RenderDrawData( ImGui::GetDrawData() );
}
#endif
glfwMakeContextCurrent( _window );
glfwSwapBuffers( _window );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::addRenderView( const Lore::RenderView& renderView )
{
// Convert Viewport to gl_viewport.
RenderView rv = renderView;
Rect vp = rv.viewport;
rv.gl_viewport.x = static_cast< int >( vp.x * static_cast< float >( _frameBufferWidth ) );
rv.gl_viewport.y = static_cast< int >( vp.y * static_cast< float >( _frameBufferHeight ) );
rv.gl_viewport.width = static_cast< int >( vp.w * static_cast< float >( _frameBufferWidth ) );
rv.gl_viewport.height = static_cast< int >( vp.h * static_cast< float >( _frameBufferHeight ) );
rv.gl_viewport.aspectRatio = static_cast< real >( rv.gl_viewport.width ) / rv.gl_viewport.height;
Lore::Window::addRenderView( rv );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::setTitle( const string& title )
{
Lore::Window::setTitle( title );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::setDimensions( const int width, const int height )
{
if ( 0 == width && 0 == height ) {
return; // This can happen when hitting Windows + D for example.
}
Lore::Window::setDimensions( width, height );
glfwSetWindowSize( _window, width, height );
// Store frame buffer size.
glfwGetFramebufferSize( _window, &_frameBufferWidth, &_frameBufferHeight );
_aspectRatio = static_cast< float >( _frameBufferWidth ) / _frameBufferHeight;
updateRenderViews();
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::setActive()
{
glfwMakeContextCurrent( _window );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLWindow::updateRenderViews()
{
for ( auto& rv : _renderViews ) {
rv.gl_viewport.x = static_cast< int >( rv.viewport.x * static_cast< float >( _frameBufferWidth ) );
rv.gl_viewport.y = static_cast< int >( rv.viewport.y * static_cast< float >( _frameBufferHeight ) );
rv.gl_viewport.width = static_cast< int >( rv.viewport.w * static_cast< float >( _frameBufferWidth ) );
rv.gl_viewport.height = static_cast< int >( rv.viewport.h * static_cast< float >( _frameBufferHeight ) );
// Resize post-processing render targets.
if ( rv.camera->postProcessing ) {
const u32 sampleCount = rv.camera->postProcessing->renderTarget->_sampleCount;
rv.camera->initPostProcessing( rv.gl_viewport.width, rv.gl_viewport.height, sampleCount );
}
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
| 34.688596 | 109 | 0.616386 | [
"render",
"object"
] |
ac2c3dac56719c2aefe17c7ffcba54834b0163c7 | 2,217 | hpp | C++ | modules/tracking/src/trackerCSRTSegmentation.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/tracking/src/trackerCSRTSegmentation.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/tracking/src/trackerCSRTSegmentation.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_TRACKER_CSRT_SEGMENTATION
#define OPENCV_TRACKER_CSRT_SEGMENTATION
namespace cv
{
class Histogram
{
public:
int m_numBinsPerDim;
int m_numDim;
Histogram() : m_numBinsPerDim(0), m_numDim(0) {}
Histogram(int numDimensions, int numBinsPerDimension = 8);
void extractForegroundHistogram(std::vector<cv::Mat> & imgChannels,
cv::Mat weights, bool useMatWeights, int x1, int y1, int x2, int y2);
void extractBackGroundHistogram(std::vector<cv::Mat> & imgChannels,
int x1, int y1, int x2, int y2, int outer_x1, int outer_y1,
int outer_x2, int outer_y2);
cv::Mat backProject(std::vector<cv::Mat> & imgChannels);
std::vector<double> getHistogramVector();
void setHistogramVector(double *vector);
private:
int p_size;
std::vector<double> p_bins;
std::vector<int> p_dimIdCoef;
inline double kernelProfile_Epanechnikov(double x)
{ return (x <= 1) ? (2.0/CV_PI)*(1-x) : 0; }
};
class Segment
{
public:
static std::pair<cv::Mat, cv::Mat> computePosteriors(std::vector<cv::Mat> & imgChannels,
int x1, int y1, int x2, int y2, cv::Mat weights, cv::Mat fgPrior,
cv::Mat bgPrior, const Histogram &fgHistPrior, int numBinsPerChannel = 16);
static std::pair<cv::Mat, cv::Mat> computePosteriors2(std::vector<cv::Mat> & imgChannels,
int x1, int y1, int x2, int y2, double p_b, cv::Mat fgPrior,
cv::Mat bgPrior, Histogram hist_target, Histogram hist_background);
static std::pair<cv::Mat, cv::Mat> computePosteriors2(std::vector<cv::Mat> &imgChannels,
cv::Mat fgPrior, cv::Mat bgPrior, Histogram hist_target, Histogram hist_background);
private:
static std::pair<cv::Mat, cv::Mat> getRegularizedSegmentation(cv::Mat & prob_o,
cv::Mat & prob_b, cv::Mat &prior_o, cv::Mat &prior_b);
inline static double gaussian(double x2, double y2, double std2){
return exp(-(x2 + y2)/(2*std2))/(2*CV_PI*std2);
}
};
}//cv namespace
#endif
| 36.95 | 96 | 0.67659 | [
"vector"
] |
ac301f440058e636f913117bdd518c6895d47dc7 | 4,677 | hpp | C++ | src/util.hpp | ChrisPattison/SYK | f62b1e9519daf804409790d01316749d010c0db2 | [
"BSD-2-Clause"
] | null | null | null | src/util.hpp | ChrisPattison/SYK | f62b1e9519daf804409790d01316749d010c0db2 | [
"BSD-2-Clause"
] | null | null | null | src/util.hpp | ChrisPattison/SYK | f62b1e9519daf804409790d01316749d010c0db2 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) 2020 C. Pattison
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <vector>
#include <algorithm>
#include <cmath>
#include <random>
#include <cassert>
#include <functional>
namespace util {
template<typename T>
std::vector<T> logspace(T a, T b, int N) {
int n = 0;
std::vector<T> vals(N);
auto m = (std::log(b) - std::log(a)) / static_cast<T>(N);
std::generate(vals.begin(), vals.end(), [&]() {
return std::exp(m * static_cast<T>(n++) + std::log(a)); });
return vals;
}
template<typename T>
std::vector<T> linspace(T a, T b, int N) {
int n = 0;
std::vector<T> vals(N);
auto m = (b - a) / static_cast<T>(N);
std::generate(vals.begin(), vals.end(), [&]() {
return m * static_cast<T>(n++) + a; });
return vals;
}
// http://blog.geomblog.org/2005/10/sampling-from-simplex.html
template<typename rng_type>
std::vector<double> sample_unit_simplex(rng_type* rand_gen, int dim) {
assert(dim >= 2);
std::uniform_real_distribution distr;
std::vector<double> vals(dim+2);
std::generate(vals.begin()+2, vals.end(), [&]() { return distr(*rand_gen); });
vals[0] = 0;
vals[1] = 1;
std::sort(vals.begin(), vals.end());
std::adjacent_difference(vals.begin(), vals.end(), vals.begin());
vals.erase(vals.begin());
assert(std::abs(std::accumulate(vals.begin(), vals.end(), 0.0) - 1.0) < 1e-7);
return vals;
}
template<typename rng_type>
std::vector<double> sample_biased_simplex(rng_type* rand_gen, int dim, double size) {
auto simplex = sample_unit_simplex(rand_gen, dim);
std::transform(simplex.begin()+1, simplex.end(), simplex.begin(), [&](const auto& v) { return v * size; });
assert(size < 1.0);
auto norm = std::accumulate(simplex.begin(), simplex.end(), 0.0);
std::transform(simplex.begin(), simplex.end(), simplex.begin(), [&](const auto& v) { return v / norm; });
return simplex;
}
template<typename InputIt, typename T, typename BinaryOp, typename UnaryOp>
T transform_reduce(InputIt first, InputIt last, T init, BinaryOp binop, UnaryOp unary_op) {
T result = init;
for(; first != last; ++first) {
result = binop(result, unary_op(*first));
}
return result;
}
template <typename InputIt1, typename InputIt2, typename T, typename BinaryOp1, typename BinaryOp2>
T transform_reduce(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOp1 binary_op1, BinaryOp2 binary_op2) {
T result = init;
while(first1 != last1) {
result = binary_op1(result, binary_op2(*first1, *first2));
++first1;
++first2;
}
return result;
}
template<typename InputIt1, typename InputIt2, typename T>
T transform_reduce(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init) {
return transform_reduce(first1, last1, first2, init, std::plus<>(), std::multiplies<>());
}
template<typename rng_type>
void warmup_rng(rng_type* rng, int warmup_cycles = 100000) {
for(int k = 0; k < warmup_cycles; ++k) {
(*rng)();
}
}
template<typename stream_type>
std::size_t get_stream_size(stream_type* stream) {
stream->seekg(0, std::ios::end);
std::size_t num_bytes = stream->tellg();
stream->seekg(0, std::ios::beg);
return num_bytes;
}
} | 38.336066 | 123 | 0.665598 | [
"vector",
"transform"
] |
ac45eede896d26b7981f419da8a3ba78ed7094d5 | 9,133 | cpp | C++ | RPGPrototype/Intermediate/Build/Win64/UE4Editor/Inc/RPGPrototype/RPGPrototypeCharacter.gen.cpp | JiaqiJin/RPGPrototype_ue4 | e328798e880089841c0bfea1e25abee045dbf447 | [
"MIT"
] | 1 | 2022-01-07T11:48:03.000Z | 2022-01-07T11:48:03.000Z | RPGPrototype/Intermediate/Build/Win64/UE4Editor/Inc/RPGPrototype/RPGPrototypeCharacter.gen.cpp | JiaqiJin/RPGPrototype_ue4 | e328798e880089841c0bfea1e25abee045dbf447 | [
"MIT"
] | null | null | null | RPGPrototype/Intermediate/Build/Win64/UE4Editor/Inc/RPGPrototype/RPGPrototypeCharacter.gen.cpp | JiaqiJin/RPGPrototype_ue4 | e328798e880089841c0bfea1e25abee045dbf447 | [
"MIT"
] | null | null | null | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "RPGPrototype/RPGPrototypeCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeRPGPrototypeCharacter() {}
// Cross Module References
RPGPROTOTYPE_API UClass* Z_Construct_UClass_ARPGPrototypeCharacter_NoRegister();
RPGPROTOTYPE_API UClass* Z_Construct_UClass_ARPGPrototypeCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_RPGPrototype();
ENGINE_API UClass* Z_Construct_UClass_USpringArmComponent_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister();
// End Cross Module References
void ARPGPrototypeCharacter::StaticRegisterNativesARPGPrototypeCharacter()
{
}
UClass* Z_Construct_UClass_ARPGPrototypeCharacter_NoRegister()
{
return ARPGPrototypeCharacter::StaticClass();
}
struct Z_Construct_UClass_ARPGPrototypeCharacter_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CameraBoom_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CameraBoom;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FollowCamera_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FollowCamera;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseTurnRate_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseTurnRate;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseLookUpRate_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseLookUpRate;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_ARPGPrototypeCharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_RPGPrototype,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ARPGPrototypeCharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "RPGPrototypeCharacter.h" },
{ "ModuleRelativePath", "RPGPrototypeCharacter.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_CameraBoom_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "Camera" },
{ "Comment", "/** Camera boom positioning the camera behind the character */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "RPGPrototypeCharacter.h" },
{ "ToolTip", "Camera boom positioning the camera behind the character" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_CameraBoom = { "CameraBoom", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ARPGPrototypeCharacter, CameraBoom), Z_Construct_UClass_USpringArmComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_CameraBoom_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_CameraBoom_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_FollowCamera_MetaData[] = {
{ "AllowPrivateAccess", "true" },
{ "Category", "Camera" },
{ "Comment", "/** Follow camera */" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "RPGPrototypeCharacter.h" },
{ "ToolTip", "Follow camera" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_FollowCamera = { "FollowCamera", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ARPGPrototypeCharacter, FollowCamera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_FollowCamera_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_FollowCamera_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseTurnRate_MetaData[] = {
{ "Category", "Camera" },
{ "Comment", "/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */" },
{ "ModuleRelativePath", "RPGPrototypeCharacter.h" },
{ "ToolTip", "Base turn rate, in deg/sec. Other scaling may affect final turn rate." },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseTurnRate = { "BaseTurnRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ARPGPrototypeCharacter, BaseTurnRate), METADATA_PARAMS(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseTurnRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseTurnRate_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseLookUpRate_MetaData[] = {
{ "Category", "Camera" },
{ "Comment", "/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */" },
{ "ModuleRelativePath", "RPGPrototypeCharacter.h" },
{ "ToolTip", "Base look up/down rate, in deg/sec. Other scaling may affect final rate." },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseLookUpRate = { "BaseLookUpRate", nullptr, (EPropertyFlags)0x0010000000020015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ARPGPrototypeCharacter, BaseLookUpRate), METADATA_PARAMS(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseLookUpRate_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseLookUpRate_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ARPGPrototypeCharacter_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_CameraBoom,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_FollowCamera,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseTurnRate,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ARPGPrototypeCharacter_Statics::NewProp_BaseLookUpRate,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_ARPGPrototypeCharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<ARPGPrototypeCharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ARPGPrototypeCharacter_Statics::ClassParams = {
&ARPGPrototypeCharacter::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
Z_Construct_UClass_ARPGPrototypeCharacter_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
0,
UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::PropPointers),
0,
0x008000A4u,
METADATA_PARAMS(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_ARPGPrototypeCharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_ARPGPrototypeCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ARPGPrototypeCharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(ARPGPrototypeCharacter, 665356909);
template<> RPGPROTOTYPE_API UClass* StaticClass<ARPGPrototypeCharacter>()
{
return ARPGPrototypeCharacter::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_ARPGPrototypeCharacter(Z_Construct_UClass_ARPGPrototypeCharacter, &ARPGPrototypeCharacter::StaticClass, TEXT("/Script/RPGPrototype"), TEXT("ARPGPrototypeCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(ARPGPrototypeCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 60.483444 | 575 | 0.820431 | [
"object"
] |
ac53b1be6b7a856f2fbe392ce76c1062f03bd171 | 5,921 | cpp | C++ | src/train/svm_train.cpp | hxl1990/new416 | f4962fddba6ce0b0e1805503d7c376352bd0e91d | [
"Apache-2.0"
] | null | null | null | src/train/svm_train.cpp | hxl1990/new416 | f4962fddba6ce0b0e1805503d7c376352bd0e91d | [
"Apache-2.0"
] | null | null | null | src/train/svm_train.cpp | hxl1990/new416 | f4962fddba6ce0b0e1805503d7c376352bd0e91d | [
"Apache-2.0"
] | 1 | 2020-01-17T09:53:22.000Z | 2020-01-17T09:53:22.000Z | #include "easypr/train/svm_train.h"
#include "easypr/core/feature.h"
#include "easypr/util/util.h"
#ifdef OS_WINDOWS
#include <ctime>
#endif
using namespace cv::ml;
namespace easypr {
SvmTrain::SvmTrain(const char* plates_folder, const char* xml)
: plates_folder_(plates_folder), svm_xml_(xml) {
assert(plates_folder);
assert(xml);
}
void SvmTrain::train() {
svm_ = cv::ml::SVM::create();
svm_->setType(cv::ml::SVM::C_SVC);
svm_->setKernel(cv::ml::SVM::RBF);
svm_->setDegree(0.1);
// 1.4 bug fix: old 1.4 ver gamma is 1
svm_->setGamma(0.1);
svm_->setCoef0(0.1);
svm_->setC(1);
svm_->setNu(0.1);
svm_->setP(0.1);
svm_->setTermCriteria(cvTermCriteria(CV_TERMCRIT_ITER, 100000, 0.00001));
auto train_data = tdata();
fprintf(stdout, ">> Training SVM model, please wait...\n");
long start = utils::getTimestamp();
//svm_->trainAuto(train_data, 10, SVM::getDefaultGrid(SVM::C),
// SVM::getDefaultGrid(SVM::GAMMA), SVM::getDefaultGrid(SVM::P),
// SVM::getDefaultGrid(SVM::NU), SVM::getDefaultGrid(SVM::COEF),
// SVM::getDefaultGrid(SVM::DEGREE), true);
svm_->train(train_data);
long end = utils::getTimestamp();
fprintf(stdout, ">> Training done. Time elapse: %ldms\n", end - start);
fprintf(stdout, ">> Saving model file...\n");
svm_->save(svm_xml_);
fprintf(stdout, ">> Your SVM Model was saved to %s\n", svm_xml_);
fprintf(stdout, ">> Testing...\n");
this->test();
}
void SvmTrain::test() {
// 1.4 bug fix: old 1.4 ver there is no null judge
if (NULL == svm_)
svm_ = cv::ml::SVM::load<cv::ml::SVM>(svm_xml_);
if (test_file_list_.empty()) {
this->prepare();
}
double count_all = test_file_list_.size();
double ptrue_rtrue = 0;
double ptrue_rfalse = 0;
double pfalse_rtrue = 0;
double pfalse_rfalse = 0;
for (auto item : test_file_list_) {
auto image = cv::imread(item.file);
if (!image.data) {
std::cout << "no" << std::endl;
continue;
}
cv::Mat feature;
getHistogramFeatures(image, feature);
//std::cout << "predict: " << result << std::endl;
auto predict = int(svm_->predict(feature));
auto real = item.label;
if (predict == kForward && real == kForward) ptrue_rtrue++;
if (predict == kForward && real == kInverse) ptrue_rfalse++;
if (predict == kInverse && real == kForward) pfalse_rtrue++;
if (predict == kInverse && real == kInverse) pfalse_rfalse++;
}
std::cout << "count_all: " << count_all << std::endl;
std::cout << "ptrue_rtrue: " << ptrue_rtrue << std::endl;
std::cout << "ptrue_rfalse: " << ptrue_rfalse << std::endl;
std::cout << "pfalse_rtrue: " << pfalse_rtrue << std::endl;
std::cout << "pfalse_rfalse: " << pfalse_rfalse << std::endl;
double precise = 0;
if (ptrue_rtrue + ptrue_rfalse != 0) {
precise = ptrue_rtrue / (ptrue_rtrue + ptrue_rfalse);
std::cout << "precise: " << precise << std::endl;
} else {
std::cout << "precise: "
<< "NA" << std::endl;
}
double recall = 0;
if (ptrue_rtrue + pfalse_rtrue != 0) {
recall = ptrue_rtrue / (ptrue_rtrue + pfalse_rtrue);
std::cout << "recall: " << recall << std::endl;
} else {
std::cout << "recall: "
<< "NA" << std::endl;
}
double Fsocre = 0;
if (precise + recall != 0) {
Fsocre = 2 * (precise * recall) / (precise + recall);
std::cout << "Fsocre: " << Fsocre << std::endl;
} else {
std::cout << "Fsocre: "
<< "NA" << std::endl;
}
}
void SvmTrain::prepare() {
srand(unsigned(time(NULL)));
char buffer[260] = {0};
sprintf(buffer, "%s/has", plates_folder_);
auto has_file_list = utils::getFiles(buffer);
std::random_shuffle(has_file_list.begin(), has_file_list.end());
sprintf(buffer, "%s/no", plates_folder_);
auto no_file_list = utils::getFiles(buffer);
std::random_shuffle(no_file_list.begin(), no_file_list.end());
auto has_num = has_file_list.size();
auto no_num = no_file_list.size();
fprintf(stdout, ">> Collecting train data...\n");
auto has_for_train = static_cast<int>(has_num * kSvmPercentage);
auto no_for_train = static_cast<int>(no_num * kSvmPercentage);
// copy kSvmPercentage of has_file_list to train_file_list_
train_file_list_.reserve(has_for_train + no_for_train);
for (auto i = 0; i < has_for_train; i++) {
train_file_list_.push_back({has_file_list[i], kForward});
}
// copy kSvmPercentage of no_file_list to the end of train_file_list_
for (auto i = 0; i < no_for_train; i++) {
train_file_list_.push_back({no_file_list[i], kInverse});
}
fprintf(stdout, ">> Collecting test data...\n");
auto has_for_test = has_num - has_for_train;
auto no_for_test = no_num - no_for_train;
// copy the rest of has_file_list to the test_file_list_
test_file_list_.reserve(has_for_test + no_for_test);
for (auto i = has_for_train; i < has_num; i++) {
test_file_list_.push_back({has_file_list[i], kForward});
}
// copy the rest of no_file_list to the end of the test_file_list_
for (auto i = no_for_train; i < no_num; i++) {
test_file_list_.push_back({no_file_list[i], kInverse});
}
}
cv::Ptr<cv::ml::TrainData> SvmTrain::tdata() {
this->prepare();
cv::Mat samples;
std::vector<int> responses;
for (auto f : train_file_list_) {
auto image = cv::imread(f.file);
if (!image.data) {
fprintf(stdout, ">> Invalid image: %s ignore.\n", f.file.c_str());
continue;
}
cv::Mat feature;
getHistogramFeatures(image, feature);
feature = feature.reshape(1, 1);
samples.push_back(feature);
responses.push_back(int(f.label));
}
cv::Mat samples_, responses_;
samples.convertTo(samples_, CV_32FC1);
cv::Mat(responses).copyTo(responses_);
return cv::ml::TrainData::create(samples_, cv::ml::SampleTypes::ROW_SAMPLE,
responses_);
}
} // namespace easypr
| 29.90404 | 81 | 0.634859 | [
"vector",
"model"
] |
ac5da6d15e1c0b4c03d028f899a68c9ba87d52a2 | 963 | cpp | C++ | boboleetcode/Play-Leetcode-master/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0199-Binary-Tree-Right-Side-View/cpp-0199/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/binary-tree-right-side-view/
/// Author : liuyubobobo
/// Time : 2019-09-26
#include <iostream>
#include <vector>
using namespace std;
/// BFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(!root) return res;
vector<TreeNode*> cur = {root};
while(cur.size()){
res.push_back(cur.back()->val);
vector<TreeNode*> next;
for(TreeNode* node: cur){
if(node->left) next.push_back(node->left);
if(node->right) next.push_back(node->right);
}
cur = next;
}
return res;
}
};
int main() {
return 0;
} | 19.26 | 71 | 0.554517 | [
"vector"
] |
ac5e9087bf4bef80515bce751851939d0b46bcde | 530 | cpp | C++ | src/413.cpp | MoRunChang2015/LeetCode | d046083b952811dfbf5f8fb646060836a3e937ce | [
"Apache-2.0"
] | null | null | null | src/413.cpp | MoRunChang2015/LeetCode | d046083b952811dfbf5f8fb646060836a3e937ce | [
"Apache-2.0"
] | null | null | null | src/413.cpp | MoRunChang2015/LeetCode | d046083b952811dfbf5f8fb646060836a3e937ce | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
int ans = 0;
if (A.size() < 3)
return ans;
for (int i = 0; i <= A.size() - 3; i++) {
if (A[i + 1] * 2 == A[i] + A[i + 2]) {
ans++;
int d = A[i + 1] - A[i];
int j = i + 3;
while (A[j] - A[j - 1] == d && j < A.size()) {
ans++;
j++;
}
}
}
return ans;
}
};
| 25.238095 | 62 | 0.292453 | [
"vector"
] |
ac63b17191833d866e1130ac21b7ee2df58e2620 | 20,276 | cpp | C++ | cppForSwig/DecryptedDataContainer.cpp | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | cppForSwig/DecryptedDataContainer.cpp | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | cppForSwig/DecryptedDataContainer.cpp | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2017, goatpig //
// Distributed under the MIT license //
// See LICENSE-MIT or https://opensource.org/licenses/MIT //
// //
////////////////////////////////////////////////////////////////////////////////
#include "DecryptedDataContainer.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//// DecryptedDataContainer
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::initAfterLock()
{
auto&& decryptedDataInstance = make_unique<DecryptedDataMaps>();
//copy default encryption key
auto&& defaultEncryptionKeyCopy = defaultEncryptionKey_.copy();
auto defaultKey =
make_unique<DecryptedEncryptionKey>(defaultEncryptionKeyCopy);
decryptedDataInstance->encryptionKeys_.insert(make_pair(
defaultEncryptionKeyId_, move(defaultKey)));
lockedDecryptedData_ = move(decryptedDataInstance);
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::cleanUpBeforeUnlock()
{
otherLocks_.clear();
lockedDecryptedData_.reset();
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::lockOther(
shared_ptr<DecryptedDataContainer> other)
{
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
otherLocks_.push_back(OtherLockedContainer(other));
}
////////////////////////////////////////////////////////////////////////////////
unique_ptr<DecryptedEncryptionKey>
DecryptedDataContainer::deriveEncryptionKey(
unique_ptr<DecryptedEncryptionKey> decrKey, const BinaryData& kdfid) const
{
//sanity check
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
//does the decryption key have this derivation?
auto derivationIter = decrKey->derivedKeys_.find(kdfid);
if (derivationIter == decrKey->derivedKeys_.end())
{
//look for the kdf
auto kdfIter = kdfMap_.find(kdfid);
if (kdfIter == kdfMap_.end() || kdfIter->second == nullptr)
throw DecryptedDataContainerException("can't find kdf params for id");
//derive the key, this will insert it into the container too
decrKey->deriveKey(kdfIter->second);
}
return move(decrKey);
}
////////////////////////////////////////////////////////////////////////////////
const SecureBinaryData& DecryptedDataContainer::getDecryptedPrivateData(
shared_ptr<Asset_EncryptedData> dataPtr)
{
//sanity check
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
auto insertDecryptedData = [this](unique_ptr<DecryptedData> decrKey)->
const SecureBinaryData&
{
//if decrKey is empty, all casts failed, throw
if (decrKey == nullptr)
throw DecryptedDataContainerException("unexpected dataPtr type");
//make sure insertion succeeds
lockedDecryptedData_->privateData_.erase(decrKey->getId());
auto&& keypair = make_pair(decrKey->getId(), move(decrKey));
auto&& insertionPair =
lockedDecryptedData_->privateData_.insert(move(keypair));
return insertionPair.first->second->getDataRef();
};
//look for already decrypted data
auto dataIter = lockedDecryptedData_->privateData_.find(dataPtr->getId());
if (dataIter != lockedDecryptedData_->privateData_.end())
return dataIter->second->getDataRef();
//no decrypted val entry, let's try to decrypt the data instead
if (!dataPtr->hasData())
{
//missing encrypted data in container (most likely uncomputed private key)
//throw back to caller, this object only deals with decryption
throw EncryptedDataMissing();
}
//check cipher
if (dataPtr->cipher_ == nullptr)
{
//null cipher, data is not encrypted, create entry and return it
auto dataCopy = dataPtr->cipherText_;
auto&& decrKey = make_unique<DecryptedData>(
dataPtr->getId(), dataCopy);
return insertDecryptedData(move(decrKey));
}
//we have a valid cipher, grab the encryption key
unique_ptr<DecryptedEncryptionKey> decrKey;
auto& encryptionKeyId = dataPtr->cipher_->getEncryptionKeyId();
auto& kdfId = dataPtr->cipher_->getKdfId();
populateEncryptionKey(encryptionKeyId, kdfId);
auto decrKeyIter =
lockedDecryptedData_->encryptionKeys_.find(encryptionKeyId);
if (decrKeyIter == lockedDecryptedData_->encryptionKeys_.end())
throw DecryptedDataContainerException("could not get encryption key");
auto derivationKeyIter = decrKeyIter->second->derivedKeys_.find(kdfId);
if (derivationKeyIter == decrKeyIter->second->derivedKeys_.end())
throw DecryptedDataContainerException("could not get derived encryption key");
//decrypt data
auto decryptedDataPtr = move(dataPtr->decrypt(derivationKeyIter->second));
//sanity check
if (decryptedDataPtr == nullptr)
throw DecryptedDataContainerException("failed to decrypt data");
//insert the newly decrypted data in the container and return
return insertDecryptedData(move(decryptedDataPtr));
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::populateEncryptionKey(
const BinaryData& keyid, const BinaryData& kdfid)
{
//sanity check
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
//lambda to insert keys back into the container
auto insertDecryptedData = [this](
const BinaryData& keyid, unique_ptr<DecryptedEncryptionKey> decrKey)->void
{
//if decrKey is empty, all casts failed, throw
if (decrKey == nullptr)
throw DecryptedDataContainerException(
"tried to insert empty decryption key");
//make sure insertion succeeds
lockedDecryptedData_->encryptionKeys_.erase(keyid);
auto&& keypair = make_pair(keyid, move(decrKey));
auto&& insertionPair =
lockedDecryptedData_->encryptionKeys_.insert(move(keypair));
};
//look for already decrypted data
unique_ptr<DecryptedEncryptionKey> decryptedKey = nullptr;
auto dataIter = lockedDecryptedData_->encryptionKeys_.find(keyid);
if (dataIter != lockedDecryptedData_->encryptionKeys_.end())
decryptedKey = move(dataIter->second);
if (decryptedKey == nullptr)
{
//we don't have a decrypted key, let's look for it in the encrypted map
auto encrKeyIter = encryptionKeyMap_.find(keyid);
if (encrKeyIter != encryptionKeyMap_.end())
{
//sanity check
auto encryptedKeyPtr = dynamic_pointer_cast<Asset_EncryptionKey>(
encrKeyIter->second);
if (encryptedKeyPtr == nullptr)
{
throw DecryptedDataContainerException(
"unexpected object for encryption key id");
}
//found the encrypted key, need to decrypt it first
populateEncryptionKey(
encryptedKeyPtr->cipher_->getEncryptionKeyId(),
encryptedKeyPtr->cipher_->getKdfId());
//grab encryption key from map
auto decrKeyIter =
lockedDecryptedData_->encryptionKeys_.find(
encryptedKeyPtr->cipher_->getEncryptionKeyId());
if (decrKeyIter == lockedDecryptedData_->encryptionKeys_.end())
throw DecryptedDataContainerException("failed to decrypt key");
auto&& decryptionKey = move(decrKeyIter->second);
//derive encryption key
decryptionKey = move(deriveEncryptionKey(
move(decryptionKey),
encryptedKeyPtr->cipher_->getKdfId()));
//decrypt encrypted key
auto&& rawDecryptedKey = encryptedKeyPtr->cipher_->decrypt(
decryptionKey->getDerivedKey(encryptedKeyPtr->cipher_->getKdfId()),
encryptedKeyPtr->cipherText_);
decryptedKey = move(make_unique<DecryptedEncryptionKey>(
rawDecryptedKey));
//move decryption key back to container
insertDecryptedData(
encryptedKeyPtr->cipher_->getEncryptionKeyId(), move(decryptionKey));
}
}
if (decryptedKey == nullptr)
{
//still no key, prompt the user
decryptedKey = move(promptPassphrase(keyid, kdfid));
}
//apply kdf
decryptedKey = move(deriveEncryptionKey(move(decryptedKey), kdfid));
//insert into map
insertDecryptedData(keyid, move(decryptedKey));
}
////////////////////////////////////////////////////////////////////////////////
SecureBinaryData DecryptedDataContainer::encryptData(
Cipher* const cipher, const SecureBinaryData& data)
{
//sanity check
if (cipher == nullptr)
throw DecryptedDataContainerException("null cipher");
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
populateEncryptionKey(cipher->getEncryptionKeyId(), cipher->getKdfId());
auto keyIter = lockedDecryptedData_->encryptionKeys_.find(
cipher->getEncryptionKeyId());
auto& derivedKey = keyIter->second->getDerivedKey(cipher->getKdfId());
return move(cipher->encrypt(derivedKey, data));
}
////////////////////////////////////////////////////////////////////////////////
unique_ptr<DecryptedEncryptionKey> DecryptedDataContainer::promptPassphrase(
const BinaryData& keyId, const BinaryData& kdfId) const
{
while (1)
{
if (!getPassphraseLambda_)
throw DecryptedDataContainerException("empty passphrase lambda");
auto&& passphrase = getPassphraseLambda_(keyId);
if (passphrase.getSize() == 0)
throw DecryptedDataContainerException("empty passphrase");
auto keyPtr = make_unique<DecryptedEncryptionKey>(passphrase);
keyPtr = move(deriveEncryptionKey(move(keyPtr), kdfId));
if (keyId == keyPtr->getId(kdfId))
return move(keyPtr);
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::updateKeyOnDisk(
const BinaryData& key, shared_ptr<Asset_EncryptedData> dataPtr)
{
//serialize db key
auto&& dbKey = WRITE_UINT8_BE(ENCRYPTIONKEY_PREFIX);
dbKey.append(key);
updateKeyOnDiskNoPrefix(dbKey, dataPtr);
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::updateKeyOnDiskNoPrefix(
const BinaryData& dbKey, shared_ptr<Asset_EncryptedData> dataPtr)
{
/*caller needs to manage db tx*/
//check if data is on disk already
CharacterArrayRef keyRef(dbKey.getSize(), dbKey.getPtr());
auto&& dataRef = dbPtr_->get_NoCopy(keyRef);
if (dataRef.len != 0)
{
BinaryDataRef bdr((uint8_t*)dataRef.data, dataRef.len);
//already have this key, is it the same data?
auto onDiskData = Asset_EncryptedData::deserialize(bdr);
//data has not changed, no need to commit
if (onDiskData->isSame(dataPtr.get()))
return;
//data has changed, wipe the existing data
deleteKeyFromDisk(dbKey);
}
auto&& serializedData = dataPtr->serialize();
CharacterArrayRef dataRef_Put(
serializedData.getSize(), serializedData.getPtr());
dbPtr_->insert(keyRef, dataRef_Put);
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::updateOnDisk()
{
//wallet needs to create the db read/write tx
//encryption keys
for (auto& key : encryptionKeyMap_)
updateKeyOnDisk(key.first, key.second);
//kdf
for (auto& key : kdfMap_)
{
//get db key
auto&& dbKey = WRITE_UINT8_BE(KDF_PREFIX);
dbKey.append(key.first);
//fetch from db
CharacterArrayRef keyRef(dbKey.getSize(), dbKey.getPtr());
auto&& dataRef = dbPtr_->get_NoCopy(keyRef);
if (dataRef.len != 0)
{
BinaryDataRef bdr((uint8_t*)dataRef.data, dataRef.len);
//already have this key, is it the same data?
auto onDiskData = KeyDerivationFunction::deserialize(bdr);
//data has not changed, not commiting to disk
if (onDiskData->isSame(key.second.get()))
continue;
//data has changed, wipe the existing data
deleteKeyFromDisk(dbKey);
}
auto&& serializedData = key.second->serialize();
CharacterArrayRef dataRef_Put(
serializedData.getSize(), serializedData.getPtr());
dbPtr_->insert(keyRef, dataRef_Put);
}
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::deleteKeyFromDisk(const BinaryData& key)
{
/***
This operation abuses the no copy read feature in lmdb. Since all data is
mmap'd, a no copy read is a pointer to the data on disk. Therefor modifying
that data will result in a modification on disk.
This is done under 3 conditions:
1) The decrypted data container is locked.
2) The calling threads owns a ReadWrite transaction on the lmdb object
3) There are no active ReadOnly transactions on the lmdb object
1. is a no brainer, 2. guarantees the changes are flushed to disk once the
tx is released. RW tx are locked, therefor only one is active at any given
time, by LMDB design.
3. is to guarantee there are no readers when the change takes place. Needs
some LMDB C++ wrapper modifications to be able to check from the db object.
The condition should be enforced by the caller regardless.
***/
//sanity checks
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
//check db only has one RW tx
/*if (!dbEnv_->isRWLockExclusive())
{
throw DecryptedDataContainerException(
"need exclusive RW lock to delete entries");
}
//check we own the RW tx
if (dbEnv_->ownsLock() != LMDB_RWLOCK)
{
throw DecryptedDataContainerException(
"need exclusive RW lock to delete entries");
}*/
CharacterArrayRef keyRef(key.getSize(), key.getCharPtr());
//check data exist son disk to begin with
{
auto dataRef = dbPtr_->get_NoCopy(keyRef);
//data is empty, nothing to wipe
if (dataRef.len == 0)
{
throw DecryptedDataContainerException(
"tried to wipe non existent entry");
}
}
//wipe it
dbPtr_->wipe(keyRef);
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::readFromDisk()
{
{
//encryption key and kdf entries
auto dbIter = dbPtr_->begin();
BinaryWriter bwEncrKey;
bwEncrKey.put_uint8_t(ENCRYPTIONKEY_PREFIX);
CharacterArrayRef keyRef(bwEncrKey.getSize(), bwEncrKey.getData().getPtr());
dbIter.seek(keyRef, LMDB::Iterator::Seek_GE);
while (dbIter.isValid())
{
auto iterkey = dbIter.key();
auto itervalue = dbIter.value();
if (iterkey.mv_size < 2)
throw runtime_error("empty db key");
if (itervalue.mv_size < 1)
throw runtime_error("empty value");
BinaryDataRef keyBDR((uint8_t*)iterkey.mv_data + 1, iterkey.mv_size - 1);
BinaryDataRef valueBDR((uint8_t*)itervalue.mv_data, itervalue.mv_size);
auto prefix = (uint8_t*)iterkey.mv_data;
switch (*prefix)
{
case ENCRYPTIONKEY_PREFIX:
{
auto keyPtr = Asset_EncryptedData::deserialize(valueBDR);
auto encrKeyPtr = dynamic_pointer_cast<Asset_EncryptionKey>(keyPtr);
if (encrKeyPtr == nullptr)
throw runtime_error("empty keyptr");
addEncryptionKey(encrKeyPtr);
break;
}
case KDF_PREFIX:
{
auto kdfPtr = KeyDerivationFunction::deserialize(valueBDR);
if (keyBDR != kdfPtr->getId())
throw runtime_error("kdf id mismatch");
addKdf(kdfPtr);
break;
}
}
dbIter.advance();
}
}
}
////////////////////////////////////////////////////////////////////////////////
void DecryptedDataContainer::encryptEncryptionKey(
const BinaryData& keyID,
const SecureBinaryData& newPassphrase)
{
/***
Encrypts an encryption key with "newPassphrase". If the key is already
encrypted, it will be changed.
***/
//sanity check
if (!ownsLock())
throw DecryptedDataContainerException("unlocked/does not own lock");
if (lockedDecryptedData_ == nullptr)
throw DecryptedDataContainerException(
"nullptr lock! how did we get this far?");
auto keyIter = encryptionKeyMap_.find(keyID);
if (keyIter == encryptionKeyMap_.end())
throw DecryptedDataContainerException(
"cannot change passphrase for unknown key");
//decrypt master encryption key
auto& kdfId = keyIter->second->cipher_->getKdfId();
populateEncryptionKey(keyID, kdfId);
//grab decrypted key
auto decryptedKeyIter = lockedDecryptedData_->encryptionKeys_.find(keyID);
if (decryptedKeyIter == lockedDecryptedData_->encryptionKeys_.end())
throw DecryptedDataContainerException(
"failed to decrypt key");
auto& decryptedKey = decryptedKeyIter->second->getData();
//grab kdf for key id computation
auto masterKeyKdfId = keyIter->second->cipher_->getKdfId();
auto kdfIter = kdfMap_.find(masterKeyKdfId);
if (kdfIter == kdfMap_.end())
throw DecryptedDataContainerException("failed to grab kdf");
//copy passphrase cause the ctor will move the data in
auto newPassphraseCopy = newPassphrase;
//kdf the key to get its id
auto newEncryptionKey = make_unique<DecryptedEncryptionKey>(newPassphraseCopy);
newEncryptionKey->deriveKey(kdfIter->second);
auto newKeyId = newEncryptionKey->getId(masterKeyKdfId);
//create new cipher, pointing to the new key id
auto newCipher = keyIter->second->cipher_->getCopy(newKeyId);
//add new encryption key object to container
lockedDecryptedData_->encryptionKeys_.insert(
move(make_pair(newKeyId, move(newEncryptionKey))));
//encrypt master key
auto&& newEncryptedKey = encryptData(newCipher.get(), decryptedKey);
//create new encrypted container
auto keyIdCopy = keyID;
auto newEncryptedKeyPtr =
make_shared<Asset_EncryptionKey>(keyIdCopy, newEncryptedKey, move(newCipher));
//update
keyIter->second = newEncryptedKeyPtr;
auto&& temp_key = WRITE_UINT8_BE(ENCRYPTIONKEY_PREFIX_TEMP);
temp_key.append(keyID);
auto&& perm_key = WRITE_UINT8_BE(ENCRYPTIONKEY_PREFIX);
perm_key.append(keyID);
{
//write new encrypted key as temp key within it's own transaction
LMDBEnv::Transaction tempTx(dbEnv_, LMDB::ReadWrite);
updateKeyOnDiskNoPrefix(temp_key, newEncryptedKeyPtr);
}
{
LMDBEnv::Transaction permTx(dbEnv_, LMDB::ReadWrite);
//wipe old key from disk
deleteKeyFromDisk(perm_key);
//write new key to disk
updateKeyOnDiskNoPrefix(perm_key, newEncryptedKeyPtr);
}
{
LMDBEnv::Transaction permTx(dbEnv_, LMDB::ReadWrite);
//wipe temp entry
deleteKeyFromDisk(temp_key);
}
}
| 33.906355 | 84 | 0.629217 | [
"object"
] |
ac6d2d3157e0fedaf167a8456a20c22b0943b126 | 11,468 | cc | C++ | cc/dual_net/dual_net_test.cc | VonRosenchild/minigo | 18d43c0950d3623ad33b9035ab91952b79f8c89c | [
"Apache-2.0"
] | 1 | 2019-10-10T06:09:32.000Z | 2019-10-10T06:09:32.000Z | cc/dual_net/dual_net_test.cc | VonRosenchild/minigo | 18d43c0950d3623ad33b9035ab91952b79f8c89c | [
"Apache-2.0"
] | null | null | null | cc/dual_net/dual_net_test.cc | VonRosenchild/minigo | 18d43c0950d3623ad33b9035ab91952b79f8c89c | [
"Apache-2.0"
] | 1 | 2019-10-10T06:09:19.000Z | 2019-10-10T06:09:19.000Z | // Copyright 2018 Google LLC
//
// 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 <array>
#include <deque>
#include <map>
#include <type_traits>
#include <vector>
#include "cc/model/features.h"
#include "cc/position.h"
#include "cc/random.h"
#include "cc/symmetries.h"
#include "cc/test_utils.h"
#include "gtest/gtest.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def_builder.h"
#if MG_ENABLE_TF_DUAL_NET
#include "cc/dual_net/tf_dual_net.h"
#endif
#if MG_ENABLE_LITE_DUAL_NET
#include "cc/dual_net/lite_dual_net.h"
#endif
namespace minigo {
namespace {
template <typename T>
std::vector<T> GetStoneFeatures(const Tensor<T>& features, Coord c) {
std::vector<T> result;
MG_CHECK(features.n == 1);
for (int i = 0; i < features.c; ++i) {
result.push_back(features.data[c * features.c + i]);
}
return result;
}
template <typename F>
class DualNetTest : public ::testing::Test {};
using TestFeatureTypes = ::testing::Types<AgzFeatures, ExtraFeatures>;
TYPED_TEST_CASE(DualNetTest, TestFeatureTypes);
// Verifies SetFeatures an empty board with black to play.
TYPED_TEST(DualNetTest, TestEmptyBoardBlackToPlay) {
using FeatureType = TypeParam;
TestablePosition board("");
ModelInput input;
input.sym = symmetry::kIdentity;
input.position_history.push_back(&board);
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, FeatureType::kNumPlanes, buffer.data()};
FeatureType::Set({&input}, &features);
for (int c = 0; c < kN * kN; ++c) {
auto f = GetStoneFeatures(features, c);
for (size_t i = 0; i < f.size(); ++i) {
if (i != FeatureType::template GetPlaneIdx<ToPlayFeature>()) {
EXPECT_EQ(0, f[i]);
} else {
EXPECT_EQ(1, f[i]);
}
}
}
}
// Verifies SetFeatures for an empty board with white to play.
TYPED_TEST(DualNetTest, TestEmptyBoardWhiteToPlay) {
using FeatureType = TypeParam;
TestablePosition board("", Color::kWhite);
ModelInput input;
input.sym = symmetry::kIdentity;
input.position_history.push_back(&board);
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, FeatureType::kNumPlanes, buffer.data()};
FeatureType::Set({&input}, &features);
for (int c = 0; c < kN * kN; ++c) {
auto f = GetStoneFeatures(features, c);
for (size_t i = 0; i < f.size(); ++i) {
EXPECT_EQ(0, f[i]);
}
}
}
// Verifies SetFeatures.
TYPED_TEST(DualNetTest, TestSetFeatures) {
using FeatureType = TypeParam;
TestablePosition board("");
std::vector<std::string> moves = {"B9", "H9", "A8", "J9",
"D5", "A1", "A2", "J1"};
std::deque<TestablePosition> positions;
for (const auto& move : moves) {
board.PlayMove(move);
positions.push_front(board);
}
ModelInput input;
input.sym = symmetry::kIdentity;
for (const auto& p : positions) {
input.position_history.push_back(&p);
}
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, FeatureType::kNumPlanes, buffer.data()};
FeatureType::Set({&input}, &features);
// B0 W0 B1 W1 B2 W2 B3 W3 B4 W4 B5 W5 B6 W6 B7 W7 C
std::vector<float> b9 = {{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}};
std::vector<float> h9 = {{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1}};
std::vector<float> a8 = {{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1}};
std::vector<float> j9 = {{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> d5 = {{1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> a1 = {{0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> a2 = {{1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> j1 = {{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> b1 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
if (std::is_same<FeatureType, ExtraFeatures>::value) {
// L1 L2 L3 C1 C2 C3 C4 C5 C6 C7 C8
b9.insert(b9.end(), {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0});
h9.insert(h9.end(), {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0});
a8.insert(a8.end(), {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0});
j9.insert(j9.end(), {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0});
d5.insert(d5.end(), {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
a1.insert(a1.end(), {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
a2.insert(a2.end(), {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0});
j1.insert(j1.end(), {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0});
b1.insert(b1.end(), {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0});
}
EXPECT_EQ(b9, GetStoneFeatures(features, Coord::FromString("B9")));
EXPECT_EQ(h9, GetStoneFeatures(features, Coord::FromString("H9")));
EXPECT_EQ(a8, GetStoneFeatures(features, Coord::FromString("A8")));
EXPECT_EQ(j9, GetStoneFeatures(features, Coord::FromString("J9")));
EXPECT_EQ(d5, GetStoneFeatures(features, Coord::FromString("D5")));
EXPECT_EQ(a1, GetStoneFeatures(features, Coord::FromString("A1")));
EXPECT_EQ(a2, GetStoneFeatures(features, Coord::FromString("A2")));
EXPECT_EQ(j1, GetStoneFeatures(features, Coord::FromString("J1")));
EXPECT_EQ(b1, GetStoneFeatures(features, Coord::FromString("B1")));
}
// Verfies that features work as expected when capturing.
TYPED_TEST(DualNetTest, TestStoneFeaturesWithCapture) {
using FeatureType = TypeParam;
TestablePosition board("");
std::vector<std::string> moves = {"J3", "pass", "H2", "J2",
"J1", "pass", "J2"};
std::deque<TestablePosition> positions;
for (const auto& move : moves) {
board.PlayMove(move);
positions.push_front(board);
}
ModelInput input;
input.sym = symmetry::kIdentity;
for (const auto& p : positions) {
input.position_history.push_back(&p);
}
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, FeatureType::kNumPlanes, buffer.data()};
FeatureType::Set({&input}, &features);
// W0 B0 W1 B1 W2 B2 W3 B3 W4 B4 W5 B5 W6 B6 W7 B7 C
std::vector<float> j2 = {{0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
if (std::is_same<FeatureType, ExtraFeatures>::value) {
// L1 L2 L3 C1 C2 C3 C4 C5 C6 C7 C8
j2.insert(j2.end(), {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
}
EXPECT_EQ(j2, GetStoneFeatures(features, Coord::FromString("J2")));
}
// Checks that the different backends produce the same result.
TYPED_TEST(DualNetTest, TestBackendsEqual) {
using FeatureType = TypeParam;
if (!std::is_same<FeatureType, AgzFeatures>::value) {
// TODO(tommadams): generate models for other feature types.
return;
}
struct Test {
Test(std::unique_ptr<ModelFactory> factory, std::string basename)
: factory(std::move(factory)), basename(std::move(basename)) {}
std::unique_ptr<ModelFactory> factory;
std::string basename;
};
std::map<std::string, Test> tests;
#if MG_ENABLE_TF_DUAL_NET
tests.emplace("TfDualNet",
Test(absl::make_unique<TfDualNetFactory>(std::vector<int>()),
"test_model.pb"));
#endif
#if MG_ENABLE_LITE_DUAL_NET
tests.emplace("LiteDualNet", Test(absl::make_unique<LiteDualNetFactory>(),
"test_model.tflite"));
#endif
Random rnd(Random::kUniqueSeed, Random::kUniqueStream);
ModelInput input;
input.sym = symmetry::kIdentity;
TestablePosition position("");
for (int i = 0; i < kN * kN; ++i) {
auto c = GetRandomLegalMove(position, &rnd);
position.PlayMove(c);
}
input.position_history.push_back(&position);
ModelOutput ref_output;
std::string ref_name;
auto policy_string = [](const std::array<float, kNumMoves>& policy) {
std::ostringstream oss;
std::copy(policy.begin(), policy.end(),
std::ostream_iterator<float>(oss, " "));
return oss.str();
};
for (const auto& kv : tests) {
const auto& name = kv.first;
auto& test = kv.second;
MG_LOG(INFO) << "Running " << name;
auto model =
test.factory->NewModel(absl::StrCat("cc/dual_net/", test.basename));
ModelOutput output;
std::vector<const ModelInput*> inputs = {&input};
std::vector<ModelOutput*> outputs = {&output};
model->RunMany(inputs, &outputs, nullptr);
if (ref_name.empty()) {
ref_output = output;
ref_name = name;
continue;
}
auto pred = [](float left, float right) {
return std::abs(left - right) <
0.0001f * (1.0f + std::abs(left) + std::abs(right));
};
EXPECT_EQ(std::equal(output.policy.begin(), output.policy.end(),
ref_output.policy.begin(), pred),
true)
<< name << ": " << policy_string(output.policy) << "\n"
<< ref_name << ": " << policy_string(ref_output.policy);
EXPECT_NEAR(output.value, ref_output.value, 0.0001f)
<< name << " vs " << ref_name;
}
}
TEST(WouldCaptureTest, WouldCaptureBlack) {
TestablePosition board(R"(
OOOX.XOOX
OXX....X.
.OOX.....
OOOOX....
XXXXX....)");
ModelInput input;
input.sym = symmetry::kIdentity;
input.position_history.push_back(&board);
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, ExtraFeatures::kNumPlanes,
buffer.data()};
ExtraFeatures::Set({&input}, &features);
// W0 B0 W1 B1 W2 B2 W3 B3 W4 B4 W5 B5 W6 B6 W7 B7 C
std::vector<float> a7 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
std::vector<float> g8 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
// L1 L2 L3 C1 C2 C3 C4 C5 C6 C7 C8
a7.insert(a7.end(), {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1});
g8.insert(g8.end(), {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0});
EXPECT_EQ(a7, GetStoneFeatures(features, Coord::FromString("A7")));
EXPECT_EQ(g8, GetStoneFeatures(features, Coord::FromString("G8")));
}
TEST(WouldCaptureTest, WouldCaptureWhite) {
TestablePosition board(R"(
XXXO.OXXO
XOO....O.
.XXO.....
XXXXO....
OOOOO....)",
Color::kWhite);
ModelInput input;
input.sym = symmetry::kIdentity;
input.position_history.push_back(&board);
BoardFeatureBuffer<float> buffer;
Tensor<float> features = {1, kN, kN, ExtraFeatures::kNumPlanes,
buffer.data()};
ExtraFeatures::Set({&input}, &features);
// W0 B0 W1 B1 W2 B2 W3 B3 W4 B4 W5 B5 W6 B6 W7 B7 C
std::vector<float> a7 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
std::vector<float> g8 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
// L1 L2 L3 C1 C2 C3 C4 C5 C6 C7 C8
a7.insert(a7.end(), {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1});
g8.insert(g8.end(), {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0});
EXPECT_EQ(a7, GetStoneFeatures(features, Coord::FromString("A7")));
EXPECT_EQ(g8, GetStoneFeatures(features, Coord::FromString("G8")));
}
} // namespace
} // namespace minigo
| 34.646526 | 80 | 0.60429 | [
"vector",
"model"
] |
ac770afbb947becd151e5df274a12c2c28ea083d | 1,455 | cc | C++ | Chapter01/dlib_samples/linreg_dlib.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 201 | 2020-05-13T12:50:50.000Z | 2022-03-27T20:56:11.000Z | Chapter01/dlib_samples/linreg_dlib.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 1 | 2021-05-12T10:01:40.000Z | 2021-05-14T19:35:05.000Z | Chapter01/dlib_samples/linreg_dlib.cc | bdonkey/Hands-On-Machine-Learning-with-CPP | d2b17abeb48db3d45369fdb1be806682ab9819ed | [
"MIT"
] | 63 | 2020-06-05T15:03:39.000Z | 2022-02-22T02:07:09.000Z | #include <dlib/matrix.h>
#include <dlib/svm.h>
#include <iostream>
#include <random>
float func(float x) {
return 4.f + 0.3f * x; // line coeficients
}
using SampleType = dlib::matrix<double, 1, 1>;
using KernelType = dlib::linear_kernel<SampleType>;
int main() {
using namespace dlib;
size_t n = 1000;
std::vector<matrix<double>> x(n);
std::vector<float> y(n);
std::random_device rd;
std::mt19937 re(rd());
std::uniform_real_distribution<float> dist(-1.5, 1.5);
// generate data
for (size_t i = 0; i < n; ++i) {
x[i].set_size(1, 1);
x[i](0, 0) = i;
y[i] = func(i) + dist(re);
}
// // normalize data
vector_normalizer<matrix<double>> normalizer_x;
// let the normalizer learn the mean and standard deviation of the samples
normalizer_x.train(x);
// now normalize each sample
for (size_t i = 0; i < x.size(); ++i) {
x[i] = normalizer_x(x[i]);
}
krr_trainer<KernelType> trainer;
trainer.set_kernel(KernelType());
decision_function<KernelType> df = trainer.train(x, y);
// Generate new data
std::cout << "Original data \n";
std::vector<matrix<double>> new_x(5);
for (size_t i = 0; i < 5; ++i) {
new_x[i].set_size(1, 1);
new_x[i](0, 0) = i;
new_x[i] = normalizer_x(new_x[i]);
std::cout << func(i) << std::endl;
}
std::cout << "Predictions \n";
for (auto& v : new_x) {
auto prediction = df(v);
std::cout << prediction << std::endl;
}
return 0;
}
| 23.095238 | 76 | 0.613058 | [
"vector"
] |
ac7ca21b61fba992077eda8dfe3de65043a5b7a6 | 12,590 | hpp | C++ | src/problems/distance_barrier_rb_problem.hpp | ipc-sim/rigid-ipc | d839af457236e7363b14c2e482a01d8160fa447e | [
"MIT"
] | 71 | 2021-09-08T13:16:43.000Z | 2022-03-27T10:23:33.000Z | src/problems/distance_barrier_rb_problem.hpp | ipc-sim/rigid-ipc | d839af457236e7363b14c2e482a01d8160fa447e | [
"MIT"
] | 4 | 2021-09-08T00:16:20.000Z | 2022-01-05T17:44:08.000Z | src/problems/distance_barrier_rb_problem.hpp | ipc-sim/rigid-ipc | d839af457236e7363b14c2e482a01d8160fa447e | [
"MIT"
] | 2 | 2021-09-18T15:15:38.000Z | 2021-09-21T15:15:38.000Z | #pragma once
#include <tbb/concurrent_vector.h>
#include <ipc/collision_constraint.hpp>
#include <ipc/friction/friction_constraint.hpp>
#include <autodiff/autodiff_types.hpp>
#include <opt/distance_barrier_constraint.hpp>
#include <opt/optimization_problem.hpp>
#include <physics/rigid_body_problem.hpp>
#include <problems/rigid_body_collision_constraint.hpp>
#include <solvers/homotopy_solver.hpp>
#include <utils/multiprecision.hpp>
namespace ipc::rigid {
/// @brief Possible methods for detecting all edge vertex collisions.
enum BodyEnergyIntegrationMethod {
IMPLICIT_EULER,
IMPLICIT_NEWMARK,
STABILIZED_NEWMARK
};
const static BodyEnergyIntegrationMethod
DEFAULT_BODY_ENERGY_INTEGRATION_METHOD = IMPLICIT_EULER;
NLOHMANN_JSON_SERIALIZE_ENUM(
BodyEnergyIntegrationMethod,
{ { IMPLICIT_EULER, "implicit_euler" },
{ IMPLICIT_NEWMARK, "implicit_newmark" },
{ STABILIZED_NEWMARK, "stabilized_newmark" },
{ DEFAULT_BODY_ENERGY_INTEGRATION_METHOD, "default" } });
/// This class is both a simulation and optimization problem.
class DistanceBarrierRBProblem : public RigidBodyProblem,
public virtual BarrierProblem {
public:
DistanceBarrierRBProblem();
virtual ~DistanceBarrierRBProblem() = default;
bool settings(const nlohmann::json& params) override;
nlohmann::json settings() const override;
nlohmann::json state() const override;
static std::string problem_name() { return "distance_barrier_rb_problem"; }
virtual std::string name() const override
{
return DistanceBarrierRBProblem::problem_name();
}
////////////////////////////////////////////////////////////
// Rigid Body Problem
void simulation_step(
bool& had_collisions,
bool& has_intersections,
bool solve_collisions = true) override;
bool take_step(const Eigen::VectorXd& x) override;
/// Use the solver to solve this problem.
OptimizationResults solve_constraints() override;
////////////////////////////////////////////////////////////
// Optimization Problem
/// @returns the number of variables
int num_vars() const override { return num_vars_; }
/// @returns A vector of booleans indicating if a DoF is fixed.
const VectorXb& is_dof_fixed() const override
{
return m_assembler.is_rb_dof_fixed;
}
Eigen::VectorXi free_dof() const override;
/// Determine if there is a collision between two configurations
bool has_collisions(
const Eigen::VectorXd& x_i, const Eigen::VectorXd& x_j) override;
/// Compute the earliest time of impact between two configurations
double compute_earliest_toi(
const Eigen::VectorXd& x_i, const Eigen::VectorXd& x_j) override;
bool is_ccd_aligned_with_newton_update() override
{
return m_constraint.trajectory_type != TrajectoryType::LINEAR;
}
/// Get the world coordinates of the vertices
Eigen::MatrixXd world_vertices(const Eigen::VectorXd& x) const override
{
return m_assembler.world_vertices(this->dofs_to_poses(x));
}
/// Get the length of the diagonal of the worlds bounding box
double world_bbox_diagonal() const override
{
// TODO: Compute this value dynamicly if necessary
return init_bbox_diagonal;
}
/// Get the mass matrix
DiagonalMatrixXd mass_matrix() const override
{
return m_assembler.m_rb_mass_matrix;
}
/// Get the average mass (average of mass matrix diagonal)
double average_mass() const override { return m_assembler.average_mass; }
/// Get the time-step
double timestep() const override { return RigidBodyProblem::timestep(); }
////////////////////////////////////////////////////////////
// Barrier Problem
/// Compute the objective function f(x)
double compute_objective(
const Eigen::VectorXd& x,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
bool compute_grad = true,
bool compute_hess = true) override;
/// Compute E(x) in f(x) = E(x) + κ ∑_{k ∈ C} b(d(x_k))
double compute_energy_term(
const Eigen::VectorXd& x,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
bool compute_grad = true,
bool compute_hess = true) override;
/// Compute ∑_{k ∈ C} b(d(x_k)) in f(x) = E(x) + κ ∑_{k ∈ C} b(d(x_k))
double compute_barrier_term(
const Eigen::VectorXd& x,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
int& num_constraints,
bool compute_grad = true,
bool compute_hess = true) override;
double compute_friction_term(
const Eigen::VectorXd& x,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
bool compute_grad = true,
bool compute_hess = true);
virtual double compute_friction_term(const Eigen::VectorXd& x) final
{
Eigen::VectorXd grad;
Eigen::SparseMatrix<double> hess;
return compute_friction_term(
x, grad, hess, /*compute_grad=*/false, /*compute_hess=*/false);
}
virtual double
compute_friction_term(const Eigen::VectorXd& x, Eigen::VectorXd& grad) final
{
Eigen::SparseMatrix<double> hess;
return compute_friction_term(
x, grad, hess, /*compute_grad=*/true, /*compute_hess=*/false);
}
// Include thes lines to avoid issues with overriding inherited
// functions with the same name.
// (http://www.cplusplus.com/forum/beginner/24978/)
using BarrierProblem::compute_barrier_term;
using BarrierProblem::compute_energy_term;
/// Compute the minimum distance among geometry
double compute_min_distance() const override;
double compute_min_distance(const Eigen::VectorXd& x) const override;
/// Compute the value of the barrier at a distance x
double barrier_hessian(double x) const override
{
return m_constraint.distance_barrier_hessian(x);
}
double barrier_activation_distance() const override
{
return m_constraint.barrier_activation_distance();
}
void barrier_activation_distance(double dhat) override
{
m_constraint.barrier_activation_distance(dhat);
}
double barrier_stiffness() const override { return m_barrier_stiffness; }
void barrier_stiffness(double kappa) override
{
m_barrier_stiffness = kappa;
}
CollisionConstraint& constraint() override { return m_constraint; }
const CollisionConstraint& constraint() const override
{
return m_constraint;
}
OptimizationSolver& solver() override { return *m_opt_solver; }
int num_contacts() const override { return m_num_contacts; };
////////////////////////////////////////////////////////////
// Augmented Lagrangian for equality constraints
/// Initialize the augmented Lagrangian variables.
void init_augmented_lagrangian();
/// Update the target poses of kinematic bodies
void step_kinematic_bodies();
/// Update the augmented Lagrangian for kinematic bodies.
void update_augmented_lagrangian(const Eigen::VectorXd& x) override;
/// Compute the convergence criteria η of the augment Lagrangian.
double
compute_linear_augment_lagrangian_progress(const Eigen::VectorXd& x) const;
double
compute_angular_augment_lagrangian_progress(const Eigen::VectorXd& x) const;
/// Determine if the value x satisfies the equality constraints.
bool
are_equality_constraints_satisfied(const Eigen::VectorXd& x) const override;
/// Compute the augmented Lagrangian potential used to enforce equality
/// constraints.
double compute_augmented_lagrangian(
const Eigen::VectorXd& x,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
bool compute_grad,
bool compute_hess);
protected:
/// Update problem using current status of bodies.
virtual void update_constraints() override;
/// Update problem using current status of bodies.
void update_friction_constraints(
const Constraints& collision_constraints, const PosesD& poses);
template <typename T>
T compute_body_energy(
const RigidBody& body,
const Pose<T>& pose,
const VectorMax6d& grad_barrier_t0);
template <typename RigidBodyConstraint, typename FrictionConstraint>
double compute_friction_potential(
const Eigen::MatrixXd& U,
const Eigen::MatrixXd& jac_V,
const Eigen::MatrixXd& hess_V,
const FrictionConstraint& constraint,
Eigen::VectorXd& grad,
std::vector<Eigen::Triplet<double>>& hess_triplets,
bool compute_grad,
bool compute_hess);
/// Computes the barrier term value, gradient, and hessian from
/// distance constraints.
double compute_barrier_term(
const Eigen::VectorXd& x,
const Constraints& distance_constraints,
Eigen::VectorXd& grad,
Eigen::SparseMatrix<double>& hess,
bool compute_grad,
bool compute_hess);
virtual double compute_barrier_term(
const Eigen::VectorXd& x, const Constraints& distance_constraints) final
{
Eigen::VectorXd grad;
Eigen::SparseMatrix<double> hess;
return compute_barrier_term(
x, distance_constraints, grad, hess, /*compute_grad=*/false,
/*compute_hess=*/false);
}
virtual double compute_barrier_term(
const Eigen::VectorXd& x,
const Constraints& distance_constraints,
Eigen::VectorXd& grad) final
{
Eigen::SparseMatrix<double> hess;
return compute_barrier_term(
x, distance_constraints, grad, hess, /*compute_grad=*/true,
/*compute_hess=*/false);
}
#ifdef RIGID_IPC_WITH_DERIVATIVE_CHECK
// The following functions are used exclusivly to check that the
// gradient and hessian match a finite difference version.
template <typename RigidBodyConstraint, typename Constraint>
void check_distance_finite_gradient(
const Eigen::VectorXd& x, const Constraint& constraint);
template <typename RigidBodyConstraint, typename Constraint>
void check_distance_finite_hessian(
const Eigen::VectorXd& x, const Constraint& constraint);
void check_barrier_gradient(
const Eigen::VectorXd& x,
const Constraints& constraints,
const Eigen::VectorXd& grad);
void check_barrier_hessian(
const Eigen::VectorXd& x,
const Constraints& constraints,
const Eigen::SparseMatrix<double>& hess);
void check_friction_gradient(
const Eigen::VectorXd& x, const Eigen::VectorXd& grad);
void check_friction_hessian(
const Eigen::VectorXd& x, const Eigen::SparseMatrix<double>& hess);
void check_augmented_lagrangian_gradient(
const Eigen::VectorXd& x, const Eigen::VectorXd& grad);
void check_augmented_lagrangian_hessian(
const Eigen::VectorXd& x, const Eigen::SparseMatrix<double>& hess);
bool is_checking_derivative = false;
#endif
/// @brief Constraint helper for active set and collision detection.
DistanceBarrierConstraint m_constraint;
/// @brief Solver for solving this optimization problem.
std::shared_ptr<OptimizationSolver> m_opt_solver;
/// @brief Multiplier of barrier term in objective, \f$\kappa\f$.
double m_barrier_stiffness;
/// @brief Current minimum distance between bodies.
/// Negative values indicate a minimum distance greater than the
/// activation distance.
double min_distance;
/// @brief Did the step have collisions?
bool m_had_collisions;
/// @brief The number of collision during the timestep.
int m_num_contacts;
/// @brief Gradient of barrier potential at the start of the time-step.
Eigen::VectorXd grad_barrier_t0;
// Friction
double static_friction_speed_bound;
int friction_iterations;
FrictionConstraints friction_constraints;
// Augmented Lagrangian
double linear_augmented_lagrangian_penalty;
double angular_augmented_lagrangian_penalty;
Eigen::VectorXd linear_augmented_lagrangian_multiplier;
Eigen::MatrixXd angular_augmented_lagrangian_multiplier;
Eigen::VectorXd x_pred; ///< Predicted DoF using unconstrained timestep
VectorXb is_dof_satisfied;
private:
/// Method for integrating the body energy.
BodyEnergyIntegrationMethod body_energy_integration_method;
};
} // namespace ipc::rigid
| 34.027027 | 80 | 0.685703 | [
"geometry",
"vector"
] |
ac80f1b02ced911f93c71c0dfd784b7b69bd7a46 | 1,420 | hpp | C++ | meta/include/mgs/meta/concepts/forward_iterator.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | 24 | 2020-07-01T13:45:50.000Z | 2021-11-04T19:54:47.000Z | meta/include/mgs/meta/concepts/forward_iterator.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | meta/include/mgs/meta/concepts/forward_iterator.hpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <iterator>
#include <tuple>
#include <type_traits>
#include <mgs/meta/concepts/derived_from.hpp>
#include <mgs/meta/concepts/incrementable.hpp>
#include <mgs/meta/concepts/input_iterator.hpp>
#include <mgs/meta/concepts/sentinel_for.hpp>
#include <mgs/meta/detected.hpp>
#include <mgs/meta/detected/types/iterator_category.hpp>
#include <mgs/meta/iter_concept.hpp>
namespace mgs
{
namespace meta
{
template <typename T>
struct is_forward_iterator
{
private:
static constexpr auto const has_correct_category =
is_derived_from<detected_t<meta::iter_concept, T>,
std::forward_iterator_tag>::value;
public:
using requirements =
std::tuple<is_input_iterator<T>, is_incrementable<T>, is_sentinel_for<T, T>>;
static constexpr auto const value =
is_input_iterator<T>::value && has_correct_category &&
is_sentinel_for<T, T>::value && is_incrementable<T>::value;
static constexpr int trigger_static_asserts()
{
static_assert(value, "T does not model meta::forward_iterator");
static_assert(
has_correct_category,
"iterator category tag must derive from std::forward_iterator_tag");
return 1;
}
};
template <typename T>
constexpr auto is_forward_iterator_v = is_forward_iterator<T>::value;
template <typename T,
typename = std::enable_if_t<is_forward_iterator<T>::value>>
using forward_iterator = T;
}
}
| 26.296296 | 83 | 0.734507 | [
"model"
] |
ac83c2ba34d6ee2ef936366d4501459b68877f9d | 1,086 | cpp | C++ | Assignments/Week2 Solution - Talha Tariq/Binary Search/P4 - Find Peak Element.cpp | TT-talhatariq/DSA-Bootcamp-Cpp | 823e8d8e3e01803667636f9c2be8f3e520214df3 | [
"MIT"
] | null | null | null | Assignments/Week2 Solution - Talha Tariq/Binary Search/P4 - Find Peak Element.cpp | TT-talhatariq/DSA-Bootcamp-Cpp | 823e8d8e3e01803667636f9c2be8f3e520214df3 | [
"MIT"
] | null | null | null | Assignments/Week2 Solution - Talha Tariq/Binary Search/P4 - Find Peak Element.cpp | TT-talhatariq/DSA-Bootcamp-Cpp | 823e8d8e3e01803667636f9c2be8f3e520214df3 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include <string.h>
using namespace std;
int findPeakBruteForce(vector<int> &arr) {
for(int i=1; i<arr.size()-1; i++){
if(arr[i] > arr[i-1] && arr[i] > arr[i+1] )
return arr[i];
}
if(arr[0] < arr[1] && arr[1] < arr[2])
return arr[arr.size()-1];
else
return arr[0];
}
// Binary Search
int findPeakBinary(vector<int> &arr) {
int start = 0;
int end = arr.size()-1;
while(start < end){
int mid = start + (end-start)/2;
if(arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])
return arr[mid];
else if(arr[mid] > arr[mid-1] && arr[mid] < arr[mid+1] )
start = mid+1;
else
end = mid-1;
}
return arr[start];
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int> v;
for(int i=0; i<n; i++){
int val;
cin >> val;
v.push_back(val);
}
cout << findPeakBinary(v) << endl;
}
return 0;
} | 20.111111 | 64 | 0.446593 | [
"vector"
] |
ac85e802d9c056489a55aef57bf8f2c4ccdaf1cd | 2,878 | cpp | C++ | LeetCode/C++/Companies/Google/Medium/FindAndReplaceInString/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/Companies/Google/Medium/FindAndReplaceInString/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/Companies/Google/Medium/FindAndReplaceInString/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <utility>
#include <vector>
/*
Solution: see comments for details
Time complexity: O((n log n) + n) [where n is the number of indices in the indices vector]
Space complexity: O(n)
*/
class Solution
{
public:
string findReplaceString(string s, vector<int> & indices, vector<string> & sources, vector<string> & targets)
{
int n=s.size();
int m=indices.size();
string result{};
int index=0;
//Hashtable that maps the replacement index to a pair of strings: the source and target
//Use map becuase we need to sort the replacement indices in increasing order
map<int, pair<string, string>> hashtable;
//Fill the map
for(int i=0;i<m;i++)
{
hashtable.emplace(indices[i], make_pair(sources[i], targets[i]));
}
//Since the first replacement index could be after index zero,
//we need to add letters from the string until we hit the first replacement index
while(index < n && index < begin(hashtable)->first)
{
result+=s[index];
index++;
}
//Iterate through the hashtable
for(auto element : hashtable)
{
//Replacement index
int start=element.first;
string source=element.second.first;
string target=element.second.second;
int substringLength=source.size();
//Get the substring starting at index start and extending substringLength characters
string substring=s.substr(start, substringLength);
//If the substring matches the source, add the target to the result string and move our index variable forward substringLength spots
if(substring==source)
{
result+=target;
index+=substringLength;
}
//Else, the source does not match the substring
//Add the substring to the result string and move our index variable forward substringLength spots
else
{
result+=substring;
index+=substringLength;
}
//To handle the case where the current replacement index is not consecutively followed by the next replacement index, we keep moving the index variable forward till we reach the next replacement index, adding the letters as we go
while(index < n && !hashtable.count(index))
{
result+=s[index];
index++;
}
}
return result;
}
}; | 32.337079 | 245 | 0.552814 | [
"vector"
] |
ac866a6d0474260d3d3ff2d5b5b6893ffe4945ca | 5,066 | cpp | C++ | core/src/ceps_interpreter_eval_id.cpp | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | 3 | 2018-09-11T11:40:24.000Z | 2021-07-02T10:24:36.000Z | core/src/ceps_interpreter_eval_id.cpp | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | null | null | null | core/src/ceps_interpreter_eval_id.cpp | cepsdev/ceps | badd1ac7582034f9b4f000ee93828bd584cf858b | [
"MIT"
] | null | null | null | /*
(C) 2021 Tomas Prerovsky (cepsdev@hotmail.com).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.elete
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 "ceps_interpreter.hh"
#include "symtab.hh"
#include <cmath>
#include "ceps_interpreter_loop.hh"
#include "ceps_interpreter_nodeset.hh"
ceps::ast::Nodebase_ptr ceps::interpreter::eval_id(ceps::ast::Nodebase_ptr root_node,
ceps::parser_env::Symboltable & sym_table,
ceps::interpreter::Environment& env,
ceps::ast::Nodebase_ptr parent_node,
ceps::ast::Nodebase_ptr predecessor,
bool& symbols_found,
ceps::interpreter::thoroughness_t thoroughness
)
{
using namespace ceps::parser_env;
ceps::ast::Identifier& id = *dynamic_cast<ceps::ast::Identifier*>(root_node);
if (name(id) == "m" || name(id) == "metre" || name(id) == "meter")
{
return new ceps::ast::Int(1, ceps::ast::m_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "s" || name(id) == "second")
{
return new ceps::ast::Int(1, ceps::ast::s_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "kg" || name(id) == "kilogram")
{
return new ceps::ast::Int(1, ceps::ast::kg_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "celsius" || name(id) == "kelvin")
{
return new ceps::ast::Int(1, ceps::ast::kelvin_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "ampere" )
{
return new ceps::ast::Int(1, ceps::ast::ampere_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "cd" || name(id) == "candela" )
{
return new ceps::ast::Int(1, ceps::ast::candela_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "mol" || name(id) == "mole" )
{
return new ceps::ast::Int(1, ceps::ast::mol_unit(), nullptr, nullptr, nullptr);
}
else if (name(id) == "scope"){
if (env.scope)
return create_ast_nodeset("", *env.scope);
return create_ast_nodeset("",std::vector<ceps::ast::Nodebase_ptr>{});
}
else if (name(id) == "root" && env.associated_universe() != nullptr)
return create_ast_nodeset("", env.associated_universe()->nodes());
else if (name(id) == "arglist"){
ceps::parser_env::Symbol* sym_ptr;
if ( (sym_ptr = sym_table.lookup(name(id))) == nullptr)
throw semantic_exception{root_node,"arglist undefined (not inside macro body)."};
if (sym_ptr->category != ceps::parser_env::Symbol::Category::NODESET)
throw semantic_exception{root_node,"arglist was redefined with wrong type (should be nodeset)."};
if(nullptr == sym_ptr->payload)
throw semantic_exception{root_node,"arglist undefined."};
ceps::ast::Ast_nodeset_ptr ndeset = (ceps::ast::Ast_nodeset_ptr)(sym_ptr->payload);
return ndeset;
}
ceps::parser_env::Symbol* sym_ptr;
if ( (sym_ptr = sym_table.lookup(name(id))) == nullptr)
{
//throw semantic_exception{root_node,"Variable '" +name(id)+"' is not defined."};
std::string id_name = name(id);
return new ceps::ast::Identifier(id_name,nullptr,nullptr,nullptr);
}
ceps::parser_env::Symbol& sym = *sym_ptr;
if (sym_ptr->category == ceps::parser_env::Symbol::Category::SYMBOL )
{
symbols_found = true;
return new ceps::ast::Symbol(name(id), ((ceps::parser_env::Symbol*)sym_ptr->payload)->name, nullptr, nullptr, nullptr);
}
if (sym_ptr->category == ceps::parser_env::Symbol::Category::MACRO)
{
return new ceps::ast::Identifier(name(id),nullptr,nullptr,nullptr);
}
else if (sym.category != ceps::parser_env::Symbol::Category::VAR)
throw semantic_exception{root_node,"Variable '" +name(id)+"' is not defined."};
if (sym.payload == nullptr) return new ceps::ast::Undefined(nullptr,nullptr,nullptr);
ceps::ast::Nodebase_ptr node_ptr = reinterpret_cast<ceps::ast::Nodebase_ptr>(sym.payload);
if (node_ptr->kind() == ceps::ast::Ast_node_kind::float_literal)
{
ceps::ast::Double & v = *dynamic_cast<ceps::ast::Double*>(node_ptr);
return new ceps::ast::Double(value(v), unit(v), nullptr, nullptr, nullptr);
}
else if (node_ptr->kind() == ceps::ast::Ast_node_kind::int_literal)
{
ceps::ast::Int & v = *dynamic_cast<ceps::ast::Int*>(node_ptr);
return new ceps::ast::Int( value(v), unit(v), nullptr, nullptr, nullptr );
}
else if (node_ptr->kind() == ceps::ast::Ast_node_kind::string_literal)
{
ceps::ast::String & v = *dynamic_cast<ceps::ast::String*>(node_ptr);
return new ceps::ast::String(value(v), nullptr, nullptr, nullptr);
}
else if (node_ptr->kind() == ceps::ast::Ast_node_kind::symbol)
{
auto & v = as_symbol_ref(node_ptr);
symbols_found = true;
return new ceps::ast::Symbol(name(v), kind(v), nullptr, nullptr, nullptr);
}
else
return node_ptr;
}
| 36.185714 | 122 | 0.680418 | [
"vector"
] |
12c63d367673c7fe75cf49d3d246255fe553e74b | 1,124 | cpp | C++ | Leetcode Daily Challenge/December-2020/05. Can Place Flowers.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Daily Challenge/December-2020/05. Can Place Flowers.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Daily Challenge/December-2020/05. Can Place Flowers.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Can Place Flowers
=================
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Constraints:
1 <= flowerbed.length <= 2 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length
*/
class Solution
{
public:
bool canPlaceFlowers(vector<int> &flowerbed, int k)
{
int n = flowerbed.size(), ans = 0;
for (int i = 0; i < n; ++i)
{
if (flowerbed[i] == 0)
{
int prev = i == 0 ? 0 : flowerbed[i - 1];
int next = i == n - 1 ? 0 : flowerbed[i + 1];
if (prev == 0 && next == 0)
{
flowerbed[i] = 1;
ans++;
}
}
}
return ans >= k;
}
};
| 23.416667 | 221 | 0.592527 | [
"vector"
] |
12c864cb00f70349d3ec680ab8ef91c3e19da9bb | 7,399 | cpp | C++ | test/ServerFifoPathTest.cpp | MisterTea/EternalTCP | 113fb23133eabce3d11681392d75ba4772814b44 | [
"Apache-2.0"
] | 568 | 2016-11-20T07:19:40.000Z | 2018-02-24T20:08:47.000Z | test/ServerFifoPathTest.cpp | MisterTea/EternalTCP | 113fb23133eabce3d11681392d75ba4772814b44 | [
"Apache-2.0"
] | 83 | 2016-12-02T19:04:32.000Z | 2018-02-27T01:30:32.000Z | test/ServerFifoPathTest.cpp | MisterTea/EternalTCP | 113fb23133eabce3d11681392d75ba4772814b44 | [
"Apache-2.0"
] | 35 | 2016-12-12T19:07:17.000Z | 2018-02-18T18:23:19.000Z | #include <ftw.h>
#include <filesystem>
#include <optional>
#include "ServerFifoPath.hpp"
#include "TestHeaders.hpp"
using namespace et;
namespace {
struct FileInfo {
bool exists = false;
mode_t mode = 0;
mode_t fileMode() const { return mode & 0777; }
// Codespaces and similar environments may enforce additional ACLs, so verify
// that the permissions are less than a certain maximum. See
// https://github.community/t/bug-umask-does-not-seem-to-be-respected/129638
void requireFileModeLessPrivilegedThan(mode_t highestMode) const {
INFO("fileMode()=" << fileMode() << ", highestMode=" << highestMode);
REQUIRE((fileMode() & highestMode) == fileMode());
}
};
int RemoveDirectory(const char* path) {
// Use posix file tree walk to traverse the directory and remove the contents.
return nftw(
path,
[](const char* fpath, const struct stat* sb, int typeflag,
struct FTW* ftwbuf) { return ::remove(fpath); },
64, // Maximum open fds.
FTW_DEPTH | FTW_PHYS);
}
class TestEnvironment {
public:
string createTempDir() {
string tmpPath = GetTempDirectory() + string("et_test_XXXXXXXX");
const string dir = string(mkdtemp(&tmpPath[0]));
temporaryDirs.push_back(dir);
return dir;
}
FileInfo getFileInfo(const string& name) {
struct stat fileStat;
const int statResult = ::stat(name.c_str(), &fileStat);
if (statResult != 0) {
return FileInfo{};
}
FileInfo result;
result.exists = true;
result.mode = fileStat.st_mode;
return result;
}
void setEnv(const char* name, const string& value) {
if (!savedEnvs.count(name)) {
const char* previousValue = ::getenv(name);
if (previousValue) {
savedEnvs[name] = string(previousValue);
} else {
savedEnvs[name] = std::nullopt;
}
}
const int replace = 1; // non-zero to replace.
::setenv(name, value.c_str(), replace);
}
~TestEnvironment() {
// Remove temporary dirs.
for (const string& dir : temporaryDirs) {
const int removeResult = RemoveDirectory(dir.c_str());
if (removeResult == -1) {
LOG(ERROR) << "Error when removing dir: " << dir;
FATAL_FAIL(removeResult);
}
}
// Restore env.
for (const auto& [key, value] : savedEnvs) {
if (value) {
const int replace = 1; // non-zero to replace.
::setenv(key.c_str(), value->c_str(), replace);
} else {
::unsetenv(key.c_str());
}
}
}
private:
vector<string> temporaryDirs;
map<string, optional<string>> savedEnvs;
};
} // namespace
TEST_CASE("Creation", "[ServerFifoPath]") {
TestEnvironment env;
const string homeDir = env.createTempDir();
env.setEnv("HOME", homeDir.c_str());
INFO("homeDir = " << homeDir);
const string expectedFifoPath =
homeDir + "/.local/share/etserver/etserver.idpasskey.fifo";
ServerFifoPath serverFifo;
REQUIRE(serverFifo.getPathForCreation() == expectedFifoPath);
REQUIRE(serverFifo.getEndpointForConnect() ==
std::nullopt); // Expected to be null unless the path is overridden.
SECTION("Create all directories") {
REQUIRE(!env.getFileInfo(homeDir + "/.local/share/etserver").exists);
serverFifo.createDirectoriesIfRequired();
// Verify the entire tree is created with the correct permissions.
env.getFileInfo(homeDir + "/.local")
.requireFileModeLessPrivilegedThan(0755);
env.getFileInfo(homeDir + "/.local/share")
.requireFileModeLessPrivilegedThan(0755);
env.getFileInfo(homeDir + "/.local/share/etserver")
.requireFileModeLessPrivilegedThan(0700);
}
const string localDir = homeDir + "/.local";
const mode_t localDirMode = 0777; // Create with different permissions so
// we can check that this hasn't changed.
const string shareDir = homeDir + "/.local/share";
const mode_t shareDirMode = 0770; // Another non-default mode.
const string etserverDir = homeDir + "/.local/share/etserver";
SECTION(".local already exists") {
const int oldMask = ::umask(0);
FATAL_FAIL(::mkdir(localDir.c_str(), localDirMode));
::umask(oldMask);
serverFifo.createDirectoriesIfRequired();
env.getFileInfo(homeDir + "/.local")
.requireFileModeLessPrivilegedThan(localDirMode);
env.getFileInfo(homeDir + "/.local/share")
.requireFileModeLessPrivilegedThan(0755);
env.getFileInfo(homeDir + "/.local/share/etserver")
.requireFileModeLessPrivilegedThan(0700);
}
SECTION(".local/share already exists") {
const int oldMask = ::umask(0);
FATAL_FAIL(::mkdir(localDir.c_str(), localDirMode));
FATAL_FAIL(::mkdir(shareDir.c_str(), shareDirMode));
::umask(oldMask);
serverFifo.createDirectoriesIfRequired();
env.getFileInfo(homeDir + "/.local")
.requireFileModeLessPrivilegedThan(localDirMode);
env.getFileInfo(homeDir + "/.local/share")
.requireFileModeLessPrivilegedThan(shareDirMode);
env.getFileInfo(homeDir + "/.local/share/etserver")
.requireFileModeLessPrivilegedThan(0700);
}
SECTION(".local/share/etserver already exists") {
const mode_t etserverDirMode = 0750; // Use slightly different permissions,
// but still without write access.
const int oldMask = ::umask(0);
FATAL_FAIL(::mkdir(localDir.c_str(), localDirMode));
FATAL_FAIL(::mkdir(shareDir.c_str(), shareDirMode));
FATAL_FAIL(::mkdir(etserverDir.c_str(), etserverDirMode));
::umask(oldMask);
serverFifo.createDirectoriesIfRequired();
env.getFileInfo(homeDir + "/.local")
.requireFileModeLessPrivilegedThan(localDirMode);
env.getFileInfo(homeDir + "/.local/share")
.requireFileModeLessPrivilegedThan(shareDirMode);
env.getFileInfo(homeDir + "/.local/share/etserver")
.requireFileModeLessPrivilegedThan(etserverDirMode);
}
SECTION("Override XDG_RUNTIME_DIR") {
const string xdgRuntimeDir = env.createTempDir();
env.setEnv("XDG_RUNTIME_DIR", xdgRuntimeDir);
const string xdgRuntimeDirFifoPath =
xdgRuntimeDir + "/etserver/etserver.idpasskey.fifo";
REQUIRE(serverFifo.getPathForCreation() == xdgRuntimeDirFifoPath);
// Test creation of the etserver subdirectory.
const string xdgRuntimeDirEtserver = xdgRuntimeDir + "/etserver";
REQUIRE(!env.getFileInfo(xdgRuntimeDirEtserver).exists);
serverFifo.createDirectoriesIfRequired();
env.getFileInfo(xdgRuntimeDirEtserver)
.requireFileModeLessPrivilegedThan(0700);
}
}
TEST_CASE("Override", "[ServerFifoPath]") {
TestEnvironment env;
const string homeDir = env.createTempDir();
env.setEnv("HOME", homeDir.c_str());
const string expectedFifoPath =
homeDir + "/.local/share/etserver/etserver.idpasskey.fifo";
ServerFifoPath serverFifo;
REQUIRE(serverFifo.getPathForCreation() == expectedFifoPath);
REQUIRE(serverFifo.getEndpointForConnect() == std::nullopt);
// Override and re-test.
const string pathOverride = env.createTempDir() + "/etserver.idpasskey.fifo";
serverFifo.setPathOverride(pathOverride);
REQUIRE(serverFifo.getPathForCreation() == pathOverride);
const optional<SocketEndpoint> endpoint = serverFifo.getEndpointForConnect();
REQUIRE(endpoint != std::nullopt);
REQUIRE(endpoint.value().name() == pathOverride);
}
| 32.030303 | 80 | 0.679822 | [
"vector"
] |
12ce9e04f11561e56e74f77bff632e465ee740e4 | 3,312 | cpp | C++ | Shiny_Engine/ComponentGraphScript.cpp | AleixCas95/Shiny_Engine | a5dca52725ed20c11f929a581e1b442988ec3237 | [
"MIT"
] | null | null | null | Shiny_Engine/ComponentGraphScript.cpp | AleixCas95/Shiny_Engine | a5dca52725ed20c11f929a581e1b442988ec3237 | [
"MIT"
] | null | null | null | Shiny_Engine/ComponentGraphScript.cpp | AleixCas95/Shiny_Engine | a5dca52725ed20c11f929a581e1b442988ec3237 | [
"MIT"
] | null | null | null | #include "Application.h"
#include "ComponentGraphScript.h"
#include "ResourceGraphManager.h"
#include "Component.h"
#include "imgui/imgui.h"
ComponentGraphScript::ComponentGraphScript(Application* app_parent, GameObject* parent, uint scriptNum) : Component(app_parent, parent, CompGraphScript)
{
type = Object_Type::CompGraphScript;
gobjects.push_back(gameObject);
this->scriptNum = scriptNum;
}
ComponentGraphScript::~ComponentGraphScript()
{
}
void ComponentGraphScript::DrawInspector()
{
//TODO: Close individual graph scripts
if (ImGui::CollapsingHeader("Graph Script", ImGuiTreeNodeFlags_DefaultOpen)) {
if (has_script) {
ImGui::Button("Drag script here");
ImGui::Button("New Script", { 80,30 });
}
}
}
void ComponentGraphScript::Save(JSON_Array* comp_array) const {
JSON_Value* value = json_value_init_object();
JSON_Object* obj = json_value_get_object(value);
json_object_set_number(obj, "Component Type", type);
json_object_set_number(obj, "Script UUID", uuid_script);
json_object_set_string(obj, "Name", script_name);
json_object_set_boolean(obj, "Active", active);
//Save Blackboard
JSON_Value* value_arr = json_value_init_array();
JSON_Array* array = json_value_get_array(value_arr);
for (uint i = 1; i < gobjects.size(); i++) {
JSON_Value* aux_val = json_value_init_object();
JSON_Object* aux_obj = json_value_get_object(aux_val);
GameObject* it = gobjects[i];
json_object_set_number(aux_obj, "GO UUID", it->uuid);
json_array_append_value(array, aux_val);
}
json_object_set_value(obj, "Blackboard", value_arr);
json_array_append_value(comp_array, value);
//Save .script file with all the info of nodes and links
//SaveScriptFile(uuid_script);
}
void ComponentGraphScript::Load(JSON_Object* comp_obj) {
uuid_script = json_object_get_number(comp_obj, "Script UUID");
active = json_object_get_boolean(comp_obj, "Active");
std::strcpy(script_name, json_object_get_string(comp_obj, "Name"));
ResourceGraphManager* res = (ResourceGraphManager*)App->resources->Get(uuid_script);
if (res)
res->LoadToMemory();
//Load Blackboard
JSON_Array* array_bb = json_object_get_array(comp_obj, "Blackboard");
JSON_Object* it;
for (uint i = 0; i < json_array_get_count(array_bb); i++) {
it = json_array_get_object(array_bb, i);
scriptType uuid_aux = json_object_get_number(it, "GO UUID");
if (uuid_aux != 0)
uuidsLoad.push_back(uuid_aux);
}
}
void ComponentGraphScript::ForceAddReferenceToBlackboard(GameObject* ref)
{
gobjects.push_back(ref);
}
uint ComponentGraphScript::GetCompSriptNum() const
{
return script_num;
}
std::vector<GameObject*> ComponentGraphScript::GetBlackboard() const
{
return gobjects;
}
uint ComponentGraphScript::CreateNewTimer()
{
timers.push_back(0.0f);
return timers.size();
}
void ComponentGraphScript::IncrementTimer(uint idx, float dt)
{
timers[idx - 1] += dt;
}
float ComponentGraphScript::GetTimer(uint idx) const
{
return timers[idx - 1];
}
uint ComponentGraphScript::GetNumTimers() const
{
return timers.size();
}
void ComponentGraphScript::LoadBlackBoard() {
for (uint i = 0; i < uuidsLoad.size(); i++) {
GameObject* bb_go = App->scene->GetGameObjectFromUUID(uuidsLoad[i], App->scene->GetRootGameObject());
gobjects.push_back(bb_go);
}
uuidsLoad.clear();
}
| 21.933775 | 152 | 0.746377 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.