hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d94b5d651e1fc92e91e4fa3aa375144b3e673f8c | 1,674 | hpp | C++ | common/rendersystem.hpp | Mikko-Finell/bullet | 0aa08008c58d4c6fb2c4e12322a8925257cecc1c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-08-12T22:52:22.000Z | 2020-08-12T22:52:22.000Z | common/rendersystem.hpp | Mikko-Finell/bullet | 0aa08008c58d4c6fb2c4e12322a8925257cecc1c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2019-06-19T19:15:26.000Z | 2019-06-19T19:15:27.000Z | common/rendersystem.hpp | Mikko-Finell/bullet | 0aa08008c58d4c6fb2c4e12322a8925257cecc1c | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | #ifndef rendersystem_hpp
#define rendersystem_hpp
#include "sprite.hpp"
#include "stl.hpp"
#include "sfml.hpp"
/**
* RenderSystem
* Base class for rendering gameobjects.
*/
class RenderSystem {
protected:
std::unordered_set<SpriteImpl *> sprites;
sf::Texture & texture;
std::vector<sf::Vertex> vs;
public:
virtual ~RenderSystem() {}
RenderSystem(sf::Texture & tex);
virtual void add(SpriteImpl * sprite, const std::string & caller);
inline void add(SpriteImpl & sprite, const std::string & caller) {
add(&sprite, caller);
}
// removes the sprite from set of sprites, preventing it from being drawn
virtual void remove(SpriteImpl * sprite);
virtual void draw(sf::RenderWindow & window) = 0;
};
/**
* WorldRender
* RenderSystem that knows about the isometric tile
* layering used in Bullet.
*/
class WorldRender : public RenderSystem {
std::vector<SpriteImpl *> visible_sprites;
public:
using RenderSystem::RenderSystem;
void remove(SpriteImpl * sprite) override;
inline void remove(SpriteImpl & sprite) {
remove(&sprite);
}
void draw(sf::RenderWindow & window) override;
};
/**
* UIRender
* RenderSystem that uses simple layering appropriate
* for UI.
*/
class UIRender : public RenderSystem {
std::vector<SpriteImpl *> sorted_sprites;
bool sorted = false;
public:
using RenderSystem::RenderSystem;
void add(SpriteImpl * sprite, const std::string & caller) override;
void remove(SpriteImpl * sprite) override;
inline void remove(SpriteImpl & sprite) {
remove(&sprite);
}
void draw(sf::RenderWindow & window) override;
};
#endif
| 24.26087 | 77 | 0.685185 | Mikko-Finell |
d94bf94e227d13b0aa6146b827ce9f0971e17023 | 608 | cpp | C++ | Leetcode/1000-2000/1339. Maximum Product of Splitted Binary Tree/1339.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1339. Maximum Product of Splitted Binary Tree/1339.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1339. Maximum Product of Splitted Binary Tree/1339.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProduct(TreeNode* root) {
constexpr int kMod = 1e9 + 7;
long ans = 0;
vector<int> allSums;
const long totalSum = treeSum(root, allSums);
for (const long sum : allSums)
ans = max(ans, sum * (totalSum - sum));
return ans % kMod;
}
private:
int treeSum(TreeNode* root, vector<int>& allSums) {
if (!root)
return 0;
const int leftSum = treeSum(root->left, allSums);
const int rightSum = treeSum(root->right, allSums);
const int sum = root->val + leftSum + rightSum;
allSums.push_back(sum);
return sum;
}
};
| 22.518519 | 55 | 0.618421 | Next-Gen-UI |
d94c9ecc0a9d01b3e1c7f66f9a48abe0555e2c87 | 685 | cpp | C++ | ParallelEngine/animation.cpp | Archiving/ParallelEngine | 53f287d6e71bcf323cfdad763c6b6818795ada7c | [
"MIT"
] | 4 | 2019-07-29T14:35:17.000Z | 2019-08-06T04:35:18.000Z | ParallelEngine/animation.cpp | Archiving/ParallelEngine | 53f287d6e71bcf323cfdad763c6b6818795ada7c | [
"MIT"
] | 6 | 2019-07-28T22:34:54.000Z | 2019-08-29T07:18:04.000Z | ParallelEngine/animation.cpp | Archiving/ParallelEngine | 53f287d6e71bcf323cfdad763c6b6818795ada7c | [
"MIT"
] | null | null | null | #include "animation.h"
#include <iostream>
Animation::Animation(ALLEGRO_BITMAP * img, int frameWidth, int frameHeight, int frameDelay, int maxFrames, int x, int y) :
image(img), width(frameWidth), height(frameHeight), delay(frameDelay), numFrames(maxFrames) {
currentFrame = 0;
frameCount = 0;
this->x = x;
this->y = y;
}
Animation::~Animation() {}
void Animation::update() {
if (delay <= 0) return;
frameCount++;
if (frameCount >= delay) {
frameCount = 0;
currentFrame++;
if (currentFrame >= numFrames) currentFrame = 0;
}
}
void Animation::render(int x, int y) {
al_draw_bitmap_region(image, this->x + currentFrame * width, this->y, width, height, x, y, 0);
}
| 24.464286 | 123 | 0.681752 | Archiving |
d9539fbedcadbb7e5d6485aa4a514acb0adcf5f2 | 5,674 | cpp | C++ | sort/src/tracker.cpp | AsakusaRinne/tensorrt_yolov5_tracker | b9a3a6fc94710e8291d6a614ed2b04cbc4c56599 | [
"MIT"
] | 22 | 2021-03-03T10:16:37.000Z | 2022-01-05T14:47:38.000Z | sort/src/tracker.cpp | AsakusaRinne/tensorrt_yolov5_tracker | b9a3a6fc94710e8291d6a614ed2b04cbc4c56599 | [
"MIT"
] | 3 | 2021-05-27T01:52:16.000Z | 2021-07-13T08:49:30.000Z | sort/src/tracker.cpp | AsakusaRinne/tensorrt_yolov5_tracker | b9a3a6fc94710e8291d6a614ed2b04cbc4c56599 | [
"MIT"
] | 5 | 2021-03-23T07:13:05.000Z | 2022-02-18T09:10:17.000Z | #include "tracker.h"
Tracker::Tracker() {
id_ = 0;
}
float Tracker::CalculateIou(const cv::Rect& det, const Track& track) {
auto trk = track.GetStateAsBbox();
// get min/max points
auto xx1 = std::max(det.tl().x, trk.tl().x);
auto yy1 = std::max(det.tl().y, trk.tl().y);
auto xx2 = std::min(det.br().x, trk.br().x);
auto yy2 = std::min(det.br().y, trk.br().y);
auto w = std::max(0, xx2 - xx1);
auto h = std::max(0, yy2 - yy1);
// calculate area of intersection and union
float det_area = det.area();
float trk_area = trk.area();
auto intersection_area = w * h;
float union_area = det_area + trk_area - intersection_area;
auto iou = intersection_area / union_area;
return iou;
}
void Tracker::HungarianMatching(const std::vector<std::vector<float>>& iou_matrix,
size_t nrows, size_t ncols,
std::vector<std::vector<float>>& association) {
Matrix<float> matrix(nrows, ncols);
// Initialize matrix with IOU values
for (size_t i = 0 ; i < nrows ; i++) {
for (size_t j = 0 ; j < ncols ; j++) {
// Multiply by -1 to find max cost
if (iou_matrix[i][j] != 0) {
matrix(i, j) = -iou_matrix[i][j];
}
else {
// TODO: figure out why we have to assign value to get correct result
matrix(i, j) = 1.0f;
}
}
}
// // Display begin matrix state.
// for (size_t row = 0 ; row < nrows ; row++) {
// for (size_t col = 0 ; col < ncols ; col++) {
// std::cout.width(10);
// std::cout << matrix(row,col) << ",";
// }
// std::cout << std::endl;
// }
// std::cout << std::endl;
// Apply Kuhn-Munkres algorithm to matrix.
Munkres<float> m;
m.solve(matrix);
// // Display solved matrix.
// for (size_t row = 0 ; row < nrows ; row++) {
// for (size_t col = 0 ; col < ncols ; col++) {
// std::cout.width(2);
// std::cout << matrix(row,col) << ",";
// }
// std::cout << std::endl;
// }
// std::cout << std::endl;
for (size_t i = 0 ; i < nrows ; i++) {
for (size_t j = 0 ; j < ncols ; j++) {
association[i][j] = matrix(i, j);
}
}
}
void Tracker::AssociateDetectionsToTrackers(const std::vector<cv::Rect>& detection,
std::map<int, Track>& tracks,
std::map<int, cv::Rect>& matched,
std::vector<cv::Rect>& unmatched_det,
float iou_threshold) {
// Set all detection as unmatched if no tracks existing
if (tracks.empty()) {
for (const auto& det : detection) {
unmatched_det.push_back(det);
}
return;
}
std::vector<std::vector<float>> iou_matrix;
// resize IOU matrix based on number of detection and tracks
iou_matrix.resize(detection.size(), std::vector<float>(tracks.size()));
std::vector<std::vector<float>> association;
// resize association matrix based on number of detection and tracks
association.resize(detection.size(), std::vector<float>(tracks.size()));
// row - detection, column - tracks
for (size_t i = 0; i < detection.size(); i++) {
size_t j = 0;
for (const auto& trk : tracks) {
iou_matrix[i][j] = CalculateIou(detection[i], trk.second);
j++;
}
}
// Find association
HungarianMatching(iou_matrix, detection.size(), tracks.size(), association);
for (size_t i = 0; i < detection.size(); i++) {
bool matched_flag = false;
size_t j = 0;
for (const auto& trk : tracks) {
if (0 == association[i][j]) {
// Filter out matched with low IOU
if (iou_matrix[i][j] >= iou_threshold) {
matched[trk.first] = detection[i];
matched_flag = true;
}
// It builds 1 to 1 association, so we can break from here
break;
}
j++;
}
// if detection cannot match with any tracks
if (!matched_flag) {
unmatched_det.push_back(detection[i]);
}
}
}
void Tracker::Run(const std::vector<cv::Rect>& detections) {
/*** Predict internal tracks from previous frame ***/
for (auto &track : tracks_) {
track.second.Predict();
}
// Hash-map between track ID and associated detection bounding box
std::map<int, cv::Rect> matched;
// vector of unassociated detections
std::vector<cv::Rect> unmatched_det;
// return values - matched, unmatched_det
if (!detections.empty()) {
AssociateDetectionsToTrackers(detections, tracks_, matched, unmatched_det);
}
/*** Update tracks with associated bbox ***/
for (const auto &match : matched) {
const auto &ID = match.first;
tracks_[ID].Update(match.second);
}
/*** Create new tracks for unmatched detections ***/
for (const auto &det : unmatched_det) {
Track tracker;
tracker.Init(det);
// Create new track and generate new ID
tracks_[id_++] = tracker;
}
/*** Delete lose tracked tracks ***/
for (auto it = tracks_.begin(); it != tracks_.end();) {
if (it->second.coast_cycles_ > kMaxCoastCycles) {
it = tracks_.erase(it);
} else {
it++;
}
}
}
std::map<int, Track> Tracker::GetTracks() {
return tracks_;
} | 31.348066 | 85 | 0.527846 | AsakusaRinne |
d9561e5b654f0f2d887ec447b96bb9c62e313b7e | 5,729 | cpp | C++ | pybindings/pyhdbscan.cpp | wangyiqiu/hdbscan | 0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e | [
"MIT"
] | 7 | 2021-03-29T05:54:11.000Z | 2021-12-28T04:13:10.000Z | pybindings/pyhdbscan.cpp | wangyiqiu/hdbscan | 0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e | [
"MIT"
] | 1 | 2021-09-16T05:38:33.000Z | 2021-09-16T22:18:26.000Z | pybindings/pyhdbscan.cpp | wangyiqiu/hdbscan | 0f21522a4d34db040dd0cd6c6506ad39ed6f2a9e | [
"MIT"
] | 3 | 2021-07-13T23:42:47.000Z | 2021-12-05T12:55:20.000Z | #include "hdbscan/hdbscan.h"
#include "hdbscan/point.h"
#include "hdbscan/edge.h"
#include <string>
#include <limits>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
using namespace parlay;
template<class T, class Seq>
py::array_t<T> wrapArray2d(Seq& result_vec, ssize_t cols) {
ssize_t rows = (ssize_t) result_vec.size() *
(ssize_t) sizeof(typename Seq::value_type) /
(ssize_t) sizeof(T);
rows /= cols;
std::vector<ssize_t> shape = { rows, cols };
std::vector<ssize_t> strides = { (ssize_t) sizeof(T) * cols, (ssize_t) sizeof(T) };
return py::array(py::buffer_info(result_vec.data(), /* data as contiguous array */
sizeof(T), /* size of one scalar */
py::format_descriptor<T>::format(), /* data type */
2, /* number of dimensions */
shape, /* shape of the matrix */
strides /* strides for each axis */
));
}
py::array_t<double> py_hdbscan(py::array_t<double, py::array::c_style | py::array::forcecast> array, size_t minPts) {
if (array.ndim() != 2)
throw std::runtime_error("Input should be 2-D NumPy array");
if (sizeof(pargeo::point<2>) != 16)
throw std::runtime_error("sizeof(pargeo::point<2>) != 16, check point.h");
int dim = array.shape()[1];
size_t n = array.size() / dim;
parlay::sequence<pargeo::dirEdge> result_vec;
sequence<pargeo::wghEdge> E;
if (dim == 2) {
parlay::sequence<pargeo::point<2>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<2>(P, minPts);
} else if (dim == 3) {
parlay::sequence<pargeo::point<3>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<3>(P, minPts);
} else if (dim == 4) {
parlay::sequence<pargeo::point<4>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<4>(P, minPts);
} else if (dim == 5) {
parlay::sequence<pargeo::point<5>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<5>(P, minPts);
} else if (dim == 6) {
parlay::sequence<pargeo::point<6>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<6>(P, minPts);
} else if (dim == 7) {
parlay::sequence<pargeo::point<7>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<7>(P, minPts);
} else if (dim == 8) {
parlay::sequence<pargeo::point<8>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<8>(P, minPts);
} else if (dim == 9) {
parlay::sequence<pargeo::point<9>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<9>(P, minPts);
} else if (dim == 10) {
parlay::sequence<pargeo::point<10>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<10>(P, minPts);
} else if (dim == 11) {
parlay::sequence<pargeo::point<11>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<11>(P, minPts);
} else if (dim == 12) {
parlay::sequence<pargeo::point<12>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<12>(P, minPts);
} else if (dim == 13) {
parlay::sequence<pargeo::point<13>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<13>(P, minPts);
} else if (dim == 14) {
parlay::sequence<pargeo::point<14>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<14>(P, minPts);
} else if (dim == 15) {
parlay::sequence<pargeo::point<15>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<15>(P, minPts);
} else if (dim == 16) {
parlay::sequence<pargeo::point<16>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<16>(P, minPts);
} else if (dim == 17) {
parlay::sequence<pargeo::point<17>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<17>(P, minPts);
} else if (dim == 18) {
parlay::sequence<pargeo::point<18>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<18>(P, minPts);
} else if (dim == 19) {
parlay::sequence<pargeo::point<19>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<19>(P, minPts);
} else if (dim == 20) {
parlay::sequence<pargeo::point<20>> P(n);
std::memcpy(P.data(), array.data(), array.size() * sizeof(double));
E = pargeo::hdbscan<20>(P, minPts);
} else {
throw std::runtime_error("Only dimensions 2-20 is supported at the moment");
}
sequence<pargeo::dendroNode> dendro = pargeo::dendrogram(E, n);
sequence<double> A(dendro.size()*4);
parlay::parallel_for(0, dendro.size(), [&](size_t i){
A[i*4+0] = std::get<0>(dendro[i]);
A[i*4+1] = std::get<1>(dendro[i]);
A[i*4+2] = std::get<2>(dendro[i]);
A[i*4+3] = std::get<3>(dendro[i]);});
return wrapArray2d<double>(A, 4);
}
PYBIND11_MODULE(pyhdbscan, m)
{
m.doc() = "Fast Parallel Algorithms for HDBSCAN*";
m.def("HDBSCAN",
&py_hdbscan,
"Hierarchical DBSCAN*",
py::arg("array"), py::arg("minPts"));
}
| 40.062937 | 117 | 0.579857 | wangyiqiu |
d9569c3daae5ab2508857810be13e24070662b22 | 6,383 | hpp | C++ | libraries/fc/include/fc/container/flat.hpp | theenemys/oasischain_inter | db968d4d0bd1a487f4edb4cb673fda481d24a06c | [
"MIT"
] | 37 | 2018-06-14T07:17:36.000Z | 2022-02-18T18:03:42.000Z | libraries/fc/include/fc/container/flat.hpp | theenemys/oasischain_inter | db968d4d0bd1a487f4edb4cb673fda481d24a06c | [
"MIT"
] | 36 | 2018-07-14T16:18:20.000Z | 2021-12-24T01:45:26.000Z | libraries/fc/include/fc/container/flat.hpp | theenemys/oasischain_inter | db968d4d0bd1a487f4edb4cb673fda481d24a06c | [
"MIT"
] | 131 | 2017-05-31T02:15:02.000Z | 2022-03-23T12:19:35.000Z | #pragma once
#include <fc/container/flat_fwd.hpp>
#include <fc/container/container_detail.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <fc/crypto/hex.hpp>
namespace fc {
namespace raw {
template<typename Stream, typename T, typename A>
void pack( Stream& s, const boost::container::vector<T, A>& value ) {
FC_ASSERT( value.size() <= MAX_NUM_ARRAY_ELEMENTS );
pack( s, unsigned_int((uint32_t)value.size()) );
if( !std::is_fundamental<T>::value ) {
for( const auto& item : value ) {
pack( s, item );
}
} else if( value.size() ) {
s.write( (const char*)value.data(), value.size() );
}
}
template<typename Stream, typename T, typename A>
void unpack( Stream& s, boost::container::vector<T, A>& value ) {
unsigned_int size;
unpack( s, size );
FC_ASSERT( size.value <= MAX_NUM_ARRAY_ELEMENTS );
value.clear();
value.resize( size.value );
if( !std::is_fundamental<T>::value ) {
for( auto& item : value ) {
unpack( s, item );
}
} else if( value.size() ) {
s.read( (char*)value.data(), value.size() );
}
}
template<typename Stream, typename A>
void pack( Stream& s, const boost::container::vector<char, A>& value ) {
FC_ASSERT( value.size() <= MAX_SIZE_OF_BYTE_ARRAYS );
pack( s, unsigned_int((uint32_t)value.size()) );
if( value.size() )
s.write( (const char*)value.data(), value.size() );
}
template<typename Stream, typename A>
void unpack( Stream& s, boost::container::vector<char, A>& value ) {
unsigned_int size;
unpack( s, size );
FC_ASSERT( size.value <= MAX_SIZE_OF_BYTE_ARRAYS );
value.clear();
value.resize( size.value );
if( value.size() )
s.read( (char*)value.data(), value.size() );
}
template<typename Stream, typename T, typename... U>
void pack( Stream& s, const flat_set<T, U...>& value ) {
detail::pack_set( s, value );
}
template<typename Stream, typename T, typename... U>
void unpack( Stream& s, flat_set<T, U...>& value ) {
detail::unpack_flat_set( s, value );
}
template<typename Stream, typename T, typename... U>
void pack( Stream& s, const flat_multiset<T, U...>& value ) {
detail::pack_set( s, value );
}
template<typename Stream, typename T, typename... U>
void unpack( Stream& s, flat_multiset<T, U...>& value ) {
detail::unpack_flat_set( s, value );
}
template<typename Stream, typename K, typename V, typename... U>
void pack( Stream& s, const flat_map<K, V, U...>& value ) {
detail::pack_map( s, value );
}
template<typename Stream, typename K, typename V, typename... U>
void unpack( Stream& s, flat_map<K, V, U...>& value ) {
detail::unpack_flat_map( s, value );
}
template<typename Stream, typename K, typename V, typename... U>
void pack( Stream& s, const flat_multimap<K, V, U...>& value ) {
detail::pack_map( s, value );
}
template<typename Stream, typename K, typename V, typename... U>
void unpack( Stream& s, flat_multimap<K, V, U...>& value ) {
detail::unpack_flat_map( s, value );
}
} // namespace raw
template<typename T, typename... U>
void to_variant( const boost::container::vector<T, U...>& vec, fc::variant& vo ) {
FC_ASSERT( vec.size() <= MAX_NUM_ARRAY_ELEMENTS );
variants vars;
vars.reserve( vec.size() );
for( const auto& item : vec ) {
vars.emplace_back( item );
}
vo = std::move(vars);
}
template<typename T, typename... U>
void from_variant( const fc::variant& v, boost::container::vector<T, U...>& vec ) {
const variants& vars = v.get_array();
FC_ASSERT( vars.size() <= MAX_NUM_ARRAY_ELEMENTS );
vec.clear();
vec.resize( vars.size() );
for( uint32_t i = 0; i < vars.size(); ++i ) {
from_variant( vars[i], vec[i] );
}
}
template<typename... U>
void to_variant( const boost::container::vector<char, U...>& vec, fc::variant& vo ) {
FC_ASSERT( vec.size() <= MAX_SIZE_OF_BYTE_ARRAYS );
if( vec.size() )
vo = variant( fc::to_hex( vec.data(), vec.size() ) );
else
vo = "";
}
template<typename... U>
void from_variant( const fc::variant& v, boost::container::vector<char, U...>& vec )
{
const auto& str = v.get_string();
FC_ASSERT( str.size() <= 2*MAX_SIZE_OF_BYTE_ARRAYS ); // Doubled because hex strings needs two characters per byte
vec.resize( str.size() / 2 );
if( vec.size() ) {
size_t r = fc::from_hex( str, vec.data(), vec.size() );
FC_ASSERT( r == vec.size() );
}
}
template<typename T, typename... U>
void to_variant( const flat_set< T, U... >& s, fc::variant& vo ) {
detail::to_variant_from_set( s, vo );
}
template<typename T, typename... U>
void from_variant( const fc::variant& v, flat_set< T, U... >& s ) {
detail::from_variant_to_flat_set( v, s );
}
template<typename T, typename... U>
void to_variant( const flat_multiset< T, U... >& s, fc::variant& vo ) {
detail::to_variant_from_set( s, vo );
}
template<typename T, typename... U>
void from_variant( const fc::variant& v, flat_multiset< T, U... >& s ) {
detail::from_variant_to_flat_set( v, s );
}
template<typename K, typename V, typename... U >
void to_variant( const flat_map< K, V, U... >& m, fc::variant& vo ) {
detail::to_variant_from_map( m, vo );
}
template<typename K, typename V, typename... U>
void from_variant( const variant& v, flat_map<K, V, U...>& m ) {
detail::from_variant_to_flat_map( v, m );
}
template<typename K, typename V, typename... U >
void to_variant( const flat_multimap< K, V, U... >& m, fc::variant& vo ) {
detail::to_variant_from_map( m, vo );
}
template<typename K, typename V, typename... U>
void from_variant( const variant& v, flat_multimap<K, V, U...>& m ) {
detail::from_variant_to_flat_map( v, m );
}
}
| 34.13369 | 120 | 0.574025 | theenemys |
d958994bf32897ef9dafbc8fb82063e6ce96d0ac | 660 | cpp | C++ | Apr'20/72(Edit Distance).cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 13 | 2019-10-12T14:36:32.000Z | 2021-06-08T04:26:30.000Z | Apr'20/72(Edit Distance).cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 1 | 2020-02-29T14:02:39.000Z | 2020-02-29T14:02:39.000Z | Apr'20/72(Edit Distance).cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 3 | 2020-02-08T12:04:28.000Z | 2020-03-17T11:53:00.000Z | class Solution {
public:
int dp[1000][1000];
int ED(string& A, string& B, int m, int n){
if(m == 0)
return n;
if(n == 0)
return m;
if(dp[m][n] != -1)
return dp[m][n];
if(A[m - 1] == B[n - 1])
return dp[m][n] = ED(A, B, m - 1, n - 1);
return dp[m][n] = 1 + min({ED(A,B,m-1,n),ED(A,B,m,n - 1),ED(A,B,m-1,n - 1)});
}
int minDistance(string word1, string word2) {
int m = word1.length();
int n = word2.length();
memset(dp, -1, sizeof(dp));
return ED(word1, word2, m, n);
}
};
| 23.571429 | 86 | 0.398485 | JanaSabuj |
d959362abe77359494b1db24a55bbb67b54a7def | 1,579 | cpp | C++ | crypto/Pbkdf2.cpp | Acidburn0zzz/NfWebCrypto | 0186e3ebde1779419053384983612d7d494e6bcc | [
"Apache-2.0"
] | null | null | null | crypto/Pbkdf2.cpp | Acidburn0zzz/NfWebCrypto | 0186e3ebde1779419053384983612d7d494e6bcc | [
"Apache-2.0"
] | null | null | null | crypto/Pbkdf2.cpp | Acidburn0zzz/NfWebCrypto | 0186e3ebde1779419053384983612d7d494e6bcc | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "Pbkdf2.h"
#include <assert.h>
#include <openssl/evp.h>
#include "DigestAlgo.h"
using namespace std;
using namespace tr1;
namespace cadmium {
namespace crypto {
Pbkdf2::Pbkdf2(shared_ptr<const DigestAlgo> digestAlgo) : digestAlgo_(digestAlgo)
{
}
bool Pbkdf2::generate(const Vuc& salt, uint32_t iterations, const string& password,
uint32_t keyLenBits, Vuc& out)
{
assert(salt.size());
assert(password.size());
assert(iterations);
assert(keyLenBits);
// size the output
const uint32_t keyLenBytes = keyLenBits / 8;
out.resize(keyLenBytes);
// do the operation
const int ret = PKCS5_PBKDF2_HMAC(password.c_str(), password.size(),
&salt[0], salt.size(), iterations, digestAlgo_->evp_md(), keyLenBytes,
&out[0]);
if (!ret)
return false;
// shrink to fit
Vuc(out.begin(), out.end()).swap(out);
return true;
}
}} // namespace cadmium:;crypto
| 26.316667 | 83 | 0.673844 | Acidburn0zzz |
d95d2faee17dced9b66de9809813caec1c08cbc9 | 2,348 | hh | C++ | include/matrix.hh | KPO-2020-2021/zad3-Szymon-Sobczak | 57a6409da5bd2971b71f93f4118d2e8c52b0f83d | [
"Unlicense"
] | null | null | null | include/matrix.hh | KPO-2020-2021/zad3-Szymon-Sobczak | 57a6409da5bd2971b71f93f4118d2e8c52b0f83d | [
"Unlicense"
] | null | null | null | include/matrix.hh | KPO-2020-2021/zad3-Szymon-Sobczak | 57a6409da5bd2971b71f93f4118d2e8c52b0f83d | [
"Unlicense"
] | null | null | null | #pragma once
#include "size.hh"
#include "vector.hh"
#include <iostream>
#include <cstdlib>
#include <cmath>
/*************************************************************************************
| Klasa modelujaca w programie pojecie macierzy. |
| Klasa posiada prywatne pole "value", stanowi ono zbior wartosci macierzy rotacji. |
| Jest to tablica dwuwymiarowa dla warosci typu double. |
| Klasa posiada publiczny interfejs pozwalajacy na wprowazdanie, |
| zmiane i odczytywanie danych z macierzy rotacji. |
| Klasa zawiera publiczne przeciazenia operatorow funkcyjnych opowiedzialnych |
| za wprowadzanie i odczytywanie wartosci z macierzy rotacji, oraz przeciazenie |
| operatora mnozenia macierzy razy wetkor i przeciazenia operatora dodawania |
| dwoch macierzy. |
| Klasa posiada metode inicjujaca macierz wartosciami funkcji trygonometrycznych |
| dla zadanego konta obrotu. |
| W roli modyfikacji zadania, dodano metode wyznaczajaca wyznacznik macierzy. |
*/
class Matrix{
private:
double value[SIZE][SIZE]; /* Wartosci macierzy */
public:
Matrix(); /* Bezparametryczny konstruktor klasy */
Matrix(double [SIZE][SIZE]); /* Konstruktor klasy z parametrem */
Vector operator * (Vector const &tmp); /* Operator mnożenia przez wektor */
Matrix operator + (Matrix const &tmp); /* Operator dodwania dwoch macierzy */
Matrix Fill_matrix (double const angle); /* Wypenienie macierzy wartosciami funkcji tryg. dla zadanego kąta obrotu */
double determinant_of_the_matrix() const; /* Obliczenie wyznacznika macierzy */
double & operator () (unsigned int row, unsigned int column); /* Przeciazenia operatora funkcyjnego */
const double & operator () (unsigned int row, unsigned int column) const;
};
std::ostream & operator << (std::ostream &out, Matrix const &mat); /* Przeciazenie operatora << sluzace wyswietlaniu macierzy */
std::istream & operator >> (std::istream &in, Matrix &mat); /* Przeciazenie operatora >> sluzace wczytywaniu wartosci do macierzy */
| 55.904762 | 140 | 0.611584 | KPO-2020-2021 |
d960c6dd1f2255bbe3434f92e1c3c1893370a74c | 153 | hpp | C++ | src/source/util/bytestream.hpp | mvpwizard/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | 1 | 2019-03-24T12:07:46.000Z | 2019-03-24T12:07:46.000Z | src/source/util/bytestream.hpp | nepitdev/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | 10 | 2019-03-06T20:27:39.000Z | 2019-11-27T08:28:12.000Z | src/source/util/bytestream.hpp | openepit/DLA | 5ead2574e61e619ca3a93f1e771e3988fc144928 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <cinttypes>
namespace dla
{
class bytestream
{
public:
virtual uint8_t next() = 0;
};
} | 11.769231 | 35 | 0.594771 | mvpwizard |
d960e1141f07857795002d6608cc9b2bfdcf3aa4 | 18,824 | cpp | C++ | Sample001/src/main.cpp | Monsho/D3D12Samples | 4624fd64b57c12fee1085ecfba1f770f802a236c | [
"MIT"
] | 32 | 2017-10-11T00:23:17.000Z | 2022-01-02T14:08:56.000Z | Sample001/src/main.cpp | Monsho/D3D12Samples | 4624fd64b57c12fee1085ecfba1f770f802a236c | [
"MIT"
] | null | null | null | Sample001/src/main.cpp | Monsho/D3D12Samples | 4624fd64b57c12fee1085ecfba1f770f802a236c | [
"MIT"
] | 6 | 2019-01-18T13:16:01.000Z | 2021-09-07T09:43:20.000Z | #include <sl12/device.h>
#include <sl12/swapchain.h>
#include <sl12/command_queue.h>
#include <sl12/command_list.h>
#include <sl12/descriptor_heap.h>
#include <sl12/descriptor.h>
#include <sl12/texture.h>
#include <sl12/texture_view.h>
#include <sl12/sampler.h>
#include <sl12/fence.h>
#include <sl12/buffer.h>
#include <sl12/buffer_view.h>
#include <sl12/root_signature.h>
#include <sl12/pipeline_state.h>
#include <sl12/descriptor_set.h>
#include <sl12/shader.h>
#include <DirectXTex.h>
#include "file.h"
namespace
{
static const wchar_t* kWindowTitle = L"D3D12Sample";
static const int kWindowWidth = 1920;
static const int kWindowHeight = 1080;
//static const DXGI_FORMAT kDepthBufferFormat = DXGI_FORMAT_R32G8X24_TYPELESS;
//static const DXGI_FORMAT kDepthViewFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
static const DXGI_FORMAT kDepthBufferFormat = DXGI_FORMAT_R32_TYPELESS;
static const DXGI_FORMAT kDepthViewFormat = DXGI_FORMAT_D32_FLOAT;
HWND g_hWnd_;
sl12::Device g_Device_;
sl12::CommandList g_mainCmdList_;
sl12::CommandList g_mainCmdLists_[sl12::Swapchain::kMaxBuffer];
sl12::CommandList* g_pNextCmdList_ = nullptr;
sl12::CommandList g_copyCmdList_;
sl12::Texture g_RenderTarget_;
sl12::RenderTargetView g_RenderTargetView_;
sl12::TextureView g_RenderTargetTexView_;
sl12::Texture g_DepthBuffer_;
sl12::DepthStencilView g_DepthBufferView_;
sl12::TextureView g_DepthBufferTexView_;
static const uint32_t kMaxCBs = sl12::Swapchain::kMaxBuffer * 2;
sl12::Buffer g_CBScenes_[kMaxCBs];
void* g_pCBSceneBuffers_[kMaxCBs] = { nullptr };
sl12::ConstantBufferView g_CBSceneViews_[kMaxCBs];
sl12::Buffer g_vbuffers_[3];
sl12::VertexBufferView g_vbufferViews_[3];
sl12::Buffer g_ibuffer_;
sl12::IndexBufferView g_ibufferView_;
sl12::Texture g_texture_;
sl12::TextureView g_textureView_;
sl12::Sampler g_sampler_;
sl12::Shader g_VShader_, g_PShader_;
sl12::Shader g_VSScreenShader_, g_PSDispDepthShader_;
sl12::RootSignature g_rootSig_;
sl12::GraphicsPipelineState g_psoWriteS_;
sl12::GraphicsPipelineState g_psoUseS_;
sl12::DescriptorSet g_descSet_;
}
// Window Proc
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
// Handle destroy/shutdown messages.
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
// Handle any messages the switch statement didn't.
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Windowの初期化
void InitWindow(HINSTANCE hInstance, int nCmdShow)
{
// Initialize the window class.
WNDCLASSEX windowClass = { 0 };
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.lpszClassName = L"WindowClass1";
RegisterClassEx(&windowClass);
RECT windowRect = { 0, 0, kWindowWidth, kWindowHeight };
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);
// Create the window and store a handle to it.
g_hWnd_ = CreateWindowEx(NULL,
L"WindowClass1",
kWindowTitle,
WS_OVERLAPPEDWINDOW,
300,
300,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
NULL, // We have no parent window, NULL.
NULL, // We aren't using menus, NULL.
hInstance,
NULL); // We aren't using multiple windows, NULL.
ShowWindow(g_hWnd_, nCmdShow);
}
bool InitializeAssets()
{
ID3D12Device* pDev = g_Device_.GetDeviceDep();
g_copyCmdList_.Reset();
// レンダーターゲットを作成
{
sl12::TextureDesc texDesc;
texDesc.dimension = sl12::TextureDimension::Texture2D;
texDesc.width = kWindowWidth;
texDesc.height = kWindowHeight;
texDesc.format = DXGI_FORMAT_R16G16B16A16_FLOAT;
texDesc.clearColor[0] = 0.0f;
texDesc.clearColor[1] = 0.6f;
texDesc.clearColor[2] = 0.0f;
texDesc.clearColor[3] = 1.0f;
texDesc.isRenderTarget = true;
if (!g_RenderTarget_.Initialize(&g_Device_, texDesc))
{
return false;
}
if (!g_RenderTargetView_.Initialize(&g_Device_, &g_RenderTarget_))
{
return false;
}
if (!g_RenderTargetTexView_.Initialize(&g_Device_, &g_RenderTarget_))
{
return false;
}
}
// 深度バッファを作成
{
sl12::TextureDesc texDesc;
texDesc.dimension = sl12::TextureDimension::Texture2D;
texDesc.width = kWindowWidth;
texDesc.height = kWindowHeight;
texDesc.format = kDepthViewFormat;
texDesc.isDepthBuffer = true;
if (!g_DepthBuffer_.Initialize(&g_Device_, texDesc))
{
return false;
}
if (!g_DepthBufferView_.Initialize(&g_Device_, &g_DepthBuffer_))
{
return false;
}
if (!g_DepthBufferTexView_.Initialize(&g_Device_, &g_DepthBuffer_))
{
return false;
}
}
// 定数バッファを作成
{
D3D12_HEAP_PROPERTIES prop{};
prop.Type = D3D12_HEAP_TYPE_UPLOAD;
prop.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
prop.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
prop.CreationNodeMask = 1;
prop.VisibleNodeMask = 1;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Alignment = 0;
desc.Width = 256;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT_UNKNOWN;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = D3D12_RESOURCE_FLAG_NONE;
for (int i = 0; i < _countof(g_CBScenes_); i++)
{
if (!g_CBScenes_[i].Initialize(&g_Device_, sizeof(DirectX::XMFLOAT4X4) * 3, 1, sl12::BufferUsage::ConstantBuffer, true, false))
{
return false;
}
if (!g_CBSceneViews_[i].Initialize(&g_Device_, &g_CBScenes_[i]))
{
return false;
}
g_pCBSceneBuffers_[i] = g_CBScenes_[i].Map(&g_mainCmdList_);
}
}
// 頂点バッファを作成
{
{
float positions[] = {
-1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
};
if (!g_vbuffers_[0].Initialize(&g_Device_, sizeof(positions), sizeof(float) * 3, sl12::BufferUsage::VertexBuffer, false, false))
{
return false;
}
if (!g_vbufferViews_[0].Initialize(&g_Device_, &g_vbuffers_[0]))
{
return false;
}
g_vbuffers_[0].UpdateBuffer(&g_Device_, &g_copyCmdList_, positions, sizeof(positions));
}
{
uint32_t colors[] = {
0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff
};
if (!g_vbuffers_[1].Initialize(&g_Device_, sizeof(colors), sizeof(sl12::u32), sl12::BufferUsage::VertexBuffer, false, false))
{
return false;
}
if (!g_vbufferViews_[1].Initialize(&g_Device_, &g_vbuffers_[1]))
{
return false;
}
g_vbuffers_[1].UpdateBuffer(&g_Device_, &g_copyCmdList_, colors, sizeof(colors));
}
{
float uvs[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
if (!g_vbuffers_[2].Initialize(&g_Device_, sizeof(uvs), sizeof(float) * 2, sl12::BufferUsage::VertexBuffer, false, false))
{
return false;
}
if (!g_vbufferViews_[2].Initialize(&g_Device_, &g_vbuffers_[2]))
{
return false;
}
g_vbuffers_[2].UpdateBuffer(&g_Device_, &g_copyCmdList_, uvs, sizeof(uvs));
}
}
// インデックスバッファを作成
{
uint32_t indices[] = {
0, 1, 2, 1, 3, 2
};
if (!g_ibuffer_.Initialize(&g_Device_, sizeof(indices), sizeof(sl12::u32), sl12::BufferUsage::IndexBuffer, false, false))
{
return false;
}
if (!g_ibufferView_.Initialize(&g_Device_, &g_ibuffer_))
{
return false;
}
g_ibuffer_.UpdateBuffer(&g_Device_, &g_copyCmdList_, indices, sizeof(indices));
}
// テクスチャロード
{
File texFile("data/icon.tga");
if (!g_texture_.InitializeFromTGA(&g_Device_, &g_copyCmdList_, texFile.GetData(), texFile.GetSize(), 1, false))
{
return false;
}
if (!g_textureView_.Initialize(&g_Device_, &g_texture_))
{
return false;
}
}
// サンプラ作成
{
D3D12_SAMPLER_DESC desc{};
desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
if (!g_sampler_.Initialize(&g_Device_, desc))
{
return false;
}
}
g_copyCmdList_.Close();
g_copyCmdList_.Execute();
sl12::Fence fence;
fence.Initialize(&g_Device_);
fence.Signal(g_copyCmdList_.GetParentQueue());
fence.WaitSignal();
fence.Destroy();
// シェーダロード
if (!g_VShader_.Initialize(&g_Device_, sl12::ShaderType::Vertex, "data/VSSample.cso"))
{
return false;
}
if (!g_PShader_.Initialize(&g_Device_, sl12::ShaderType::Pixel, "data/PSSample.cso"))
{
return false;
}
if (!g_VSScreenShader_.Initialize(&g_Device_, sl12::ShaderType::Vertex, "data/VSScreen.cso"))
{
return false;
}
if (!g_PSDispDepthShader_.Initialize(&g_Device_, sl12::ShaderType::Pixel, "data/PSDispDepth.cso"))
{
return false;
}
// ルートシグネチャを作成
{
if (!g_rootSig_.Initialize(&g_Device_, &g_VShader_, &g_PShader_, nullptr, nullptr, nullptr))
{
return false;
}
}
// PSOを作成
{
D3D12_INPUT_ELEMENT_DESC elementDescs[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 2, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
};
sl12::GraphicsPipelineStateDesc desc{};
desc.rasterizer.fillMode = D3D12_FILL_MODE_SOLID;
desc.rasterizer.cullMode = D3D12_CULL_MODE_NONE;
desc.rasterizer.isFrontCCW = false;
desc.rasterizer.isDepthClipEnable = true;
desc.multisampleCount = 1;
desc.blend.sampleMask = UINT_MAX;
desc.blend.rtDesc[0].isBlendEnable = false;
desc.blend.rtDesc[0].srcBlendColor = D3D12_BLEND_ONE;
desc.blend.rtDesc[0].dstBlendColor = D3D12_BLEND_ZERO;
desc.blend.rtDesc[0].blendOpColor = D3D12_BLEND_OP_ADD;
desc.blend.rtDesc[0].srcBlendAlpha = D3D12_BLEND_ONE;
desc.blend.rtDesc[0].dstBlendAlpha = D3D12_BLEND_ZERO;
desc.blend.rtDesc[0].blendOpAlpha = D3D12_BLEND_OP_ADD;
desc.blend.rtDesc[0].writeMask = D3D12_COLOR_WRITE_ENABLE_ALL;
desc.depthStencil.isDepthEnable = true;
desc.depthStencil.isDepthWriteEnable = true;
desc.depthStencil.depthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
desc.pRootSignature = &g_rootSig_;
desc.pVS = &g_VShader_;
desc.pPS = &g_PShader_;
desc.primTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
desc.inputLayout.numElements = _countof(elementDescs);
desc.inputLayout.pElements = elementDescs;
desc.numRTVs = 0;
desc.rtvFormats[desc.numRTVs++] = g_RenderTarget_.GetTextureDesc().format;
desc.dsvFormat = g_DepthBuffer_.GetTextureDesc().format;
if (!g_psoWriteS_.Initialize(&g_Device_, desc))
{
return false;
}
desc.inputLayout.numElements = 0;
desc.inputLayout.pElements = nullptr;
desc.pVS = &g_VSScreenShader_;
desc.pPS = &g_PSDispDepthShader_;
desc.depthStencil.isDepthEnable = false;
desc.numRTVs = 0;
desc.rtvFormats[desc.numRTVs++] = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.dsvFormat = DXGI_FORMAT_UNKNOWN;
if (!g_psoUseS_.Initialize(&g_Device_, desc))
{
return false;
}
}
return true;
}
void DestroyAssets()
{
g_psoWriteS_.Destroy();
g_psoUseS_.Destroy();
g_rootSig_.Destroy();
g_VSScreenShader_.Destroy();
g_PSDispDepthShader_.Destroy();
g_VShader_.Destroy();
g_PShader_.Destroy();
g_sampler_.Destroy();
g_textureView_.Destroy();
g_texture_.Destroy();
for (auto& v : g_vbufferViews_)
{
v.Destroy();
}
for (auto& v : g_vbuffers_)
{
v.Destroy();
}
g_ibufferView_.Destroy();
g_ibuffer_.Destroy();
for (auto& v : g_CBSceneViews_)
{
v.Destroy();
}
for (auto& v : g_CBScenes_)
{
v.Unmap();
v.Destroy();
}
g_DepthBufferTexView_.Destroy();
g_DepthBufferView_.Destroy();
g_DepthBuffer_.Destroy();
g_RenderTargetTexView_.Destroy();
g_RenderTargetView_.Destroy();
g_RenderTarget_.Destroy();
}
void RenderScene()
{
if (g_pNextCmdList_)
g_pNextCmdList_->Execute();
g_Device_.SyncKillObjects();
int32_t frameIndex = (g_Device_.GetSwapchain().GetFrameIndex() + 1) % sl12::Swapchain::kMaxBuffer;
g_pNextCmdList_ = &g_mainCmdLists_[frameIndex];
g_pNextCmdList_->Reset();
static bool s_InitFrame = true;
if (s_InitFrame)
{
g_pNextCmdList_->TransitionBarrier(&g_texture_, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
for (auto& v : g_vbuffers_)
{
g_pNextCmdList_->TransitionBarrier(&v, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
}
g_pNextCmdList_->TransitionBarrier(&g_ibuffer_, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER);
s_InitFrame = false;
}
auto scTex = g_Device_.GetSwapchain().GetCurrentTexture(1);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_Device_.GetSwapchain().GetCurrentDescHandle(1);
D3D12_CPU_DESCRIPTOR_HANDLE rtvOffHandle = g_RenderTargetView_.GetDescInfo().cpuHandle;
D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = g_DepthBufferView_.GetDescInfo().cpuHandle;
ID3D12GraphicsCommandList* pCmdList = g_pNextCmdList_->GetCommandList();
g_pNextCmdList_->TransitionBarrier(scTex, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
g_pNextCmdList_->TransitionBarrier(&g_RenderTarget_, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_RENDER_TARGET);
g_pNextCmdList_->TransitionBarrier(&g_DepthBuffer_, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_DEPTH_WRITE);
// 画面クリア
const float kClearColor[] = { 0.0f, 0.0f, 0.6f, 1.0f };
pCmdList->ClearRenderTargetView(rtvHandle, kClearColor, 0, nullptr);
pCmdList->ClearRenderTargetView(rtvOffHandle, g_RenderTarget_.GetTextureDesc().clearColor, 0, nullptr);
pCmdList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, g_DepthBuffer_.GetTextureDesc().clearDepth, g_DepthBuffer_.GetTextureDesc().clearStencil, 0, nullptr);
// Viewport + Scissor設定
D3D12_VIEWPORT viewport{ 0.0f, 0.0f, (float)kWindowWidth, (float)kWindowHeight, 0.0f, 1.0f };
D3D12_RECT scissor{ 0, 0, kWindowWidth, kWindowHeight };
pCmdList->RSSetViewports(1, &viewport);
pCmdList->RSSetScissorRects(1, &scissor);
// Scene定数バッファを更新
auto&& cbScene = g_CBSceneViews_[frameIndex];
auto&& cbPrevScene = g_CBSceneViews_[frameIndex + sl12::Swapchain::kMaxBuffer];
{
static float sAngle = 0.0f;
void* p0 = g_pCBSceneBuffers_[frameIndex];
DirectX::XMFLOAT4X4* pMtxs = reinterpret_cast<DirectX::XMFLOAT4X4*>(p0);
DirectX::XMMATRIX mtxW = DirectX::XMMatrixRotationY(sAngle * DirectX::XM_PI / 180.0f);
DirectX::FXMVECTOR eye = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 5.0f, 10.0f));
DirectX::FXMVECTOR focus = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f));
DirectX::FXMVECTOR up = DirectX::XMLoadFloat3(&DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f));
DirectX::XMMATRIX mtxV = DirectX::XMMatrixLookAtRH(eye, focus, up);
DirectX::XMMATRIX mtxP = DirectX::XMMatrixPerspectiveFovRH(60.0f * DirectX::XM_PI / 180.0f, (float)kWindowWidth / (float)kWindowHeight, 1.0f, 100000.0f);
DirectX::XMStoreFloat4x4(pMtxs + 0, mtxW);
DirectX::XMStoreFloat4x4(pMtxs + 1, mtxV);
DirectX::XMStoreFloat4x4(pMtxs + 2, mtxP);
void* p1 = g_pCBSceneBuffers_[frameIndex + sl12::Swapchain::kMaxBuffer];
memcpy(p1, p0, sizeof(DirectX::XMFLOAT4X4) * 3);
pMtxs = reinterpret_cast<DirectX::XMFLOAT4X4*>(p1);
mtxW = DirectX::XMMatrixTranslation(0.5f, 0.0f, 0.5f) * DirectX::XMMatrixScaling(4.0f, 2.0f, 1.0f);
DirectX::XMStoreFloat4x4(pMtxs + 0, mtxW);
sAngle += 1.0f;
}
{
// レンダーターゲット設定
pCmdList->OMSetRenderTargets(1, &rtvOffHandle, false, &dsvHandle);
pCmdList->SetPipelineState(g_psoWriteS_.GetPSO());
g_descSet_.Reset();
g_descSet_.SetVsCbv(0, cbScene.GetDescInfo().cpuHandle);
g_descSet_.SetPsSrv(0, g_textureView_.GetDescInfo().cpuHandle);
g_descSet_.SetPsSampler(0, g_sampler_.GetDescInfo().cpuHandle);
g_pNextCmdList_->SetGraphicsRootSignatureAndDescriptorSet(&g_rootSig_, &g_descSet_);
// DrawCall
D3D12_VERTEX_BUFFER_VIEW views[] = { g_vbufferViews_[0].GetView(), g_vbufferViews_[1].GetView(), g_vbufferViews_[2].GetView() };
pCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pCmdList->IASetVertexBuffers(0, _countof(views), views);
pCmdList->IASetIndexBuffer(&g_ibufferView_.GetView());
pCmdList->DrawIndexedInstanced(6, 1, 0, 0, 0);
}
g_pNextCmdList_->TransitionBarrier(&g_RenderTarget_, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_GENERIC_READ);
g_pNextCmdList_->TransitionBarrier(&g_DepthBuffer_, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_GENERIC_READ);
{
// レンダーターゲット設定
pCmdList->OMSetRenderTargets(1, &rtvHandle, false, nullptr);
//pCmdList->OMSetRenderTargets(1, &rtvHandle, false, &dsvHandle);
pCmdList->SetPipelineState(g_psoUseS_.GetPSO());
pCmdList->OMSetStencilRef(0xf);
g_descSet_.Reset();
g_descSet_.SetVsCbv(0, cbPrevScene.GetDescInfo().cpuHandle);
g_descSet_.SetPsSrv(0, g_DepthBufferTexView_.GetDescInfo().cpuHandle);
g_descSet_.SetPsSampler(0, g_sampler_.GetDescInfo().cpuHandle);
g_pNextCmdList_->SetGraphicsRootSignatureAndDescriptorSet(&g_rootSig_, &g_descSet_);
// DrawCall
D3D12_VERTEX_BUFFER_VIEW views[] = { g_vbufferViews_[0].GetView(), g_vbufferViews_[1].GetView(), g_vbufferViews_[2].GetView() };
pCmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pCmdList->IASetVertexBuffers(0, _countof(views), views);
pCmdList->IASetIndexBuffer(&g_ibufferView_.GetView());
pCmdList->DrawIndexedInstanced(6, 1, 0, 0, 0);
}
g_pNextCmdList_->TransitionBarrier(scTex, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
g_pNextCmdList_->Close();
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
InitWindow(hInstance, nCmdShow);
std::array<uint32_t, D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES> kDescNums
{ 100, 100, 20, 10 };
auto ret = g_Device_.Initialize(g_hWnd_, kWindowWidth, kWindowHeight, kDescNums);
assert(ret);
ret = g_mainCmdList_.Initialize(&g_Device_, &g_Device_.GetGraphicsQueue());
assert(ret);
for (int i = 0; i < _countof(g_mainCmdLists_); ++i)
{
ret = g_mainCmdLists_[i].Initialize(&g_Device_, &g_Device_.GetGraphicsQueue());
assert(ret);
}
ret = g_copyCmdList_.Initialize(&g_Device_, &g_Device_.GetCopyQueue());
assert(ret);
ret = InitializeAssets();
assert(ret);
// メインループ
MSG msg = { 0 };
while (true)
{
// Process any messages in the queue.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
break;
}
g_Device_.WaitPresent();
RenderScene();
g_Device_.Present();
g_Device_.WaitDrawDone();
}
g_Device_.WaitDrawDone();
DestroyAssets();
g_copyCmdList_.Destroy();
for (int i = 0; i < _countof(g_mainCmdLists_); ++i)
{
g_mainCmdLists_[i].Destroy();
}
g_mainCmdList_.Destroy();
g_Device_.Destroy();
return static_cast<char>(msg.wParam);
}
| 29.184496 | 197 | 0.740703 | Monsho |
d961e99b79a916ca0f61a8909cbe1c26635b5d9a | 2,443 | cpp | C++ | src/core/DataProxy.cpp | Opticalp/instrumentall | f952c1cd54f375dc4cb258fec5af34d14c2b8044 | [
"MIT"
] | 1 | 2020-05-19T02:06:55.000Z | 2020-05-19T02:06:55.000Z | src/core/DataProxy.cpp | Opticalp/instrumentall | f952c1cd54f375dc4cb258fec5af34d14c2b8044 | [
"MIT"
] | 16 | 2015-11-18T13:25:30.000Z | 2018-05-17T19:25:46.000Z | src/core/DataProxy.cpp | Opticalp/instrumentall | f952c1cd54f375dc4cb258fec5af34d14c2b8044 | [
"MIT"
] | null | null | null | /**
* @file src/core/DataProxy.cpp
* @date Jul. 2016
* @author PhRG - opticalp.fr
*/
/*
Copyright (c) 2016 Ph. Renaud-Goud / Opticalp
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 "DataProxy.h"
#include "ExecutionAbortedException.h"
#include "Poco/NumberFormatter.h"
void DataProxy::runTarget()
{
if (!tryCatchSource())
poco_bugcheck_msg((name() + ": not able to catch the source").c_str());
lockSource();
DataAttribute attr;
readInputDataAttribute(&attr);
while (!tryWriteDataLock())
{
if (yield())
{
releaseInputData();
throw ExecutionAbortedException("DataProxy::runTarget",
"Task cancellation upon user request");
}
}
try
{
convert();
}
catch (...)
{
releaseInputData();
releaseWriteOnFailure();
throw;
}
releaseInputData();
notifyReady(attr);
}
void DataProxy::setName(size_t refCount)
{
if (className.empty())
poco_bugcheck_msg("trying to set the name of the data proxy "
"but its class name is empty");
std::string tmpName(className);
if (refCount)
tmpName += Poco::NumberFormatter::format(refCount);
UniqueNameEntity::setName(tmpName);
}
void DataProxy::setName(std::string newName)
{
UniqueNameEntity::setName(newName);
std::string identifier = "dataProxy." + getClassName() + "." + newName;
setLogger(identifier);
setPrefixKey(identifier);
setAllParametersFromConf();
}
| 26.554348 | 78 | 0.714695 | Opticalp |
d9632bf50b6a41f647f6954a10d20645a2a9c57c | 18,384 | hpp | C++ | src/sim-driver/SimCallbacks.hpp | LoganBarnes/SimulationDriver | 25b68b653afa81f3b55681513d3dd99fd36f6a5e | [
"MIT"
] | null | null | null | src/sim-driver/SimCallbacks.hpp | LoganBarnes/SimulationDriver | 25b68b653afa81f3b55681513d3dd99fd36f6a5e | [
"MIT"
] | 1 | 2018-02-24T11:47:26.000Z | 2018-02-24T11:47:26.000Z | src/sim-driver/SimCallbacks.hpp | LoganBarnes/SimulationDriver | 25b68b653afa81f3b55681513d3dd99fd36f6a5e | [
"MIT"
] | null | null | null | #pragma once
#include <sim-driver/CallbackWrapper.hpp>
#include <sim-driver/SimData.hpp>
#include <memory>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
namespace sim {
template <size_t N>
struct priority_tag : public priority_tag<N - 1>
{
};
template <>
struct priority_tag<0>
{
};
template <typename C = EmptyCallbacks>
class SimCallbacks
{
public:
explicit SimCallbacks(SimData *pSimData, C *pCallbacks = nullptr);
void framebufferSizeCallback(GLFWwindow *pWindow, int width, int height);
void windowFocusCallback(GLFWwindow *pWindow, int focus);
void mouseButtonCallback(GLFWwindow *pWindow, int button, int action, int mods);
void keyCallback(GLFWwindow *pWindow, int key, int scancode, int action, int mods);
void cursorPosCallback(GLFWwindow *pWindow, double xpos, double ypos);
void scrollCallback(GLFWwindow *pWindow, double xoffset, double yoffset);
void charCallback(GLFWwindow *pWindow, unsigned codepoint);
bool isLeftMouseDown() const;
bool isRightMouseDown() const;
bool isShiftDown() const;
bool isCtrlDown() const;
private:
SimData *pSimData_;
C *pCallbacks_;
sim::priority_tag<2> p_;
bool leftMouseDown_{false};
bool rightMouseDown_{false};
bool shiftDown_{false};
bool ctrlDown_{false};
double prevX_;
double prevY_;
template <typename T>
auto framebufferSizeCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<2> p)
-> decltype(callbacks.framebufferSizeCallback(window, width, height, parent), void());
template <typename T>
auto framebufferSizeCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<1> p)
-> decltype(callbacks.framebufferSizeCallback(window, width, height), void());
template <typename T>
void framebufferSizeCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<0> p);
template <typename T>
auto
windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<2> p)
-> decltype(callbacks.windowFocusCallback(window, focus, parent), void());
template <typename T>
auto
windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<1> p)
-> decltype(callbacks.windowFocusCallback(window, focus), void());
template <typename T>
void
windowFocusCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<0> p);
template <typename T>
auto mouseButtonCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int button,
int action,
int mods,
priority_tag<2> p)
-> decltype(callbacks.mouseButtonCallback(window, button, action, mods, parent), void());
template <typename T>
auto mouseButtonCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int button,
int action,
int mods,
priority_tag<1> p)
-> decltype(callbacks.mouseButtonCallback(window, button, action, mods), void());
template <typename T>
void mouseButtonCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int button,
int action,
int mods,
priority_tag<0> p);
template <typename T>
auto keyCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int key,
int scancode,
int action,
int mods,
priority_tag<2> p)
-> decltype(callbacks.keyCallback(window, key, scancode, action, mods, parent), void());
template <typename T>
auto keyCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int key,
int scancode,
int action,
int mods,
priority_tag<1> p) -> decltype(callbacks.keyCallback(window, key, scancode, action, mods), void());
template <typename T>
void keyCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int key,
int scancode,
int action,
int mods,
priority_tag<0> p);
template <typename T>
auto cursorPosCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<2> p)
-> decltype(callbacks.cursorPosCallback(window, xpos, ypos, parent), void());
template <typename T>
auto cursorPosCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<1> p)
-> decltype(callbacks.cursorPosCallback(window, xpos, ypos), void());
template <typename T>
void cursorPosCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<0> p);
template <typename T>
auto scrollCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
double xoffset,
double yoffset,
priority_tag<2> p)
-> decltype(callbacks.scrollCallback(window, xoffset, yoffset, parent), void());
template <typename T>
auto scrollCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
double xoffset,
double yoffset,
priority_tag<1> p) -> decltype(callbacks.scrollCallback(window, xoffset, yoffset), void());
template <typename T>
void scrollCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
double xoffset,
double yoffset,
priority_tag<0> p);
template <typename T>
auto
charCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<2> p)
-> decltype(callbacks.charCallback(window, codepoint, parent), void());
template <typename T>
auto
charCallback(T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<1> p)
-> decltype(callbacks.charCallback(window, codepoint), void());
template <typename T>
void charCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<0> p);
};
template <typename C>
SimCallbacks<C>::SimCallbacks(SimData *pSimData, C *pCallbacks) : pSimData_{pSimData}, pCallbacks_(pCallbacks)
{
}
template <typename C>
void SimCallbacks<C>::framebufferSizeCallback(GLFWwindow *pWindow, int width, int height)
{
if (pSimData_) {
pSimData_->camera().setAspectRatio(static_cast<float>(width) / height);
}
if (pCallbacks_) {
framebufferSizeCallback(*pCallbacks_, *this, pWindow, width, height, p_);
}
}
template <typename C>
void SimCallbacks<C>::windowFocusCallback(GLFWwindow *pWindow, int focus)
{
if (pCallbacks_) {
windowFocusCallback(*pCallbacks_, *this, pWindow, focus, p_);
}
}
template <typename C>
void SimCallbacks<C>::mouseButtonCallback(GLFWwindow *pWindow, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_1) {
if (action == GLFW_PRESS) {
leftMouseDown_ = true;
glfwGetCursorPos(pWindow, &prevX_, &prevY_);
} else if (action == GLFW_RELEASE) {
leftMouseDown_ = false;
}
} else if (button == GLFW_MOUSE_BUTTON_2) {
if (action == GLFW_PRESS) {
rightMouseDown_ = true;
glfwGetCursorPos(pWindow, &prevX_, &prevY_);
} else if (action == GLFW_RELEASE) {
rightMouseDown_ = false;
}
}
if (pCallbacks_) {
mouseButtonCallback(*pCallbacks_, *this, pWindow, button, action, mods, p_);
}
}
template <typename C>
void SimCallbacks<C>::keyCallback(GLFWwindow *pWindow, int key, int scancode, int action, int mods)
{
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(pWindow, GLFW_TRUE);
break;
case GLFW_KEY_S:
if (action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
// save something?
}
break;
case GLFW_KEY_P:
if (pSimData_ && action == GLFW_RELEASE) {
pSimData_->paused = !(pSimData_->paused);
}
default:
break;
}
shiftDown_ = (mods == GLFW_MOD_SHIFT);
ctrlDown_ = (mods == GLFW_MOD_CONTROL);
if (pCallbacks_) {
keyCallback(*pCallbacks_, *this, pWindow, key, scancode, action, mods, p_);
}
}
template <typename C>
void SimCallbacks<C>::cursorPosCallback(GLFWwindow *pWindow, double xpos, double ypos)
{
if (pSimData_) {
if (leftMouseDown_) {
pSimData_->cameraMover.pitch(static_cast<float>(prevY_ - ypos));
pSimData_->cameraMover.yaw(static_cast<float>(prevX_ - xpos));
} else if (rightMouseDown_) {
pSimData_->cameraMover.zoom(static_cast<float>(prevY_ - ypos));
}
}
prevX_ = xpos;
prevY_ = ypos;
if (pCallbacks_) {
cursorPosCallback(*pCallbacks_, *this, pWindow, xpos, ypos, p_);
}
}
template <typename C>
void SimCallbacks<C>::scrollCallback(GLFWwindow *pWindow, double xoffset, double yoffset)
{
if (pSimData_) {
pSimData_->cameraMover.zoom(static_cast<float>(-yoffset));
}
if (pCallbacks_) {
scrollCallback(*pCallbacks_, *this, pWindow, xoffset, yoffset, p_);
}
}
template <typename C>
void SimCallbacks<C>::charCallback(GLFWwindow *pWindow, unsigned codepoint)
{
if (pCallbacks_) {
charCallback(*pCallbacks_, *this, pWindow, codepoint, p_);
}
}
/////////////////////////////////////// Private implementation functions ///////////////////////////////////////
template <typename C>
template <typename T>
auto SimCallbacks<C>::framebufferSizeCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int width, int height, priority_tag<2>)
-> decltype(callbacks.framebufferSizeCallback(window, width, height, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.framebufferSizeCallback(window, width, height, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::framebufferSizeCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int width, int height, priority_tag<1>)
-> decltype(callbacks.framebufferSizeCallback(window, width, height), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.framebufferSizeCallback(window, width, height);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::windowFocusCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int focus, priority_tag<2>)
-> decltype(callbacks.windowFocusCallback(window, focus, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.windowFocusCallback(window, focus, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::windowFocusCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int focus, priority_tag<1>)
-> decltype(callbacks.windowFocusCallback(window, focus), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.windowFocusCallback(window, focus);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::mouseButtonCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, int button, int action, int mods, priority_tag<2>)
-> decltype(callbacks.mouseButtonCallback(window, button, action, mods, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.mouseButtonCallback(window, button, action, mods, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::mouseButtonCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, int button, int action, int mods, priority_tag<1>)
-> decltype(callbacks.mouseButtonCallback(window, button, action, mods), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.mouseButtonCallback(window, button, action, mods);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::keyCallback(T &callbacks,
const SimCallbacks<T> &parent,
GLFWwindow *window,
int key,
int scancode,
int action,
int mods,
priority_tag<2>)
-> decltype(callbacks.keyCallback(window, key, scancode, action, mods, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.keyCallback(window, key, scancode, action, mods, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::keyCallback(T &callbacks,
const SimCallbacks<T> &,
GLFWwindow *window,
int key,
int scancode,
int action,
int mods,
priority_tag<1>)
-> decltype(callbacks.keyCallback(window, key, scancode, action, mods), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.keyCallback(window, key, scancode, action, mods);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::cursorPosCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xpos, double ypos, priority_tag<2>)
-> decltype(callbacks.cursorPosCallback(window, xpos, ypos, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.cursorPosCallback(window, xpos, ypos, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::cursorPosCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, double xpos, double ypos, priority_tag<1>)
-> decltype(callbacks.cursorPosCallback(window, xpos, ypos), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.cursorPosCallback(window, xpos, ypos);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::scrollCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, double xoffset, double yoffset, priority_tag<2>)
-> decltype(callbacks.scrollCallback(window, xoffset, yoffset, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.scrollCallback(window, xoffset, yoffset, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::scrollCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, double xoffset, double yoffset, priority_tag<1>)
-> decltype(callbacks.scrollCallback(window, xoffset, yoffset), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.scrollCallback(window, xoffset, yoffset);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::charCallback(
T &callbacks, const SimCallbacks<T> &parent, GLFWwindow *window, unsigned codepoint, priority_tag<2>)
-> decltype(callbacks.charCallback(window, codepoint, parent), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.charCallback(window, codepoint, parent);
}
template <typename C>
template <typename T>
auto SimCallbacks<C>::charCallback(
T &callbacks, const SimCallbacks<T> &, GLFWwindow *window, unsigned codepoint, priority_tag<1>)
-> decltype(callbacks.charCallback(window, codepoint), void())
{
static_assert(std::is_same<T, C>::value, "");
callbacks.charCallback(window, codepoint);
}
/////////////////////////////////////// Empty implementation functions ///////////////////////////////////////
template <typename C>
template <typename T>
void SimCallbacks<C>::framebufferSizeCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::windowFocusCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::mouseButtonCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, int, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::keyCallback(T &, const SimCallbacks<T> &, GLFWwindow *, int, int, int, int, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::cursorPosCallback(T &, const SimCallbacks<T> &, GLFWwindow *, double, double, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::scrollCallback(T &, const SimCallbacks<T> &, GLFWwindow *, double, double, priority_tag<0>)
{
}
template <typename C>
template <typename T>
void SimCallbacks<C>::charCallback(T &, const SimCallbacks<T> &, GLFWwindow *, unsigned, priority_tag<0>)
{
}
template <typename C>
bool SimCallbacks<C>::isLeftMouseDown() const
{
return leftMouseDown_;
}
template <typename C>
bool SimCallbacks<C>::isRightMouseDown() const
{
return rightMouseDown_;
}
template <typename C>
bool SimCallbacks<C>::isShiftDown() const
{
return shiftDown_;
}
template <typename C>
bool SimCallbacks<C>::isCtrlDown() const
{
return ctrlDown_;
}
} // namespace sim
| 36.260355 | 120 | 0.631364 | LoganBarnes |
d9634f68149f776f57850245b4314d92d7b3da30 | 2,193 | cpp | C++ | cpp/game of two stack.cpp | kuwarkapur/Hacktoberfest-2022 | efaafeba5ce51d8d2e2d94c6326cc20bff946f17 | [
"MIT"
] | 1 | 2021-12-03T09:23:41.000Z | 2021-12-03T09:23:41.000Z | cpp/game of two stack.cpp | kuwarkapur/Hacktoberfest-2022 | efaafeba5ce51d8d2e2d94c6326cc20bff946f17 | [
"MIT"
] | null | null | null | cpp/game of two stack.cpp | kuwarkapur/Hacktoberfest-2022 | efaafeba5ce51d8d2e2d94c6326cc20bff946f17 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
class _stack{
public:
int size = 0;
int *nStack;
_stack(int n){
size = 0;
nStack = new int[n];
}
_stack(int n, bool a){
size = n;
nStack = new int[size];
}
_stack(int a[],int n){
size = n;
nStack = new int[size];
for (int i = 0; i< size; i++){
nStack[i] = a[size-(i+1)];
}
}
int top(){
return nStack[size-1];
}
int pop(){
size --;
return nStack[size];
}
void push(int a){
nStack[size] = a;
size ++;
}
};
int max_tam(_stack &stac, _stack &popedItems, int &x){
int size = stac.size, sumando, act_size = 0;
for (int i = 0; i < size; i ++){
sumando = stac.top();
if (x - sumando >=0){
stac.pop();
popedItems.push(sumando);
x -= sumando;
act_size ++;
}
else break;
}
return act_size;
}
int intercalado (int x, int tam_act, _stack b, _stack res){
int sumando, max_tam = tam_act, size = b.size;
for (int i = 0; i < size; i ++){
sumando = b.top();
if ( x - sumando >= 0){
b.pop();
x -= sumando;
tam_act ++;
if (tam_act > max_tam) max_tam = tam_act;
}
else if (res.size > 0){
i --;
x += res.pop();
tam_act --;
}
else break;
}
return max_tam;
}
int twoStacks(int &x, _stack &_a, _stack &_b) {
_stack c = _stack(_a.size);
int tam_sub_a = max_tam(_a, c, x);
return intercalado(x, tam_sub_a, _b, c);
}
int main()
{
int g;
cin >> g;
while (g--){
int n, m , x;
cin>>n>>m>>x;
_stack a = _stack(n, true);
_stack b = _stack(m, true);
for(int i = 0; i < n; i++)cin>>a.nStack[n-(i+1)];
for(int i = 0; i < m; i++)cin>>b.nStack[m-(i+1)];
cout << twoStacks(x,a,b)<<endl;
}
return 0;
} | 21.712871 | 59 | 0.427725 | kuwarkapur |
d96cf49e6730cb56c4d72e6b5a8efcb85d7a8ad9 | 6,513 | cpp | C++ | OPERA-LG/src/GapCorrecter.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 81 | 2018-03-22T15:01:08.000Z | 2022-01-17T17:52:31.000Z | OPERA-LG/src/GapCorrecter.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 68 | 2017-09-14T08:17:53.000Z | 2022-03-09T18:56:12.000Z | OPERA-LG/src/GapCorrecter.cpp | lorenzgerber/OPERA-MS | bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f | [
"MIT"
] | 21 | 2017-09-14T06:15:18.000Z | 2021-09-30T03:19:22.000Z | #include "GapCorrecter.h"
GapCorrecter::GapCorrecter(void){
m_gapList = new vector<Gap*>;
}
GapCorrecter::GapCorrecter( int max, int min, int contigLength, int mean, int std, int readLength, vector<double> *pos ){
m_gapList = new vector<Gap*>();
m_contigLength = 0;
m_contigLength = contigLength;
m_maxGapSize = max; // should be the max insert size - read length
m_minGapSize = 0;
m_minGapSize = min;
m_mean = mean;
m_std = std;
m_possibility = pos;
m_readLength = 0;
m_readLength = readLength;
m_useNormalDistribution = true;
int sum = 0;
for( int i = 0; i < (int) pos->size(); i++ ){
sum += pos->at( i );
}
if( sum <= 100000 ){
//cerr<<"use normal distribution\n";
m_useNormalDistribution = true;
}
else
m_useNormalDistribution = false;
Init();
}
GapCorrecter::~GapCorrecter(void){
for( int i = 0; i < (int) m_gapList->size(); i++ ){
delete m_gapList->at( i );
}
m_gapList->clear();
delete m_gapList;
}
void GapCorrecter::Init(){
for( int i = 0; i <= m_maxGapSize; i++ ){
Gap *newGap = new Gap();
newGap->m_realGapSize = i;
m_gapList->push_back( newGap );
}
}
// construct the relationship between real gap size and estimated gap size
void GapCorrecter::CalculateTable(){
//cerr<<"mean: "<<m_mean<<endl;
m_minEstimatedGapSize = 0;
m_maxEstimatedGapSize = 0;
//bool startIsZero = true;
//bool endIsZero = false;
// for gap = 0,
// calculate summation of i*P(i) from g to g+c
// calculate summation of P(i) from g to g+c
double numerator = 0;
double denominator = 0;
for( int i = m_readLength; i <= m_contigLength; i++ ){
double possibility = CalculatePossibility( i );
//double possibility = m_possibility->at( i );
numerator += i * possibility;
denominator += possibility;
}
// calculate new mu
double newMu;
if( denominator == 0 )
newMu = 0;
else
newMu = numerator / denominator;
// calculate estimated gap size
// g_head = g - mu_head + mu
double newGapSize;
if( m_contigLength >= m_minGapSize )
newGapSize = 0 - newMu + m_mean;
else
newGapSize = 0;
m_gapList->at( 0 )->m_estimatedGapSize = newGapSize;
m_gapList->at( 0 )->m_newMu = newMu;
if( newGapSize != 0 )
m_minEstimatedGapSize = newGapSize;
if( newGapSize > m_maxEstimatedGapSize )
m_maxEstimatedGapSize = newGapSize;
// for gap g from 1 to max
for( int i = 1; i < (int) m_gapList->size(); i++ ){
double possibilityGM1 = CalculatePossibility( i - 1 + m_readLength);
double possibilityGPC = CalculatePossibility( i + m_contigLength );
//double possibilityGM1 = m_possibility->at( i - 1 );
//double possibilityGPC = m_possibility->at( i + m_contigLength );
// update i*P(i): minus (g-1)P(g-1), plus (g+c)P(g+c)
numerator -= (i - 1 + m_readLength) * possibilityGM1;
numerator += (i + m_contigLength) * possibilityGPC;
// update P(i): minus P(g-1), plus P(g+c)
denominator -= possibilityGM1;
denominator += possibilityGPC;
// calculate new mu
if( denominator > 0 )
newMu = numerator / denominator;
else
newMu = 0;
// calculate estimated gap size
double newGapSize;
if( denominator > 0 )
newGapSize = i - newMu + m_mean;
else
newGapSize = 0;
if( newGapSize > m_maxEstimatedGapSize )
m_maxEstimatedGapSize = newGapSize;
if( m_minEstimatedGapSize == 0 && newGapSize != 0 )
m_minEstimatedGapSize = newGapSize;
m_gapList->at( i )->m_estimatedGapSize = newGapSize;
m_gapList->at( i )->m_newMu = newMu;
}
}
// calculate the possibility of a certain value
double GapCorrecter::CalculatePossibility( int value ){
if( m_useNormalDistribution ){
// use normal distribution
double result = exp( -pow(value - m_mean, 2)/(2 * m_std * m_std) );
return result * 10000;
}
else{
double result;
if( value >= (int) m_possibility->size() )
result = 0;
else
result = m_possibility->at( value );
return result;
}
}
// print the constructed table
int GapCorrecter::PrintTable( string fileName ){
ofstream tableWriter( (Configure::OUTPUT_FOLDER + fileName).c_str() );
if( tableWriter.fail() ){
cout<<"ERROR: Cannot open "<<(Configure::OUTPUT_FOLDER + fileName)<<" file"<<endl;
return -1;
}
string results;
results = "read_gap_size\testimated_gap_size\tnew_mean\n";
for( int i = 0; i < (int) m_gapList->size(); i++ ){
results.append( itos( i ) + "\t" + itos( m_gapList->at( i )->m_estimatedGapSize ) +
"\t" + itos( m_gapList->at( i )->m_newMu ) + "\n" );
}
tableWriter.write( results.c_str(), results.length() );
tableWriter.close();
return 1;
}
// get the corresponding real gap size of a given estimated gap size
int GapCorrecter::GetRealGapSize( double estimatedGapSize )
{
//cout<<"Estimated gap size is: "<<estimatedGapSize<<endl;
//cerr<<"Get real gaps size\n";
// if the value is too small
if( estimatedGapSize < m_minEstimatedGapSize )
return estimatedGapSize;
// if the value is too big
if( estimatedGapSize > m_maxEstimatedGapSize ){
// bigger than the tail value, just use the tail value
//int number = 0;
//double sum = 0;
for( int i = m_gapList->size() - 1; i >= 0; i-- ){
if( i == 0 ){
continue;
}
if( m_gapList->at( i )->m_estimatedGapSize > 0 ){ //== m_maxEstimatedGapSize ){
return i;
//number++;
//sum += i;
}
//else
// break;
}
//double realValue = sum / number;
//return realValue;
return estimatedGapSize;
}
// search for the right position
int max = m_gapList->size() - 1;
int min = 0;
int middle = -1;
while( min != max ){
middle = (min + max)/2;
if( m_gapList->at( middle )->m_estimatedGapSize == estimatedGapSize ){
// find the exact value, exit
break;
}
if( middle == min || middle == max )
break;
if( m_gapList->at( middle )->m_estimatedGapSize < estimatedGapSize ){
min = middle;
}
else{
max = middle;
}
}
middle = (min+max)/2;
// collect all the possible gap sizes
int number = 1;
double sum = middle;
// check the one before middle
for( int i = middle - 1; i >= 0; i-- ){
if( m_gapList->at( i )->m_estimatedGapSize == m_gapList->at( middle )->m_estimatedGapSize ){
number++;
sum += i;
}
else
break;
}
// check the one after middle
for( int i = middle + 1; i < (int) m_gapList->size(); i++ ){
if( m_gapList->at( i )->m_estimatedGapSize == m_gapList->at( middle )->m_estimatedGapSize ){
number++;
sum += i;
}
else
break;
}
//cerr<<"find the value\n";
double realValue = sum / number;
return realValue;
}
| 24.393258 | 121 | 0.647014 | lorenzgerber |
d96dd08a6b14a3eaf66076413dcb98ef5c003663 | 2,716 | cpp | C++ | Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp | AnthonyDas/Cpp_Data_Structures_And_Algorithms | 4ba834803dde0285ee2695b7ef97afbcdcf0484a | [
"MIT"
] | null | null | null | Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp | AnthonyDas/Cpp_Data_Structures_And_Algorithms | 4ba834803dde0285ee2695b7ef97afbcdcf0484a | [
"MIT"
] | null | null | null | Cpp_Data_Structures_And_Algorithms/HashTableOpenAddressing.cpp | AnthonyDas/Cpp_Data_Structures_And_Algorithms | 4ba834803dde0285ee2695b7ef97afbcdcf0484a | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include "HashTableOpenAddressing.h"
HashTableOpenAddressing::HashTableOpenAddressing() {
// Initialize current size as 0
currentSize = 0;
// Initialize table
arr = new HashElement *[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; ++i)
arr[i] = nullptr;
// Specify deleted node content
deletedElement = new HashElement(-1, "");
}
int HashTableOpenAddressing::HashFunction(int key) {
return key % TABLE_SIZE;
}
void HashTableOpenAddressing::Insert(int key, std::string value) {
// It's impossible to store a new element
// if hash table doesn't have free space
if (currentSize >= TABLE_SIZE)
return;
// Create a temporary element
// to be inserted to hash table
HashElement * temp = new HashElement(key, value);
// Get hash key from hash function
int hashIndex = HashFunction(key);
// Find next free space
// using linear probing
while (arr[hashIndex] != nullptr && arr[hashIndex]->Key != key && arr[hashIndex]->Key != -1) {
++hashIndex;
hashIndex %= TABLE_SIZE;
}
// If there's new element to be inserted
// then increase the current size
if (arr[hashIndex] == nullptr || arr[hashIndex]->Key == -1) {
++currentSize;
arr[hashIndex] = temp;
}
}
std::string HashTableOpenAddressing::Search(int key) {
// Get hash key from hash function
int hashIndex = HashFunction(key);
// Find the element with given key
while (arr[hashIndex] != nullptr && arr[hashIndex]->Key != deletedElement->Key) {
// If element is found
// then return its value
if (arr[hashIndex]->Key == key)
return arr[hashIndex]->Value;
// Keep looking for the key
// using linear probing
++hashIndex;
hashIndex %= TABLE_SIZE;
}
// If not found return null
return "";
}
void HashTableOpenAddressing::Remove(int key) {
// Get hash key from hash function
int hashIndex = HashFunction(key);
// Find the element with given key
while (arr[hashIndex] != nullptr) {
// If element is found then mark the cell as deletedElement
if (arr[hashIndex]->Key == key) {
arr[hashIndex] = deletedElement;
// Reduce size
--currentSize;
// No need to search anymore
return;
}
// Keep looking for the key
// using linear probing
++hashIndex;
hashIndex %= TABLE_SIZE;
}
// Note: if key is not found just do nothing
}
bool HashTableOpenAddressing::IsEmpty() {
return currentSize == 0;
}
void HashTableOpenAddressing::PrintHashTableOpenAddressing() {
// Iterate through array
for (int i = 0; i < currentSize; ++i) {
// Just print the element if it exist
if (arr[i] != nullptr && arr[i]->Key != -1) {
std::cout << "Cell: " << i << " Key: " << arr[i]->Key;
std::cout << " Value: " << arr[i]->Value << std::endl;
}
}
}
| 24.468468 | 95 | 0.672312 | AnthonyDas |
d96eb2f9ec5a7d60f38c0f83da3303802db86ac1 | 1,710 | cpp | C++ | Source.cpp | UFFFF/TicTacToe | 7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb | [
"CC0-1.0"
] | null | null | null | Source.cpp | UFFFF/TicTacToe | 7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb | [
"CC0-1.0"
] | null | null | null | Source.cpp | UFFFF/TicTacToe | 7ba20567f9d71c07f2a67a9e5d55aa1521ccd0fb | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <SFML/Graphics.hpp>
#include "Visual.h"
#include "Field.h"
int main() {
bool game_over = false;
int a = 0;
WinCon w;
Field f;
sf::RenderWindow window(sf::VideoMode(620, 620), "TicTacToe");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
sf::Vector2i p = sf::Mouse::getPosition(window);
std::pair<int,int> s_s = f.containsfield(p.x, p.y);
std::cout << s_s.first << " " << s_s.second << std::endl;
if (a % 2 == 0 && (f.available(p.x, p.y)) && !game_over) {
f.append_Kreis(s_s.first, s_s.second);
w.append_kreis(f.get_number(p.x, p.y));
if (w.won()) {
std::cout << "KREIS HAT GEWONNEN" << std::endl;
game_over = true;
}
a++;
}
else if(a % 2 != 0 && (f.available(p.x, p.y)) && !game_over){
f.append_Kreuz(s_s.first, s_s.second);
w.append_kreuz(f.get_number(p.x, p.y));
if (w.won()) {
std::cout << "KREUZ HAT GEWONNEN" << std::endl;
game_over = true;
}
a++;
}
}
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
Visual v(window);
f.update(window);
window.display();
}
return 0;
} | 34.897959 | 78 | 0.415205 | UFFFF |
d96f5dbe62d74dea33ddf962164768b362ec2e26 | 440 | hpp | C++ | src/visum/events/repeats/Weekdays.hpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | src/visum/events/repeats/Weekdays.hpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | src/visum/events/repeats/Weekdays.hpp | Mokon/visum | 53f602fcf22eadd60f446d04a26b4a6e7217c052 | [
"RSA-MD"
] | null | null | null | /* Copyright (C) 2013-2016 David 'Mokon' Bond, All Rights Reserved */
#pragma once
enum Weekdays
: uint8_t
{
Sunday = 0x01,
Monday = 0x02,
Tuesday = 0x04,
Wednesday = 0x08,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40,
};
inline Weekdays operator|(Weekdays a, Weekdays b)
{
return static_cast<Weekdays>(static_cast<uint8_t>(a)|
static_cast<uint8_t>(b));
}
| 20 | 69 | 0.588636 | Mokon |
d97165b8ba5d737885033466a61556bf7b114470 | 2,800 | cpp | C++ | src/scene.cpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | src/scene.cpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | src/scene.cpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | #include <SDL.h>
#include <math.h>
#include <map>
#include "scene.hpp"
#include "entity.hpp"
#include "screen.hpp"
#include "collider2d.hpp"
#include "vector2.hpp"
#include "vector4.hpp"
#include "rect.hpp"
using namespace Prova;
void Scene::EnableDebug()
{
_debug = true;
}
void Scene::DisableDebug()
{
_debug = false;
}
bool Scene::IsDebugEnabled()
{
return _debug;
}
void Scene::AddEntity(Entity& entity)
{
entities.push_back(&entity);
entity.scene = this;
_collider2DMap.AddColliders(entity);
if(!entity._setup)
{
entity.Setup();
entity._setup = true;
}
entity.Start();
}
void Scene::RemoveEntity(Entity& entity)
{
entities.remove(&entity);
if(entity.scene == this)
entity.scene = nullptr;
_collider2DMap.RemoveColliders(entity);
}
// finds the closest entity to this entity
Entity& Scene::FindClosestEntity(Entity& myEntity)
{
float closestDistance = -1;
Entity* closestEntity = nullptr;
for(Entity* entity : entities)
{
// dont count yourself
if(entity == &myEntity)
continue;
float distance = entity->position.DistanceFrom(myEntity.position);
if(distance < closestDistance || closestDistance == -1)
{
closestDistance = distance;
closestEntity = entity;
}
}
return *closestEntity;
}
Entity& Scene::FindClosestEntity(Entity& myEntity, int tag)
{
float closestDistance = -1;
Entity* closestEntity = nullptr;
for(Entity* entity : entities)
{
// match tags and make sure we aren't matching with self
if(entity == &myEntity || !entity->HasTag(tag))
continue;
float distance = entity->position.DistanceFrom(myEntity.position);
if(distance < closestDistance || closestDistance == -1)
{
closestDistance = distance;
closestEntity = entity;
}
}
return *closestEntity;
}
void Scene::Setup() { }
void Scene::Start() { }
void Scene::Update()
{
EntityUpdate();
Collider2DUpdate();
}
void Scene::Collider2DUpdate()
{
_collider2DMap.MapColliders();
_collider2DMap.FindCollisions();
_collider2DMap.ResolveCollisions();
}
void Scene::EntityUpdate()
{
for(Entity* entity : entities)
{
entity->Update();
entity->position += entity->velocity;
}
}
void Scene::Draw(Screen& screen)
{
std::multimap<float, Entity*> sorted;
for(Entity* entity : entities)
{
float distance;
if(camera.sortingMethod == SortingMethod::Distance)
distance = entity->position.DistanceFrom(camera.position);
else
distance = camera.position.z - entity->position.z;
sorted.emplace(distance, entity);
}
for(auto it = sorted.rbegin(); it != sorted.rend(); ++it)
{
Entity& entity = *it->second;
entity.Draw(screen);
}
if(IsDebugEnabled())
_collider2DMap.Draw(*game->screen);
} | 18.421053 | 70 | 0.666786 | teamprova |
d9745592d0b182ef1da12e586ee31f913dac15a4 | 2,160 | cpp | C++ | source/gtpBullet/gtCollisionShapeImpl.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | null | null | null | source/gtpBullet/gtCollisionShapeImpl.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | null | null | null | source/gtpBullet/gtCollisionShapeImpl.cpp | lineCode/gost.engine | 5f69216b97fc638663b6a38bee3cacfea2abf7ba | [
"MIT"
] | 2 | 2020-01-22T08:45:44.000Z | 2020-02-15T20:08:41.000Z | #include "common.h"
gtCollisionShapeImpl::gtCollisionShapeImpl(gtPhysicsBullet * ps):
m_ps( ps ),
m_shape( nullptr ),
m_shapeBase( nullptr )
{}
gtCollisionShapeImpl::~gtCollisionShapeImpl(){
if( m_shape ){
m_ps->_removeShape( m_shape );
}
}
bool gtCollisionShapeImpl::initBox( const v3f& size ){
m_shape = new btBoxShape(btVector3(size.x, size.y, size.z));
if( !m_shape )
return false;
m_shapeBase = (btPolyhedralConvexShape*)m_shape;
m_ps->_addShape( m_shape );
return true;
}
btCollisionShape * gtCollisionShapeImpl::getBulletShape(){
return m_shape;
}
u32 gtCollisionShapeImpl::getNumVertices(){
return (u32)m_shapeBase->getNumVertices();
}
void gtCollisionShapeImpl::getVertex( u32 index, v3f& vertex ){
btVector3 v;
m_shapeBase->getVertex( (s32)index, v );
vertex.set(v[0],v[1],v[2]);
}
u32 gtCollisionShapeImpl::getNumEdges(){
return (u32)m_shapeBase->getNumEdges();
}
void gtCollisionShapeImpl::getEdge( u32 index, v3f& v1, v3f& v2 ){
btVector3 pa, pb;
m_shapeBase->getEdge( (s32)index, pa, pb );
v1.set(pa[0],pa[1],pa[2]);
v2.set(pb[0],pb[1],pb[2]);
}
/*
Copyright (c) 2018 532235
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.
*/ | 31.764706 | 126 | 0.753704 | lineCode |
d976167f2d2eb026e00b5a036c28b9a3a44a8230 | 3,894 | cpp | C++ | fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp | bkoray/fboss | 31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0 | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp | bkoray/fboss | 31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0 | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/benchmarks/HwTxSlowPathBenchmark.cpp | bkoray/fboss | 31ba4fab15b61ee36b7a117a80c7d55bb4dc70c0 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/Platform.h"
#include "fboss/agent/hw/test/ConfigFactory.h"
#include "fboss/agent/hw/test/HwSwitchEnsemble.h"
#include "fboss/agent/hw/test/HwSwitchEnsembleFactory.h"
#include "fboss/agent/hw/test/HwTestPacketUtils.h"
#include "fboss/agent/test/EcmpSetupHelper.h"
#include <folly/IPAddressV6.h>
#include <folly/dynamic.h>
#include <folly/init/Init.h>
#include <folly/json.h>
#include "common/time/Time.h"
#include <chrono>
#include <iostream>
#include <thread>
DEFINE_bool(json, true, "Output in json form");
namespace facebook::fboss {
std::pair<uint64_t, uint64_t> getOutPktsAndBytes(
HwSwitchEnsemble* ensemble,
PortID port) {
auto stats = ensemble->getLatestPortStats({port})[port];
return {stats.outUnicastPkts_, stats.outBytes_};
}
void runTxSlowPathBenchmark() {
constexpr int kEcmpWidth = 1;
auto ensemble = createHwEnsemble(HwSwitch::FeaturesDesired::LINKSCAN_DESIRED);
auto hwSwitch = ensemble->getHwSwitch();
auto portUsed = ensemble->masterLogicalPortIds()[0];
auto config = utility::oneL3IntfConfig(hwSwitch, portUsed);
ensemble->applyInitialConfigAndBringUpPorts(config);
auto ecmpHelper =
utility::EcmpSetupAnyNPorts6(ensemble->getProgrammedState());
auto ecmpRouteState = ecmpHelper.setupECMPForwarding(
ecmpHelper.resolveNextHops(ensemble->getProgrammedState(), kEcmpWidth),
kEcmpWidth);
ensemble->applyNewState(ecmpRouteState);
auto cpuMac = ensemble->getPlatform()->getLocalMac();
std::atomic<bool> packetTxDone{false};
std::thread t([cpuMac, hwSwitch, &config, &packetTxDone]() {
const auto kSrcIp = folly::IPAddressV6("2620:0:1cfe:face:b00c::3");
const auto kDstIp = folly::IPAddressV6("2620:0:1cfe:face:b00c::4");
while (!packetTxDone) {
for (auto i = 0; i < 1'000; ++i) {
// Send packet
auto txPacket = utility::makeUDPTxPacket(
hwSwitch,
VlanID(config.vlanPorts[0].vlanID),
cpuMac,
cpuMac,
kSrcIp,
kDstIp,
8000,
8001);
hwSwitch->sendPacketSwitchedAsync(std::move(txPacket));
}
}
});
auto [pktsBefore, bytesBefore] =
getOutPktsAndBytes(ensemble.get(), PortID(portUsed));
auto timeBefore = std::chrono::steady_clock::now();
constexpr auto kBurnIntevalMs = 5000;
// Let the packet flood warm up
WallClockMs::Burn(kBurnIntevalMs);
auto [pktsAfter, bytesAfter] =
getOutPktsAndBytes(ensemble.get(), PortID(portUsed));
auto timeAfter = std::chrono::steady_clock::now();
packetTxDone = true;
t.join();
std::chrono::duration<double, std::milli> durationMillseconds =
timeAfter - timeBefore;
uint32_t pps = (static_cast<double>(pktsAfter - pktsBefore) /
durationMillseconds.count()) *
1000;
uint32_t bytesPerSec = (static_cast<double>(bytesAfter - bytesBefore) /
durationMillseconds.count()) *
1000;
if (FLAGS_json) {
folly::dynamic cpuTxRateJson = folly::dynamic::object;
cpuTxRateJson["cpu_tx_pps"] = pps;
cpuTxRateJson["cpu_tx_bytes_per_sec"] = bytesPerSec;
std::cout << toPrettyJson(cpuTxRateJson) << std::endl;
} else {
XLOG(INFO) << " Pkts before: " << pktsBefore << " Pkts after: " << pktsAfter
<< " interval ms: " << durationMillseconds.count()
<< " pps: " << pps << " bytes per sec: " << bytesPerSec;
}
}
} // namespace facebook::fboss
int main(int argc, char* argv[]) {
folly::init(&argc, &argv, true);
facebook::fboss::runTxSlowPathBenchmark();
return 0;
}
| 34.460177 | 80 | 0.678223 | bkoray |
d97784a53ebaad89cdbcc8c73ea7f1034b620173 | 483 | cpp | C++ | src/Files/main.cpp | bbkane/Sandbox | 848030da315045888fd8542ddee49b929fa2e64a | [
"Unlicense"
] | null | null | null | src/Files/main.cpp | bbkane/Sandbox | 848030da315045888fd8542ddee49b929fa2e64a | [
"Unlicense"
] | null | null | null | src/Files/main.cpp | bbkane/Sandbox | 848030da315045888fd8542ddee49b929fa2e64a | [
"Unlicense"
] | null | null | null | #include <fstream>
#include <iostream>
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef _WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
int main()
{
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf("The current working directory is\n %s\n", cCurrentPath);
} | 20.125 | 73 | 0.722567 | bbkane |
d979215a6c8f2f05746a09d0f4d5f6a81360e3db | 25,932 | cpp | C++ | src/Regard3DFeatures.cpp | RichardQZeng/Regard3D | 2822275259e9ca140b77b89c1edeccf72bc45f07 | [
"MIT"
] | 213 | 2015-06-14T03:29:16.000Z | 2022-03-25T17:42:43.000Z | src/Regard3DFeatures.cpp | RichardQZeng/Regard3D | 2822275259e9ca140b77b89c1edeccf72bc45f07 | [
"MIT"
] | 45 | 2015-10-25T16:59:24.000Z | 2022-02-08T22:44:52.000Z | src/Regard3DFeatures.cpp | RichardQZeng/Regard3D | 2822275259e9ca140b77b89c1edeccf72bc45f07 | [
"MIT"
] | 49 | 2015-07-02T05:28:15.000Z | 2022-01-23T06:37:31.000Z | /**
* Copyright (C) 2015 Roman Hiestand
*
* 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 "CommonIncludes.h"
#include "Regard3DFeatures.h"
#include <memory>
#include <boost/locale.hpp>
#if defined(R3D_HAVE_OPENMP)
# include <omp.h>
#endif
#if defined(R3D_HAVE_TBB) // && !defined(R3D_HAVE_OPENMP)
#define R3D_USE_TBB_THREADING 1
# include <tbb/tbb.h>
#endif
#undef R3D_USE_TBB_THREADING
#undef R3D_HAVE_TBB
#undef R3D_HAVE_OPENMP
#undef R3D_HAVE_VLFEAT
#if defined(R3D_HAVE_VLFEAT)
// VLFEAT
extern "C" {
#include "vlfeat/covdet.h"
#include "vlfeat/mser.h"
}
#endif
// LIOP (copied from VLFEAT)
extern "C" {
#include "vl_liop.h"
}
// OpenCV Includes
#include "opencv2/core/eigen.hpp" //To Convert Eigen matrix to cv matrix
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d.hpp"
// AKAZE
#include "AKAZE.h"
// Fast-AKAZE
#include "features2d_akaze2.hpp"
// OpenMVG
#include "features/tbmr/tbmr.hpp"
#include "openMVG/features/feature.hpp"
// Helper class for locking the AKAZE semaphore (based on wxMutexLocker)
class AKAZESemaLocker
{
public:
// lock the mutex in the ctor
AKAZESemaLocker()
: isOK_(false)
{
if(pAKAZESemaphore_ != NULL)
isOK_ = (pAKAZESemaphore_->Wait() == wxSEMA_NO_ERROR);
}
// returns true if mutex was successfully locked in ctor
bool IsOk() const
{
return isOK_;
}
// unlock the mutex in dtor
~AKAZESemaLocker()
{
if(IsOk() && pAKAZESemaphore_ != NULL)
pAKAZESemaphore_->Post();
}
// Initializes the semaphore with the amount of allowed simultaneous threads
static bool initialize(int count)
{
if(pAKAZESemaphore_ != NULL)
delete pAKAZESemaphore_;
pAKAZESemaphore_ = new wxSemaphore(count, 0);
if(pAKAZESemaphore_->IsOk())
return true;
delete pAKAZESemaphore_;
return false;
}
static void uninitialize()
{
if(pAKAZESemaphore_ != NULL)
delete pAKAZESemaphore_;
pAKAZESemaphore_ = NULL;
}
private:
// no assignment operator nor copy ctor
AKAZESemaLocker(const AKAZESemaLocker&);
AKAZESemaLocker& operator=(const AKAZESemaLocker&);
bool isOK_;
static wxSemaphore *pAKAZESemaphore_;
};
wxSemaphore *AKAZESemaLocker::pAKAZESemaphore_ = NULL;
Regard3DFeatures::R3DFParams::R3DFParams()
: threshold_(0.001), nFeatures_(20000), distRatio_(0.6),
computeHomographyMatrix_(true),
computeFundalmentalMatrix_(true), computeEssentialMatrix_(true)
{
keypointDetectorList_.push_back( std::string("Fast-AKAZE") );
//keypointDetectorList_.push_back( std::string("TBMR") );
}
Regard3DFeatures::R3DFParams::R3DFParams(const Regard3DFeatures::R3DFParams &o)
{
copy(o);
}
Regard3DFeatures::R3DFParams::~R3DFParams()
{
}
Regard3DFeatures::R3DFParams &Regard3DFeatures::R3DFParams::copy(const Regard3DFeatures::R3DFParams &o)
{
keypointDetectorList_ = o.keypointDetectorList_;
threshold_ = o.threshold_;
nFeatures_ = o.nFeatures_;
distRatio_ = o.distRatio_;
computeHomographyMatrix_ = o.computeHomographyMatrix_;
computeFundalmentalMatrix_ = o.computeFundalmentalMatrix_;
computeEssentialMatrix_ = o.computeEssentialMatrix_;
return *this;
}
Regard3DFeatures::R3DFParams & Regard3DFeatures::R3DFParams::operator=(const Regard3DFeatures::R3DFParams &o)
{
return copy(o);
}
Regard3DFeatures::Regard3DFeatures()
{
}
Regard3DFeatures::~Regard3DFeatures()
{
}
bool Regard3DFeatures::initAKAZESemaphore(int count)
{
return AKAZESemaLocker::initialize(count);
}
void Regard3DFeatures::uninitializeAKAZESemaphore()
{
AKAZESemaLocker::uninitialize();
}
std::vector<std::string> Regard3DFeatures::getKeypointDetectors()
{
std::vector<std::string> ret;
ret.push_back( std::string( "AKAZE" ) ); // Own
ret.push_back( std::string( "Fast-AKAZE" ) ); // Own
ret.push_back( std::string( "MSER" ) ); // OpenCV
ret.push_back( std::string( "ORB" ) ); // OpenCV
ret.push_back( std::string( "BRISK" ) ); // OpenCV
ret.push_back( std::string( "GFTT" ) ); // OpenCV
#if defined(R3D_HAVE_VLFEAT)
ret.push_back( std::string( "DOG" ) ); // VLFEAT
#endif
return ret;
}
std::vector<std::string> Regard3DFeatures::getFeatureExtractors()
{
std::vector<std::string> ret;
ret.push_back( std::string( "LIOP" ) );
return ret;
}
void Regard3DFeatures::detectAndExtract(const openMVG::image::Image<float> &img,
Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs,
const Regard3DFeatures::R3DFParams ¶ms)
{
std::vector< cv::KeyPoint > vec_keypoints;
// Iterate over all keypoint detectors
std::vector<std::string>::const_iterator iter = params.keypointDetectorList_.begin();
for(;iter != params.keypointDetectorList_.end(); iter++)
{
std::string keypointDetector = *iter;
vec_keypoints.clear();
detectKeypoints(img, vec_keypoints, keypointDetector, params);
float kpSizeFactor = getKpSizeFactor(keypointDetector);
extractLIOPFeatures(img, vec_keypoints, kpSizeFactor, feats, descs);
}
/*
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
cv::Mat img_uchar;
cvimg.convertTo(img_uchar, CV_8U, 255.0, 0);
std::vector<openMVG::features::AffinePointFeature> features;
openMVG::image::Image<unsigned char> imaChar;
imaChar = Eigen::Map<openMVG::image::Image<unsigned char>::Base>(img_uchar.ptr<unsigned char>(0), img_uchar.rows, img_uchar.cols);
bool bUpRight = false;
using namespace openMVG::features;
std::unique_ptr<Image_describer> image_describer;
image_describer.reset(new AKAZE_Image_describer
(AKAZE_Image_describer::Params(AKAZE::Params(), AKAZE_LIOP), !bUpRight));
image_describer->Set_configuration_preset(EDESCRIBER_PRESET::HIGH_PRESET);
// Compute features and descriptors
std::unique_ptr<Regions> regions;
image_describer->Describe(imaChar, regions, nullptr);
*/
}
void Regard3DFeatures::detectAndExtract_NLOPT(const openMVG::image::Image<unsigned char> &img,
Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs, double kpSizeFactorIn)
{
std::vector< cv::KeyPoint > vec_keypoints;
Regard3DFeatures::R3DFParams params;
params.nFeatures_ = 10000;
params.threshold_ = 0.0007;
std::string keypointDetector("AKAZE");
vec_keypoints.clear();
// detectKeypoints(img, vec_keypoints, keypointDetector, params);
// extractLIOPFeatures(img, vec_keypoints, kpSizeFactorIn, feats, descs);
}
/**
* Detect keypoints using MSER from OpenCV and create LIOP descriptors.
*
* Make sure DescriptorR3D is set to 144 floats.
*/
void Regard3DFeatures::detectAndExtractVLFEAT_MSER_LIOP(const openMVG::image::Image<unsigned char> &img,
Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs)
{
// Convert image to OpenCV data
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
std::vector< cv::KeyPoint > vec_keypoints;
cv::Mat m_desc;
// cv::Ptr<cv::FeatureDetector> fd(cv::FeatureDetector::create(std::string("MSER")));
int nrPixels = img.Width() * img.Height();
int maxArea = static_cast<int>(nrPixels * 0.75);
/*
fd->setInt("delta", 5);
fd->setInt("minArea", 3);
fd->setInt("maxArea", maxArea);
fd->setDouble("maxVariation", 0.25);
fd->setDouble("minDiversity", 0.2);
fd->detect(cvimg, vec_keypoints);
*/
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Rect> bboxes;
cv::Ptr<cv::MSER> mser = cv::MSER::create(); //(5, 3, maxArea, 0.25, 0.2);
mser->detectRegions(cvimg, contours, bboxes);
double expandPatchFactor = 2.0; // This expands the extracted patch around the found MSER. Seems to help...
int patchResolution = 20;
vl_size patchSize = 2*patchResolution + 1;
std::vector<float> patch(patchSize * patchSize);
// Prepare LIOP descriptor
VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize);
vl_size dimension = r3d_vl_liopdesc_get_dimension(liop);
assert(dimension == DescriptorR3D::static_size); // Make sure descriptor sizes match
std::vector<float> desc(dimension);
DescriptorR3D descriptor;
for(size_t i = 0; i < contours.size(); i++)
{
// Find enclosing rectangle for all points in the contour
const std::vector<cv::Point> &curContour = contours[i];
int minx = img.Width() - 1, maxx = 0;
int miny = img.Height() - 1, maxy = 0;
for(size_t j = 0; j < curContour.size(); j++)
{
int curX = curContour[j].x;
int curY = curContour[j].y;
minx = std::min(minx, curX);
maxx = std::max(maxx, curX);
miny = std::min(miny, curY);
maxy = std::max(maxy, curY);
}
if(expandPatchFactor > 0)
{
int minxnew = static_cast<int>( ((1.0 - expandPatchFactor)*maxx + (1.0 + expandPatchFactor)*minx ) / 2.0 );
int maxxnew = static_cast<int>( ((1.0 + expandPatchFactor)*maxx + (1.0 - expandPatchFactor)*minx ) / 2.0 );
int minynew = static_cast<int>( ((1.0 - expandPatchFactor)*maxy + (1.0 + expandPatchFactor)*miny ) / 2.0 );
int maxynew = static_cast<int>( ((1.0 + expandPatchFactor)*maxy + (1.0 - expandPatchFactor)*miny ) / 2.0 );
minx = minxnew;
maxx = maxxnew;
miny = minynew;
maxy = maxynew;
}
// Extract patch from image
int x = minx, y = miny;
int width = maxx - minx + 1, height = maxy - miny + 1;
if(x >= 0
&& y >= 0
&& (x + width) < cvimg.cols
&& (y + height) < cvimg.rows
&& width > 2
&& height > 2)
{
cv::Rect keyPointRect(x, y, width, height);
cv::Mat patch(cvimg, keyPointRect);
int matType = patch.type();
cv::Mat patchF_tmp, patchF;
patch.convertTo(patchF_tmp, CV_32F);
cv::resize(patchF_tmp, patchF, cv::Size(patchSize, patchSize));
float *patchPtr = NULL;
std::vector<float> patchVec;
if(patch.isContinuous())
{
patchPtr = patchF.ptr<float>(0);
}
else
{
patchVec.resize(patchSize*patchSize);
for(int i = 0; i < patchSize; i++)
{
float *rowPtr = patchF.ptr<float>(i);
for(int j = 0; j < patchSize; j++)
patchVec[i * patchSize + j] = *(rowPtr++);
}
patchPtr = &(patchVec[0]);
}
r3d_vl_liopdesc_process(liop, &(desc[0]), patchPtr);
// Convert to OpenMVG keypoint and descriptor
openMVG::features::SIOPointFeature fp;
fp.x() = minx + (width/2);
fp.y() = miny + (height/2);
fp.scale() = std::sqrt(static_cast<float>(width*width + height*height)) / 2.0f;
fp.orientation() = 0;
for(int j = 0; j < dimension; j++)
descriptor[j] = desc[j];
descs.push_back(descriptor);
feats.push_back(fp);
}
}
/*
for(std::vector< cv::KeyPoint >::const_iterator i_keypoint = vec_keypoints.begin();
i_keypoint != vec_keypoints.end(); ++i_keypoint)
{
const cv::KeyPoint &kp = *(i_keypoint);
// int x = static_cast<int>(kp.pt.x + 0.5f) - patchResolution;
// int y = static_cast<int>(kp.pt.y + 0.5f) - patchResolution;
int keypointSize = static_cast<int>(kp.size + 0.5f); // Although kp.size is diameter, use it as radius for extracting the patch for LIOP
int x = static_cast<int>(kp.pt.x + 0.5f) - keypointSize;
int y = static_cast<int>(kp.pt.y + 0.5f) - keypointSize;
//int width = patchSize, height = patchSize;
int width = 2*keypointSize + 1, height = 2*keypointSize+1;
if(x >= 0
&& y >= 0
&& (x + width) < cvimg.cols
&& (y + height) < cvimg.rows
&& keypointSize > 2)
{
cv::Rect keyPointRect(x, y, width, height);
cv::Mat patch(cvimg, keyPointRect);
int matType = patch.type();
cv::Mat patchF_tmp, patchF;
patch.convertTo(patchF_tmp, CV_32F);
cv::resize(patchF_tmp, patchF, cv::Size(patchSize, patchSize));
float *patchPtr = NULL;
std::vector<float> patchVec;
if(patch.isContinuous())
{
patchPtr = patchF.ptr<float>(0);
}
else
{
patchVec.resize(patchSize*patchSize);
for(int i = 0; i < patchSize; i++)
{
float *rowPtr = patchF.ptr<float>(i);
for(int j = 0; j < patchSize; j++)
patchVec[i * patchSize + j] = *(rowPtr++);
}
patchPtr = &(patchVec[0]);
}
vl_liopdesc_process(liop, &(desc[0]), patchPtr);
// Convert to OpenMVG keypoint and descriptor
openMVG::features::SIOPointFeature fp;
fp.x() = kp.pt.x;
fp.y() = kp.pt.y;
fp.scale() = kp.size/2.0f; // kp.size is diameter, convert to radius
fp.orientation() = kp.angle;
for(int j = 0; j < dimension; j++)
descriptor[j] = desc[j];
descs.push_back(descriptor);
feats.push_back(fp);
}
}
*/
}
/**
* Detect keypoints using covariant feature detectors from VLFEAT and create LIOP descriptors.
*
* Make sure DescriptorR3D is set to 144 floats.
*/
void Regard3DFeatures::detectAndExtractVLFEAT_CoV_LIOP(const openMVG::image::Image<unsigned char> &img,
Regard3DFeatures::FeatsR3D &feats, Regard3DFeatures::DescsR3D &descs)
{
#if defined(R3D_HAVE_VLFEAT)
// Convert image float
openMVG::image::Image<float> imgFloat( img.GetMat().cast<float>() );
int w = img.Width(), h = img.Height();
int octaveResolution = 2;
double peakThreshold = 0.01;
double edgeThreshold = 10.0;
double boundaryMargin = 2.0;
int patchResolution = 20;
double patchRelativeExtent = 4.0;
double patchRelativeSmoothing = 1.2; //0.5;
bool doubleImage = false;
double smoothBeforeDetection = 0; //1.0;
// VL_COVDET_METHOD_DOG
// VL_COVDET_METHOD_MULTISCALE_HARRIS
VlCovDet * covdet = vl_covdet_new(VL_COVDET_METHOD_DOG);
vl_covdet_set_first_octave(covdet, doubleImage ? -1 : 0);
vl_covdet_set_octave_resolution(covdet, octaveResolution);
vl_covdet_set_peak_threshold(covdet, peakThreshold);
vl_covdet_set_edge_threshold(covdet, edgeThreshold);
// Smooth image
if(smoothBeforeDetection > 0)
vl_imsmooth_f(imgFloat.data(), w, imgFloat.data(), w, h, w,
smoothBeforeDetection, smoothBeforeDetection);
// process the image and run the detector
vl_covdet_put_image(covdet, imgFloat.data(), w, h);
vl_covdet_detect(covdet);
// drop features on the margin
vl_covdet_drop_features_outside(covdet, boundaryMargin);
// compute the affine shape of the features
vl_covdet_extract_affine_shape(covdet);
// compute the orientation of the features
// vl_covdet_extract_orientations(covdet);
// get feature frames back
vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
VlCovDetFeature const *feature = reinterpret_cast<VlCovDetFeature const *>(vl_covdet_get_features(covdet));
// get normalized feature appearance patches
vl_size patchSize = 2*patchResolution + 1;
std::vector<float> patch(patchSize * patchSize);
// Prepare LIOP descriptor
VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize);
vl_size dimension = r3d_vl_liopdesc_get_dimension(liop);
assert(dimension == DescriptorR3D::static_size); // Make sure descriptor sizes match
std::vector<float> desc(dimension);
DescriptorR3D descriptor;
for (int i = 0 ; i < numFeatures ; i++)
{
vl_covdet_extract_patch_for_frame(covdet,
&(patch[0]),
patchResolution,
patchRelativeExtent,
patchRelativeSmoothing,
feature[i].frame);
/*
vl_size numOrientations = 0;
VlCovDetFeatureOrientation *featOrient = vl_covdet_extract_orientations_for_frame(covdet,
&numOrientations, feature[i].frame);
double angle1 = featOrient->angle;
// double angle2 = std::atan2(feature[i].frame.a11, feature[i].frame.a12);
// double angle3 = std::atan2(feature[i].frame.a21, feature[i].frame.a22);
double angle2 = std::atan2(feature[i].frame.a11, feature[i].frame.a21);
double angle3 = std::atan2(feature[i].frame.a12, feature[i].frame.a22);
**/
double scale = 0;
{
double a11 = feature[i].frame.a11;
double a12 = feature[i].frame.a12;
double a21 = feature[i].frame.a21;
double a22 = feature[i].frame.a22;
double a = std::sqrt(a11*a11 + a21*a21);
double b = std::sqrt(a21*a21 + a22*a22);
scale = std::sqrt(a*a + b*b);
}
// Calculate LIOP descriptor
r3d_vl_liopdesc_process(liop, &(desc[0]), &(patch[0]));
// Convert to OpenMVG keypoint and descriptor
openMVG::features::SIOPointFeature fp;
fp.x() = feature[i].frame.x;
fp.y() = feature[i].frame.y;
fp.scale() = static_cast<float>(scale);
fp.orientation() = 0.0f; // TODO
//siftDescToFloat(descr, descriptor, bRootSift);
for(int j = 0; j < dimension; j++)
descriptor[j] = desc[j];
descs.push_back(descriptor);
feats.push_back(fp);
}
// Clean up
r3d_vl_liopdesc_delete(liop);
vl_covdet_delete(covdet);
#endif
}
void Regard3DFeatures::detectKeypoints(const openMVG::image::Image<float> &img,
std::vector< cv::KeyPoint > &vec_keypoints, const std::string &fdname,
const Regard3DFeatures::R3DFParams ¶ms)
{
if(fdname == std::string("AKAZE"))
{
AKAZESemaLocker akazeLocker; // Only allow one thread in this area
// Convert image to OpenCV data
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
cv::Ptr<cv::FeatureDetector> akazeDetector(cv::AKAZE::create(cv::AKAZE::DESCRIPTOR_MLDB,
0, 3, params.threshold_, 4, 4, cv::KAZE::DIFF_PM_G2));
akazeDetector->detect(cvimg, vec_keypoints);
}
else if(fdname == std::string("Fast-AKAZE"))
{
AKAZESemaLocker akazeLocker; // Only allow one thread in this area
// Convert image to OpenCV data
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
// cv::Mat img_32;
// cvimg.convertTo(img_32, CV_32F, 1.0/255.0, 0); // Convert to float, value range 0..1
cv::Ptr<cv::AKAZE2> fd = cv::AKAZE2::create();
fd->setThreshold(params.threshold_);
fd->detect(cvimg, vec_keypoints);
for(int i = 0; i < static_cast<int>(vec_keypoints.size()); i++)
{
// Convert from radians to degrees
(vec_keypoints[i].angle) *= 180.0 / CV_PI;
vec_keypoints[i].angle += 90.0f;
while(vec_keypoints[i].angle < 0)
vec_keypoints[i].angle += 360.0f;
while(vec_keypoints[i].angle > 360.0f)
vec_keypoints[i].angle -= 360.0f;
}
}
else if(fdname == std::string("DOG")) // VLFEAT
{
}
else if(fdname == std::string( "TBMR" ))
{
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
cv::Mat img_uchar;
cvimg.convertTo(img_uchar, CV_8U, 255.0, 0);
std::vector<openMVG::features::AffinePointFeature> features;
openMVG::image::Image<unsigned char> imaChar;
imaChar = Eigen::Map<openMVG::image::Image<unsigned char>::Base>(img_uchar.ptr<unsigned char>(0), img_uchar.rows, img_uchar.cols);
openMVG::features::tbmr::Extract_tbmr(imaChar, features);
vec_keypoints.resize(features.size());
for(size_t i = 0; i < features.size(); i++)
{
const auto &f = features[i];
vec_keypoints[i].pt.x = f.coords().x();
vec_keypoints[i].pt.y = f.coords().y();
vec_keypoints[i].size = std::sqrt(f.l1()*f.l1() + f.l2()*f.l2());
vec_keypoints[i].angle = 180.0 * f.orientation() / M_PI;
}
}
else // OpenCV
{
// Convert image to OpenCV data
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
// Convert string to C locale
// std::string fdname_cloc = boost::locale::conv::from_utf(fdname, "C");
//cv::Ptr<cv::FeatureDetector> fd(cv::FeatureDetector::create(fdname));
cv::Ptr<cv::FeatureDetector> fd;
//assert(!fd.empty());
if(fdname == std::string( "MSER" ))
{
fd = cv::MSER::create();
/*int nrPixels = img.Width() * img.Height();
int maxArea = static_cast<int>(nrPixels * 0.75);
fd->setInt("delta", 5);
fd->setInt("minArea", 3);
fd->setInt("maxArea", maxArea);
fd->setDouble("maxVariation", 0.25);
fd->setDouble("minDiversity", 0.2);*/
}
else if(fdname == std::string( "ORB" ))
{
// fd->setInt("nFeatures", params.nFeatures_);
fd = cv::ORB::create(params.nFeatures_);
}
else if(fdname == std::string( "BRISK" ))
{
// fd->setInt("thres", static_cast<int>(params.threshold_));
fd = cv::BRISK::create();
}
else if(fdname == std::string( "GFTT" ))
{
//fd->setInt("nfeatures", params.nFeatures_);
fd = cv::GFTTDetector::create(params.nFeatures_);
}
// fd->setDouble("edgeThreshold", 0.01); // for SIFT
fd->detect(cvimg, vec_keypoints);
}
}
/**
* Return the factor from keypoint size to feature size.
*
* Those factors have been determined with nlopt.
*/
float Regard3DFeatures::getKpSizeFactor(const std::string &fdname)
{
float retVal = 1.0f;
if(fdname == std::string("AKAZE"))
retVal = 8.0f;
if(fdname == std::string("Fast-AKAZE"))
retVal = 8.0f;
else if(fdname == std::string("DOG"))
retVal = 0.25f;
else if(fdname == std::string( "MSER" ))
retVal = 0.08;
else if(fdname == std::string( "ORB" ))
retVal = 0.025f;
else if(fdname == std::string( "BRISK" ))
retVal = 0.15f;
else if(fdname == std::string( "GFTT" ))
retVal = 0.13f;
else if(fdname == std::string( "HARRIS" ))
retVal = 0.25f;
else if(fdname == std::string( "SimpleBlob" ))
retVal = 1.0f; // No working parameters found
else if(fdname == std::string("TBMR"))
retVal = 1.0f;
return retVal;
}
void Regard3DFeatures::extractLIOPFeatures(const openMVG::image::Image<float> &img,
std::vector< cv::KeyPoint > &vec_keypoints, float kpSizeFactor,
FeatsR3D &feats, DescsR3D &descs)
{
// Convert image to OpenCV data
cv::Mat cvimg;
cv::eigen2cv(img.GetMat(), cvimg);
const int patchResolution = 20;
const double patchRelativeExtent = 4.0;
const double patchRelativeSmoothing = 1.2;
vl_size patchSize = 2*patchResolution + 1;
#if defined(R3D_USE_TBB_THREADING)
tbb::mutex critSectionMutex;
tbb::parallel_for(tbb::blocked_range<size_t>(0, vec_keypoints.size()),
[=, &critSectionMutex, &vec_keypoints, &descs, &feats](const tbb::blocked_range<size_t>& r) // Use lambda notation
#else
#if defined(R3D_HAVE_OPENMP)
#pragma omp parallel
#endif
#endif
{
// Initialisation of (in OpenMP or TBB case: per-thread) variables/structures
std::vector<float> patchvec(patchSize * patchSize);
// Prepare LIOP descriptor
VlLiopDesc * liop = r3d_vl_liopdesc_new_basic((vl_size)patchSize);
vl_size dimension = r3d_vl_liopdesc_get_dimension(liop);
assert(dimension == DescriptorR3D::static_size); // Must be equal to the size of DescriptorR3D
std::vector<float> desc(dimension);
DescriptorR3D descriptor;
cv::Mat M(2, 3, CV_32F); // 2x3 matrix
// Prepare patch
cv::Mat patchcv;
patchcv.create(patchSize, patchSize, CV_32F);
#if defined(R3D_USE_TBB_THREADING)
for(size_t i = r.begin(); i != r.end(); ++i)
#else
#if defined(R3D_HAVE_OPENMP)
#pragma omp for schedule(static)
#endif
for (int i = 0 ; i < static_cast<int>(vec_keypoints.size()); i++)
#endif
{
const cv::KeyPoint &kp = vec_keypoints[i];
float x = kp.pt.x;
float y = kp.pt.y;
// LIOP is rotationally invariant, so angle is not improving much
float angle = -90.0f-kp.angle; // angle in degrees
float kpsize = kp.size; // diameter
float scale = kpsize / static_cast<float>(patchSize) * kpSizeFactor;
// Extract patch TODO: Detect corner case
/* cv::Mat M_rot, M, M_trans;
M_trans = cv::Mat::eye(3, 3, CV_64F); // Identity matrix: rows, columns, type
M_trans.at<double>(0, 2) = x - static_cast<double>(patchResolution);
M_trans.at<double>(1, 2) = y - static_cast<double>(patchResolution);
M_rot = cv::getRotationMatrix2D(cv::Point2f(x, y), angle, scale);
M_rot.resize(3, cv::Scalar(0)); // Set number of rows to 3 (-> 3x3 matrix)
M_rot.at<double>(2, 2) = 1.0;
M = M_rot * M_trans;
M.resize(2); // Reduce one row to 2x3 matrix
*/
float alpha = scale * std::cos( angle * CV_PI / 180.0f );
float beta = scale * std::sin( angle * CV_PI / 180.0f );
float trans_x = x - static_cast<float>(patchResolution);
float trans_y = y - static_cast<float>(patchResolution);
M.at<float>(0, 0) = alpha;
M.at<float>(0, 1) = beta;
M.at<float>(0, 2) = beta*trans_y + alpha*trans_x - beta*y + (1.0f - alpha)*x;
M.at<float>(1, 0) = -beta;
M.at<float>(1, 1) = alpha;
M.at<float>(1, 2) = alpha*trans_y - beta*trans_x + beta*x + (1.0f - alpha)*y;
// Extract patch, rotate and resize it to patchSize * patchSize
cv::warpAffine(cvimg, patchcv, M, cv::Size(patchSize, patchSize),
cv::INTER_LINEAR | cv::WARP_INVERSE_MAP);
// Gauss filter for smoothing (suggested by LIOP paper)
if(patchRelativeSmoothing > 1.0)
cv::GaussianBlur(patchcv, patchcv, cv::Size(0, 0), patchRelativeSmoothing);
float *patchPtr = NULL;
if(patchcv.isContinuous())
{
patchPtr = patchcv.ptr<float>(0);
}
else
{
patchvec.resize(patchSize*patchSize);
for(int i = 0; i < patchSize; i++)
{
float *rowPtr = patchcv.ptr<float>(i);
for(int j = 0; j < patchSize; j++)
patchvec[i * patchSize + j] = *(rowPtr++);
}
patchPtr = &(patchvec[0]);
}
// Calculate LIOP descriptor
r3d_vl_liopdesc_process(liop, &(desc[0]), patchPtr);
{
// Convert to OpenMVG keypoint and descriptor
openMVG::features::SIOPointFeature fp;
fp.x() = kp.pt.x;
fp.y() = kp.pt.y;
fp.scale() = kp.size/2.0f; // kp.size is diameter, convert to radius
fp.orientation() = kp.angle;
for(int j = 0; j < dimension; j++)
descriptor[j] = desc[j];
#if defined(R3D_USE_TBB_THREADING)
#elif defined(USE_OPENMP)
#pragma omp critical
#endif
{
#if defined(R3D_USE_TBB_THREADING)
tbb::mutex::scoped_lock lock(critSectionMutex);
#endif
descs.push_back(descriptor);
feats.push_back(fp);
}
}
}
r3d_vl_liopdesc_delete(liop);
}
#if defined(R3D_USE_TBB_THREADING)
);
#endif
// Clean up
//r3d_vl_liopdesc_delete(liop);
}
| 30.048667 | 138 | 0.691771 | RichardQZeng |
d97b756f548ad29a198f026ccfad34012c3c7b28 | 43,552 | cpp | C++ | lib/wx/c_src/gen/wxe_events.cpp | jjhoo/otp | 808eccc796a05caf2f2a244db385df83c2680b9f | [
"Apache-2.0"
] | 8,238 | 2015-01-02T01:05:29.000Z | 2022-03-30T04:09:46.000Z | lib/wx/c_src/gen/wxe_events.cpp | jjhoo/otp | 808eccc796a05caf2f2a244db385df83c2680b9f | [
"Apache-2.0"
] | 2,988 | 2015-01-02T11:40:59.000Z | 2022-03-31T18:29:54.000Z | lib/wx/c_src/gen/wxe_events.cpp | jjhoo/otp | 808eccc796a05caf2f2a244db385df83c2680b9f | [
"Apache-2.0"
] | 2,459 | 2015-01-01T18:54:55.000Z | 2022-03-31T08:58:25.000Z | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2008-2021. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/***** This file is generated do not edit ****/
#include <wx/wx.h>
#include "../wxe_impl.h"
#include "wxe_macros.h"
#include "../wxe_events.h"
#include "../wxe_return.h"
WX_DECLARE_HASH_MAP(int, wxeEtype*, wxIntegerHash, wxIntegerEqual, wxeETmap );
wxeETmap etmap;
int wxeEventTypeFromAtom(ERL_NIF_TERM etype_atom) {
wxeETmap::iterator it;
for(it = etmap.begin(); it != etmap.end(); ++it) {
wxeEtype * value = it->second;
if(enif_is_identical(value->evName, etype_atom)) {
if(it->first > wxEVT_USER_FIRST) {
return it->first - wxEVT_USER_FIRST;
} else {
return it->first;
}
}
}
return -1;
}
void initEventTable()
{
wxe_evInfo event_types[] =
{
{wxEVT_NULL, 0, "null", "wxWXENullEvent", "wxWXENull"},
{wxEVT_COMMAND_BUTTON_CLICKED, 168, "command_button_clicked", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_CHECKBOX_CLICKED, 168, "command_checkbox_clicked", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_CHOICE_SELECTED, 168, "command_choice_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_LISTBOX_SELECTED, 168, "command_listbox_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, 168, "command_listbox_doubleclicked", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_TEXT_UPDATED, 168, "command_text_updated", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_TEXT_ENTER, 168, "command_text_enter", "wxCommandEvent", "wxCommand"},
{wxEVT_TEXT_MAXLEN, 168, "text_maxlen", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_MENU_SELECTED, 168, "command_menu_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_SLIDER_UPDATED, 168, "command_slider_updated", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_RADIOBOX_SELECTED, 168, "command_radiobox_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_RADIOBUTTON_SELECTED, 168, "command_radiobutton_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_SCROLLBAR_UPDATED, 168, "command_scrollbar_updated", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_VLBOX_SELECTED, 168, "command_vlbox_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_COMBOBOX_SELECTED, 168, "command_combobox_selected", "wxCommandEvent", "wxCommand"},
{wxEVT_COMBOBOX_DROPDOWN, 168, "combobox_dropdown", "wxCommandEvent", "wxCommand"},
{wxEVT_COMBOBOX_CLOSEUP, 168, "combobox_closeup", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_TOOL_RCLICKED, 168, "command_tool_rclicked", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_TOOL_ENTER, 168, "command_tool_enter", "wxCommandEvent", "wxCommand"},
{wxEVT_TOOL_DROPDOWN, 168, "tool_dropdown", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, 168, "command_checklistbox_toggled", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, 168, "command_togglebutton_clicked", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_LEFT_CLICK, 168, "command_left_click", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_LEFT_DCLICK, 168, "command_left_dclick", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_RIGHT_CLICK, 168, "command_right_click", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_SET_FOCUS, 168, "command_set_focus", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_KILL_FOCUS, 168, "command_kill_focus", "wxCommandEvent", "wxCommand"},
{wxEVT_COMMAND_ENTER, 168, "command_enter", "wxCommandEvent", "wxCommand"},
#if wxCHECK_VERSION(3,1,0)
{wxEVT_NOTIFICATION_MESSAGE_CLICK, 168, "notification_message_click", "wxCommandEvent", "wxCommand"},
#endif
#if wxCHECK_VERSION(3,1,0)
{wxEVT_NOTIFICATION_MESSAGE_DISMISSED, 168, "notification_message_dismissed", "wxCommandEvent", "wxCommand"},
#endif
#if wxCHECK_VERSION(3,1,0)
{wxEVT_NOTIFICATION_MESSAGE_ACTION, 168, "notification_message_action", "wxCommandEvent", "wxCommand"},
#endif
{wxEVT_SCROLL_TOP, 169, "scroll_top", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_BOTTOM, 169, "scroll_bottom", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_LINEUP, 169, "scroll_lineup", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_LINEDOWN, 169, "scroll_linedown", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_PAGEUP, 169, "scroll_pageup", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_PAGEDOWN, 169, "scroll_pagedown", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_THUMBTRACK, 169, "scroll_thumbtrack", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_THUMBRELEASE, 169, "scroll_thumbrelease", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLL_CHANGED, 169, "scroll_changed", "wxScrollEvent", "wxScroll"},
{wxEVT_SCROLLWIN_TOP, 170, "scrollwin_top", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_BOTTOM, 170, "scrollwin_bottom", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_LINEUP, 170, "scrollwin_lineup", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_LINEDOWN, 170, "scrollwin_linedown", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_PAGEUP, 170, "scrollwin_pageup", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_PAGEDOWN, 170, "scrollwin_pagedown", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_THUMBTRACK, 170, "scrollwin_thumbtrack", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_SCROLLWIN_THUMBRELEASE, 170, "scrollwin_thumbrelease", "wxScrollWinEvent", "wxScrollWin"},
{wxEVT_LEFT_DOWN, 171, "left_down", "wxMouseEvent", "wxMouse"},
{wxEVT_LEFT_UP, 171, "left_up", "wxMouseEvent", "wxMouse"},
{wxEVT_MIDDLE_DOWN, 171, "middle_down", "wxMouseEvent", "wxMouse"},
{wxEVT_MIDDLE_UP, 171, "middle_up", "wxMouseEvent", "wxMouse"},
{wxEVT_RIGHT_DOWN, 171, "right_down", "wxMouseEvent", "wxMouse"},
{wxEVT_RIGHT_UP, 171, "right_up", "wxMouseEvent", "wxMouse"},
{wxEVT_MOTION, 171, "motion", "wxMouseEvent", "wxMouse"},
{wxEVT_ENTER_WINDOW, 171, "enter_window", "wxMouseEvent", "wxMouse"},
{wxEVT_LEAVE_WINDOW, 171, "leave_window", "wxMouseEvent", "wxMouse"},
{wxEVT_LEFT_DCLICK, 171, "left_dclick", "wxMouseEvent", "wxMouse"},
{wxEVT_MIDDLE_DCLICK, 171, "middle_dclick", "wxMouseEvent", "wxMouse"},
{wxEVT_RIGHT_DCLICK, 171, "right_dclick", "wxMouseEvent", "wxMouse"},
{wxEVT_MOUSEWHEEL, 171, "mousewheel", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX1_DOWN, 171, "aux1_down", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX1_UP, 171, "aux1_up", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX1_DCLICK, 171, "aux1_dclick", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX2_DOWN, 171, "aux2_down", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX2_UP, 171, "aux2_up", "wxMouseEvent", "wxMouse"},
{wxEVT_AUX2_DCLICK, 171, "aux2_dclick", "wxMouseEvent", "wxMouse"},
{wxEVT_SET_CURSOR, 172, "set_cursor", "wxSetCursorEvent", "wxSetCursor"},
{wxEVT_CHAR, 173, "char", "wxKeyEvent", "wxKey"},
{wxEVT_CHAR_HOOK, 173, "char_hook", "wxKeyEvent", "wxKey"},
{wxEVT_KEY_DOWN, 173, "key_down", "wxKeyEvent", "wxKey"},
{wxEVT_KEY_UP, 173, "key_up", "wxKeyEvent", "wxKey"},
{wxEVT_SIZE, 174, "size", "wxSizeEvent", "wxSize"},
{wxEVT_MOVE, 175, "move", "wxMoveEvent", "wxMove"},
{wxEVT_PAINT, 176, "paint", "wxPaintEvent", "wxPaint"},
{wxEVT_ERASE_BACKGROUND, 177, "erase_background", "wxEraseEvent", "wxErase"},
{wxEVT_SET_FOCUS, 178, "set_focus", "wxFocusEvent", "wxFocus"},
{wxEVT_KILL_FOCUS, 178, "kill_focus", "wxFocusEvent", "wxFocus"},
{wxEVT_CHILD_FOCUS, 179, "child_focus", "wxChildFocusEvent", "wxChildFocus"},
{wxEVT_MENU_OPEN, 180, "menu_open", "wxMenuEvent", "wxMenu"},
{wxEVT_MENU_CLOSE, 180, "menu_close", "wxMenuEvent", "wxMenu"},
{wxEVT_MENU_HIGHLIGHT, 180, "menu_highlight", "wxMenuEvent", "wxMenu"},
{wxEVT_CLOSE_WINDOW, 181, "close_window", "wxCloseEvent", "wxClose"},
{wxEVT_END_SESSION, 181, "end_session", "wxCloseEvent", "wxClose"},
{wxEVT_QUERY_END_SESSION, 181, "query_end_session", "wxCloseEvent", "wxClose"},
{wxEVT_SHOW, 182, "show", "wxShowEvent", "wxShow"},
{wxEVT_ICONIZE, 183, "iconize", "wxIconizeEvent", "wxIconize"},
{wxEVT_MAXIMIZE, 184, "maximize", "wxMaximizeEvent", "wxMaximize"},
{wxEVT_JOY_BUTTON_DOWN, 185, "joy_button_down", "wxJoystickEvent", "wxJoystick"},
{wxEVT_JOY_BUTTON_UP, 185, "joy_button_up", "wxJoystickEvent", "wxJoystick"},
{wxEVT_JOY_MOVE, 185, "joy_move", "wxJoystickEvent", "wxJoystick"},
{wxEVT_JOY_ZMOVE, 185, "joy_zmove", "wxJoystickEvent", "wxJoystick"},
{wxEVT_UPDATE_UI, 186, "update_ui", "wxUpdateUIEvent", "wxUpdateUI"},
{wxEVT_SYS_COLOUR_CHANGED, 187, "sys_colour_changed", "wxSysColourChangedEvent", "wxSysColourChanged"},
{wxEVT_MOUSE_CAPTURE_CHANGED, 188, "mouse_capture_changed", "wxMouseCaptureChangedEvent", "wxMouseCaptureChanged"},
{wxEVT_DISPLAY_CHANGED, 189, "display_changed", "wxDisplayChangedEvent", "wxDisplayChanged"},
{wxEVT_PALETTE_CHANGED, 190, "palette_changed", "wxPaletteChangedEvent", "wxPaletteChanged"},
{wxEVT_QUERY_NEW_PALETTE, 191, "query_new_palette", "wxQueryNewPaletteEvent", "wxQueryNewPalette"},
{wxEVT_NAVIGATION_KEY, 192, "navigation_key", "wxNavigationKeyEvent", "wxNavigationKey"},
{wxEVT_CREATE, 193, "create", "wxWindowCreateEvent", "wxWindowCreate"},
{wxEVT_DESTROY, 194, "destroy", "wxWindowDestroyEvent", "wxWindowDestroy"},
{wxEVT_HELP, 195, "help", "wxHelpEvent", "wxHelp"},
{wxEVT_DETAILED_HELP, 195, "detailed_help", "wxHelpEvent", "wxHelp"},
{wxEVT_CONTEXT_MENU, 196, "context_menu", "wxContextMenuEvent", "wxContextMenu"},
{wxEVT_IDLE, 197, "idle", "wxIdleEvent", "wxIdle"},
{wxEVT_GRID_CELL_LEFT_CLICK, 198, "grid_cell_left_click", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_CELL_RIGHT_CLICK, 198, "grid_cell_right_click", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_CELL_LEFT_DCLICK, 198, "grid_cell_left_dclick", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_CELL_RIGHT_DCLICK, 198, "grid_cell_right_dclick", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_LABEL_LEFT_CLICK, 198, "grid_label_left_click", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_LABEL_RIGHT_CLICK, 198, "grid_label_right_click", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_LABEL_LEFT_DCLICK, 198, "grid_label_left_dclick", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_LABEL_RIGHT_DCLICK, 198, "grid_label_right_dclick", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_ROW_SIZE, 198, "grid_row_size", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_COL_SIZE, 198, "grid_col_size", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_RANGE_SELECT, 198, "grid_range_select", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_CELL_CHANGED, 198, "grid_cell_changed", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_SELECT_CELL, 198, "grid_select_cell", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_EDITOR_SHOWN, 198, "grid_editor_shown", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_EDITOR_HIDDEN, 198, "grid_editor_hidden", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_EDITOR_CREATED, 198, "grid_editor_created", "wxGridEvent", "wxGrid"},
{wxEVT_GRID_CELL_BEGIN_DRAG, 198, "grid_cell_begin_drag", "wxGridEvent", "wxGrid"},
{wxEVT_SASH_DRAGGED, 200, "sash_dragged", "wxSashEvent", "wxSash"},
{wxEVT_COMMAND_LIST_BEGIN_DRAG, 201, "command_list_begin_drag", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_BEGIN_RDRAG, 201, "command_list_begin_rdrag", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, 201, "command_list_begin_label_edit", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_END_LABEL_EDIT, 201, "command_list_end_label_edit", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_DELETE_ITEM, 201, "command_list_delete_item", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS, 201, "command_list_delete_all_items", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_KEY_DOWN, 201, "command_list_key_down", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_INSERT_ITEM, 201, "command_list_insert_item", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_COL_CLICK, 201, "command_list_col_click", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_COL_RIGHT_CLICK, 201, "command_list_col_right_click", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_COL_BEGIN_DRAG, 201, "command_list_col_begin_drag", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_COL_DRAGGING, 201, "command_list_col_dragging", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_COL_END_DRAG, 201, "command_list_col_end_drag", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_SELECTED, 201, "command_list_item_selected", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_DESELECTED, 201, "command_list_item_deselected", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, 201, "command_list_item_right_click", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK, 201, "command_list_item_middle_click", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_ACTIVATED, 201, "command_list_item_activated", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_ITEM_FOCUSED, 201, "command_list_item_focused", "wxListEvent", "wxList"},
{wxEVT_COMMAND_LIST_CACHE_HINT, 201, "command_list_cache_hint", "wxListEvent", "wxList"},
{wxEVT_DATE_CHANGED, 202, "date_changed", "wxDateEvent", "wxDate"},
{wxEVT_CALENDAR_SEL_CHANGED, 203, "calendar_sel_changed", "wxCalendarEvent", "wxCalendar"},
{wxEVT_CALENDAR_DAY_CHANGED, 203, "calendar_day_changed", "wxCalendarEvent", "wxCalendar"},
{wxEVT_CALENDAR_MONTH_CHANGED, 203, "calendar_month_changed", "wxCalendarEvent", "wxCalendar"},
{wxEVT_CALENDAR_YEAR_CHANGED, 203, "calendar_year_changed", "wxCalendarEvent", "wxCalendar"},
{wxEVT_CALENDAR_DOUBLECLICKED, 203, "calendar_doubleclicked", "wxCalendarEvent", "wxCalendar"},
{wxEVT_CALENDAR_WEEKDAY_CLICKED, 203, "calendar_weekday_clicked", "wxCalendarEvent", "wxCalendar"},
{wxEVT_COMMAND_FILEPICKER_CHANGED, 204, "command_filepicker_changed", "wxFileDirPickerEvent", "wxFileDirPicker"},
{wxEVT_COMMAND_DIRPICKER_CHANGED, 204, "command_dirpicker_changed", "wxFileDirPickerEvent", "wxFileDirPicker"},
{wxEVT_COMMAND_COLOURPICKER_CHANGED, 205, "command_colourpicker_changed", "wxColourPickerEvent", "wxColourPicker"},
{wxEVT_COMMAND_FONTPICKER_CHANGED, 206, "command_fontpicker_changed", "wxFontPickerEvent", "wxFontPicker"},
{wxEVT_STC_AUTOCOMP_CANCELLED, 207, "stc_autocomp_cancelled", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_AUTOCOMP_CHAR_DELETED, 207, "stc_autocomp_char_deleted", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_AUTOCOMP_SELECTION, 207, "stc_autocomp_selection", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_CALLTIP_CLICK, 207, "stc_calltip_click", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_CHANGE, 207, "stc_change", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_CHARADDED, 207, "stc_charadded", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_DO_DROP, 207, "stc_do_drop", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_DOUBLECLICK, 207, "stc_doubleclick", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_DRAG_OVER, 207, "stc_drag_over", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_DWELLEND, 207, "stc_dwellend", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_DWELLSTART, 207, "stc_dwellstart", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_HOTSPOT_CLICK, 207, "stc_hotspot_click", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_HOTSPOT_DCLICK, 207, "stc_hotspot_dclick", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_HOTSPOT_RELEASE_CLICK, 207, "stc_hotspot_release_click", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_INDICATOR_CLICK, 207, "stc_indicator_click", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_INDICATOR_RELEASE, 207, "stc_indicator_release", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_MACRORECORD, 207, "stc_macrorecord", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_MARGINCLICK, 207, "stc_marginclick", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_MODIFIED, 207, "stc_modified", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_NEEDSHOWN, 207, "stc_needshown", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_PAINTED, 207, "stc_painted", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_ROMODIFYATTEMPT, 207, "stc_romodifyattempt", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_SAVEPOINTLEFT, 207, "stc_savepointleft", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_SAVEPOINTREACHED, 207, "stc_savepointreached", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_START_DRAG, 207, "stc_start_drag", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_STYLENEEDED, 207, "stc_styleneeded", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_UPDATEUI, 207, "stc_updateui", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_USERLISTSELECTION, 207, "stc_userlistselection", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_STC_ZOOM, 207, "stc_zoom", "wxStyledTextEvent", "wxStyledText"},
{wxEVT_COMMAND_TREE_BEGIN_DRAG, 213, "command_tree_begin_drag", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_BEGIN_RDRAG, 213, "command_tree_begin_rdrag", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT, 213, "command_tree_begin_label_edit", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_END_LABEL_EDIT, 213, "command_tree_end_label_edit", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_DELETE_ITEM, 213, "command_tree_delete_item", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_GET_INFO, 213, "command_tree_get_info", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_SET_INFO, 213, "command_tree_set_info", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_EXPANDED, 213, "command_tree_item_expanded", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_EXPANDING, 213, "command_tree_item_expanding", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_COLLAPSED, 213, "command_tree_item_collapsed", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_COLLAPSING, 213, "command_tree_item_collapsing", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_SEL_CHANGED, 213, "command_tree_sel_changed", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_SEL_CHANGING, 213, "command_tree_sel_changing", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_KEY_DOWN, 213, "command_tree_key_down", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_ACTIVATED, 213, "command_tree_item_activated", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK, 213, "command_tree_item_right_click", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK, 213, "command_tree_item_middle_click", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_END_DRAG, 213, "command_tree_end_drag", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, 213, "command_tree_state_image_click", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, 213, "command_tree_item_gettooltip", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_TREE_ITEM_MENU, 213, "command_tree_item_menu", "wxTreeEvent", "wxTree"},
{wxEVT_DIRCTRL_SELECTIONCHANGED, 213, "dirctrl_selectionchanged", "wxTreeEvent", "wxTree"},
{wxEVT_DIRCTRL_FILEACTIVATED, 213, "dirctrl_fileactivated", "wxTreeEvent", "wxTree"},
{wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, 214, "command_notebook_page_changed", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING, 214, "command_notebook_page_changing", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_CHOICEBOOK_PAGE_CHANGED, 214, "choicebook_page_changed", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_CHOICEBOOK_PAGE_CHANGING, 214, "choicebook_page_changing", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_TREEBOOK_PAGE_CHANGED, 214, "treebook_page_changed", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_TREEBOOK_PAGE_CHANGING, 214, "treebook_page_changing", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_TOOLBOOK_PAGE_CHANGED, 214, "toolbook_page_changed", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_TOOLBOOK_PAGE_CHANGING, 214, "toolbook_page_changing", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_LISTBOOK_PAGE_CHANGED, 214, "listbook_page_changed", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_LISTBOOK_PAGE_CHANGING, 214, "listbook_page_changing", "wxBookCtrlEvent", "wxBookCtrl"},
{wxEVT_COMMAND_TEXT_COPY, 220, "command_text_copy", "wxClipboardTextEvent", "wxClipboardText"},
{wxEVT_COMMAND_TEXT_CUT, 220, "command_text_cut", "wxClipboardTextEvent", "wxClipboardText"},
{wxEVT_COMMAND_TEXT_PASTE, 220, "command_text_paste", "wxClipboardTextEvent", "wxClipboardText"},
{wxEVT_COMMAND_SPINCTRL_UPDATED, 221, "command_spinctrl_updated", "wxSpinEvent", "wxSpin"},
{wxEVT_SCROLL_LINEUP + wxEVT_USER_FIRST, 169, "spin_up", "wxSpinEvent", "wxSpin"},
{wxEVT_SCROLL_LINEDOWN + wxEVT_USER_FIRST, 169, "spin_down", "wxSpinEvent", "wxSpin"},
{wxEVT_SCROLL_THUMBTRACK + wxEVT_USER_FIRST, 169, "spin", "wxSpinEvent", "wxSpin"},
{wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED, 223, "command_splitter_sash_pos_changed", "wxSplitterEvent", "wxSplitter"},
{wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING, 223, "command_splitter_sash_pos_changing", "wxSplitterEvent", "wxSplitter"},
{wxEVT_COMMAND_SPLITTER_DOUBLECLICKED, 223, "command_splitter_doubleclicked", "wxSplitterEvent", "wxSplitter"},
{wxEVT_COMMAND_SPLITTER_UNSPLIT, 223, "command_splitter_unsplit", "wxSplitterEvent", "wxSplitter"},
{wxEVT_COMMAND_HTML_LINK_CLICKED, 225, "command_html_link_clicked", "wxHtmlLinkEvent", "wxHtmlLink"},
{wxEVT_HTML_CELL_CLICKED, 225, "html_cell_clicked", "wxHtmlLinkEvent", "wxHtmlLink"},
{wxEVT_HTML_CELL_HOVER, 225, "html_cell_hover", "wxHtmlLinkEvent", "wxHtmlLink"},
{wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE, 228, "command_auinotebook_page_close", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGED, 228, "command_auinotebook_page_changed", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_PAGE_CHANGING, 228, "command_auinotebook_page_changing", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_BUTTON, 228, "command_auinotebook_button", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_BEGIN_DRAG, 228, "command_auinotebook_begin_drag", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_END_DRAG, 228, "command_auinotebook_end_drag", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_DRAG_MOTION, 228, "command_auinotebook_drag_motion", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_ALLOW_DND, 228, "command_auinotebook_allow_dnd", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN, 228, "command_auinotebook_tab_middle_down", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_UP, 228, "command_auinotebook_tab_middle_up", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, 228, "command_auinotebook_tab_right_down", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_UP, 228, "command_auinotebook_tab_right_up", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSED, 228, "command_auinotebook_page_closed", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_DRAG_DONE, 228, "command_auinotebook_drag_done", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_COMMAND_AUINOTEBOOK_BG_DCLICK, 228, "command_auinotebook_bg_dclick", "wxAuiNotebookEvent", "wxAuiNotebook"},
{wxEVT_AUI_PANE_BUTTON, 229, "aui_pane_button", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_PANE_CLOSE, 229, "aui_pane_close", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_PANE_MAXIMIZE, 229, "aui_pane_maximize", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_PANE_RESTORE, 229, "aui_pane_restore", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_PANE_ACTIVATED, 229, "aui_pane_activated", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_RENDER, 229, "aui_render", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_AUI_FIND_MANAGER, 229, "aui_find_manager", "wxAuiManagerEvent", "wxAuiManager"},
{wxEVT_TASKBAR_MOVE, 232, "taskbar_move", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_LEFT_DOWN, 232, "taskbar_left_down", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_LEFT_UP, 232, "taskbar_left_up", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_RIGHT_DOWN, 232, "taskbar_right_down", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_RIGHT_UP, 232, "taskbar_right_up", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_LEFT_DCLICK, 232, "taskbar_left_dclick", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_TASKBAR_RIGHT_DCLICK, 232, "taskbar_right_dclick", "wxTaskBarIconEvent", "wxTaskBarIcon"},
{wxEVT_INIT_DIALOG, 233, "init_dialog", "wxInitDialogEvent", "wxInitDialog"},
{wxEVT_ACTIVATE, 235, "activate", "wxActivateEvent", "wxActivate"},
{wxEVT_ACTIVATE_APP, 235, "activate_app", "wxActivateEvent", "wxActivate"},
{wxEVT_HIBERNATE, 235, "hibernate", "wxActivateEvent", "wxActivate"},
{wxEVT_MOUSE_CAPTURE_LOST, 238, "mouse_capture_lost", "wxMouseCaptureLostEvent", "wxMouseCaptureLost"},
{wxEVT_DROP_FILES, 241, "drop_files", "wxDropFilesEvent", "wxDropFiles"},
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_NAVIGATING, 246, "webview_navigating", "wxWebViewEvent", "wxWebView"},
#endif
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_NAVIGATED, 246, "webview_navigated", "wxWebViewEvent", "wxWebView"},
#endif
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_LOADED, 246, "webview_loaded", "wxWebViewEvent", "wxWebView"},
#endif
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_ERROR, 246, "webview_error", "wxWebViewEvent", "wxWebView"},
#endif
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_NEWWINDOW, 246, "webview_newwindow", "wxWebViewEvent", "wxWebView"},
#endif
#if WXE_WEBVIEW
{wxEVT_WEBVIEW_TITLE_CHANGED, 246, "webview_title_changed", "wxWebViewEvent", "wxWebView"},
#endif
{-1, 0, "", "", ""}
};
ErlNifEnv *env = enif_alloc_env();
for(int i=0; event_types[i].ev_type != -1; i++) {
if(NULL == etmap[event_types[i].ev_type]) {
etmap[event_types[i].ev_type] =
new wxeEtype(env, &event_types[i]);
} else {
wxeEtype *prev = etmap[event_types[i].ev_type];
wxString msg(wxT("Duplicate event defs: "));
msg += wxString::FromAscii(event_types[i].ev_name);
msg += wxString::Format(wxT(" %d "), event_types[i].class_id);
msg += wxString::FromAscii(prev->evName);
msg += wxString::Format(wxT(" %d"), prev->cID);
send_msg("internal_error", &msg);
}
}
enif_free_env(env);
}
bool sendevent(wxEvent *event, wxeMemEnv *memenv)
{
int send_res ;
wxMBConvUTF32 UTFconverter;
wxeEtype *Etype = etmap[event->GetEventType()];
wxeEvtListener *cb = (wxeEvtListener *)event->m_callbackUserData;
WxeApp * app = (WxeApp *) wxTheApp;
if(!memenv) return 0;
wxeReturn rt = wxeReturn(memenv, cb->listener, false);
ERL_NIF_TERM ev_term;
switch(Etype->cID) {
case 168: {// wxCommandEvent
wxCommandEvent * ev = (wxCommandEvent *) event;
ev_term = enif_make_tuple5(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetString()),
rt.make_int(ev->GetInt()),
rt.make_int(ev->GetExtraLong()));
break;
}
case 169: {// wxScrollEvent or wxSpinEvent
if(event->IsKindOf(CLASSINFO(wxScrollEvent))) {
wxScrollEvent * ev = (wxScrollEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetPosition()),
rt.make_int(ev->GetOrientation()));
} else {
Etype = etmap[event->GetEventType() + wxEVT_USER_FIRST];
wxSpinEvent * ev = (wxSpinEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetPosition()));
}
break;
}
case 170: {// wxScrollWinEvent
wxScrollWinEvent * ev = (wxScrollWinEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetPosition()),
rt.make_int(ev->GetOrientation()));
break;
}
case 171: {// wxMouseEvent
wxMouseEvent * ev = (wxMouseEvent *) event;
ev_term = enif_make_tuple(rt.env,14,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetX()),
rt.make_int(ev->GetY()),
rt.make_bool(ev->LeftIsDown()),
rt.make_bool(ev->MiddleIsDown()),
rt.make_bool(ev->RightIsDown()),
rt.make_bool(ev->ControlDown()),
rt.make_bool(ev->ShiftDown()),
rt.make_bool(ev->AltDown()),
rt.make_bool(ev->MetaDown()),
rt.make_int(ev->GetWheelRotation()),
rt.make_int(ev->GetWheelDelta()),
rt.make_int(ev->GetLinesPerAction()));
break;
}
case 172: {// wxSetCursorEvent
wxSetCursorEvent * ev = (wxSetCursorEvent *) event;
const wxCursor * GetCursor = &ev->GetCursor();
ev_term = enif_make_tuple5(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetX()),
rt.make_int(ev->GetY()),
rt.make_ref(app->getRef((void *)GetCursor,memenv), "wxCursor"));
break;
}
case 173: {// wxKeyEvent
wxKeyEvent * ev = (wxKeyEvent *) event;
ev_term = enif_make_tuple(rt.env,12,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetX()),
rt.make_int(ev->GetY()),
rt.make_int(ev->GetKeyCode()),
rt.make_bool(ev->ControlDown()),
rt.make_bool(ev->ShiftDown()),
rt.make_bool(ev->AltDown()),
rt.make_bool(ev->MetaDown()),
rt.make_int(ev->GetUnicodeKey()),
rt.make_uint(ev->GetRawKeyCode()),
rt.make_uint(ev->GetRawKeyFlags()));
break;
}
case 174: {// wxSizeEvent
wxSizeEvent * ev = (wxSizeEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetSize()),
rt.make(ev->GetRect()));
break;
}
case 175: {// wxMoveEvent
wxMoveEvent * ev = (wxMoveEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetPosition()),
rt.make(ev->GetRect()));
break;
}
case 176: {// wxPaintEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 177: {// wxEraseEvent
wxEraseEvent * ev = (wxEraseEvent *) event;
wxDC * GetDC = ev->GetDC();
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_ref(app->getRef((void *)GetDC,memenv), "wxDC"));
break;
}
case 178: {// wxFocusEvent
wxFocusEvent * ev = (wxFocusEvent *) event;
wxWindow * GetWindow = ev->GetWindow();
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_ref(app->getRef((void *)GetWindow,memenv), "wxWindow"));
break;
}
case 179: {// wxChildFocusEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 180: {// wxMenuEvent
wxMenuEvent * ev = (wxMenuEvent *) event;
wxMenu * GetMenu = ev->GetMenu();
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetMenuId()),
rt.make_ref(app->getRef((void *)GetMenu,memenv), "wxMenu"));
break;
}
case 181: {// wxCloseEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 182: {// wxShowEvent
wxShowEvent * ev = (wxShowEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_bool(ev->IsShown()));
break;
}
case 183: {// wxIconizeEvent
wxIconizeEvent * ev = (wxIconizeEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_bool(ev->IsIconized()));
break;
}
case 184: {// wxMaximizeEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 185: {// wxJoystickEvent
wxJoystickEvent * ev = (wxJoystickEvent *) event;
ev_term = enif_make_tuple7(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetPosition()),
rt.make_int(ev->GetZPosition()),
rt.make_int(ev->GetButtonChange()),
rt.make_int(ev->GetButtonState()),
rt.make_int(ev->GetJoystick()));
break;
}
case 186: {// wxUpdateUIEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 187: {// wxSysColourChangedEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 188: {// wxMouseCaptureChangedEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 189: {// wxDisplayChangedEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 190: {// wxPaletteChangedEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 191: {// wxQueryNewPaletteEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 192: {// wxNavigationKeyEvent
wxNavigationKeyEvent * ev = (wxNavigationKeyEvent *) event;
wxWindow * GetCurrentFocus = ev->GetCurrentFocus();
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_bool(ev->GetDirection()),
rt.make_ref(app->getRef((void *)GetCurrentFocus,memenv), "wxWindow"));
break;
}
case 193: {// wxWindowCreateEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 194: {// wxWindowDestroyEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 195: {// wxHelpEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 196: {// wxContextMenuEvent
wxContextMenuEvent * ev = (wxContextMenuEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetPosition()));
break;
}
case 197: {// wxIdleEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 198: {// wxGridEvent
wxGridEvent * ev = (wxGridEvent *) event;
ev_term = enif_make_tuple(rt.env,10,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetRow()),
rt.make_int(ev->GetCol()),
rt.make(ev->GetPosition()),
rt.make_bool(ev->Selecting()),
rt.make_bool(ev->ControlDown()),
rt.make_bool(ev->MetaDown()),
rt.make_bool(ev->ShiftDown()),
rt.make_bool(ev->AltDown()));
break;
}
case 200: {// wxSashEvent
wxSashEvent * ev = (wxSashEvent *) event;
ev_term = enif_make_tuple5(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetEdge()),
rt.make(ev->GetDragRect()),
rt.make_int(ev->GetDragStatus()));
break;
}
case 201: {// wxListEvent
wxListEvent * ev = (wxListEvent *) event;
ev_term = enif_make_tuple7(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetKeyCode()),
rt.make_int(ev->GetCacheFrom()),
rt.make_int(ev->GetIndex()),
rt.make_int(ev->GetColumn()),
rt.make(ev->GetPoint()));
break;
}
case 202: {// wxDateEvent
wxDateEvent * ev = (wxDateEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetDate()));
break;
}
case 203: {// wxCalendarEvent
wxCalendarEvent * ev = (wxCalendarEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetWeekDay()),
rt.make(ev->GetDate()));
break;
}
case 204: {// wxFileDirPickerEvent
wxFileDirPickerEvent * ev = (wxFileDirPickerEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetPath()));
break;
}
case 205: {// wxColourPickerEvent
wxColourPickerEvent * ev = (wxColourPickerEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetColour()));
break;
}
case 206: {// wxFontPickerEvent
wxFontPickerEvent * ev = (wxFontPickerEvent *) event;
wxFont * GetFont = new wxFont(ev->GetFont());
app->newPtr((void *) GetFont,3, memenv);
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_ref(app->getRef((void *)GetFont,memenv), "wxFont"));
break;
}
case 207: {// wxStyledTextEvent
wxStyledTextEvent * ev = (wxStyledTextEvent *) event;
ev_term = enif_make_tuple(rt.env,22,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetPosition()),
rt.make_int(ev->GetKey()),
rt.make_int(ev->GetModifiers()),
rt.make_int(ev->GetModificationType()),
rt.make(ev->GetText()),
rt.make_int(ev->GetLength()),
rt.make_int(ev->GetLinesAdded()),
rt.make_int(ev->GetLine()),
rt.make_int(ev->GetFoldLevelNow()),
rt.make_int(ev->GetFoldLevelPrev()),
rt.make_int(ev->GetMargin()),
rt.make_int(ev->GetMessage()),
rt.make_int(ev->GetWParam()),
rt.make_int(ev->GetLParam()),
rt.make_int(ev->GetListType()),
rt.make_int(ev->GetX()),
rt.make_int(ev->GetY()),
rt.make(ev->GetDragText()),
rt.make_bool(ev->GetDragAllowMove()),
rt.make_int(ev->GetDragResult()));
break;
}
case 213: {// wxTreeEvent
wxTreeEvent * ev = (wxTreeEvent *) event;
ev_term = enif_make_tuple5(rt.env,
Etype->evRecord,
Etype->evName,
rt.make((wxUIntPtr *) ev->GetItem().m_pItem),
rt.make((wxUIntPtr *) ev->GetOldItem().m_pItem),
rt.make(ev->GetPoint()));
break;
}
case 214: {// wxBookCtrlEvent
wxBookCtrlEvent * ev = (wxBookCtrlEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetSelection()),
rt.make_int(ev->GetOldSelection()));
break;
}
case 220: {// wxClipboardTextEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 221: {// wxSpinEvent
wxSpinEvent * ev = (wxSpinEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetPosition()));
break;
}
case 223: {// wxSplitterEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 225: {// wxHtmlLinkEvent
wxHtmlLinkEvent * ev = (wxHtmlLinkEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetLinkInfo()));
break;
}
case 228: {// wxAuiNotebookEvent
wxAuiNotebookEvent * ev = (wxAuiNotebookEvent *) event;
wxAuiNotebook * GetDragSource = ev->GetDragSource();
ev_term = enif_make_tuple5(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_int(ev->GetOldSelection()),
rt.make_int(ev->GetSelection()),
rt.make_ref(app->getRef((void *)GetDragSource,memenv), "wxAuiNotebook"));
break;
}
case 229: {// wxAuiManagerEvent
wxAuiManagerEvent * ev = (wxAuiManagerEvent *) event;
wxAuiManager * GetManager = ev->GetManager();
wxAuiPaneInfo * GetPane = ev->GetPane();
wxDC * GetDC = ev->GetDC();
ev_term = enif_make_tuple(rt.env,8,
Etype->evRecord,
Etype->evName,
rt.make_ref(app->getRef((void *)GetManager,memenv), "wxAuiManager"),
rt.make_ref(app->getRef((void *)GetPane,memenv), "wxAuiPaneInfo"),
rt.make_int(ev->GetButton()),
rt.make_bool(ev->GetVeto()),
rt.make_bool(ev->CanVeto()),
rt.make_ref(app->getRef((void *)GetDC,memenv), "wxDC"));
break;
}
case 232: {// wxTaskBarIconEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 233: {// wxInitDialogEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 235: {// wxActivateEvent
wxActivateEvent * ev = (wxActivateEvent *) event;
ev_term = enif_make_tuple3(rt.env,
Etype->evRecord,
Etype->evName,
rt.make_bool(ev->GetActive()));
break;
}
case 238: {// wxMouseCaptureLostEvent
ev_term = enif_make_tuple2(rt.env,
Etype->evRecord,
Etype->evName
);
break;
}
case 241: {// wxDropFilesEvent
wxDropFilesEvent * ev = (wxDropFilesEvent *) event;
ev_term = enif_make_tuple4(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetPosition()),
rt.make_list_strings(ev->m_noFiles, ev->GetFiles())
);
break;
}
#if WXE_WEBVIEW
case 246: {// wxWebViewEvent
wxWebViewEvent * ev = (wxWebViewEvent *) event;
ev_term = enif_make_tuple6(rt.env,
Etype->evRecord,
Etype->evName,
rt.make(ev->GetString()),
rt.make_int(ev->GetInt()),
rt.make(ev->GetTarget()),
rt.make(ev->GetURL()));
break;
}
#endif // "WXE_WEBVIEW"
}
ERL_NIF_TERM wx_ev =
enif_make_tuple5(rt.env,
WXE_ATOM_wx,
rt.make_int((int) event->GetId()),
rt.make_ref(cb->obj, cb->class_name),
rt.make_ext2term(cb->user_data),
ev_term);
if(cb->fun_id) {
ERL_NIF_TERM wx_cb =
enif_make_tuple4(rt.env,
WXE_ATOM__wx_invoke_cb_,
rt.make_int(cb->fun_id),
wx_ev,
rt.make_ref(app->getRef((void *)event,memenv), Etype->evClass)
);
pre_callback();
send_res = rt.send(wx_cb);
if(send_res) handle_event_callback(memenv->me_ref, cb->listener);
app->clearPtr((void *) event);
} else {
send_res = rt.send(wx_ev);
if(cb->skip) event->Skip();
if(app->recurse_level < 1 && (Etype->cID == 174 || Etype->cID == 175)) {
app->recurse_level++;
app->dispatch_cmds();
app->recurse_level--;
}
};
return send_res;
}
| 47.33913 | 132 | 0.686903 | jjhoo |
d97bd98e8c85f7c4376fb93ac89f2f0eb9c8bca8 | 1,640 | hpp | C++ | include/sqlitepp/exception.hpp | Fadis/SQLitepp_CMake | edb4bcc06563b715518834de941160dd7afa6d84 | [
"BSL-1.0"
] | 1 | 2015-04-30T10:18:47.000Z | 2015-04-30T10:18:47.000Z | include/sqlitepp/exception.hpp | Fadis/SQLitepp_CMake | edb4bcc06563b715518834de941160dd7afa6d84 | [
"BSL-1.0"
] | null | null | null | include/sqlitepp/exception.hpp | Fadis/SQLitepp_CMake | edb4bcc06563b715518834de941160dd7afa6d84 | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// $Id: exception.hpp 46 2006-09-05 06:38:56Z pmed $
//
// Copyright (c) 2005 Pavel Medvedev
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef SQLITEPP_EXCEPTION_HPP_INCLUDED
#define SQLITEPP_EXCEPTION_HPP_INCLUDED
#include <stdexcept>
#include "string.hpp"
//////////////////////////////////////////////////////////////////////////////
namespace sqlitepp {
//////////////////////////////////////////////////////////////////////////////
class session;
// SQLite exception
class exception : public std::runtime_error
{
public:
// create exception with UTF-8 encoded message
exception(int code, string_t const& msg);
// SQLite library error code.
int code() const // throw()
{
return code_;
}
private:
int code_;
};
struct nested_txn_not_supported : exception
{
nested_txn_not_supported();
};
struct no_such_column : exception
{
no_such_column(string_t const& col_name);
};
struct session_not_open : exception
{
session_not_open();
};
struct multi_stmt_not_supported : exception
{
multi_stmt_not_supported();
};
//////////////////////////////////////////////////////////////////////////////
} // namespace sqlitepp
//////////////////////////////////////////////////////////////////////////////
#endif // SQLITEPP_EXCEPTION_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
| 23.768116 | 79 | 0.50061 | Fadis |
d9805e6f15e837c1ebb5c6b571337cb7cdbce9a8 | 7,562 | cpp | C++ | src/server_main/engine/scripting/character_script.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | src/server_main/engine/scripting/character_script.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | 7 | 2021-05-30T21:52:39.000Z | 2021-06-25T22:35:28.000Z | src/server_main/engine/scripting/character_script.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | #include "character_script.h"
#include "character_script_object.h"
#include "engine/entities/character.h"
#include "engine/world/world.h"
#include "api/logging/logging.h"
namespace projectfarm::engine::scripting
{
std::vector<std::pair<shared::scripting::FunctionTypes, bool>> CharacterScript::GetFunctions() const noexcept
{
return
{
{ shared::scripting::FunctionTypes::Update, true },
{ shared::scripting::FunctionTypes::Init, true },
};
}
void CharacterScript::SetupGlobalTemplate(v8::Local<v8::ObjectTemplate>& globalTemplate) noexcept
{
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "set_update_interval").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::SetUpdateInterval));
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "move").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::Move));
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "move_to").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::MoveTo));
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "get_position_x").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetPositionX));
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "get_position_y").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetPositionY));
globalTemplate->Set(v8::String::NewFromUtf8(this->_isolate, "world_get_characters_within_distance").ToLocalChecked(),
v8::FunctionTemplate::New(this->_isolate, &CharacterScript::GetCharactersWithinDistance));
}
void CharacterScript::SetUpdateInterval(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto character = static_cast<entities::Character*>(wrap->Value());
if (args.Length() != 1)
{
shared::api::logging::Log("Invalid number of arguments for 'SetUpdateInterval'.");
return;
}
auto interval = args[0]->Uint32Value(context).FromMaybe(0);
if (interval == 0)
{
shared::api::logging::Log("Ignoring value - possibly invalid.");
return;
}
character->SetScriptUpdateInterval(interval);
}
void CharacterScript::Move(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto character = static_cast<entities::Character*>(wrap->Value());
if (args.Length() != 4)
{
shared::api::logging::Log("Invalid number of arguments for 'Move'.");
return;
}
v8::String::Utf8Value action(isolate, args[0]);
auto x = args[1]->NumberValue(context).FromMaybe(character->GetLocation().first);
auto y = args[2]->NumberValue(context).FromMaybe(character->GetLocation().second);
auto distance = args[3]->NumberValue(context).FromMaybe(0.0f);
if (distance == 0.0f)
{
shared::api::logging::Log("Ignoring distance - possibly invalid.");
return;
}
character->ScriptMove(*action, static_cast<float>(x), static_cast<float>(y),
static_cast<float>(distance));
}
void CharacterScript::MoveTo(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto character = static_cast<entities::Character*>(wrap->Value());
if (args.Length() != 3)
{
shared::api::logging::Log("Invalid number of arguments for 'MoveTo'.");
return;
}
v8::String::Utf8Value action(isolate, args[0]);
auto x = args[1]->NumberValue(context).FromMaybe(0.0f);
auto y = args[2]->NumberValue(context).FromMaybe(0.0f);
character->ScriptMoveTo(*action, static_cast<float>(x), static_cast<float>(y));
}
void CharacterScript::GetPositionX(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto character = static_cast<entities::Character*>(wrap->Value());
args.GetReturnValue().Set(character->GetLocation().first);
}
void CharacterScript::GetPositionY(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto character = static_cast<entities::Character*>(wrap->Value());
args.GetReturnValue().Set(character->GetLocation().second);
}
void CharacterScript::GetCharactersWithinDistance(const v8::FunctionCallbackInfo<v8::Value>& args)
{
using namespace std::literals::string_literals;
auto isolate = args.GetIsolate();
auto context = isolate->GetCurrentContext();
v8::HandleScope handScope(isolate);
auto self = args.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(1));
auto thisCharacter = static_cast<entities::Character*>(wrap->Value());
if (args.Length() != 1)
{
shared::api::logging::Log("Invalid number of arguments for 'GetCharactersWithinDistance'.");
return;
}
auto distance = static_cast<float>(args[0]->NumberValue(context).FromMaybe(0.0f));
if (distance == 0.0f)
{
auto emptyArray = v8::Array::New(isolate, 0);
args.GetReturnValue().Set(emptyArray);
return;
}
auto& world = thisCharacter->GetCurrentWorld();
auto charactersWithinDistance = world->GetCharactersWithinDistance(thisCharacter->GetEntityId(), distance);
v8::Local<v8::Array> result = v8::Array::New(isolate, static_cast<int>(charactersWithinDistance.size()));
auto index = 0u;
for (const auto& character : charactersWithinDistance)
{
auto objectInstance = CharacterScriptObject::GetObjectTemplateInstance(isolate, character.get());
result->Set(context, index++, objectInstance).Check();
}
args.GetReturnValue().Set(result);
}
} | 36.887805 | 125 | 0.626686 | snowmeltarcade |
d9828a63c8d6e902fef2c1b86520f97d36d25d98 | 86,229 | cpp | C++ | Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Landscape/Private/LandscapeGrass.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "CoreMinimal.h"
#include "GenericPlatform/GenericPlatformStackWalk.h"
#include "HAL/FileManager.h"
#include "Templates/ScopedPointer.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Misc/Guid.h"
#include "Math/RandomStream.h"
#include "Stats/Stats.h"
#include "Async/AsyncWork.h"
#include "HAL/IConsoleManager.h"
#include "Misc/App.h"
#include "UObject/ObjectMacros.h"
#include "UObject/UObjectIterator.h"
#include "EngineDefines.h"
#include "Engine/EngineTypes.h"
#include "GameFramework/Actor.h"
#include "ShowFlags.h"
#include "RHI.h"
#include "RenderingThread.h"
#include "ShaderParameters.h"
#include "RHIStaticStates.h"
#include "SceneView.h"
#include "Shader.h"
#include "LandscapeProxy.h"
#include "LightMap.h"
#include "Engine/MapBuildDataRegistry.h"
#include "ShadowMap.h"
#include "LandscapeComponent.h"
#include "LandscapeVersion.h"
#include "MaterialShaderType.h"
#include "MeshMaterialShaderType.h"
#include "DrawingPolicy.h"
#include "MeshMaterialShader.h"
#include "Materials/Material.h"
#include "LandscapeGrassType.h"
#include "Materials/MaterialExpressionLandscapeGrassOutput.h"
#include "Engine/TextureRenderTarget2D.h"
#include "ContentStreaming.h"
#include "LandscapeDataAccess.h"
#include "StaticMeshResources.h"
#include "LandscapeLight.h"
#include "Components/HierarchicalInstancedStaticMeshComponent.h"
#include "Materials/MaterialInstanceConstant.h"
#include "ShaderParameterUtils.h"
#include "EngineModule.h"
#include "LandscapeRender.h"
#include "MaterialCompiler.h"
#include "Containers/Algo/Accumulate.h"
#include "Package.h"
#include "Engine/StaticMesh.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "InstancedStaticMesh.h"
#define LOCTEXT_NAMESPACE "Landscape"
DEFINE_LOG_CATEGORY_STATIC(LogGrass, Log, All);
static TAutoConsoleVariable<float> CVarGuardBandMultiplier(
TEXT("grass.GuardBandMultiplier"),
1.3f,
TEXT("Used to control discarding in the grass system. Approximate range, 1-4. Multiplied by the cull distance to control when we add grass components."));
static TAutoConsoleVariable<float> CVarGuardBandDiscardMultiplier(
TEXT("grass.GuardBandDiscardMultiplier"),
1.4f,
TEXT("Used to control discarding in the grass system. Approximate range, 1-4. Multiplied by the cull distance to control when we discard grass components."));
static TAutoConsoleVariable<int32> CVarMinFramesToKeepGrass(
TEXT("grass.MinFramesToKeepGrass"),
30,
TEXT("Minimum number of frames before cached grass can be discarded; used to prevent thrashing."));
static TAutoConsoleVariable<float> CVarMinTimeToKeepGrass(
TEXT("grass.MinTimeToKeepGrass"),
5.0f,
TEXT("Minimum number of seconds before cached grass can be discarded; used to prevent thrashing."));
static TAutoConsoleVariable<int32> CVarMaxInstancesPerComponent(
TEXT("grass.MaxInstancesPerComponent"),
65536,
TEXT("Used to control the number of hierarchical components created. More can be more efficient, but can be hitchy as new components come into range"));
static TAutoConsoleVariable<int32> CVarMaxAsyncTasks(
TEXT("grass.MaxAsyncTasks"),
4,
TEXT("Used to control the number of hierarchical components created at a time."));
static TAutoConsoleVariable<int32> CVarUseHaltonDistribution(
TEXT("grass.UseHaltonDistribution"),
0,
TEXT("Used to control the distribution of grass instances. If non-zero, use a halton sequence."));
static TAutoConsoleVariable<float> CVarGrassDensityScale(
TEXT("grass.densityScale"),
1,
TEXT("Multiplier on all grass densities."),
ECVF_Scalability);
static TAutoConsoleVariable<int32> CVarGrassEnable(
TEXT("grass.Enable"),
1,
TEXT("1: Enable Grass; 0: Disable Grass"));
static TAutoConsoleVariable<int32> CVarGrassDiscardDataOnLoad(
TEXT("grass.DiscardDataOnLoad"),
0,
TEXT("1: Discard grass data on load (disables grass); 0: Keep grass data (requires reloading level)"),
ECVF_Scalability);
static TAutoConsoleVariable<int32> CVarUseStreamingManagerForCameras(
TEXT("grass.UseStreamingManagerForCameras"),
1,
TEXT("1: Use Streaming Manager; 0: Use ViewLocationsRenderedLastFrame"));
static TAutoConsoleVariable<int32> CVarCullSubsections(
TEXT("grass.CullSubsections"),
1,
TEXT("1: Cull each foliage component; 0: Cull only based on the landscape component."));
static TAutoConsoleVariable<int32> CVarDisableGPUCull(
TEXT("grass.DisableGPUCull"),
0,
TEXT("For debugging. Set this to zero to see where the grass is generated. Useful for tweaking the guard bands."));
static TAutoConsoleVariable<int32> CVarPrerenderGrassmaps(
TEXT("grass.PrerenderGrassmaps"),
1,
TEXT("1: Pre-render grass maps for all components in the editor; 0: Generate grass maps on demand while moving through the editor"));
DECLARE_CYCLE_STAT(TEXT("Grass Async Build Time"), STAT_FoliageGrassAsyncBuildTime, STATGROUP_Foliage);
DECLARE_CYCLE_STAT(TEXT("Grass Start Comp"), STAT_FoliageGrassStartComp, STATGROUP_Foliage);
DECLARE_CYCLE_STAT(TEXT("Grass End Comp"), STAT_FoliageGrassEndComp, STATGROUP_Foliage);
DECLARE_CYCLE_STAT(TEXT("Grass Destroy Comps"), STAT_FoliageGrassDestoryComp, STATGROUP_Foliage);
DECLARE_CYCLE_STAT(TEXT("Grass Update"), STAT_GrassUpdate, STATGROUP_Foliage);
static void GrassCVarSinkFunction()
{
static float CachedGrassDensityScale = 1.0f;
float GrassDensityScale = CVarGrassDensityScale.GetValueOnGameThread();
if (GrassDensityScale != CachedGrassDensityScale)
{
CachedGrassDensityScale = GrassDensityScale;
for (auto* Landscape : TObjectRange<ALandscapeProxy>(RF_ClassDefaultObject | RF_ArchetypeObject, true, EInternalObjectFlags::PendingKill))
{
Landscape->FlushGrassComponents(nullptr, false);
}
}
}
static FAutoConsoleVariableSink CVarGrassSink(FConsoleCommandDelegate::CreateStatic(&GrassCVarSinkFunction));
//
// Grass weightmap rendering
//
#if WITH_EDITOR
static bool ShouldCacheLandscapeGrassShaders(EShaderPlatform Platform, const FMaterial* Material, const FVertexFactoryType* VertexFactoryType)
{
// We only need grass weight shaders for Landscape vertex factories on desktop platforms
return (Material->IsUsedWithLandscape() || Material->IsSpecialEngineMaterial()) &&
IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4) &&
((VertexFactoryType == FindVertexFactoryType(FName(TEXT("FLandscapeVertexFactory"), FNAME_Find))) || (VertexFactoryType == FindVertexFactoryType(FName(TEXT("FLandscapeXYOffsetVertexFactory"), FNAME_Find))))
&& !IsConsolePlatform(Platform);
}
class FLandscapeGrassWeightVS : public FMeshMaterialShader
{
DECLARE_SHADER_TYPE(FLandscapeGrassWeightVS, MeshMaterial);
FShaderParameter RenderOffsetParameter;
protected:
FLandscapeGrassWeightVS()
{}
FLandscapeGrassWeightVS(const FMeshMaterialShaderType::CompiledShaderInitializerType& Initializer)
: FMeshMaterialShader(Initializer)
{
RenderOffsetParameter.Bind(Initializer.ParameterMap, TEXT("RenderOffset"));
}
public:
static bool ShouldCache(EShaderPlatform Platform, const FMaterial* Material, const FVertexFactoryType* VertexFactoryType)
{
return ShouldCacheLandscapeGrassShaders(Platform, Material, VertexFactoryType);
}
void SetParameters(FRHICommandList& RHICmdList, const FMaterialRenderProxy* MaterialRenderProxy, const FMaterial& MaterialResource, const FSceneView& View, const FVector2D& RenderOffset)
{
FMeshMaterialShader::SetParameters(RHICmdList, GetVertexShader(), MaterialRenderProxy, MaterialResource, View, View.ViewUniformBuffer, ESceneRenderTargetsMode::DontSet);
SetShaderValue(RHICmdList, GetVertexShader(), RenderOffsetParameter, RenderOffset);
}
void SetMesh(FRHICommandList& RHICmdList, const FVertexFactory* VertexFactory, const FSceneView& View, const FPrimitiveSceneProxy* Proxy, const FMeshBatchElement& BatchElement, const FDrawingPolicyRenderState& DrawRenderState)
{
FMeshMaterialShader::SetMesh(RHICmdList, GetVertexShader(), VertexFactory, View, Proxy, BatchElement, DrawRenderState);
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FMeshMaterialShader::Serialize(Ar);
Ar << RenderOffsetParameter;
return bShaderHasOutdatedParameters;
}
};
IMPLEMENT_MATERIAL_SHADER_TYPE(, FLandscapeGrassWeightVS, TEXT("/Engine/Private/LandscapeGrassWeight.usf"), TEXT("VSMain"), SF_Vertex);
class FLandscapeGrassWeightPS : public FMeshMaterialShader
{
DECLARE_SHADER_TYPE(FLandscapeGrassWeightPS, MeshMaterial);
FShaderParameter OutputPassParameter;
public:
static bool ShouldCache(EShaderPlatform Platform, const FMaterial* Material, const FVertexFactoryType* VertexFactoryType)
{
return ShouldCacheLandscapeGrassShaders(Platform, Material, VertexFactoryType);
}
FLandscapeGrassWeightPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FMeshMaterialShader(Initializer)
{
OutputPassParameter.Bind(Initializer.ParameterMap, TEXT("OutputPass"));
}
FLandscapeGrassWeightPS()
{}
void SetParameters(FRHICommandList& RHICmdList, const FMaterialRenderProxy* MaterialRenderProxy, const FMaterial& MaterialResource, const FSceneView* View, int32 OutputPass)
{
FMeshMaterialShader::SetParameters(RHICmdList, GetPixelShader(), MaterialRenderProxy, MaterialResource, *View, View->ViewUniformBuffer, ESceneRenderTargetsMode::DontSet);
if (OutputPassParameter.IsBound())
{
SetShaderValue(RHICmdList, GetPixelShader(), OutputPassParameter, OutputPass);
}
}
void SetMesh(FRHICommandList& RHICmdList, const FVertexFactory* VertexFactory, const FSceneView& View, const FPrimitiveSceneProxy* Proxy, const FMeshBatchElement& BatchElement, const FDrawingPolicyRenderState& DrawRenderState)
{
FMeshMaterialShader::SetMesh(RHICmdList, GetPixelShader(), VertexFactory, View, Proxy, BatchElement, DrawRenderState);
}
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FMeshMaterialShader::Serialize(Ar);
Ar << OutputPassParameter;
return bShaderHasOutdatedParameters;
}
};
IMPLEMENT_MATERIAL_SHADER_TYPE(, FLandscapeGrassWeightPS, TEXT("/Engine/Private/LandscapeGrassWeight.usf"), TEXT("PSMain"), SF_Pixel);
/**
* Drawing policy used to write out landscape grass weightmap.
*/
class FLandscapeGrassWeightDrawingPolicy : public FMeshDrawingPolicy
{
public:
FLandscapeGrassWeightDrawingPolicy(
const FVertexFactory* InVertexFactory,
const FMaterialRenderProxy* InMaterialRenderProxy,
const FMaterial& InMaterialResource,
const FMeshDrawingPolicyOverrideSettings& InOverrideSettings
)
:
FMeshDrawingPolicy(InVertexFactory, InMaterialRenderProxy, InMaterialResource, InOverrideSettings)
{
PixelShader = InMaterialResource.GetShader<FLandscapeGrassWeightPS>(InVertexFactory->GetType());
VertexShader = InMaterialResource.GetShader<FLandscapeGrassWeightVS>(VertexFactory->GetType());
}
// FMeshDrawingPolicy interface.
FDrawingPolicyMatchResult Matches(const FLandscapeGrassWeightDrawingPolicy& Other) const
{
DRAWING_POLICY_MATCH_BEGIN
DRAWING_POLICY_MATCH(FMeshDrawingPolicy::Matches(Other)) &&
DRAWING_POLICY_MATCH(VertexShader == Other.VertexShader) &&
DRAWING_POLICY_MATCH(PixelShader == Other.PixelShader);
DRAWING_POLICY_MATCH_END
}
void SetSharedState(FRHICommandList& RHICmdList, const FDrawingPolicyRenderState& DrawRenderState, const FSceneView* View, const ContextDataType PolicyContext, int32 OutputPass, const FVector2D& RenderOffset) const
{
// Set the shader parameters for the material.
VertexShader->SetParameters(RHICmdList, MaterialRenderProxy, *MaterialResource, *View, RenderOffset);
PixelShader->SetParameters(RHICmdList, MaterialRenderProxy, *MaterialResource, View, OutputPass);
// Set the shared mesh resources.
FMeshDrawingPolicy::SetSharedState(RHICmdList, DrawRenderState, View, PolicyContext);
}
FBoundShaderStateInput GetBoundShaderStateInput(ERHIFeatureLevel::Type InFeatureLevel) const
{
return FBoundShaderStateInput(
FMeshDrawingPolicy::GetVertexDeclaration(),
VertexShader->GetVertexShader(),
FHullShaderRHIRef(),
FDomainShaderRHIRef(),
PixelShader->GetPixelShader(),
NULL);
}
void SetMeshRenderState(
FRHICommandList& RHICmdList,
const FSceneView& View,
const FPrimitiveSceneProxy* PrimitiveSceneProxy,
const FMeshBatch& Mesh,
int32 BatchElementIndex,
const FDrawingPolicyRenderState& DrawRenderState,
const ElementDataType& ElementData,
const ContextDataType PolicyContext
) const
{
const FMeshBatchElement& BatchElement = Mesh.Elements[BatchElementIndex];
VertexShader->SetMesh(RHICmdList, VertexFactory, View, PrimitiveSceneProxy, BatchElement, DrawRenderState);
PixelShader->SetMesh(RHICmdList, VertexFactory, View, PrimitiveSceneProxy, BatchElement, DrawRenderState);
}
friend int32 CompareDrawingPolicy(const FLandscapeGrassWeightDrawingPolicy& A, const FLandscapeGrassWeightDrawingPolicy& B)
{
COMPAREDRAWINGPOLICYMEMBERS(VertexShader);
COMPAREDRAWINGPOLICYMEMBERS(PixelShader);
COMPAREDRAWINGPOLICYMEMBERS(VertexFactory);
COMPAREDRAWINGPOLICYMEMBERS(MaterialRenderProxy);
return 0;
}
private:
FLandscapeGrassWeightVS* VertexShader;
FLandscapeGrassWeightPS* PixelShader;
};
// data also accessible by render thread
class FLandscapeGrassWeightExporter_RenderThread
{
FLandscapeGrassWeightExporter_RenderThread(int32 InNumGrassMaps, bool InbNeedsHeightmap, TArray<int32> InHeightMips)
: RenderTargetResource(nullptr)
, NumPasses(0)
, HeightMips(MoveTemp(InHeightMips))
, FirstHeightMipsPassIndex(MAX_int32)
{
if (InbNeedsHeightmap || InNumGrassMaps > 0)
{
NumPasses += FMath::DivideAndRoundUp(2 /* heightmap */ + InNumGrassMaps, 4);
}
if (HeightMips.Num() > 0)
{
FirstHeightMipsPassIndex = NumPasses;
NumPasses += HeightMips.Num();
}
}
friend class FLandscapeGrassWeightExporter;
public:
virtual ~FLandscapeGrassWeightExporter_RenderThread()
{}
struct FComponentInfo
{
ULandscapeComponent* Component;
FVector2D ViewOffset;
int32 PixelOffsetX;
FLandscapeComponentSceneProxy* SceneProxy;
FComponentInfo(ULandscapeComponent* InComponent, FVector2D& InViewOffset, int32 InPixelOffsetX)
: Component(InComponent)
, ViewOffset(InViewOffset)
, PixelOffsetX(InPixelOffsetX)
, SceneProxy((FLandscapeComponentSceneProxy*)InComponent->SceneProxy)
{}
};
FTextureRenderTarget2DResource* RenderTargetResource;
TArray<FComponentInfo, TInlineAllocator<1>> ComponentInfos;
FIntPoint TargetSize;
int32 NumPasses;
TArray<int32> HeightMips;
int32 FirstHeightMipsPassIndex;
float PassOffsetX;
FVector ViewOrigin;
FMatrix ViewRotationMatrix;
FMatrix ProjectionMatrix;
void RenderLandscapeComponentToTexture_RenderThread(FRHICommandListImmediate& RHICmdList)
{
FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(RenderTargetResource, NULL, FEngineShowFlags(ESFIM_Game)).SetWorldTimes(FApp::GetCurrentTime() - GStartTime, FApp::GetDeltaTime(), FApp::GetCurrentTime() - GStartTime));
ViewFamily.LandscapeLODOverride = 0; // Force LOD render
FSceneViewInitOptions ViewInitOptions;
ViewInitOptions.SetViewRectangle(FIntRect(0, 0, TargetSize.X, TargetSize.Y));
ViewInitOptions.ViewOrigin = ViewOrigin;
ViewInitOptions.ViewRotationMatrix = ViewRotationMatrix;
ViewInitOptions.ProjectionMatrix = ProjectionMatrix;
ViewInitOptions.ViewFamily = &ViewFamily;
GetRendererModule().CreateAndInitSingleView(RHICmdList, &ViewFamily, &ViewInitOptions);
const FSceneView* View = ViewFamily.Views[0];
RHICmdList.SetViewport(View->ViewRect.Min.X, View->ViewRect.Min.Y, 0.0f, View->ViewRect.Max.X, View->ViewRect.Max.Y, 1.0f);
FDrawingPolicyRenderState DrawRenderState(*View);
DrawRenderState.ModifyViewOverrideFlags() |= EDrawingPolicyOverrideFlags::TwoSided;
DrawRenderState.SetBlendState(TStaticBlendState<>::GetRHI());
DrawRenderState.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
RHICmdList.SetScissorRect(false, 0, 0, 0, 0);
for (auto& ComponentInfo : ComponentInfos)
{
const FMeshBatch& Mesh = ComponentInfo.SceneProxy->GetGrassMeshBatch();
for (int32 PassIdx = 0; PassIdx < NumPasses; PassIdx++)
{
FLandscapeGrassWeightDrawingPolicy DrawingPolicy(Mesh.VertexFactory, Mesh.MaterialRenderProxy, *Mesh.MaterialRenderProxy->GetMaterial(GMaxRHIFeatureLevel), ComputeMeshOverrideSettings(Mesh));
const int32 ShaderPass = (PassIdx >= FirstHeightMipsPassIndex) ? 0 : PassIdx;
DrawingPolicy.SetupPipelineState(DrawRenderState, *View);
CommitGraphicsPipelineState(RHICmdList, DrawingPolicy, DrawRenderState, DrawingPolicy.GetBoundShaderStateInput(View->GetFeatureLevel()));
DrawingPolicy.SetSharedState(RHICmdList, DrawRenderState, View, FLandscapeGrassWeightDrawingPolicy::ContextDataType(), ShaderPass, ComponentInfo.ViewOffset + FVector2D(PassOffsetX * PassIdx, 0));
// The first batch element contains the grass batch for the entire component
const int32 ElementIndex = (PassIdx >= FirstHeightMipsPassIndex) ? HeightMips[PassIdx - FirstHeightMipsPassIndex] : 0;
DrawingPolicy.SetMeshRenderState(RHICmdList, *View, ComponentInfo.SceneProxy, Mesh, ElementIndex, DrawRenderState, FMeshDrawingPolicy::ElementDataType(), FLandscapeGrassWeightDrawingPolicy::ContextDataType());
DrawingPolicy.DrawMesh(RHICmdList, Mesh, ElementIndex);
}
}
}
};
class FLandscapeGrassWeightExporter : public FLandscapeGrassWeightExporter_RenderThread
{
ALandscapeProxy* LandscapeProxy;
int32 ComponentSizeVerts;
int32 SubsectionSizeQuads;
int32 NumSubsections;
TArray<ULandscapeGrassType*> GrassTypes;
UTextureRenderTarget2D* RenderTargetTexture;
public:
FLandscapeGrassWeightExporter(ALandscapeProxy* InLandscapeProxy, const TArray<ULandscapeComponent*>& InLandscapeComponents, TArray<ULandscapeGrassType*> InGrassTypes, bool InbNeedsHeightmap = true, TArray<int32> InHeightMips = {})
: FLandscapeGrassWeightExporter_RenderThread(
InGrassTypes.Num(),
InbNeedsHeightmap,
MoveTemp(InHeightMips))
, LandscapeProxy(InLandscapeProxy)
, ComponentSizeVerts(InLandscapeProxy->ComponentSizeQuads + 1)
, SubsectionSizeQuads(InLandscapeProxy->SubsectionSizeQuads)
, NumSubsections(InLandscapeProxy->NumSubsections)
, GrassTypes(MoveTemp(InGrassTypes))
, RenderTargetTexture(nullptr)
{
check(InLandscapeComponents.Num() > 0);
// todo: use a 2d target?
TargetSize = FIntPoint(ComponentSizeVerts * NumPasses * InLandscapeComponents.Num(), ComponentSizeVerts);
FIntPoint TargetSizeMinusOne(TargetSize - FIntPoint(1, 1));
PassOffsetX = 2.0f * (float)ComponentSizeVerts / (float)TargetSize.X;
for (int32 Idx = 0; Idx < InLandscapeComponents.Num(); Idx++)
{
ULandscapeComponent* Component = InLandscapeComponents[Idx];
FIntPoint ComponentOffset = (Component->GetSectionBase() - LandscapeProxy->LandscapeSectionOffset);
int32 PixelOffsetX = Idx * NumPasses * ComponentSizeVerts;
FVector2D ViewOffset(-ComponentOffset.X, ComponentOffset.Y);
ViewOffset.X += PixelOffsetX;
ViewOffset /= (FVector2D(TargetSize) * 0.5f);
ComponentInfos.Add(FComponentInfo(Component, ViewOffset, PixelOffsetX));
}
// center of target area in world
FVector TargetCenter = LandscapeProxy->GetTransform().TransformPosition(FVector(TargetSizeMinusOne, 0.f)*0.5f);
// extent of target in world space
FVector TargetExtent = FVector(TargetSize, 0.0f)*LandscapeProxy->GetActorScale()*0.5f;
ViewOrigin = TargetCenter;
ViewRotationMatrix = FInverseRotationMatrix(LandscapeProxy->GetActorRotation());
ViewRotationMatrix *= FMatrix(FPlane(1, 0, 0, 0),
FPlane(0,-1, 0, 0),
FPlane(0, 0,-1, 0),
FPlane(0, 0, 0, 1));
const float ZOffset = WORLD_MAX;
ProjectionMatrix = FReversedZOrthoMatrix(
TargetExtent.X,
TargetExtent.Y,
0.5f / ZOffset,
ZOffset);
RenderTargetTexture = NewObject<UTextureRenderTarget2D>();
check(RenderTargetTexture);
RenderTargetTexture->ClearColor = FLinearColor::White;
RenderTargetTexture->TargetGamma = 1.0f;
RenderTargetTexture->InitCustomFormat(TargetSize.X, TargetSize.Y, PF_B8G8R8A8, false);
RenderTargetResource = RenderTargetTexture->GameThread_GetRenderTargetResource()->GetTextureRenderTarget2DResource();
// render
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
FDrawSceneCommand,
FLandscapeGrassWeightExporter_RenderThread*, Exporter, this,
{
Exporter->RenderLandscapeComponentToTexture_RenderThread(RHICmdList);
FlushPendingDeleteRHIResources_RenderThread();
});
}
TMap<ULandscapeComponent*, TUniquePtr<FLandscapeComponentGrassData>, TInlineSetAllocator<1>>
FetchResults()
{
TArray<FColor> Samples;
Samples.SetNumUninitialized(TargetSize.X*TargetSize.Y);
// Copy the contents of the remote texture to system memory
FReadSurfaceDataFlags ReadSurfaceDataFlags;
ReadSurfaceDataFlags.SetLinearToGamma(false);
RenderTargetResource->ReadPixels(Samples, ReadSurfaceDataFlags, FIntRect(0, 0, TargetSize.X, TargetSize.Y));
TMap<ULandscapeComponent*, TUniquePtr<FLandscapeComponentGrassData>, TInlineSetAllocator<1>> Results;
Results.Reserve(ComponentInfos.Num());
for (auto& ComponentInfo : ComponentInfos)
{
ULandscapeComponent* Component = ComponentInfo.Component;
ALandscapeProxy* Proxy = Component->GetLandscapeProxy();
TUniquePtr<FLandscapeComponentGrassData> NewGrassData = MakeUnique<FLandscapeComponentGrassData>(Component);
if (FirstHeightMipsPassIndex > 0)
{
NewGrassData->HeightData.Empty(FMath::Square(ComponentSizeVerts));
}
else
{
NewGrassData->HeightData.Empty(0);
}
NewGrassData->HeightMipData.Empty(HeightMips.Num());
TArray<TArray<uint8>*> GrassWeightArrays;
GrassWeightArrays.Empty(GrassTypes.Num());
for (auto GrassType : GrassTypes)
{
NewGrassData->WeightData.Add(GrassType);
}
// need a second loop because the WeightData map will reallocate its arrays as grass types are added
for (auto GrassType : GrassTypes)
{
TArray<uint8>* DataArray = NewGrassData->WeightData.Find(GrassType);
check(DataArray);
DataArray->Empty(FMath::Square(ComponentSizeVerts));
GrassWeightArrays.Add(DataArray);
}
// output debug bitmap
#if UE_BUILD_DEBUG
static bool bOutputGrassBitmap = false;
if (bOutputGrassBitmap)
{
FString TempPath = FPaths::ScreenShotDir();
TempPath += TEXT("/GrassDebug");
IFileManager::Get().MakeDirectory(*TempPath, true);
FFileHelper::CreateBitmap(*(TempPath / "Grass"), TargetSize.X, TargetSize.Y, Samples.GetData(), nullptr, &IFileManager::Get(), nullptr, GrassTypes.Num() >= 2);
}
#endif
for (int32 PassIdx = 0; PassIdx < NumPasses; PassIdx++)
{
FColor* SampleData = &Samples[ComponentInfo.PixelOffsetX + PassIdx*ComponentSizeVerts];
if (PassIdx < FirstHeightMipsPassIndex)
{
if (PassIdx == 0)
{
for (int32 y = 0; y < ComponentSizeVerts; y++)
{
for (int32 x = 0; x < ComponentSizeVerts; x++)
{
FColor& Sample = SampleData[x + y * TargetSize.X];
uint16 Height = (((uint16)Sample.R) << 8) + (uint16)(Sample.G);
NewGrassData->HeightData.Add(Height);
if (GrassTypes.Num() > 0)
{
GrassWeightArrays[0]->Add(Sample.B);
if (GrassTypes.Num() > 1)
{
GrassWeightArrays[1]->Add(Sample.A);
}
}
}
}
}
else
{
for (int32 y = 0; y < ComponentSizeVerts; y++)
{
for (int32 x = 0; x < ComponentSizeVerts; x++)
{
FColor& Sample = SampleData[x + y * TargetSize.X];
int32 TypeIdx = PassIdx * 4 - 2;
GrassWeightArrays[TypeIdx++]->Add(Sample.R);
if (TypeIdx < GrassTypes.Num())
{
GrassWeightArrays[TypeIdx++]->Add(Sample.G);
if (TypeIdx < GrassTypes.Num())
{
GrassWeightArrays[TypeIdx++]->Add(Sample.B);
if (TypeIdx < GrassTypes.Num())
{
GrassWeightArrays[TypeIdx++]->Add(Sample.A);
}
}
}
}
}
}
}
else // PassIdx >= FirstHeightMipsPassIndex
{
const int32 Mip = HeightMips[PassIdx - FirstHeightMipsPassIndex];
int32 MipSizeVerts = NumSubsections * (SubsectionSizeQuads >> Mip);
TArray<uint16>& MipHeightData = NewGrassData->HeightMipData.Add(Mip);
for (int32 y = 0; y < MipSizeVerts; y++)
{
for (int32 x = 0; x < MipSizeVerts; x++)
{
FColor& Sample = SampleData[x + y * TargetSize.X];
uint16 Height = (((uint16)Sample.R) << 8) + (uint16)(Sample.G);
MipHeightData.Add(Height);
}
}
}
}
// remove null grass type if we had one (can occur if the node has null entries)
NewGrassData->WeightData.Remove(nullptr);
// Remove any grass data that is entirely weight 0
for (auto Iter(NewGrassData->WeightData.CreateIterator()); Iter; ++Iter)
{
if (Iter->Value.IndexOfByPredicate([&](const int8& Weight) { return Weight != 0; }) == INDEX_NONE)
{
Iter.RemoveCurrent();
}
}
Results.Add(Component, MoveTemp(NewGrassData));
}
return Results;
}
void ApplyResults()
{
TMap<ULandscapeComponent*, TUniquePtr<FLandscapeComponentGrassData>, TInlineSetAllocator<1>> NewGrassData = FetchResults();
for (auto&& GrassDataPair : NewGrassData)
{
ULandscapeComponent* Component = GrassDataPair.Key;
FLandscapeComponentGrassData* ComponentGrassData = GrassDataPair.Value.Release();
ALandscapeProxy* Proxy = Component->GetLandscapeProxy();
// Assign the new data (thread-safe)
Component->GrassData = MakeShareable(ComponentGrassData);
if (Proxy->bBakeMaterialPositionOffsetIntoCollision)
{
Component->UpdateCollisionData(true);
}
}
}
void AddReferencedObjects(UObject* InThis, FReferenceCollector& Collector)
{
if (RenderTargetTexture)
{
Collector.AddReferencedObject(RenderTargetTexture);
}
if (LandscapeProxy)
{
Collector.AddReferencedObject(LandscapeProxy);
}
for (auto& Info : ComponentInfos)
{
if (Info.Component)
{
Collector.AddReferencedObject(Info.Component);
}
}
for (auto GrassType : GrassTypes)
{
if (GrassType)
{
Collector.AddReferencedObject(GrassType);
}
}
}
};
FLandscapeComponentGrassData::FLandscapeComponentGrassData(ULandscapeComponent* Component)
: RotationForWPO(Component->GetLandscapeMaterial()->GetMaterial()->WorldPositionOffset.IsConnected() ? Component->GetComponentTransform().GetRotation() : FQuat(0, 0, 0, 0))
{
UMaterialInterface* Material = Component->GetLandscapeMaterial();
for (UMaterialInstanceConstant* MIC = Cast<UMaterialInstanceConstant>(Material); MIC; MIC = Cast<UMaterialInstanceConstant>(Material))
{
MaterialStateIds.Add(MIC->ParameterStateId);
Material = MIC->Parent;
}
MaterialStateIds.Add(CastChecked<UMaterial>(Material)->StateId);
}
bool ULandscapeComponent::MaterialHasGrass() const
{
UMaterialInterface* Material = GetLandscapeMaterial();
TArray<const UMaterialExpressionLandscapeGrassOutput*> GrassExpressions;
Material->GetMaterial()->GetAllExpressionsOfType<UMaterialExpressionLandscapeGrassOutput>(GrassExpressions);
if (GrassExpressions.Num() > 0 &&
GrassExpressions[0]->GrassTypes.Num() > 0)
{
return GrassExpressions[0]->GrassTypes.ContainsByPredicate([](FGrassInput& GrassInput) { return (GrassInput.Input.IsConnected() && GrassInput.GrassType); });
}
return false;
}
bool ULandscapeComponent::IsGrassMapOutdated() const
{
if (GrassData->HasData())
{
// check material / instances haven't changed
const auto& MaterialStateIds = GrassData->MaterialStateIds;
UMaterialInterface* Material = GetLandscapeMaterial();
int32 TestIndex = 0;
for (UMaterialInstanceConstant* MIC = Cast<UMaterialInstanceConstant>(Material); MIC; MIC = Cast<UMaterialInstanceConstant>(Material))
{
if (!MaterialStateIds.IsValidIndex(TestIndex) || MaterialStateIds[TestIndex] != MIC->ParameterStateId)
{
return true;
}
Material = MIC->Parent;
++TestIndex;
}
// last one should be a UMaterial
if (TestIndex != MaterialStateIds.Num() - 1 || MaterialStateIds[TestIndex] != CastChecked<UMaterial>(Material)->StateId)
{
return true;
}
FQuat RotationForWPO = GetLandscapeMaterial()->GetMaterial()->WorldPositionOffset.IsConnected() ? GetComponentTransform().GetRotation() : FQuat(0, 0, 0, 0);
if (GrassData->RotationForWPO != RotationForWPO)
{
return true;
}
}
return false;
}
bool ULandscapeComponent::CanRenderGrassMap() const
{
// Check we can render
UWorld* ComponentWorld = GetWorld();
if (!GIsEditor || GUsingNullRHI || !ComponentWorld || ComponentWorld->IsGameWorld() || ComponentWorld->FeatureLevel < ERHIFeatureLevel::SM4 || !SceneProxy)
{
return false;
}
// Check we can render the material
if (!MaterialInstances[0]->GetMaterialResource(ComponentWorld->FeatureLevel)->HasValidGameThreadShaderMap())
{
return false;
}
return true;
}
static bool IsTextureStreamedForGrassMapRender(UTexture2D* InTexture)
{
if (!InTexture || InTexture->GetNumResidentMips() != InTexture->GetNumMips()
|| !InTexture->Resource || ((FTexture2DResource*)InTexture->Resource)->GetCurrentFirstMip() > 0)
{
return false;
}
return true;
}
bool ULandscapeComponent::AreTexturesStreamedForGrassMapRender() const
{
// Check for valid heightmap that is fully streamed in
if (!IsTextureStreamedForGrassMapRender(HeightmapTexture))
{
return false;
}
// Check for valid weightmaps that is fully streamed in
for (auto WeightmapTexture : WeightmapTextures)
{
if (!IsTextureStreamedForGrassMapRender(WeightmapTexture))
{
return false;
}
}
return true;
}
void ULandscapeComponent::RenderGrassMap()
{
UMaterialInterface* Material = GetLandscapeMaterial();
if (CanRenderGrassMap())
{
TArray<ULandscapeGrassType*> GrassTypes;
TArray<const UMaterialExpressionLandscapeGrassOutput*> GrassExpressions;
Material->GetMaterial()->GetAllExpressionsOfType<UMaterialExpressionLandscapeGrassOutput>(GrassExpressions);
if (GrassExpressions.Num() > 0)
{
GrassTypes.Empty(GrassExpressions[0]->GrassTypes.Num());
for (auto& GrassTypeInput : GrassExpressions[0]->GrassTypes)
{
GrassTypes.Add(GrassTypeInput.GrassType);
}
}
const bool bBakeMaterialPositionOffsetIntoCollision = (GetLandscapeProxy() && GetLandscapeProxy()->bBakeMaterialPositionOffsetIntoCollision);
TArray<int32> HeightMips;
if (bBakeMaterialPositionOffsetIntoCollision)
{
if (CollisionMipLevel > 0)
{
HeightMips.Add(CollisionMipLevel);
}
if (SimpleCollisionMipLevel > CollisionMipLevel)
{
HeightMips.Add(SimpleCollisionMipLevel);
}
}
if (GrassTypes.Num() > 0 || bBakeMaterialPositionOffsetIntoCollision)
{
TArray<ULandscapeComponent*> LandscapeComponents;
LandscapeComponents.Add(this);
FLandscapeGrassWeightExporter Exporter(GetLandscapeProxy(), MoveTemp(LandscapeComponents), MoveTemp(GrassTypes), true, MoveTemp(HeightMips));
Exporter.ApplyResults();
}
}
}
TArray<uint16> ULandscapeComponent::RenderWPOHeightmap(int32 LOD)
{
TArray<uint16> Results;
if (!CanRenderGrassMap())
{
MaterialInstances[0]->GetMaterialResource(GetWorld()->FeatureLevel)->FinishCompilation();
}
TArray<ULandscapeGrassType*> GrassTypes;
TArray<ULandscapeComponent*> LandscapeComponents;
LandscapeComponents.Add(this);
if (LOD == 0)
{
FLandscapeGrassWeightExporter Exporter(GetLandscapeProxy(), MoveTemp(LandscapeComponents), MoveTemp(GrassTypes), true, {});
TMap<ULandscapeComponent*, TUniquePtr<FLandscapeComponentGrassData>, TInlineSetAllocator<1>> TempGrassData;
TempGrassData = Exporter.FetchResults();
Results = MoveTemp(TempGrassData[this]->HeightData);
}
else
{
TArray<int32> HeightMips;
HeightMips.Add(LOD);
FLandscapeGrassWeightExporter Exporter(GetLandscapeProxy(), MoveTemp(LandscapeComponents), MoveTemp(GrassTypes), false, MoveTemp(HeightMips));
TMap<ULandscapeComponent*, TUniquePtr<FLandscapeComponentGrassData>, TInlineSetAllocator<1>> TempGrassData;
TempGrassData = Exporter.FetchResults();
Results = MoveTemp(TempGrassData[this]->HeightMipData[LOD]);
}
return Results;
}
void ULandscapeComponent::RemoveGrassMap()
{
GrassData = MakeShareable(new FLandscapeComponentGrassData());
}
void ALandscapeProxy::RenderGrassMaps(const TArray<ULandscapeComponent*>& InLandscapeComponents, const TArray<ULandscapeGrassType*>& GrassTypes)
{
TArray<int32> HeightMips;
if (CollisionMipLevel > 0)
{
HeightMips.Add(CollisionMipLevel);
}
if (SimpleCollisionMipLevel > CollisionMipLevel)
{
HeightMips.Add(SimpleCollisionMipLevel);
}
FLandscapeGrassWeightExporter Exporter(this, InLandscapeComponents, GrassTypes, true, MoveTemp(HeightMips));
Exporter.ApplyResults();
}
#endif //WITH_EDITOR
// the purpose of this class is to copy the lightmap from the terrain, and set the CoordinateScale and CoordinateBias to zero.
// we re-use the same texture references, so the memory cost is relatively minimal.
class FLandscapeGrassLightMap : public FLightMap2D
{
public:
FLandscapeGrassLightMap(const FLightMap2D& InLightMap)
: FLightMap2D(InLightMap)
{
CoordinateScale = FVector2D::ZeroVector;
CoordinateBias = FVector2D::ZeroVector;
}
};
// the purpose of this class is to copy the shadowmap from the terrain, and set the CoordinateScale and CoordinateBias to zero.
// we re-use the same texture references, so the memory cost is relatively minimal.
class FLandscapeGrassShadowMap : public FShadowMap2D
{
public:
FLandscapeGrassShadowMap(const FShadowMap2D& InShadowMap)
: FShadowMap2D(InShadowMap)
{
CoordinateScale = FVector2D::ZeroVector;
CoordinateBias = FVector2D::ZeroVector;
}
};
//
// UMaterialExpressionLandscapeGrassOutput
//
UMaterialExpressionLandscapeGrassOutput::UMaterialExpressionLandscapeGrassOutput(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
// Structure to hold one-time initialization
struct FConstructorStatics
{
FText STRING_Landscape;
FName NAME_Grass;
FConstructorStatics()
: STRING_Landscape(LOCTEXT("Landscape", "Landscape"))
, NAME_Grass("Grass")
{
}
};
static FConstructorStatics ConstructorStatics;
#if WITH_EDITORONLY_DATA
MenuCategories.Add(ConstructorStatics.STRING_Landscape);
#endif
// No outputs
Outputs.Reset();
// Default input
new(GrassTypes)FGrassInput(ConstructorStatics.NAME_Grass);
}
#if WITH_EDITOR
int32 UMaterialExpressionLandscapeGrassOutput::Compile(class FMaterialCompiler* Compiler, int32 OutputIndex)
{
if (GrassTypes.IsValidIndex(OutputIndex))
{
if (GrassTypes[OutputIndex].Input.Expression)
{
return Compiler->CustomOutput(this, OutputIndex, GrassTypes[OutputIndex].Input.Compile(Compiler));
}
else
{
return CompilerError(Compiler, TEXT("Input missing"));
}
}
return INDEX_NONE;
}
void UMaterialExpressionLandscapeGrassOutput::GetCaption(TArray<FString>& OutCaptions) const
{
OutCaptions.Add(TEXT("Grass"));
}
#endif // WITH_EDITOR
const TArray<FExpressionInput*> UMaterialExpressionLandscapeGrassOutput::GetInputs()
{
TArray<FExpressionInput*> OutInputs;
for (auto& GrassType : GrassTypes)
{
OutInputs.Add(&GrassType.Input);
}
return OutInputs;
}
FExpressionInput* UMaterialExpressionLandscapeGrassOutput::GetInput(int32 InputIndex)
{
return &GrassTypes[InputIndex].Input;
}
FString UMaterialExpressionLandscapeGrassOutput::GetInputName(int32 InputIndex) const
{
return GrassTypes[InputIndex].Name.ToString();
}
bool UMaterialExpressionLandscapeGrassOutput::NeedsLoadForClient() const
{
return true;
}
#if WITH_EDITOR
void UMaterialExpressionLandscapeGrassOutput::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.MemberProperty)
{
const FName PropertyName = PropertyChangedEvent.MemberProperty->GetFName();
if (PropertyName == GET_MEMBER_NAME_CHECKED(UMaterialExpressionLandscapeGrassOutput, GrassTypes))
{
if (GraphNode)
{
GraphNode->ReconstructNode();
}
}
}
}
#endif
//
// ULandscapeGrassType
//
ULandscapeGrassType::ULandscapeGrassType(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
GrassDensity_DEPRECATED = 400;
StartCullDistance_DEPRECATED = 10000.0f;
EndCullDistance_DEPRECATED = 10000.0f;
PlacementJitter_DEPRECATED = 1.0f;
RandomRotation_DEPRECATED = true;
AlignToSurface_DEPRECATED = true;
}
void ULandscapeGrassType::PostLoad()
{
Super::PostLoad();
if (GrassMesh_DEPRECATED && !GrassVarieties.Num())
{
FGrassVariety Grass;
Grass.GrassMesh = GrassMesh_DEPRECATED;
Grass.GrassDensity = GrassDensity_DEPRECATED;
Grass.StartCullDistance = StartCullDistance_DEPRECATED;
Grass.EndCullDistance = EndCullDistance_DEPRECATED;
Grass.PlacementJitter = PlacementJitter_DEPRECATED;
Grass.RandomRotation = RandomRotation_DEPRECATED;
Grass.AlignToSurface = AlignToSurface_DEPRECATED;
GrassVarieties.Add(Grass);
GrassMesh_DEPRECATED = nullptr;
}
}
#if WITH_EDITOR
void ULandscapeGrassType::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (GIsEditor)
{
for (TObjectIterator<ALandscapeProxy> It; It; ++It)
{
ALandscapeProxy* Proxy = *It;
if (Proxy->GetWorld() && !Proxy->GetWorld()->IsPlayInEditor())
{
const UMaterialInterface* MaterialInterface = Proxy->LandscapeMaterial;
if (MaterialInterface)
{
TArray<const UMaterialExpressionLandscapeGrassOutput*> GrassExpressions;
MaterialInterface->GetMaterial()->GetAllExpressionsOfType<UMaterialExpressionLandscapeGrassOutput>(GrassExpressions);
// Should only be one grass type node
if (GrassExpressions.Num() > 0)
{
for (auto& Output : GrassExpressions[0]->GrassTypes)
{
if (Output.GrassType == this)
{
Proxy->FlushGrassComponents();
break;
}
}
}
}
}
}
}
}
#endif
//
// FLandscapeComponentGrassData
//
SIZE_T FLandscapeComponentGrassData::GetAllocatedSize() const
{
SIZE_T WeightSize = 0;
for (auto It = WeightData.CreateConstIterator(); It; ++It)
{
WeightSize += It.Value().GetAllocatedSize();
}
return sizeof(*this)
+ HeightData.GetAllocatedSize()
#if WITH_EDITORONLY_DATA
+ HeightMipData.GetAllocatedSize()
+ Algo::TransformAccumulate(HeightMipData, [](const TPair<int32, TArray<uint16>>& HeightMipDataPair) { return HeightMipDataPair.Value.GetAllocatedSize(); }, 0)
#endif
+ WeightData.GetAllocatedSize() + WeightSize;
}
FArchive& operator<<(FArchive& Ar, FLandscapeComponentGrassData& Data)
{
Ar.UsingCustomVersion(FLandscapeCustomVersion::GUID);
#if WITH_EDITORONLY_DATA
if (!Ar.IsFilterEditorOnly())
{
if (Ar.CustomVer(FLandscapeCustomVersion::GUID) >= FLandscapeCustomVersion::GrassMaterialInstanceFix)
{
Ar << Data.MaterialStateIds;
}
else
{
Data.MaterialStateIds.Empty(1);
if (Ar.UE4Ver() >= VER_UE4_SERIALIZE_LANDSCAPE_GRASS_DATA_MATERIAL_GUID)
{
FGuid MaterialStateId;
Ar << MaterialStateId;
Data.MaterialStateIds.Add(MaterialStateId);
}
}
if (Ar.CustomVer(FLandscapeCustomVersion::GUID) >= FLandscapeCustomVersion::GrassMaterialWPO)
{
Ar << Data.RotationForWPO;
}
}
#endif
Data.HeightData.BulkSerialize(Ar);
#if WITH_EDITORONLY_DATA
if (!Ar.IsFilterEditorOnly())
{
if (Ar.CustomVer(FLandscapeCustomVersion::GUID) >= FLandscapeCustomVersion::CollisionMaterialWPO)
{
if (Ar.CustomVer(FLandscapeCustomVersion::GUID) >= FLandscapeCustomVersion::LightmassMaterialWPO)
{
// todo - BulkSerialize each mip?
Ar << Data.HeightMipData;
}
else
{
checkSlow(Ar.IsLoading());
TArray<uint16> CollisionHeightData;
CollisionHeightData.BulkSerialize(Ar);
if (CollisionHeightData.Num())
{
const int32 ComponentSizeQuads = FMath::Sqrt(Data.HeightData.Num()) - 1;
const int32 CollisionSizeQuads = FMath::Sqrt(CollisionHeightData.Num()) - 1;
const int32 CollisionMip = FMath::FloorLog2(ComponentSizeQuads / CollisionSizeQuads);
Data.HeightMipData.Add(CollisionMip, MoveTemp(CollisionHeightData));
}
TArray<uint16> SimpleCollisionHeightData;
SimpleCollisionHeightData.BulkSerialize(Ar);
if (SimpleCollisionHeightData.Num())
{
const int32 ComponentSizeQuads = FMath::Sqrt(Data.HeightData.Num()) - 1;
const int32 SimpleCollisionSizeQuads = FMath::Sqrt(SimpleCollisionHeightData.Num()) - 1;
const int32 SimpleCollisionMip = FMath::FloorLog2(ComponentSizeQuads / SimpleCollisionSizeQuads);
Data.HeightMipData.Add(SimpleCollisionMip, MoveTemp(SimpleCollisionHeightData));
}
}
}
}
#endif
// Each weight data array, being 1 byte will be serialized in bulk.
Ar << Data.WeightData;
if (Ar.IsLoading() && !GIsEditor && CVarGrassDiscardDataOnLoad.GetValueOnAnyThread())
{
//Data = FLandscapeComponentGrassData();
Data.WeightData.Empty();
Data.HeightData.Empty();
Data = FLandscapeComponentGrassData();
}
return Ar;
}
//
// ALandscapeProxy grass-related functions
//
void ALandscapeProxy::TickGrass()
{
// Update foliage
static TArray<FVector> OldCameras;
if (CVarUseStreamingManagerForCameras.GetValueOnGameThread() == 0)
{
UWorld* World = GetWorld();
if (!World)
{
return;
}
if (!OldCameras.Num() && !World->ViewLocationsRenderedLastFrame.Num())
{
// no cameras, no grass update
return;
}
// there is a bug here, which often leaves us with no cameras in the editor
const TArray<FVector>& Cameras = World->ViewLocationsRenderedLastFrame.Num() ? World->ViewLocationsRenderedLastFrame : OldCameras;
if (&Cameras != &OldCameras)
{
check(IsInGameThread());
OldCameras = Cameras;
}
UpdateGrass(Cameras);
}
else
{
int32 Num = IStreamingManager::Get().GetNumViews();
if (!Num)
{
// no cameras, no grass update
return;
}
OldCameras.Reset(Num);
for (int32 Index = 0; Index < Num; Index++)
{
auto& ViewInfo = IStreamingManager::Get().GetViewInformation(Index);
OldCameras.Add(ViewInfo.ViewOrigin);
}
UpdateGrass(OldCameras);
}
}
struct FGrassBuilderBase
{
bool bHaveValidData;
float GrassDensity;
FVector DrawScale;
FVector DrawLoc;
FMatrix LandscapeToWorld;
FIntPoint SectionBase;
FIntPoint LandscapeSectionOffset;
int32 ComponentSizeQuads;
FVector Origin;
FVector Extent;
FVector ComponentOrigin;
int32 SqrtMaxInstances;
FGrassBuilderBase(ALandscapeProxy* Landscape, ULandscapeComponent* Component, const FGrassVariety& GrassVariety, int32 SqrtSubsections = 1, int32 SubX = 0, int32 SubY = 0)
{
bHaveValidData = true;
const float DensityScale = CVarGrassDensityScale.GetValueOnAnyThread();
GrassDensity = GrassVariety.GrassDensity * DensityScale;
DrawScale = Landscape->GetRootComponent()->RelativeScale3D;
DrawLoc = Landscape->GetActorLocation();
LandscapeSectionOffset = Landscape->LandscapeSectionOffset;
SectionBase = Component->GetSectionBase();
ComponentSizeQuads = Component->ComponentSizeQuads;
Origin = FVector(DrawScale.X * float(SectionBase.X), DrawScale.Y * float(SectionBase.Y), 0.0f);
Extent = FVector(DrawScale.X * float(SectionBase.X + ComponentSizeQuads), DrawScale.Y * float(SectionBase.Y + ComponentSizeQuads), 0.0f) - Origin;
ComponentOrigin = Origin - FVector(DrawScale.X * LandscapeSectionOffset.X, DrawScale.Y * LandscapeSectionOffset.Y, 0.0f);
SqrtMaxInstances = FMath::CeilToInt(FMath::Sqrt(FMath::Abs(Extent.X * Extent.Y * GrassDensity / 1000.0f / 1000.0f)));
if (SqrtMaxInstances == 0)
{
bHaveValidData = false;
}
const FRotator DrawRot = Landscape->GetActorRotation();
LandscapeToWorld = Landscape->GetRootComponent()->GetComponentTransform().ToMatrixNoScale();
if (bHaveValidData && SqrtSubsections != 1)
{
check(SqrtMaxInstances > 2 * SqrtSubsections);
SqrtMaxInstances /= SqrtSubsections;
check(SqrtMaxInstances > 0);
Extent /= float(SqrtSubsections);
Origin += Extent * FVector(float(SubX), float(SubY), 0.0f);
}
}
};
// FLandscapeComponentGrassAccess - accessor wrapper for data for one GrassType from one Component
struct FLandscapeComponentGrassAccess
{
FLandscapeComponentGrassAccess(const ULandscapeComponent* InComponent, const ULandscapeGrassType* GrassType)
: GrassData(InComponent->GrassData)
, HeightData(InComponent->GrassData->HeightData)
, WeightData(InComponent->GrassData->WeightData.Find(GrassType))
, Stride(InComponent->ComponentSizeQuads + 1)
{}
bool IsValid()
{
return WeightData && WeightData->Num() == FMath::Square(Stride) && HeightData.Num() == FMath::Square(Stride);
}
FORCEINLINE float GetHeight(int32 IdxX, int32 IdxY)
{
return LandscapeDataAccess::GetLocalHeight(HeightData[IdxX + Stride*IdxY]);
}
FORCEINLINE float GetWeight(int32 IdxX, int32 IdxY)
{
return ((float)(*WeightData)[IdxX + Stride*IdxY]) / 255.f;
}
FORCEINLINE int32 GetStride()
{
return Stride;
}
private:
TSharedRef<FLandscapeComponentGrassData, ESPMode::ThreadSafe> GrassData;
TArray<uint16>& HeightData;
TArray<uint8>* WeightData;
int32 Stride;
};
template<uint32 Base>
static FORCEINLINE float Halton(uint32 Index)
{
float Result = 0.0f;
float InvBase = 1.0f / Base;
float Fraction = InvBase;
while( Index > 0 )
{
Result += ( Index % Base ) * Fraction;
Index /= Base;
Fraction *= InvBase;
}
return Result;
}
struct FAsyncGrassBuilder : public FGrassBuilderBase
{
FLandscapeComponentGrassAccess GrassData;
EGrassScaling Scaling;
FFloatInterval ScaleX;
FFloatInterval ScaleY;
FFloatInterval ScaleZ;
bool RandomRotation;
bool RandomScale;
bool AlignToSurface;
float PlacementJitter;
FRandomStream RandomStream;
FMatrix XForm;
FBox MeshBox;
int32 DesiredInstancesPerLeaf;
double RasterTime;
double BuildTime;
double InstanceTime;
int32 TotalInstances;
uint32 HaltonBaseIndex;
bool UseLandscapeLightmap;
FVector2D LightmapBaseBias;
FVector2D LightmapBaseScale;
FVector2D ShadowmapBaseBias;
FVector2D ShadowmapBaseScale;
FVector2D LightMapComponentBias;
FVector2D LightMapComponentScale;
// output
FStaticMeshInstanceData InstanceBuffer;
TArray<FClusterNode> ClusterTree;
int32 OutOcclusionLayerNum;
FAsyncGrassBuilder(ALandscapeProxy* Landscape, ULandscapeComponent* Component, const ULandscapeGrassType* GrassType, const FGrassVariety& GrassVariety, UHierarchicalInstancedStaticMeshComponent* HierarchicalInstancedStaticMeshComponent, int32 SqrtSubsections, int32 SubX, int32 SubY, uint32 InHaltonBaseIndex)
: FGrassBuilderBase(Landscape, Component, GrassVariety, SqrtSubsections, SubX, SubY)
, GrassData(Component, GrassType)
, Scaling(GrassVariety.Scaling)
, ScaleX(GrassVariety.ScaleX)
, ScaleY(GrassVariety.ScaleY)
, ScaleZ(GrassVariety.ScaleZ)
, RandomRotation(GrassVariety.RandomRotation)
, RandomScale(GrassVariety.ScaleX.Size() > 0 || GrassVariety.ScaleY.Size() > 0 || GrassVariety.ScaleZ.Size() > 0)
, AlignToSurface(GrassVariety.AlignToSurface)
, PlacementJitter(GrassVariety.PlacementJitter)
, RandomStream(HierarchicalInstancedStaticMeshComponent->InstancingRandomSeed)
, XForm(LandscapeToWorld * HierarchicalInstancedStaticMeshComponent->GetComponentTransform().ToMatrixWithScale().Inverse())
, MeshBox(GrassVariety.GrassMesh->GetBounds().GetBox())
, DesiredInstancesPerLeaf(HierarchicalInstancedStaticMeshComponent->DesiredInstancesPerLeaf())
, RasterTime(0)
, BuildTime(0)
, InstanceTime(0)
, TotalInstances(0)
, HaltonBaseIndex(InHaltonBaseIndex)
, UseLandscapeLightmap(GrassVariety.bUseLandscapeLightmap)
, LightmapBaseBias(FVector2D::ZeroVector)
, LightmapBaseScale(FVector2D::UnitVector)
, ShadowmapBaseBias(FVector2D::ZeroVector)
, ShadowmapBaseScale(FVector2D::UnitVector)
, LightMapComponentBias(FVector2D::ZeroVector)
, LightMapComponentScale(FVector2D::UnitVector)
// output
, InstanceBuffer(/*NeedsCPUAccess*/ false, /*bSupportsVertexHalfFloat*/ GVertexElementTypeSupport.IsSupported(VET_Half2))
, ClusterTree()
, OutOcclusionLayerNum(0)
{
bHaveValidData = bHaveValidData && GrassData.IsValid();
check(DesiredInstancesPerLeaf > 0);
if (UseLandscapeLightmap)
{
InitLandscapeLightmap(Component);
}
}
void InitLandscapeLightmap(ULandscapeComponent* Component)
{
const int32 SubsectionSizeQuads = Component->SubsectionSizeQuads;
const int32 NumSubsections = Component->NumSubsections;
const int32 LandscapeComponentSizeQuads = Component->ComponentSizeQuads;
const int32 StaticLightingLOD = Component->GetLandscapeProxy()->StaticLightingLOD;
const int32 ComponentSizeVerts = LandscapeComponentSizeQuads + 1;
const float LightMapRes = Component->StaticLightingResolution > 0.0f ? Component->StaticLightingResolution : Component->GetLandscapeProxy()->StaticLightingResolution;
const int32 LightingLOD = Component->GetLandscapeProxy()->StaticLightingLOD;
// Calculate mapping from landscape to lightmap space for mapping landscape grass to the landscape lightmap
// Copied from the calculation of FLandscapeUniformShaderParameters::LandscapeLightmapScaleBias in FLandscapeComponentSceneProxy::OnTransformChanged()
int32 PatchExpandCountX = 0;
int32 PatchExpandCountY = 0;
int32 DesiredSize = 1;
const float LightMapRatio = ::GetTerrainExpandPatchCount(LightMapRes, PatchExpandCountX, PatchExpandCountY, LandscapeComponentSizeQuads, (NumSubsections * (SubsectionSizeQuads + 1)), DesiredSize, LightingLOD);
const float LightmapLODScaleX = LightMapRatio / ((ComponentSizeVerts >> StaticLightingLOD) + 2 * PatchExpandCountX);
const float LightmapLODScaleY = LightMapRatio / ((ComponentSizeVerts >> StaticLightingLOD) + 2 * PatchExpandCountY);
const float LightmapBiasX = PatchExpandCountX * LightmapLODScaleX;
const float LightmapBiasY = PatchExpandCountY * LightmapLODScaleY;
const float LightmapScaleX = LightmapLODScaleX * (float)((ComponentSizeVerts >> StaticLightingLOD) - 1) / LandscapeComponentSizeQuads;
const float LightmapScaleY = LightmapLODScaleY * (float)((ComponentSizeVerts >> StaticLightingLOD) - 1) / LandscapeComponentSizeQuads;
LightMapComponentScale = FVector2D(LightmapScaleX, LightmapScaleY) / FVector2D(DrawScale);
LightMapComponentBias = FVector2D(LightmapBiasX, LightmapBiasY);
const FMeshMapBuildData* MeshMapBuildData = Component->GetMeshMapBuildData();
if (MeshMapBuildData != nullptr)
{
if (MeshMapBuildData->LightMap.IsValid())
{
LightmapBaseBias = MeshMapBuildData->LightMap->GetLightMap2D()->GetCoordinateBias();
LightmapBaseScale = MeshMapBuildData->LightMap->GetLightMap2D()->GetCoordinateScale();
}
if (MeshMapBuildData->ShadowMap.IsValid())
{
ShadowmapBaseBias = MeshMapBuildData->ShadowMap->GetShadowMap2D()->GetCoordinateBias();
ShadowmapBaseScale = MeshMapBuildData->ShadowMap->GetShadowMap2D()->GetCoordinateScale();
}
}
}
void SetInstance(int32 InstanceIndex, const FMatrix& InXForm, float RandomFraction)
{
if (UseLandscapeLightmap)
{
float InstanceX = InXForm.M[3][0];
float InstanceY = InXForm.M[3][1];
FVector2D NormalizedGrassCoordinate;
NormalizedGrassCoordinate.X = (InstanceX - ComponentOrigin.X) * LightMapComponentScale.X + LightMapComponentBias.X;
NormalizedGrassCoordinate.Y = (InstanceY - ComponentOrigin.Y) * LightMapComponentScale.Y + LightMapComponentBias.Y;
FVector2D LightMapCoordinate = NormalizedGrassCoordinate * LightmapBaseScale + LightmapBaseBias;
FVector2D ShadowMapCoordinate = NormalizedGrassCoordinate * ShadowmapBaseScale + ShadowmapBaseBias;
InstanceBuffer.SetInstance(InstanceIndex, InXForm, RandomStream.GetFraction(), LightMapCoordinate, ShadowMapCoordinate);
}
else
{
InstanceBuffer.SetInstance(InstanceIndex, InXForm, RandomStream.GetFraction());
}
}
FVector GetRandomScale() const
{
FVector Result(1.0f);
switch (Scaling)
{
case EGrassScaling::Uniform:
Result.X = ScaleX.Interpolate(RandomStream.GetFraction());
Result.Y = Result.X;
Result.Z = Result.X;
break;
case EGrassScaling::Free:
Result.X = ScaleX.Interpolate(RandomStream.GetFraction());
Result.Y = ScaleY.Interpolate(RandomStream.GetFraction());
Result.Z = ScaleZ.Interpolate(RandomStream.GetFraction());
break;
case EGrassScaling::LockXY:
Result.X = ScaleX.Interpolate(RandomStream.GetFraction());
Result.Y = Result.X;
Result.Z = ScaleZ.Interpolate(RandomStream.GetFraction());
break;
default:
check(0);
}
return Result;
}
void Build()
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassAsyncBuildTime);
check(bHaveValidData);
RasterTime -= FPlatformTime::Seconds();
float Div = 1.0f / float(SqrtMaxInstances);
TArray<FMatrix> InstanceTransforms;
if (HaltonBaseIndex)
{
if (Extent.X < 0)
{
Origin.X += Extent.X;
Extent.X *= -1.0f;
}
if (Extent.Y < 0)
{
Origin.Y += Extent.Y;
Extent.Y *= -1.0f;
}
int32 MaxNum = SqrtMaxInstances * SqrtMaxInstances;
InstanceTransforms.Reserve(MaxNum);
FVector DivExtent(Extent * Div);
for (int32 InstanceIndex = 0; InstanceIndex < MaxNum; InstanceIndex++)
{
float HaltonX = Halton<2>(InstanceIndex + HaltonBaseIndex);
float HaltonY = Halton<3>(InstanceIndex + HaltonBaseIndex);
FVector Location(Origin.X + HaltonX * Extent.X, Origin.Y + HaltonY * Extent.Y, 0.0f);
FVector LocationWithHeight;
float Weight = GetLayerWeightAtLocationLocal(Location, &LocationWithHeight);
bool bKeep = Weight > 0.0f && Weight >= RandomStream.GetFraction();
if (bKeep)
{
const FVector Scale = RandomScale ? GetRandomScale() : FVector(1);
const float Rot = RandomRotation ? RandomStream.GetFraction() * 360.0f : 0.0f;
const FMatrix BaseXForm = FScaleRotationTranslationMatrix(Scale, FRotator(0.0f, Rot, 0.0f), FVector::ZeroVector);
FMatrix OutXForm;
if (AlignToSurface)
{
FVector LocationWithHeightDX;
FVector LocationDX(Location);
LocationDX.X = FMath::Clamp<float>(LocationDX.X + (HaltonX < 0.5f ? DivExtent.X : -DivExtent.X), Origin.X, Origin.X + Extent.X);
GetLayerWeightAtLocationLocal(LocationDX, &LocationWithHeightDX, false);
FVector LocationWithHeightDY;
FVector LocationDY(Location);
LocationDY.Y = FMath::Clamp<float>(LocationDX.Y + (HaltonY < 0.5f ? DivExtent.Y : -DivExtent.Y), Origin.Y, Origin.Y + Extent.Y);
GetLayerWeightAtLocationLocal(LocationDY, &LocationWithHeightDY, false);
if (LocationWithHeight != LocationWithHeightDX && LocationWithHeight != LocationWithHeightDY)
{
FVector NewZ = ((LocationWithHeight - LocationWithHeightDX) ^ (LocationWithHeight - LocationWithHeightDY)).GetSafeNormal();
NewZ *= FMath::Sign(NewZ.Z);
const FVector NewX = (FVector(0, -1, 0) ^ NewZ).GetSafeNormal();
const FVector NewY = NewZ ^ NewX;
FMatrix Align = FMatrix(NewX, NewY, NewZ, FVector::ZeroVector);
OutXForm = (BaseXForm * Align).ConcatTranslation(LocationWithHeight) * XForm;
}
else
{
OutXForm = BaseXForm.ConcatTranslation(LocationWithHeight) * XForm;
}
}
else
{
OutXForm = BaseXForm.ConcatTranslation(LocationWithHeight) * XForm;
}
InstanceTransforms.Add(OutXForm);
}
}
if (InstanceTransforms.Num())
{
TotalInstances += InstanceTransforms.Num();
InstanceBuffer.AllocateInstances(InstanceTransforms.Num(), true);
for (int32 InstanceIndex = 0; InstanceIndex < InstanceTransforms.Num(); InstanceIndex++)
{
const FMatrix& OutXForm = InstanceTransforms[InstanceIndex];
SetInstance(InstanceIndex, OutXForm, RandomStream.GetFraction());
}
}
}
else
{
int32 NumKept = 0;
float MaxJitter1D = FMath::Clamp<float>(PlacementJitter, 0.0f, .99f) * Div * .5f;
FVector MaxJitter(MaxJitter1D, MaxJitter1D, 0.0f);
MaxJitter *= Extent;
Origin += Extent * (Div * 0.5f);
struct FInstanceLocal
{
FVector Pos;
bool bKeep;
};
TArray<FInstanceLocal> Instances;
Instances.AddUninitialized(SqrtMaxInstances * SqrtMaxInstances);
{
int32 InstanceIndex = 0;
for (int32 xStart = 0; xStart < SqrtMaxInstances; xStart++)
{
for (int32 yStart = 0; yStart < SqrtMaxInstances; yStart++)
{
FVector Location(Origin.X + float(xStart) * Div * Extent.X, Origin.Y + float(yStart) * Div * Extent.Y, 0.0f);
Location += FVector(RandomStream.GetFraction() * 2.0f - 1.0f, RandomStream.GetFraction() * 2.0f - 1.0f, 0.0f) * MaxJitter;
FInstanceLocal& Instance = Instances[InstanceIndex];
float Weight = GetLayerWeightAtLocationLocal(Location, &Instance.Pos);
Instance.bKeep = Weight > 0.0f && Weight >= RandomStream.GetFraction();
if (Instance.bKeep)
{
NumKept++;
}
InstanceIndex++;
}
}
}
if (NumKept)
{
InstanceTransforms.AddUninitialized(NumKept);
TotalInstances += NumKept;
{
InstanceBuffer.AllocateInstances(NumKept, true);
int32 InstanceIndex = 0;
int32 OutInstanceIndex = 0;
for (int32 xStart = 0; xStart < SqrtMaxInstances; xStart++)
{
for (int32 yStart = 0; yStart < SqrtMaxInstances; yStart++)
{
const FInstanceLocal& Instance = Instances[InstanceIndex];
if (Instance.bKeep)
{
const FVector Scale = RandomScale ? GetRandomScale() : FVector(1);
const float Rot = RandomRotation ? RandomStream.GetFraction() * 360.0f : 0.0f;
const FMatrix BaseXForm = FScaleRotationTranslationMatrix(Scale, FRotator(0.0f, Rot, 0.0f), FVector::ZeroVector);
FMatrix OutXForm;
if (AlignToSurface)
{
FVector PosX1 = xStart ? Instances[InstanceIndex - SqrtMaxInstances].Pos : Instance.Pos;
FVector PosX2 = (xStart + 1 < SqrtMaxInstances) ? Instances[InstanceIndex + SqrtMaxInstances].Pos : Instance.Pos;
FVector PosY1 = yStart ? Instances[InstanceIndex - 1].Pos : Instance.Pos;
FVector PosY2 = (yStart + 1 < SqrtMaxInstances) ? Instances[InstanceIndex + 1].Pos : Instance.Pos;
if (PosX1 != PosX2 && PosY1 != PosY2)
{
FVector NewZ = ((PosX1 - PosX2) ^ (PosY1 - PosY2)).GetSafeNormal();
NewZ *= FMath::Sign(NewZ.Z);
const FVector NewX = (FVector(0, -1, 0) ^ NewZ).GetSafeNormal();
const FVector NewY = NewZ ^ NewX;
FMatrix Align = FMatrix(NewX, NewY, NewZ, FVector::ZeroVector);
OutXForm = (BaseXForm * Align).ConcatTranslation(Instance.Pos) * XForm;
}
else
{
OutXForm = BaseXForm.ConcatTranslation(Instance.Pos) * XForm;
}
}
else
{
OutXForm = BaseXForm.ConcatTranslation(Instance.Pos) * XForm;
}
InstanceTransforms[OutInstanceIndex] = OutXForm;
SetInstance(OutInstanceIndex++, OutXForm, RandomStream.GetFraction());
}
InstanceIndex++;
}
}
}
}
}
int32 NumInstances = InstanceTransforms.Num();
if (NumInstances)
{
TArray<int32> SortedInstances;
TArray<int32> InstanceReorderTable;
UHierarchicalInstancedStaticMeshComponent::BuildTreeAnyThread(InstanceTransforms, MeshBox, ClusterTree, SortedInstances, InstanceReorderTable, OutOcclusionLayerNum, DesiredInstancesPerLeaf);
// in-place sort the instances
const uint32 InstanceStreamSize = InstanceBuffer.GetStride();
FInstanceStream32 SwapBuffer;
check(sizeof(SwapBuffer) >= InstanceStreamSize);
for (int32 FirstUnfixedIndex = 0; FirstUnfixedIndex < NumInstances; FirstUnfixedIndex++)
{
int32 LoadFrom = SortedInstances[FirstUnfixedIndex];
if (LoadFrom != FirstUnfixedIndex)
{
check(LoadFrom > FirstUnfixedIndex);
FMemory::Memcpy(&SwapBuffer, InstanceBuffer.GetInstanceWriteAddress(FirstUnfixedIndex), InstanceStreamSize);
FMemory::Memcpy(InstanceBuffer.GetInstanceWriteAddress(FirstUnfixedIndex), InstanceBuffer.GetInstanceWriteAddress(LoadFrom), InstanceStreamSize);
FMemory::Memcpy(InstanceBuffer.GetInstanceWriteAddress(LoadFrom), &SwapBuffer, InstanceStreamSize);
int32 SwapGoesTo = InstanceReorderTable[FirstUnfixedIndex];
check(SwapGoesTo > FirstUnfixedIndex);
check(SortedInstances[SwapGoesTo] == FirstUnfixedIndex);
SortedInstances[SwapGoesTo] = LoadFrom;
InstanceReorderTable[LoadFrom] = SwapGoesTo;
InstanceReorderTable[FirstUnfixedIndex] = FirstUnfixedIndex;
SortedInstances[FirstUnfixedIndex] = FirstUnfixedIndex;
}
}
}
}
FORCEINLINE_DEBUGGABLE float GetLayerWeightAtLocationLocal(const FVector& InLocation, FVector* OutLocation, bool bWeight = true)
{
// Find location
float TestX = InLocation.X / DrawScale.X - (float)SectionBase.X;
float TestY = InLocation.Y / DrawScale.Y - (float)SectionBase.Y;
// Find data
int32 X1 = FMath::FloorToInt(TestX);
int32 Y1 = FMath::FloorToInt(TestY);
int32 X2 = FMath::CeilToInt(TestX);
int32 Y2 = FMath::CeilToInt(TestY);
// Min is to prevent the sampling of the final column from overflowing
int32 IdxX1 = FMath::Min<int32>(X1, GrassData.GetStride() - 1);
int32 IdxY1 = FMath::Min<int32>(Y1, GrassData.GetStride() - 1);
int32 IdxX2 = FMath::Min<int32>(X2, GrassData.GetStride() - 1);
int32 IdxY2 = FMath::Min<int32>(Y2, GrassData.GetStride() - 1);
float LerpX = FMath::Fractional(TestX);
float LerpY = FMath::Fractional(TestY);
float Result = 0.0f;
if (bWeight)
{
// sample
float Sample11 = GrassData.GetWeight(IdxX1, IdxY1);
float Sample21 = GrassData.GetWeight(IdxX2, IdxY1);
float Sample12 = GrassData.GetWeight(IdxX1, IdxY2);
float Sample22 = GrassData.GetWeight(IdxX2, IdxY2);
// Bilinear interpolate
Result = FMath::Lerp(
FMath::Lerp(Sample11, Sample21, LerpX),
FMath::Lerp(Sample12, Sample22, LerpX),
LerpY);
}
{
// sample
float Sample11 = GrassData.GetHeight(IdxX1, IdxY1);
float Sample21 = GrassData.GetHeight(IdxX2, IdxY1);
float Sample12 = GrassData.GetHeight(IdxX1, IdxY2);
float Sample22 = GrassData.GetHeight(IdxX2, IdxY2);
OutLocation->X = InLocation.X - DrawScale.X * float(LandscapeSectionOffset.X);
OutLocation->Y = InLocation.Y - DrawScale.Y * float(LandscapeSectionOffset.Y);
// Bilinear interpolate
OutLocation->Z = DrawScale.Z * FMath::Lerp(
FMath::Lerp(Sample11, Sample21, LerpX),
FMath::Lerp(Sample12, Sample22, LerpX),
LerpY);
}
return Result;
}
};
void ALandscapeProxy::FlushGrassComponents(const TSet<ULandscapeComponent*>* OnlyForComponents, bool bFlushGrassMaps)
{
if (OnlyForComponents)
{
for (FCachedLandscapeFoliage::TGrassSet::TIterator Iter(FoliageCache.CachedGrassComps); Iter; ++Iter)
{
ULandscapeComponent* Component = (*Iter).Key.BasedOn.Get();
// if the weak pointer in the cache is invalid, we should kill them anyway
if (Component == nullptr || OnlyForComponents->Contains(Component))
{
UHierarchicalInstancedStaticMeshComponent *Used = (*Iter).Foliage.Get();
if (Used)
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassDestoryComp);
Used->ClearInstances();
Used->DetachFromComponent(FDetachmentTransformRules(EDetachmentRule::KeepRelative, false));
Used->DestroyComponent();
}
Iter.RemoveCurrent();
}
}
#if WITH_EDITOR
if (GIsEditor && bFlushGrassMaps)
{
for (ULandscapeComponent* Component : *OnlyForComponents)
{
Component->RemoveGrassMap();
}
}
#endif
}
else
{
// Clear old foliage component containers
FoliageComponents.Empty();
// Might as well clear the cache...
FoliageCache.ClearCache();
// Destroy any owned foliage components
TInlineComponentArray<UHierarchicalInstancedStaticMeshComponent*> FoliageComps;
GetComponents(FoliageComps);
for (UHierarchicalInstancedStaticMeshComponent* Component : FoliageComps)
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassDestoryComp);
Component->ClearInstances();
Component->DetachFromComponent(FDetachmentTransformRules(EDetachmentRule::KeepRelative, false));
Component->DestroyComponent();
}
TArray<USceneComponent*> AttachedFoliageComponents = RootComponent->GetAttachChildren().FilterByPredicate(
[](USceneComponent* Component)
{
return Cast<UHierarchicalInstancedStaticMeshComponent>(Component);
});
// Destroy any attached but un-owned foliage components
for (USceneComponent* Component : AttachedFoliageComponents)
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassDestoryComp);
CastChecked<UHierarchicalInstancedStaticMeshComponent>(Component)->ClearInstances();
Component->DetachFromComponent(FDetachmentTransformRules(EDetachmentRule::KeepRelative, false));
Component->DestroyComponent();
}
#if WITH_EDITOR
if (GIsEditor && bFlushGrassMaps)
{
// Clear GrassMaps
TInlineComponentArray<ULandscapeComponent*> LandComps;
GetComponents(LandComps);
for (ULandscapeComponent* Component : LandComps)
{
Component->RemoveGrassMap();
}
}
#endif
}
}
TArray<ULandscapeGrassType*> ALandscapeProxy::GetGrassTypes() const
{
TArray<ULandscapeGrassType*> GrassTypes;
if (LandscapeMaterial)
{
TArray<const UMaterialExpressionLandscapeGrassOutput*> GrassExpressions;
LandscapeMaterial->GetMaterial()->GetAllExpressionsOfType<UMaterialExpressionLandscapeGrassOutput>(GrassExpressions);
if (GrassExpressions.Num() > 0)
{
for (auto& Type : GrassExpressions[0]->GrassTypes)
{
GrassTypes.Add(Type.GrassType);
}
}
}
return GrassTypes;
}
#if WITH_EDITOR
int32 ALandscapeProxy::TotalComponentsNeedingGrassMapRender = 0;
int32 ALandscapeProxy::TotalTexturesToStreamForVisibleGrassMapRender = 0;
int32 ALandscapeProxy::TotalComponentsNeedingTextureBaking = 0;
#endif
void ALandscapeProxy::UpdateGrass(const TArray<FVector>& Cameras, bool bForceSync)
{
SCOPE_CYCLE_COUNTER(STAT_GrassUpdate);
if (CVarGrassEnable.GetValueOnAnyThread() > 0)
{
TArray<ULandscapeGrassType*> GrassTypes = GetGrassTypes();
float GuardBand = CVarGuardBandMultiplier.GetValueOnAnyThread();
float DiscardGuardBand = CVarGuardBandDiscardMultiplier.GetValueOnAnyThread();
bool bCullSubsections = CVarCullSubsections.GetValueOnAnyThread() > 0;
bool bDisableGPUCull = CVarDisableGPUCull.GetValueOnAnyThread() > 0;
int32 MaxInstancesPerComponent = FMath::Max<int32>(1024, CVarMaxInstancesPerComponent.GetValueOnAnyThread());
int32 MaxTasks = CVarMaxAsyncTasks.GetValueOnAnyThread();
UWorld* World = GetWorld();
if (World)
{
#if WITH_EDITOR
int32 RequiredTexturesNotStreamedIn = 0;
TSet<ULandscapeComponent*> ComponentsNeedingGrassMapRender;
TSet<UTexture2D*> CurrentForcedStreamedTextures;
TSet<UTexture2D*> DesiredForceStreamedTextures;
if (!World->IsGameWorld())
{
// see if we need to flush grass for any components
TSet<ULandscapeComponent*> FlushComponents;
for (auto Component : LandscapeComponents)
{
// check textures currently needing force streaming
if (Component->HeightmapTexture->bForceMiplevelsToBeResident)
{
CurrentForcedStreamedTextures.Add(Component->HeightmapTexture);
}
for (auto WeightmapTexture : Component->WeightmapTextures)
{
if (WeightmapTexture->bForceMiplevelsToBeResident)
{
CurrentForcedStreamedTextures.Add(WeightmapTexture);
}
}
if (Component->IsGrassMapOutdated())
{
FlushComponents.Add(Component);
}
if (GrassTypes.Num() > 0 || bBakeMaterialPositionOffsetIntoCollision)
{
if (Component->IsGrassMapOutdated() ||
!Component->GrassData->HasData())
{
ComponentsNeedingGrassMapRender.Add(Component);
}
}
}
if (FlushComponents.Num())
{
FlushGrassComponents(&FlushComponents);
}
}
#endif
int32 NumCompsCreated = 0;
for (int32 ComponentIndex = 0; ComponentIndex < LandscapeComponents.Num(); ComponentIndex++)
{
ULandscapeComponent* Component = LandscapeComponents[ComponentIndex];
// skip if we have no data and no way to generate it
if (World->IsGameWorld() && !Component->GrassData->HasData())
{
continue;
}
FBoxSphereBounds WorldBounds = Component->CalcBounds(Component->GetComponentTransform());
float MinDistanceToComp = Cameras.Num() ? MAX_flt : 0.0f;
for (auto& Pos : Cameras)
{
MinDistanceToComp = FMath::Min<float>(MinDistanceToComp, WorldBounds.ComputeSquaredDistanceFromBoxToPoint(Pos));
}
MinDistanceToComp = FMath::Sqrt(MinDistanceToComp);
for (auto GrassType : GrassTypes)
{
if (GrassType)
{
int32 GrassVarietyIndex = -1;
uint32 HaltonBaseIndex = 1;
for (auto& GrassVariety : GrassType->GrassVarieties)
{
GrassVarietyIndex++;
if (GrassVariety.GrassMesh && GrassVariety.GrassDensity > 0.0f && GrassVariety.EndCullDistance > 0)
{
float MustHaveDistance = GuardBand * (float)GrassVariety.EndCullDistance;
float DiscardDistance = DiscardGuardBand * (float)GrassVariety.EndCullDistance;
bool bUseHalton = !GrassVariety.bUseGrid;
if (!bUseHalton && MinDistanceToComp > DiscardDistance)
{
continue;
}
FGrassBuilderBase ForSubsectionMath(this, Component, GrassVariety);
int32 SqrtSubsections = 1;
if (ForSubsectionMath.bHaveValidData && ForSubsectionMath.SqrtMaxInstances > 0)
{
SqrtSubsections = FMath::Clamp<int32>(FMath::CeilToInt(float(ForSubsectionMath.SqrtMaxInstances) / FMath::Sqrt((float)MaxInstancesPerComponent)), 1, 16);
}
int32 MaxInstancesSub = FMath::Square(ForSubsectionMath.SqrtMaxInstances / SqrtSubsections);
if (bUseHalton && MinDistanceToComp > DiscardDistance)
{
HaltonBaseIndex += MaxInstancesSub * SqrtSubsections * SqrtSubsections;
continue;
}
FBox LocalBox = Component->CachedLocalBox;
FVector LocalExtentDiv = (LocalBox.Max - LocalBox.Min) * FVector(1.0f / float(SqrtSubsections), 1.0f / float(SqrtSubsections), 1.0f);
for (int32 SubX = 0; SubX < SqrtSubsections; SubX++)
{
for (int32 SubY = 0; SubY < SqrtSubsections; SubY++)
{
float MinDistanceToSubComp = MinDistanceToComp;
if (bCullSubsections && SqrtSubsections > 1)
{
FVector BoxMin;
BoxMin.X = LocalBox.Min.X + LocalExtentDiv.X * float(SubX);
BoxMin.Y = LocalBox.Min.Y + LocalExtentDiv.Y * float(SubY);
BoxMin.Z = LocalBox.Min.Z;
FVector BoxMax;
BoxMax.X = LocalBox.Min.X + LocalExtentDiv.X * float(SubX + 1);
BoxMax.Y = LocalBox.Min.Y + LocalExtentDiv.Y * float(SubY + 1);
BoxMax.Z = LocalBox.Max.Z;
FBox LocalSubBox(BoxMin, BoxMax);
FBox WorldSubBox = LocalSubBox.TransformBy(Component->GetComponentTransform());
MinDistanceToSubComp = Cameras.Num() ? MAX_flt : 0.0f;
for (auto& Pos : Cameras)
{
MinDistanceToSubComp = FMath::Min<float>(MinDistanceToSubComp, ComputeSquaredDistanceFromBoxToPoint(WorldSubBox.Min, WorldSubBox.Max, Pos));
}
MinDistanceToSubComp = FMath::Sqrt(MinDistanceToSubComp);
}
if (bUseHalton)
{
HaltonBaseIndex += MaxInstancesSub; // we are going to pre-increment this for all of the continues...however we need to subtract later if we actually do this sub
}
if (MinDistanceToSubComp > DiscardDistance)
{
continue;
}
FCachedLandscapeFoliage::FGrassComp NewComp;
NewComp.Key.BasedOn = Component;
NewComp.Key.GrassType = GrassType;
NewComp.Key.SqrtSubsections = SqrtSubsections;
NewComp.Key.CachedMaxInstancesPerComponent = MaxInstancesPerComponent;
NewComp.Key.SubsectionX = SubX;
NewComp.Key.SubsectionY = SubY;
NewComp.Key.NumVarieties = GrassType->GrassVarieties.Num();
NewComp.Key.VarietyIndex = GrassVarietyIndex;
{
FCachedLandscapeFoliage::FGrassComp* Existing = FoliageCache.CachedGrassComps.Find(NewComp.Key);
if (Existing || MinDistanceToSubComp > MustHaveDistance)
{
if (Existing)
{
Existing->Touch();
}
continue;
}
}
if (!bForceSync && (NumCompsCreated || AsyncFoliageTasks.Num() >= MaxTasks))
{
continue; // one per frame, but we still want to touch the existing ones
}
#if WITH_EDITOR
// render grass data if we don't have any
if (!Component->GrassData->HasData())
{
if (!Component->CanRenderGrassMap())
{
// we can't currently render grassmaps (eg shaders not compiled)
continue;
}
else if (!Component->AreTexturesStreamedForGrassMapRender())
{
// we're ready to generate but our textures need streaming in
DesiredForceStreamedTextures.Add(Component->HeightmapTexture);
for (auto WeightmapTexture : Component->WeightmapTextures)
{
DesiredForceStreamedTextures.Add(WeightmapTexture);
}
RequiredTexturesNotStreamedIn++;
continue;
}
QUICK_SCOPE_CYCLE_COUNTER(STAT_GrassRenderToTexture);
Component->RenderGrassMap();
ComponentsNeedingGrassMapRender.Remove(Component);
}
#endif
NumCompsCreated++;
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassStartComp);
int32 FolSeed = FCrc::StrCrc32((GrassType->GetName() + Component->GetName() + FString::Printf(TEXT("%d %d %d"), SubX, SubY, GrassVarietyIndex)).GetCharArray().GetData());
if (FolSeed == 0)
{
FolSeed++;
}
// Do not record the transaction of creating temp component for visualizations
ClearFlags(RF_Transactional);
bool PreviousPackageDirtyFlag = GetOutermost()->IsDirty();
UHierarchicalInstancedStaticMeshComponent* HierarchicalInstancedStaticMeshComponent;
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_GrassCreateComp);
HierarchicalInstancedStaticMeshComponent = NewObject<UHierarchicalInstancedStaticMeshComponent>(this, NAME_None, RF_Transient);
}
NewComp.Foliage = HierarchicalInstancedStaticMeshComponent;
FoliageCache.CachedGrassComps.Add(NewComp);
HierarchicalInstancedStaticMeshComponent->Mobility = EComponentMobility::Static;
HierarchicalInstancedStaticMeshComponent->bCastStaticShadow = false;
HierarchicalInstancedStaticMeshComponent->SetStaticMesh(GrassVariety.GrassMesh);
HierarchicalInstancedStaticMeshComponent->MinLOD = GrassVariety.MinLOD;
HierarchicalInstancedStaticMeshComponent->bSelectable = false;
HierarchicalInstancedStaticMeshComponent->bHasPerInstanceHitProxies = false;
HierarchicalInstancedStaticMeshComponent->bReceivesDecals = GrassVariety.bReceivesDecals;
static FName NoCollision(TEXT("NoCollision"));
HierarchicalInstancedStaticMeshComponent->SetCollisionProfileName(NoCollision);
HierarchicalInstancedStaticMeshComponent->bDisableCollision = true;
HierarchicalInstancedStaticMeshComponent->SetCanEverAffectNavigation(false);
HierarchicalInstancedStaticMeshComponent->InstancingRandomSeed = FolSeed;
HierarchicalInstancedStaticMeshComponent->LightingChannels = GrassVariety.LightingChannels;
HierarchicalInstancedStaticMeshComponent->KeepInstanceBufferCPUAccess = true;
const FMeshMapBuildData* MeshMapBuildData = Component->GetMeshMapBuildData();
if (GrassVariety.bUseLandscapeLightmap
&& GrassVariety.GrassMesh->GetNumLODs() > 0
&& MeshMapBuildData
&& MeshMapBuildData->LightMap)
{
HierarchicalInstancedStaticMeshComponent->SetLODDataCount(GrassVariety.GrassMesh->GetNumLODs(), GrassVariety.GrassMesh->GetNumLODs());
FLightMapRef GrassLightMap = new FLandscapeGrassLightMap(*MeshMapBuildData->LightMap->GetLightMap2D());
FShadowMapRef GrassShadowMap = MeshMapBuildData->ShadowMap ? new FLandscapeGrassShadowMap(*MeshMapBuildData->ShadowMap->GetShadowMap2D()) : nullptr;
for (auto& LOD : HierarchicalInstancedStaticMeshComponent->LODData)
{
LOD.OverrideMapBuildData = MakeUnique<FMeshMapBuildData>();
LOD.OverrideMapBuildData->LightMap = GrassLightMap;
LOD.OverrideMapBuildData->ShadowMap = GrassShadowMap;
}
}
if (!Cameras.Num() || bDisableGPUCull)
{
// if we don't have any cameras, then we are rendering landscape LOD materials or somesuch and we want to disable culling
HierarchicalInstancedStaticMeshComponent->InstanceStartCullDistance = 0;
HierarchicalInstancedStaticMeshComponent->InstanceEndCullDistance = 0;
}
else
{
HierarchicalInstancedStaticMeshComponent->InstanceStartCullDistance = GrassVariety.StartCullDistance;
HierarchicalInstancedStaticMeshComponent->InstanceEndCullDistance = GrassVariety.EndCullDistance;
}
//@todo - take the settings from a UFoliageType object. For now, disable distance field lighting on grass so we don't hitch.
HierarchicalInstancedStaticMeshComponent->bAffectDistanceFieldLighting = false;
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_GrassAttachComp);
HierarchicalInstancedStaticMeshComponent->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
FTransform DesiredTransform = GetRootComponent()->GetComponentTransform();
DesiredTransform.RemoveScaling();
HierarchicalInstancedStaticMeshComponent->SetWorldTransform(DesiredTransform);
FoliageComponents.Add(HierarchicalInstancedStaticMeshComponent);
}
FAsyncGrassBuilder* Builder;
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_GrassCreateBuilder);
uint32 HaltonIndexForSub = 0;
if (bUseHalton)
{
check(HaltonBaseIndex > (uint32)MaxInstancesSub);
HaltonIndexForSub = HaltonBaseIndex - (uint32)MaxInstancesSub;
}
Builder = new FAsyncGrassBuilder(this, Component, GrassType, GrassVariety, HierarchicalInstancedStaticMeshComponent, SqrtSubsections, SubX, SubY, HaltonIndexForSub);
}
if (Builder->bHaveValidData)
{
FAsyncTask<FAsyncGrassTask>* Task = new FAsyncTask<FAsyncGrassTask>(Builder, NewComp.Key, HierarchicalInstancedStaticMeshComponent);
Task->StartBackgroundTask();
AsyncFoliageTasks.Add(Task);
}
else
{
delete Builder;
}
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_GrassRegisterComp);
HierarchicalInstancedStaticMeshComponent->RegisterComponent();
}
SetFlags(RF_Transactional);
GetOutermost()->SetDirtyFlag(PreviousPackageDirtyFlag);
}
}
}
}
}
}
}
#if WITH_EDITOR
TotalTexturesToStreamForVisibleGrassMapRender -= NumTexturesToStreamForVisibleGrassMapRender;
NumTexturesToStreamForVisibleGrassMapRender = RequiredTexturesNotStreamedIn;
TotalTexturesToStreamForVisibleGrassMapRender += NumTexturesToStreamForVisibleGrassMapRender;
{
int32 NumComponentsRendered = 0;
int32 NumComponentsUnableToRender = 0;
if ((GrassTypes.Num() > 0 && CVarPrerenderGrassmaps.GetValueOnAnyThread() > 0) || bBakeMaterialPositionOffsetIntoCollision)
{
// try to render some grassmaps
TArray<ULandscapeComponent*> ComponentsToRender;
for (auto Component : ComponentsNeedingGrassMapRender)
{
if (Component->CanRenderGrassMap())
{
if (Component->AreTexturesStreamedForGrassMapRender())
{
// We really want to throttle the number based on component size.
if (NumComponentsRendered <= 4)
{
ComponentsToRender.Add(Component);
NumComponentsRendered++;
}
}
else
if (TotalTexturesToStreamForVisibleGrassMapRender == 0)
{
// Force stream in other heightmaps but only if we're not waiting for the textures
// near the camera to stream in
DesiredForceStreamedTextures.Add(Component->HeightmapTexture);
for (auto WeightmapTexture : Component->WeightmapTextures)
{
DesiredForceStreamedTextures.Add(WeightmapTexture);
}
}
}
else
{
NumComponentsUnableToRender++;
}
}
if (ComponentsToRender.Num())
{
RenderGrassMaps(ComponentsToRender, GrassTypes);
MarkPackageDirty();
}
}
TotalComponentsNeedingGrassMapRender -= NumComponentsNeedingGrassMapRender;
NumComponentsNeedingGrassMapRender = ComponentsNeedingGrassMapRender.Num() - NumComponentsRendered - NumComponentsUnableToRender;
TotalComponentsNeedingGrassMapRender += NumComponentsNeedingGrassMapRender;
// Update resident flags
for (auto Texture : DesiredForceStreamedTextures.Difference(CurrentForcedStreamedTextures))
{
Texture->bForceMiplevelsToBeResident = true;
}
for (auto Texture : CurrentForcedStreamedTextures.Difference(DesiredForceStreamedTextures))
{
Texture->bForceMiplevelsToBeResident = false;
}
}
#endif
}
}
static TSet<UHierarchicalInstancedStaticMeshComponent *> StillUsed;
StillUsed.Empty(256);
{
// trim cached items based on time, pending and emptiness
double OldestToKeepTime = FPlatformTime::Seconds() - CVarMinTimeToKeepGrass.GetValueOnGameThread();
uint32 OldestToKeepFrame = GFrameNumber - CVarMinFramesToKeepGrass.GetValueOnGameThread();
for (FCachedLandscapeFoliage::TGrassSet::TIterator Iter(FoliageCache.CachedGrassComps); Iter; ++Iter)
{
const FCachedLandscapeFoliage::FGrassComp& GrassItem = *Iter;
UHierarchicalInstancedStaticMeshComponent *Used = GrassItem.Foliage.Get();
bool bOld =
!GrassItem.Pending &&
(
!GrassItem.Key.BasedOn.Get() ||
!GrassItem.Key.GrassType.Get() ||
!Used ||
(GrassItem.LastUsedFrameNumber < OldestToKeepFrame && GrassItem.LastUsedTime < OldestToKeepTime)
);
if (bOld)
{
Iter.RemoveCurrent();
}
else if (Used)
{
StillUsed.Add(Used);
}
}
}
{
// delete components that are no longer used
for (UActorComponent* ActorComponent : GetComponents())
{
UHierarchicalInstancedStaticMeshComponent* HComponent = Cast<UHierarchicalInstancedStaticMeshComponent>(ActorComponent);
if (HComponent && !StillUsed.Contains(HComponent))
{
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassDestoryComp);
HComponent->ClearInstances();
HComponent->DetachFromComponent(FDetachmentTransformRules(EDetachmentRule::KeepRelative, false));
HComponent->DestroyComponent();
FoliageComponents.Remove(HComponent);
}
if (!bForceSync)
{
break; // one per frame is fine
}
}
}
}
{
// finish async tasks
for (int32 Index = 0; Index < AsyncFoliageTasks.Num(); Index++)
{
FAsyncTask<FAsyncGrassTask>* Task = AsyncFoliageTasks[Index];
if (bForceSync)
{
Task->EnsureCompletion();
}
if (Task->IsDone())
{
SCOPE_CYCLE_COUNTER(STAT_FoliageGrassEndComp);
FAsyncGrassTask& Inner = Task->GetTask();
AsyncFoliageTasks.RemoveAtSwap(Index--);
UHierarchicalInstancedStaticMeshComponent* HierarchicalInstancedStaticMeshComponent = Inner.Foliage.Get();
if (HierarchicalInstancedStaticMeshComponent && StillUsed.Contains(HierarchicalInstancedStaticMeshComponent))
{
if (Inner.Builder->InstanceBuffer.NumInstances())
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FoliageGrassEndComp_AcceptPrebuiltTree);
if (!HierarchicalInstancedStaticMeshComponent->PerInstanceRenderData.IsValid())
{
HierarchicalInstancedStaticMeshComponent->InitPerInstanceRenderData(true, &Inner.Builder->InstanceBuffer);
}
else
{
HierarchicalInstancedStaticMeshComponent->PerInstanceRenderData->UpdateFromPreallocatedData(HierarchicalInstancedStaticMeshComponent, Inner.Builder->InstanceBuffer, HierarchicalInstancedStaticMeshComponent->KeepInstanceBufferCPUAccess);
}
HierarchicalInstancedStaticMeshComponent->AcceptPrebuiltTree(Inner.Builder->ClusterTree, Inner.Builder->OutOcclusionLayerNum);
if (bForceSync && GetWorld())
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FoliageGrassEndComp_SyncUpdate);
HierarchicalInstancedStaticMeshComponent->RecreateRenderState_Concurrent();
}
}
}
FCachedLandscapeFoliage::FGrassComp* Existing = FoliageCache.CachedGrassComps.Find(Inner.Key);
if (Existing)
{
Existing->Pending = false;
Existing->Touch();
}
delete Task;
if (!bForceSync)
{
break; // one per frame is fine
}
}
}
}
}
FAsyncGrassTask::FAsyncGrassTask(FAsyncGrassBuilder* InBuilder, const FCachedLandscapeFoliage::FGrassCompKey& InKey, UHierarchicalInstancedStaticMeshComponent* InFoliage)
: Builder(InBuilder)
, Key(InKey)
, Foliage(InFoliage)
{
}
void FAsyncGrassTask::DoWork()
{
Builder->Build();
}
FAsyncGrassTask::~FAsyncGrassTask()
{
delete Builder;
}
static void FlushGrass(const TArray<FString>& Args)
{
for (ALandscapeProxy* Landscape : TObjectRange<ALandscapeProxy>(RF_ClassDefaultObject | RF_ArchetypeObject, true, EInternalObjectFlags::PendingKill))
{
Landscape->FlushGrassComponents();
}
}
static void FlushGrassPIE(const TArray<FString>& Args)
{
for (ALandscapeProxy* Landscape : TObjectRange<ALandscapeProxy>(RF_ClassDefaultObject | RF_ArchetypeObject, true, EInternalObjectFlags::PendingKill))
{
Landscape->FlushGrassComponents(nullptr, false);
}
}
static FAutoConsoleCommand FlushGrassCmd(
TEXT("grass.FlushCache"),
TEXT("Flush the grass cache, debugging."),
FConsoleCommandWithArgsDelegate::CreateStatic(&FlushGrass)
);
static FAutoConsoleCommand FlushGrassCmdPIE(
TEXT("grass.FlushCachePIE"),
TEXT("Flush the grass cache, debugging."),
FConsoleCommandWithArgsDelegate::CreateStatic(&FlushGrassPIE)
);
#undef LOCTEXT_NAMESPACE
| 34.811869 | 310 | 0.739194 | windystrife |
d986bd6f2e24f717ba44765c9c9857ef8aa460dc | 2,074 | cpp | C++ | dbms/src/Functions/Conditional/NullMapBuilder.cpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | null | null | null | dbms/src/Functions/Conditional/NullMapBuilder.cpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | null | null | null | dbms/src/Functions/Conditional/NullMapBuilder.cpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 2 | 2018-11-29T11:15:02.000Z | 2019-04-12T16:56:31.000Z | #include <Functions/Conditional/NullMapBuilder.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnNullable.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
namespace Conditional
{
Block NullMapBuilder::empty_block;
void NullMapBuilder::init(const ColumnNumbers & args)
{
null_map = std::make_shared<ColumnUInt8>(row_count);
cols_properties.resize(block.columns());
for (const auto & arg : args)
{
const auto & col = *block.getByPosition(arg).column;
if (col.isNullable())
cols_properties[arg] = IS_NULLABLE;
else if (col.isNull())
cols_properties[arg] = IS_NULL;
else
cols_properties[arg] = IS_ORDINARY;
}
}
void NullMapBuilder::update(size_t index, size_t row)
{
const IColumn & from = *block.getByPosition(index).column;
bool is_null;
auto property = cols_properties[index];
if (property == IS_NULL)
is_null = true;
else if (property == IS_NULLABLE)
{
const auto & nullable_col = static_cast<const ColumnNullable &>(from);
is_null = nullable_col.isNullAt(row);
}
else if (property == IS_ORDINARY)
is_null = false;
else
throw Exception{"NullMapBuilder: internal error", ErrorCodes::LOGICAL_ERROR};
auto & null_map_data = static_cast<ColumnUInt8 &>(*null_map).getData();
null_map_data[row] = is_null ? 1 : 0;
}
void NullMapBuilder::build(size_t index)
{
const IColumn & from = *block.getByPosition(index).column;
if (from.isNull())
null_map = std::make_shared<ColumnUInt8>(row_count, 1);
else if (from.isNullable())
{
const auto & nullable_col = static_cast<const ColumnNullable &>(from);
null_map = nullable_col.getNullMapColumn();
}
else
null_map = std::make_shared<ColumnUInt8>(row_count, 0);
}
}
}
| 26.935065 | 89 | 0.600771 | 189569400 |
d98c96eea7780ad16bcfa4826a721d160ad83918 | 669 | cpp | C++ | P1816.cpp | daily-boj/SkyLightQP | 5038819b6ad31f94d84a66c7679c746a870bb857 | [
"Unlicense"
] | 6 | 2020-04-08T09:05:38.000Z | 2022-01-20T08:09:48.000Z | P1816.cpp | daily-boj/SkyLightQP | 5038819b6ad31f94d84a66c7679c746a870bb857 | [
"Unlicense"
] | null | null | null | P1816.cpp | daily-boj/SkyLightQP | 5038819b6ad31f94d84a66c7679c746a870bb857 | [
"Unlicense"
] | 1 | 2020-05-23T21:17:10.000Z | 2020-05-23T21:17:10.000Z | #include <iostream>
#define MAX 1000001
typedef long long ll;
using namespace std;
int prime[MAX] = {};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
for (int i = 2; i < MAX; ++i) {
if (prime[i]) continue;
for(int j = 2 * i; j <= MAX; j += i) {
prime[j] = 1;
}
}
int T; cin >> T;
while (T--) {
int flag = 0;
ll a; cin >> a;
for (int i = 2; i < MAX; ++i) {
if (flag == 0 && a % i == 0) {
cout << "NO\n";
flag = 1;
}
}
if (flag == 0) cout << "YES\n";
}
return 0;
} | 18.583333 | 46 | 0.402093 | daily-boj |
d98df8b20431890f8718821f8f45ab4df72bd8ca | 1,164 | cpp | C++ | LeetCode/494. Target Sum.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | 2 | 2021-04-13T00:19:56.000Z | 2021-04-13T01:19:45.000Z | LeetCode/494. Target Sum.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | null | null | null | LeetCode/494. Target Sum.cpp | Joon7891/Competitive-Programming | d860b7ad932cd5a6fb91fdc8c53101da57f4a408 | [
"MIT"
] | 1 | 2020-08-26T12:36:08.000Z | 2020-08-26T12:36:08.000Z | class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
set<int> s;
vector<int> cur;
map<int, int> freq;
s.insert(nums[0]);
s.insert(-nums[0]);
freq[nums[0]] = 1;
freq[-nums[0]] = 1;
cur.push_back(nums[0]);
cur.push_back(-nums[0]);
for (int i = 1; i < nums.size(); i++){
set<int> newS;
vector<int> newCur;
map<int, int> newFreq;
for (int c : cur){
newFreq[c + nums[i]] += freq[c];
newFreq[c - nums[i]] += freq[c];
if (newS.find(c + nums[i]) == newS.end()){
newS.insert(c + nums[i]);
newCur.push_back(c + nums[i]);
}
if (newS.find(c - nums[i]) == newS.end()){
newS.insert(c - nums[i]);
newCur.push_back(c - nums[i]);
}
}
s = newS;
cur = newCur;
freq = newFreq;
}
return freq[S];
}
}; | 27.714286 | 58 | 0.366838 | Joon7891 |
d98f915b5f9d0dff635e1231a5cb986e32b52bc6 | 4,243 | cpp | C++ | Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/RESceneUtils.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/RESceneUtils.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Modules/REPlatform/Sources/REPlatform/Scene/Private/Utils/RESceneUtils.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "REPlatform/Scene/Utils/RESceneUtils.h"
#include <FileSystem/FileSystem.h>
#include <Logger/Logger.h>
#include <Render/Renderer.h>
#include <Render/RenderHelper.h>
#include <Render/RHI/rhi_Public.h>
#include <Utils/StringFormat.h>
namespace DAVA
{
void RESceneUtils::CleanFolder(const FilePath& folderPathname)
{
bool ret = FileSystem::Instance()->DeleteDirectory(folderPathname);
if (!ret)
{
bool folderExists = FileSystem::Instance()->IsDirectory(folderPathname);
if (folderExists)
{
Logger::Error("[CleanFolder] ret = %d, folder = %s", ret, folderPathname.GetAbsolutePathname().c_str());
}
}
}
void RESceneUtils::SetInFolder(const FilePath& folderPathname)
{
DVASSERT(folderPathname.IsDirectoryPathname());
dataSourceFolder = folderPathname;
}
void RESceneUtils::SetOutFolder(const FilePath& folderPathname)
{
DVASSERT(folderPathname.IsDirectoryPathname());
dataFolder = folderPathname;
}
bool RESceneUtils::CopyFile(const FilePath& filePathname)
{
String workingPathname = filePathname.GetRelativePathname(dataSourceFolder);
PrepareFolderForCopyFile(workingPathname);
bool retCopy = FileSystem::Instance()->CopyFile(dataSourceFolder + workingPathname, dataFolder + workingPathname);
if (!retCopy)
{
Logger::Error("Can't copy %s from %s to %s",
workingPathname.c_str(),
dataSourceFolder.GetAbsolutePathname().c_str(),
dataFolder.GetAbsolutePathname().c_str());
}
return retCopy;
}
void RESceneUtils::PrepareFolderForCopyFile(const String& filename)
{
FilePath newFolderPath = (dataFolder + filename).GetDirectory();
if (!FileSystem::Instance()->IsDirectory(newFolderPath))
{
FileSystem::eCreateDirectoryResult retCreate = FileSystem::Instance()->CreateDirectory(newFolderPath, true);
if (FileSystem::DIRECTORY_CANT_CREATE == retCreate)
{
Logger::Error("Can't create folder %s", newFolderPath.GetAbsolutePathname().c_str());
}
}
FileSystem::Instance()->DeleteFile(dataFolder + filename);
}
FilePath RESceneUtils::GetNewFilePath(const FilePath& oldPathname) const
{
String workingPathname = oldPathname.GetRelativePathname(dataSourceFolder);
return dataFolder + workingPathname;
}
void RESceneUtils::AddFile(const FilePath& sourcePath)
{
String workingPathname = sourcePath.GetRelativePathname(dataSourceFolder);
FilePath destinationPath = dataFolder + workingPathname;
if (sourcePath != destinationPath)
{
DVASSERT(!sourcePath.IsEmpty());
DVASSERT(!destinationPath.IsEmpty());
filesForCopy[sourcePath] = destinationPath;
}
}
void RESceneUtils::CopyFiles()
{
PrepareDestination();
auto endIt = filesForCopy.end();
for (auto it = filesForCopy.begin(); it != endIt; ++it)
{
bool retCopy = false;
if (FileSystem::Instance()->Exists(it->first))
{
FileSystem::Instance()->DeleteFile(it->second);
retCopy = FileSystem::Instance()->CopyFile(it->first, it->second);
}
if (!retCopy)
{
Logger::Error("Can't copy %s to %s",
it->first.GetAbsolutePathname().c_str(),
it->second.GetAbsolutePathname().c_str());
}
}
}
void RESceneUtils::PrepareDestination()
{
Set<FilePath> folders;
Map<FilePath, FilePath>::const_iterator endMapIt = filesForCopy.end();
for (Map<FilePath, FilePath>::const_iterator it = filesForCopy.begin(); it != endMapIt; ++it)
{
folders.insert(it->second.GetDirectory());
}
Set<FilePath>::const_iterator endSetIt = folders.end();
for (Set<FilePath>::const_iterator it = folders.begin(); it != endSetIt; ++it)
{
if (!FileSystem::Instance()->Exists(*it))
{
FileSystem::eCreateDirectoryResult retCreate = FileSystem::Instance()->CreateDirectory((*it), true);
if (FileSystem::DIRECTORY_CANT_CREATE == retCreate)
{
Logger::Error("Can't create folder %s", (*it).GetAbsolutePathname().c_str());
}
}
}
}
} // namespace DAVA
| 30.746377 | 118 | 0.657318 | stinvi |
d99150de49d2059391a435d301295a0d27fea848 | 6,834 | hpp | C++ | src/asio_cares/include/asio_cares/channel.hpp | RobertLeahy/ASIO-C-ARES | f62150d4c5467396ac79fade11c6885cd5fe942c | [
"Unlicense"
] | 5 | 2019-03-30T17:42:31.000Z | 2021-07-02T18:48:05.000Z | src/asio_cares/include/asio_cares/channel.hpp | RobertLeahy/ASIO-C-ARES | f62150d4c5467396ac79fade11c6885cd5fe942c | [
"Unlicense"
] | null | null | null | src/asio_cares/include/asio_cares/channel.hpp | RobertLeahy/ASIO-C-ARES | f62150d4c5467396ac79fade11c6885cd5fe942c | [
"Unlicense"
] | 3 | 2019-01-30T03:43:58.000Z | 2020-03-04T04:01:55.000Z | /**
* \file
*/
#pragma once
#include <ares.h>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/system/error_code.hpp>
#include <mpark/variant.hpp>
#include <utility>
#include <vector>
namespace asio_cares {
/**
* Encapsulates a libcares channel and the state
* required for it to interoperate with Boost.Asio.
*/
class channel {
public:
channel () = delete;
channel (const channel &) = delete;
channel (channel &&) = delete;
channel & operator = (const channel &) = delete;
channel & operator = (channel &&) = delete;
/**
* Creates a new channel object by calling
* `ares_init`.
*
* \param [in] ios
* The `io_service` which shall be used for
* asynchronous operations. This reference must
* remain valid for the lifetime of the object.
*/
explicit channel (boost::asio::io_service & ios);
/**
* Creates a new channel object by calling
* `ares_init_options`.
*
* \param [in] options
* An `ares_options` object giving the options
* to pass as the second argument to `ares_init_options`.
* \param [in] optmask
* An integer giving the mask to pass as the
* third argument to `ares_init_options`.
* \param [in] ios
* The `io_service` which shall be used for
* asynchronous operations. This reference must
* remain valid for the lifetime of the object.
*/
channel (const ares_options & options, int optmask, boost::asio::io_service & ios);
/**
* Cleans up a channel object.
*/
~channel () noexcept;
/**
* Retrieves the managed `io_service`.
*
* \return
* A reference to an `io_service` object.
*/
boost::asio::io_service & get_io_service () noexcept;
/**
* All operations on a channel are conceptually
* operations on the underlying `ares_channel`
* which are not thread safe, accordingly a
* `boost::asio::strand` is used to ensure the
* `ares_channel` is only accessed by one thread
* of execution at a time. This method retrieves
* that `boost::asio::strand` object.
*
* \return
* A reference to a `strand`.
*/
boost::asio::strand & get_strand () noexcept;
/**
* Operations on a channel have timeouts. This
* method retrieves the `boost::asio::deadline_timer`
* used to track those timeouts.
*
* \return
* A reference to a `deadline_timer`.
*/
boost::asio::deadline_timer & get_timer () noexcept;
private:
using socket_type = mpark::variant<boost::asio::ip::tcp::socket, boost::asio::ip::udp::socket>;
template <typename Function>
static constexpr auto is_nothrow_invocable = noexcept(std::declval<Function>()(std::declval<boost::asio::ip::tcp::socket &>())) &&
noexcept(std::declval<Function>()(std::declval<boost::asio::ip::udp::socket &>()));
public:
/**
* The type used to represent a socket when
* it is acquired.
*
* In addition to making a certain socket
* accessible alse releases the socket back
* to the associated \ref channel once its
* lifetime ends.
*/
class socket_guard {
public:
socket_guard () = delete;
socket_guard (const socket_guard &) = delete;
socket_guard & operator = (const socket_guard &) = delete;
socket_guard & operator = (socket_guard &&) = delete;
socket_guard (socket_type &, channel &) noexcept;
socket_guard (socket_guard &&) noexcept;
~socket_guard () noexcept;
/**
* Provides access to the underlying Boost.Asio
* socket object by invoking a provided function
* object with the socket as its sole argument.
*
* Since libcares sockets may be TCP or UDP
* the provided function object must accept
* either `boost::asio::ip::tcp::socket` or
* `boost::asio::ip::udp::socket`.
*
* \tparam Function
* The type of function object.
*
* \param [in] function
* The function object.
*/
template <typename Function>
void unwrap (Function && function) noexcept(is_nothrow_invocable<Function>) {
assert(socket_);
mpark::visit(function, *socket_);
}
private:
socket_type * socket_;
channel * channel_;
};
/**
* Acquires a socket.
*
* Acquiring a socket which has already been acquired
* and not yet released results in undefined behavior.
*
* Once a socket has been acquired it cannot be closed
* by libcares until it is released. If libcares attempts
* to close it while it is acquired the closure shall be
* deferred until it is released.
*
* \param [in] socket
* The libcares handle for the socket to acquire.
*
* \return
* A \ref socket_guard which shall release the
* socket when it goes out of scope and through
* which the socket may be accessed.
*/
socket_guard acquire_socket (ares_socket_t socket) noexcept;
/**
* Retrieves the managed `ares_channel` object.
*
* \return
* An `ares_channel` object.
*/
operator ares_channel () noexcept;
/**
* Invokes a certain function object for each
* socket currently in use by the channel.
*
* Due to the fact libcares uses both TCP and
* UDP sockets the provided function object must
* be invocable with both `boost::asio::ip::tcp::socket`
* and `boost::asio::ip::udp::socket` objects.
*
* \tparam Function
* The type of function object to invoke.
*
* \param [in] function
* The function object to invoke.
*/
template <typename Function>
void for_each_socket (Function && function) noexcept(is_nothrow_invocable<Function>) {
for (auto && state : sockets_) mpark::visit(function, state.socket);
}
private:
class socket_state {
public:
socket_state () = delete;
socket_state (const socket_state &) = delete;
socket_state (socket_state &&) = default;
socket_state & operator = (const socket_state &) = delete;
socket_state & operator = (socket_state &&) = default;
explicit socket_state (socket_type);
socket_type socket;
bool acquired;
bool closed;
};
void release_socket (int) noexcept;
using sockets_collection_type = std::vector<socket_state>;
template <typename T>
sockets_collection_type::iterator insertion_point (const T &) noexcept;
template <typename T>
sockets_collection_type::iterator find (const T &) noexcept;
boost::asio::ip::tcp::socket tcp_socket (bool, boost::system::error_code &) noexcept;
boost::asio::ip::udp::socket udp_socket (bool, boost::system::error_code &) noexcept;
socket_type socket (bool, bool, boost::system::error_code &) noexcept;
static ares_socket_t socket (int, int, int, void *) noexcept;
static int close (ares_socket_t, void *) noexcept;
void init () noexcept;
ares_socket_functions funcs_;
ares_channel channel_;
boost::asio::strand strand_;
sockets_collection_type sockets_;
boost::asio::deadline_timer timer_;
};
}
| 31.348624 | 131 | 0.68803 | RobertLeahy |
d996397acbfa59e9d565c769b6c8f268a3d6b245 | 17,758 | cpp | C++ | lib/hip_surgery/xregPAOVolAfterRepo.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 30 | 2020-09-29T18:36:13.000Z | 2022-03-28T09:25:13.000Z | lib/hip_surgery/xregPAOVolAfterRepo.cpp | gaocong13/Orthopedic-Robot-Navigation | bf36f7de116c1c99b86c9ba50f111c3796336af0 | [
"MIT"
] | 3 | 2020-10-09T01:21:27.000Z | 2020-12-10T15:39:44.000Z | lib/hip_surgery/xregPAOVolAfterRepo.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 8 | 2021-05-25T05:14:48.000Z | 2022-02-26T12:29:50.000Z | /*
* MIT License
*
* Copyright (c) 2020 Robert Grupp
*
* 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 "xregPAOVolAfterRepo.h"
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkBSplineInterpolateImageFunction.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkBinaryBallStructuringElement.h>
#include <itkGrayscaleDilateImageFilter.h>
#include "xregAssert.h"
#include "xregITKBasicImageUtils.h"
#include "xregITKLabelUtils.h"
#include "xregSampleUtils.h"
#include "xregMetalObjSampling.h"
#include "xregITKCropPadUtils.h"
#include "xregITKResampleUtils.h"
void xreg::UpdateVolAfterRepos::operator()()
{
using ITKIndex = Vol::IndexType;
using ContinuousIndexType = itk::ContinuousIndex<double,3>;
using NNInterp = itk::NearestNeighborInterpolateImageFunction<LabelVol>;
using VolInterp = itk::BSplineInterpolateImageFunction<Vol>;
using VolIt = itk::ImageRegionIteratorWithIndex<Vol>;
using LabelVolIt = itk::ImageRegionIteratorWithIndex<LabelVol>;
xregASSERT(ImagesHaveSameCoords(labels.GetPointer(), src_vol.GetPointer()));
std::mt19937 rng_eng;
std::normal_distribution<VolScalar> norm_dist(0,add_rand_to_default_val_std_dev);
const bool add_rand = add_rand_to_default_val_std_dev > 0;
if (add_rand)
{
SeedRNGEngWithRandDev(&rng_eng);
}
const VolScalar tmp_default_val = default_val;
auto replacement_intensity = [add_rand, &rng_eng,
&norm_dist,
tmp_default_val] ()
{
return tmp_default_val + (add_rand ? norm_dist(rng_eng) :
VolScalar(0));
};
std::normal_distribution<VolScalar> air_normal_dist(0,10);
auto air_intensity = [add_rand,&rng_eng,&air_normal_dist]()
{
return -1000 + (add_rand ? air_normal_dist(rng_eng) : VolScalar(0));
};
const FrameTransform itk_idx_to_phys_pt = ITKImagePhysicalPointTransformsAsEigen(src_vol.GetPointer());
const FrameTransform phys_pt_to_itk_idx = itk_idx_to_phys_pt.inverse();
auto vol_interp_fn = VolInterp::New();
vol_interp_fn->SetSplineOrder(3);
dst_vol = ITKImageDeepCopy(src_vol.GetPointer());
if (!labels_of_air.empty())
{
for (const auto l : labels_of_air)
{
VolIt dst_it(dst_vol, dst_vol->GetLargestPossibleRegion());
LabelVolIt label_it(labels, labels->GetLargestPossibleRegion());
for (dst_it.GoToBegin(), label_it.GoToBegin(); !dst_it.IsAtEnd(); ++dst_it, ++label_it)
{
if (label_it.Value() == l)
{
dst_it.Value() = air_intensity();
}
}
}
// we want to interpolate as if the cuts have already been made
vol_interp_fn->SetInputImage(ITKImageDeepCopy(dst_vol.GetPointer()));
}
else
{
// no cuts incorporated, just use the source volume
vol_interp_fn->SetInputImage(src_vol);
}
const bool do_dilate = labels_dilate_rad;
auto label_interp = NNInterp::New();
if (!do_dilate)
{
// we can look directly into the original labelmap if we are not
// dilating it
label_interp->SetInputImage(labels);
}
Pt3 tmp_idx;
ContinuousIndexType tmp_itk_idx;
const unsigned long num_repo_objs = labels_of_repo_objs.size();
xregASSERT(num_repo_objs == repo_objs_xforms.size());
for (unsigned long obj_idx = 0; obj_idx < num_repo_objs; ++obj_idx)
{
const LabelScalar cur_label = labels_of_repo_objs[obj_idx];
if (do_dilate)
{
using MorphKernel = itk::BinaryBallStructuringElement<LabelScalar,3>;
using DilateFilter = itk::GrayscaleDilateImageFilter<LabelVol,LabelVol,MorphKernel>;
LabelVolPtr cur_labels = ApplyMaskToITKImage(labels.GetPointer(), labels.GetPointer(),
cur_label, LabelScalar(0));
MorphKernel kern;
kern.SetRadius(labels_dilate_rad);
kern.CreateStructuringElement();
auto dilate_fn = DilateFilter::New();
dilate_fn->SetInput(cur_labels);
dilate_fn->SetKernel(kern);
dilate_fn->Update();
label_interp->SetInputImage(dilate_fn->GetOutput());
}
const FrameTransform obj_warp = repo_objs_xforms[obj_idx].inverse();
VolIt dst_it(dst_vol, dst_vol->GetLargestPossibleRegion());
LabelVolIt label_it(labels, labels->GetLargestPossibleRegion());
for (dst_it.GoToBegin(), label_it.GoToBegin(); !dst_it.IsAtEnd(); ++dst_it, ++label_it)
{
// First find out if this location now belongs to the current repositioned object
const ITKIndex& cur_idx = dst_it.GetIndex();
tmp_idx[0] = cur_idx[0];
tmp_idx[1] = cur_idx[1];
tmp_idx[2] = cur_idx[2];
// continuous index before repositioning
tmp_idx = phys_pt_to_itk_idx * obj_warp * itk_idx_to_phys_pt * tmp_idx;
tmp_itk_idx[0] = tmp_idx[0];
tmp_itk_idx[1] = tmp_idx[1];
tmp_itk_idx[2] = tmp_idx[2];
if (label_interp->IsInsideBuffer(tmp_itk_idx) &&
(label_interp->EvaluateAtContinuousIndex(tmp_itk_idx) == cur_label))
{
// this location should be set to an intensity value from the repositioned object
dst_it.Value() = vol_interp_fn->EvaluateAtContinuousIndex(tmp_itk_idx);
}
else if (label_it.Value() == cur_label)
{
// this location was, but no longer corresponds to the repositioned object,
// fill the intensity with a default value, e.g. air
dst_it.Value() = replacement_intensity();
}
}
}
}
namespace
{
using namespace xreg;
struct PtInObjVisitor : public boost::static_visitor<bool>
{
Pt3 p;
bool operator()(const NaiveScrewModel& s) const
{
return PointInNaiveScrew(s, p);
}
bool operator()(const NaiveKWireModel& w) const
{
return PointInNaiveKWire(w, p);
}
};
} // un-named
void xreg::AddPAOScrewKWireToVol::operator()()
{
const size_type num_objs = obj_start_pts.size();
xregASSERT(num_objs == obj_end_pts.size());
screw_models.clear();
screw_models.reserve(num_objs);
screw_poses_wrt_vol.clear();
screw_poses_wrt_vol.reserve(num_objs);
kwire_models.clear();
kwire_models.reserve(num_objs);
kwire_poses_wrt_vol.clear();
kwire_poses_wrt_vol.reserve(num_objs);
CreateRandScrew create_rand_screws;
CreateRandKWire create_rand_kwires;
create_rand_kwires.set_debug_output_stream(*this);
std::uniform_real_distribution<double> obj_dist(0,1);
std::uniform_real_distribution<PixelScalar> screw_hu_dist(14000, 16000);
std::uniform_real_distribution<PixelScalar> kwire_hu_dist(14000, 26000);
using ObjVar = boost::variant<NaiveScrewModel,NaiveKWireModel>;
using ObjVarList = std::vector<ObjVar>;
ObjVarList objs;
objs.reserve(num_objs);
FrameTransformList obj_to_vol_poses;
obj_to_vol_poses.reserve(num_objs);
std::vector<PixelScalar> obj_hu_vals;
obj_hu_vals.reserve(num_objs);
std::vector<BoundBox3> obj_bbs;
obj_bbs.reserve(num_objs);
// for each object
for (size_type obj_idx = 0; obj_idx < num_objs; ++obj_idx)
{
this->dout() << "creating object model: " << obj_idx << std::endl;
if (obj_dist(create_rand_screws.rng_eng) < prob_screw)
{
this->dout() << " a screw..." << std::endl;
obj_hu_vals.push_back(screw_hu_dist(create_rand_screws.rng_eng));
NaiveScrewModel s;
FrameTransform screw_to_vol_xform;
// create random screw model and get pose in volume
this->dout() << "creating random screw model..." << std::endl;
std::tie(s,screw_to_vol_xform) = create_rand_screws(obj_start_pts[obj_idx],
obj_end_pts[obj_idx]);
screw_models.push_back(s);
screw_poses_wrt_vol.push_back(screw_to_vol_xform);
obj_bbs.push_back(ComputeBoundingBox(s));
objs.push_back(s);
obj_to_vol_poses.push_back(screw_to_vol_xform);
}
else
{
this->dout() << "a K-Wire..." << std::endl;
// insert a K-Wire
obj_hu_vals.push_back(kwire_hu_dist(create_rand_screws.rng_eng));
NaiveKWireModel s;
FrameTransform kwire_to_vol_xform;
// create random screw model and get pose in volume
this->dout() << "creating random K-Wire model..." << std::endl;
std::tie(s,kwire_to_vol_xform) = create_rand_kwires(obj_start_pts[obj_idx],
obj_end_pts[obj_idx]);
kwire_models.push_back(s);
kwire_poses_wrt_vol.push_back(kwire_to_vol_xform);
obj_bbs.push_back(ComputeBoundingBox(s));
objs.push_back(s);
obj_to_vol_poses.push_back(kwire_to_vol_xform);
}
} // end for each obj
BoundBox3 all_objs_bb_wrt_vol = TransformBoundBox(obj_bbs[0], obj_to_vol_poses[0]);
for (size_type obj_idx = 1; obj_idx < num_objs; ++obj_idx)
{
all_objs_bb_wrt_vol = CombineBoundBoxes(all_objs_bb_wrt_vol,
TransformBoundBox(obj_bbs[obj_idx], obj_to_vol_poses[obj_idx]));
}
orig_vol_start_pad = { 0, 0, 0 };
orig_vol_end_pad = { 0, 0, 0 };
{
this->dout() << "determing if additional padding is needed to fit objects in volume..." << std::endl;
const FrameTransform orig_vol_inds_to_phys_pts = ITKImagePhysicalPointTransformsAsEigen(orig_vol.GetPointer());
const FrameTransform phys_pts_to_orig_vol_inds = orig_vol_inds_to_phys_pts.inverse();
const BoundBox3 all_objs_bb_wrt_vol_idx = TransformBoundBox(all_objs_bb_wrt_vol,
phys_pts_to_orig_vol_inds);
const auto orig_vol_itk_reg = orig_vol->GetLargestPossibleRegion();
const auto orig_vol_itk_size = orig_vol_itk_reg.GetSize();
for (size_type i = 0; i < 3; ++i)
{
const CoordScalar lower_round = std::floor(all_objs_bb_wrt_vol_idx.lower(i));
orig_vol_start_pad[i] = (lower_round < 0) ? static_cast<size_type>(-lower_round) : size_type(0);
const CoordScalar upper_round = std::ceil(all_objs_bb_wrt_vol_idx.upper(i));
orig_vol_end_pad[i] = (upper_round > orig_vol_itk_size[i]) ?
static_cast<size_type>(upper_round - orig_vol_itk_size[i]) :
size_type(0);
}
bool need_to_pad = false;
for (size_type i = 0; i < 3; ++i)
{
if (orig_vol_start_pad[i] || orig_vol_end_pad[i])
{
need_to_pad = true;
break;
}
}
if (need_to_pad)
{
this->dout() << "padding volume..." << std::endl;
orig_vol_pad = ITKPadImage(orig_vol.GetPointer(),
orig_vol_start_pad,
orig_vol_end_pad,
PixelScalar(-1000));
}
else
{
this->dout() << "no padding required..." << std::endl;
orig_vol_pad = ITKImageDeepCopy(orig_vol.GetPointer());
}
}
VolPtr vol_sup;
if (std::abs(super_sample_factor - 1.0) > 1.0e-3)
{
// super sample the original volume
this->dout() << "super sampling (padded) original volume..." << std::endl;
vol_sup = DownsampleImageNNInterp(orig_vol_pad.GetPointer(), super_sample_factor, 0.0);
}
else
{
this->dout() << "no super-sampling..." << std::endl;
vol_sup = ITKImageDeepCopy(orig_vol_pad.GetPointer());
}
const FrameTransform vol_inds_to_phys_pts = ITKImagePhysicalPointTransformsAsEigen(vol_sup.GetPointer());
const FrameTransform phys_pts_to_vol_inds = vol_inds_to_phys_pts.inverse();
// keep track of voxels that are marked as belonging to a screw, we'll downsample
// this back to the original resolution and only update the screw voxels
// in the final output
VolPtr voxels_modified_sup = MakeITKNDVol<PixelScalar>(vol_sup->GetLargestPossibleRegion());
const auto itk_size = vol_sup->GetLargestPossibleRegion().GetSize();
// for each object
for (size_type obj_idx = 0; obj_idx < num_objs; ++obj_idx)
{
this->dout() << "inserting object: " << obj_idx << std::endl;
const FrameTransform& obj_to_vol_xform = obj_to_vol_poses[obj_idx];
const FrameTransform obj_to_vol_idx = phys_pts_to_vol_inds * obj_to_vol_xform;
const auto obj_bb_wrt_inds = TransformBoundBox(obj_bbs[obj_idx], obj_to_vol_idx);
const std::array<size_type,3> start_inds = {
static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(0)))),
static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(1)))),
static_cast<size_type>(std::max(CoordScalar(0), std::floor(obj_bb_wrt_inds.lower(2)))) };
const std::array<size_type,3> stop_inds = {
static_cast<size_type>(std::min(CoordScalar(itk_size[0]), std::ceil(obj_bb_wrt_inds.upper(0)))),
static_cast<size_type>(std::min(CoordScalar(itk_size[1]), std::ceil(obj_bb_wrt_inds.upper(1)))),
static_cast<size_type>(std::min(CoordScalar(itk_size[2]), std::ceil(obj_bb_wrt_inds.upper(2)))) };
const std::array<size_type,3> num_inds_to_check = {
stop_inds[0] - start_inds[0] + 1,
stop_inds[1] - start_inds[1] + 1,
stop_inds[2] - start_inds[2] + 1 };
const size_type xy_num_inds_to_check = num_inds_to_check[0] *
num_inds_to_check[1];
const size_type tot_num_inds_to_check = xy_num_inds_to_check *
num_inds_to_check[2];
// now fill intersecting voxels
const FrameTransform vol_to_obj_xform = obj_to_vol_xform.inverse();
const FrameTransform vol_idx_to_obj_pts = vol_to_obj_xform * vol_inds_to_phys_pts;
const PixelScalar obj_hu = obj_hu_vals[obj_idx];
ObjVar& obj = objs[obj_idx];
auto insert_obj_intens_fn = [&] (const RangeType& r)
{
Vol::IndexType itk_idx;
PtInObjVisitor pt_in_obj;
Pt3 idx;
size_type cur_idx_1d = r.begin();
// these indices need to be offset by the start_inds[]
size_type z_idx = cur_idx_1d / xy_num_inds_to_check;
const size_type tmp = cur_idx_1d - (z_idx * xy_num_inds_to_check);
size_type y_idx = tmp / num_inds_to_check[0];
size_type x_idx = tmp - (y_idx * num_inds_to_check[0]);
for (; cur_idx_1d < r.end(); ++cur_idx_1d)
{
itk_idx[0] = start_inds[0] + x_idx;
itk_idx[1] = start_inds[1] + y_idx;
itk_idx[2] = start_inds[2] + z_idx;
idx[0] = itk_idx[0];
idx[1] = itk_idx[1];
idx[2] = itk_idx[2];
pt_in_obj.p = vol_idx_to_obj_pts * idx;
if (boost::apply_visitor(pt_in_obj, obj))
{
vol_sup->SetPixel(itk_idx, obj_hu);
voxels_modified_sup->SetPixel(itk_idx, 1);
}
// increment
++x_idx;
if (x_idx == num_inds_to_check[0])
{
x_idx = 0;
++y_idx;
if (y_idx == num_inds_to_check[1])
{
y_idx = 0;
++z_idx;
}
}
}
};
this->dout() << "running parallel for over all indices to check..." << std::endl;
ParallelFor(insert_obj_intens_fn, RangeType(0, tot_num_inds_to_check));
} // end for each obj
// downsample back to original resolution
this->dout() << "downsampling from super-sampled..." << std::endl;
// -1 --> smooth before downsampling and choose the kernel size automatically
VolPtr vol_tmp_ds = DownsampleImageNNInterp(vol_sup.GetPointer(),
1.0 / super_sample_factor, -1.0);
VolPtr modified_ds = DownsampleImageLinearInterp(voxels_modified_sup.GetPointer(),
1.0 / super_sample_factor, -1.0);
// adding in screw voxels in the original volume resolution
this->dout() << "updating original volume intensities where necessary and creating label map..." << std::endl;
obj_vol = ITKImageDeepCopy(orig_vol_pad.GetPointer());
obj_labels = LabelVol::New();
obj_labels->SetDirection(obj_vol->GetDirection());
obj_labels->SetSpacing(obj_vol->GetSpacing());
obj_labels->SetOrigin(obj_vol->GetOrigin());
obj_labels->SetRegions(obj_vol->GetLargestPossibleRegion());
obj_labels->Allocate();
obj_labels->FillBuffer(0);
itk::ImageRegionIteratorWithIndex<Vol> mod_ds_it(modified_ds, modified_ds->GetLargestPossibleRegion());
while (!mod_ds_it.IsAtEnd())
{
if (mod_ds_it.Value() > 1.0e-6)
{
const auto idx = mod_ds_it.GetIndex();
obj_vol->SetPixel(idx, vol_tmp_ds->GetPixel(idx));
obj_labels->SetPixel(idx, 1);
}
++mod_ds_it;
}
}
| 33.192523 | 115 | 0.661843 | rg2 |
d996bc39b9c086bc4f86e8e00bf6342476f1f360 | 4,191 | cpp | C++ | src/luac/luactext.cpp | Twinklebear/LPCGame | f01a6ebe857b3b67cc1cb5cad39bf0641aa79e12 | [
"MIT"
] | 9 | 2015-09-09T05:59:40.000Z | 2021-05-22T11:07:54.000Z | src/luac/luactext.cpp | Twinklebear/LPCGame | f01a6ebe857b3b67cc1cb5cad39bf0641aa79e12 | [
"MIT"
] | null | null | null | src/luac/luactext.cpp | Twinklebear/LPCGame | f01a6ebe857b3b67cc1cb5cad39bf0641aa79e12 | [
"MIT"
] | 1 | 2015-08-06T06:55:12.000Z | 2015-08-06T06:55:12.000Z | #include <string>
#include <memory>
#include <lua.hpp>
#include "core/text.h"
#include "luacscript.h"
#include "luaccolor.h"
#include "luactext.h"
int LuaC::TextLib::luaopen_text(lua_State *l){
return LuaScriptLib::LuaOpenLib(l, mMetaTable, textClass, luaTextLib, newText);
}
const struct luaL_reg LuaC::TextLib::luaTextLib[] = {
{ "set", set },
{ "release", release },
{ "message", getMessage },
{ "font", getFont },
{ "fontSize", getFontSize },
{ "color", getColor },
{ "size", size },
{ "w", width },
{ "h", height },
{ "__newindex", newIndex },
{ "__gc", garbageCollection },
{ NULL, NULL }
};
int LuaC::TextLib::newText(lua_State *l){
//Stack: class table, message, font file, color, font size
std::string msg = luaL_checkstring(l, 2);
std::string fontFile = luaL_checkstring(l, 3);
Color *color = ColorLib::Check(l, 4);
int size = luaL_checkint(l, 5);
Push(l, std::make_shared<Text>(msg, fontFile, *color, size));
return 1;
}
int LuaC::TextLib::set(lua_State *l){
//Stack: text to set values of, message, font file, color, font size
std::shared_ptr<Text> *txt = Check(l, 1);
std::string msg = luaL_checkstring(l, 2);
std::string fontFile = luaL_checkstring(l, 3);
Color *color = ColorLib::Check(l, 4);
int size = luaL_checkint(l, 5);
(*txt)->Set(msg, fontFile, *color, size);
return 0;
}
int LuaC::TextLib::newIndex(lua_State *l){
//Stack: text, string of index to set, val for index
std::string index = luaL_checkstring(l, 2);
switch (index.at(0)){
case 'm':
return setMessage(l);
case 'f':
return setFont(l);
case 's':
return setSize(l);
case 'c':
return setColor(l);
default:
return 0;
}
}
int LuaC::TextLib::setMessage(lua_State *l){
//Stack: text, string of index to set, message to set
std::shared_ptr<Text> *txt = Check(l, 1);
std::string msg = luaL_checkstring(l, 3);
(*txt)->SetMessage(msg);
return 0;
}
int LuaC::TextLib::setFont(lua_State *l){
//Stack: text, string of index to set, font file to use
std::shared_ptr<Text> *txt = Check(l, 1);
std::string font = luaL_checkstring(l, 3);
(*txt)->SetFont(font);
return 0;
}
int LuaC::TextLib::setSize(lua_State *l){
//Stack: text, string of index to set, font size to set
std::shared_ptr<Text> *txt = Check(l, 1);
int size = luaL_checkint(l, 3);
(*txt)->SetFontSize(size);
return 0;
}
int LuaC::TextLib::setColor(lua_State *l){
//Stack: text, string of index to set, color to set
std::shared_ptr<Text> *txt = Check(l, 1);
Color color = *ColorLib::Check(l, 3);
(*txt)->SetColor(color);
return 0;
}
int LuaC::TextLib::getMessage(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushstring(l, (*txt)->GetMessage().c_str());
return 1;
}
int LuaC::TextLib::getFont(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushstring(l, (*txt)->GetFont().c_str());
return 1;
}
int LuaC::TextLib::getFontSize(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushinteger(l, (*txt)->GetFontSize());
return 1;
}
int LuaC::TextLib::getColor(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
ColorLib::Push(l, (*txt)->GetColor());
return 1;
}
int LuaC::TextLib::size(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushinteger(l, (*txt)->W());
lua_pushinteger(l, (*txt)->H());
return 2;
}
int LuaC::TextLib::width(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushinteger(l, (*txt)->W());
return 1;
}
int LuaC::TextLib::height(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
lua_pushinteger(l, (*txt)->H());
return 1;
}
int LuaC::TextLib::release(lua_State *l){
//Stack: text
std::shared_ptr<Text> *txt = Check(l, 1);
txt->~shared_ptr();
return 0;
}
int LuaC::TextLib::garbageCollection(lua_State *l){
return release(l);
}
| 29.307692 | 83 | 0.606299 | Twinklebear |
d99794d41639388a565295350fec1c6877cae395 | 760 | cpp | C++ | src/ECS/Utility/IDConversions.cpp | InversePalindrome/ProceduralX | f53d734970be4300f06db295d25e1a012b1a8fd9 | [
"MIT"
] | 2 | 2020-02-06T14:39:56.000Z | 2022-02-27T08:27:54.000Z | src/ECS/Utility/IDConversions.cpp | InversePalindrome/ProceduralX | f53d734970be4300f06db295d25e1a012b1a8fd9 | [
"MIT"
] | null | null | null | src/ECS/Utility/IDConversions.cpp | InversePalindrome/ProceduralX | f53d734970be4300f06db295d25e1a012b1a8fd9 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2020 Inverse Palindrome
ProceduralX - ECS/Utility/IDConversions.cpp
https://inversepalindrome.com/
*/
#include "ECS/Utility/IDConversions.hpp"
#include "ECS/Components/IDComponent.hpp"
entt::entity ECS::Utility::getEntity(const entt::registry& registry, std::size_t id)
{
auto foundEntity = entt::entity{ entt::null };
registry.each([®istry, &foundEntity, id](auto entity)
{
if (registry.has<Components::IDComponent>(entity))
{
const auto& idComponent = registry.get<Components::IDComponent>(entity);
if (id == idComponent.getID())
{
foundEntity = entity;
}
}
});
return foundEntity;
} | 25.333333 | 88 | 0.596053 | InversePalindrome |
d9995906ce38c0755759dd44583e44c298787045 | 1,855 | cc | C++ | src/benchmark/solve/exhaustive/solve_exhaustive.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | src/benchmark/solve/exhaustive/solve_exhaustive.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | src/benchmark/solve/exhaustive/solve_exhaustive.cc | ojcole/re-pairing-brackets | 1bd76bd5f19381d881116564bbaaa5e4e1395942 | [
"MIT"
] | null | null | null | #include "solve/exhaustive/solve_exhaustive.h"
#include <benchmark/benchmark.h>
#include <fstream>
#include <vector>
#include "generate/generate_random.h"
#include "solve/solve_approximate.h"
static void BM_SolveExhaustiveRandom50(benchmark::State &state) {
std::ifstream stream("benchmark/solve/exhaustive/exhaustive_bench_set50.txt");
std::vector<std::string> words;
std::string line;
while (std::getline(stream, line)) {
words.push_back(line);
}
stream.close();
words = std::vector<std::string>(words.begin(), words.begin() + 5000);
for (auto _ : state) {
for (auto &word : words) {
solve::ExhaustiveSolve(word);
}
}
}
static void BM_SolveExhaustiveRandom100(benchmark::State &state) {
std::ifstream stream(
"benchmark/solve/exhaustive/exhaustive_bench_set100.txt");
std::vector<std::string> words;
std::string line;
while (std::getline(stream, line)) {
words.push_back(line);
}
stream.close();
words = std::vector<std::string>(words.begin(), words.begin() + 100);
for (auto _ : state) {
for (auto &word : words) {
solve::ExhaustiveSolve(word);
}
}
}
static void BM_SolveExhaustiveRandom200(benchmark::State &state) {
std::ifstream stream(
"benchmark/solve/exhaustive/exhaustive_bench_set200.txt");
std::vector<std::string> words;
std::string line;
while (std::getline(stream, line)) {
words.push_back(line);
}
stream.close();
words = std::vector<std::string>(words.begin(), words.begin() + 15);
for (auto _ : state) {
for (auto &word : words) {
solve::ExhaustiveSolve(word);
}
}
}
BENCHMARK(BM_SolveExhaustiveRandom50)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_SolveExhaustiveRandom100)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_SolveExhaustiveRandom200)->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
| 23.782051 | 80 | 0.691644 | ojcole |
d9a02cfef35b191eea9203713a45672d73b9c2dc | 585 | cpp | C++ | problemsets/Programming Challenges/Capitulo 10/111004 - 10039 Railroads (Incomplete)/b.out.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Programming Challenges/Capitulo 10/111004 - 10039 Railroads (Incomplete)/b.out.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/Programming Challenges/Capitulo 10/111004 - 10039 Railroads (Incomplete)/b.out.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
Scenario 1
Departure 1000 A
Arrival 1300 C
Scenario 2
Departure 0800 A
Arrival 1400 D
Scenario 3
No connection
Scenario 4
Departure 0859 A
Arrival 1300 D
Scenario 5
No connection
Scenario 6
No connection
Scenario 7
No connection
Scenario 8
No connection
Scenario 9
Departure 0949 Hamburg
Arrival 1411 Darmstadt
Scenario 10
No connection
Scenario 11
No connection
Scenario 12
Departure 0949 Hamburg
Arrival 1411 Darmstadt
Scenario 13
No connection
Scenario 14
No connection
| 11.037736 | 38 | 0.77265 | juarezpaulino |
d9a1e1b63eb0ac1c813a3c213b9af26ca417226d | 5,481 | cpp | C++ | Source/SprueEngine/Texturing/SprueTextureBaker.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 35 | 2017-04-07T22:49:41.000Z | 2021-08-03T13:59:20.000Z | Source/SprueEngine/Texturing/SprueTextureBaker.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 1 | 2017-04-13T17:43:54.000Z | 2017-04-15T04:17:37.000Z | Source/SprueEngine/Texturing/SprueTextureBaker.cpp | Qt-Widgets/TexGraph | 8fe72cea1afcf5e235c810003bf4ee062bb3fc13 | [
"MIT"
] | 7 | 2019-03-11T19:26:53.000Z | 2021-03-04T07:17:10.000Z | #include "SprueTextureBaker.h"
#include <SprueEngine/Logging.h>
#include <SprueEngine/Texturing/RasterizerData.h>
#include <SprueEngine/Core/SprueModel.h>
#include <SprueEngine/Core/Components/TexturingComponent.h>
#include <SprueEngine/Math/Trig.h>
#include <SprueEngine/Texturing/Sampling.h>
namespace SprueEngine
{
#define DECL_RASTER RasterizerData rasterData; \
rasterData.Pixels = ret->getData(); \
rasterData.Mask = 0x0; \
rasterData.WrittenMask = new bool[ret->getWidth() * ret->getHeight() * ret->getDepth()]; \
memset(rasterData.WrittenMask, 0, ret->getWidth() * ret->getHeight() * ret->getDepth()); \
rasterData.Width = ret->getWidth(); \
rasterData.Height = ret->getHeight(); \
rasterData.Depth = ret->getDepth();
SprueTextureBaker::SprueTextureBaker(SprueModel* model, const std::vector<TexturingComponent*>& components) :
TextureBaker(0x0, 0x0),
model_(model),
texturingComponents_(components)
{
SetWidth(1024);
SetHeight(1024);
}
SprueTextureBaker::~SprueTextureBaker()
{
}
FilterableBlockMap<RGBA>* SprueTextureBaker::Bake() const
{
FilterableBlockMap<RGBA>* ret = new FilterableBlockMap<RGBA>(GetWidth(), GetHeight());
DECL_RASTER;
for (unsigned i = 0; i < model_->GetMeshedParts()->GetMeshCount(); ++i)
{
const auto mesh = model_->GetMeshedParts()->GetMesh(i);
if (mesh->uvBuffer_.empty() || mesh->normalBuffer_.empty() || mesh->positionBuffer_.empty())
continue;
for (unsigned i = 0; i < mesh->indexBuffer_.size(); i += 3)
{
const unsigned index0 = mesh->indexBuffer_[i];
const unsigned index1 = mesh->indexBuffer_[i + 1];
const unsigned index2 = mesh->indexBuffer_[i + 2];
Vec2 uv[3];
uv[0] = mesh->uvBuffer_[index0];
uv[1] = mesh->uvBuffer_[index1];
uv[2] = mesh->uvBuffer_[index2];
Vec3 p[3];
p[0] = mesh->positionBuffer_[index0];
p[1] = mesh->positionBuffer_[index1];
p[2] = mesh->positionBuffer_[index2];
Vec3 n[3];
n[0] = mesh->normalBuffer_[index0];
n[1] = mesh->normalBuffer_[index1];
n[2] = mesh->normalBuffer_[index2];
RasterizeTextured(&rasterData, uv, n, p);
}
}
PadEdges(&rasterData, 4);
return ret;
}
void SprueTextureBaker::RasterizeTextured(RasterizerData* rasterData, Vec2* uv, Vec3* norms, Vec3* pos) const
{
const float xSize = 1.0f / rasterData->Width;
const float ySize = 1.0f / rasterData->Width;
Rect triBounds = CalculateTriangleImageBounds(rasterData->Width, rasterData->Height, uv);
for (float y = triBounds.yMin; y <= triBounds.yMax; y += 1.0f)
{
if (y < 0 || y >= rasterData->Height)
continue;
float yCoord = y / rasterData->Height;
for (float x = triBounds.xMin; x <= triBounds.xMax; x += 1.0f)
{
if (x < 0 || x >= rasterData->Width)
continue;
float xCoord = x / rasterData->Width;
Vec2 pt(xCoord, yCoord);
// Fragment corners for conservative rasterization
const float mul = rasterData->OriginAtTop ? 1.0f : -1.0f;
const Vec2 pixelCorners[] = {
{ pt.x, pt.y * mul },
{ pt.x + xSize, pt.y * mul },
{ pt.x, (pt.y + ySize) * mul },
{ pt.x + xSize, (pt.y + ySize) * mul },
{ pt.x + xSize*0.5f, (pt.y+ySize*0.5f) * mul },
};
// If any corner is overlapped then we pass for rendering under conservative rasterization
bool anyCornersContained = false;
for (unsigned i = 0; i < 5; ++i)
anyCornersContained |= IsPointContained(uv, pixelCorners[i].x, pixelCorners[i].y);
if (anyCornersContained) //if (IsPointContained(uv, xCoord, yCoord))
{
Vec3 interpolatedNormal = AttributeToWorldSpace(uv, pt, norms);
Vec3 interpolatedPosition = AttributeToWorldSpace(uv, pt, pos);
RGBA toWrite = RGBA::Invalid;
for (auto comp : texturingComponents_)
{
RGBA writeColor = comp->SampleColorProjection(interpolatedPosition, interpolatedNormal);
if (writeColor.IsValid())
toWrite = writeColor;
}
if (toWrite.IsValid())
{
const int writeIndex = ToArrayIndex(x, y, 0, rasterData->Width, rasterData->Height, rasterData->Depth);
// If there's a mask than grab the appropriate mask pixel and multiply it with the write target
rasterData->Pixels[writeIndex] = toWrite;
if (rasterData->WrittenMask)
rasterData->WrittenMask[writeIndex] = true;
}
}
}
}
}
} | 40.902985 | 128 | 0.525999 | Qt-Widgets |
d2636086585df68d6257ee240525c85ff9e60ea7 | 1,752 | cc | C++ | src/selfmessagehandlers/crawlerselfmsgehandler/CrawlerSelfMsgHandler.cc | Seabreg/BSF | 89bccd20359ec794cd19a1211d5e52c751e7405c | [
"MIT"
] | null | null | null | src/selfmessagehandlers/crawlerselfmsgehandler/CrawlerSelfMsgHandler.cc | Seabreg/BSF | 89bccd20359ec794cd19a1211d5e52c751e7405c | [
"MIT"
] | null | null | null | src/selfmessagehandlers/crawlerselfmsgehandler/CrawlerSelfMsgHandler.cc | Seabreg/BSF | 89bccd20359ec794cd19a1211d5e52c751e7405c | [
"MIT"
] | null | null | null | #include "CrawlerSelfMsgHandler.h"
#include "omnetpp.h"
using namespace omnetpp;
CrawlerSelfMsgHandler::CrawlerSelfMsgHandler(NodeBase* node,
CrawlerBase *crawler, double startTime) {
this->node = node;
this->crawler = crawler;
this->startTime = startTime;
}
CrawlerSelfMsgHandler::~CrawlerSelfMsgHandler() {
// TODO Auto-generated destructor stub
}
bool CrawlerSelfMsgHandler::handleSelfMessage(BasicSelfMsg* msg) {
if (msg == crawler->crawl_msg) {
if (node->isActive()) {
if (simTime() > startTime) {
if (!crawler->isCrawling) {
crawler->startCrawl();
}
}
node->scheduleAt(simTime() + crawler->crawl_timeout,
crawler->crawl_msg);
}
return true;
} else if (msg == crawler->crawl_dump_msg) {
crawler->crawler_data->dumpEntries();
double normalize = std::round(
1 + SIMTIME_DBL(simTime() / crawler->crawl_dump_timeout));
node->scheduleAt(0 + normalize * crawler->crawl_dump_timeout,
crawler->crawl_dump_msg);
return true;
}
return false;
}
void CrawlerSelfMsgHandler::cancelEvents() {
node->cancelEvent(crawler->crawl_msg);
node->cancelEvent(crawler->crawl_dump_msg);
}
void CrawlerSelfMsgHandler::rescheduleEvents() {
node->cancelEvent(crawler->crawl_msg);
node->scheduleAt(simTime() + crawler->crawl_timeout, crawler->crawl_msg);
node->cancelEvent(crawler->crawl_dump_msg);
double normalize = std::round(
1 + SIMTIME_DBL(simTime() / crawler->crawl_dump_timeout));
node->scheduleAt(0 + normalize * crawler->crawl_dump_timeout,
crawler->crawl_dump_msg);
}
| 30.736842 | 77 | 0.635845 | Seabreg |
d26472cd5bad35551b7d593abe1715544bb5829b | 851 | cpp | C++ | NOIP/oj.noi.cn/1100FunctionApplication.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | NOIP/oj.noi.cn/1100FunctionApplication.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | NOIP/oj.noi.cn/1100FunctionApplication.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2018-06-19T12:18:30.000Z | 2019-03-18T03:23:45.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
inline void f0(LL &a) {};
inline void f1(LL &a) { a = a * 11 + 24; }
inline void f2(LL &a) { a = (a >> 3) + 3; }
inline void f3(LL &a) { a = a * a + 10 * a + 31; }
inline void f4(LL &a) { a = a / 13 + 31; }
inline void f5(LL &a) { a = a - (int) sqrt(a); }
inline void f6(LL &a) { a = (int) sqrt(a); }
inline void f7(LL &a) { a = a % 206211; }
inline void f8(LL &a) { a = a | 10311999; }
inline void f9(LL &a) { a = a & 19991124; }
inline void f10(LL &a) { a = a ^ 11241031; }
vector<void (*)(LL &)> F{f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10};
int main(int argc, char const *argv[]) {
int m, x, y;
LL a;
for (cin >> m; m-- && cin >> x >> y >> a;) {
swap(F[x], F[y]);
for (auto f : F) f(a);
cout << a << endl;
}
return 0;
} | 21.820513 | 70 | 0.491187 | webturing |
d264e3574b91a9c4b56777745da44a5750aac03e | 5,298 | cpp | C++ | Codeforces/E60/C_WA.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Codeforces/E60/C_WA.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Codeforces/E60/C_WA.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define fi first
#define se second
#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cerr<<"here"<<endl;
#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
using namespace std;
int main()
{
__;
int x1,x2,y1,y2;
cin>>x1>>y1>>x2>>y2;
int n;
cin>>n;
string s;
cin>>s;
if(x1==x2 && y1==y2) {cout<<0<<endl;return 0;}
int up = 0, right = 0;
int x=x1,y=y1;
if(x2>x1) right = 1;
else if(x2==x1) right = 0;
else right = -1;
if(y2>y1) up = 1;
else if(y1==y2) up = 0;
else up = -1;
int count = 0;
int boo1=0,boo2=0,boo3=0,boo4=0;
vector<int> v;
for(int i=0;i<s.size();i++)
{
if(s[i]=='U')
{
if(up>0)
{
v.push_back(1);
y1++;
if(y2>y1) y1++;
else if(x2>x1) x1++;
else if(x1>x2) x1--;
}
else v.push_back(0);
boo1 = 1;
}
else if(s[i]=='D')
{
if(up<0)
{
v.push_back(1);
y1--;
if(y2<y1) y1--;
else if(x2>x1) x1++;
else if(x2<x1) x1--;
}
else v.push_back(0);
boo2 = 1;
}
else if(s[i]=='L')
{
if(right<0)
{
v.push_back(1);
x1--;
if(x1>x2) x1--;
else if(y1>y2) y1--;
else if(y1<y2) y1++;
}
else v.push_back(0);
boo3 = 1;
}
else
{
if(right>0)
{
v.push_back(1);
if(x1<x2) x1++;
else if(y1>y2) y1--;
else if(y2>y1) y1++;
}
else v.push_back(0);
}
// count++;
// // t(x1,x2,count);
// v.push_back(abs(x-x1)+abs(y-y1));
// if(x1==x2 && y1==y2) break;
// // Update after every call
// if(x2>x1) right = 1;
// else if(x2==x1) right = 0;
// else right = -1;
// if(y2>y1) up = 1;
// else if(y1==y2) up = 0;
// else up = -1;
}
// t(count);
// pr(v);
ll sum1 = 0;
for(int i=0;i<v.size();i++) sum1+=v[i];
sum1*=2;
if(sum1==0 && up!=0 && right!=0)
{
cout<<-1<<endl;
}
else
{
ll dist = 2*min(abs(x-x2),abs(y-y2));
// t(dist,sum1);
ll a = 0,b = 0,count = 0,count1 = 0,counter = 0;
if(sum1!=0)
{
a = dist/sum1;
b = dist%sum1;
}
count = a*n;
counter = 0;
count1 = 0;
for(int i=0;i<v.size() && b>0;i++)
{
counter+=v[i]*2;
count1++;
// t(counter,i,v[i]);
if(counter>=b) break;
}
int xy = 0;
if(abs(x-x2)>abs(y-y2)) xy = 1;
else if(abs(x-x2)<abs(y-y2)) xy = 2;
if(xy==1)
{
// UD
int boo =0;
for(int i=0;i<n;i++) v[i] = 0;
for(int i=0;i<n;i++)
{
if(right>0 && s[i]=='R') v[i] = 1;
else if(right<0 && s[i]=='L') v[i] = 1;
else if(s[i]=='U' || s[i]=='D')
{
boo^=1;
if(boo) v[i] = 1;
}
}
}
else if(xy==2)
{
int boo =0;
for(int i=0;i<n;i++) v[i] = 0;
for(int i=0;i<n;i++)
{
if(up>0 && s[i]=='U') v[i] = 1;
else if(up<0 && s[i]=='D') v[i] = 1;
else if(s[i]=='R' || s[i]=='L')
{
if(boo) v[i] = 1;
boo^=1;
}
}
}
else {cout<<count+count1<<endl;return 0;}
// t(count);
int sum2 = 0;
for(int i=0;i<v.size();i++) sum2+=v[i];
sum2*=2;
// t(sum2);
if(sum1==0 && sum2==0) {cout<<-1<<endl; return 0;}
dist = abs(abs(x2-x)-abs(y2-y));
for(int i=count1;i<n && dist>0;i++)
{
dist-=v[i]*2;
count++;
if(dist<=0) break;
}
a = 0;b = 0;
if(sum2!=0 && dist>0)
{
a = dist/sum2;
b = dist%sum2;
}
count+=count1+a*n;
for(int i=0;i<n && b>0;i++)
{
b-=v[i]*2;
count++;
if(b<=0) break;
}
if(count==0) cout<<-1<<endl;
else cout<<count<<endl;
// cout<<count<<endl;
}
// if(v[v.size()-1]==0) cout<<-1<<endl;
// else
// {
// int a = v[v.size()-1];
// t(a);
// if(a==abs(x-x2)+abs(y-y2)) {cout<<count<<endl; return 0;}
// ll dist = abs(x-x2)+abs(y-y2);
// ll b = dist/a;
// ll c = dist%a;
// ll count = b*n;
// for(int i=0;i<v.size();i++)
// {
// if(v[i]==c && c!=0) {count+=i+1; break;}
// }
// cout<<count<<endl;
// }
// cout<<count<<endl;
return 0;
}
| 21.983402 | 152 | 0.415062 | Mindjolt2406 |
d2664dc46a98979d200eefbe15b199bf717c247d | 36,291 | hpp | C++ | src/axom/mint/execution/internal/for_all_faces.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | src/axom/mint/execution/internal/for_all_faces.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | src/axom/mint/execution/internal/for_all_faces.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
// other Axom Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#ifndef MINT_FOR_ALL_FACES_HPP_
#define MINT_FOR_ALL_FACES_HPP_
// Axom core includes
#include "axom/config.hpp" // compile time definitions
#include "axom/core/execution/execution_space.hpp" // for execution_space traits
#include "axom/core/execution/for_all.hpp" // for axom::for_all
// mint includes
#include "axom/mint/execution/xargs.hpp" // for xargs
#include "axom/mint/config.hpp" // for compile-time definitions
#include "axom/mint/mesh/Mesh.hpp" // for Mesh
#include "axom/mint/mesh/StructuredMesh.hpp" // for StructuredMesh
#include "axom/mint/mesh/UniformMesh.hpp" // for UniformMesh
#include "axom/mint/mesh/RectilinearMesh.hpp" // for RectilinearMesh
#include "axom/mint/mesh/CurvilinearMesh.hpp" // for CurvilinearMesh
#include "axom/mint/execution/internal/helpers.hpp" // for for_all_coords
#include "axom/mint/execution/internal/structured_exec.hpp"
#include "axom/core/numerics/Matrix.hpp" // for Matrix
#ifdef AXOM_USE_RAJA
#include "RAJA/RAJA.hpp"
#endif
namespace axom
{
namespace mint
{
namespace internal
{
namespace helpers
{
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_I_faces(xargs::ij, const StructuredMesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() != 2, "Mesh must be 2D.");
const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION);
const IndexType Ni = INodeResolution;
const IndexType Nj = m.getCellResolution(J_DIRECTION);
#ifdef AXOM_USE_RAJA
RAJA::RangeSegment i_range(0, Ni);
RAJA::RangeSegment j_range(0, Nj);
using exec_pol = typename structured_exec<ExecPolicy>::loop2d_policy;
RAJA::kernel<exec_pol>(
RAJA::make_tuple(i_range, j_range),
AXOM_LAMBDA(IndexType i, IndexType j) {
const IndexType faceID = i + j * INodeResolution;
kernel(faceID, i, j);
});
#else
constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value;
AXOM_STATIC_ASSERT(is_serial);
for(IndexType j = 0; j < Nj; ++j)
{
const IndexType offset = j * INodeResolution;
for(IndexType i = 0; i < Ni; ++i)
{
const IndexType faceID = i + offset;
kernel(faceID, i, j);
}
}
#endif
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_I_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be a 3D.");
const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION);
const IndexType numIFacesInKSlice =
INodeResolution * m.getCellResolution(J_DIRECTION);
const IndexType Ni = INodeResolution;
const IndexType Nj = m.getCellResolution(J_DIRECTION);
const IndexType Nk = m.getCellResolution(K_DIRECTION);
#ifdef AXOM_USE_RAJA
RAJA::RangeSegment i_range(0, Ni);
RAJA::RangeSegment j_range(0, Nj);
RAJA::RangeSegment k_range(0, Nk);
using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy;
RAJA::kernel<exec_pol>(
RAJA::make_tuple(i_range, j_range, k_range),
AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) {
const IndexType faceID = i + j * INodeResolution + k * numIFacesInKSlice;
kernel(faceID, i, j, k);
});
#else
constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value;
AXOM_STATIC_ASSERT(is_serial);
for(IndexType k = 0; k < Nk; ++k)
{
const IndexType k_offset = k * numIFacesInKSlice;
for(IndexType j = 0; j < Nj; ++j)
{
const IndexType offset = j * INodeResolution + k_offset;
for(IndexType i = 0; i < Ni; ++i)
{
const IndexType faceID = i + offset;
kernel(faceID, i, j, k);
}
}
}
#endif
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_J_faces(xargs::ij, const StructuredMesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() != 2, "Mesh must be 2D.");
const IndexType ICellResolution = m.getCellResolution(I_DIRECTION);
const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION);
const IndexType Ni = ICellResolution;
const IndexType Nj = m.getNodeResolution(J_DIRECTION);
#ifdef AXOM_USE_RAJA
RAJA::RangeSegment i_range(0, Ni);
RAJA::RangeSegment j_range(0, Nj);
using exec_pol = typename structured_exec<ExecPolicy>::loop2d_policy;
RAJA::kernel<exec_pol>(
RAJA::make_tuple(i_range, j_range),
AXOM_LAMBDA(IndexType i, IndexType j) {
const IndexType faceID = numIFaces + i + j * ICellResolution;
kernel(faceID, i, j);
});
#else
constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value;
AXOM_STATIC_ASSERT(is_serial);
for(IndexType j = 0; j < Nj; ++j)
{
const IndexType offset = numIFaces + j * ICellResolution;
for(IndexType i = 0; i < Ni; ++i)
{
const IndexType faceID = i + offset;
kernel(faceID, i, j);
}
}
#endif
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_J_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be 3D.");
const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION);
const IndexType ICellResolution = m.getCellResolution(I_DIRECTION);
const IndexType numJFacesInKSlice =
ICellResolution * m.getNodeResolution(J_DIRECTION);
const IndexType Ni = ICellResolution;
const IndexType Nj = m.getNodeResolution(J_DIRECTION);
const IndexType Nk = m.getCellResolution(K_DIRECTION);
#ifdef AXOM_USE_RAJA
RAJA::RangeSegment i_range(0, Ni);
RAJA::RangeSegment j_range(0, Nj);
RAJA::RangeSegment k_range(0, Nk);
using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy;
RAJA::kernel<exec_pol>(
RAJA::make_tuple(i_range, j_range, k_range),
AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) {
const IndexType jp = j * ICellResolution;
const IndexType kp = k * numJFacesInKSlice;
const IndexType faceID = numIFaces + i + jp + kp;
kernel(faceID, i, j, k);
});
#else
constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value;
AXOM_STATIC_ASSERT(is_serial);
for(IndexType k = 0; k < Nk; ++k)
{
const IndexType k_offset = k * numJFacesInKSlice + numIFaces;
for(IndexType j = 0; j < Nj; ++j)
{
const IndexType offset = j * ICellResolution + k_offset;
for(IndexType i = 0; i < Ni; ++i)
{
const IndexType faceID = i + offset;
kernel(faceID, i, j, k);
}
}
}
#endif
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_K_faces(xargs::ijk, const StructuredMesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() != 3, "Mesh must be 3D.");
const IndexType numIJFaces =
m.getTotalNumFaces(I_DIRECTION) + m.getTotalNumFaces(J_DIRECTION);
const IndexType ICellResolution = m.getCellResolution(I_DIRECTION);
const IndexType cellKp = m.cellKp();
const IndexType Ni = ICellResolution;
const IndexType Nj = m.getCellResolution(J_DIRECTION);
const IndexType Nk = m.getNodeResolution(K_DIRECTION);
#ifdef AXOM_USE_RAJA
RAJA::RangeSegment i_range(0, Ni);
RAJA::RangeSegment j_range(0, Nj);
RAJA::RangeSegment k_range(0, Nk);
using exec_pol = typename structured_exec<ExecPolicy>::loop3d_policy;
RAJA::kernel<exec_pol>(
RAJA::make_tuple(i_range, j_range, k_range),
AXOM_LAMBDA(IndexType i, IndexType j, IndexType k) {
const IndexType jp = j * ICellResolution;
const IndexType kp = k * cellKp;
const IndexType faceID = numIJFaces + i + jp + kp;
kernel(faceID, i, j, k);
});
#else
constexpr bool is_serial = std::is_same<ExecPolicy, axom::SEQ_EXEC>::value;
AXOM_STATIC_ASSERT(is_serial);
for(IndexType k = 0; k < Nk; ++k)
{
const IndexType k_offset = k * cellKp + numIJFaces;
for(IndexType j = 0; j < Nj; ++j)
{
const IndexType offset = j * ICellResolution + k_offset;
for(IndexType i = 0; i < Ni; ++i)
{
const IndexType faceID = i + offset;
kernel(faceID, i, j, k);
}
}
}
#endif
}
} /* namespace helpers */
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::index, const Mesh& m, KernelType&& kernel)
{
const IndexType numFaces = m.getNumberOfFaces();
axom::for_all<ExecPolicy>(numFaces, std::forward<KernelType>(kernel));
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces(xargs::index, const Mesh& m, KernelType&& kernel)
{
return for_all_faces_impl<ExecPolicy>(xargs::index(),
m,
std::forward<KernelType>(kernel));
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::nodeids,
const StructuredMesh& m,
KernelType&& kernel)
{
const IndexType dimension = m.getDimension();
const IndexType* offsets = m.getCellNodeOffsetsArray();
const IndexType cellNodeOffset3 = offsets[3];
if(dimension == 2)
{
const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION);
helpers::for_all_I_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID,
IndexType AXOM_UNUSED_PARAM(i),
IndexType AXOM_UNUSED_PARAM(j)) {
IndexType nodes[2];
nodes[0] = faceID;
nodes[1] = nodes[0] + cellNodeOffset3;
kernel(faceID, nodes, 2);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType AXOM_UNUSED_PARAM(i), IndexType j) {
const IndexType shiftedID = faceID - numIFaces;
IndexType nodes[2];
nodes[0] = shiftedID + j;
nodes[1] = nodes[0] + 1;
kernel(faceID, nodes, 2);
});
}
else
{
SLIC_ERROR_IF(dimension != 3,
"for_all_faces is only valid for 2 or 3D meshes.");
const IndexType numIFaces = m.getTotalNumFaces(I_DIRECTION);
const IndexType numIJFaces = numIFaces + m.getTotalNumFaces(J_DIRECTION);
const IndexType INodeResolution = m.getNodeResolution(I_DIRECTION);
const IndexType JNodeResolution = m.getNodeResolution(J_DIRECTION);
const IndexType KFaceNodeStride =
m.getCellResolution(I_DIRECTION) + m.getCellResolution(J_DIRECTION) + 1;
const IndexType cellNodeOffset2 = offsets[2];
const IndexType cellNodeOffset4 = offsets[4];
const IndexType cellNodeOffset5 = offsets[5];
const IndexType cellNodeOffset7 = offsets[7];
helpers::for_all_I_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID,
IndexType AXOM_UNUSED_PARAM(i),
IndexType AXOM_UNUSED_PARAM(j),
IndexType k) {
IndexType nodes[4];
nodes[0] = faceID + k * INodeResolution;
nodes[1] = nodes[0] + cellNodeOffset4;
nodes[2] = nodes[0] + cellNodeOffset7;
nodes[3] = nodes[0] + cellNodeOffset3;
kernel(faceID, nodes, 4);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID,
IndexType AXOM_UNUSED_PARAM(i),
IndexType j,
IndexType k) {
const IndexType shiftedID = faceID - numIFaces;
IndexType nodes[4];
nodes[0] = shiftedID + j + k * JNodeResolution;
nodes[1] = nodes[0] + 1;
nodes[2] = nodes[0] + cellNodeOffset5;
nodes[3] = nodes[0] + cellNodeOffset4;
kernel(faceID, nodes, 4);
});
helpers::for_all_K_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID,
IndexType AXOM_UNUSED_PARAM(i),
IndexType j,
IndexType k) {
const IndexType shiftedID = faceID - numIJFaces;
IndexType nodes[4];
nodes[0] = shiftedID + j + k * KFaceNodeStride;
nodes[1] = nodes[0] + 1;
nodes[2] = nodes[0] + cellNodeOffset2;
nodes[3] = nodes[0] + cellNodeOffset3;
kernel(faceID, nodes, 4);
});
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::nodeids,
const UnstructuredMesh<SINGLE_SHAPE>& m,
KernelType&& kernel)
{
SLIC_ERROR_IF(m.getNumberOfFaces() <= 0,
"No faces in the mesh, perhaps you meant to call "
<< "UnstructuredMesh::initializeFaceConnectivity first.");
const IndexType* faces_to_nodes = m.getFaceNodesArray();
const IndexType num_nodes = m.getNumberOfFaceNodes();
for_all_faces_impl<ExecPolicy>(
xargs::index(),
m,
AXOM_LAMBDA(IndexType faceID) {
kernel(faceID, faces_to_nodes + faceID * num_nodes, num_nodes);
});
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::nodeids,
const UnstructuredMesh<MIXED_SHAPE>& m,
KernelType&& kernel)
{
SLIC_ERROR_IF(m.getNumberOfFaces() <= 0,
"No faces in the mesh, perhaps you meant to call "
<< "UnstructuredMesh::initializeFaceConnectivity first.");
const IndexType* faces_to_nodes = m.getFaceNodesArray();
const IndexType* offsets = m.getFaceNodesOffsetsArray();
for_all_faces_impl<ExecPolicy>(
xargs::index(),
m,
AXOM_LAMBDA(IndexType faceID) {
const IndexType num_nodes = offsets[faceID + 1] - offsets[faceID];
kernel(faceID, faces_to_nodes + offsets[faceID], num_nodes);
});
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces(xargs::nodeids, const Mesh& m, KernelType&& kernel)
{
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
if(m.isStructured())
{
const StructuredMesh& sm = static_cast<const StructuredMesh&>(m);
for_all_faces_impl<ExecPolicy>(xargs::nodeids(),
sm,
std::forward<KernelType>(kernel));
}
else if(m.hasMixedCellTypes())
{
const UnstructuredMesh<MIXED_SHAPE>& um =
static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::nodeids(),
um,
std::forward<KernelType>(kernel));
}
else
{
const UnstructuredMesh<SINGLE_SHAPE>& um =
static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::nodeids(),
um,
std::forward<KernelType>(kernel));
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::cellids,
const StructuredMesh& m,
KernelType&& kernel)
{
const IndexType ICellResolution = m.getCellResolution(I_DIRECTION);
const IndexType JCellResolution = m.getCellResolution(J_DIRECTION);
const IndexType cellJp = m.cellJp();
const int dimension = m.getDimension();
if(dimension == 2)
{
helpers::for_all_I_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
IndexType cellIDTwo = i + j * cellJp;
IndexType cellIDOne = cellIDTwo - 1;
if(i == 0)
{
cellIDOne = cellIDTwo;
cellIDTwo = -1;
}
else if(i == ICellResolution)
{
cellIDTwo = -1;
}
kernel(faceID, cellIDOne, cellIDTwo);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
IndexType cellIDTwo = i + j * cellJp;
IndexType cellIDOne = cellIDTwo - cellJp;
if(j == 0)
{
cellIDOne = cellIDTwo;
cellIDTwo = -1;
}
else if(j == JCellResolution)
{
cellIDTwo = -1;
}
kernel(faceID, cellIDOne, cellIDTwo);
});
}
else
{
SLIC_ERROR_IF(dimension != 3,
"for_all_faces only valid for 2 or 3D meshes.");
const IndexType KCellResolution = m.getCellResolution(K_DIRECTION);
const IndexType cellKp = m.cellKp();
helpers::for_all_I_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
IndexType cellIDTwo = i + j * cellJp + k * cellKp;
IndexType cellIDOne = cellIDTwo - 1;
if(i == 0)
{
cellIDOne = cellIDTwo;
cellIDTwo = -1;
}
else if(i == ICellResolution)
{
cellIDTwo = -1;
}
kernel(faceID, cellIDOne, cellIDTwo);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
IndexType cellIDTwo = i + j * cellJp + k * cellKp;
IndexType cellIDOne = cellIDTwo - cellJp;
if(j == 0)
{
cellIDOne = cellIDTwo;
cellIDTwo = -1;
}
else if(j == JCellResolution)
{
cellIDTwo = -1;
}
kernel(faceID, cellIDOne, cellIDTwo);
});
helpers::for_all_K_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
IndexType cellIDTwo = i + j * cellJp + k * cellKp;
IndexType cellIDOne = cellIDTwo - cellKp;
if(k == 0)
{
cellIDOne = cellIDTwo;
cellIDTwo = -1;
}
else if(k == KCellResolution)
{
cellIDTwo = -1;
}
kernel(faceID, cellIDOne, cellIDTwo);
});
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, Topology TOPO, typename KernelType>
inline void for_all_faces_impl(xargs::cellids,
const UnstructuredMesh<TOPO>& m,
KernelType&& kernel)
{
SLIC_ERROR_IF(m.getNumberOfFaces() <= 0,
"No faces in the mesh, perhaps you meant to call "
<< "UnstructuredMesh::initializeFaceConnectivity first.");
const IndexType* faces_to_cells = m.getFaceCellsArray();
for_all_faces_impl<ExecPolicy>(
xargs::index(),
m,
AXOM_LAMBDA(IndexType faceID) {
const IndexType offset = 2 * faceID;
kernel(faceID, faces_to_cells[offset], faces_to_cells[offset + 1]);
});
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces(xargs::cellids, const Mesh& m, KernelType&& kernel)
{
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
if(m.isStructured())
{
const StructuredMesh& sm = static_cast<const StructuredMesh&>(m);
for_all_faces_impl<ExecPolicy>(xargs::cellids(),
sm,
std::forward<KernelType>(kernel));
}
else if(m.hasMixedCellTypes())
{
const UnstructuredMesh<MIXED_SHAPE>& um =
static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::cellids(),
um,
std::forward<KernelType>(kernel));
}
else
{
const UnstructuredMesh<SINGLE_SHAPE>& um =
static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::cellids(),
um,
std::forward<KernelType>(kernel));
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::coords,
const UniformMesh& m,
KernelType&& kernel)
{
constexpr bool NO_COPY = true;
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
const int dimension = m.getDimension();
const double* origin = m.getOrigin();
const double* spacing = m.getSpacing();
const IndexType nodeJp = m.nodeJp();
const IndexType nodeKp = m.nodeKp();
const double x0 = origin[0];
const double dx = spacing[0];
const double y0 = origin[1];
const double dy = spacing[1];
const double z0 = origin[2];
const double dz = spacing[2];
if(dimension == 2)
{
helpers::for_all_I_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
const IndexType n0 = i + j * nodeJp;
const IndexType nodeIDs[2] = {n0, n0 + nodeJp};
double coords[4] = {x0 + i * dx,
y0 + j * dy,
x0 + i * dx,
y0 + (j + 1) * dy};
numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
const IndexType n0 = i + j * nodeJp;
const IndexType nodeIDs[2] = {n0, n0 + 1};
double coords[4] = {x0 + i * dx,
y0 + j * dy,
x0 + (i + 1) * dx,
y0 + j * dy};
numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
else
{
helpers::for_all_I_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0,
n0 + nodeKp,
n0 + nodeJp + nodeKp,
n0 + nodeJp};
double coords[12] = {x0 + i * dx,
y0 + j * dy,
z0 + k * dz,
x0 + i * dx,
y0 + j * dy,
z0 + (k + 1) * dz,
x0 + i * dx,
y0 + (j + 1) * dy,
z0 + (k + 1) * dz,
x0 + i * dx,
y0 + (j + 1) * dy,
z0 + k * dz};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeKp, n0 + nodeKp};
double coords[12] = {x0 + i * dx,
y0 + j * dy,
z0 + k * dz,
x0 + (i + 1) * dx,
y0 + j * dy,
z0 + k * dz,
x0 + (i + 1) * dx,
y0 + j * dy,
z0 + (k + 1) * dz,
x0 + i * dx,
y0 + j * dy,
z0 + (k + 1) * dz};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_K_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeJp, n0 + nodeJp};
double coords[12] = {x0 + i * dx,
y0 + j * dy,
z0 + k * dz,
x0 + (i + 1) * dx,
y0 + j * dy,
z0 + k * dz,
x0 + (i + 1) * dx,
y0 + (j + 1) * dy,
z0 + k * dz,
x0 + i * dx,
y0 + (j + 1) * dy,
z0 + k * dz};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::coords,
const RectilinearMesh& m,
KernelType&& kernel)
{
constexpr bool NO_COPY = true;
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
const int dimension = m.getDimension();
const IndexType nodeJp = m.nodeJp();
const IndexType nodeKp = m.nodeKp();
const double* x = m.getCoordinateArray(X_COORDINATE);
const double* y = m.getCoordinateArray(Y_COORDINATE);
if(dimension == 2)
{
helpers::for_all_I_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
const IndexType n0 = i + j * nodeJp;
const IndexType nodeIDs[2] = {n0, n0 + nodeJp};
double coords[4] = {x[i], y[j], x[i], y[j + 1]};
numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ij(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j) {
const IndexType n0 = i + j * nodeJp;
const IndexType nodeIDs[2] = {n0, n0 + 1};
double coords[4] = {x[i], y[j], x[i + 1], y[j]};
numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
else
{
const double* z = m.getCoordinateArray(Z_COORDINATE);
helpers::for_all_I_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0,
n0 + nodeKp,
n0 + nodeJp + nodeKp,
n0 + nodeJp};
double coords[12] = {x[i],
y[j],
z[k],
x[i],
y[j],
z[k + 1],
x[i],
y[j + 1],
z[k + 1],
x[i],
y[j + 1],
z[k]};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_J_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeKp, n0 + nodeKp};
double coords[12] = {x[i],
y[j],
z[k],
x[i + 1],
y[j],
z[k],
x[i + 1],
y[j],
z[k + 1],
x[i],
y[j],
z[k + 1]};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
helpers::for_all_K_faces<ExecPolicy>(
xargs::ijk(),
m,
AXOM_LAMBDA(IndexType faceID, IndexType i, IndexType j, IndexType k) {
const IndexType n0 = i + j * nodeJp + k * nodeKp;
const IndexType nodeIDs[4] = {n0, n0 + 1, n0 + 1 + nodeJp, n0 + nodeJp};
double coords[12] = {x[i],
y[j],
z[k],
x[i + 1],
y[j],
z[k],
x[i + 1],
y[j + 1],
z[k],
x[i],
y[j + 1],
z[k]};
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
}
//------------------------------------------------------------------------------
struct for_all_face_nodes_functor
{
template <typename ExecPolicy, typename MeshType, typename KernelType>
inline void operator()(ExecPolicy AXOM_UNUSED_PARAM(policy),
const MeshType& m,
KernelType&& kernel) const
{
constexpr bool valid_mesh_type = std::is_base_of<Mesh, MeshType>::value;
AXOM_STATIC_ASSERT(valid_mesh_type);
for_all_faces_impl<ExecPolicy>(xargs::nodeids(),
m,
std::forward<KernelType>(kernel));
}
};
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces_impl(xargs::coords,
const CurvilinearMesh& m,
KernelType&& kernel)
{
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
const int dimension = m.getDimension();
if(dimension == 2)
{
for_all_coords<ExecPolicy, 2, 2>(for_all_face_nodes_functor(),
m,
std::forward<KernelType>(kernel));
}
else
{
for_all_coords<ExecPolicy, 3, 4>(for_all_face_nodes_functor(),
m,
std::forward<KernelType>(kernel));
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType, Topology TOPO>
inline void for_all_faces_impl(xargs::coords,
const UnstructuredMesh<TOPO>& m,
KernelType&& kernel)
{
constexpr bool NO_COPY = true;
SLIC_ASSERT(m.getDimension() > 1 && m.getDimension() <= 3);
const int dimension = m.getDimension();
const double* x = m.getCoordinateArray(X_COORDINATE);
const double* y = m.getCoordinateArray(Y_COORDINATE);
if(dimension == 2)
{
for_all_faces_impl<ExecPolicy>(
xargs::nodeids(),
m,
AXOM_LAMBDA(IndexType faceID, const IndexType* nodeIDs, IndexType numNodes) {
double coords[2 * MAX_FACE_NODES];
for(int i = 0; i < numNodes; ++i)
{
const IndexType nodeID = nodeIDs[i];
coords[2 * i] = x[nodeID];
coords[2 * i + 1] = y[nodeID];
}
numerics::Matrix<double> coordsMatrix(dimension, 2, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
else
{
const double* z = m.getCoordinateArray(Z_COORDINATE);
for_all_faces_impl<ExecPolicy>(
xargs::nodeids(),
m,
AXOM_LAMBDA(IndexType faceID, const IndexType* nodeIDs, IndexType numNodes) {
double coords[3 * MAX_FACE_NODES];
for(int i = 0; i < numNodes; ++i)
{
const IndexType nodeID = nodeIDs[i];
coords[3 * i] = x[nodeID];
coords[3 * i + 1] = y[nodeID];
coords[3 * i + 2] = z[nodeID];
}
numerics::Matrix<double> coordsMatrix(dimension, 4, coords, NO_COPY);
kernel(faceID, coordsMatrix, nodeIDs);
});
}
}
//------------------------------------------------------------------------------
template <typename ExecPolicy, typename KernelType>
inline void for_all_faces(xargs::coords, const Mesh& m, KernelType&& kernel)
{
SLIC_ERROR_IF(m.getDimension() <= 1 || m.getDimension() > 3,
"Invalid dimension");
if(m.getMeshType() == STRUCTURED_UNIFORM_MESH)
{
const UniformMesh& um = static_cast<const UniformMesh&>(m);
for_all_faces_impl<ExecPolicy>(xargs::coords(),
um,
std::forward<KernelType>(kernel));
}
else if(m.getMeshType() == STRUCTURED_RECTILINEAR_MESH)
{
const RectilinearMesh& rm = static_cast<const RectilinearMesh&>(m);
for_all_faces_impl<ExecPolicy>(xargs::coords(),
rm,
std::forward<KernelType>(kernel));
}
else if(m.getMeshType() == STRUCTURED_CURVILINEAR_MESH)
{
const CurvilinearMesh& cm = static_cast<const CurvilinearMesh&>(m);
for_all_faces_impl<ExecPolicy>(xargs::coords(),
cm,
std::forward<KernelType>(kernel));
}
else if(m.getMeshType() == UNSTRUCTURED_MESH)
{
if(m.hasMixedCellTypes())
{
const UnstructuredMesh<MIXED_SHAPE>& um =
static_cast<const UnstructuredMesh<MIXED_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::coords(),
um,
std::forward<KernelType>(kernel));
}
else
{
const UnstructuredMesh<SINGLE_SHAPE>& um =
static_cast<const UnstructuredMesh<SINGLE_SHAPE>&>(m);
for_all_faces_impl<ExecPolicy>(xargs::coords(),
um,
std::forward<KernelType>(kernel));
}
}
else
{
SLIC_ERROR("Unknown mesh type.");
}
}
} /* namespace internal */
} /* namespace mint */
} /* namespace axom */
#endif /* MINT_FOR_ALL_FACES_HPP_ */
| 34.333964 | 86 | 0.525034 | bmhan12 |
d266b8077013c9ffe750c9f6e334bf630be5fae3 | 4,056 | cpp | C++ | src/Seasons.cpp | powerof3/SeasonsOfSkyrim | 6a35bf36e6c1d808eea6a77a485eb267e0b36236 | [
"MIT"
] | 6 | 2022-01-25T04:15:38.000Z | 2022-03-04T13:02:30.000Z | src/Seasons.cpp | alandtse/SeasonsOfSkyrim | b26893a9bfb82bdcf655d0cbd6551d43e195f651 | [
"MIT"
] | null | null | null | src/Seasons.cpp | alandtse/SeasonsOfSkyrim | b26893a9bfb82bdcf655d0cbd6551d43e195f651 | [
"MIT"
] | 4 | 2022-01-25T04:15:42.000Z | 2022-03-14T02:53:59.000Z | #include "Seasons.h"
void Season::LoadSettings(CSimpleIniA& a_ini, bool a_writeComment)
{
const auto& [seasonType, suffix] = ID;
logger::info("{}", seasonType);
INI::get_value(a_ini, validWorldspaces, seasonType.c_str(), "Worldspaces", a_writeComment ? ";Valid worldspaces." : ";");
INI::get_value(a_ini, swapActivators, seasonType.c_str(), "Activators", a_writeComment ? ";Swap objects of these types for seasonal variants." : ";");
INI::get_value(a_ini, swapFurniture, seasonType.c_str(), "Furniture", nullptr);
INI::get_value(a_ini, swapMovableStatics, seasonType.c_str(), "Movable Statics", nullptr);
INI::get_value(a_ini, swapStatics, seasonType.c_str(), "Statics", nullptr);
INI::get_value(a_ini, swapTrees, seasonType.c_str(), "Trees", nullptr);
INI::get_value(a_ini, swapFlora, seasonType.c_str(), "Flora", nullptr);
INI::get_value(a_ini, swapVFX, seasonType.c_str(), "Visual Effects", nullptr);
INI::get_value(a_ini, swapObjectLOD, seasonType.c_str(), "Object LOD", a_writeComment ? ";Seasonal LOD must be generated using DynDOLOD Alpha 67/SSELODGen Beta 88 or higher.\n;See https://dyndolod.info/Help/Seasons for more info" : ";");
INI::get_value(a_ini, swapTerrainLOD, seasonType.c_str(), "Terrain LOD", nullptr);
INI::get_value(a_ini, swapTreeLOD, seasonType.c_str(), "Tree LOD", nullptr);
INI::get_value(a_ini, swapGrass, seasonType.c_str(), "Grass", a_writeComment ? ";Enable seasonal grass types (eg. snow grass in winter)." : ";");
//make sure LOD has been generated! No need to check form swaps
const auto check_if_lod_exists = [&](bool& a_swaplod, std::string_view a_lodType, std::string_view a_folderName) {
if (a_swaplod) {
const auto folderPath = fmt::format(a_folderName, "Tamriel");
bool exists = false;
try {
if (std::filesystem::exists(folderPath)) {
for (const auto& entry : std::filesystem::directory_iterator(folderPath)) {
if (entry.exists() && entry.is_regular_file() && entry.path().string().contains(suffix)) {
exists = true;
break;
}
}
}
} catch (...) {}
if (!exists) {
a_swaplod = false;
logger::warn(" {} LOD files not found! Default LOD will be used instead", a_lodType);
} else {
logger::info(" {} LOD files found", a_lodType);
}
}
};
check_if_lod_exists(swapTerrainLOD, "Terrain", R"(Data\Meshes\Terrain\{})");
check_if_lod_exists(swapObjectLOD, "Object", R"(Data\Meshes\Terrain\{}\Objects)");
check_if_lod_exists(swapTreeLOD, "Tree", R"(Data\Meshes\Terrain\{}\Trees)");
}
bool Season::CanApplySnowShader() const
{
return season == SEASON::kWinter && is_in_valid_worldspace();
}
bool Season::CanSwapForm(RE::FormType a_formType) const
{
return is_valid_swap_type(a_formType) && is_in_valid_worldspace();
}
bool Season::CanSwapLandscape() const
{
return is_in_valid_worldspace();
}
bool Season::CanSwapLOD(const LOD_TYPE a_type) const
{
if (!is_in_valid_worldspace()) {
return false;
}
switch (a_type) {
case LOD_TYPE::kTerrain:
return swapTerrainLOD;
case LOD_TYPE::kObject:
return swapObjectLOD;
case LOD_TYPE::kTree:
return swapTreeLOD;
default:
return false;
}
}
const SEASON_ID& Season::GetID() const
{
return ID;
}
SEASON Season::GetType() const
{
return season;
}
FormSwapMap& Season::GetFormSwapMap()
{
return formMap;
}
void Season::LoadData(const CSimpleIniA& a_ini)
{
formMap.LoadFormSwaps(a_ini);
if (const auto values = a_ini.GetSection("Grass"); values && !values->empty()) {
useAltGrass = true;
}
if (const auto values = a_ini.GetSection("Worldspaces"); values && !values->empty()) {
std::ranges::transform(*values, std::back_inserter(validWorldspaces), [&](const auto& val) { return val.first.pItem; });
}
}
void Season::SaveData(CSimpleIniA& a_ini)
{
std::ranges::sort(validWorldspaces);
validWorldspaces.erase(std::ranges::unique(validWorldspaces).begin(), validWorldspaces.end());
INI::set_value(a_ini, validWorldspaces, ID.type.c_str(), "Worldspaces", ";Valid worldspaces");
}
bool Season::GetUseAltGrass() const
{
return useAltGrass;
}
| 31.44186 | 238 | 0.709073 | powerof3 |
d26a2c70c3317556e82aa4db4c2d9767e6e90a97 | 1,300 | hpp | C++ | src/accel/bvh.hpp | jkrueger/phosphorus_mk2 | f26330fc2d013ca875d68de78ea9f92f344ddf4e | [
"MIT"
] | 2 | 2019-12-12T04:59:41.000Z | 2020-09-15T12:57:35.000Z | src/accel/bvh.hpp | jkrueger/phosphorus_mk2 | f26330fc2d013ca875d68de78ea9f92f344ddf4e | [
"MIT"
] | 1 | 2020-09-15T12:58:42.000Z | 2020-09-15T12:58:42.000Z | src/accel/bvh.hpp | jkrueger/phosphorus_mk2 | f26330fc2d013ca875d68de78ea9f92f344ddf4e | [
"MIT"
] | null | null | null | #pragma once
#include "../triangle.hpp"
#include "bvh/node.hpp"
#include "bvh/builder.hpp"
#include "math/simd.hpp"
namespace accel {
namespace triangle {
template<int N> struct moeller_trumbore_t;
}
/* this models a regular bounding volume hierarchy, but with n-wide
* nodes, which allows to do multiple bounding volume intersections
* at the same time */
struct mbvh_t {
static const uint32_t width = SIMD_WIDTH;
typedef triangle::moeller_trumbore_t<width> triangle_t;
typedef bvh::builder_t<mbvh::node_t<width>, ::triangle_t> builder_t;
struct details_t;
details_t* details;
// pointer to the beginning of the bvh data structure. this is
// ultimately a flat array of nodes, which represents a linearized
// tree of nodes
mbvh::node_t<width>* root;
// the number of nodes in the tree
uint32_t num_nodes;
// the optimized triangle data structures in the tree. nodes point into this
// array, if they are leaf nodes
triangle_t* triangles;
// number of triangles in the tree
uint32_t num_triangles;
mbvh_t();
~mbvh_t();
/** clear all data from the bvh */
void reset();
builder_t* builder();
// the bounds of the mesh data in this accelerator
Imath::Box3f bounds() const;
};
}
| 25.490196 | 80 | 0.685385 | jkrueger |
d26a321fcfeac98248db1d9c69c4a84976c46354 | 6,814 | hpp | C++ | sources/SceneGraph/Collision/spCollisionConfigTypes.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/SceneGraph/Collision/spCollisionConfigTypes.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/SceneGraph/Collision/spCollisionConfigTypes.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2016-10-31T06:08:44.000Z | 2019-08-02T16:12:33.000Z | /*
* Collision configuration types header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_COLLISION_CONFIG_TYPES_H__
#define __SP_COLLISION_CONFIG_TYPES_H__
#include "Base/spStandard.hpp"
#include "Base/spMeshBuffer.hpp"
#include "SceneGraph/spSceneMesh.hpp"
namespace sp
{
namespace scene
{
/*
* Pre-declerations
*/
class CollisionMaterial;
class CollisionNode;
class CollisionSphere;
class CollisionCapsule;
class CollisionCylinder;
class CollisionCone;
class CollisionBox;
class CollisionPlane;
class CollisionMesh;
/*
* Enumerations
*/
//! Collision models.
enum ECollisionModels
{
COLLISION_NONE = 0, //!< No collision model.
COLLISION_SPHERE, //!< Collision sphere with position and radius.
COLLISION_CAPSULE, //!< Collision capsule with position, rotation, radius and height.
COLLISION_CYLINDER, //!< Collision cylinder with position, rotation, radius and height.
COLLISION_CONE, //!< Collision cone with position, rotation, radius and height.
COLLISION_BOX, //!< Collision box with position, rotation and axis-alined-bounding-box.
COLLISION_PLANE, //!< Collision plane with position and normal vector.
COLLISION_MESH, //!< Collision mesh using kd-Tree.
};
//! Flags for collision detection.
enum ECollisionFlags
{
COLLISIONFLAG_NONE = 0x00, //!< No collision detection, resolving and intersection tests will be performed.
COLLISIONFLAG_DETECTION = 0x01, //!< Collision detection is performed.
COLLISIONFLAG_RESOLVE = 0x02 | COLLISIONFLAG_DETECTION, //!< Collision resolving is performed.
COLLISIONFLAG_INTERSECTION = 0x04, //!< Intersection tests are performed.
COLLISIONFLAG_PERMANENT_UPDATE = 0x08, //!< Collision detection will be performed every frame. Otherwise only when the object has been moved.
//! Collision resolving and intersection tests are performed.
COLLISIONFLAG_FULL =
COLLISIONFLAG_RESOLVE |
COLLISIONFLAG_INTERSECTION |
COLLISIONFLAG_PERMANENT_UPDATE,
};
//! Flags for collision detection support to rival collision nodes.
enum ECollisionSupportFlags
{
COLLISIONSUPPORT_NONE = 0x00, //!< Collision to no rival collision node is supported.
COLLISIONSUPPORT_SPHERE = 0x01, //!< Collision to sphere is supported.
COLLISIONSUPPORT_CAPSULE = 0x02, //!< Collision to capsule is supported.
COLLISIONSUPPORT_CYLINDER = 0x04, //!< Collision to cylinder is supported.
COLLISIONSUPPORT_CONE = 0x08, //!< Collision to cone is supported.
COLLISIONSUPPORT_BOX = 0x10, //!< Collision to box is supported.
COLLISIONSUPPORT_PLANE = 0x20, //!< Collision to plane is supported.
COLLISIONSUPPORT_MESH = 0x40, //!< Collision to mesh is supported.
COLLISIONSUPPORT_ALL = ~0, //!< COllision to any rival collision node is supported.
};
/*
* Structures
*/
struct SCollisionFace
{
SCollisionFace() :
Mesh (0),
Surface (0),
Index (0)
{
}
SCollisionFace(
scene::Mesh* InitMesh, u32 InitSurface, u32 InitIndex, const dim::triangle3df &InitTriangle) :
Mesh (InitMesh ),
Surface (InitSurface ),
Index (InitIndex ),
Triangle(InitTriangle )
{
}
~SCollisionFace()
{
}
/* === Functions === */
//! Returns true if the specified inverse point is on the back side of this face's triangle.
inline bool isBackFaceCulling(const video::EFaceTypes CollFace, const dim::vector3df &InversePoint) const
{
if (CollFace != video::FACE_BOTH)
{
bool isPointFront = dim::plane3df(Triangle).isPointFrontSide(InversePoint);
if ( ( CollFace == video::FACE_FRONT && !isPointFront ) ||
( CollFace == video::FACE_BACK && isPointFront ) )
{
return true;
}
}
return false;
}
//! Returns true if the specified inverse point is on the back side of this face's triangle.
inline bool isBackFaceCulling(const video::EFaceTypes CollFace, const dim::line3df &InverseLine) const
{
if (CollFace != video::FACE_BOTH)
{
bool isPointFrontA = dim::plane3df(Triangle).isPointFrontSide(InverseLine.Start);
bool isPointFrontB = dim::plane3df(Triangle).isPointFrontSide(InverseLine.End);
if ( ( CollFace == video::FACE_FRONT && !isPointFrontA && !isPointFrontB ) ||
( CollFace == video::FACE_BACK && isPointFrontA && isPointFrontB ) )
{
return true;
}
}
return false;
}
/* Members */
scene::Mesh* Mesh;
u32 Surface; //!< Surface index.
u32 Index; //!< Triangle index.
dim::triangle3df Triangle; //!< Triangle face construction.
};
struct SContactBase
{
SContactBase() :
Impact (0.0f ),
Face (0 )
{
}
virtual ~SContactBase()
{
}
/* Members */
dim::vector3df Point; //!< Contact point onto the rival collision-node.
dim::vector3df Normal; //!< Contact normal. Normal vector from the rival collision-node to the source collision-node.
f32 Impact; //!< Contact impact distance.
dim::triangle3df Triangle; //!< Triangle face construction. Only used for mesh contacts.
SCollisionFace* Face; //!< Contact triangle. Only used for mesh contacts.
};
struct SIntersectionContact : public SContactBase
{
SIntersectionContact() :
SContactBase( ),
Object (0 ),
DistanceSq (0.0f )
{
}
~SIntersectionContact()
{
}
/* Operators */
inline bool operator == (const SIntersectionContact &Other) const
{
return Object == Other.Object && Face == Other.Face;
}
/* Members */
const CollisionNode* Object; //!< Constant collision object.
f32 DistanceSq; //!< Squared distance used for internal sorting.
};
struct SCollisionContact : public SContactBase
{
SCollisionContact() :
SContactBase()
{
}
~SCollisionContact()
{
}
/* Operators */
inline bool operator == (const SCollisionContact &Other) const
{
return Face == Other.Face;
}
};
} // /namespace scene
} // /namespace sp
#endif
// ================================================================================
| 30.150442 | 174 | 0.612709 | rontrek |
d270709304d1c91565917bfd4d0c1c804bb31c9d | 2,565 | hpp | C++ | modules/core/include/facekit/core/utils/proto.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/include/facekit/core/utils/proto.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | null | null | null | modules/core/include/facekit/core/utils/proto.hpp | cecabert/FaceKit | 766a32fc7f65ae5deceeba5628c225631986c4d8 | [
"Apache-2.0"
] | 1 | 2017-11-29T12:03:08.000Z | 2017-11-29T12:03:08.000Z | /**
* @file proto.hpp
* @brief Utility function for dealing with protocol buffer object
* @ingroup core
*
* @author Christophe Ecabert
* @date 01.03.18
* Copyright © 2018 Christophe Ecabert. All rights reserved.
*/
#ifndef __FACEKIT_PROTO__
#define __FACEKIT_PROTO__
#include <string>
#include "facekit/core/library_export.hpp"
/**
* @namespace FaceKit
* @brief Development space
*/
namespace FaceKit {
/**
* @name AddVarInt32
* @fn void AddVarInt32(const uint32_t& value, std::string* str)
* @brief Convert a given value into its varint representation and add it to
* a given string
* @param[in] value Value to convert to add
* @param[out] str Buffer in which to add representation
*/
void FK_EXPORTS AddVarInt32(const uint32_t& value, std::string* str);
/**
* @name RetrieveVarInt32
* @fn bool RetrieveVarInt32(std::string* str, uint32_t* value)
* @brief Extract a value from its varint representation stored in a given
* array
* @param[in,out] str Array storing the varints representation
* @param[out] value Extracted value
* @return True if conversion was successfull, false otherwise
*/
bool FK_EXPORTS RetrieveVarInt32(std::string* str, uint32_t* value);
/**
* @name EncodeStringList
* @fn void EncodeStringList(const std::string* list, const size_t& n,
std::string* str)
* @brief Convert array of strings into a single string that can be saved
* into a protobuf object
* @param[in] list Array of string to convert
* @param[in] n Array dimension
* @param[out] str Encoded string
* @ingroup core
*/
void FK_EXPORTS EncodeStringList(const std::string* list,
const size_t& n,
std::string* str);
/**
* @name DecodeStringList
* @fn bool DecodeStringList(const std::string& in, const size_t& n,
std::string* str)
* @brief Split a given string `str` into the corresponding piece stored
* as array. Concatenated comes from protobuf object
* @param[in] in Concatenated string
* @param[in] n Number of string to store in the array
* @param[in,out] str Array of strings
* @return True if successfully decoded, false otherwise
*/
bool FK_EXPORTS DecodeStringList(const std::string& in,
const size_t& n,
std::string* str);
} // namespace FaceKit
#endif /* __FACEKIT_PROTO__ */
| 32.468354 | 78 | 0.634308 | cecabert |
d27350e83f6abfe6deec2e7ab9dbdec631d6aea1 | 3,442 | hpp | C++ | Recorder/src/WaitEventThread.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | 1 | 2015-03-26T02:35:13.000Z | 2015-03-26T02:35:13.000Z | Recorder/src/WaitEventThread.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | Recorder/src/WaitEventThread.hpp | vividos/OldStuff | dbfcce086d1101b576d99d25ef051efbd8dd117c | [
"BSD-2-Clause"
] | null | null | null | //
// Recorder - a GPS logger app for Windows Mobile
// Copyright (C) 2006-2019 Michael Fink
//
/// \file WaitEventThread.hpp WaitEvent() thread
//
#pragma once
#include "WorkerThread.hpp"
#include <boost/bind.hpp>
/// \brief class that implements a worker thread that waits on a serial port for read/write events
/// the class is mainly written for Windows CE when no overlapped support is available; waiting
/// for events is simulated using calling WaitCommEvent() in another thread waiting for an event
/// that gets set when the call returns.
class CWaitEventThread
{
public:
/// ctor
CWaitEventThread(HANDLE hPort)
:m_hPort(hPort),
m_hEventReady(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventWait(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventContinue(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventStop(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_workerThread(boost::bind(&CWaitEventThread::Run, this))
{
}
~CWaitEventThread()
{
// stop background thread
StopThread();
m_workerThread.Join();
CloseHandle(m_hEventReady);
CloseHandle(m_hEventWait);
CloseHandle(m_hEventContinue);
CloseHandle(m_hEventStop);
}
/// \todo only in ready state?
void SetPort(HANDLE hPort)
{
// TODO only in "ready" state?
m_hPort = hPort;
}
/// \todo thread-safe exchange?
void SetMask(DWORD dwEventMask)
{
//ATLTRACE(_T("T1: setting new mask, %08x\n"), dwEventMask);
// TODO thread-safe exchange? only do in "ready" thread state?
m_dwEventMask = dwEventMask;
}
/// waits for thead to be ready to wait for comm event
void WaitForThreadReady()
{
WaitForSingleObject(m_hEventReady, INFINITE);
ResetEvent(m_hEventReady);
}
/// tells thread to continue waiting
void ContinueWait()
{
SetEvent(m_hEventContinue);
}
/// \todo wait for ready thread state
void StopThread()
{
// TODO wait for "ready" thread state
//ATLTRACE(_T("T1: stopping worker thread\n"));
::SetEvent(m_hEventStop);
if (FALSE == ::SetCommMask(m_hPort, 0))
{
DWORD dw = GetLastError();
dw++;
}
//ATLTRACE(_T("T1: stopped worker thread\n"));
}
bool WaitComm();
int Run();
/// returns wait event handle
HANDLE GetWaitEventHandle() const { return m_hEventWait; }
/// returns event result mask
DWORD GetEventResult()
{
// wait event must be set
//ATLTRACE(_T("T2: testing wait event\n"));
DWORD dwTest = ::WaitForSingleObject(m_hEventWait, 0);
//ATLASSERT(WAIT_OBJECT_0 == dwTest);
// note: m_dwEventResult can be accessed without protection from the worker
// thread because it is set when WaitCommEvent() returned.
return m_dwEventResult;
}
private:
DWORD m_dwEventMask;
DWORD m_dwEventResult;
HANDLE m_hPort;
/// when event is set, the wait thread is ready to do a next "wait" task
HANDLE m_hEventReady;
/// when event is set, the WaitCommEvent call returned successfully
HANDLE m_hEventWait;
/// when event is set, the wait thread is allowed to continue with a WaitCommEvent call
HANDLE m_hEventContinue;
/// when event is set, the wait thread should exit
HANDLE m_hEventStop;
/// worker thread
WorkerThread m_workerThread;
};
| 27.536 | 98 | 0.663277 | vividos |
d27772768cf2451195785d4100799ba6e0d8f58c | 22,468 | cpp | C++ | src/test-apps/TestTAKE.cpp | aiw-google/openweave-core | 5dfb14b21d0898ef95bb62ff564cadfeea4b4702 | [
"Apache-2.0"
] | 249 | 2017-09-18T17:48:34.000Z | 2022-02-02T06:46:21.000Z | src/test-apps/TestTAKE.cpp | aiw-google/openweave-core | 5dfb14b21d0898ef95bb62ff564cadfeea4b4702 | [
"Apache-2.0"
] | 501 | 2017-11-10T11:25:32.000Z | 2022-02-01T10:43:13.000Z | src/test-apps/TestTAKE.cpp | aiw-google/openweave-core | 5dfb14b21d0898ef95bb62ff564cadfeea4b4702 | [
"Apache-2.0"
] | 116 | 2017-09-20T07:06:55.000Z | 2022-01-08T13:41:15.000Z | /*
*
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a process to effect a functional test for
* the Weave Token Authenticated Key Exchange (TAKE) protocol
* engine.
*
*/
#include <stdio.h>
#include <string.h>
#include "ToolCommon.h"
#include <Weave/Support/ErrorStr.h>
#include <Weave/Profiles/security/WeaveSecurity.h>
#include <Weave/Profiles/security/WeaveTAKE.h>
#include <Weave/Support/crypto/AESBlockCipher.h>
#include "TAKEOptions.h"
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
#include "lwip/tcpip.h"
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
using namespace nl::Inet;
using namespace nl::Weave::Profiles::Security;
using namespace nl::Weave::Profiles::Security::TAKE;
#define DEBUG_PRINT_ENABLE 0
#define DEBUG_PRINT_MESSAGE_LENGTH 0
#define Clean() \
do { \
if (encodedMsg) \
PacketBuffer::Free(encodedMsg); \
} while (0)
#define VerifyOrFail(TST, MSG) \
do { \
if (!(TST)) \
{ \
fprintf(stderr, "%s FAILED: ", __FUNCTION__); \
fputs(MSG, stderr); \
Clean(); \
exit(-1); \
} \
} while (0)
#define SuccessOrFail(ERR, MSG) \
do { \
if ((ERR) != WEAVE_NO_ERROR) \
{ \
fprintf(stderr, "%s FAILED: ", __FUNCTION__); \
fputs(MSG, stderr); \
fputs(ErrorStr(ERR), stderr); \
fputs("\n", stderr); \
Clean(); \
exit(-1); \
} \
} while (0)
class TAKEConfigNoAuthorized : public MockTAKEChallengerDelegate
{
public:
WEAVE_ERROR GetNextIdentificationKey(uint64_t & tokenId, uint8_t *identificationKey, uint16_t & identificationKeyLen)
{
tokenId = kNodeIdNotSpecified;
return WEAVE_NO_ERROR;
}
};
uint8_t junk0[] = { 0x6a, 0x75, 0x6e, 0x6b, 0x6a, 0x75, 0x6e, 0x6b, 0x6a, 0x75, 0x6e, 0x6b, 0x6a, 0x75, 0x6e, 0x6b };
uint8_t junk1[] = { 0x74, 0x72, 0x61, 0x73, 0x68, 0x74, 0x72, 0x61, 0x73, 0x68, 0x74, 0x72, 0x61, 0x73, 0x68, 0x74 };
uint8_t junk2[] = { 0x74, 0x68, 0x69, 0x73, 0x69, 0x73, 0x61, 0x70, 0x69, 0x6c, 0x65, 0x6f, 0x73, 0x68, 0x69, 0x74 };
class TAKEConfigJunkAuthorized : public MockTAKEChallengerDelegate
{
int position;
public:
TAKEConfigJunkAuthorized() : position(0) { }
WEAVE_ERROR RewindIdentificationKeyIterator()
{
position = 0;
return WEAVE_NO_ERROR;
}
// Get next {tokenId, IK} pair.
// returns tokenId = kNodeIdNotSpecified if no more IKs are available.
WEAVE_ERROR GetNextIdentificationKey(uint64_t & tokenId, uint8_t *identificationKey, uint16_t & identificationKeyLen)
{
if (identificationKeyLen < kIdentificationKeySize)
return WEAVE_ERROR_BUFFER_TOO_SMALL;
identificationKeyLen = kIdentificationKeySize;
switch (position)
{
case 0:
memcpy(identificationKey, junk0, identificationKeyLen);
break;
case 1:
memcpy(identificationKey, junk1, identificationKeyLen);
break;
case 2:
memcpy(identificationKey, junk2, identificationKeyLen);
break;
default:
tokenId = kNodeIdNotSpecified;
break;
}
position++;
return WEAVE_NO_ERROR;
}
};
// This IK correspond to an IK generated with takeTime = 17167, (number of days til 01/01/2017) which is the value used by the test Token auth delegate
uint8_t IK_timeLimited[] = { 0x0F, 0x8E, 0x23, 0x34, 0xA4, 0xA1, 0xF7, 0x60, 0x29, 0x42, 0xB3, 0x4C, 0xA5, 0x28, 0xC5, 0xA9 };
class TAKEConfigTimeLimitedIK : public MockTAKEChallengerDelegate
{
public:
// Get next {tokenId, IK} pair.
// returns tokenId = kNodeIdNotSpecified if no more IKs are available.
WEAVE_ERROR GetNextIdentificationKey(uint64_t & tokenId, uint8_t *identificationKey, uint16_t & identificationKeyLen)
{
if (Rewinded)
{
if (identificationKeyLen < kIdentificationKeySize)
return WEAVE_ERROR_BUFFER_TOO_SMALL;
tokenId = 1;
identificationKeyLen = kIdentificationKeySize;
memcpy(identificationKey, IK_timeLimited, identificationKeyLen);
Rewinded = false;
}
else
{
tokenId = nl::Weave::kNodeIdNotSpecified;
}
return WEAVE_NO_ERROR;
}
};
uint8_t IK_ChallengerIdIsNodeId[] = { 0xAE, 0x2D, 0xD8, 0x16, 0x4B, 0xAE, 0x1A, 0x77, 0xB8, 0xCF, 0x52, 0x0D, 0x20, 0x21, 0xE2, 0x45 };
class TAKEConfigChallengerIdIsNodeId : public MockTAKEChallengerDelegate
{
public:
// Get next {tokenId, IK} pair.
// returns tokenId = kNodeIdNotSpecified if no more IKs are available.
WEAVE_ERROR GetNextIdentificationKey(uint64_t & tokenId, uint8_t *identificationKey, uint16_t & identificationKeyLen)
{
if (Rewinded)
{
if (identificationKeyLen < kIdentificationKeySize)
return WEAVE_ERROR_BUFFER_TOO_SMALL;
tokenId = 1;
identificationKeyLen = kIdentificationKeySize;
memcpy(identificationKey, IK_ChallengerIdIsNodeId, identificationKeyLen);
Rewinded = false;
}
else
{
tokenId = nl::Weave::kNodeIdNotSpecified;
}
return WEAVE_NO_ERROR;
}
};
uint8_t MasterKey[] = { 0x11, 0xFF, 0xF1, 0x1F, 0xD1, 0x3F, 0xB1, 0x5F, 0x91, 0x7F, 0x71, 0x9F, 0x51, 0xBF, 0x31, 0xDF, 0x11, 0xFF, 0xF1, 0x1F, 0xD1, 0x3F, 0xB1, 0x5F, 0x91, 0x7F, 0x71, 0x9F, 0x51, 0xBF, 0x31, 0xDF };
void TestTAKEEngine(WeaveTAKEChallengerAuthDelegate& ChallengerAuthDelegate, bool authorized = true, uint8_t config = kTAKEConfig_Config1, bool encryptAuthPhase = false, bool encryptCommPhase = true, bool timeLimitedIK = false, bool canDoReauth = false, bool sendChallengerId = true)
{
WEAVE_ERROR err;
WeaveTAKEEngine initEng;
WeaveTAKEEngine respEng;
uint16_t sessionKeyIdInitiator = sTestDefaultSessionKeyId;
MockTAKETokenDelegate takeTokenAuthDelegate;
uint64_t challengerNodeId = 1337;
PacketBuffer *encodedMsg = NULL;
const WeaveEncryptionKey *initSessionKey;
const WeaveEncryptionKey *respSessionKey;
// Init TAKE Engines
initEng.Init();
respEng.Init();
initEng.ChallengerAuthDelegate = &ChallengerAuthDelegate;
respEng.TokenAuthDelegate = &takeTokenAuthDelegate;
// Initiator generates and sends Identify Token message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateIdentifyTokenMessage (Started):\n");
#endif
err = initEng.GenerateIdentifyTokenMessage(sessionKeyIdInitiator, config, encryptAuthPhase, encryptCommPhase, timeLimitedIK, sendChallengerId, kWeaveEncryptionType_AES128CTRSHA1, challengerNodeId, encodedMsg);
if (config != kTAKEConfig_Config1)
{
VerifyOrFail(err == WEAVE_ERROR_UNSUPPORTED_TAKE_CONFIGURATION, "GenerateIdentifyTokenMessage: should have returned an error");
Clean();
return;
}
SuccessOrFail(err, "WeaveTAKEEngine::GenerateIdentifyTokenMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateIdentifyTokenMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateIdentifyTokenMessage (Finished):\n");
#endif
}
// Responder receives and processes Identify Token message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessIdentifyTokenMessage (Started):\n");
#endif
err = respEng.ProcessIdentifyTokenMessage(challengerNodeId, encodedMsg); // peerNodeId parameter is not used
if (err == WEAVE_ERROR_TAKE_RECONFIGURE_REQUIRED)
{
VerifyOrFail(config != kTAKEConfig_Config1, "WeaveTAKEEngine::ProcessIdentifyTokenMessage asks for unescessary reconfigure");
Clean();
return;
}
else
{
VerifyOrFail(config == kTAKEConfig_Config1, "WeaveTAKEEngine::ProcessIdentifyTokenMessage do not asks for reconfigure");
SuccessOrFail(err, "WeaveTAKEEngine::ProcessIdentifyTokenMessage failed\n");
}
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessIdentifyTokenMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
// Responder generates and sends Identify Token Response message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateIdentifyTokenResponseMessage (Started):\n");
#endif
err = respEng.GenerateIdentifyTokenResponseMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::GenerateIdentifyTokenResponseMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateIdentifyTokenResponseMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateIdentifyTokenResponseMessage (Finished):\n");
#endif
}
// Initiator receives and processes Identify token Response message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessIdentifyTokenResponseMessage (Started):\n");
#endif
err = initEng.ProcessIdentifyTokenResponseMessage(encodedMsg);
if (!authorized)
{
VerifyOrFail(err == WEAVE_ERROR_TAKE_TOKEN_IDENTIFICATION_FAILED, "Initiator accepted key, but shouldn't have done so\n");
Clean();
return;
}
if (canDoReauth)
{
VerifyOrFail(err == WEAVE_ERROR_TAKE_REAUTH_POSSIBLE, "Initiator should have initiated a Reauth\n");
}
else
{
SuccessOrFail(err, "WeaveTAKEEngine::ProcessIdentifyTokenResponseMessage failed\n");
}
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessIdentifyTokenResponseMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
VerifyOrFail(initEng.SessionKeyId == respEng.SessionKeyId, "Initiator SessionKeyId != Responder SessionKeyId\n");
VerifyOrFail(initEng.ControlHeader == respEng.ControlHeader, "Initiator controlHeader != Responder controlHeader\n");
VerifyOrFail(initEng.EncryptionType == respEng.EncryptionType, "Initiator encryptionType != Responder encryptionType\n");
VerifyOrFail(initEng.ProtocolConfig == respEng.ProtocolConfig, "Initiator protocolConfig != Responder protocolConfig\n");
VerifyOrFail(initEng.GetNumOptionalConfigurations() == respEng.GetNumOptionalConfigurations(), "Initiator numOptionalConfigurations != Responder numOptionalConfigurations\n");
VerifyOrFail(initEng.ProtocolConfig == respEng.ProtocolConfig, "Initiator protocolConfig != Responder protocolConfig\n");
VerifyOrFail(memcmp(initEng.OptionalConfigurations, respEng.OptionalConfigurations, respEng.GetNumOptionalConfigurations()*sizeof(uint8_t)) == 0, "Initiator optionalConfigurations != Responder optionalConfigurations\n");
VerifyOrFail(initEng.IsEncryptAuthPhase() == respEng.IsEncryptAuthPhase(), "Initiator EAP != Responder EAP\n");
VerifyOrFail(initEng.IsEncryptCommPhase() == respEng.IsEncryptCommPhase(), "Initiator ECP != Responder ECP\n");
VerifyOrFail(initEng.IsTimeLimitedIK() == respEng.IsTimeLimitedIK(), "Initiator TL != Responder TL\n");
VerifyOrFail(initEng.ChallengerIdLen == respEng.ChallengerIdLen, "Initiator ChallengerIdLen != Responder ChallengerIdLen\n");
VerifyOrFail(memcmp(initEng.ChallengerId, respEng.ChallengerId, initEng.ChallengerIdLen) == 0, "Initiator ChallengerId != Responder ChallengerId\n");
VerifyOrFail(memcmp(initEng.ChallengerNonce, respEng.ChallengerNonce, kNonceSize) == 0, "Initiator ChallengerNonce != Responder ChallengerNonce\n");
VerifyOrFail(memcmp(initEng.TokenNonce, respEng.TokenNonce, kNonceSize) == 0, "Initiator TokenNonce != Responder TokenNonce\n");
if (encryptAuthPhase)
{
err = initEng.GetSessionKey(initSessionKey);
SuccessOrFail(err, "WeaveTAKEEngine::GetSessionKey() failed\n");
err = respEng.GetSessionKey(respSessionKey);
SuccessOrFail(err, "WeaveTAKEEngine::GetSessionKey() failed\n");
VerifyOrFail(memcmp(initSessionKey->AES128CTRSHA1.DataKey, respSessionKey->AES128CTRSHA1.DataKey, WeaveEncryptionKey_AES128CTRSHA1::DataKeySize) == 0,
"Data key mismatch\n");
VerifyOrFail(memcmp(initSessionKey->AES128CTRSHA1.IntegrityKey, respSessionKey->AES128CTRSHA1.IntegrityKey, WeaveEncryptionKey_AES128CTRSHA1::IntegrityKeySize) == 0,
"Integrity key mismatch\n");
}
if (canDoReauth)
{
// Initiator generates and sends ReAuthenticate Token message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateReAuthenticateTokenMessage (Started):\n");
#endif
err = initEng.GenerateReAuthenticateTokenMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::GenerateReAuthenticateTokenMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateReAuthenticateTokenMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateReAuthenticateTokenMessage (Finished):\n");
#endif
}
// Responder receives and processes REAuthenticate Token message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessReAuthenticateTokenMessage (Started):\n");
#endif
err = respEng.ProcessReAuthenticateTokenMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::ProcessReAuthenticateTokenMessage failed\n");
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessReAuthenticateTokenMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
// Responder generates and sends ReAuthenticate Token Response message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateReAuthenticateTokenResponseMessage (Started):\n");
#endif
err = respEng.GenerateReAuthenticateTokenResponseMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::GenerateReAuthenticateTokenResponseMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateReAuthenticateTokenResponseMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateReAuthenticateTokenResponseMessage (Finished):\n");
#endif
}
// Initiator receives and processes ReAuthenticate Token Response message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessReAuthenticateTokenResponseMessage (Started):\n");
#endif
err = initEng.ProcessReAuthenticateTokenResponseMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::ProcessReAuthenticateTokenResponseMessage failed\n");
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessReAuthenticateTokenResponseMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
}
else
{
// Initiator generates and sends Authenticate Token message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateAuthenticateTokenMessage (Started):\n");
#endif
err = initEng.GenerateAuthenticateTokenMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::GenerateAuthenticateTokenMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateAuthenticateTokenMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateAuthenticateTokenMessage (Finished):\n");
#endif
}
// Responder receives and processes Authenticate Token message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessAuthenticateTokenMessage (Started):\n");
#endif
err = respEng.ProcessAuthenticateTokenMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::ProcessAuthenticateTokenMessage failed\n");
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessAuthenticateTokenMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
// Responder generates and sends Authenticate Token Response message.
{
encodedMsg = PacketBuffer::New();
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateAuthenticateTokenResponseMessage (Started):\n");
#endif
err = respEng.GenerateAuthenticateTokenResponseMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::GenerateAuthenticateTokenResponseMessage failed\n");
#if DEBUG_PRINT_MESSAGE_LENGTH
fprintf(stdout, "GenerateAuthenticateTokenResponseMessage: Message Size = %d \n", encodedMsg->DataLength());
#endif
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "GenerateAuthenticateTokenResponseMessage (Finished):\n");
#endif
}
// Initiator receives and processes Authenticate Token Response message.
{
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessAuthenticateTokenResponseMessage (Started):\n");
#endif
err = initEng.ProcessAuthenticateTokenResponseMessage(encodedMsg);
SuccessOrFail(err, "WeaveTAKEEngine::ProcessAuthenticateTokenResponseMessage failed\n");
#if DEBUG_PRINT_ENABLE
fprintf(stdout, "ProcessAuthenticateTokenResponseMessage (Finished):\n");
#endif
PacketBuffer::Free(encodedMsg);
encodedMsg = NULL;
}
}
if (encryptCommPhase)
{
err = initEng.GetSessionKey(initSessionKey);
SuccessOrFail(err, "WeaveTAKEEngine::GetSessionKey() failed\n");
err = respEng.GetSessionKey(respSessionKey);
SuccessOrFail(err, "WeaveTAKEEngine::GetSessionKey() failed\n");
VerifyOrFail(memcmp(initSessionKey->AES128CTRSHA1.DataKey, respSessionKey->AES128CTRSHA1.DataKey, WeaveEncryptionKey_AES128CTRSHA1::DataKeySize) == 0,
"Data key mismatch\n");
VerifyOrFail(memcmp(initSessionKey->AES128CTRSHA1.IntegrityKey, respSessionKey->AES128CTRSHA1.IntegrityKey, WeaveEncryptionKey_AES128CTRSHA1::IntegrityKeySize) == 0,
"Integrity key mismatch\n");
}
}
void test1(bool EAP, bool ECP)
{
// Standard test, Authenticate
MockTAKEChallengerDelegate config;
TestTAKEEngine(config, true, kTAKEConfig_Config1, EAP, ECP);
}
void test2(bool EAP, bool ECP)
{
// No authorised Tokens
TAKEConfigNoAuthorized config;
TestTAKEEngine(config, false, kTAKEConfig_Config1, EAP, ECP);
}
void test3(bool EAP, bool ECP)
{
// 3 authorised tokens, none of them are the correct one
TAKEConfigJunkAuthorized config;
TestTAKEEngine(config, false, kTAKEConfig_Config1, EAP, ECP);
}
void test4(bool EAP, bool ECP)
{
// Tries to use an invalid config
MockTAKEChallengerDelegate config;
TestTAKEEngine(config, true, 27, EAP, ECP);
}
void test5(bool EAP, bool ECP)
{
// TL is true, invalid argument
TAKEConfigTimeLimitedIK config;
TestTAKEEngine(config, true, kTAKEConfig_Config1, EAP, ECP, true); // TL is true => error
}
void test6(bool EAP, bool ECP)
{
uint8_t AK[] = { 0x9F, 0x0F, 0x92, 0xE3, 0xB9, 0x04, 0x96, 0xA1, 0xCB, 0x7C, 0x94, 0x99, 0xAB, 0x34, 0xDD, 0x04 };
uint8_t ENC_AK[] = { 0xE6, 0xC4, 0x03, 0xE8, 0xEE, 0xA3, 0x80, 0x56, 0xE0, 0xB1, 0x9C, 0xE9, 0xE3, 0xA6, 0xD8, 0x3A };
MockTAKEChallengerDelegate config;
uint16_t authKeyLen = TAKE::kAuthenticationKeySize;
uint16_t encryptedAuthKeyLen = kTokenEncryptedStateSize;
WEAVE_ERROR err = config.StoreTokenAuthData(1, kTAKEConfig_Config1, AK, authKeyLen, ENC_AK, encryptedAuthKeyLen);
if (err != WEAVE_NO_ERROR)
{
fprintf(stderr, "%s FAILED: ", __FUNCTION__);
fputs("TAKEConfig::UpdateAuthenticationKeys", stderr);
fputs(ErrorStr(err), stderr);
fputs("\n", stderr);
exit(-1);
}
TestTAKEEngine(config, true, kTAKEConfig_Config1, EAP, ECP, false, true);
}
void test7(bool EAP, bool ECP)
{
// Standard test, Authenticate
TAKEConfigChallengerIdIsNodeId config;
TestTAKEEngine(config, true, kTAKEConfig_Config1, EAP, ECP, false, false, false);
}
// Parameters are EAP and ECP
typedef void(*testFunction)(bool, bool);
int main(int argc, char *argv[])
{
WEAVE_ERROR err;
int i;
time_t sec_now;
time_t sec_last;
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
tcpip_init(NULL, NULL);
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
err = nl::Weave::Platform::Security::InitSecureRandomDataSource(NULL, 64, NULL, 0);
FAIL_ERROR(err, "InitSecureRandomDataSource() failed");
#define NUMBER_OF_ITERATIONS 1
#define NUMBER_OF_TESTS 7
#define NUMBER_OF_CONFIGS 4
testFunction tests[NUMBER_OF_TESTS] = { test1, test2, test3, test4, test5, test6, test7 };
bool configs[NUMBER_OF_CONFIGS][2] = { { false, false }, { true, false }, { false, true }, { true, true } };
for (int test = 0; test < NUMBER_OF_TESTS; test++)
{
for (int conf = 0; conf < NUMBER_OF_CONFIGS; conf++)
{
bool EAP = configs[conf][0];
bool ECP = configs[conf][1];
printf("\nTEST%d, EAP = %s, ECP = %s (%d iterations)\n", test+1, EAP ? "true" : "false", ECP ? "true" : "false", NUMBER_OF_ITERATIONS);
sec_last = time(NULL);
for (i=0; i < NUMBER_OF_ITERATIONS; i++)
{
tests[test](EAP, ECP);
}
sec_now = time(NULL);
printf("TIME DELTA (sec) = %ld sec\n", (sec_now - sec_last));
}
}
printf("All tests succeeded\n");
}
| 37.014827 | 283 | 0.686977 | aiw-google |
d279be24d0d49882a2c91748a78015c45fedfc20 | 1,026 | cc | C++ | code/render/graphics/stage.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 377 | 2018-10-24T08:34:21.000Z | 2022-03-31T23:37:49.000Z | code/render/graphics/stage.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 11 | 2020-01-22T13:34:46.000Z | 2022-03-07T10:07:34.000Z | code/render/graphics/stage.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 23 | 2019-07-13T16:28:32.000Z | 2022-03-20T09:00:59.000Z | //------------------------------------------------------------------------------
// stage.cc
// (C)2017-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "render/stdneb.h"
#include "stage.h"
namespace Graphics
{
__ImplementClass(Graphics::Stage, 'STAG', Core::RefCounted);
//------------------------------------------------------------------------------
/**
*/
Stage::Stage()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
Stage::~Stage()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
Stage::AttachEntity(const GraphicsEntityId entity)
{
this->entities.Append(entity);
}
//------------------------------------------------------------------------------
/**
*/
void
Stage::DetachEntity(const GraphicsEntityId entity)
{
this->entities.EraseIndex(this->entities.FindIndex(entity));
}
} // namespace Graphics | 22.304348 | 80 | 0.35575 | sirAgg |
d27b6724563ff928837eaef6cdab1c7c2aa134ae | 21,491 | cpp | C++ | src/sim/tcESMSensor.cpp | dhanin/friendly-bassoon | fafcfd3921805baddc1889dc0ee2fa367ad882f8 | [
"BSD-3-Clause"
] | 2 | 2021-11-17T10:59:38.000Z | 2021-11-17T10:59:45.000Z | src/sim/tcESMSensor.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | src/sim/tcESMSensor.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | /**
** @file tcESMSensor.cpp
*/
/*
** Copyright (c) 2014, GCBLUE PROJECT
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdwx.h"
#include "tcESMSensor.h"
#include "aerror.h"
#include "nsNav.h"
#include "tcGameObject.h"
#include "tcMissileObject.h"
#include "tcPlatformObject.h"
#include "tcECM.h"
#include "tcRadar.h"
#include "common/tcStream.h"
#include "common/tcGameStream.h"
#include "common/tcObjStream.h"
#include "tcGameObjIterator.h"
#include "tcSimState.h"
#include "tcMessageInterface.h"
#include "tcEventManager.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
float tcESMSensor::targetRange_km = -88.8f;
float tcESMSensor::last_margin_dB = -88.8f;
float tcESMSensor::last_ERP_dBW = -88.8f;
bool tcESMSensor::rwrUpdate = false;
tcGameStream& tcESMSensor::operator<<(tcGameStream& stream)
{
tcSensorState::operator<<(stream);
stream >> lastRWRupdate;
stream >> rwrWarningLevel;
return stream;
}
tcGameStream& tcESMSensor::operator>>(tcGameStream& stream)
{
tcSensorState::operator>>(stream);
stream << lastRWRupdate;
stream << rwrWarningLevel;
return stream;
}
/**
* Load state from stream
*/
tcUpdateStream& tcESMSensor::operator<<(tcUpdateStream& stream)
{
tcSensorState::operator<<(stream);
stream >> rwrWarningLevel;
return stream;
}
/**
* Save state to stream
*/
tcUpdateStream& tcESMSensor::operator>>(tcUpdateStream& stream)
{
tcSensorState::operator>>(stream);
stream << rwrWarningLevel;
return stream;
}
/**
* This method is used for passive seeker (anti-rad or home-on-jam) detection testing. It
* doesn't build an emitter id list like ProcessESMDetection.
*
* TODO: merge this with ProcessESMDetection method, look at search method that
* uses maximum received power vs. range (cheating?)
*/
bool tcESMSensor::CanDetectTarget(const tcGameObject* target, float& range_km, bool useRandom)
{
float fAz_rad = 0;
range_km = 0;
last_margin_dB = -99.0f; ///< from last call to IsDetected
last_ERP_dBW = -99.0f; ///< from last call to IsDetected
if (const tcMissileObject *pMissileObj = dynamic_cast<const tcMissileObject*>(target))
{
if (tcRadar* emitter = pMissileObj->GetSeekerRadar()) // some AGMs have no sensor
{
bool bDetected = IsDetectedRadar(emitter, fAz_rad);
range_km = targetRange_km;
return bDetected;
}
else
{
return false;
}
}
else if (const tcPlatformObject *pPlatformObj = dynamic_cast<const tcPlatformObject*>(target))
{
if (!pPlatformObj->IsRadiating()) return false;
bool bDetected = false;
unsigned nSensors = pPlatformObj->GetSensorCount();
for (unsigned n=0; (n<nSensors) && (!bDetected); n++)
{
const tcSensorState* sensor = pPlatformObj->GetSensor(n);
if (const tcRadar* emitter = dynamic_cast<const tcRadar*>(sensor))
{
bDetected = bDetected || IsDetectedRadar(emitter, fAz_rad);
range_km = targetRange_km;
}
else if (const tcECM* emitter = dynamic_cast<const tcECM*>(sensor))
{
bDetected = bDetected || IsDetectedECM(emitter, fAz_rad);
range_km = targetRange_km;
}
}
return bDetected;
}
return false; // target class does not have radar, so impossible to detect
}
/**
* @return false if key not found in database
*/
bool tcESMSensor::InitFromDatabase(long key)
{
wxASSERT(database);
tcSensorState::InitFromDatabase(key);
mpDBObj = dynamic_cast<tcESMDBObject*>(database->GetObject(key));
if (mpDBObj == NULL)
{
fprintf(stderr, "Error - tcESMSensor::InitFromDatabase - Not found in db or bad class for key\n");
return false;
}
mfSensorHeight_m = 10.0f;
mnMode = SSMODE_SURVEILLANCE;
mbActive = true;
return true;
}
bool tcESMSensor::IsDetectedECM(const tcECM* emitter, float& az_rad)
{
wxASSERT(emitter);
if (emitter == 0) return false;
float ERP_dBW = emitter->mpDBObj->ERP_dBW; // make ECM easier to detect until model is improved
return IsDetected(emitter, ERP_dBW, az_rad);
}
bool tcESMSensor::IsDetectedRadar(const tcRadar* emitter, float& az_rad)
{
wxASSERT(emitter);
if (emitter == 0) return false;
if (emitter->IsSemiactive()) return false;
float ERP_dBW = emitter->mpDBObj->ERPpeak_dBW;
return IsDetected(emitter, ERP_dBW, az_rad);
}
/**
*
*/
bool tcESMSensor::IsDetected(const tcSensorState* emitter, float ERP_dBW, float& az_rad)
{
wxASSERT(emitter);
wxASSERT(emitter->parent);
targetRange_km = 0;
last_margin_dB = -99.0f;
last_ERP_dBW = -99.0f;
if ((!mbActive) || (!emitter->IsActive())) return false;
float emitterFreq_Hz = emitter->mpDBObj->averageFrequency_Hz;
bool inBand = (mpDBObj->minFrequency_Hz <= emitterFreq_Hz) &&
(mpDBObj->maxFrequency_Hz >= emitterFreq_Hz);
if (!inBand)
{
return false;
}
const tcKinematics& emitter_kin = emitter->parent->mcKin;
float emitterERP_dBW = ERP_dBW;
last_ERP_dBW = ERP_dBW;
float emitterFOV_rad = C_PIOVER180*emitter->mpDBObj->mfFieldOfView_deg;
// look az is az relative to north, might have to change later
// float lookAz_rad = parent->mcKin.mfHeading_rad + mountAz_rad;
float emitterAz_rad = emitter_kin.mfHeading_rad + emitter->mountAz_rad;
float fTargetAz_rad;
float fCoverageAz1, fCoverageAz2;
bool bInSearchVolume = false;
bool bInEmitterScan = false;
wxASSERT(mpDBObj);
wxASSERT(parent);
const tcKinematics& sensor_kin = parent->mcKin; // kinematic state of parent object
fTargetAz_rad = nsNav::GCHeadingApprox_rad(sensor_kin.mfLat_rad, sensor_kin.mfLon_rad,
emitter_kin.mfLat_rad, emitter_kin.mfLon_rad);
az_rad = fTargetAz_rad;
if (az_rad < 0) {az_rad += C_TWOPI;}
if (mpDBObj->mfFieldOfView_deg >= 360.0f)
{
bInSearchVolume = true;
}
else
{
float lookAz_rad = sensor_kin.mfHeading_rad + mountAz_rad;
float fHalfFOV_rad = 0.5f*C_PIOVER180*mpDBObj->mfFieldOfView_deg;
fCoverageAz1 = lookAz_rad - fHalfFOV_rad;
fCoverageAz2 = lookAz_rad + fHalfFOV_rad;
bInSearchVolume = AngleWithinRange(fTargetAz_rad, fCoverageAz1, fCoverageAz2) != 0;
if (!bInSearchVolume) {return false;}
}
// check same for emitter
if (emitterFOV_rad >= C_TWOPIM)
{
bInEmitterScan = true;
}
else
{
float esmBearing_rad = fTargetAz_rad + C_PI; // bearing of ESM platform relative to emitter
if (esmBearing_rad > C_TWOPI) {esmBearing_rad -= C_TWOPI;}
float fHalfFOV_rad = 0.5f * emitterFOV_rad;
fCoverageAz1 = emitterAz_rad - fHalfFOV_rad;
fCoverageAz2 = emitterAz_rad + fHalfFOV_rad;
bInEmitterScan = AngleWithinRange(esmBearing_rad, fCoverageAz1, fCoverageAz2) != 0;
if (!bInEmitterScan) {return false;}
}
float fRadarHorizon = C_RADARHOR*(sqrtf(emitter_kin.mfAlt_m + emitter->mfSensorHeight_m) + sqrtf(sensor_kin.mfAlt_m + mfSensorHeight_m));
targetRange_km = C_RADTOKM*nsNav::GCDistanceApprox_rad(
sensor_kin.mfLat_rad, sensor_kin.mfLon_rad,
emitter_kin.mfLat_rad, emitter_kin.mfLon_rad);
if (targetRange_km > fRadarHorizon)
{
return false;
}
if (!HasLOS(emitter->parent)) return false;
float fSNR = emitterERP_dBW
+ 20.0f*(log10f(mpDBObj->mfRefRange_km)-log10f(targetRange_km));
last_margin_dB = fSNR;
return RandomDetect(fSNR);
}
bool tcESMSensor::IsESM() const
{
return true;
}
/**
*
*/
void tcESMSensor::Serialize(tcFile& file, bool mbLoad)
{
tcSensorState::Serialize(file, mbLoad);
}
void tcESMSensor::Update(double t)
{
if (mnMode == SSMODE_SURVEILLANCE)
{
UpdateSurveillance(t);
}
else if ((mnMode == SSMODE_SEEKERTRACK)||(mnMode == SSMODE_SEEKERSEARCH)
||(mnMode == SSMODE_SEEKERACQUIRE))
{
UpdateSeeker(t);
}
}
/**
* Special update that only looks at sensors on platforms that are targeting parent
*/
bool tcESMSensor::UpdateScanRWR(double t)
{
if (!mbActive || (!mpDBObj->isRWR))
{
rwrWarningLevel = 0;
return false;
}
if ((t - lastRWRupdate) >= 2.0f)
{
lastRWRupdate = t;
return true;
}
else
{
return false;
}
}
/**
* Updates anti-radiation type seekers
*/
void tcESMSensor::UpdateSeeker(double t)
{
if (!UpdateScan(t)) return; // only update once per scan period
long nTargetID;
tcGameObject *ptarget = 0;
int bFound;
switch (mnMode)
{
case SSMODE_SEEKERACQUIRE: // fall through to SEEKERTRACK
case SSMODE_SEEKERTRACK:
nTargetID = mcTrack.mnID;
if (nTargetID == parent->mnID) // no self detection
{
bFound = false;
}
else
{
bFound = simState->maPlatformState.Lookup(nTargetID, ptarget);
}
if (bFound)
{ // own-alliance is allowed
float fRange_km;
if (CanDetectTarget(ptarget, fRange_km))
{
UpdateTrack(ptarget, t);
return;
}
}
/* Shut down missile if track lost for too long
** Missile will coast up until then allowing hits if missile was close enough
** to the target before it shut down
*/
if ((mnMode == SSMODE_SEEKERTRACK)&&
(t - mcTrack.mfTimestamp) > 300.0) // set high for now to coast
{
parent->SelfDestruct();
mcTrack.mnID = NULL_INDEX;
#ifdef _DEBUG
if(simState->mpUserInfo->IsOwnAlliance(parent->GetAlliance()))
{
char zBuff[128];
_snprintf(zBuff, 128, "Mis %d shut down (%s)\n", parent->mnID, parent->mzClass.c_str());
tcMessageInterface::Get()->ConsoleMessage(zBuff);
}
#endif
return;
}
// this code to enter search mode after track lost
//pTrack->mnID = NULL_INDEX;
//apRadarSS->mnMode = SSMODE_SEEKERSEARCH;
break;
case SSMODE_SEEKERSEARCH:
{
// get list of candidate tracks/detections
tcGeoRect region;
GetTestArea(region);
tcGameObjIterator iter(region);
float minRange = 1e15f;
long minID = NULL_INDEX;
// find closest detectable target
for (iter.First();iter.NotDone();iter.Next())
{
tcGameObject *target = iter.Get();
if (target != parent) // no self detection
{
float range_km;
/* Substitute this to disable own-alliance seeker detections:
** bool bDetected = (parent->GetAlliance() != target->GetAlliance()) &&
** CanDetectTarget(target,range_km);
*/
bool bDetected = CanDetectTarget(target, range_km);
if ((bDetected) && (range_km < minRange))
{
minID = target->mnID;
minRange = range_km;
}
}
}
if (minID==NULL_INDEX) return; // no targets found
parent->DesignateTarget(minID); // select closest as target
}
}
}
void tcESMSensor::UpdateSurveillance(double t)
{
if (UpdateScanRWR(t))
{
UpdateSurveillanceRWR(t);
}
if (!UpdateScan(t)) return; // only update once per scan period
tcGeoRect region;
GetTestArea(region);
tcGameObjIterator iter(region);
for (iter.First();iter.NotDone();iter.Next())
{
tcGameObject *target = iter.Get();
ProcessESMDetection(target, t);
}
}
void tcESMSensor::UpdateSurveillanceRWR(double t)
{
wxASSERT(mpDBObj->isRWR);
rwrUpdate = true;
rwrWarningLevel = 0;
std::vector<long> targetersToRemove;
size_t nTargeters = parent->targeters.size();
for (size_t n=0; n<nTargeters; n++)
{
long targeterId = parent->targeters[n];
if (tcGameObject* target = simState->GetObject(targeterId))
{
float range_km = parent->RangeTo(*target);
if (range_km < mpDBObj->mfMaxRange_km)
{
ProcessESMDetection(target, t);
}
}
else
{
targetersToRemove.push_back(targeterId);
}
}
for (size_t n=0; n<targetersToRemove.size(); n++)
{
parent->RemoveTargeter(targetersToRemove[n]);
}
rwrUpdate = false;
}
/**
* Update sensor track with target state. Normally used with
* missile seekers.
* This version cheats since passive sensor can't directly measure range.
*/
void tcESMSensor::UpdateTrack(const tcGameObject* target, double t)
{
mcTrack.mfLat_rad = (float)target->mcKin.mfLat_rad;
mcTrack.mfLon_rad = (float)target->mcKin.mfLon_rad;
// perturb the latitude to simulate track inaccuracy at longer range
if (targetRange_km > 1.0f)
{
mcTrack.mfLat_rad += randfc(1.6e-6 * targetRange_km); // about 100 m of error at 10 km
}
mcTrack.mfAlt_m = target->mcKin.mfAlt_m;
mcTrack.mfSpeed_kts = target->mcKin.mfSpeed_kts;
mcTrack.mfHeading_rad = target->mcKin.mfHeading_rad;
mcTrack.mfClimbAngle_rad = target->mcKin.mfClimbAngle_rad;
mcTrack.mfTimestamp = t;
mcTrack.mnFlags = (TRACK_HEADING_VALID | TRACK_SPEED_VALID
| TRACK_ALT_VALID | TRACK_CLIMB_VALID);
if (mnMode == SSMODE_SEEKERACQUIRE)
{
mnMode = SSMODE_SEEKERTRACK;
//if (simState->mpUserInfo->IsOwnAlliance(parent->GetAlliance()))
//{
// tcSound::Get()->PlayEffect("TwoBeeps");
//}
}
}
void tcESMSensor::ProcessESMDetection(tcGameObject* target, double t)
{
enum {MAX_EMITTERS=4};
float fAz_rad = 0;
wxASSERT(parent);
if (parent->GetAlliance() == target->GetAlliance()) return;
bool bDetected = false;
long maEmitter[MAX_EMITTERS];
int nEmitters = 0;
if (tcMissileObject *pMissileObj = dynamic_cast<tcMissileObject*>(target))
{
if (tcRadar* emitter = pMissileObj->GetSeekerRadar()) // some AGMs have no sensor
{
bDetected = IsDetectedRadar(emitter, fAz_rad);
if ((bDetected) && (nEmitters < MAX_EMITTERS))
{
maEmitter[nEmitters++] = emitter->mnDBKey;
}
if (rwrUpdate && bDetected) rwrWarningLevel = 2;
}
}
else if (tcPlatformObject *pPlatformObj = dynamic_cast<tcPlatformObject*>(target))
{
if (!pPlatformObj->IsRadiating()) return;
unsigned nSensors = pPlatformObj->GetSensorCount();
for (unsigned n=0; n<nSensors; n++)
{
const tcSensorState* sensor = pPlatformObj->GetSensor(n);
if (const tcRadar* emitter = dynamic_cast<const tcRadar*>(sensor))
{
if (IsDetectedRadar(emitter, fAz_rad))
{
bDetected = true;
if (nEmitters < MAX_EMITTERS)
{
maEmitter[nEmitters++] = emitter->mnDBKey;
}
if (rwrUpdate && (rwrWarningLevel == 0)) rwrWarningLevel = 1;
}
}
else if (const tcECM* emitter = dynamic_cast<const tcECM*>(sensor))
{
if (IsDetectedECM(emitter, fAz_rad))
{
bDetected = true;
if (nEmitters < MAX_EMITTERS)
{
maEmitter[nEmitters++] = emitter->mnDBKey;
}
}
}
}
}
if (!bDetected) {return;}
UpdateSensorMap(target, maEmitter, nEmitters, fAz_rad, t);
}
/**
* Called after ESM detection to update sensor map
*/
void tcESMSensor::UpdateSensorMap(const tcGameObject* target, long* emitters, unsigned int nEmitters,
float az_rad, double t)
{
tcSensorMapTrack *pSMTrack = 0;
wxASSERT(simState);
wxASSERT(emitters);
if (targetRange_km == 0)
{
targetRange_km = parent->mcKin.RangeToKmAlt(target); // target range may not be updated when multiple emitters on target
}
// call update to check for this report already in track, or for an empty slot
tcSensorReport* report =
simState->mcSensorMap.GetOrCreateReport(parent->mnID, mpDBObj->mnKey, target->mnID, pSMTrack, parent->GetAlliance());
// update passive report if available
if (report != 0)
{
//bool bNewReport = report->IsNew();
//if (bNewReport) // new detection report
//{
// // RWR reports jump to classify and range info much quicker
// report->startTime = rwrUpdate ? t - 60.0f : t;
//}
tcSensorState::UpdatePassiveReport(report, t, az_rad, targetRange_km, pSMTrack);
double trackLife = report->GetTrackLife();
unsigned int nClassification = target->mpDBObject->mnType;
bool isMissile = (nClassification & PTYPE_MISSILE) != 0;
bool updateClassification = (isMissile || (trackLife > 30.0));
// TODO: problem here with radar and ESM updates competing
// need to merge updates vs. taking first one only
if (updateClassification)
{
report->classification = nClassification & 0xFFF0;
if (isMissile)
{
report->alliance = target->GetAlliance();
}
//tcAllianceInfo::Affiliation eAffil = tcAllianceInfo::UNKNOWN;
//if (isMissile)
//{
// eAffil = tcAllianceInfo::HOSTILE;
//}
//pSMTrack->UpdateClassification(nClassification & 0xFFF0, eAffil, NULL_INDEX);
//tcEventManager::Get()->UpdatedContact(parent->GetAlliance(), pSMTrack);
}
else
{
report->classification = 0;
}
bool bNewDetection = pSMTrack->IsNew();
if (bNewDetection)
{
pSMTrack->UpdateTrack(0);
tcEventManager::Get()->NewContact(parent->GetAlliance(), pSMTrack);
if (simState->mpUserInfo->IsOwnAlliance(parent->GetAlliance()))
{
tcSound::Get()->PlayEffect("Ping");
}
//char zBuff[128];
//sprintf(zBuff, "target %d detected with ESM at %3.1f deg at time %.1f [a:%d]",
// target->mnID, az_rad, t, parent->GetAlliance());
//WTLC(zBuff);
}
/* this section is called even if no free reports are available, (?)
** so that ESM can update classification and emitters
*/
// update emitter info
report->emitterList.clear();
if (last_margin_dB >= mpDBObj->idThreshold_dB)
{
for (unsigned int n=0; n<nEmitters; n++)
{
report->emitterList.push_back(emitters[n]);
}
}
}
}
/**
*
*/
tcESMSensor& tcESMSensor::operator=(tcESMSensor& ss)
{
tcSensorState::operator =(ss);
mpDBObj = ss.mpDBObj;
return(*this);
}
#if 0
/**
* Load state from stream
*/
tcStream& tcESMSensor::operator<<(tcStream& stream)
{
tcSensorState::operator<<(stream);
return stream;
}
/**
* Save state to stream
*/
tcStream& tcESMSensor::operator>>(tcStream& stream)
{
tcSensorState::operator>>(stream);
return stream;
}
#endif
/**
*
*/
tcESMSensor* tcESMSensor::Clone(void)
{
tcESMSensor *pNew = new tcESMSensor();
*pNew = *this;
return pNew;
}
unsigned char tcESMSensor::GetRWRWarningLevel() const
{
return rwrWarningLevel;
}
/**
*
*/
tcESMSensor::tcESMSensor()
: tcSensorState()
{
mpDBObj = NULL;
}
tcESMSensor::tcESMSensor(tcESMDBObject* dbObj)
: tcSensorState(dbObj),
mpDBObj(dbObj),
lastRWRupdate(0),
rwrWarningLevel(0)
{
wxASSERT(dbObj);
mfSensorHeight_m = 10.0f;
mnMode = SSMODE_SURVEILLANCE;
mbActive = true;
}
/**
*
*/
tcESMSensor::~tcESMSensor() {} | 27.482097 | 146 | 0.627007 | dhanin |
d27d1696d8ed42ec726e940b9cf9f5dfc88a00fb | 7,762 | cc | C++ | src/corbaExample/src/cpp/RemoteFileServerSK.cc | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 7 | 2016-04-05T15:58:01.000Z | 2020-10-30T18:38:05.000Z | src/corbaExample/src/cpp/RemoteFileServerSK.cc | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 2 | 2016-07-04T01:32:56.000Z | 2020-12-11T02:54:56.000Z | src/corbaExample/src/cpp/RemoteFileServerSK.cc | jahlborn/rmiio | 58c05f29e6dbc44c0f18c9a2247aff113d487c71 | [
"Apache-2.0"
] | 6 | 2016-04-05T15:58:16.000Z | 2020-04-27T21:45:47.000Z | // This file is generated by omniidl (C++ backend)- omniORB_4_1. Do not edit.
#include "RemoteFileServer.hh"
#include <omniORB4/IOP_S.h>
#include <omniORB4/IOP_C.h>
#include <omniORB4/callDescriptor.h>
#include <omniORB4/callHandle.h>
#include <omniORB4/objTracker.h>
OMNI_USING_NAMESPACE(omni)
static const char* _0RL_library_version = omniORB_4_1;
examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer_Helper::_nil() {
return ::examples::iiop::RemoteFileServer::_nil();
}
CORBA::Boolean examples::iiop::RemoteFileServer_Helper::is_nil(::examples::iiop::RemoteFileServer_ptr p) {
return CORBA::is_nil(p);
}
void examples::iiop::RemoteFileServer_Helper::release(::examples::iiop::RemoteFileServer_ptr p) {
CORBA::release(p);
}
void examples::iiop::RemoteFileServer_Helper::marshalObjRef(::examples::iiop::RemoteFileServer_ptr obj, cdrStream& s) {
::examples::iiop::RemoteFileServer::_marshalObjRef(obj, s);
}
examples::iiop::RemoteFileServer_ptr examples::iiop::RemoteFileServer_Helper::unmarshalObjRef(cdrStream& s) {
return ::examples::iiop::RemoteFileServer::_unmarshalObjRef(s);
}
void examples::iiop::RemoteFileServer_Helper::duplicate(::examples::iiop::RemoteFileServer_ptr obj) {
if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj);
}
examples::iiop::RemoteFileServer_ptr
examples::iiop::RemoteFileServer::_duplicate(::examples::iiop::RemoteFileServer_ptr obj)
{
if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj);
return obj;
}
examples::iiop::RemoteFileServer_ptr
examples::iiop::RemoteFileServer::_narrow(CORBA::Object_ptr obj)
{
if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil();
_ptr_type e = (_ptr_type) obj->_PR_getobj()->_realNarrow(_PD_repoId);
return e ? e : _nil();
}
examples::iiop::RemoteFileServer_ptr
examples::iiop::RemoteFileServer::_unchecked_narrow(CORBA::Object_ptr obj)
{
if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil();
_ptr_type e = (_ptr_type) obj->_PR_getobj()->_uncheckedNarrow(_PD_repoId);
return e ? e : _nil();
}
examples::iiop::RemoteFileServer_ptr
examples::iiop::RemoteFileServer::_nil()
{
#ifdef OMNI_UNLOADABLE_STUBS
static _objref_RemoteFileServer _the_nil_obj;
return &_the_nil_obj;
#else
static _objref_RemoteFileServer* _the_nil_ptr = 0;
if( !_the_nil_ptr ) {
omni::nilRefLock().lock();
if( !_the_nil_ptr ) {
_the_nil_ptr = new _objref_RemoteFileServer;
registerNilCorbaObject(_the_nil_ptr);
}
omni::nilRefLock().unlock();
}
return _the_nil_ptr;
#endif
}
const char* examples::iiop::RemoteFileServer::_PD_repoId = "RMI:examples.iiop.RemoteFileServer:0000000000000000";
examples::iiop::_objref_RemoteFileServer::~_objref_RemoteFileServer() {
}
examples::iiop::_objref_RemoteFileServer::_objref_RemoteFileServer(omniIOR* ior, omniIdentity* id) :
omniObjRef(::examples::iiop::RemoteFileServer::_PD_repoId, ior, id, 1)
{
_PR_setobj(this);
}
void*
examples::iiop::_objref_RemoteFileServer::_ptrToObjRef(const char* id)
{
if( id == ::examples::iiop::RemoteFileServer::_PD_repoId )
return (::examples::iiop::RemoteFileServer_ptr) this;
if( id == ::CORBA::Object::_PD_repoId )
return (::CORBA::Object_ptr) this;
if( omni::strMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) )
return (::examples::iiop::RemoteFileServer_ptr) this;
if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) )
return (::CORBA::Object_ptr) this;
return 0;
}
// Proxy call descriptor class. Mangled signature:
// void_i_ccom_mhealthmarketscience_mrmiio_mRemoteInputStream_e_cjava_mio_mIOEx
class _0RL_cd_5EAB75CAD9A547B4_00000000
: public omniCallDescriptor
{
public:
inline _0RL_cd_5EAB75CAD9A547B4_00000000(LocalCallFn lcfn,const char* op_,size_t oplen,_CORBA_Boolean upcall=0):
omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 1, upcall)
{
}
void marshalArguments(cdrStream&);
void unmarshalArguments(cdrStream&);
void userException(cdrStream&,_OMNI_NS(IOP_C)*,const char*);
static const char* const _user_exns[];
com::healthmarketscience::rmiio::RemoteInputStream_var arg_0_;
com::healthmarketscience::rmiio::RemoteInputStream_ptr arg_0;
};
void _0RL_cd_5EAB75CAD9A547B4_00000000::marshalArguments(cdrStream& _n)
{
com::healthmarketscience::rmiio::RemoteInputStream_Helper::marshalObjRef(arg_0,_n);
}
void _0RL_cd_5EAB75CAD9A547B4_00000000::unmarshalArguments(cdrStream& _n)
{
arg_0_ = com::healthmarketscience::rmiio::RemoteInputStream_Helper::unmarshalObjRef(_n);
arg_0 = arg_0_.in();
}
const char* const _0RL_cd_5EAB75CAD9A547B4_00000000::_user_exns[] = {
java::io::IOEx::_PD_repoId
};
void _0RL_cd_5EAB75CAD9A547B4_00000000::userException(cdrStream& s, _OMNI_NS(IOP_C)* iop_client, const char* repoId)
{
if ( omni::strMatch(repoId, java::io::IOEx::_PD_repoId) ) {
java::io::IOEx _ex;
_ex <<= s;
if (iop_client) iop_client->RequestCompleted();
throw _ex;
}
else {
if (iop_client) iop_client->RequestCompleted(1);
OMNIORB_THROW(UNKNOWN,UNKNOWN_UserException,
(CORBA::CompletionStatus)s.completion());
}
}
// Local call call-back function.
static void
_0RL_lcfn_5EAB75CAD9A547B4_10000000(omniCallDescriptor* cd, omniServant* svnt)
{
_0RL_cd_5EAB75CAD9A547B4_00000000* tcd = (_0RL_cd_5EAB75CAD9A547B4_00000000*)cd;
examples::iiop::_impl_RemoteFileServer* impl = (examples::iiop::_impl_RemoteFileServer*) svnt->_ptrToInterface(examples::iiop::RemoteFileServer::_PD_repoId);
#ifdef HAS_Cplusplus_catch_exception_by_base
impl->sendFile(tcd->arg_0);
#else
if (!cd->is_upcall())
impl->sendFile(tcd->arg_0);
else {
try {
impl->sendFile(tcd->arg_0);
}
catch(java::io::IOEx& ex) {
throw omniORB::StubUserException(ex._NP_duplicate());
}
}
#endif
}
void examples::iiop::_objref_RemoteFileServer::sendFile(com::healthmarketscience::rmiio::RemoteInputStream_ptr arg0)
{
_0RL_cd_5EAB75CAD9A547B4_00000000 _call_desc(_0RL_lcfn_5EAB75CAD9A547B4_10000000, "sendFile", 9);
_call_desc.arg_0 = arg0;
_invoke(_call_desc);
}
examples::iiop::_pof_RemoteFileServer::~_pof_RemoteFileServer() {}
omniObjRef*
examples::iiop::_pof_RemoteFileServer::newObjRef(omniIOR* ior, omniIdentity* id)
{
return new ::examples::iiop::_objref_RemoteFileServer(ior, id);
}
CORBA::Boolean
examples::iiop::_pof_RemoteFileServer::is_a(const char* id) const
{
if( omni::ptrStrMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) )
return 1;
return 0;
}
const examples::iiop::_pof_RemoteFileServer _the_pof_examples_miiop_mRemoteFileServer;
examples::iiop::_impl_RemoteFileServer::~_impl_RemoteFileServer() {}
CORBA::Boolean
examples::iiop::_impl_RemoteFileServer::_dispatch(omniCallHandle& _handle)
{
const char* op = _handle.operation_name();
if( omni::strMatch(op, "sendFile") ) {
_0RL_cd_5EAB75CAD9A547B4_00000000 _call_desc(_0RL_lcfn_5EAB75CAD9A547B4_10000000, "sendFile", 9, 1);
_handle.upcall(this,_call_desc);
return 1;
}
return 0;
}
void*
examples::iiop::_impl_RemoteFileServer::_ptrToInterface(const char* id)
{
if( id == ::examples::iiop::RemoteFileServer::_PD_repoId )
return (::examples::iiop::_impl_RemoteFileServer*) this;
if( id == ::CORBA::Object::_PD_repoId )
return (void*) 1;
if( omni::strMatch(id, ::examples::iiop::RemoteFileServer::_PD_repoId) )
return (::examples::iiop::_impl_RemoteFileServer*) this;
if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) )
return (void*) 1;
return 0;
}
const char*
examples::iiop::_impl_RemoteFileServer::_mostDerivedRepoId()
{
return ::examples::iiop::RemoteFileServer::_PD_repoId;
}
POA_examples::iiop::RemoteFileServer::~RemoteFileServer() {}
| 27.820789 | 159 | 0.741304 | jahlborn |
d27f9baccf2d0070e506fc3f5a58051b2afa2117 | 1,039 | cpp | C++ | geospatial/test/cpp/suites/Cover.cpp | icarazob/mr4c | fe367fac1d634fe5cea477e14ba39d0df630255f | [
"Apache-2.0"
] | 1,062 | 2015-02-18T18:26:33.000Z | 2022-03-23T10:16:07.000Z | geospatial/test/cpp/suites/Cover.cpp | syzf1314/mr4c | fe367fac1d634fe5cea477e14ba39d0df630255f | [
"Apache-2.0"
] | 22 | 2015-02-24T03:09:18.000Z | 2020-07-04T05:53:10.000Z | geospatial/test/cpp/suites/Cover.cpp | syzf1314/mr4c | fe367fac1d634fe5cea477e14ba39d0df630255f | [
"Apache-2.0"
] | 315 | 2015-02-18T22:29:52.000Z | 2022-01-24T06:29:40.000Z | /**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TextTestRunner.h>
#include "MR4CGeoTests.h"
// local test runner that just dumps to the console
int main( int argc, char* argv[])
{
std::string name = MR4C::extractTestName(argc, argv);
CPPUNIT_NS::TextTestRunner testrunner;
testrunner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry(name).makeTest());
testrunner.run();
}
| 33.516129 | 84 | 0.737247 | icarazob |
d2817fdc1cecd6818bc37383ccb537ab035c409e | 32,675 | cpp | C++ | Classes/HelloWorldScene.cpp | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | Classes/HelloWorldScene.cpp | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | Classes/HelloWorldScene.cpp | otakuidoru/Reflection | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <cmath>
#include <sstream>
#include <sqlite3.h>
#include "LevelSelectScene.h"
#include "HelloWorldScene.h"
#include "BackArrow.h"
#include "ResetButton.h"
#include "Indicator.h"
#define BACKGROUND_LAYER -1
#define LASER_LAYER 1
#define OBJECT_LAYER 2
#define BACK_ARROW_LAYER 255
#define RESET_LAYER 253
#define INTRO_LAYER 254
USING_NS_CC;
static const float DEGTORAD = 0.0174532925199432957f;
static const float RADTODEG = 57.295779513082320876f;
/**
*
*/
Scene* HelloWorld::createScene(const std::string& levelFilename, int levelId, int worldId) {
return HelloWorld::create(levelFilename, levelId, worldId);
}
/**
* Print useful error message instead of segfaulting when files are not there.
*/
static void problemLoading(const char* filename) {
log("Error while loading: %s\n", filename);
log("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
/**
*
*/
static int levelUnlockCallback(void* object, int argc, char** data, char** azColName) {
return 0;
}
/**
*
*/
HelloWorld* HelloWorld::create(const std::string& levelFilename, int levelId, int worldId) {
HelloWorld* ret = new (std::nothrow) HelloWorld();
if (ret && ret->init(levelFilename, levelId, worldId)) {
ret->autorelease();
return ret;
} else {
CC_SAFE_DELETE(ret);
return nullptr;
}
}
/**
* on "init" you need to initialize your instance
*/
bool HelloWorld::init(const std::string& levelFilename, int levelId, int worldId) {
//////////////////////////////
// 1. super init first
if (!Scene::init()) {
return false;
}
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
const float scale = std::min(visibleSize.width/1536.0f, visibleSize.height/2048.0f);
this->levelId = levelId;
this->worldId = worldId;
this->levelFilename = levelFilename;
this->introLayers = IntroLayerMultiplex::create();
//this->introLayers->setPosition(Vec2(origin.x + visibleSize.width/2.0f, origin.y + visibleSize.height/2.0f));
this->addChild(this->introLayers, 255);
/////////////////////////////
// 2. add your codes below...
strToColorTypeMap = {
{"NONE", ColorType::NONE},
{"RED", ColorType::RED},
{"GREEN", ColorType::GREEN},
{"BLUE", ColorType::BLUE},
{"YELLOW", ColorType::YELLOW},
{"ORANGE", ColorType::ORANGE},
{"PURPLE", ColorType::PURPLE},
{"WHITE", ColorType::WHITE},
{"BLACK", ColorType::BLACK}
};
colorTypeToObjectColor3BMap = {
{ColorType::NONE, Color3B(255, 255, 255)},
{ColorType::RED, Color3B(255, 153, 153)},
{ColorType::GREEN, Color3B(153, 255, 153)},
{ColorType::BLUE, Color3B(153, 153, 255)},
{ColorType::YELLOW, Color3B(255, 255, 255)}, // TODO
{ColorType::ORANGE, Color3B(255, 255, 255)}, // TODO
{ColorType::PURPLE, Color3B(255, 255, 255)}, // TODO
{ColorType::WHITE, Color3B(255, 255, 255)},
{ColorType::BLACK, Color3B( 0, 0, 0)}
};
colorTypeToLaserColor3BMap = {
{ColorType::NONE, Color3B(255, 255, 255)},
{ColorType::RED, Color3B(255, 0, 0)},
{ColorType::GREEN, Color3B(0, 255, 0)},
{ColorType::BLUE, Color3B(0, 0, 255)},
{ColorType::YELLOW, Color3B(255, 255, 0)},
{ColorType::ORANGE, Color3B(251, 139, 35)},
{ColorType::PURPLE, Color3B(148, 0, 211)},
{ColorType::WHITE, Color3B(255, 255, 255)},
{ColorType::BLACK, Color3B( 0, 0, 0)}
};
strToDirectionMap = {
{"NORTH", Direction::NORTH },
{"NORTHEAST", Direction::NORTHEAST},
{"EAST", Direction::EAST },
{"SOUTHEAST", Direction::SOUTHEAST},
{"SOUTH", Direction::SOUTH },
{"SOUTHWEST", Direction::SOUTHWEST},
{"WEST", Direction::WEST },
{"NORTHWEST", Direction::NORTHWEST},
};
auto background = LayerGradient::create(Color4B(253, 158, 246, 255), Color4B(255, 255, 255, 255), Vec2(1.0f, 1.0f));
this->addChild(background, BACKGROUND_LAYER);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#define PATH_SEPARATOR "\\"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#define PATH_SEPARATOR "/"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define PATH_SEPARATOR "\/"
#endif
std::stringstream source;
source << this->levelFilename;
//log("com.zenprogramming.reflection: Source Filename = %s", source.str().c_str());
std::stringstream target;
target << FileUtils::getInstance()->getWritablePath() << "level.xml";
//log("com.zenprogramming.reflection: Target Filename = %s", target.str().c_str());
// copy the file to the writable area on the device
// (have to do this for TinyXML to read the file)
FileUtils::getInstance()->writeStringToFile(FileUtils::getInstance()->getStringFromFile(source.str()), target.str());
this->createLevel(target.str());
if (!this->introLayers->isEmpty()) {
this->introLayers->switchTo(0);
}
// create the back arrow
auto backArrow = BackArrow::create();
backArrow->onClick = [&]() {
auto levelSelectScene = LevelSelect::create(this->worldId);
Director::getInstance()->replaceScene(TransitionFade::create(0.5f, levelSelectScene, Color3B(0, 0, 0)));
};
backArrow->setColor(Color3B(255, 255, 255));
backArrow->setScale(visibleSize.width / 1536.0f);
backArrow->setPosition(Vec2(origin.x + backArrow->getContentSize().width / 2.0f, origin.y + backArrow->getContentSize().height / 2.0f));
this->addChild(backArrow, BACK_ARROW_LAYER);
// create the reset button
auto resetButton = ResetButton::create();
resetButton->onClick = [&]() {
auto levelScene = HelloWorld::createScene(this->levelFilename, this->levelId, this->worldId);
Director::getInstance()->replaceScene(TransitionFade::create(0.5f, levelScene, Color3B(0, 0, 0)));
};
resetButton->setColor(Color3B(255, 255, 255));
resetButton->setScale(visibleSize.width / 1536.0f);
resetButton->setPosition(Vec2(origin.x + visibleSize.width - resetButton->getContentSize().width / 2.0f, origin.y + resetButton->getContentSize().height / 2.0f));
this->addChild(resetButton, RESET_LAYER);
//////////////////////////////////////////////////////////////////////////////
//
// Create a "one by one" touch event listener (processes one touch at a time)
//
//////////////////////////////////////////////////////////////////////////////
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->setSwallowTouches(true);
// triggered when pressed
touchListener->onTouchBegan = [&](Touch* touch, Event* event) -> bool {
bool consuming = false;
if (this->introLayers->getEnabledLayerIndex() < this->introLayers->getNumLayers()) {
consuming = true;
this->introLayers->getEnabledLayer()->runAction(Sequence::create(
FadeOut::create(1.0f),
CallFunc::create([&]() {
if (this->introLayers->getEnabledLayerIndex() < this->introLayers->getNumLayers()-1) {
this->introLayers->switchTo(this->introLayers->getEnabledLayerIndex()+1);
} else if (this->introLayers->getEnabledLayerIndex() == this->introLayers->getNumLayers()-1) {
this->introLayers->removeFromParent();
}
}),
nullptr
));
}
return consuming;
};
// triggered when moving touch
touchListener->onTouchMoved = [&](Touch* touch, Event* event) {};
// triggered when released
touchListener->onTouchEnded = [&](Touch* touch, Event* event) {};
// add listener
this->introLayers->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this->introLayers);
//////////////////////////////////////////////////////////////////////////////
//
//
//
//////////////////////////////////////////////////////////////////////////////
this->ready = true;
this->scheduleUpdate();
return true;
}
/**
*
*/
void HelloWorld::addEmitters(tinyxml2::XMLElement* const emittersElement, float scale) {
if (emittersElement) {
tinyxml2::XMLElement* emitterElement = emittersElement->FirstChildElement("emitter");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (emitterElement) {
// id
int id;
emitterElement->QueryIntAttribute("id", &id);
// color type
std::string colorTypeStr(emitterElement->FirstChildElement("colortype")->GetText());
const ColorType colorType = this->strToColorTypeMap[colorTypeStr];
// create emitter
auto emitter = Emitter::create(id, colorType);
emitter->onAfterActivate = [&]() {};
this->emitters.insert(emitter);
this->objects.insert(emitter);
// set emitter color
const Color3B color = colorTypeToObjectColor3BMap[colorType];
emitter->setColor(color);
// set emitter scale
emitter->setScale(scale);
// set emitter position
float x, y;
tinyxml2::XMLElement* positionElement = emitterElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
emitter->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
// set emitter direction
std::string directionStr(emitterElement->FirstChildElement("direction")->GetText());
emitter->setDirection(strToDirectionMap[directionStr]);
// set emitter active
std::string activeStr = emitterElement->FirstChildElement("active")->GetText();
emitter->setActive(!activeStr.compare("true"));
// add the emitter to the scene
this->addChild(emitter, OBJECT_LAYER);
emitterElement = emitterElement->NextSiblingElement("emitter");
}
}
}
/**
*
*/
void HelloWorld::addMirrors(tinyxml2::XMLElement* const mirrorsElement, float scale) {
if (mirrorsElement) {
tinyxml2::XMLElement* mirrorElement = mirrorsElement->FirstChildElement("mirror");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (mirrorElement) {
// id
int id;
mirrorElement->QueryIntAttribute("id", &id);
// create mirror
auto mirror = Mirror::create(id);
mirror->onBeforeRotate = [&]() {};
mirror->onAfterRotate = [&]() {};
this->mirrors.insert(mirror);
this->objects.insert(mirror);
// set mirror scale
mirror->setScale(scale);
// set mirror position
float x, y;
tinyxml2::XMLElement* positionElement = mirrorElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
mirror->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
// set mirror direction
std::string directionStr(mirrorElement->FirstChildElement("direction")->GetText());
mirror->setDirection(strToDirectionMap[directionStr]);
// add the mirror to the scene
this->addChild(mirror, OBJECT_LAYER);
mirrorElement = mirrorElement->NextSiblingElement("mirror");
}
}
}
/**
*
*/
void HelloWorld::addReceptors(tinyxml2::XMLElement* const receptorsElement, float scale) {
if (receptorsElement) {
tinyxml2::XMLElement* receptorElement = receptorsElement->FirstChildElement("receptor");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (receptorElement) {
// id
int id;
receptorElement->QueryIntAttribute("id", &id);
// color type
std::string colorTypeStr(receptorElement->FirstChildElement("colortype")->GetText());
const ColorType colorType = this->strToColorTypeMap[colorTypeStr];
// create receptor
auto receptor = Receptor::create(id, colorType);
this->receptors.insert(receptor);
this->objects.insert(receptor);
// set receptor color
const Color3B color = colorTypeToObjectColor3BMap[colorType];
receptor->setColor(color);
// set receptor scale
receptor->setScale(scale);
// set receptor position
float x, y;
tinyxml2::XMLElement* positionElement = receptorElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
receptor->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
// set receptor direction
std::string directionStr(receptorElement->FirstChildElement("direction")->GetText());
receptor->setDirection(strToDirectionMap[directionStr]);
// add the receptor to the scene
this->addChild(receptor, OBJECT_LAYER);
receptorElement = receptorElement->NextSiblingElement("receptor");
}
}
}
/**
*
*/
void HelloWorld::addBlocks(tinyxml2::XMLElement* const blocksElement, float scale) {
if (blocksElement) {
tinyxml2::XMLElement* blockElement = blocksElement->FirstChildElement("block");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (blockElement) {
// id
int id;
blockElement->QueryIntAttribute("id", &id);
// create block
auto block = Block::create(id);
this->blocks.insert(block);
this->objects.insert(block);
// set block scale
block->setScale(scale);
// set block position
float x, y;
tinyxml2::XMLElement* positionElement = blockElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
block->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
// add the block to the scene
this->addChild(block, OBJECT_LAYER);
blockElement = blockElement->NextSiblingElement("block");
}
}
}
/**
*
*/
void HelloWorld::addBonusStars(tinyxml2::XMLElement* const bonusStarsElement, float scale) {
if (bonusStarsElement) {
tinyxml2::XMLElement* bonusStarElement = bonusStarsElement->FirstChildElement("bonusstar");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (bonusStarElement) {
// id
int id;
bonusStarElement->QueryIntAttribute("id", &id);
// create block
auto bonusStar = BonusStar::create(id);
this->bonusStars.insert(bonusStar);
this->objects.insert(bonusStar);
// set block scale
bonusStar->setScale(scale);
// set block position
float x, y;
tinyxml2::XMLElement* positionElement = bonusStarElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
bonusStar->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
// add the block to the scene
this->addChild(bonusStar, OBJECT_LAYER);
bonusStarElement = bonusStarElement->NextSiblingElement("bonusstar");
}
}
}
/**
*
*/
void HelloWorld::createLevel(const std::string& filename) {
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
const float scale = std::min(visibleSize.width/1536.0f, visibleSize.height/2048.0f);
tinyxml2::XMLDocument document;
tinyxml2::XMLError error = document.LoadFile(filename.c_str());
//log("com.zenprogramming.reflection: error = %d", error);
//////////////////////////////////////////////////////////////////////////////
//
// Add the initial objects
//
//////////////////////////////////////////////////////////////////////////////
this->addEmitters(document.RootElement()->FirstChildElement("setup")->FirstChildElement("emitters"), scale);
this->addMirrors(document.RootElement()->FirstChildElement("setup")->FirstChildElement("mirrors"), scale);
this->addReceptors(document.RootElement()->FirstChildElement("setup")->FirstChildElement("receptors"), scale);
this->addBlocks(document.RootElement()->FirstChildElement("setup")->FirstChildElement("blocks"), scale);
this->addBonusStars(document.RootElement()->FirstChildElement("setup")->FirstChildElement("bonusstars"), scale);
//////////////////////////////////////////////////////////////////////////////
//
// Create the intro layers
//
//////////////////////////////////////////////////////////////////////////////
// get the <intro> element
tinyxml2::XMLElement* introElement = document.RootElement()->FirstChildElement("intro");
if (introElement) {
tinyxml2::XMLElement* layerElement = introElement->FirstChildElement("layer");
const Size visibleSize = Director::getInstance()->getVisibleSize();
const Vec2 origin = Director::getInstance()->getVisibleOrigin();
while (layerElement) {
// auto layer = LayerGradient::create(Color4B(255, 255, 255, 64), Color4B(255, 255, 255, 64));
Layer* layer = Layer::create();
const std::string text = layerElement->FirstChildElement("text")->GetText();
//log("com.zenprogramming.reflection: %s", text.c_str());
auto label = Label::createWithTTF(text, "fonts/centurygothic_bold.ttf", 160);
if (label == nullptr) {
problemLoading("'fonts/centurygothic_bold.ttf'");
} else {
// position the label on the top center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2.0f, origin.y + visibleSize.height*3.0f/4.0f));
label->setScale(scale);
label->setColor(Color3B(0, 0, 0));
Sprite* background = Sprite::create("intro_layer.png");
background->setPosition(label->getPosition());
background->setScaleX(scale);
layer->addChild(background, INTRO_LAYER);
// add the label as a child to this layer
layer->addChild(label, INTRO_LAYER);
layer->setCascadeOpacityEnabled(true);
Label* continueLabel = Label::createWithTTF("Touch to continue", "fonts/centurygothic_bold.ttf", 60);
continueLabel->setPosition(Vec2(background->getPositionX(), background->getPositionY() - background->getContentSize().height/2.0f + continueLabel->getContentSize().height));
continueLabel->setScale(scale);
continueLabel->setColor(Color3B(0, 0, 0));
layer->addChild(continueLabel, INTRO_LAYER);
}
tinyxml2::XMLElement* indicatorElement = layerElement->FirstChildElement("indicator");
if (indicatorElement) {
// set indicator position
float x, y;
tinyxml2::XMLElement* positionElement = indicatorElement->FirstChildElement("position");
positionElement->QueryFloatAttribute("x", &x);
positionElement->QueryFloatAttribute("y", &y);
Indicator* indicator = Indicator::create();
indicator->setPosition(Vec2(origin.x + visibleSize.width * x, origin.y + visibleSize.height * y));
indicator->setColor(Color3B(0, 0, 255));
// indicator->setOnEnterCallback([&]() {
// indicator->runAction(ScaleTo::create(2.0f, 0.0f));
// });
layer->addChild(indicator);
indicator->runAction(RepeatForever::create(
Sequence::create(
ScaleTo::create(2.0f, 0.0f),
ScaleTo::create(2.0f, 1.0f),
nullptr
)
));
}
this->introLayers->addLayer(layer);
layerElement = layerElement->NextSiblingElement("layer");
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Add the win conditions
//
//////////////////////////////////////////////////////////////////////////////
// get the <winconditions> element
tinyxml2::XMLElement* winConditionsElement = document.RootElement()->FirstChildElement("winconditions");
if (winConditionsElement) {
// get the <wincondition> element
tinyxml2::XMLElement* winConditionElement = winConditionsElement->FirstChildElement("wincondition");
if (winConditionElement) {
std::shared_ptr<WinCondition> winCondition(new WinCondition());
{ // parse the win condition - emitters
tinyxml2::XMLElement* winConditionEmittersElement = winConditionElement->FirstChildElement("emitters");
if (winConditionEmittersElement) {
tinyxml2::XMLElement* winConditionEmitterElement = winConditionEmittersElement->FirstChildElement("emitter");
while (winConditionEmitterElement) {
// get emitter id
int emitterId;
winConditionEmitterElement->QueryIntAttribute("id", &emitterId);
// get emitter activity
const std::string emitterActiveStr(winConditionEmitterElement->Attribute("active"));
const bool emitterActive = !emitterActiveStr.compare("true");
for (auto emitter : this->emitters) {
if (emitter->getId() == emitterId) {
winCondition->addEmitterActivation(emitter, emitterActive);
}
}
winConditionEmitterElement = winConditionEmitterElement->NextSiblingElement("emitter");
}
}
}
{ // parse the win condition - mirrors
tinyxml2::XMLElement* winConditionMirrorsElement = winConditionElement->FirstChildElement("mirrors");
if (winConditionMirrorsElement) {
tinyxml2::XMLElement* winConditionMirrorElement = winConditionMirrorsElement->FirstChildElement("mirror");
while (winConditionMirrorElement) {
// get mirror id
int mirrorId;
winConditionMirrorElement->QueryIntAttribute("id", &mirrorId);
// get mirror direction
const std::string mirrorDirectionStr(winConditionMirrorElement->Attribute("direction"));
const Direction mirrorDirection = strToDirectionMap[mirrorDirectionStr];
for (auto mirror : this->mirrors) {
if (mirror->getId() == mirrorId) {
winCondition->addMirrorDirection(mirror, mirrorDirection);
}
}
winConditionMirrorElement = winConditionMirrorElement->NextSiblingElement("mirror");
}
}
}
this->winConditions.push_back(winCondition);
}
}
}
/**
* https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector
*/
Vec3 HelloWorld::getReflectionVector(const Plane& plane, const Ray& ray) {
//log("com.zenprogramming.reflection: BEGIN getReflectionVector");
const Vec3 d = ray._direction;
const Vec3 n = plane.getNormal();
const Vec3 reflectionVector = d - 2 * (d.dot(n)) * n;
//log("com.zenprogramming.reflection: reflectionVector = (%f, %f, %f)", reflectionVector.x, reflectionVector.y, reflectionVector.z);
//log("com.zenprogramming.reflection: END getReflectionVector");
return reflectionVector;
}
/**
*
*/
void HelloWorld::activateLaserChain(const Ray& originRay, const Vec3& origLaserStartingPoint, const Plane& originPlane, ColorType colorType) {
//log("com.zenprogramming.reflection: BEGIN activateLaserChain");
const Vec3 reflectionVector = this->getReflectionVector(originPlane, originRay);
const float angle = -std::atan2(reflectionVector.y, reflectionVector.x) * RADTODEG;
const Ray reflectionRay(origLaserStartingPoint, reflectionVector);
// create and add a laser
Laser* const laser = this->addLaser(angle, Vec2(origLaserStartingPoint.x, origLaserStartingPoint.y), colorTypeToLaserColor3BMap[colorType]);
std::shared_ptr<Intersection> intersection = this->getClosestIntersection(reflectionRay);
if (intersection.get()) {
laser->setScaleX(intersection->getDistance());
if (intersection->isPlaneReflective()) {
this->activateLaserChain(laser->getRay(), intersection->getPoint(), intersection->getPlane(), colorType);
}
}
//log("com.zenprogramming.reflection: END activateLaserChain");
}
/**
*
*/
std::shared_ptr<Intersection> HelloWorld::getClosestIntersection(const Ray& ray) {
//log("com.zenprogramming.reflection: BEGIN getClosestIntersection");
std::shared_ptr<Intersection> intersection;
float minDistance = 2560.0f;
//log("com.zenprogramming.reflection: ray = origin (%f, %f, %f), direction (%f, %f, %f)", ray._origin.x, ray._origin.y, ray._origin.z, ray._direction.x, ray._direction.y, ray._direction.z);
// check each object
for (auto object : this->objects) {
//log("com.zenprogramming.reflection: checking object[%d]...", object->getId());
// get the AABB for the object
const Rect objectBoundingBox = object->getBoundingBox();
const AABB objectAABB(Vec3(objectBoundingBox.getMinX(), objectBoundingBox.getMinY(), 0.0f), Vec3(objectBoundingBox.getMaxX(), objectBoundingBox.getMaxY(), 0.0f));
//log("com.zenprogramming.reflection: object[%d] AABB = (%f, %f, %f, %f), width = %f, height = %f", object->getId(), objectBoundingBox.getMinX(), objectBoundingBox.getMinY(), objectBoundingBox.getMaxX(), objectBoundingBox.getMaxY(), objectBoundingBox.getMaxX() - objectBoundingBox.getMinX(), objectBoundingBox.getMaxY() - objectBoundingBox.getMinY());
for (int planeIndex=0; planeIndex<object->getNumPlanes(); ++planeIndex) {
const Plane plane = object->getPlane(planeIndex);
const Vec3 intersectionPoint = ray.intersects(plane);
const float intersectionDist = intersectionPoint.distance(ray._origin);
const bool intersects = ray.intersects(objectAABB);
//log("com.zenprogramming.reflection: intersects? %d, dist = %f", intersects, intersectionDist);
if (!intersectionPoint.isZero() && ray.intersects(objectAABB) && objectBoundingBox.containsPoint(Vec2(intersectionPoint.x, intersectionPoint.y))) {
// ray intersects plane in the object's bounding box
if (intersectionDist < minDistance) {
minDistance = intersectionDist;
intersection.reset(new Intersection(plane, intersectionPoint, plane.getSide(ray._origin), object->isPlaneReflective(planeIndex), intersectionDist));
//log("com.zenprogramming.reflection: laser hits object[%d] at distance = %f at point (%f, %f, %f)", object->getId(), intersectionDist, intersectionPoint.x, intersectionPoint.y, intersectionPoint.z);
//log("com.zenprogramming.reflection: closest object is now %d", object->getId());
}
}
}
}
//log("com.zenprogramming.reflection: END getClosestIntersection");
return intersection;
}
/**
*
*/
bool HelloWorld::checkWinConditions() {
//log("com.zenprogramming.reflection: BEGIN checkWinConditions");
if (this->ready) {
////////////////////////////////////////////////////////////////////////////
//
// Check all objects for their win condition
//
////////////////////////////////////////////////////////////////////////////
std::shared_ptr<WinCondition> currentWinCondition = nullptr;
for (auto winCondition : this->winConditions) {
if (!winCondition->evaluate()) {
return false;
}
currentWinCondition = winCondition;
}
// // remove all bonus stars
// for (auto bonusStar : currentWinCondition->getBonusStars()) {
// bonusStar->removeFromParent();
// }
// player has won, so set the ready to false
this->ready = false;
////////////////////////////////////////////////////////////////////////////
//
// Copy the scene to a RenderTexture
//
////////////////////////////////////////////////////////////////////////////
// create and copy the scene to a RenderTexture
RenderTexture* renderTexture = RenderTexture::create(this->getBoundingBox().size.width, this->getBoundingBox().size.height, PixelFormat::RGBA8888);
renderTexture->begin();
this->visit();
renderTexture->end();
renderTexture->setPositionNormalized(Vec2(0.5f, 0.5f));
this->addChild(renderTexture, 250);
////////////////////////////////////////////////////////////////////////////
//
// Play the win animation
//
////////////////////////////////////////////////////////////////////////////
Sprite* const winBanner = Sprite::create("well_done.png");
winBanner->setPositionNormalized(Vec2(0.5f, 0.5f));
winBanner->setOpacity(0);
winBanner->setScale(5.0f);
this->addChild(winBanner, 255);
winBanner->runAction(Sequence::create(
CallFunc::create([&]() {
auto emitter = ParticleExplosion::create();
emitter->setPositionNormalized(Vec2(0.5f, 0.5f));
// set the duration
// emitter->setDuration(ParticleSystem::DURATION_INFINITY);
// // radius mode
// emitter->setEmitterMode(ParticleSystem::Mode::RADIUS);
// radius mode: 100 pixels from center
emitter->setStartRadius(0);
emitter->setStartRadiusVar(0);
emitter->setEndRadius(ParticleSystem::START_RADIUS_EQUAL_TO_END_RADIUS);
emitter->setEndRadiusVar(500); // not used when start == end
this->addChild(emitter, 254);
}),
DelayTime::create(1.0f), // pause
Spawn::create(
FadeIn::create(0.5f),
ScaleTo::create(0.5f, 1.75f),
nullptr
),
nullptr
));
// remove all objects from the scene
//for (auto object : this->objects) {
// object->removeFromParent();
//}
//this->objects.clear();
// TODO: do sand blowing away animation
//////////////////////////////////////////////////////////////////////////////
//
// Update the database to unlock the next level
//
//////////////////////////////////////////////////////////////////////////////
sqlite3* db;
char* errMsg = 0;
int rc;
// open the database
std::stringstream dbPath;
dbPath << FileUtils::getInstance()->getWritablePath() << "levels.db";
rc = sqlite3_open(dbPath.str().c_str(), &db);
if (rc) {
log("com.zenprogramming.reflection: Can't open database: %s", sqlite3_errmsg(db));
sqlite3_close(db);
return false;
}
std::stringstream sql;
sql << "UPDATE game_levels SET locked = 0 WHERE id = (SELECT next_level_id FROM game_levels WHERE id = " << this->levelId << ")";
rc = sqlite3_exec(db, sql.str().c_str(), levelUnlockCallback, static_cast<void*>(this), &errMsg);
if (rc != SQLITE_OK) {
log("com.zenprogramming.reflection: SQL error: %s", errMsg);
sqlite3_free(errMsg);
}
// close the database
rc = sqlite3_close(db);
}
//log("com.zenprogramming.reflection: END checkWinConditions");
return true;
}
/**
*
*/
Laser* HelloWorld::addLaser(float angle, const Vec2& position, const Color3B& color) {
// create and add a laser
Laser* const laser = Laser::create(color);
laser->setPosition(position);
laser->setRotation(angle);
laser->setAnchorPoint(Vec2(0.0f, 0.5f));
laser->setScaleX(2560.0f);
this->addChild(laser, LASER_LAYER);
this->lasers.insert(laser);
return laser;
}
/**
*
*/
void HelloWorld::update(float dt) {
//log("com.zenprogramming.reflection: BEGIN update");
if (ready) {
// remove all lasers from the board
for (auto laser : this->lasers) {
laser->removeFromParent();
}
this->lasers.clear();
// regenerate lasers on the board
for (auto emitter : this->emitters) {
if (emitter->isActive()) {
const Vec2 emitterWorldPos = emitter->getParent()->convertToWorldSpace(emitter->getPosition());
// create and add a laser
Laser* const laser = this->addLaser(emitter->getRotation(), emitterWorldPos, colorTypeToLaserColor3BMap[emitter->getColorType()]);
// find the closest intersection for the emitter laser
std::shared_ptr<Intersection> intersection = this->getClosestIntersection(laser->getRay());
if (intersection.get()) {
laser->setScaleX(intersection->getDistance());
//log("com.zenprogramming.reflection: laser origin (%f, %f), direction (%f, %f, %f), length = %f", laser->getRay()._origin.x, laser->getRay()._origin.y, laser->getRay()._direction.x, laser->getRay()._direction.y, laser->getRay()._direction.z, laser->getScaleX());
//log("com.zenprogramming.reflection: intersection at (%f, %f, %f) side = %d, reflective = %d, distance = %f", intersection->getPoint().x, intersection->getPoint().y, intersection->getPoint().z, intersection->getPointSide(), intersection->isPlaneReflective(), intersection->getDistance());
if (intersection->isPlaneReflective()) {
this->activateLaserChain(laser->getRay(), intersection->getPoint(), intersection->getPlane(), emitter->getColorType());
}
}
}
}
this->checkWinConditions();
}
//log("com.zenprogramming.reflection: END update");
}
| 35.867179 | 353 | 0.673298 | otakuidoru |
d28479bb788c0602587c937612e7b37a57769cbc | 23,099 | cc | C++ | art-extension/compiler/optimizing/extensions/infrastructure/ext_utility.cc | pramulkant/https-github.com-android-art-intel-marshmallow | 87e8c22f248164780b92aaa0cdea14bf6cda3859 | [
"Apache-2.0"
] | 8 | 2016-08-11T09:46:36.000Z | 2018-03-02T17:28:35.000Z | art-extension/compiler/optimizing/extensions/infrastructure/ext_utility.cc | android-art-intel/marshmallow | 87e8c22f248164780b92aaa0cdea14bf6cda3859 | [
"Apache-2.0"
] | null | null | null | art-extension/compiler/optimizing/extensions/infrastructure/ext_utility.cc | android-art-intel/marshmallow | 87e8c22f248164780b92aaa0cdea14bf6cda3859 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015 Intel Corporation
*
* 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 "ext_utility.h"
#include "nodes.h"
#include "optimization.h"
#include <sstream>
namespace art {
std::ostream& operator<<(std::ostream& os, const ConstantValue& cv) {
switch (cv.type) {
case Primitive::kPrimInt:
os << cv.value.i;
break;
case Primitive::kPrimLong:
os << cv.value.l;
break;
case Primitive::kPrimFloat:
os << cv.value.f;
break;
case Primitive::kPrimDouble:
os << cv.value.d;
break;
default:
os << "Unknown constant type " << cv.type;
}
return os;
}
std::ostream& operator<<(std::ostream& os, HInstruction* instruction) {
os << GetTypeId(instruction->GetType()) << instruction->GetId() << " ";
os << instruction->DebugName();
switch (instruction->GetKind()) {
case HInstruction::kIntConstant:
os << ' ' << instruction->AsIntConstant()->GetValue();
break;
case HInstruction::kLongConstant:
os << ' ' << instruction->AsLongConstant()->GetValue();
break;
case HInstruction::kFloatConstant:
os << ' ' << instruction->AsFloatConstant()->GetValue();
break;
case HInstruction::kDoubleConstant:
os << ' ' << instruction->AsDoubleConstant()->GetValue();
break;
default:
break;
}
if (instruction->InputCount() > 0) {
os << " [ ";
for (HInputIterator inputs(instruction); !inputs.Done(); inputs.Advance()) {
os << GetTypeId(inputs.Current()->GetType()) << inputs.Current()->GetId() << ' ';
}
os << ']';
}
return os;
}
IfCondition NegateCondition(IfCondition cond) {
switch (cond) {
case kCondNE:
return kCondEQ;
case kCondEQ:
return kCondNE;
case kCondLT:
return kCondGE;
case kCondGE:
return kCondLT;
case kCondGT:
return kCondLE;
case kCondLE:
return kCondGT;
default:
LOG(FATAL) << "Unknown if condition";
}
// Unreachable code.
return kCondEQ;
}
IfCondition FlipConditionForOperandSwap(IfCondition cond) {
switch (cond) {
case kCondEQ:
case kCondNE:
// Do nothing, a == b <==> b == a.
// Same for a != b.
return cond;
case kCondLT:
return kCondGT;
case kCondLE:
return kCondGE;
case kCondGT:
return kCondLT;
case kCondGE:
return kCondLE;
default:
LOG(FATAL) << "Unknown if condition";
}
// Unreachable code.
return kCondEQ;
}
bool GetFPConstantValue(HConstant* constant, double& value) {
if (constant->IsFloatConstant()) {
HFloatConstant* fp_cst = constant->AsFloatConstant();
value = fp_cst->GetValue();
return true;
} else if (constant->IsDoubleConstant()) {
HDoubleConstant* double_cst = constant->AsDoubleConstant();
value = double_cst->GetValue();
return true;
}
// If not int or long, bail.
return false;
}
bool GetIntConstantValue(HConstant* constant, int64_t& value) {
if (constant->IsIntConstant()) {
HIntConstant* int_cst = constant->AsIntConstant();
value = int_cst->GetValue();
return true;
} else if (constant->IsLongConstant()) {
HLongConstant* long_cst = constant->AsLongConstant();
value = long_cst->GetValue();
return true;
}
// If not int or long, bail.
return false;
}
HInstruction* GetCompareInstruction(HInstruction* instruction) {
// Look at the first instruction, is it a compare?
HInstruction* first = instruction->InputAt(0);
if (first->IsCompare()) {
return first;
}
// Not the first one, what about the second one?
HInstruction* second = instruction->InputAt(1);
if (second->IsCompare()) {
return second;
}
// None of the two, so return the original one.
return instruction;
}
static Primitive::Type GetResultType(HUnaryOperation* insn) {
Primitive::Type type = insn->GetResultType();
return type == Primitive::kPrimBoolean ? Primitive::kPrimInt : type;
}
static Primitive::Type GetResultType(HBinaryOperation* insn) {
Primitive::Type type = insn->GetResultType();
return type == Primitive::kPrimBoolean ? Primitive::kPrimInt : type;
}
static Primitive::Type GetResultType(HTypeConversion* insn) {
Primitive::Type type = insn->GetResultType();
return type == Primitive::kPrimBoolean ? Primitive::kPrimInt : type;
}
bool EvaluateCast(HTypeConversion* conv, const ConstantValue& x, ConstantValue& res) {
constexpr int32_t int32_min_value = std::numeric_limits<int32_t>::min();
constexpr int32_t int32_max_value = std::numeric_limits<int32_t>::max();
constexpr int64_t int64_min_value = std::numeric_limits<int64_t>::min();
constexpr int64_t int64_max_value = std::numeric_limits<int64_t>::max();
Primitive::Type cast_to = GetResultType(conv);
bool success = true;
DCHECK(cast_to != Primitive::kPrimBoolean);
DCHECK(x.type != Primitive::kPrimBoolean);
if (x.type == Primitive::kPrimInt) {
int32_t value = x.value.i;
switch (cast_to) {
case Primitive::kPrimLong:
res.value.l = static_cast<int64_t>(value);
break;
case Primitive::kPrimFloat:
res.value.f = static_cast<float>(value);
break;
case Primitive::kPrimDouble:
res.value.d = static_cast<double>(value);
break;
case Primitive::kPrimByte:
res.value.i = static_cast<int32_t>(static_cast<int8_t>(value));
cast_to = Primitive::kPrimInt;
break;
case Primitive::kPrimShort:
res.value.i = static_cast<int32_t>(static_cast<int16_t>(value));
cast_to = Primitive::kPrimInt;
break;
default:
success = false;
}
} else if (x.type == Primitive::kPrimLong) {
int64_t value = x.value.l;
switch (cast_to) {
case Primitive::kPrimInt:
res.value.i = static_cast<int32_t>(value);
break;
case Primitive::kPrimFloat:
res.value.f = static_cast<float>(value);
break;
case Primitive::kPrimDouble:
res.value.d = static_cast<double>(value);
break;
default:
success = false;
}
} else if (x.type == Primitive::kPrimFloat) {
float value = x.value.f;
switch (cast_to) {
case Primitive::kPrimInt:
if (std::isnan(value)) {
res.value.i = 0;
} else if (value >= int32_max_value) {
res.value.i = int32_max_value;
} else if (value <= int32_min_value) {
res.value.i = int32_min_value;
} else {
res.value.i = static_cast<int32_t>(value);
}
break;
case Primitive::kPrimLong:
if (std::isnan(value)) {
res.value.l = 0L;
} else if (value >= int64_max_value) {
res.value.l = int64_max_value;
} else if (value <= int64_min_value) {
res.value.l = int64_min_value;
} else {
res.value.l = static_cast<int64_t>(value);
}
break;
case Primitive::kPrimDouble:
res.value.d = static_cast<double>(value);
break;
default:
success = false;
};
} else if (x.type == Primitive::kPrimDouble) {
double value = x.value.d;
switch (cast_to) {
case Primitive::kPrimInt:
if (std::isnan(value)) {
res.value.i = 0;
} else if (value >= int32_max_value) {
res.value.i = int32_max_value;
} else if (value <= int32_min_value) {
res.value.i = int32_min_value;
} else {
res.value.i = static_cast<int32_t>(value);
}
break;
case Primitive::kPrimLong:
if (std::isnan(value)) {
res.value.l = 0;
} else if (value >= int64_max_value) {
res.value.l = int64_max_value;
} else if (value <= int64_min_value) {
res.value.l = int64_min_value;
} else {
res.value.l = static_cast<int64_t>(value);
}
break;
case Primitive::kPrimFloat:
res.value.f = static_cast<float>(value);
break;
default:
success = false;
}
} else {
success = false;
}
// Finally, update the type of the instruction.
res.type = cast_to;
return success;
}
bool Evaluate(HInstruction* insn, const ConstantValue& x, ConstantValue& res) {
DCHECK(insn != nullptr);
bool success = true;
DCHECK(x.type != Primitive::kPrimBoolean);
if (insn->IsUnaryOperation()) {
HUnaryOperation* uop = insn->AsUnaryOperation();
res.type = GetResultType(uop);
DCHECK(res.type != Primitive::kPrimBoolean);
switch (res.type) {
case Primitive::kPrimBoolean:
FALLTHROUGH_INTENDED;
case Primitive::kPrimInt: {
int32_t int_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
int_res = uop->Evaluate(x.value.i);
break;
case Primitive::kPrimFloat:
int_res = static_cast<int32_t>(uop->Evaluate(x.value.f));
break;
case Primitive::kPrimLong:
int_res = static_cast<int32_t>(uop->Evaluate(x.value.l));
break;
case Primitive::kPrimDouble:
int_res = static_cast<int32_t>(uop->Evaluate(x.value.d));
break;
default:
success = false;
};
res.value.i = int_res;
break;
}
case Primitive::kPrimFloat: {
float float_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
float_res = static_cast<float>(uop->Evaluate(x.value.i));
break;
case Primitive::kPrimFloat:
float_res = uop->Evaluate(x.value.f);
break;
case Primitive::kPrimLong:
float_res = static_cast<float>(uop->Evaluate(x.value.l));
break;
case Primitive::kPrimDouble:
float_res = static_cast<float>(uop->Evaluate(x.value.d));
break;
default:
success = false;
};
res.value.f = float_res;
break;
}
case Primitive::kPrimLong: {
int64_t long_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
long_res = static_cast<int64_t>(uop->Evaluate(x.value.i));
break;
case Primitive::kPrimFloat:
long_res = static_cast<int64_t>(uop->Evaluate(x.value.f));
break;
case Primitive::kPrimLong:
long_res = uop->Evaluate(x.value.l);
break;
case Primitive::kPrimDouble:
long_res = static_cast<int64_t>(uop->Evaluate(x.value.d));
break;
default:
success = false;
};
res.value.l = long_res;
break;
}
case Primitive::kPrimDouble: {
double double_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
double_res = static_cast<double>(uop->Evaluate(x.value.i));
break;
case Primitive::kPrimFloat:
double_res = static_cast<double>(uop->Evaluate(x.value.f));
break;
case Primitive::kPrimLong:
double_res = static_cast<double>(uop->Evaluate(x.value.l));
break;
case Primitive::kPrimDouble:
double_res = uop->Evaluate(x.value.d);
break;
default:
success = false;
};
res.value.d = double_res;
break;
}
default:
success = false;
};
} else if (insn->IsTypeConversion()) {
HTypeConversion* cast = insn->AsTypeConversion();
success = EvaluateCast(cast, x, res);
}
return success;
}
bool Evaluate(HBinaryOperation* insn, const ConstantValue& x, const ConstantValue& y, ConstantValue& res) {
DCHECK(insn != nullptr);
bool success = true;
res.type = GetResultType(insn);
DCHECK(res.type != Primitive::kPrimBoolean);
DCHECK(x.type != Primitive::kPrimBoolean);
DCHECK(y.type != Primitive::kPrimBoolean);
switch (res.type) {
case Primitive::kPrimInt: {
int32_t int_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
DCHECK(y.type == Primitive::kPrimInt);
int_res = insn->Evaluate(x.value.i, y.value.i);
break;
case Primitive::kPrimFloat:
DCHECK(y.type == Primitive::kPrimFloat);
int_res = static_cast<int32_t>(insn->Evaluate(x.value.f, y.value.f));
break;
case Primitive::kPrimLong:
DCHECK(y.type == Primitive::kPrimLong);
int_res = static_cast<int32_t>(insn->Evaluate(x.value.l, y.value.l));
break;
case Primitive::kPrimDouble:
DCHECK(y.type == Primitive::kPrimDouble);
int_res = static_cast<int32_t>(insn->Evaluate(x.value.d, y.value.d));
break;
default:
success = false;
};
res.value.i = int_res;
break;
}
case Primitive::kPrimFloat: {
float float_res = 0.0f;
switch (x.type) {
case Primitive::kPrimInt:
DCHECK(y.type == Primitive::kPrimInt);
float_res = static_cast<float>(insn->Evaluate(x.value.i, y.value.i));
break;
case Primitive::kPrimFloat:
DCHECK(y.type == Primitive::kPrimFloat);
float_res = insn->Evaluate(x.value.f, y.value.f);
break;
case Primitive::kPrimLong:
DCHECK(y.type == Primitive::kPrimLong);
float_res = static_cast<float>(insn->Evaluate(x.value.l, y.value.l));
break;
case Primitive::kPrimDouble:
DCHECK(y.type == Primitive::kPrimDouble);
float_res = static_cast<float>(insn->Evaluate(x.value.d, y.value.d));
break;
default:
success = false;
};
res.value.f = float_res;
break;
}
case Primitive::kPrimLong: {
int64_t long_res = 0;
switch (x.type) {
case Primitive::kPrimInt:
DCHECK(y.type == Primitive::kPrimInt);
long_res = static_cast<int64_t>(insn->Evaluate(x.value.i, y.value.i));
break;
case Primitive::kPrimFloat:
DCHECK(y.type == Primitive::kPrimFloat);
long_res = static_cast<int64_t>(insn->Evaluate(x.value.f, y.value.f));
break;
case Primitive::kPrimLong:
if (y.type == Primitive::kPrimLong) {
long_res = insn->Evaluate(x.value.l, y.value.l);
} else {
long_res = insn->Evaluate(x.value.l, static_cast<int64_t>(y.value.i));
}
break;
case Primitive::kPrimDouble:
DCHECK(y.type == Primitive::kPrimDouble);
long_res = static_cast<float>(insn->Evaluate(x.value.d, y.value.d));
break;
default:
success = false;
};
res.value.l = long_res;
break;
}
case Primitive::kPrimDouble: {
double double_res = 0.0;
switch (x.type) {
case Primitive::kPrimInt:
DCHECK(y.type == Primitive::kPrimInt);
double_res = static_cast<double>(insn->Evaluate(x.value.i, y.value.i));
break;
case Primitive::kPrimFloat:
DCHECK(y.type == Primitive::kPrimFloat);
double_res = static_cast<double>(insn->Evaluate(x.value.f, y.value.f));
break;
case Primitive::kPrimLong:
DCHECK(y.type == Primitive::kPrimLong);
double_res = static_cast<double>(insn->Evaluate(x.value.l, y.value.l));
break;
case Primitive::kPrimDouble:
DCHECK(y.type == Primitive::kPrimDouble);
double_res = insn->Evaluate(x.value.d, y.value.d);
break;
default:
success = false;
};
res.value.d = double_res;
break;
}
default:
success = false;
};
return success;
}
std::string GetInvokeMethodName(HInstruction* insn, DexCompilationUnit* outer_compilation_unit) {
if (insn == nullptr) {
return nullptr;
}
HInvokeStaticOrDirect* call = insn->AsInvokeStaticOrDirect();
if (call == nullptr) {
return nullptr;
}
return PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit->GetDexFile());
}
std::string GetMethodName(const DexCompilationUnit& c_unit) {
return PrettyMethod(c_unit.GetDexMethodIndex(), *c_unit.GetDexFile());
}
std::string GetMethodName(const HGraph* graph) {
DCHECK(graph != nullptr);
return PrettyMethod(graph->GetMethodIdx(), graph->GetDexFile());
}
char GetTypeId(Primitive::Type type) {
// Note that Primitive::Descriptor would not work for us
// because it does not handle reference types (that is kPrimNot).
switch (type) {
case Primitive::kPrimBoolean: return 'z';
case Primitive::kPrimByte: return 'b';
case Primitive::kPrimChar: return 'c';
case Primitive::kPrimShort: return 's';
case Primitive::kPrimInt: return 'i';
case Primitive::kPrimLong: return 'j';
case Primitive::kPrimFloat: return 'f';
case Primitive::kPrimDouble: return 'd';
case Primitive::kPrimNot: return 'l';
case Primitive::kPrimVoid: return 'v';
}
LOG(FATAL) << "Unreachable";
return 'v';
}
void RemoveEnvAsUser(HInstruction* instruction) {
for (HEnvironment* environment = instruction->GetEnvironment();
environment != nullptr;
environment = environment->GetParent()) {
for (size_t i = 0, e = environment->Size(); i < e; ++i) {
if (environment->GetInstructionAt(i) != nullptr) {
environment->RemoveAsUserOfInput(i);
}
}
}
}
void RemoveAsUser(HInstruction* instruction) {
for (size_t i = 0; i < instruction->InputCount(); i++) {
instruction->RemoveAsUserOfInput(i);
}
RemoveEnvAsUser(instruction);
}
void RemoveFromEnvironmentUsers(HInstruction* insn) {
for (HUseIterator<HEnvironment*> use_it(insn->GetEnvUses()); !use_it.Done();
use_it.Advance()) {
HUseListNode<HEnvironment*>* user_node = use_it.Current();
HEnvironment* user = user_node->GetUser();
user->SetRawEnvAt(user_node->GetIndex(), nullptr);
}
}
ConstantValue::ConstantValue(HConstant* constant) {
DCHECK(constant != nullptr);
if (constant->IsIntConstant()) {
type = Primitive::kPrimInt;
value.i = constant->AsIntConstant()->GetValue();
} else if (constant->IsFloatConstant()) {
type = Primitive::kPrimFloat;
value.f = constant->AsFloatConstant()->GetValue();
} else if (constant->IsLongConstant()) {
type = Primitive::kPrimLong;
value.l = constant->AsLongConstant()->GetValue();
} else if (constant->IsDoubleConstant()) {
type = Primitive::kPrimDouble;
value.d = constant->AsDoubleConstant()->GetValue();
} else {
LOG(FATAL) << "Could not handle constant value";
}
}
HConstant* ConstantValue::ToHConstant(HGraph* graph) const {
DCHECK(graph != nullptr);
switch (type) {
case Primitive::kPrimInt:
return graph->GetIntConstant(value.i);
case Primitive::kPrimLong:
return graph->GetLongConstant(value.l);
case Primitive::kPrimFloat:
return graph->GetFloatConstant(value.f);
case Primitive::kPrimDouble:
return graph->GetDoubleConstant(value.d);
default:
LOG(FATAL) << "Unknown constant type: " << type;
};
return nullptr;
}
void DeconstructFP(double value, bool is_double, bool with_implicit_one, int32_t& sign, int32_t& power, int64_t& mantissa) {
int32_t exponent_length;
int32_t mantissa_length;
int64_t as_int;
const int64_t one = 1;
if (is_double) {
union {
double d;
int64_t l;
} conversion;
conversion.d = value;
as_int = conversion.l;
exponent_length = 11;
mantissa_length = 52;
} else {
union {
float f;
int32_t i;
} conversion;
conversion.f = static_cast<float>(value);
// Extend to 64 bit.
as_int = conversion.i | (int64_t)0;
exponent_length = 8;
mantissa_length = 23;
}
// Get the actual output values.
// Sign is the leftmost (31th or 63th) bit.
sign = static_cast<int32_t>((as_int >> (is_double ? 63 : 31)) & 1);
// Mantissa bits are the last ones.
mantissa = as_int & ((one << mantissa_length) - one);
// Exponent bits are between them.
int32_t exponent = static_cast<int32_t>
((as_int >> mantissa_length) &
((one << exponent_length) - one));
// For non-zero values, power is exponent - 01111...11.
if (value == 0.0) {
power = 0;
} else {
power = exponent - ((1 << (exponent_length - 1)) - 1);
}
// For non-zero value, add an implicit 1 to mantissa.
if (with_implicit_one && (value != 0.0)) {
mantissa |= ((int64_t)1 << mantissa_length);
}
}
int32_t CountEndZerosInMantissa(int64_t mantissa, bool is_double) {
const int32_t limit = (is_double ? 52 : 23);
int32_t ret = 0;
while ((ret < limit) && ((mantissa & 1) == 0)) {
ret++;
mantissa >>= 1;
}
return ret;
}
void SplitStringIntoSet(const std::string& s, char delim, std::unordered_set<std::string>& tokens) {
std::stringstream stream(s);
std::string item;
while (std::getline(stream, item, delim)) {
if (item.size() > 1) {
tokens.insert(item);
}
}
}
std::string CalledMethodName(HInvokeStaticOrDirect* call) {
DCHECK(call != nullptr);
const MethodReference target_method = call->GetTargetMethod();
return PrettyMethod(target_method.dex_method_index,
*target_method.dex_file);
}
} // namespace art
| 32.216179 | 126 | 0.577384 | pramulkant |
d286697e41b470e6fcf9c7f7ff2491a79bf5183d | 889 | cc | C++ | aoj/volumn5/0521/0521aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2015-10-06T16:27:42.000Z | 2015-10-06T16:27:42.000Z | aoj/volumn5/0521/0521aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2016-03-02T16:18:11.000Z | 2016-03-02T16:18:11.000Z | aoj/volumn5/0521/0521aoj.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | null | null | null | /*c++11*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <cmath>
#include <deque>
using namespace std;
int main(int args, char *argc[]){
char a,b,c;
char t;
int joi=0;
int ioi=0;
deque<char> que;
while(scanf("%c",&a)!=EOF){
scanf("%c%c",&b,&c);
que.clear();
joi=0;
ioi=0;
if(a=='J' && b=='O' && c=='I')
joi++;
else if(a=='I' && b=='O' && c=='I')
ioi++;
que.push_back(a);
que.push_back(b);
que.push_back(c);
while(scanf("%c",&t)!=EOF){
if(t=='\n')
break;
que.pop_front();
que.push_back(t);
if(que[0]=='J' && que[1]=='O' && que[2]=='I')
joi++;
else if(que[0]=='I' && que[1]=='O' && que[2]=='I')
ioi++;
}
printf("%d\n%d\n",joi,ioi);
}
return 0;
}
| 17.431373 | 56 | 0.482565 | punkieL |
d28713ecd5b2df494c956cf82d037b165648833a | 545 | hpp | C++ | hoibase/include/hoibase/helper/library.hpp | openhoi/openhoi | 5705ea8456ac526645f943b78b37bb993d44320c | [
"BSD-2-Clause",
"MIT"
] | 2 | 2022-02-11T17:28:38.000Z | 2022-03-17T00:57:40.000Z | hoibase/include/hoibase/helper/library.hpp | openhoi/openhoi | 5705ea8456ac526645f943b78b37bb993d44320c | [
"BSD-2-Clause",
"MIT"
] | 1 | 2019-03-07T09:51:18.000Z | 2019-03-07T09:51:18.000Z | hoibase/include/hoibase/helper/library.hpp | openhoi/openhoi | 5705ea8456ac526645f943b78b37bb993d44320c | [
"BSD-2-Clause",
"MIT"
] | 6 | 2019-10-03T13:26:53.000Z | 2022-03-20T14:33:22.000Z | // Copyright 2018-2019 the openhoi authors. See COPYING.md for legal info.
#pragma once
#if defined(_MSC_VER)
// Microsoft Visual Studio
# define OPENHOI_LIB_EXPORT __declspec(dllexport)
# define OPENHOI_LIB_IMPORT __declspec(dllimport)
#elif defined(__GNUC__)
// GCC
# define OPENHOI_LIB_EXPORT __attribute__((visibility("default")))
# define OPENHOI_LIB_IMPORT
#else
// do nothing and hope for the best?
# define OPENHOI_LIB_EXPORT
# define OPENHOI_LIB_IMPORT
# pragma warning Unknown dynamic link import / export semantics.
#endif | 30.277778 | 74 | 0.783486 | openhoi |
d2877dd17038f63f0aee5411151cf78462356faf | 2,048 | cpp | C++ | test/lexer.cpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | test/lexer.cpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | 3 | 2021-07-24T23:06:37.000Z | 2021-08-21T03:24:58.000Z | test/lexer.cpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "../src/lexer.hpp"
#include "../src/token.hpp"
TEST(Lexer, Function)
{
std::string input = "FUNCTION F_Sample : INT"
" VAR_INPUT"
" x : INT;"
" y : INT;"
" END_VAR"
" F_Sample := x + y;"
"END_FUNCTION;";
auto tokens = tokenize(input);
auto tok_vec = tokens.to_vec();
std::vector<Token>
expected_tok_vec{
Token("KEYWORD", "FUNCTION"),
Token("IDENTIFIER", "F_Sample"),
Token("SPECIAL_CHARACTER", ":"),
Token("IDENTIFIER", "INT"),
Token("KEYWORD", "VAR_INPUT"),
Token("IDENTIFIER", "x"),
Token("SPECIAL_CHARACTER", ":"),
Token("IDENTIFIER", "INT"),
Token("SPECIAL_CHARACTER", ";"),
Token("IDENTIFIER", "y"),
Token("SPECIAL_CHARACTER", ":"),
Token("IDENTIFIER", "INT"),
Token("SPECIAL_CHARACTER", ";"),
Token("KEYWORD", "END_VAR"),
Token("IDENTIFIER", "F_Sample"),
Token("OPERATOR", ":="),
Token("IDENTIFIER", "x"),
Token("OPERATOR", "+"),
Token("IDENTIFIER", "y"),
Token("SPECIAL_CHARACTER", ";"),
Token("KEYWORD", "END_FUNCTION"),
Token("SPECIAL_CHARACTER", ";"),
};
ASSERT_EQ(tok_vec.size(), expected_tok_vec.size());
for (int i = 0; i < tok_vec.size(); ++i)
{
EXPECT_EQ(tok_vec[i], expected_tok_vec[i]) << "Vectors x and y differ at index " << i;
}
}
TEST(Lexer, Assignment)
{
auto tokens = tokenize(":=");
auto tok_vec = tokens.to_vec();
std::vector<Token>
expected_tok_vec{Token("OPERATOR", ":=")};
ASSERT_EQ(tok_vec.size(), expected_tok_vec.size());
for (int i = 0; i < tok_vec.size(); ++i)
{
EXPECT_EQ(tok_vec[i], expected_tok_vec[i]) << "Vectors x and y differ at index " << i;
}
} | 30.117647 | 94 | 0.487793 | sethitow |
d288d7f715b9921343373e937b2e6875650e0c31 | 2,247 | cpp | C++ | lib/VM/BuildMetadata.cpp | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 2 | 2020-02-09T21:47:10.000Z | 2021-07-13T09:27:33.000Z | lib/VM/BuildMetadata.cpp | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 6 | 2021-03-11T07:21:46.000Z | 2022-02-27T11:15:48.000Z | lib/VM/BuildMetadata.cpp | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 2 | 2020-10-25T04:11:10.000Z | 2020-10-25T04:11:11.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/VM/BuildMetadata.h"
#include "hermes/VM/CellKind.h"
#include "llvm/Support/Debug.h"
#include <cstdint>
#define DEBUG_TYPE "metadata"
namespace hermes {
namespace vm {
static size_t getNumCellKinds() {
// This embeds the same value as the CellKind enum, but adds one more at the
// end to know how many values it contains.
enum CellKinds {
#define CELL_KIND(name) name,
#include "hermes/VM/CellKinds.def"
#undef CELL_KIND
numKinds,
};
return numKinds;
}
/// Creates and populates the storage for the metadata of the classes.
/// The caller takes ownership of the memory.
static const Metadata *buildStorage() {
// For each class of object, initialize its metadata
// Only run this once per class, not once per Runtime instantiation.
Metadata *storage = new Metadata[getNumCellKinds()];
size_t i = 0;
#define CELL_KIND(name) \
storage[i++] = buildMetadata(CellKind::name##Kind, name##BuildMeta);
#include "hermes/VM/CellKinds.def"
#undef CELL_KIND
assert(i == getNumCellKinds() && "Incorrect number of metadata populated");
return storage;
}
Metadata buildMetadata(CellKind kind, BuildMetadataCallback *builder) {
const GCCell *base;
#ifdef HERMES_UBSAN
// Using members on a nullptr is UB, but using a pointer to static memory is
// not.
static const int64_t buf[128]{};
base = reinterpret_cast<const GCCell *>(&buf);
#else
// Use nullptr when not building with UBSAN to ensure fast failures.
base = nullptr;
#endif
// This memory should not be read or written to
Metadata::Builder mb(base);
builder(base, mb);
Metadata meta = mb.build();
LLVM_DEBUG(
llvm::dbgs() << "Initialized metadata for cell kind " << cellKindStr(kind)
<< ": " << meta << "\n");
return meta;
}
MetadataTable getMetadataTable() {
// We intentionally leak memory here in order to avoid any static destructors
// running at exit time.
static const Metadata *storage = buildStorage();
return MetadataTable(storage, getNumCellKinds());
}
} // namespace vm
} // namespace hermes
| 29.181818 | 80 | 0.712061 | exced |
d28a42c1174cc5365e662ced523bcc0e01351f9e | 2,463 | cpp | C++ | framework/code/gui/android/imguiAndroid.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | framework/code/gui/android/imguiAndroid.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | framework/code/gui/android/imguiAndroid.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
#include "imguiAndroid.hpp"
#define NOMINMAX
#include <imgui/imgui.h>
//
// Implementation of GuiImguiPlatform (for Android)
//
GuiImguiPlatform::GuiImguiPlatform()
{}
GuiImguiPlatform::~GuiImguiPlatform()
{}
bool GuiImguiPlatform::Initialize(uintptr_t windowHandle, uint32_t deviceWidth, uint32_t deviceHeight, uint32_t renderWidth, uint32_t renderHeight)
{
if (!GuiImguiBase::Initialize(windowHandle))
{
return false;
}
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = 1.0f / 60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = float(deviceWidth); // set the current display width
io.DisplaySize.y = float(deviceHeight); // set the current display height here
io.DisplayFramebufferScale.x = (float)renderWidth / io.DisplaySize.x;
io.DisplayFramebufferScale.y = (float)renderHeight / io.DisplaySize.y;
float SCALE = 4.0f;
ImFontConfig cfg;
cfg.SizePixels = 13 * SCALE;
ImGui::GetIO().Fonts->AddFontDefault(&cfg)->DisplayOffset.y = SCALE;
//style.ScaleAllSizes(0);
return true;
}
//-----------------------------------------------------------------------------
void GuiImguiPlatform::Update()
{
GuiImguiBase::Update();
}
//-----------------------------------------------------------------------------
bool GuiImguiPlatform::TouchDownEvent(int iPointerID, float xPos, float yPos)
{
if (iPointerID == 0)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[0] = true; // left button down
io.MousePos = { xPos, yPos };
return io.WantCaptureMouse;
}
return false;
}
//-----------------------------------------------------------------------------
bool GuiImguiPlatform::TouchMoveEvent(int iPointerID, float xPos, float yPos)
{
if (iPointerID == 0)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[0] = true;
io.MousePos = { xPos,yPos };
return io.WantCaptureMouse;
}
return false;
}
//-----------------------------------------------------------------------------
bool GuiImguiPlatform::TouchUpEvent(int iPointerID, float xPos, float yPos)
{
if (iPointerID == 0)
{
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[0] = false; // left button up
return io.WantCaptureMouse;
}
return false;
}
| 27.366667 | 147 | 0.574503 | MikeCurrington |
d28dff0987dbb8ae6edb9bcb56c0f3199a19a8da | 1,606 | cpp | C++ | ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/stub/javax/swing/JComponent_ReadObjectCallback-stub.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <javax/swing/JComponent_ReadObjectCallback.hpp>
#include <javax/swing/JComponent.hpp>
extern void unimplemented_(const char16_t* name);
javax::swing::JComponent_ReadObjectCallback::JComponent_ReadObjectCallback(JComponent *JComponent_this, const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
, JComponent_this(JComponent_this)
{
clinit();
}
javax::swing::JComponent_ReadObjectCallback::JComponent_ReadObjectCallback(JComponent *JComponent_this, ::java::io::ObjectInputStream* s)
: JComponent_ReadObjectCallback(JComponent_this, *static_cast< ::default_init_tag* >(0))
{
ctor(s);
}
void ::javax::swing::JComponent_ReadObjectCallback::ctor(::java::io::ObjectInputStream* s)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::javax::swing::JComponent_ReadObjectCallback::ctor(::java::io::ObjectInputStream* s)");
}
/* private: void javax::swing::JComponent_ReadObjectCallback::registerComponent(JComponent* c) */
void javax::swing::JComponent_ReadObjectCallback::validateObject()
{ /* stub */
unimplemented_(u"void javax::swing::JComponent_ReadObjectCallback::validateObject()");
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* javax::swing::JComponent_ReadObjectCallback::class_()
{
static ::java::lang::Class* c = ::class_(u"javax.swing.JComponent.ReadObjectCallback", 41);
return c;
}
java::lang::Class* javax::swing::JComponent_ReadObjectCallback::getClass0()
{
return class_();
}
| 34.913043 | 137 | 0.750311 | pebble2015 |
d28e3369e27864527358fa4c542e06a8913d58f7 | 450 | cpp | C++ | c++/xu/learn.cpp | nkysg/Asenal | 12444c7e50fae2be82d3c4737715a52e3693a3cd | [
"Apache-2.0"
] | 5 | 2017-04-10T03:35:40.000Z | 2020-11-26T10:00:57.000Z | c++/xu/learn.cpp | nkysg/Asenal | 12444c7e50fae2be82d3c4737715a52e3693a3cd | [
"Apache-2.0"
] | 1 | 2015-04-09T13:45:25.000Z | 2015-04-09T13:45:25.000Z | c++/xu/learn.cpp | baotiao/Asenal | 102170aa92ae72b1d589dd74e8bbbc9ae27a8d97 | [
"Apache-2.0"
] | 15 | 2015-03-10T04:15:10.000Z | 2021-03-19T13:00:48.000Z | #include<iostream>
#include<stdio.h>
using namespace std;
class X {
public:
X(int x) { _val = x;}
int val() { return _val;}
private:
int _val;
};
class Y {
public:
Y(int y);
static X xval();
static int callsXval();
private:
static X _xval;
static int _callsXval;
};
int main()
{
int num = 20;
X *xx = new X (num);
printf("%d\n", xx->val());
return 0;
}
| 16.071429 | 33 | 0.502222 | nkysg |
d2904c04e891f05dddd6b2eaf3574eaa05531979 | 1,178 | cpp | C++ | TEST_C++/Test_env/src/robot-config.cpp | Asik007/1526B-VEX-code | 69dc0187001b70793afa7a395be563daf303d163 | [
"MIT"
] | 1 | 2021-11-02T20:27:41.000Z | 2021-11-02T20:27:41.000Z | TEST_C++/Test_env/src/robot-config.cpp | Asik007/1526B-VEX-code | 69dc0187001b70793afa7a395be563daf303d163 | [
"MIT"
] | null | null | null | TEST_C++/Test_env/src/robot-config.cpp | Asik007/1526B-VEX-code | 69dc0187001b70793afa7a395be563daf303d163 | [
"MIT"
] | 1 | 2021-09-05T19:06:36.000Z | 2021-09-05T19:06:36.000Z | #include "vex.h"
using namespace vex;
using signature = vision::signature;
using code = vision::code;
// A global instance of brain used for printing to the V5 Brain screen
brain Brain;
// VEXcode device constructors
encoder EncoderA = encoder(Brain.ThreeWirePort.A);
encoder EncoderB = encoder(Brain.ThreeWirePort.C);
encoder EncoderC = encoder(Brain.ThreeWirePort.E);
controller Controller1 = controller(primary);
motor leftMotorA = motor(PORT1, ratio18_1, false);
motor leftMotorB = motor(PORT2, ratio18_1, false);
motor_group LeftDriveSmart = motor_group(leftMotorA, leftMotorB);
motor rightMotorA = motor(PORT3, ratio18_1, true);
motor rightMotorB = motor(PORT4, ratio18_1, true);
motor_group RightDriveSmart = motor_group(rightMotorA, rightMotorB);
gyro DrivetrainGyro = gyro(Brain.ThreeWirePort.H);
smartdrive Drivetrain = smartdrive(LeftDriveSmart, RightDriveSmart, DrivetrainGyro, 319.19, 320, 40, mm, 2.3333333333333335);
// VEXcode generated functions
/**
* Used to initialize code/tasks/devices added using tools in VEXcode Pro.
*
* This should be called at the start of your int main function.
*/
void vexcodeInit( void ) {
// nothing to initialize
} | 33.657143 | 125 | 0.774194 | Asik007 |
d2908c83591b7d84ac3eb321a2ef98cd310c9080 | 1,242 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_old_calc/calc_constantnumbertype.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_old_calc/calc_constantnumbertype.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_old_calc/calc_constantnumbertype.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #include "stddefx.h"
#ifndef INCLUDED_CALC_CONSTANTNUMBERTYPE
#include "calc_constantnumbertype.h"
#define INCLUDED_CALC_CONSTANTNUMBERTYPE
#endif
#ifndef INCLUDED_CALC_VS
#include "calc_vs.h" // intersect
#define INCLUDED_CALC_VS
#endif
#ifndef INCLUDED_SSTREAM
#include <sstream>
#define INCLUDED_SSTREAM
#endif
static VS TypeNumber(double value)
{
int set = (int)VS_FIELD;
if ( value >= (double)LONG_MIN && value <= (double)LONG_MAX )
{
long i = (long)value;
if ( value == ((double)i) )
{
/* if the value is not equal to 0 or 1
then it's not a boolean */
if (value != 0 && value != 1)
set &= ~VS_B; /* mask VS_B out of set */
/* same sort of check for ldd */
if (value < 1 || value > 9 )
set &= ~VS_L; /* idem */
} else {
/* it's a real: mask classifieds out */
set &= ~(VS_N|VS_O|VS_B|VS_L);
}
} else {
/* even if it is an integer we cannot store it in a real: mask classifieds out */
set &= ~(VS_N|VS_O|VS_B|VS_L);
}
VS setTypes = (VS)set;
return setTypes;
}
calc::ConstantNumberType::ConstantNumberType(double value, VS restrictBy):
calc::FieldType(intersect(TypeNumber(value),restrictBy),ST_NONSPATIAL)
{
}
| 23.884615 | 85 | 0.633655 | quanpands |
d2909926506b3d7751e7378311fa03c544095476 | 700 | cpp | C++ | CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp | JCharlieDev/CPP-Intro | 3d4888d413a09ae3579ef9079eaf1982a10c0d05 | [
"MIT"
] | null | null | null | CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp | JCharlieDev/CPP-Intro | 3d4888d413a09ae3579ef9079eaf1982a10c0d05 | [
"MIT"
] | null | null | null | CPP-BasicToAdvanced/CPP-BasicToAdvanced/Math.cpp | JCharlieDev/CPP-Intro | 3d4888d413a09ae3579ef9079eaf1982a10c0d05 | [
"MIT"
] | null | null | null | // #define INTEGER int
// Stuff about how the compiler works and how to read the output files in the properties menu of the project.
// How to set up the optimization and how it affects the code
// How header files work and use them to generate and replace code.
#include <iostream>
#include "Log.h"
//// Optimized version
//const char* Log(const char* message)
//{
// return message;
//}
//void Log(const char* message)
//{
// std::cout << message << std::endl;
//}
int MultiplyNum(int a, int b)
{
Log("Multiplication");
return Multiply(a, b);
}
inline int Multiply(int a, int b)
{
return a * b;
}
// #include "EndBrace.h" // Literally copies the code of the header file into the cpp file
| 21.212121 | 109 | 0.69 | JCharlieDev |
d293a1ca252bc7340d9cd21cc5b7164cfeebc84b | 7,825 | hpp | C++ | tests/make_json.hpp | amoylel/json | 551b4faac85a6a38754100bb8635a7a894476ccc | [
"MIT"
] | 3 | 2020-02-16T15:26:30.000Z | 2020-07-05T04:50:22.000Z | tests/make_json.hpp | amoylel/json | 551b4faac85a6a38754100bb8635a7a894476ccc | [
"MIT"
] | null | null | null | tests/make_json.hpp | amoylel/json | 551b4faac85a6a38754100bb8635a7a894476ccc | [
"MIT"
] | 1 | 2020-06-11T02:58:11.000Z | 2020-06-11T02:58:11.000Z | #include "./../json.hpp"
typedef amo::json json_type;
namespace {
//dde.set_value(33);
int32_t length = 10000;
json_type make_json2() {
json_type info;
info.put("m_bool", true);
//info.put("m_char", 'c');
info.put("m_int8_t", 8);
info.put("m_int16_t", 16);
info.put("m_int32_t", 32);
info.put("m_int64_t", 64);
info.put("m_uint8_t", 8u);
info.put("m_uint16_t", 16u);
info.put("m_uint32_t", 32u);
info.put("m_uin64_t", 64u);
info.put("m_float", 1.0);
info.put("m_double", 2.22);
info.put("m_string", "string txt");
info["m_string"].put("string txt");
/* info.put("m_strine", u8"kd wer\\r\\n中方式\\u3053\\u3093\\u306b\\u3061\\u306f\\u4e16\\u754c\\uff0112312中文");
info.put("m_string2", "string txt11111111111111111111111111111111111111111111");*/
//std::string st = info.to_string();
return info;
}
json_type make_json() {
json_type vec1(amo::json_value_array);
vec1.push_back("1");
vec1.push_back("2");
vec1.push_back("3");
json_type vec2(amo::json_value_array);
vec2.push_back(4);
vec2.push_back(5);
vec2.push_back(6);
json_type vec3(amo::json_value_array);
{
json_type arr3(amo::json_value_array);
arr3.push_back(7);
arr3.push_back(8);
arr3.push_back(9);
/*arr3.push_back( u8"kd wer\\r\\n中方式\\u3053\\u3093\\u306b\\u3061\\u306f\\u4e16\\u754c\\uff0112312中文");
arr3.push_back( "string txt11111111111111111111111111111111111111111111");*/
vec3.push_back(arr3);
vec3.push_back(arr3);
vec3.push_back(arr3);
}
json_type json;
json.put("vec1", vec1);
json.put("vec2", vec2);
json.put("vec3", vec3);
;
json_type info;
info.put("m_bool", true);
//info.put("m_char", 'c');
info.put("m_int8_t", 8);
info.put("m_int16_t", 16);
info.put("m_int32_t", 32);
info.put("m_int64_t", 64);
info.put("m_uint8_t", 8u);
info.put("m_uint16_t", 16u);
info.put("m_uint32_t", 32u);
info.put("m_uin64_t", 64u);
info.put("m_float", 1.0);
info.put("m_double", 2.22);
info.put("m_string", "string txt");
/* info.put("m_strine2", u8"kd wer\\r\\n中方式\\u3053\\u3093\\u306b\\u3061\\u306f\\u4e16\\u754c\\uff0112312中文");
info.put("m_string3", "string txt11111111111111111111111111111111111111111111");*/
// json.put("m_jsoninfo2", info);
// json.put("m_jsoninfo3", info);
//
// std::cout << json.to_string() << std::endl;
json_type jsoninfoclass;
jsoninfoclass.put("m_jsoninfo1", info);
jsoninfoclass.put("m_jsoninfo2", info);
json.put("m_jsoninfo2", jsoninfoclass);
json.put("m_jsoninfo3", jsoninfoclass);
// std::cout << json.to_string() << std::endl;
json_type arr(amo::json_value_array);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
json.put("m_jsoninfo4", arr);
json.put("m_jsoninfo5", arr);
json_type arr2(amo::json_value_array);
arr2.push_back(arr);
arr2.push_back(arr);
arr2.push_back(arr);
json.put("m_jsoninfo6", arr2);
return json;
}
json_type make_json3() {
json_type vec1(amo::json_value_array);
/*vec1.push_back("1");
vec1.push_back("2");
vec1.push_back("3");
*/
json_type vec2(amo::json_value_array);
/*vec2.push_back(4);
vec2.push_back(5);
vec2.push_back(6);*/
json_type vec3(amo::json_value_array);
{
json_type arr3(amo::json_value_array);
/*arr3.push_back(7);
arr3.push_back(8);
arr3.push_back(9);*/
vec3.push_back(arr3);
vec3.push_back(arr3);
vec3.push_back(arr3);
}
json_type json;
/* json.put("vec1", vec1);
json.put("vec2", vec2);
json.put("vec3", vec3);*/
;
json_type info;
//info.put("m_bool", true);
////info.put("m_char", 'c');
//info.put("m_int8_t", 8);
//info.put("m_int16_t", 16);
//info.put("m_int32_t", 32);
//info.put("m_int64_t", 64);
//info.put("m_uint8_t", 8u);
//info.put("m_uint16_t", 16u);
//info.put("m_uint32_t", 32u);
//info.put("m_uin64_t", 64u);
//info.put("m_float", 1.0);
//info.put("m_double", 2.22);
//info.put("m_string", "string txt");
json.put("m_jsoninfo2", info);
json.put("m_jsoninfo3", info);
json_type jsoninfoclass;
jsoninfoclass.put("m_jsoninfo1", info);
jsoninfoclass.put("m_jsoninfo2", info);
json.put("m_jsoninfo2", jsoninfoclass);
json.put("m_jsoninfo3", jsoninfoclass);
json_type arr(amo::json_value_array);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
arr.push_back(jsoninfoclass);
json.put("m_jsoninfo4", arr);
json.put("m_jsoninfo5", arr);
json_type arr2(amo::json_value_array);
arr2.push_back(arr);
arr2.push_back(arr);
arr2.push_back(arr);
json.put("m_jsoninfo6", arr2);
return json;
}
}
namespace amo {
class custom_class {
public:
const static int __json_type_value__ = 11111;
public:
custom_class() { }
custom_class(const std::string& str) : m_str(str) { }
std::string to_string() const { return m_str; }
static custom_class from_string(const std::string& str) { return custom_class(str); }
std::string m_str;
};
static inline std::string to_string(const amo::custom_class& val) {
return val.to_string();
}
template<> inline amo::custom_class from_string(const std::string& str) {
return custom_class::from_string(str);
}
class custom_class2 {
public:
custom_class2() { }
custom_class2(const std::string& str) : m_str(str) { }
json_type to_json() const { return json_type(); }
static custom_class2* from_json(const json_type& json, custom_class2* ptr) {
if (ptr == nullptr) {
ptr = new custom_class2();
}
ptr->m_str = json["m_str"].get<std::string>();
return ptr;
}
std::string m_str;
};
class custom_class3 {
public:
json_type to_json() const { return json_type(); }
public:
custom_class3() {}
custom_class3(const json_type& str) : m_str(str["m_string"].get<std::string>()) {
std::cout << __FUNCTION__ << std::endl;
}
custom_class3(const std::string& str) : m_str(str) { }
std::string to_string() const { json_type json; json["m_str"] = m_str; return json.to_string(); }
static custom_class3* from_json(const json_type& json, custom_class3* ptr) {
if (ptr == nullptr) {
ptr = new custom_class3();
}
ptr->m_str = json["m_str"].get<std::string>();
return ptr;
}
std::string m_str;
};
} | 30.928854 | 118 | 0.532652 | amoylel |
d293c5755c27c9cb0da3e2df7cf15417ee7552a0 | 724 | hpp | C++ | src/mirrage/graphic/src/ktx_parser.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 14 | 2017-10-26T08:45:54.000Z | 2021-04-06T11:44:17.000Z | src/mirrage/graphic/src/ktx_parser.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 17 | 2017-10-09T20:11:58.000Z | 2018-11-08T22:05:14.000Z | src/mirrage/graphic/src/ktx_parser.hpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 1 | 2018-09-26T23:10:06.000Z | 2018-09-26T23:10:06.000Z | #pragma once
#include <mirrage/asset/stream.hpp>
#include <mirrage/graphic/vk_wrapper.hpp>
#include <mirrage/utils/maybe.hpp>
#include <vulkan/vulkan.hpp>
namespace mirrage::graphic {
// https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
struct Ktx_header {
std::uint32_t width;
std::uint32_t height;
std::uint32_t depth;
std::uint32_t layers;
bool cubemap;
std::uint32_t mip_levels;
std::uint32_t size;
vk::Format format;
Image_type type;
};
// reads the KTX header and advances the read position to the beginning of the actual data
extern auto parse_header(asset::istream&, const std::string& filename) -> util::maybe<Ktx_header>;
} // namespace mirrage::graphic
| 24.965517 | 99 | 0.723757 | lowkey42 |
d295da490be9ad3d3473fe46d9ca69bd4f30687d | 21,046 | cpp | C++ | src/cmd/kits/row.cpp | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | 12 | 2018-12-14T08:57:05.000Z | 2021-12-14T17:37:44.000Z | src/cmd/kits/row.cpp | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | null | null | null | src/cmd/kits/row.cpp | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | 2 | 2019-08-04T21:39:12.000Z | 2019-11-09T03:18:48.000Z | /* -*- mode:C++; c-basic-offset:4 -*-
Shore-kits -- Benchmark implementations for Shore-MT
Copyright (c) 2007-2009
Data Intensive Applications and Systems Labaratory (DIAS)
Ecole Polytechnique Federale de Lausanne
All Rights Reserved.
Permission to use, copy, modify and distribute this software and
its documentation is hereby granted, provided that both the
copyright notice and this permission notice appear in all copies of
the software, derivative works or modified versions, and any
portions thereof, and that both notices appear in supporting
documentation.
This code 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. THE AUTHORS
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
RESULTING FROM THE USE OF THIS SOFTWARE.
*/
/** @file: row.cpp
*
* @brief: Implementation of the base class for records (rows) of tables in Shore
*
* @author: Ippokratis Pandis, January 2008
* @author: Caetano Sauer, April 2015
*
*/
#include "row.h"
#include "table_desc.h"
#include "index_desc.h"
#define VAR_SLOT(start, offset) ((start)+(offset))
#define SET_NULL_FLAG(start, offset) \
(*(char*)((start)+((offset)>>3))) &= (1<<((offset)>>3))
#define IS_NULL_FLAG(start, offset) \
(*(char*)((start)+((offset)>>3)))&(1<<((offset)>>3))
/******************************************************************
*
* @struct: rep_row_t
*
* @brief: A scratchpad for writing the disk format of a tuple
*
******************************************************************/
rep_row_t::rep_row_t()
: _dest(NULL), _bufsz(0), _pts(NULL)
{ }
rep_row_t::rep_row_t(blob_pool* apts)
: _dest(NULL), _bufsz(0), _pts(apts)
{
assert (_pts);
}
rep_row_t::~rep_row_t()
{
if (_dest) {
_pts->destroy(_dest);
_dest = NULL;
}
}
/******************************************************************
*
* @fn: set
*
* @brief: Set new buffer size
*
******************************************************************/
void rep_row_t::set(const unsigned nsz)
{
if ((!_dest) || (_bufsz < nsz)) {
char* tmp = _dest;
// Using the trash stack
assert (_pts);
//_dest = new(*_pts) char(nsz);
w_assert1(nsz <= _pts->nbytes());
_dest = (char*)_pts->acquire();
assert (_dest); // Failed to allocate such a big buffer
if (tmp) {
// delete [] tmp;
_pts->destroy(tmp);
tmp = NULL;
}
_bufsz = _pts->nbytes();
}
// in any case, clean up the buffer
memset (_dest, 0, nsz);
}
/******************************************************************
*
* @fn: set_ts
*
* @brief: Set new trash stack and buffer size
*
******************************************************************/
void rep_row_t::set_ts(blob_pool* apts, const unsigned nsz)
{
assert(apts);
_pts = apts;
set(nsz);
}
/******************************************************************
*
* @class: table_row_t
*
* @brief: The (main-memory) record representation in kits
*
******************************************************************/
table_row_t::table_row_t()
: _ptable(NULL),
_field_cnt(0), _is_setup(false),
_pvalues(NULL),
_fixed_offset(0),_var_slot_offset(0),_var_offset(0),_null_count(0),
_rep(NULL), _rep_key(NULL)
{
}
table_row_t::~table_row_t()
{
freevalues();
}
/******************************************************************
*
* @fn: setup()
*
* @brief: Setups the row (tuple main-memory representation) according
* to its table description. This setup will be done only
* *once*. When this row will be initialized in the row cache.
*
******************************************************************/
int table_row_t::setup(table_desc_t* ptd)
{
assert (ptd);
// if it is already setup for this table just reset it
if ((_ptable == ptd) && (_pvalues != NULL) && (_is_setup)) {
reset();
return (1);
}
// else do the normal setup
_ptable = ptd;
_field_cnt = ptd->field_count();
assert (_field_cnt>0);
_pvalues = new field_value_t[_field_cnt];
unsigned var_count = 0;
unsigned fixed_size = 0;
// setup each field and calculate offsets along the way
for (unsigned i=0; i<_field_cnt; i++) {
_pvalues[i].setup(ptd->desc(i));
// count variable- and fixed-sized fields
if (_pvalues[i].is_variable_length())
var_count++;
else
fixed_size += _pvalues[i].maxsize();
// count null-able fields
if (_pvalues[i].field_desc()->allow_null())
_null_count++;
}
// offset for fixed length field values
_fixed_offset = 0;
if (_null_count) _fixed_offset = ((_null_count-1) >> 3) + 1;
// offset for variable length field slots
_var_slot_offset = _fixed_offset + fixed_size;
// offset for variable length field values
_var_offset = _var_slot_offset + sizeof(offset_t)*var_count;
_is_setup = true;
return (0);
}
/******************************************************************
*
* @fn: size()
*
* @brief: Return the actual size of the tuple in disk format
*
******************************************************************/
unsigned table_row_t::size() const
{
assert (_is_setup);
unsigned size = 0;
/* for a fixed length field, it just takes as much as the
* space for the value itself to store.
* for a variable length field, we store as much as the data
* and the offset to tell the length of the data.
* Of course, there is a bit for each nullable field.
*/
for (unsigned i=0; i<_field_cnt; i++) {
if (_pvalues[i]._pfield_desc->allow_null()) {
if (_pvalues[i].is_null()) continue;
}
if (_pvalues[i].is_variable_length()) {
size += _pvalues[i].realsize();
size += sizeof(offset_t);
}
else size += _pvalues[i].maxsize();
}
if (_null_count) size += (_null_count >> 3) + 1;
return (size);
}
void _load_signed_int(char* dest, char* src, size_t nbytes)
{
// invert sign bit and reverse endianness
size_t lsb = nbytes - 1;
for (size_t i = 0; i < nbytes; i++) {
dest[i] = src[lsb - i];
}
dest[lsb] ^= 0x80;
}
void table_row_t::load_key(char* data, index_desc_t* pindex)
{
char buffer[8];
char* pos = data;
#ifdef USE_LEVELDB
if (pindex) {
// In LevelDB storage, first byte of key is the StoreID
auto stid = static_cast<StoreID>(*data);
w_assert1(stid > 0 && stid < 128);
w_assert1(stid == pindex->stid());
pos++;
}
#endif
unsigned field_cnt = pindex ? pindex->field_count() : _field_cnt;
for (unsigned j = 0; j < field_cnt; j++) {
unsigned i = pindex ? pindex->key_index(j) : j;
field_value_t& field = _pvalues[i];
field_desc_t* fdesc = field._pfield_desc;
w_assert1(field.is_setup());
if (fdesc->allow_null()) {
bool is_null = (*pos == true);
field.set_null(is_null);
pos++;
if (is_null) {
continue;
}
}
switch (fdesc->type()) {
case SQL_BIT: {
field.set_bit_value(*pos);
pos++;
break;
}
case SQL_SMALLINT: {
memcpy(buffer, pos, 2);
_load_signed_int(buffer, pos, 2);
field.set_smallint_value(*(int16_t*) buffer);
pos += 2;
break;
}
case SQL_INT: {
memcpy(buffer, pos, 4);
_load_signed_int(buffer, pos, 4);
field.set_int_value(*(int32_t*) buffer);
pos += 4;
break;
}
case SQL_LONG: {
memcpy(buffer, pos, 8);
_load_signed_int(buffer, pos, 8);
field.set_long_value(*(int64_t*) buffer);
pos += 8;
break;
}
case SQL_FLOAT: {
memcpy(buffer, pos, 8);
// invert endianness and handle sign bit
if (buffer[0] & 0x80) {
// inverted sign bit == 1 -> positive
// invert only sign bit
for (int i = 0; i < 8; i++) {
buffer[i] = pos[7 - i];
}
buffer[7] ^= 0x80;
}
else {
// otherwise invert all bits
for (int i = 0; i < 8; i++) {
buffer[i] = pos[7 - i] ^ 0x80;
}
}
field.set_float_value(*(double*) buffer);
pos += 8;
break;
}
case SQL_CHAR:
field.set_char_value(*pos);
pos++;
break;
case SQL_FIXCHAR: {
size_t len = strlen(pos);
field.set_fixed_string_value(pos, len);
pos += len + 1;
break;
}
case SQL_VARCHAR: {
size_t len = strlen(pos);
field.set_var_string_value(pos, len);
pos += len + 1;
break;
}
default:
throw runtime_error("Serialization not supported for the \
given type");
}
}
}
void table_row_t::load_value(char* data, index_desc_t* pindex)
{
// Read the data field by field
assert (data);
// 1. Get the pre-calculated offsets
// current offset for fixed length field values
offset_t fixed_offset = get_fixed_offset();
// current offset for variable length field slots
offset_t var_slot_offset = get_var_slot_offset();
// current offset for variable length field values
offset_t var_offset = get_var_offset();
// 2. Read the data field by field
int null_index = -1;
for (unsigned i=0; i<_ptable->field_count(); i++) {
if (pindex) {
bool skip = false;
// skip key fields
for (unsigned j = 0; j < pindex->field_count(); j++) {
if ((int) i == pindex->key_index(j)) {
skip = true;
break;
}
}
if (skip) continue;
}
// Check if the field can be NULL.
// If it can be NULL, increase the null_index,
// and check if the bit in the null_flags bitmap is set.
// If it is set, set the corresponding value in the tuple
// as null, and go to the next field, ignoring the rest
if (_pvalues[i].field_desc()->allow_null()) {
null_index++;
if (IS_NULL_FLAG(data, null_index)) {
_pvalues[i].set_null();
continue;
}
}
// Check if the field is of VARIABLE length.
// If it is, copy the offset of the value from the offset part of the
// buffer (pointed by var_slot_offset). Then, copy that many chars from
// the variable length part of the buffer (pointed by var_offset).
// Then increase by one offset index, and offset of the pointer of the
// next variable value
if (_pvalues[i].is_variable_length()) {
offset_t var_len;
memcpy(&var_len, VAR_SLOT(data, var_slot_offset), sizeof(offset_t));
_pvalues[i].set_value(data+var_offset, var_len);
var_offset += var_len;
var_slot_offset += sizeof(offset_t);
}
else {
// If it is of FIXED length, copy the data from the fixed length
// part of the buffer (pointed by fixed_offset), and the increase
// the fixed offset by the (fixed) size of the field
_pvalues[i].set_value(data+fixed_offset, _pvalues[i].maxsize());
fixed_offset += _pvalues[i].maxsize();
}
}
}
void _store_signed_int(char* dest, char* src, size_t nbytes)
{
// reverse endianness and invert sign bit
size_t lsb = nbytes - 1;
for (size_t i = 0; i < nbytes; i++) {
dest[i] = src[lsb - i];
}
dest[0] ^= 0x80;
}
void table_row_t::store_key(char* data, size_t& length, index_desc_t* pindex)
{
size_t req_size = 0;
char buffer[8];
char* pos = data;
#ifdef USE_LEVELDB
// In LevelDB storage, first byte of key is the StoreID
if (pindex) {
auto stid = pindex->stid();
w_assert1(stid > 0 && stid < 128);
*pos = static_cast<char>(stid);
pos++;
req_size++;
w_assert1(data[0] != 0);
}
#endif
unsigned field_cnt = pindex ? pindex->field_count() : _field_cnt;
for (unsigned j = 0; j < field_cnt; j++) {
unsigned i = pindex ? pindex->key_index(j) : j;
field_value_t& field = _pvalues[i];
field_desc_t* fdesc = field._pfield_desc;
w_assert1(field.is_setup());
req_size += field.realsize();
if (fdesc->allow_null()) { req_size++; }
if (length < req_size) {
throw runtime_error("Tuple does not fit on given buffer");
}
if (fdesc->allow_null()) {
if (field.is_null()) {
// copy a zero byte to the output and proceed
*pos = 0x00;
pos++;
continue;
}
else {
// non-null nullable fields require a 1 prefix
*pos = 0xFF;
pos++;
}
}
switch (fdesc->type()) {
case SQL_BIT: {
bool v = field.get_bit_value();
*pos = v ? 0xFF : 0x00;
break;
}
case SQL_SMALLINT: {
field.copy_value(buffer);
_store_signed_int(pos, buffer, 2);
pos += 2;
break;
}
case SQL_INT: {
field.copy_value(buffer);
_store_signed_int(pos, buffer, 4);
pos += 4;
break;
}
case SQL_LONG: {
field.copy_value(buffer);
_store_signed_int(pos, buffer, 8);
pos += 8;
break;
}
case SQL_FLOAT: {
field.copy_value(buffer);
// invert endianness and handle sign bit
if (buffer[0] & 0x80) {
// if negative, invert all bits
for (int i = 0; i < 8; i++) {
pos[i] = buffer[7 - i] ^ 0xFF;
}
}
else {
// otherwise invert only sign bit
for (int i = 0; i < 8; i++) {
pos[i] = buffer[7 - i];
}
pos[0] ^= 0x80;
}
pos += 8;
break;
}
case SQL_CHAR:
*pos = field.get_char_value();
pos++;
break;
case SQL_FIXCHAR:
case SQL_VARCHAR:
// Assumption is that strings already include the terminating zero
field.copy_value(pos);
pos += field.realsize();
w_assert1(*(pos - 1) == 0);
break;
default:
throw runtime_error("Serialization not supported for the \
given type");
}
}
length = req_size;
w_assert1(pos - data == (long) length);
}
void table_row_t::store_value(char* data, size_t& length, index_desc_t* pindex)
{
// 1. Get the pre-calculated offsets
// current offset for fixed length field values
offset_t fixed_offset = get_fixed_offset();
// current offset for variable length field slots
offset_t var_slot_offset = get_var_slot_offset();
// current offset for variable length field values
offset_t var_offset = get_var_offset();
// 2. calculate the total space of the tuple
// (tupsize) : total space of the tuple
int tupsize = 0;
int null_count = get_null_count();
int fixed_size = get_var_slot_offset() - get_fixed_offset();
// loop over all the variable-sized fields and add their real size (set at ::set())
for (unsigned i=0; i<_ptable->field_count(); i++) {
if (_pvalues[i].is_variable_length()) {
// If it is of VARIABLE length, then if the value is null
// do nothing, else add to the total tuple length the (real)
// size of the value plus the size of an offset.
if (_pvalues[i].is_null()) continue;
tupsize += _pvalues[i].realsize();
tupsize += sizeof(offset_t);
}
// If it is of FIXED length, then increase the total tuple
// length, as well as, the size of the fixed length part of
// the tuple by the fixed size of this type of field.
// IP: The length of the fixed-sized fields is added after the loop
}
// Add up the length of the fixed-sized fields
tupsize += fixed_size;
// In the total tuple length add the size of the bitmap that
// shows which fields can be NULL
if (null_count) tupsize += (null_count >> 3) + 1;
assert (tupsize);
if ((long) length < tupsize) {
throw runtime_error("Tuple does not fit on allocated buffer");
}
length = tupsize;
// 4. Copy the fields to the array, field by field
int null_index = -1;
// iterate over all fields
for (unsigned i=0; i<_ptable->field_count(); i++) {
// skip fields which are part of the given index
if (pindex) {
bool skip = false;
for (unsigned j=0; j<pindex->field_count(); j++) {
if ((int) i == pindex->key_index(j)) {
skip = true;
break;
}
}
if (skip) continue;
}
// Check if the field can be NULL.
// If it can be NULL, increase the null_index, and
// if it is indeed NULL set the corresponding bit
if (_pvalues[i].field_desc()->allow_null()) {
null_index++;
if (_pvalues[i].is_null()) {
SET_NULL_FLAG(data, null_index);
}
}
// Check if the field is of VARIABLE length.
// If it is, copy the field value to the variable length part of the
// buffer, to position (buffer + var_offset)
// and increase the var_offset.
if (_pvalues[i].is_variable_length()) {
_pvalues[i].copy_value(data + var_offset);
int offset = _pvalues[i].realsize();
var_offset += offset;
// set the offset
offset_t len = offset;
memcpy(VAR_SLOT(data, var_slot_offset), &len,
sizeof(offset_t));
var_slot_offset += sizeof(offset_t);
}
else {
// If it is of FIXED length, then copy the field value to the
// fixed length part of the buffer, to position
// (buffer + fixed_offset)
// and increase the fixed_offset
_pvalues[i].copy_value(data + fixed_offset);
fixed_offset += _pvalues[i].maxsize();
}
}
}
/* ----------------- */
/* --- debugging --- */
/* ----------------- */
/* For debug use only: print the value of all the fields of the tuple */
void table_row_t::print_values(ostream& os)
{
assert (_is_setup);
// cout << "Number of fields: " << _field_count << endl;
for (unsigned i=0; i<_field_cnt; i++) {
_pvalues[i].print_value(os);
if (i != _field_cnt-1) os << DELIM_CHAR;
}
os << ROWEND_CHAR << endl;
}
/* For debug use only: print the tuple */
void table_row_t::print_tuple()
{
assert (_is_setup);
char* sbuf = NULL;
int sz = 0;
for (unsigned i=0; i<_field_cnt; i++) {
sz = _pvalues[i].get_debug_str(sbuf);
if (sbuf) {
TRACE( TRACE_TRX_FLOW, "%d. %s (%d)\n", i, sbuf, sz);
delete [] sbuf;
sbuf = NULL;
}
}
}
/* For debug use only: print the tuple without tracing */
void table_row_t::print_tuple_no_tracing()
{
assert (_is_setup);
char* sbuf = NULL;
int sz = 0;
for (unsigned i=0; i<_field_cnt; i++) {
sz = _pvalues[i].get_debug_str(sbuf);
if (sbuf) {
fprintf( stderr, "%d. %s (%d)\n", i, sbuf, sz);
delete [] sbuf;
sbuf = NULL;
}
}
}
#include <sstream>
char const* db_pretty_print(table_row_t const* rec, int /* i=0 */, char const* /* s=0 */)
{
static char data[1024];
std::stringstream inout(data,stringstream::in | stringstream::out);
//std::strstream inout(data, sizeof(data));
((table_row_t*)rec)->print_values(inout);
inout << std::ends;
return data;
}
| 29.311978 | 89 | 0.518483 | caetanosauer |
d29739c3adbe4c99a8a28120e1ecac258c85ba52 | 2,750 | cpp | C++ | src/external/coremltools_wrap/coremltools/caffeconverter/Caffe/InputLayers.cpp | LeeCenY/turicreate | fb2f3bf313e831ceb42a2e10aacda6e472ea8d93 | [
"BSD-3-Clause"
] | 2 | 2019-02-08T08:45:27.000Z | 2020-09-07T05:55:18.000Z | src/external/coremltools_wrap/coremltools/caffeconverter/Caffe/InputLayers.cpp | znation/turicreate | f56f9ef9c138d8047037184afb6356c20bbc7f71 | [
"BSD-3-Clause"
] | 3 | 2022-02-15T04:42:24.000Z | 2022-03-12T01:05:15.000Z | src/external/coremltools_wrap/coremltools/caffeconverter/Caffe/InputLayers.cpp | znation/turicreate | f56f9ef9c138d8047037184afb6356c20bbc7f71 | [
"BSD-3-Clause"
] | 1 | 2019-11-23T09:47:24.000Z | 2019-11-23T09:47:24.000Z | //
// InputLayers.cpp
// CoreML
//
// Created by Srikrishna Sridhar on 11/13/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
#include "CaffeConverter.hpp"
#include "Utils-inl.hpp"
#include <stdio.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace CoreML;
void CoreMLConverter::convertCaffeInputLayers(CoreMLConverter::ConvertLayerParameters layerParameters) {
int layerId = *layerParameters.layerId;
const caffe::LayerParameter& caffeLayer = layerParameters.prototxt.layer(layerId);
std::map<std::string, std::vector<int64_t> >& mapBlobNameToDimensions = layerParameters.mapBlobNameToDimensions;
std::set<std::string>& caffeNetworkInputNames = layerParameters.caffeNetworkInputNames;
/*
Mapping from Caffe Input Layer dimensions to CoreML Specification input dimensions:
1-D (C) ----> (C)
2-D : (Batch/Seq,C) ----> (C) [last dimension retained]
>=3-D (...,C,H,W) ----> (C,H,W) [last 3 dimensions retained]
*/
if (caffeLayer.type() == "Input"){
if (caffeLayer.input_param().shape_size() == 0) {
std::stringstream ss;
ss << "Invalid caffe model: Input layer '" << caffeLayer.name() << "' does not specify the shape parameter." << std::endl;
throw std::runtime_error(ss.str());
}
const ::caffe::BlobShape& shape = caffeLayer.input_param().shape(0);
std::vector<int64_t> dims;
if (shape.dim_size() == 0) {
std::stringstream ss;
ss << "Invalid caffe model: Input layer '" << caffeLayer.name() << "' does not specify dimensions." << std::endl;
throw std::runtime_error(ss.str());
}
for (const auto& dim: shape.dim()) {
assert(dim >= 0);
dims.push_back(dim);
}
if (dims.size() == 2) {
std::cout<<"Ignoring batch/seq size and retaining only the last dimension for conversion. " << std::endl;
dims.erase(dims.begin(),dims.end()-1);
}
if (dims.size() > 3) {
std::cout<<"Ignoring batch size and retaining only the trailing 3 dimensions for conversion. " << std::endl;
dims.erase(dims.begin(),dims.end()-3);
}
if (caffeLayer.top_size() == 0) {
CoreMLConverter::errorInCaffeProto("Caffe layer does not have a top blob ",caffeLayer.name(),caffeLayer.type());
}
mapBlobNameToDimensions[caffeLayer.top(0)] = dims;
caffeNetworkInputNames.insert(caffeLayer.top(0));
} else {
std::cout<<"WARNING: Skipping Data Layer '"<< caffeLayer.name() << "' of type '" << caffeLayer.type() <<"'. It is recommended to use Input layer for deployment."
<<std::endl;
}
}
| 39.285714 | 169 | 0.614182 | LeeCenY |
d297aeafc8dcbdcc08449980c5e500b23432f323 | 5,171 | cpp | C++ | platform/mbedtls/network.cpp | jflynn129/aws-iot-device-sdk-mbed-c | 3248e6ea5467aaa2fc5f66ee6baca9f50095daa8 | [
"Apache-2.0"
] | null | null | null | platform/mbedtls/network.cpp | jflynn129/aws-iot-device-sdk-mbed-c | 3248e6ea5467aaa2fc5f66ee6baca9f50095daa8 | [
"Apache-2.0"
] | null | null | null | platform/mbedtls/network.cpp | jflynn129/aws-iot-device-sdk-mbed-c | 3248e6ea5467aaa2fc5f66ee6baca9f50095daa8 | [
"Apache-2.0"
] | null | null | null | /*
* TCP/IP or UDP/IP networking functions
*
* This version of net_sockets.c is setup to use ARM easy-connect for network connectivity
*
*
* 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 "mbed.h"
#include "easy-connect.h"
#define MBEDTLS_FS_IO 1
#include <stdbool.h>
#include <string.h>
#include <timer_platform.h>
#include <network_interface.h>
#include "mbedtls/platform.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/pk.h"
#if DEBUG_LEVEL > 0
#include "mbedtls/debug.h"
#endif
#include "aws_iot_error.h"
#include "aws_iot_log.h"
#include "network_interface.h"
#include "network_platform.h"
#include "awscerts.h"
NetworkInterface *network = NULL;
TCPSocket mbedtls_socket;
bool network_connected = false;
/*
* Initialize a context
*/
void mbedtls_aws_init( mbedtls_net_context *ctx )
{
FUNC_ENTRY;
if( network != NULL )
network->disconnect(); //disconnect from the current network
network_connected = false;
network = easy_connect(true);
if (!network) {
IOT_DEBUG("Network Connection Failed!");
return;
}
IOT_DEBUG("Modem SW Revision: %s", FIRMWARE_REV(network));
network_connected = true;
ctx->fd = 1;
}
/*
* Initiate a TCP connection with host:port and the given protocol
* return 0 if success, otherwise error is returned
*/
int mbedtls_aws_connect( mbedtls_net_context *ctx, const char *host, uint16_t port, int proto )
{
FUNC_ENTRY;
if( !network_connected ) {
IOT_DEBUG("No network connection");
FUNC_EXIT_RC(NETWORK_ERR_NET_CONNECT_FAILED);
}
int ret = mbedtls_socket.open(network) || mbedtls_socket.connect(host,port);
if( ret != 0 ){
IOT_DEBUG("Socket Open Failed - %d",ret);
}
FUNC_EXIT_RC(ret);
}
/*
* Create a listening socket on bind_ip:port
*/
int mbedtls_aws_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto )
{
FUNC_EXIT_RC(MBEDTLS_ERR_NET_BIND_FAILED);
}
/*
* Accept a connection from a remote client
*/
int mbedtls_aws_accept( mbedtls_net_context *bind_ctx,
mbedtls_net_context *client_ctx,
void *client_ip, size_t buf_size, size_t *ip_len )
{
FUNC_ENTRY;
FUNC_EXIT_RC(MBEDTLS_ERR_NET_ACCEPT_FAILED );
}
/*
* Set the socket blocking or non-blocking
*/
int mbedtls_aws_set_block( mbedtls_net_context *ctx )
{
mbedtls_socket.set_blocking(true);
return 0;
}
int mbedtls_aws_set_nonblock( mbedtls_net_context *ctx )
{
mbedtls_socket.set_blocking(false);
return 0;
}
/*
* Portable usleep helper
*/
void mbedtls_aws_usleep( unsigned long usec )
{
FUNC_ENTRY;
Timer t;
t.start();
while( t.read_us() < (int)usec )
/* wait here */ ;
}
/*
* Read at most 'len' characters
*/
int mbedtls_aws_recv( void *ctx, unsigned char *buf, size_t len )
{
int ret;
int fd = ((mbedtls_net_context *) ctx)->fd;
FUNC_ENTRY;
if( fd < 0 )
FUNC_EXIT_RC(MBEDTLS_ERR_NET_INVALID_CONTEXT );
ret = (int) mbedtls_socket.recv( buf, len );
if( ret == NSAPI_ERROR_WOULD_BLOCK )
ret = MBEDTLS_ERR_SSL_WANT_READ;
FUNC_EXIT_RC(ret );
}
/*
* Read at most 'len' characters, blocking for at most 'timeout' ms
*/
int mbedtls_aws_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout )
{
int ret, ttime;
Timer t;
FUNC_ENTRY;
t.start();
do {
ret = mbedtls_aws_recv( ctx, buf, len );
ttime = t.read_ms();
}
while( ttime < (int)timeout && ret < 0 );
if( ret < 0 && ttime >= (int)timeout )
ret = MBEDTLS_ERR_SSL_TIMEOUT;
FUNC_EXIT_RC(ret);
}
/*
* Write at most 'len' characters
*/
int mbedtls_aws_send( void *ctx, const unsigned char *buf, size_t len )
{
int ret = NSAPI_ERROR_WOULD_BLOCK;
Timer t;
int fd = ((mbedtls_net_context *) ctx)->fd;
FUNC_ENTRY;
if( fd < 0 )
FUNC_EXIT_RC(NETWORK_PHYSICAL_LAYER_DISCONNECTED);
t.start();
while( ret == NSAPI_ERROR_WOULD_BLOCK && t.read_ms() < 100)
ret = mbedtls_socket.send(buf, len);
if( ret < 0 )
ret = MBEDTLS_ERR_NET_SEND_FAILED;
FUNC_EXIT_RC( ret );
}
/*
* Gracefully close the connection
*/
void mbedtls_aws_free( mbedtls_net_context *ctx )
{
FUNC_ENTRY;
if( !network_connected || ctx->fd < 0 ) {
FUNC_EXIT;
}
mbedtls_socket.close();
network->disconnect(); //disconnect from the current network
ctx->fd = -1;
FUNC_EXIT;
}
| 23.188341 | 98 | 0.662928 | jflynn129 |
d29bcda9f89d1f84ac4bc7f8f76e4f01426c6665 | 7,045 | hpp | C++ | OREData/ored/model/crossassetmodelbuilder.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | OREData/ored/model/crossassetmodelbuilder.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | OREData/ored/model/crossassetmodelbuilder.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file ored/model/crossassetmodelbuilder.hpp
\brief Build a cross asset model
\ingroup models
*/
#pragma once
#include <vector>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/types.hpp>
#include <qle/models/crossassetmodel.hpp>
#include <qle/models/infdkparametrization.hpp>
#include <qle/models/infjyparameterization.hpp>
#include <ored/marketdata/market.hpp>
#include <ored/model/crossassetmodeldata.hpp>
#include <ored/model/inflation/infdkdata.hpp>
#include <ored/model/inflation/infjydata.hpp>
#include <ored/model/inflation/infjybuilder.hpp>
#include <ored/model/marketobserver.hpp>
#include <ored/model/modelbuilder.hpp>
#include <ored/utilities/xmlutils.hpp>
namespace ore {
namespace data {
using namespace QuantLib;
//! Cross Asset Model Builder
/*!
CrossAssetModelBuilder takes a market snapshot, market conventions (the latter two
passed to the constructor), and a model configuarion (passed to
the "build" member function) to build and calibrate a cross asset model.
\ingroup models
*/
class CrossAssetModelBuilder : public ModelBuilder {
public:
/*! The market for the calibration can possibly be different from the final market
defining the curves attached to the marginal LGM models; for example domestic OIS
curves may be used for the in currency swaption calibration while the global model
is operated under FX basis consistent discounting curves relative to the collateral
OIS curve. */
CrossAssetModelBuilder( //! Market object
const boost::shared_ptr<Market>& market,
//! cam configuration
const boost::shared_ptr<CrossAssetModelData>& config,
//! Market configuration for interest rate model calibration
const std::string& configurationLgmCalibration = Market::defaultConfiguration,
//! Market configuration for FX model calibration
const std::string& configurationFxCalibration = Market::defaultConfiguration,
//! Market configuration for EQ model calibration
const std::string& configurationEqCalibration = Market::defaultConfiguration,
//! Market configuration for INF model calibration
const std::string& configurationInfCalibration = Market::defaultConfiguration,
//! Market configuration for CR model calibration
const std::string& configurationCrCalibration = Market::defaultConfiguration,
//! Market configuration for simulation
const std::string& configurationFinalModel = Market::defaultConfiguration,
//! Daycounter for date/time conversions
const DayCounter& dayCounter = ActualActual(),
//! calibrate the model?
const bool dontCalibrate = false,
//! continue if bootstrap error exceeds tolerance
const bool continueOnError = false,
//! reference calibration grid
const std::string& referenceCalibrationGrid_ = "");
//! Default destructor
~CrossAssetModelBuilder() {}
//! return the model
Handle<QuantExt::CrossAssetModel> model() const;
//! \name Inspectors
//@{
const std::vector<Real>& swaptionCalibrationErrors();
const std::vector<Real>& fxOptionCalibrationErrors();
const std::vector<Real>& eqOptionCalibrationErrors();
const std::vector<Real>& inflationCalibrationErrors();
//@}
//! \name ModelBuilder interface
//@{
void forceRecalculate() override;
bool requiresRecalibration() const override;
//@}
private:
void performCalculations() const override;
void buildModel() const;
void registerWithSubBuilders();
void unregisterWithSubBuilders();
mutable std::vector<std::vector<boost::shared_ptr<BlackCalibrationHelper>>> swaptionBaskets_;
mutable std::vector<std::vector<boost::shared_ptr<BlackCalibrationHelper>>> fxOptionBaskets_;
mutable std::vector<std::vector<boost::shared_ptr<BlackCalibrationHelper>>> eqOptionBaskets_;
mutable std::vector<Array> optionExpiries_;
mutable std::vector<Array> swaptionMaturities_;
mutable std::vector<Array> fxOptionExpiries_;
mutable std::vector<Array> eqOptionExpiries_;
mutable std::vector<Real> swaptionCalibrationErrors_;
mutable std::vector<Real> fxOptionCalibrationErrors_;
mutable std::vector<Real> eqOptionCalibrationErrors_;
mutable std::vector<Real> inflationCalibrationErrors_;
//! Store model builders for each asset under each asset type.
mutable std::map<QuantExt::CrossAssetModelTypes::AssetType,
std::map<QuantLib::Size, boost::shared_ptr<ModelBuilder>>> subBuilders_;
const boost::shared_ptr<ore::data::Market> market_;
const boost::shared_ptr<CrossAssetModelData> config_;
const std::string configurationLgmCalibration_, configurationFxCalibration_, configurationEqCalibration_,
configurationInfCalibration_, configurationCrCalibration_, configurationFinalModel_;
const DayCounter dayCounter_;
const bool dontCalibrate_;
const bool continueOnError_;
const std::string referenceCalibrationGrid_;
// TODO: Move CalibrationErrorType, optimizer and end criteria parameters to data
boost::shared_ptr<OptimizationMethod> optimizationMethod_;
EndCriteria endCriteria_;
// helper flag to prcess forceRecalculate()
bool forceCalibration_ = false;
// market observer
boost::shared_ptr<MarketObserver> marketObserver_;
// resulting model
mutable RelinkableHandle<QuantExt::CrossAssetModel> model_;
// Calibrate DK inflation model
void calibrateInflation(const InfDkData& data,
QuantLib::Size modelIdx,
const std::vector<boost::shared_ptr<QuantLib::BlackCalibrationHelper>>& calibrationBasket,
const boost::shared_ptr<QuantExt::InfDkParametrization>& inflationParam) const;
// Calibrate JY inflation model
void calibrateInflation(const InfJyData& data,
QuantLib::Size modelIdx,
const boost::shared_ptr<InfJyBuilder>& jyBuilder,
const boost::shared_ptr<QuantExt::InfJyParameterization>& inflationParam) const;
// Attach JY engines to helpers for JY calibration
void setJyPricingEngine(QuantLib::Size modelIdx,
const std::vector<boost::shared_ptr<QuantLib::CalibrationHelper>>& calibrationBasket) const;
};
} // namespace data
} // namespace ore
| 41.19883 | 109 | 0.746771 | mrslezak |
d29f5e0ba91821cf5241b47ddb346d3a89d8fe18 | 477 | cpp | C++ | src/RE/Scaleform/GAtomic/GAtomic.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | 1 | 2021-08-30T20:33:43.000Z | 2021-08-30T20:33:43.000Z | src/RE/Scaleform/GAtomic/GAtomic.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | null | null | null | src/RE/Scaleform/GAtomic/GAtomic.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | 1 | 2020-10-08T02:48:33.000Z | 2020-10-08T02:48:33.000Z | #include "RE/Scaleform/GAtomic/GAtomic.h"
namespace RE
{
GLock::Locker::Locker(GLock* a_lock)
{
lock = a_lock;
lock->Lock();
}
GLock::Locker::~Locker()
{
lock->Unlock();
}
GLock::GLock(std::uint32_t a_spinCount)
{
::InitializeCriticalSectionAndSpinCount(&cs, a_spinCount);
}
GLock::~GLock()
{
::DeleteCriticalSection(&cs);
}
void GLock::Lock()
{
::EnterCriticalSection(&cs);
}
void GLock::Unlock()
{
::LeaveCriticalSection(&cs);
}
}
| 11.357143 | 60 | 0.637317 | thallada |
d2a1120223d31252ef287252028181cb58f0bdf7 | 533 | cc | C++ | CMC040/smg/lbr_get_record.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | 1 | 2018-10-17T08:53:17.000Z | 2018-10-17T08:53:17.000Z | CMC040/smg/lbr_get_record.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | null | null | null | CMC040/smg/lbr_get_record.cc | khandy21yo/aplus | 3b4024a2a8315f5dcc78479a24100efa3c4a6504 | [
"MIT"
] | null | null | null | //! \file
//! \brief Get Record
//!
#include <string>
#include "smg/lbr.h"
//!
//! \brief Get Record
//!
long lbr$get_record(
lbr_index_cdd &lr_index,
std::string &text)
{
//
// Nothing left
//
if (lr_index.datum.size() == 0)
{
text = "";
return 0;
}
//
// Pull off one line of text
//
int pos = lr_index.datum.find('\n');
if (pos == std::string::npos)
{
text = lr_index.datum;
lr_index.datum.empty();
}
else
{
text = lr_index.datum.substr(0, pos);
lr_index.datum.erase(0, pos + 1);
}
return 1;
}
| 12.690476 | 39 | 0.581614 | khandy21yo |
d2a1b5b1ccfe60bad3f46411a75cd9c3392d1189 | 6,731 | cpp | C++ | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/settings/global/UIGlobalSettingsUpdate.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/settings/global/UIGlobalSettingsUpdate.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/settings/global/UIGlobalSettingsUpdate.cpp | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /* $Id: UIGlobalSettingsUpdate.cpp $ */
/** @file
* VBox Qt GUI - UIGlobalSettingsUpdate class implementation.
*/
/*
* Copyright (C) 2006-2013 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else /* !VBOX_WITH_PRECOMPILED_HEADERS */
/* GUI includes: */
# include "UIGlobalSettingsUpdate.h"
# include "UIExtraDataManager.h"
# include "VBoxGlobal.h"
#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */
UIGlobalSettingsUpdate::UIGlobalSettingsUpdate()
: m_pLastChosenRadio(0)
, m_fChanged(false)
{
/* Apply UI decorations: */
Ui::UIGlobalSettingsUpdate::setupUi(this);
/* Setup connections: */
connect(m_pCheckBoxUpdate, SIGNAL(toggled(bool)), this, SLOT(sltUpdaterToggled(bool)));
connect(m_pComboBoxUpdatePeriod, SIGNAL(activated(int)), this, SLOT(sltPeriodActivated()));
connect(m_pRadioUpdateFilterStable, SIGNAL(toggled(bool)), this, SLOT(sltBranchToggled()));
connect(m_pRadioUpdateFilterEvery, SIGNAL(toggled(bool)), this, SLOT(sltBranchToggled()));
connect(m_pRadioUpdateFilterBetas, SIGNAL(toggled(bool)), this, SLOT(sltBranchToggled()));
/* Apply language settings: */
retranslateUi();
}
/* Load data to cache from corresponding external object(s),
* this task COULD be performed in other than GUI thread: */
void UIGlobalSettingsUpdate::loadToCacheFrom(QVariant &data)
{
/* Fetch data to properties & settings: */
UISettingsPageGlobal::fetchData(data);
/* Fill internal variables with corresponding values: */
VBoxUpdateData updateData(gEDataManager->applicationUpdateData());
m_cache.m_fCheckEnabled = !updateData.isNoNeedToCheck();
m_cache.m_periodIndex = updateData.periodIndex();
m_cache.m_branchIndex = updateData.branchIndex();
m_cache.m_strDate = updateData.date();
/* Upload properties & settings to data: */
UISettingsPageGlobal::uploadData(data);
}
/* Load data to corresponding widgets from cache,
* this task SHOULD be performed in GUI thread only: */
void UIGlobalSettingsUpdate::getFromCache()
{
/* Apply internal variables data to QWidget(s): */
m_pCheckBoxUpdate->setChecked(m_cache.m_fCheckEnabled);
if (m_pCheckBoxUpdate->isChecked())
{
m_pComboBoxUpdatePeriod->setCurrentIndex(m_cache.m_periodIndex);
if (m_cache.m_branchIndex == VBoxUpdateData::BranchWithBetas)
m_pRadioUpdateFilterBetas->setChecked(true);
else if (m_cache.m_branchIndex == VBoxUpdateData::BranchAllRelease)
m_pRadioUpdateFilterEvery->setChecked(true);
else
m_pRadioUpdateFilterStable->setChecked(true);
}
m_pUpdateDateText->setText(m_cache.m_strDate);
sltUpdaterToggled(m_cache.m_fCheckEnabled);
/* Mark page as *not changed*: */
m_fChanged = false;
}
/* Save data from corresponding widgets to cache,
* this task SHOULD be performed in GUI thread only: */
void UIGlobalSettingsUpdate::putToCache()
{
/* Gather internal variables data from QWidget(s): */
m_cache.m_periodIndex = periodType();
m_cache.m_branchIndex = branchType();
}
/* Save data from cache to corresponding external object(s),
* this task COULD be performed in other than GUI thread: */
void UIGlobalSettingsUpdate::saveFromCacheTo(QVariant &data)
{
/* Test settings altering flag: */
if (!m_fChanged)
return;
/* Fetch data to properties & settings: */
UISettingsPageGlobal::fetchData(data);
/* Gather corresponding values from internal variables: */
VBoxUpdateData newData(m_cache.m_periodIndex, m_cache.m_branchIndex);
gEDataManager->setApplicationUpdateData(newData.data());
/* Upload properties & settings to data: */
UISettingsPageGlobal::uploadData(data);
}
void UIGlobalSettingsUpdate::setOrderAfter(QWidget *pWidget)
{
/* Configure navigation: */
setTabOrder(pWidget, m_pCheckBoxUpdate);
setTabOrder(m_pCheckBoxUpdate, m_pComboBoxUpdatePeriod);
setTabOrder(m_pComboBoxUpdatePeriod, m_pRadioUpdateFilterStable);
setTabOrder(m_pRadioUpdateFilterStable, m_pRadioUpdateFilterEvery);
setTabOrder(m_pRadioUpdateFilterEvery, m_pRadioUpdateFilterBetas);
}
void UIGlobalSettingsUpdate::retranslateUi()
{
/* Translate uic generated strings: */
Ui::UIGlobalSettingsUpdate::retranslateUi(this);
/* Retranslate m_pComboBoxUpdatePeriod combobox: */
int iCurrenIndex = m_pComboBoxUpdatePeriod->currentIndex();
m_pComboBoxUpdatePeriod->clear();
VBoxUpdateData::populate();
m_pComboBoxUpdatePeriod->insertItems(0, VBoxUpdateData::list());
m_pComboBoxUpdatePeriod->setCurrentIndex(iCurrenIndex == -1 ? 0 : iCurrenIndex);
}
void UIGlobalSettingsUpdate::sltUpdaterToggled(bool fEnabled)
{
/* Update activity status: */
m_pContainerUpdate->setEnabled(fEnabled);
/* Update time of next check: */
sltPeriodActivated();
/* Temporary remember branch type if was switched off: */
if (!fEnabled)
{
m_pLastChosenRadio = m_pRadioUpdateFilterBetas->isChecked() ? m_pRadioUpdateFilterBetas :
m_pRadioUpdateFilterEvery->isChecked() ? m_pRadioUpdateFilterEvery : m_pRadioUpdateFilterStable;
}
/* Check/uncheck last selected radio depending on activity status: */
if (m_pLastChosenRadio)
m_pLastChosenRadio->setChecked(fEnabled);
}
void UIGlobalSettingsUpdate::sltPeriodActivated()
{
VBoxUpdateData data(periodType(), branchType());
m_pUpdateDateText->setText(data.date());
m_fChanged = true;
}
void UIGlobalSettingsUpdate::sltBranchToggled()
{
m_fChanged = true;
}
VBoxUpdateData::PeriodType UIGlobalSettingsUpdate::periodType() const
{
VBoxUpdateData::PeriodType result = m_pCheckBoxUpdate->isChecked() ?
(VBoxUpdateData::PeriodType)m_pComboBoxUpdatePeriod->currentIndex() : VBoxUpdateData::PeriodNever;
return result == VBoxUpdateData::PeriodUndefined ? VBoxUpdateData::Period1Day : result;
}
VBoxUpdateData::BranchType UIGlobalSettingsUpdate::branchType() const
{
if (m_pRadioUpdateFilterBetas->isChecked())
return VBoxUpdateData::BranchWithBetas;
else if (m_pRadioUpdateFilterEvery->isChecked())
return VBoxUpdateData::BranchAllRelease;
else
return VBoxUpdateData::BranchStable;
}
| 35.613757 | 125 | 0.735998 | egraba |
d2ac5ac9554243a34846ab68ca6b0c391af09960 | 7,821 | cc | C++ | src/blackbox_optimizer.cc | Coloquinte/minipart2 | 00b864bd21fab4909984aa6f5c07cae61d2c2c0a | [
"MIT"
] | 1 | 2020-06-14T16:51:26.000Z | 2020-06-14T16:51:26.000Z | src/blackbox_optimizer.cc | Coloquinte/minipart2 | 00b864bd21fab4909984aa6f5c07cae61d2c2c0a | [
"MIT"
] | null | null | null | src/blackbox_optimizer.cc | Coloquinte/minipart2 | 00b864bd21fab4909984aa6f5c07cae61d2c2c0a | [
"MIT"
] | null | null | null | // Copyright (C) 2019 Gabriel Gouvine - All Rights Reserved
#include "blackbox_optimizer.hh"
#include "objective.hh"
#include "incremental_objective.hh"
#include "partitioning_params.hh"
#include "local_search_optimizer.hh"
#include <iostream>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#include <limits>
using namespace std;
namespace minipart {
BlackboxOptimizer::BlackboxOptimizer(const Hypergraph &hypergraph, const PartitioningParams ¶ms, const Objective &objective, mt19937 &rgen, vector<Solution> &solutions, Index level)
: hypergraph_(hypergraph)
, params_(params)
, objective_(objective)
, rgen_(rgen)
, solutions_(solutions)
, level_(level) {
}
void BlackboxOptimizer::runInitialPlacement() {
while ((Index) solutions_.size() < params_.nSolutions) {
uniform_int_distribution<int> partDist(0, hypergraph_.nParts()-1);
Solution solution(hypergraph_.nNodes(), hypergraph_.nParts());
for (Index i = 0; i < hypergraph_.nNodes(); ++i) {
solution[i] = partDist(rgen_);
}
solutions_.push_back(solution);
}
}
void BlackboxOptimizer::report(const string &step) const {
report(step, solutions_.size());
}
void BlackboxOptimizer::report(const string &step, Index nSols) const {
if (params_.verbosity >= 3) {
for (int i = 0; i < level_; ++i) cout << " ";
cout << step << ": ";
cout << hypergraph_.nNodes() << " nodes, ";
cout << hypergraph_.nHedges() << " edges, ";
cout << hypergraph_.nPins() << " pins ";
cout << "on " << nSols << " solutions";
cout << endl;
}
}
void BlackboxOptimizer::reportStartCycle() const {
if (params_.verbosity >= 2) {
cout << "Starting V-cycle #" << cycle_ + 1 << endl;
}
}
void BlackboxOptimizer::reportEndCycle() const {
if (params_.verbosity >= 2) {
Solution solution = bestSolution();
vector<int64_t> obj = objective_.eval(hypergraph_, solution);
cout << "Objectives: ";
for (size_t i = 0; i < obj.size(); ++i) {
if (i > 0) cout << ", ";
cout << obj[i];
}
cout << endl;
}
}
void BlackboxOptimizer::reportStartSearch() const {
}
void BlackboxOptimizer::reportEndSearch() const {
if (params_.verbosity >= 2) {
cout << endl;
}
}
Solution BlackboxOptimizer::run(const Hypergraph &hypergraph, const PartitioningParams ¶ms, const Objective &objective, const vector<Solution> &solutions) {
mt19937 rgen(params.seed);
// Copy because modified in-place
vector<Solution> sols = solutions;
BlackboxOptimizer opt(hypergraph, params, objective, rgen, sols, 0);
return opt.run();
}
Solution BlackboxOptimizer::run() {
reportStartSearch();
runInitialPlacement();
runLocalSearch();
for (cycle_ = 0; cycle_ < params_.nCycles; ++cycle_) {
reportStartCycle();
runVCycle();
reportEndCycle();
}
reportEndSearch();
return bestSolution();
}
Solution BlackboxOptimizer::bestSolution() const {
assert (!solutions_.empty());
size_t best = 0;
for (size_t i = 1; i < solutions_.size(); ++i) {
if (objective_.eval(hypergraph_, solutions_[i]) < objective_.eval(hypergraph_, solutions_[best])) {
best = i;
}
}
return solutions_[best];
}
namespace {
class SolutionHasher {
public:
SolutionHasher(const vector<Solution> &solutions)
: solutions_(solutions) {}
uint64_t operator()(const Index &node) const {
// FNV hash
uint64_t magic = 1099511628211llu;
uint64_t ret = 0;
for (const Solution &solution : solutions_) {
ret = (ret ^ (uint64_t)solution[node]) * magic;
}
return ret;
}
private:
const vector<Solution> &solutions_;
};
class SolutionComparer {
public:
SolutionComparer(const vector<Solution> &solutions)
: solutions_(solutions) {}
bool operator()(const Index &n1, const Index &n2) const {
for (const Solution &solution : solutions_) {
if (solution[n1] != solution[n2]) return false;
}
return true;
}
private:
const vector<Solution> &solutions_;
};
} // End anonymous namespace
Solution BlackboxOptimizer::computeCoarsening(const vector<Solution> &solutions) {
assert (solutions.size() >= 1);
Index nNodes = solutions.front().nNodes();
unordered_map<Index, Index, SolutionHasher, SolutionComparer> coarseningMap(nNodes, SolutionHasher(solutions), SolutionComparer(solutions));
coarseningMap.reserve(nNodes);
Index nCoarsenedNodes = 0;
vector<Index> coarsening(nNodes);
for (Index node = 0; node < nNodes; ++node) {
auto p = coarseningMap.emplace(node, nCoarsenedNodes);
if (p.second) {
coarsening[node] = nCoarsenedNodes++;
}
else {
coarsening[node] = p.first->second;
}
}
return Solution(coarsening);
}
namespace {
class CoarseningComparer {
public:
CoarseningComparer(const PartitioningParams ¶ms)
: params_(params) {
}
bool operator()(const Solution &c1, const Solution &c2) const {
assert (c1.nNodes() == c2.nNodes());
Index nNodes = c1.nNodes();
double fac1 = nNodes / (double) c1.nParts();
double fac2 = nNodes / (double) c2.nParts();
if (fac1 < params_.minCoarseningFactor || fac2 < params_.minCoarseningFactor)
return fac1 > fac2;
if (fac1 > params_.maxCoarseningFactor || fac2 < params_.maxCoarseningFactor)
return fac1 < fac2;
double tgt = 0.5 * (params_.maxCoarseningFactor + params_.minCoarseningFactor);
return abs(fac1 - tgt) < abs(fac2 - tgt);
}
private:
const PartitioningParams ¶ms_;
};
} // End anonymous namespace
void BlackboxOptimizer::runLocalSearch() {
report ("Local search");
for (Solution &solution : solutions_) {
unique_ptr<IncrementalObjective> inc = objective_.incremental(hypergraph_, solution);
LocalSearchOptimizer(*inc, params_, rgen_).run();
inc->checkConsistency();
}
}
void BlackboxOptimizer::runVCycle() {
checkConsistency();
if (hypergraph_.nNodes() < params_.minCoarseningNodes * hypergraph_.nParts()) return;
report ("V-cycle step");
// Pick the best number of solutions for the coarsening
// If the coarsening is still too large, stop the recursion
shuffle(solutions_.begin(), solutions_.end(), rgen_);
vector<Solution> coarsenings;
for (size_t nSols = 1; nSols <= solutions_.size(); ++nSols) {
coarsenings.emplace_back(computeCoarsening(vector<Solution>(solutions_.begin(), solutions_.begin() + nSols)));
}
size_t coarseningIndex = min_element(coarsenings.begin(), coarsenings.end(), CoarseningComparer(params_)) - coarsenings.begin();
Solution coarsening = coarsenings[coarseningIndex];
if (coarsening.nNodes() / (double) coarsening.nParts() < params_.minCoarseningFactor) return;
Hypergraph cHypergraph = hypergraph_.coarsen(coarsening);
vector<Solution> cSolutions;
for (size_t i = 0; i <= coarseningIndex; ++i) {
cSolutions.emplace_back(solutions_[i].coarsen(coarsening));
}
BlackboxOptimizer nextLevel(cHypergraph, params_, objective_, rgen_, cSolutions, level_+1);
nextLevel.runLocalSearch();
nextLevel.runVCycle();
report("Refinement", coarseningIndex + 1);
for (size_t i = 0; i <= coarseningIndex; ++i) {
solutions_[i] = cSolutions[i].uncoarsen(coarsening);
unique_ptr<IncrementalObjective> inc = objective_.incremental(hypergraph_, solutions_[i]);
LocalSearchOptimizer(*inc, params_, rgen_).run();
inc->checkConsistency();
}
checkConsistency();
}
void BlackboxOptimizer::checkConsistency() const {
hypergraph_.checkConsistency();
for (const Solution &solution : solutions_) {
if (hypergraph_.nNodes() != solution.nNodes())
throw runtime_error("Hypergraph and solutions must have the same number of nodes");
if (hypergraph_.nParts() != solution.nParts())
throw runtime_error("Hypergraph and solutions must have the same number of partitions");
solution.checkConsistency();
}
}
} // End namespace minipart
| 30.313953 | 185 | 0.694029 | Coloquinte |
d2ac93cfaa8397466000b001333848a5d5232da5 | 4,245 | cpp | C++ | cpp/wrappers/ffmpeg-wrapper/H264Utils.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | cpp/wrappers/ffmpeg-wrapper/H264Utils.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | cpp/wrappers/ffmpeg-wrapper/H264Utils.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | #include "H264Utils.h"
#ifdef _WIN32
// win32 includes
#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <process.h>
#include <math.h>
enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
#endif
namespace FFmpegWrapper {
H264CheckNewFrame::H264CheckNewFrame() {
log2_max_frame_num = 0x0;
frame_num_mask = 0x0;
last_frame_delta = 0x0;
old_frame_num = 0;
first_frame_num_set = false;
newFrameOnNextIDR = false;
}
bool H264CheckNewFrame::isNewFrame(const uint8_t* input_nal, int input_size) {
// check for 00 00 00 01 seq
//bool validNAL = (input_size > 4) && array_index_of(input_nal, 0, input_size, h264_delimiter, 4) == 0;
bool validNAL = (input_size > 4) && array_index_of(input_nal, 0, 4, h264_delimiter, 4) == 0;
if (!validNAL) {
printf("isThisNALANewFrame - Not valid NAL.\n");
return false;
}
uint8_t nal_type = input_nal[4] & 0x1f;
if (nal_type == h264_NAL_TYPE_SPS) {
nal2RBSP(&input_nal[4], input_size - 4, &rbsp, 26);
uint8_t* sps_raw = &rbsp[0];
int sps_size = rbsp.size();
// sps_raw[1]; // profile_idc
// sps_raw[2]; // constraints
// sps_raw[3]; // level_idc
uint32_t bit_index = 8 + 24;//NAL bit + profile_idc (8bits) + constraints (8bits) + level_idc (8bits)
bit_index += bitsToSkip_ue(bit_index, sps_raw, sps_size);//seq_parameter_set_id (ue)
uint32_t log2_max_frame_num_minus4 = read_golomb_ue(bit_index, sps_raw, sps_size);
ARIBEIRO_ABORT(
(log2_max_frame_num_minus4 < 0 ||
log2_max_frame_num_minus4 > 12),
"parseSPS_log2_max_frame_num_minus4 value not in range [0-12] \n");
log2_max_frame_num = log2_max_frame_num_minus4 + 4;
frame_num_mask = ((1 << log2_max_frame_num) - 1);
}
if (nal_type == (h264_NAL_TYPE_SPS) ||
nal_type == (h264_NAL_TYPE_PPS) ||
nal_type == (h264_NAL_TYPE_AUD) ||
nal_type == (h264_NAL_TYPE_SEI) ||
(nal_type >= 14 && nal_type <= 18)) {
newFrameOnNextIDR = true;
}
else if (log2_max_frame_num != 0x0 &&
(nal_type == h264_NAL_TYPE_CSIDRP || nal_type == h264_NAL_TYPE_CSNIDRP)) {
rbsp.clear();
//(8 + 3*(32*2+1) + 16) = max header per NALU slice bits = 27.375 bytes
// 32 bytes + 8 (Possibility of Emulation in 32 bytes)
int RBSPMaxBytes = 32 + 8;
if ((input_size - 4) < (32 + 8))
RBSPMaxBytes = input_size - 4;
nal2RBSP(&input_nal[4], input_size - 4, &rbsp, RBSPMaxBytes);
uint8_t * idr_raw = &rbsp[0];
uint32_t idr_size = rbsp.size();
uint32_t frame_num_index = 8;//start counting after the nal_bit
frame_num_index += bitsToSkip_ue(frame_num_index, idr_raw, idr_size);//first_mb_in_slice (ue)
frame_num_index += bitsToSkip_ue(frame_num_index, idr_raw, idr_size);//slice_type (ue)
frame_num_index += bitsToSkip_ue(frame_num_index, idr_raw, idr_size);//pic_parameter_set_id (ue)
//now can read frame_num
uint32_t frame_num = readbits(frame_num_index, log2_max_frame_num, idr_raw, idr_size);
if (!first_frame_num_set) {
//first frame_num...
first_frame_num_set = true;
old_frame_num = frame_num;
}
if (old_frame_num != frame_num) {
newFrameOnNextIDR = true;
//frame_num will be in the range [0, ( 1 << spsinfo.log2_max_frame_num )[
last_frame_delta = (frame_num - old_frame_num) & frame_num_mask;
old_frame_num = frame_num;
}
}
if (newFrameOnNextIDR &&
(nal_type == h264_NAL_TYPE_CSIDRP || nal_type == h264_NAL_TYPE_CSNIDRP)) {
newFrameOnNextIDR = false;
printf(" ++ new frame\n");
return true;
}
printf(" -- not new frame\n");
return false;
}
} | 33.690476 | 113 | 0.577385 | A-Ribeiro |
d2b1af3211a02523576f5d63fe617aea84a3a3fb | 1,786 | hpp | C++ | CfgLoadouts.hpp | TheeProTag/Atropia_Free | 0988c6addaf7cd2334e0d8d553d61ed50dd6faa5 | [
"Unlicense"
] | null | null | null | CfgLoadouts.hpp | TheeProTag/Atropia_Free | 0988c6addaf7cd2334e0d8d553d61ed50dd6faa5 | [
"Unlicense"
] | null | null | null | CfgLoadouts.hpp | TheeProTag/Atropia_Free | 0988c6addaf7cd2334e0d8d553d61ed50dd6faa5 | [
"Unlicense"
] | null | null | null | class CfgLoadouts {
//Use POTATO to run gear assignment
usePotato = 1;
//Fast, Easy Settings to change loadouts without touching the arrays. For TVT Balancing.
//Allow Zoomed Optics (1 is true, 0 is false) <Anything like a HAMR (4x) optic won't be added, "red dot" would be fine>
allowMagnifiedOptics = 0;
//Do Vehicle Loadouts
//(1 will run normaly, 0 will leave them to vanilla defaults, -1 will clear and leave empty)
setVehicleLoadouts = -1;
//Fallback: use a basic soldiers loadout when the unit's classname isn't found (for Alive spawning random units)
useFallback = 1;
//Shared items
#include "Loadouts\common.hpp" // DO NOT COMMENT OUT, WILL BREAK EVERYTHING
//Only include one hpp per faction; use (//) to comment out other files
//BLUFOR FACTION (blu_f):
#include "Loadouts\blu_us_m4_ucp.hpp" // US: M4 - Gray/Green
// #include "Loadouts\blu_us_m4_ocp.hpp" // US: M4 - Tan
// #include "Loadouts\blu_brit_l85_mtp.hpp" // British: L86 - Multi-Terrain Pattern
// #include "Loadouts\blu_ger_g36_fleck.hpp" // German: G36 - Flecktarn Camo
//INDFOR FACTION (ind_f):
#include "Loadouts\ind_ukr_ak74_ttsko.hpp" // Ukraine: AK74 - TTskO
// #include "Loadouts\ind_ukr_ak74_ddpm.hpp" // "Ukraine": AK74 - Desert DPM
// #include "Loadouts\ind_reb_ak47_desert.hpp" // Rebel: AK47 - Mixed Desert
// #include "Loadouts\ind_ger_g36_tropen.hpp" // German: G36 - Tropen Camo
//OPFOR FACTION (opf_f):
#include "Loadouts\opf_ru_ak74_floral.hpp" // Russian: AK74 - Floral
// #include "Loadouts\opf_reb_ak47_desert.hpp" // Rebel: AK47 - Mixed Desert
//Civilians (mainly for RP missions)
#include "Loadouts\civilians.hpp" //Bare example of doing civilian loadouts
};
| 44.65 | 121 | 0.68869 | TheeProTag |
d2b2eb6cf3915ec8d95adbc664266f87372bc5c2 | 367 | cpp | C++ | docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/atl-mfc-shared/codesnippet/CPP/cstringt-class_39.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | // typedef CStringT<TCHAR, StrTraitATL<TCHAR, ChTraitsCRT<TCHAR>>> CAtlString;
CAtlString str(_T("%First Second#Third"));
CAtlString resToken;
int curPos = 0;
resToken= str.Tokenize(_T("% #"),curPos);
while (resToken != _T(""))
{
_tprintf_s(_T("Resulting token: %s\n"), resToken);
resToken = str.Tokenize(_T("% #"), curPos);
}; | 33.363636 | 81 | 0.615804 | bobbrow |
d2b61e4b76cb18e954f0173aade99523bd7bbcde | 320 | cpp | C++ | src/widgets/fonteditor.cpp | Eggbertx/QtSphere-IDE | 7ae7ed840fcef7a79fb47a6903afb95ca23838ca | [
"BSD-2-Clause"
] | 12 | 2017-05-04T16:58:07.000Z | 2021-06-09T03:08:29.000Z | src/widgets/fonteditor.cpp | Eggbertx/QtSphere-IDE | 7ae7ed840fcef7a79fb47a6903afb95ca23838ca | [
"BSD-2-Clause"
] | 1 | 2017-06-19T03:30:22.000Z | 2018-04-09T21:35:00.000Z | src/widgets/fonteditor.cpp | Eggbertx/QtSphere-IDE | 7ae7ed840fcef7a79fb47a6903afb95ca23838ca | [
"BSD-2-Clause"
] | 1 | 2018-09-04T00:27:54.000Z | 2018-09-04T00:27:54.000Z | #include "fonteditor.h"
#include "ui_fonteditor.h"
// This doesn't do anything yet, and with the direction
// I'm planning on taking QSI, it might be removed.
FontEditor::FontEditor(QWidget *parent): QWidget(parent), ui(new Ui::FontEditor) {
ui->setupUi(this);
}
FontEditor::~FontEditor() {
delete ui;
}
| 24.615385 | 83 | 0.69375 | Eggbertx |
d2b727146b89d8598c5841c874e13f5542cbb3cf | 2,387 | cpp | C++ | src/core/game/Asteroid.cpp | NoctisGames/insectoid-defense_opensource | 23c348d41072fc4b8a18578cd341cf58d8dd8cd7 | [
"MIT"
] | 2 | 2016-12-10T03:27:07.000Z | 2020-09-30T16:06:06.000Z | src/core/game/Asteroid.cpp | NoctisGames/insectoid-defense_opensource | 23c348d41072fc4b8a18578cd341cf58d8dd8cd7 | [
"MIT"
] | null | null | null | src/core/game/Asteroid.cpp | NoctisGames/insectoid-defense_opensource | 23c348d41072fc4b8a18578cd341cf58d8dd8cd7 | [
"MIT"
] | 2 | 2015-10-07T00:32:18.000Z | 2016-01-30T23:23:55.000Z | //
// Asteroid.cpp
// insectoid-defense
//
// Created by Stephen Gowen on 8/18/13.
// Copyright (c) 2014 Gowen Game Dev. All rights reserved.
//
#include "Asteroid.h"
#include "ScreenUtils.h"
#include "World.h"
#include "Vector2D.h"
#include "macros.h"
#include <ctime>
#include <stdlib.h>
#include <math.h>
Asteroid * Asteroid::generateRandomAsteroid()
{
srand((unsigned)time(0));
float size = ((float)(rand() % 101)) / 100.0f + ((float)(rand() % 101)) / 100.0f;
float speed = ((float)(rand() % 101)) / 100.0f + 0.5f;
float spinDegreesPerSecond = (rand() % 166) + 15.0f;
float x = -2;
float y = -2;
int random_integer = rand() % 3;
switch (random_integer)
{
case 0:
x = -2;
y = (rand() % (int) GAME_HEIGHT) - 3;
break;
case 1:
x = (rand() % (int) GAME_WIDTH) + 1;
y = (rand() % 2) == 0 ? GAME_HEIGHT + 2 : -2;
break;
case 2:
x = GAME_WIDTH + 2;
y = (rand() % (int) GAME_HEIGHT) - 2;
}
Vector2D asteroidPosition(x, y);
Vector2D destinationPosition((rand() % (int) GAME_WIDTH) + 1, (rand() % (int) GAME_HEIGHT) + 1);
float directionalAngle = destinationPosition.sub(asteroidPosition.getX(), asteroidPosition.getY()).angle();
int random_asteroid = (rand() % 2);
return new Asteroid(x, y, size, size, speed, directionalAngle, spinDegreesPerSecond, random_asteroid == 0 ? Asteroid_Type::GRAY : Asteroid_Type::BROWN);
}
Asteroid::Asteroid(float x, float y, float width, float height, float velocityConstant, float directionalAngle, float spinDegreesPerSecond, Asteroid_Type type) : PhysicalEntity (x, y, width, height, 0)
{
m_spinDegreesPerSecond = spinDegreesPerSecond;
float radians = DEGREES_TO_RADIANS(directionalAngle);
m_velocity->set(cosf(radians) * velocityConstant, sinf(radians) * velocityConstant);
m_hasEnteredWorld = false;
m_remove = false;
m_type = type;
}
void Asteroid::update(float &deltaTime)
{
m_fAngle += m_spinDegreesPerSecond * deltaTime;
m_position->add(m_velocity->getX() * deltaTime, m_velocity->getY() * deltaTime);
updateBounds();
if (m_hasEnteredWorld)
{
m_remove = ScreenUtils::isVectorOffScreen(*m_position);
}
else if (World::isVectorInWorld(*m_position))
{
m_hasEnteredWorld = true;
}
}
Asteroid_Type Asteroid::getAsteroidType()
{
return m_type;
}
bool Asteroid::remove()
{
return m_remove;
} | 25.945652 | 202 | 0.661081 | NoctisGames |
d2b7d290bdb806a18110e6c11e1380227f02f0a1 | 3,848 | cc | C++ | chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_apitest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_apitest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_apitest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 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/macros.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/autofill_assistant_private/autofill_assistant_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/extensions/api/autofill_assistant_private.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill_assistant/browser/mock_service.h"
#include "components/autofill_assistant/browser/service.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/test/test_utils.h"
#include "extensions/common/switches.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace extensions {
namespace {
using autofill_assistant::ActionsResponseProto;
using autofill_assistant::MockService;
using autofill_assistant::SupportedScriptProto;
using autofill_assistant::SupportsScriptResponseProto;
using autofill_assistant::TellProto;
using base::test::RunOnceCallback;
using testing::_;
using testing::NiceMock;
using testing::StrEq;
// TODO(crbug.com/1015753): We have to split some of these tests up due to the
// MockService being owned by the controller. If we were to run two tests that
// create a controller in the same browser test, the mock service is lost and a
// real ServiceImpl is used. This is an issue in the architecture of the
// controller and service and should be changed to avoid this issue.
class AutofillAssistantPrivateApiTest : public ExtensionApiTest {
public:
AutofillAssistantPrivateApiTest() = default;
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
auto service = std::make_unique<NiceMock<MockService>>();
mock_service_ = service.get();
AutofillAssistantPrivateAPI::GetFactoryInstance()
->Get(browser()->profile())
->SetService(std::move(service));
// Prepare the mock service to return two scripts when asked.
SupportsScriptResponseProto scripts_proto;
SupportedScriptProto* script = scripts_proto.add_scripts();
script->set_path("some/path");
script->mutable_presentation()->mutable_chip()->set_text("Action 0");
SupportedScriptProto* script1 = scripts_proto.add_scripts();
script1->set_path("some/path");
script1->mutable_presentation()->mutable_chip()->set_text("Action 1");
std::string scripts_output;
scripts_proto.SerializeToString(&scripts_output);
ON_CALL(*mock_service_, OnGetScriptsForUrl(_, _, _))
.WillByDefault(RunOnceCallback<2>(true, scripts_output));
// Always return a script with a single tell action.
ActionsResponseProto actions_proto;
TellProto* tell_action = actions_proto.add_actions()->mutable_tell();
tell_action->set_message("This is a test status.");
std::string actions_output;
actions_proto.SerializeToString(&actions_output);
ON_CALL(*mock_service_, OnGetActions(StrEq("some/path"), _, _, _, _, _))
.WillByDefault(RunOnceCallback<5>(true, actions_output));
// We never return more additional actions.
ON_CALL(*mock_service_, OnGetNextActions(_, _, _, _, _))
.WillByDefault(RunOnceCallback<4>(true, ""));
}
private:
std::unique_ptr<MockService> service_;
MockService* mock_service_;
DISALLOW_COPY_AND_ASSIGN(AutofillAssistantPrivateApiTest);
};
IN_PROC_BROWSER_TEST_F(AutofillAssistantPrivateApiTest, DefaultTest) {
ui_test_utils::NavigateToURL(browser(), GURL("chrome://version"));
EXPECT_TRUE(
RunComponentExtensionTestWithArg("autofill_assistant_private", "default"))
<< message_;
}
} // namespace
} // namespace extensions
| 39.670103 | 100 | 0.765073 | sarang-apps |
d2bce2f1c6dd0acd4bc2cf66c4f25fc0a73a37d4 | 3,042 | cpp | C++ | libsmtutil/Z3CHCInterface.cpp | step21/solidity | 2a0d701f709673162e8417d2f388b8171a34e892 | [
"MIT"
] | null | null | null | libsmtutil/Z3CHCInterface.cpp | step21/solidity | 2a0d701f709673162e8417d2f388b8171a34e892 | [
"MIT"
] | 1 | 2020-06-17T14:24:49.000Z | 2020-06-17T14:24:49.000Z | libsmtutil/Z3CHCInterface.cpp | step21/solidity | 2a0d701f709673162e8417d2f388b8171a34e892 | [
"MIT"
] | null | null | null | /*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libsmtutil/Z3CHCInterface.h>
#include <libsolutil/CommonIO.h>
using namespace std;
using namespace solidity;
using namespace solidity::smtutil;
Z3CHCInterface::Z3CHCInterface():
m_z3Interface(make_unique<Z3Interface>()),
m_context(m_z3Interface->context()),
m_solver(*m_context)
{
// These need to be set globally.
z3::set_param("rewriter.pull_cheap_ite", true);
z3::set_param("rlimit", Z3Interface::resourceLimit);
// Spacer options.
// These needs to be set in the solver.
// https://github.com/Z3Prover/z3/blob/master/src/muz/base/fp_params.pyg
z3::params p(*m_context);
// These are useful for solving problems with arrays and loops.
// Use quantified lemma generalizer.
p.set("fp.spacer.q3.use_qgen", true);
p.set("fp.spacer.mbqi", false);
// Ground pobs by using values from a model.
p.set("fp.spacer.ground_pobs", false);
m_solver.set(p);
}
void Z3CHCInterface::declareVariable(string const& _name, SortPointer const& _sort)
{
smtAssert(_sort, "");
m_z3Interface->declareVariable(_name, _sort);
}
void Z3CHCInterface::registerRelation(Expression const& _expr)
{
m_solver.register_relation(m_z3Interface->functions().at(_expr.name));
}
void Z3CHCInterface::addRule(Expression const& _expr, string const& _name)
{
z3::expr rule = m_z3Interface->toZ3Expr(_expr);
if (m_z3Interface->constants().empty())
m_solver.add_rule(rule, m_context->str_symbol(_name.c_str()));
else
{
z3::expr_vector variables(*m_context);
for (auto const& var: m_z3Interface->constants())
variables.push_back(var.second);
z3::expr boundRule = z3::forall(variables, rule);
m_solver.add_rule(boundRule, m_context->str_symbol(_name.c_str()));
}
}
pair<CheckResult, vector<string>> Z3CHCInterface::query(Expression const& _expr)
{
CheckResult result;
vector<string> values;
try
{
z3::expr z3Expr = m_z3Interface->toZ3Expr(_expr);
switch (m_solver.query(z3Expr))
{
case z3::check_result::sat:
{
result = CheckResult::SATISFIABLE;
// TODO retrieve model.
break;
}
case z3::check_result::unsat:
{
result = CheckResult::UNSATISFIABLE;
// TODO retrieve invariants.
break;
}
case z3::check_result::unknown:
{
result = CheckResult::UNKNOWN;
break;
}
}
// TODO retrieve model / invariants
}
catch (z3::exception const&)
{
result = CheckResult::ERROR;
values.clear();
}
return make_pair(result, values);
}
| 27.405405 | 83 | 0.73307 | step21 |
d2bf610f8676af660ad0a6574d700801e15affce | 3,078 | cpp | C++ | src/plugins/sb2/tabunhidelistview.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/sb2/tabunhidelistview.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/sb2/tabunhidelistview.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "tabunhidelistview.h"
#if QT_VERSION < 0x050000
#include <QGraphicsObject>
#else
#include <QQuickItem>
#endif
#include <QtDebug>
#include <util/util.h>
#include <util/qml/unhidelistmodel.h>
namespace LeechCraft
{
namespace SB2
{
TabUnhideListView::TabUnhideListView (const QList<TabClassInfo>& tcs,
ICoreProxy_ptr proxy, QWidget *parent)
: UnhideListViewBase (proxy,
[&tcs] (QStandardItemModel *model)
{
for (const auto& tc : tcs)
{
auto item = new QStandardItem;
item->setData (tc.TabClass_, Util::UnhideListModel::Roles::ItemClass);
item->setData (tc.VisibleName_, Util::UnhideListModel::Roles::ItemName);
item->setData (tc.Description_, Util::UnhideListModel::Roles::ItemDescription);
item->setData (Util::GetAsBase64Src (tc.Icon_.pixmap (32, 32).toImage ()),
Util::UnhideListModel::Roles::ItemIcon);
model->appendRow (item);
}
},
parent)
{
connect (rootObject (),
SIGNAL (itemUnhideRequested (QString)),
this,
SLOT (unhide (QString)),
Qt::QueuedConnection);
}
void TabUnhideListView::unhide (const QString& idStr)
{
const auto& id = idStr.toUtf8 ();
emit unhideRequested (id);
for (int i = 0; i < Model_->rowCount (); ++i)
if (Model_->item (i)->data (Util::UnhideListModel::Roles::ItemClass).toByteArray () == id)
{
Model_->removeRow (i);
break;
}
if (!Model_->rowCount ())
deleteLater ();
}
}
}
| 35.790698 | 93 | 0.690058 | MellonQ |
d2c158a5d6b3e21981c3908c958902651f26de91 | 2,146 | hpp | C++ | decompiler/exe.hpp | WastedMeerkat/gm81decompiler | 80040ac74f95af03b4b6649b0f5be11a7d13700b | [
"MIT"
] | 40 | 2017-07-31T22:20:49.000Z | 2022-01-28T14:57:44.000Z | decompiler/exe.hpp | nkrapivin/gm81decompiler | bae1f8c3f52ed80c50319555c96752d087520821 | [
"MIT"
] | null | null | null | decompiler/exe.hpp | nkrapivin/gm81decompiler | bae1f8c3f52ed80c50319555c96752d087520821 | [
"MIT"
] | 15 | 2015-12-29T16:36:28.000Z | 2021-12-19T09:04:54.000Z | /*
* exe.hpp
* GM EXE Abstraction
*/
#ifndef __EXE_HPP
#define __EXE_HPP
#include <iostream>
#include <string>
#include "gmk.hpp"
#define SWAP_TABLE_SIZE 256
// Icon headers
#pragma pack(push, 1)
typedef struct {
unsigned char bWidth; // Width, in pixels, of the image
unsigned char bHeight; // Height, in pixels, of the image
unsigned char bColorCount; // Number of colors in image (0 if >=8bpp)
unsigned char bReserved; // Reserved ( must be 0)
unsigned short wPlanes; // Color Planes
unsigned short wBitCount; // Bits per pixel
unsigned int dwBytesInRes; // How many bytes in this resource?
unsigned int dwImageOffset; // Where in the file is this image?
} ICONDIRENTRY, *LPICONDIRENTRY;
typedef struct {
unsigned short idReserved; // Reserved (must be 0)
unsigned short idType; // Resource Type (1 for icons)
unsigned short idCount; // How many images?
ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em)
} ICONDIR, *LPICONDIR;
#pragma pack(pop)
class GmExe {
private:
std::string exeFilename;
unsigned int version;
GmkStream* exeHandle;
Gmk* gmkHandle;
// GMK support -- Technically shouldn't be here
void RTAddItem(const std::string& name, int rtId, int index);
bool DecryptGameData();
GmkStream* GetIconData();
void ReadAction(GmkStream* stream, ObjectAction* action);
bool ReadSettings();
bool ReadWrapper();
bool ReadExtensions();
bool ReadTriggers();
bool ReadConstants();
bool ReadSounds();
bool ReadSprites();
bool ReadBackgrounds();
bool ReadPaths();
bool ReadScripts();
bool ReadFonts();
bool ReadTimelines();
bool ReadObjects();
bool ReadRooms();
bool ReadIncludes();
bool ReadGameInformation();
public:
GmExe() : exeHandle(new GmkStream()), version(0), exeFilename("") { }
~GmExe() { delete exeHandle; }
// Interface functions
bool Load(const std::string& filename, Gmk* gmk, unsigned int ver);
const unsigned int GetExeVersion() const { return version; }
};
#endif
| 26.493827 | 84 | 0.66123 | WastedMeerkat |
d2c20f256d5fd0bec41871a5c726c73f480ca8b6 | 2,802 | cpp | C++ | mfcc/Feature/mathtool.cpp | wengsht/cuda-mfcc-gmm | 83587058e3b023060de15f05d848d730add2fe65 | [
"MIT",
"Unlicense"
] | 9 | 2015-07-07T11:56:20.000Z | 2021-02-11T01:31:02.000Z | mfcc/Feature/mathtool.cpp | wengsht/cuda-mfcc-gmm | 83587058e3b023060de15f05d848d730add2fe65 | [
"MIT",
"Unlicense"
] | 1 | 2015-07-25T14:04:00.000Z | 2015-07-25T14:04:00.000Z | mfcc/Feature/mathtool.cpp | wengsht/cuda-mfcc-gmm | 83587058e3b023060de15f05d848d730add2fe65 | [
"MIT",
"Unlicense"
] | 5 | 2015-04-23T12:30:48.000Z | 2019-02-11T06:53:43.000Z | //
// mathtool.cpp
// SpeechRecongnitionSystem
//
// Created by Admin on 9/11/14.
// Copyright (c) 2014 Admin. All rights reserved.
//
#include "mathtool.h"
#include <assert.h>
#include <iostream>
#include "math.h"
#include "Feature.h"
using namespace std;
const int MAXN = 1000;
// fft(a, n, 1) -- dft
// fft(a, n, -1) -- idft
// n should be 2^k
void fft(cp *a,int n,int f)
{
// assert(MAXN > n);
cp *b = new cp[n];
double arg = PI;
for(int k = n>>1;k;k>>=1,arg*=0.5){
cp wm = std::polar(1.0,f*arg),w(1,0);
for(int i = 0;i<n;i+=k,w*=wm){
int p = i << 1;
if(p>=n) p-= n;
for(int j = 0;j<k;++j){
b[i+j] = a[p+j] + w*a[p+k+j];
}
}
for(int i = 0;i<n;++i) a[i] = b[i];
}
delete []b;
}
// use to check fft is right
void dft(cp *a,int n,int f)
{
cp *b = new cp[n];
for(int i = 0;i < n;i++) {
b[i] = cp(0, 0);
for(int j = 0;j < n;j++) {
b[i] += cp(std::real(a[j])*cos(-2.0*PI*j*i/n), std::real(a[j])*sin(-2.0*PI*j*i/n));
}
}
for(int i = 0;i<n;++i) a[i] = b[i];
delete []b;
}
// a's size should be more then 2*n
void dct(double *a,int n,int f)
{
cp *b = new cp[2*n];
for(int i = n-1;i >= 0;i--) {
b[n-i-1] = b[n+i] = cp(a[i], 0);
}
dft(b, 2*n, f);
for(int i = 0;i < 2*n;i++)
a[i] = std::real(b[i]);
delete [] b;
}
void dct2(double *a, int n) {
double *b = new double[n];
for(int i = 0;i < n;i++) {
b[i] = 0.0;
for(int j = 0;j < n;j++)
b[i] += a[j] * cos(PI*i*(j+1.0/2)/n);
}
for(int i = 0;i < n;i++)
a[i] = b[i] * sqrt(2.0/n) / sqrt(2.0);
delete [] b;
}
// -log(x+y) a = -log(x) b = -log(y)
double logInsideSum(double a, double b) {
if(a >= b) std::swap(a, b);
// printf("%lf %lf %lf\n", a, b,a - log(1.0 + pow(e, a-b)));
return a - log(1.0 + pow(e, a-b));
}
// -log((abs(x-y)) a = -log(x) b = -log(y)
double logInsideDist(double a, double b) {
if(a >= b) std::swap(a, b);
// printf("%lf %lf %lf\n", a, b,a - log(1.0 + pow(e, a-b)));
return a - log(1.0 - pow(e, a-b));
}
// probability to cost
double p2cost(double p) {
if(p <= 0) return Feature::IllegalDist;
return - log(p);
}
double cost2p(double cost) {
return pow(e, -cost);
}
void matrix2vector(const Matrix<double> & data, double *vec){
int rowSize=data[0].size();
for(int i=0; i<data.size(); i++){
for(int j=0; j<rowSize; j++){
*vec = data[i][j];
vec++;
}
}
}
void vector2matrix(double *vec, Matrix<double> & data){
for(int i=0; i< data.size(); i++){
for(int j=0; j<data[0].size(); j++){
data[i][j] = *vec;
vec++;
}
}
}
| 22.780488 | 95 | 0.457173 | wengsht |
d2c457ec8ff551a703e136a14bb0e854f7f24b58 | 1,530 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_PropertiesDialog.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_PropertiesDialog.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_PropertiesDialog.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #include "ag_PropertiesDialog.h"
// Library headers.
// PCRaster library headers.
// Module headers.
#include "ag_PropertiesWidget.h"
/*!
\file
This file contains the implementation of the PropertiesDialog class.
*/
//------------------------------------------------------------------------------
namespace ag {
class PropertiesDialogPrivate
{
public:
PropertiesDialogPrivate()
{
}
~PropertiesDialogPrivate()
{
}
};
} // namespace ag
//------------------------------------------------------------------------------
// DEFINITION OF STATIC PROPERTIESDIALOG MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF PROPERTIESDIALOG MEMBERS
//------------------------------------------------------------------------------
ag::PropertiesDialog::PropertiesDialog(PropertiesWidget* widget,
QWidget* parent)
: qt::PropertiesDialog(widget, parent, true),
d_data(new PropertiesDialogPrivate())
{
}
ag::PropertiesDialog::~PropertiesDialog()
{
}
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
| 19.125 | 80 | 0.367974 | quanpands |
d2c49949e6e8fcbcc67831349a64f1862e838466 | 13,978 | cpp | C++ | examples/platforms/utils/settings.cpp | mostafanfs/openthread | 28c049f2ce0b664abf2f85562cfd9b79b4680389 | [
"BSD-3-Clause"
] | null | null | null | examples/platforms/utils/settings.cpp | mostafanfs/openthread | 28c049f2ce0b664abf2f85562cfd9b79b4680389 | [
"BSD-3-Clause"
] | null | null | null | examples/platforms/utils/settings.cpp | mostafanfs/openthread | 28c049f2ce0b664abf2f85562cfd9b79b4680389 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the OpenThread platform abstraction for non-volatile storage of settings.
*
*/
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include <openthread-types.h>
#include <openthread-core-config.h>
#include <common/code_utils.hpp>
#include <platform/settings.h>
#include "flash.h"
#ifdef __cplusplus
extern "C" {
#endif
enum
{
kBlockAddBeginFlag = 0x1,
kBlockAddCompleteFlag = 0x02,
kBlockDeleteFlag = 0x04,
kBlockIndex0Flag = 0x08,
};
enum
{
kSettingsFlagSize = 4,
kSettingsBlockDataSize = 255,
kSettingsInSwap = 0xbe5cc5ef,
kSettingsInUse = 0xbe5cc5ee,
kSettingsNotUse = 0xbe5cc5ec,
};
OT_TOOL_PACKED_BEGIN
struct settingsBlock
{
uint16_t key;
uint16_t flag;
uint16_t length;
uint16_t reserved;
} OT_TOOL_PACKED_END;
/**
* @def SETTINGS_CONFIG_BASE_ADDRESS
*
* The base address of settings.
*
*/
#ifndef SETTINGS_CONFIG_BASE_ADDRESS
#define SETTINGS_CONFIG_BASE_ADDRESS 0x39000
#endif // SETTINGS_CONFIG_BASE_ADDRESS
/**
* @def SETTINGS_CONFIG_PAGE_SIZE
*
* The page size of settings.
*
*/
#ifndef SETTINGS_CONFIG_PAGE_SIZE
#define SETTINGS_CONFIG_PAGE_SIZE 0x800
#endif // SETTINGS_CONFIG_PAGE_SIZE
/**
* @def SETTINGS_CONFIG_PAGE_NUM
*
* The page number of settings.
*
*/
#ifndef SETTINGS_CONFIG_PAGE_NUM
#define SETTINGS_CONFIG_PAGE_NUM 2
#endif // SETTINGS_CONFIG_PAGE_NUM
static uint32_t sSettingsBaseAddress;
static uint32_t sSettingsUsedSize;
static uint16_t getAlignLength(uint16_t length)
{
return (length + 3) & 0xfffc;
}
static void setSettingsFlag(uint32_t aBase, uint32_t aFlag)
{
utilsFlashWrite(aBase, reinterpret_cast<uint8_t *>(&aFlag), sizeof(aFlag));
}
static void initSettings(uint32_t aBase, uint32_t aFlag)
{
uint32_t address = aBase;
uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ?
SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 :
SETTINGS_CONFIG_PAGE_SIZE;
while (address < (aBase + settingsSize))
{
utilsFlashErasePage(address);
utilsFlashStatusWait(1000);
address += SETTINGS_CONFIG_PAGE_SIZE;
}
setSettingsFlag(aBase, aFlag);
}
static uint32_t swapSettingsBlock(otInstance *aInstance)
{
uint32_t oldBase = sSettingsBaseAddress;
uint32_t swapAddress = oldBase;
uint32_t usedSize = sSettingsUsedSize;
uint8_t pageNum = SETTINGS_CONFIG_PAGE_NUM;
uint32_t settingsSize = pageNum > 1 ? SETTINGS_CONFIG_PAGE_SIZE * pageNum / 2 :
SETTINGS_CONFIG_PAGE_SIZE;
(void)aInstance;
VerifyOrExit(pageNum > 1, ;);
sSettingsBaseAddress = (swapAddress == SETTINGS_CONFIG_BASE_ADDRESS) ?
(swapAddress + settingsSize) :
SETTINGS_CONFIG_BASE_ADDRESS;
initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInSwap));
sSettingsUsedSize = kSettingsFlagSize;
swapAddress += kSettingsFlagSize;
while (swapAddress < (oldBase + usedSize))
{
OT_TOOL_PACKED_BEGIN
struct addSettingsBlock
{
struct settingsBlock block;
uint8_t data[kSettingsBlockDataSize];
} OT_TOOL_PACKED_END addBlock;
bool valid = true;
utilsFlashRead(swapAddress, reinterpret_cast<uint8_t *>(&addBlock.block), sizeof(struct settingsBlock));
swapAddress += sizeof(struct settingsBlock);
if (!(addBlock.block.flag & kBlockAddCompleteFlag) && (addBlock.block.flag & kBlockDeleteFlag))
{
uint32_t address = swapAddress + getAlignLength(addBlock.block.length);
while (address < (oldBase + usedSize))
{
struct settingsBlock block;
utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block));
if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag) &&
!(block.flag & kBlockIndex0Flag) && (block.key == addBlock.block.key))
{
valid = false;
break;
}
address += (getAlignLength(block.length) + sizeof(struct settingsBlock));
}
if (valid)
{
utilsFlashRead(swapAddress, addBlock.data, getAlignLength(addBlock.block.length));
utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize,
reinterpret_cast<uint8_t *>(&addBlock),
getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock));
sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length));
}
}
else if (addBlock.block.flag == 0xff)
{
break;
}
swapAddress += getAlignLength(addBlock.block.length);
}
setSettingsFlag(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse));
setSettingsFlag(oldBase, static_cast<uint32_t>(kSettingsNotUse));
exit:
return settingsSize - sSettingsUsedSize;
}
static ThreadError addSetting(otInstance *aInstance, uint16_t aKey, bool aIndex0, const uint8_t *aValue,
uint16_t aValueLength)
{
ThreadError error = kThreadError_None;
OT_TOOL_PACKED_BEGIN
struct addSettingsBlock
{
struct settingsBlock block;
uint8_t data[kSettingsBlockDataSize];
} OT_TOOL_PACKED_END addBlock;
uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ?
SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 :
SETTINGS_CONFIG_PAGE_SIZE;
addBlock.block.flag = 0xff;
addBlock.block.key = aKey;
if (aIndex0)
{
addBlock.block.flag &= (~kBlockIndex0Flag);
}
addBlock.block.flag &= (~kBlockAddBeginFlag);
addBlock.block.length = aValueLength;
if ((sSettingsUsedSize + getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)) >=
settingsSize)
{
VerifyOrExit(swapSettingsBlock(aInstance) >= (getAlignLength(addBlock.block.length) + sizeof(struct settingsBlock)),
error = kThreadError_NoBufs);
}
utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize,
reinterpret_cast<uint8_t *>(&addBlock.block),
sizeof(struct settingsBlock));
memset(addBlock.data, 0xff, kSettingsBlockDataSize);
memcpy(addBlock.data, aValue, addBlock.block.length);
utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize + sizeof(struct settingsBlock),
reinterpret_cast<uint8_t *>(addBlock.data), getAlignLength(addBlock.block.length));
addBlock.block.flag &= (~kBlockAddCompleteFlag);
utilsFlashWrite(sSettingsBaseAddress + sSettingsUsedSize,
reinterpret_cast<uint8_t *>(&addBlock.block),
sizeof(struct settingsBlock));
sSettingsUsedSize += (sizeof(struct settingsBlock) + getAlignLength(addBlock.block.length));
exit:
return error;
}
// settings API
void otPlatSettingsInit(otInstance *aInstance)
{
uint8_t index;
uint32_t settingsSize = SETTINGS_CONFIG_PAGE_NUM > 1 ?
SETTINGS_CONFIG_PAGE_SIZE * SETTINGS_CONFIG_PAGE_NUM / 2 :
SETTINGS_CONFIG_PAGE_SIZE;
(void)aInstance;
sSettingsBaseAddress = SETTINGS_CONFIG_BASE_ADDRESS;
utilsFlashInit();
for (index = 0; index < 2; index++)
{
uint32_t blockFlag;
sSettingsBaseAddress += settingsSize * index;
utilsFlashRead(sSettingsBaseAddress, reinterpret_cast<uint8_t *>(&blockFlag), sizeof(blockFlag));
if (blockFlag == kSettingsInUse)
{
break;
}
}
if (index == 2)
{
initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse));
}
sSettingsUsedSize = kSettingsFlagSize;
while (sSettingsUsedSize < settingsSize)
{
struct settingsBlock block;
utilsFlashRead(sSettingsBaseAddress + sSettingsUsedSize,
reinterpret_cast<uint8_t *>(&block), sizeof(block));
if (!(block.flag & kBlockAddBeginFlag))
{
sSettingsUsedSize += (getAlignLength(block.length) + sizeof(struct settingsBlock));
}
else
{
break;
}
}
}
ThreadError otPlatSettingsBeginChange(otInstance *aInstance)
{
(void)aInstance;
return kThreadError_None;
}
ThreadError otPlatSettingsCommitChange(otInstance *aInstance)
{
(void)aInstance;
return kThreadError_None;
}
ThreadError otPlatSettingsAbandonChange(otInstance *aInstance)
{
(void)aInstance;
return kThreadError_None;
}
ThreadError otPlatSettingsGet(otInstance *aInstance, uint16_t aKey, int aIndex, uint8_t *aValue, uint16_t *aValueLength)
{
ThreadError error = kThreadError_NotFound;
uint32_t address = sSettingsBaseAddress + kSettingsFlagSize;
int index = 0;
(void)aInstance;
while (address < (sSettingsBaseAddress + sSettingsUsedSize))
{
struct settingsBlock block;
utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block));
if (block.key == aKey)
{
if (!(block.flag & kBlockIndex0Flag))
{
index = 0;
}
if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag))
{
if (index == aIndex)
{
error = kThreadError_None;
if (aValueLength)
{
*aValueLength = block.length;
}
if (aValue)
{
VerifyOrExit(aValueLength, error = kThreadError_InvalidArgs);
utilsFlashRead(address + sizeof(struct settingsBlock), aValue, block.length);
}
}
index++;
}
}
address += (getAlignLength(block.length) + sizeof(struct settingsBlock));
}
exit:
return error;
}
ThreadError otPlatSettingsSet(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength)
{
return addSetting(aInstance, aKey, true, aValue, aValueLength);
}
ThreadError otPlatSettingsAdd(otInstance *aInstance, uint16_t aKey, const uint8_t *aValue, uint16_t aValueLength)
{
uint16_t length;
bool index0;
index0 = (otPlatSettingsGet(aInstance, aKey, 0, NULL, &length) == kThreadError_NotFound ? true : false);
return addSetting(aInstance, aKey, index0, aValue, aValueLength);
}
ThreadError otPlatSettingsDelete(otInstance *aInstance, uint16_t aKey, int aIndex)
{
ThreadError error = kThreadError_NotFound;
uint32_t address = sSettingsBaseAddress + kSettingsFlagSize;
int index = 0;
(void)aInstance;
while (address < (sSettingsBaseAddress + sSettingsUsedSize))
{
struct settingsBlock block;
utilsFlashRead(address, reinterpret_cast<uint8_t *>(&block), sizeof(block));
if (block.key == aKey)
{
if (!(block.flag & kBlockIndex0Flag))
{
index = 0;
}
if (!(block.flag & kBlockAddCompleteFlag) && (block.flag & kBlockDeleteFlag))
{
if (aIndex == index || aIndex == -1)
{
error = kThreadError_None;
block.flag &= (~kBlockDeleteFlag);
utilsFlashWrite(address, reinterpret_cast<uint8_t *>(&block), sizeof(block));
}
if (index == 1 && aIndex == 0)
{
block.flag &= (~kBlockIndex0Flag);
utilsFlashWrite(address, reinterpret_cast<uint8_t *>(&block), sizeof(block));
}
index++;
}
}
address += (getAlignLength(block.length) + sizeof(struct settingsBlock));
}
return error;
}
void otPlatSettingsWipe(otInstance *aInstance)
{
initSettings(sSettingsBaseAddress, static_cast<uint32_t>(kSettingsInUse));
otPlatSettingsInit(aInstance);
}
#ifdef __cplusplus
};
#endif
| 30.453159 | 124 | 0.645443 | mostafanfs |
d2c53e1ad0298b833d81da5f7bfe9da3b2aab22d | 8,646 | cc | C++ | test/util/test_OrderedMap.cc | ecmwf-projects/dasi | 0ca5c0a847b92586fae18d3b421ba9fb4014d716 | [
"Apache-2.0"
] | null | null | null | test/util/test_OrderedMap.cc | ecmwf-projects/dasi | 0ca5c0a847b92586fae18d3b421ba9fb4014d716 | [
"Apache-2.0"
] | 1 | 2022-03-21T16:20:10.000Z | 2022-03-21T16:20:10.000Z | test/util/test_OrderedMap.cc | ecmwf-projects/dasi | 0ca5c0a847b92586fae18d3b421ba9fb4014d716 | [
"Apache-2.0"
] | null | null | null |
#include "dasi/util/Test.h"
#include "dasi/util/OrderedMap.h"
CASE("Construct an ordered map and add things to it") {
dasi::util::OrderedMap<std::string, std::string> om;
EXPECT(om.empty());
std::vector<std::pair<std::string, std::string>> expected{
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
for (const auto& v : expected) {
om.insert(v);
}
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
CASE("Construct an ordered map with an initialiser list") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
std::vector<std::pair<std::string, std::string>> expected{
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
// Check values are accessible
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
// Check values can be iterated
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
CASE("Copy an ordered map and modify values") {
dasi::util::OrderedMap<std::string, std::string> base {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
std::vector<std::pair<std::string, std::string>> expected {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
dasi::util::OrderedMap<std::string, std::string> om(base);
EXPECT(om.size() == expected.size());
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
om["yyyy"] = "ynew";
expected[1] = std::make_pair("yyyy", "ynew");
EXPECT(om.size() == expected.size());
i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
CASE("We can iterate with mutable values") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
EXPECT(om.size() == 3);
std::vector<std::string> updates = { "aaaa", "bbbb", "cccc"};
int i = 0;
for (auto& v : om) {
v.second = updates[i++];
}
EXPECT(om["zzzz"] == "aaaa");
EXPECT(om["yyyy"] == "bbbb");
EXPECT(om["xxxx"] == "cccc");
om["yyyy"] = "another-value";
EXPECT(om["yyyy"] == "another-value");
// And we can create new values
EXPECT(om.find("pppp") == om.end());
EXPECT(om.find("pppp") == om.end());
om["pppp"];
EXPECT(om.find("pppp") != om.end());
EXPECT(om.find("pppp")->second.empty());
om["pppp"] = "new value";
EXPECT(om.find("pppp")->second == "new value");
}
CASE("Check that we can search for values as well") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
auto it = om.find("yyyy");
EXPECT(it != om.end());
EXPECT(it->first == "yyyy");
EXPECT(it->second == "yvalue");
EXPECT(om.find("badkey") == om.end());
}
CASE("Iterators obtained via 'find' are not iterable") {
// n.b. iteration order is determined by keys_ not the values_ dict.
// But lookups using 'find' use the values_ dict. Converting iterators between vector<>
// and map<> is not straightforward --> don't implement unless we really need it
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
EXPECT(om.size() == 3);
auto it = om.find("yyyy");
EXPECT(it != om.end());
EXPECT(it->second == "yvalue");
EXPECT_THROWS_AS(++it, dasi::util::NotImplemented);
}
CASE("ordered map is printable") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
EXPECT(om.size() == 3);
std::ostringstream ss;
ss << om;
EXPECT(ss.str() == "{zzzz:zvalue, yyyy:yvalue, xxxx:xvalue}");
}
CASE("string_view as values") {
dasi::util::OrderedMap<std::string, std::string_view> om {
{"abcd", "efgh"},
{"ijkl", "mnap"}
};
EXPECT(om.size() == 2);
EXPECT(om["abcd"] == "efgh");
EXPECT(om["ijkl"] == "mnap");
om["ijkl"] = "newvalue";
EXPECT(om["ijkl"] == "newvalue");
}
CASE("insert_or_assign") {
dasi::util::OrderedMap<std::string, std::string> om;
EXPECT(om.empty());
std::vector<std::pair<std::string, std::string>> expected {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
for (const auto& v : expected) {
auto r = om.insert_or_assign(v.first, v.second);
EXPECT(r.second);
EXPECT(r.first->first == v.first);
EXPECT(r.first->second == v.second);
}
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
std::vector<std::pair<std::string, std::string>> expected2 {
{"zzzz", "zvalue"},
{"yyyy", "newval"},
{"xxxx", "xvalue"}
};
auto r = om.insert_or_assign("yyyy", "newval");
EXPECT(!r.second);
EXPECT(r.first->first == "yyyy");
EXPECT(r.first->second == "newval");
EXPECT(om.size() == expected2.size());
for (const auto& v : expected2) {
EXPECT(om[v.first] == v.second);
}
i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected2[i].first);
EXPECT(kv.second == expected2[i++].second);
}
}
CASE("test emplace") {
dasi::util::OrderedMap<std::string, std::string> om;
EXPECT(om.empty());
std::vector<std::pair<std::string, std::string>> expected{
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"}
};
for (const auto& v : expected) {
om.emplace(std::make_pair(v.first, v.second));
}
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
CASE("Test erase") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"},
{"wwww", "wvalue"},
{"vvvv", "vvalue"},
{"uuuu", "uvalue"},
};
EXPECT(om.size() == 6);
om.erase("xxxx");
om.erase("zzzz");
om.erase("uuuu");
std::vector<std::pair<std::string, std::string>> expected{
{"yyyy", "yvalue"},
{"wwww", "wvalue"},
{"vvvv", "vvalue"},
};
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
CASE("Test erase with iterators") {
dasi::util::OrderedMap<std::string, std::string> om {
{"zzzz", "zvalue"},
{"yyyy", "yvalue"},
{"xxxx", "xvalue"},
{"wwww", "wvalue"},
{"vvvv", "vvalue"},
{"uuuu", "uvalue"},
};
EXPECT(om.size() == 6);
for (const char* k : {"xxxx", "zzzz", "uuuu"}) {
auto it = om.find(k);
EXPECT(it != om.end());
om.erase(it);
it = om.find(k);
EXPECT(it == om.end());
}
std::vector<std::pair<std::string, std::string>> expected {
{"yyyy", "yvalue"},
{"wwww", "wvalue"},
{"vvvv", "vvalue"},
};
EXPECT(om.size() == expected.size());
for (const auto& v : expected) {
EXPECT(om[v.first] == v.second);
}
int i = 0;
for (const auto& kv : om) {
EXPECT(kv.first == expected[i].first);
EXPECT(kv.second == expected[i++].second);
}
}
int main(int argc, char** argv) {
return ::dasi::util::run_tests();
} | 24.988439 | 96 | 0.516655 | ecmwf-projects |
d2c6555ef3950ab04bf037f26f7c58a15c32538f | 1,014 | cpp | C++ | Source/OpenTournament/OpenTournament.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 97 | 2020-05-24T23:09:26.000Z | 2022-01-22T13:35:58.000Z | Source/OpenTournament/OpenTournament.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 165 | 2020-05-26T02:42:54.000Z | 2022-03-29T11:01:11.000Z | Source/OpenTournament/OpenTournament.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 78 | 2020-05-24T23:10:29.000Z | 2022-03-14T13:54:09.000Z | // Copyright (c) 2019-2020 Open Tournament Project, All Rights Reserved.
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "OpenTournament.h"
#include "Modules/ModuleManager.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, OpenTournament, "OpenTournament" );
/////////////////////////////////////////////////////////////////////////////////////////////////
DEFINE_LOG_CATEGORY(Game);
DEFINE_LOG_CATEGORY(GameUI);
DEFINE_LOG_CATEGORY(Net);
DEFINE_LOG_CATEGORY(LogWeapon);
/////////////////////////////////////////////////////////////////////////////////////////////////
FCollisionResponseParams WorldResponseParams = []()
{
FCollisionResponseParams Response(ECR_Ignore);
Response.CollisionResponse.WorldStatic = ECR_Block;
Response.CollisionResponse.WorldDynamic = ECR_Block;
return Response;
}(); | 34.965517 | 98 | 0.466469 | HAARP-art |
d2c83b39d7219d090d32fd1079c275a0d301ff43 | 357 | hh | C++ | c++/gtest_tryout/corba_proxy.hh | jdmichaud/snippets | 1af85cf25156231165838b309860586f62bf43e2 | [
"Apache-2.0"
] | null | null | null | c++/gtest_tryout/corba_proxy.hh | jdmichaud/snippets | 1af85cf25156231165838b309860586f62bf43e2 | [
"Apache-2.0"
] | null | null | null | c++/gtest_tryout/corba_proxy.hh | jdmichaud/snippets | 1af85cf25156231165838b309860586f62bf43e2 | [
"Apache-2.0"
] | null | null | null | #ifndef __CORBA_PROXY__
#define __CORBA_PROXY__
#include <iostream>
class CorbaProxy {
public:
CorbaProxy() {}
virtual ~CorbaProxy() {}
virtual void corba_call_1(unsigned int i) {
std::cout << "corba_call_1 " << i << std::endl;
}
virtual void corba_call_2() {
std::cout << "corba_call_2" << std::endl;
}
};
#endif // __CORBA_PROXY__
| 17.85 | 51 | 0.661064 | jdmichaud |
d2c944dac7af77e474a98b541e90d9d5ddfbdec4 | 4,780 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/tools/valgrindfake/outputgenerator.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/tools/valgrindfake/outputgenerator.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/tools/valgrindfake/outputgenerator.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Author: Milian Wolff, KDAB (milian.wolff@kdab.com)
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "outputgenerator.h"
#include <QAbstractSocket>
#include <QIODevice>
#include <QTextStream>
#include <QCoreApplication>
#include <QStringList>
#include <QDebug>
// Yes, this is ugly. But please don't introduce a libUtils dependency
// just to get rid of a single function.
#ifdef Q_OS_WIN
#include <windows.h>
void doSleep(int msec) { ::Sleep(msec); }
#else
#include <time.h>
#include <unistd.h>
void doSleep(int msec)
{
struct timespec ts = {msec / 1000, (msec % 1000) * 1000000};
::nanosleep(&ts, NULL);
}
#endif
using namespace Valgrind::Fake;
OutputGenerator::OutputGenerator(QAbstractSocket *output, QIODevice *input) :
m_output(output),
m_input(input),
m_finished(false),
m_crash(false),
m_garbage(false),
m_wait(0)
{
Q_ASSERT(input->isOpen());
Q_ASSERT(input->isReadable());
m_timer.setSingleShot(true);
m_timer.start();
connect(&m_timer, &QTimer::timeout,
this, &OutputGenerator::writeOutput);
}
void OutputGenerator::setCrashRandomly(bool enable)
{
m_crash = enable;
}
void OutputGenerator::setOutputGarbage(bool enable)
{
m_garbage = enable;
}
void OutputGenerator::setWait(uint seconds)
{
m_wait = seconds;
}
#include <iostream>
static bool blockingWrite(QIODevice *dev, const QByteArray &ba)
{
const qint64 toWrite = ba.size();
qint64 written = 0;
while (written < ba.size()) {
const qint64 n = dev->write(ba.constData() + written, toWrite - written);
if (n < 0)
return false;
written += n;
}
return true;
}
void OutputGenerator::produceRuntimeError()
{
if (m_crash) {
std::cerr << "Goodbye, cruel world" << std::endl;
#ifndef __clang_analyzer__
int zero = 0; // hide the error at compile-time to avoid a compiler warning
int i = 1 / zero;
Q_UNUSED(i);
#endif
Q_ASSERT(false);
} else if (m_garbage) {
std::cerr << "Writing garbage" << std::endl;
blockingWrite(m_output, "<</GARBAGE = '\"''asdfaqre");
m_output->flush();
} else if (m_wait) {
qDebug() << "waiting in fake valgrind for " << m_wait << " seconds..." << endl;
doSleep(1000 * m_wait);
}
}
void OutputGenerator::writeOutput()
{
m_timer.setInterval(qrand() % 1000);
int lines = 0;
while (!m_input->atEnd()) {
qint64 lastPos = m_input->pos();
QByteArray line = m_input->readLine();
if (lines > 0 && !m_finished && line.contains("<error>")) {
if ((m_crash || m_garbage || m_wait) && qrand() % 10 == 1) {
produceRuntimeError();
m_timer.start();
return;
}
m_input->seek(lastPos);
m_timer.start();
return;
} else {
if (!m_finished && line.contains("<state>FINISHED</state>")) {
m_finished = true;
if (m_crash || m_garbage || m_wait) {
produceRuntimeError();
m_timer.start();
return;
}
}
if (!blockingWrite(m_output, line)) {
std::cerr << "Writing to socket failed: " << qPrintable(m_output->errorString()) << std::endl;
emit finished();
return;
}
m_output->flush();
++lines;
}
}
Q_ASSERT(m_input->atEnd());
while (m_output->bytesToWrite() > 0)
m_output->waitForBytesWritten(-1);
emit finished();
}
| 28.452381 | 110 | 0.596862 | kevinlq |
d2cb570e6a48c71f95aea0aac3e1e1c66db8b496 | 4,066 | cc | C++ | tests/ut/cpp/utils/orderedset_test.cc | unseenme/mindspore | 4ba052f0cd9146ac0ccc4880a778706f1b2d0af8 | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | tests/ut/cpp/utils/orderedset_test.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 7 | 2020-03-30T08:31:56.000Z | 2020-04-01T09:54:39.000Z | tests/ut/cpp/utils/orderedset_test.cc | liyong126/mindspore | 930a1fb0a8fa9432025442c4f4732058bb7af592 | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 <iostream>
#include <sstream>
#include <memory>
#include <algorithm>
#include "utils/ordered_set.h"
#include "common/common_test.h"
using std::cout;
using std::endl;
using std::string;
namespace mindspore {
class TestOrderedSet : public UT::Common {
public:
TestOrderedSet() {
std::shared_ptr<int> e;
for (int i = 1; i <= 10; i++) {
e = std::make_shared<int>(i);
osa.add(e);
}
for (int i = 11; i <= 20; i++) {
e = std::make_shared<int>(i);
osa.add(e);
osb.add(e);
}
for (int i = 21; i <= 30; i++) {
e = std::make_shared<int>(i);
osb.add(e);
osc.add(e);
}
}
public:
OrderedSet<std::shared_ptr<int>> osa;
OrderedSet<std::shared_ptr<int>> osb;
OrderedSet<std::shared_ptr<int>> osc;
};
TEST_F(TestOrderedSet, test_constructor) {
OrderedSet<std::shared_ptr<int>> osa_copy = osa;
ASSERT_EQ(osa_copy.size(), osa.size());
std::shared_ptr<int> e = std::make_shared<int>(1);
OrderedSet<std::shared_ptr<int>> se;
se.add(std::make_shared<int>(10));
se.add(std::make_shared<int>(20));
OrderedSet<std::shared_ptr<int>> order_se(se);
ASSERT_EQ(order_se.size(), 2);
}
TEST_F(TestOrderedSet, test_add_remove_clear) {
OrderedSet<std::shared_ptr<int>> res;
res.add(std::make_shared<int>(1));
std::shared_ptr<int> e = std::make_shared<int>(2);
std::shared_ptr<int> e2 = std::make_shared<int>(10);
res.add(e);
ASSERT_EQ(res.size(), 2);
ASSERT_EQ(res.count(e), 1);
auto elem = res.back();
ASSERT_EQ(elem, e);
res.erase(e);
ASSERT_EQ(res.size(), 1);
res.clear();
ASSERT_EQ(res.size(), 0);
}
TEST_F(TestOrderedSet, test_add_remove_first) {
OrderedSet<int> a;
a.add(1);
a.add(2);
a.add(3);
a.erase(1);
auto first = a.pop();
// 1 removed, 2 3 followd, 2 should be the poped one, remaining size = 1
ASSERT_EQ(first, 2);
ASSERT_EQ(a.size(), 1);
}
TEST_F(TestOrderedSet, test_compare) {
OrderedSet<std::shared_ptr<int>> c1;
OrderedSet<std::shared_ptr<int>> c2;
std::shared_ptr<int> e1 = std::make_shared<int>(10);
std::shared_ptr<int> e2 = std::make_shared<int>(20);
c1.add(e1);
c1.add(e2);
c2.add(e1);
c2.add(e2);
ASSERT_EQ(c1, c2);
}
TEST_F(TestOrderedSet, test_pop) {
OrderedSet<std::shared_ptr<int>> oset;
oset.add(std::make_shared<int>(10));
oset.add(std::make_shared<int>(20));
oset.add(std::make_shared<int>(30));
std::shared_ptr<int> ele = oset.pop();
int pop_size = 0;
pop_size++;
while (oset.size() != 0) {
ele = oset.pop();
pop_size++;
}
ASSERT_EQ(pop_size, 3);
ASSERT_EQ(oset.size(), 0);
}
TEST_F(TestOrderedSet, test_operation) {
ASSERT_TRUE(osc.is_disjoint(osa));
ASSERT_TRUE(!osb.is_disjoint(osa));
ASSERT_TRUE(osc.is_subset(osb));
ASSERT_TRUE(!osc.is_subset(osa));
OrderedSet<std::shared_ptr<int>> res_inter = osa | osb;
ASSERT_EQ(res_inter.size(), 30);
OrderedSet<std::shared_ptr<int>> res_union = osa & osb;
ASSERT_EQ(res_union.size(), 10);
OrderedSet<std::shared_ptr<int>> res_diff = osa - osb;
ASSERT_EQ(res_diff.size(), 10);
OrderedSet<std::shared_ptr<int>> res_symdiff = osa ^ osb;
ASSERT_EQ(res_symdiff.size(), 20);
}
TEST_F(TestOrderedSet, test_contains) {
OrderedSet<std::shared_ptr<int>> res;
std::shared_ptr<int> e1 = std::make_shared<int>(10);
std::shared_ptr<int> e2 = std::make_shared<int>(20);
res.add(e1);
ASSERT_TRUE(res.contains(e1));
ASSERT_TRUE(!res.contains(e2));
}
} // namespace mindspore
| 26.927152 | 75 | 0.665273 | unseenme |
d2cbdf2f76ae487e03495662b7b82b3948c23860 | 1,949 | hh | C++ | extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/attributes/fast_clear_attribute.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <polymesh/attributes.hh>
#include <polymesh/primitives.hh>
namespace polymesh
{
template <class T, class tag, class gen_t = int>
struct fast_clear_attribute;
template <class T, class gen_t = int, class mesh_ptr, class tag, class iterator>
fast_clear_attribute<T, tag, gen_t> make_fast_clear_attribute(smart_collection<mesh_ptr, tag, iterator> const& c, T const& clear_value = {});
/**
* A wrapper around a pm::attribute that provides a O(1) clear operation
*
* Internally, each primitive holds a generation counter.
* When accessing the attribute, the value is cleared in a lazy manner if the generation mismatches
*/
template <class T, class tag, class gen_t>
struct fast_clear_attribute
{
using index_t = typename primitive<tag>::index;
fast_clear_attribute(Mesh const& m, T const& clear_value) : _values(m), _clear_value(clear_value) {}
void clear(T const& new_value = {})
{
++_gen;
POLYMESH_ASSERT(_gen != 0 && "generation got wrapped around!");
_clear_value = new_value;
}
T& operator[](index_t i)
{
auto& e = _values[i];
if (e.gen != _gen)
{
e.value = _clear_value;
e.gen = _gen;
}
return e.value;
}
T const& operator[](index_t i) const
{
auto const& e = _values[i];
return e.gen != _gen ? _clear_value : e.value;
}
T& operator()(index_t i) { return operator[](i); }
T const& operator()(index_t i) const { return operator[](i); }
private:
struct entry
{
T value;
gen_t gen = 0;
};
primitive_attribute<tag, entry> _values;
gen_t _gen = 1;
T _clear_value;
};
template <class T, class gen_t, class mesh_ptr, class tag, class iterator>
fast_clear_attribute<T, tag, gen_t> make_fast_clear_attribute(smart_collection<mesh_ptr, tag, iterator> const& c, T const& clear_value)
{
return {c.mesh(), clear_value};
}
}
| 27.842857 | 141 | 0.654182 | rovedit |
d2cc8c0bca403ffbe14591ae09841c606490bdb7 | 2,298 | cpp | C++ | src/application.qt.objectview/ObjectViewPlugin.cpp | toeb/sine | 96bcde571218f89a2b0b3cc51c19ad2b7be89c13 | [
"MIT"
] | null | null | null | src/application.qt.objectview/ObjectViewPlugin.cpp | toeb/sine | 96bcde571218f89a2b0b3cc51c19ad2b7be89c13 | [
"MIT"
] | null | null | null | src/application.qt.objectview/ObjectViewPlugin.cpp | toeb/sine | 96bcde571218f89a2b0b3cc51c19ad2b7be89c13 | [
"MIT"
] | null | null | null | #include "ObjectViewPlugin.h"
#include <application.qt/PluginContainer.h>
#include "ui_objectview.h"
#include <application.qt/DataBinding.h>
#include <core.utilities.h>
using namespace std;
using namespace nspace;
void ObjectViewPlugin::objectDoubleClicked(QListWidgetItem * qobject){
auto data= qobject->data(Qt::UserRole);
void * value =data.value<void*>();
Object * object = static_cast<Object*>(value);
_objectPropertyView->setCurrentObject(object);
}
void ObjectViewPlugin::install(PluginContainer & container){
PluginWindow * window = new PluginWindow();
window->setWindowTitle(tr("Object View"));
QWidget * w = new QWidget();
_ui= new Ui_ObjectView();
_ui->setupUi(w);
_objectPropertyView = new ObjectPropertyView();
//QGridLayout * gridLayout = _ui->gridLayout;
QSplitter * splitter = _ui->splitter;
auto binding = new LineEditDataBinding();
binding->setSource(this);
binding->setTarget(_ui->searchTextBox);
binding->setPropertyName("SearchString");
//gridLayout->addWidget(_objectPropertyView,0,1,2,1);
splitter->addWidget(_objectPropertyView);
connect(_ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)),this, SLOT(objectDoubleClicked(QListWidgetItem*)));
window->setWidget(w);
container.setPluginWindow(window);
container.toggleWindow(true);
}
void ObjectViewPlugin::itemAdded(Object * , Objects){
}
void ObjectViewPlugin::itemRemoved(Object * , Objects){
}
void ObjectViewPlugin::onPropertyChanged(const std::string &name){
if(name!="SearchString"){return;}
updateObjectList();
}
void ObjectViewPlugin::updateListView(){
if(_ui)_ui->listWidget->clear();
Objects().foreachElement([this](Object * object){
string n = nspace::name(object);
QListWidgetItem * item=new QListWidgetItem(tr(n.c_str()));
QVariant variant = QVariant::fromValue<void*>(object);
item->setData(Qt::UserRole,variant);
if(_ui)_ui->listWidget->addItem(item);
});
}
void ObjectViewPlugin::updateObjectList(){
auto search = getSearchString();
if(search==""){
Objects()=*this;
}else{
Objects()=subset([&search](Object * object){
return nspace::stringtools::containsIgnoreCase(nspace::name(object),search);
});
}
updateListView();
} | 32.828571 | 124 | 0.707572 | toeb |
d2ccdb52f03b4ec1f67b6546ec34c4aeec0eeca7 | 9,073 | cpp | C++ | src/decoder-phrasebased/src/native/decoder/moses/HypothesisStackNormal.cpp | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | 3 | 2020-02-28T21:42:44.000Z | 2021-03-12T13:56:16.000Z | tools/mosesdecoder-master/moses/HypothesisStackNormal.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-11-06T14:40:10.000Z | 2020-12-29T19:03:11.000Z | tools/mosesdecoder-master/moses/HypothesisStackNormal.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-03-26T16:05:11.000Z | 2020-08-06T16:35:39.000Z | // $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <algorithm>
#include <set>
#include <queue>
#include "HypothesisStackNormal.h"
#include "TypeDef.h"
#include "Util.h"
#include "Manager.h"
#include "util/exception.hh"
using namespace std;
namespace Moses
{
HypothesisStackNormal::HypothesisStackNormal(Manager& manager) :
HypothesisStack(manager)
{
m_nBestIsEnabled = manager.options()->nbest.enabled;
m_bestScore = -std::numeric_limits<float>::infinity();
m_worstScore = -std::numeric_limits<float>::infinity();
}
/** remove all hypotheses from the collection */
void HypothesisStackNormal::RemoveAll()
{
while (m_hypos.begin() != m_hypos.end()) {
Remove(m_hypos.begin());
}
}
pair<HypothesisStackNormal::iterator, bool> HypothesisStackNormal::Add(Hypothesis *hypo)
{
std::pair<iterator, bool> ret = m_hypos.insert(hypo);
if (ret.second) {
// equiv hypo doesn't exists
VERBOSE(3,"added hyp to stack");
// Update best score, if this hypothesis is new best
if (hypo->GetFutureScore() > m_bestScore) {
VERBOSE(3,", best on stack");
m_bestScore = hypo->GetFutureScore();
// this may also affect the worst score
if ( m_bestScore + m_beamWidth > m_worstScore )
m_worstScore = m_bestScore + m_beamWidth;
}
// update best/worst score for stack diversity 1
if ( m_minHypoStackDiversity == 1 &&
hypo->GetFutureScore() > GetWorstScoreForBitmap( hypo->GetWordsBitmap() ) ) {
SetWorstScoreForBitmap( hypo->GetWordsBitmap().GetID(), hypo->GetFutureScore() );
}
VERBOSE(3,", now size " << m_hypos.size());
// prune only if stack is twice as big as needed (lazy pruning)
size_t toleratedSize = 2*m_maxHypoStackSize-1;
// add in room for stack diversity
if (m_minHypoStackDiversity) {
// so what happens if maxdistortion is negative?
toleratedSize += m_minHypoStackDiversity
<< m_manager.options()->reordering.max_distortion;
}
if (m_hypos.size() > toleratedSize) {
PruneToSize(m_maxHypoStackSize);
} else {
VERBOSE(3,std::endl);
}
}
return ret;
}
bool HypothesisStackNormal::AddPrune(Hypothesis *hypo)
{
if (hypo->GetFutureScore() == - std::numeric_limits<float>::infinity()) {
m_manager.GetSentenceStats().AddDiscarded();
VERBOSE(3,"discarded, constraint" << std::endl);
delete hypo;
return false;
}
// too bad for stack. don't bother adding hypo into collection
if (m_manager.options()->search.disable_discarding == false
&& hypo->GetFutureScore() < m_worstScore
&& ! ( m_minHypoStackDiversity > 0
&& hypo->GetFutureScore() >= GetWorstScoreForBitmap( hypo->GetWordsBitmap() ) ) ) {
m_manager.GetSentenceStats().AddDiscarded();
VERBOSE(3,"discarded, too bad for stack" << std::endl);
delete hypo;
return false;
}
// over threshold, try to add to collection
std::pair<iterator, bool> addRet = Add(hypo);
if (addRet.second) {
// nothing found. add to collection
return true;
}
// equiv hypo exists, recombine with other hypo
iterator &iterExisting = addRet.first;
Hypothesis *hypoExisting = *iterExisting;
assert(iterExisting != m_hypos.end());
m_manager.GetSentenceStats().AddRecombination(*hypo, **iterExisting);
// found existing hypo with same target ending.
// keep the best 1
if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
// incoming hypo is better than the one we have
VERBOSE(3,"better than matching hyp " << hypoExisting->GetId() << ", recombining, ");
if (m_nBestIsEnabled) {
hypo->AddArc(hypoExisting);
Detach(iterExisting);
} else {
Remove(iterExisting);
}
bool added = Add(hypo).second;
if (!added) {
iterExisting = m_hypos.find(hypo);
UTIL_THROW2("Offending hypo = " << **iterExisting);
}
return false;
} else {
// already storing the best hypo. discard current hypo
VERBOSE(3,"worse than matching hyp " << hypoExisting->GetId() << ", recombining" << std::endl)
if (m_nBestIsEnabled) {
hypoExisting->AddArc(hypo);
} else {
delete hypo;
}
return false;
}
}
void HypothesisStackNormal::PruneToSize(size_t newSize)
{
if ( newSize == 0) return; // no limit
if ( size() <= newSize ) return; // ok, if not over the limit
// we need to store a temporary list of hypotheses
vector< Hypothesis* > hypos = GetSortedListNOTCONST();
bool* included = (bool*) malloc(sizeof(bool) * hypos.size());
for(size_t i=0; i<hypos.size(); i++) included[i] = false;
// clear out original set
for( iterator iter = m_hypos.begin(); iter != m_hypos.end(); ) {
iterator removeHyp = iter++;
Detach(removeHyp);
}
// add best hyps for each coverage according to minStackDiversity
if ( m_minHypoStackDiversity > 0 ) {
map< WordsBitmapID, size_t > diversityCount;
for(size_t i=0; i<hypos.size(); i++) {
Hypothesis *hyp = hypos[i];
WordsBitmapID coverage = hyp->GetWordsBitmap().GetID();;
if (diversityCount.find( coverage ) == diversityCount.end())
diversityCount[ coverage ] = 0;
if (diversityCount[ coverage ] < m_minHypoStackDiversity) {
m_hypos.insert( hyp );
included[i] = true;
diversityCount[ coverage ]++;
if (diversityCount[ coverage ] == m_minHypoStackDiversity)
SetWorstScoreForBitmap( coverage, hyp->GetFutureScore());
}
}
}
// only add more if stack not full after satisfying minStackDiversity
if ( size() < newSize ) {
// add best remaining hypotheses
for(size_t i=0; i<hypos.size()
&& size() < newSize
&& hypos[i]->GetFutureScore() > m_bestScore+m_beamWidth; i++) {
if (! included[i]) {
m_hypos.insert( hypos[i] );
included[i] = true;
if (size() == newSize)
m_worstScore = hypos[i]->GetFutureScore();
}
}
}
// delete hypotheses that have not been included
for(size_t i=0; i<hypos.size(); i++) {
if (! included[i]) {
delete hypos[i];
m_manager.GetSentenceStats().AddPruning();
}
}
free(included);
// some reporting....
VERBOSE(3,", pruned to size " << size() << endl);
IFVERBOSE(3) {
TRACE_ERR("stack now contains: ");
for(iterator iter = m_hypos.begin(); iter != m_hypos.end(); iter++) {
Hypothesis *hypo = *iter;
TRACE_ERR( hypo->GetId() << " (" << hypo->GetFutureScore() << ") ");
}
TRACE_ERR( endl);
}
}
const Hypothesis *HypothesisStackNormal::GetBestHypothesis() const
{
if (!m_hypos.empty()) {
const_iterator iter = m_hypos.begin();
Hypothesis *bestHypo = *iter;
while (++iter != m_hypos.end()) {
Hypothesis *hypo = *iter;
if (hypo->GetFutureScore() > bestHypo->GetFutureScore())
bestHypo = hypo;
}
return bestHypo;
}
return NULL;
}
vector<const Hypothesis*> HypothesisStackNormal::GetSortedList() const
{
vector<const Hypothesis*> ret;
ret.reserve(m_hypos.size());
std::copy(m_hypos.begin(), m_hypos.end(), std::inserter(ret, ret.end()));
sort(ret.begin(), ret.end(), CompareHypothesisTotalScore());
return ret;
}
vector<Hypothesis*> HypothesisStackNormal::GetSortedListNOTCONST()
{
vector<Hypothesis*> ret;
ret.reserve(m_hypos.size());
std::copy(m_hypos.begin(), m_hypos.end(), std::inserter(ret, ret.end()));
sort(ret.begin(), ret.end(), CompareHypothesisTotalScore());
return ret;
}
void HypothesisStackNormal::CleanupArcList()
{
// only necessary if n-best calculations are enabled
if (!m_nBestIsEnabled) return;
iterator iter;
for (iter = m_hypos.begin() ; iter != m_hypos.end() ; ++iter) {
Hypothesis *mainHypo = *iter;
mainHypo->CleanupArcList(this->m_manager.options()->nbest.nbest_size, this->m_manager.options()->NBestDistinct());
}
}
TO_STRING_BODY(HypothesisStackNormal);
// friend
std::ostream& operator<<(std::ostream& out, const HypothesisStackNormal& hypoColl)
{
HypothesisStackNormal::const_iterator iter;
for (iter = hypoColl.begin() ; iter != hypoColl.end() ; ++iter) {
const Hypothesis &hypo = **iter;
out << hypo << endl;
}
return out;
}
}
| 30.755932 | 118 | 0.654139 | ugermann |
d2cf5bf30439fa3e6d02f3d20095f943e27a9b7d | 326 | cpp | C++ | 10-generic-algorithms/10-32.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | 10-generic-algorithms/10-32.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | 10-generic-algorithms/10-32.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | // Exercise 10.32: Rewrite the bookstore problem from Section 1.6 (p. 24) using
// a vector to hold the transactions and various algorithms to do the
// processing. Use sort with your compareIsbn function from Section 10.3.1 (p.
// 387) to arrange the transactions in order, and then use find and accumulate
// to do the sum.
| 54.333333 | 79 | 0.751534 | aafulei |
d2cff4f2cf7446839d32cb58f32ea78ce3b379d0 | 5,749 | cpp | C++ | PolarisEngine/src/Rendering/Camera.cpp | Delunado/PolarisEngine | 9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1 | [
"Apache-2.0"
] | 2 | 2021-01-12T21:24:24.000Z | 2021-02-19T15:06:23.000Z | PolarisEngine/src/Rendering/Camera.cpp | Delunado/PolarisEngine | 9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1 | [
"Apache-2.0"
] | 2 | 2021-03-10T19:16:38.000Z | 2021-12-01T22:47:13.000Z | PolarisEngine/src/Rendering/Camera.cpp | Delunado/PolarisEngine | 9de5cb1a3c576f4908dae7b0122f6dd1dab0f7f1 | [
"Apache-2.0"
] | null | null | null | #include <GL/glew.h>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Camera.h"
namespace Render {
Camera::Camera(glm::vec3 position, glm::vec3 lookAtPoint, GLfloat aspectRel) : position(position),
lookAtPoint(lookAtPoint), aspectRel(aspectRel), worldUp(glm::vec3(0, 1, 0)), fovX(7.5f),
zNear(0.1f), zFar(200.0f)
{
CalculateVisionAngle();
CalculateLocalVectors();
CalculateVisionMatrix();
CalculateProjectionMatrix();
}
Camera::Camera(const Camera& other)
{
this->aspectRel = other.aspectRel;
this->fovX = other.fovX;
this->fovY = other.fovY;
this->front = other.front;
this->right = other.right;
this->up = other.up;
this->worldUp = other.worldUp;
this->lookAtPoint = other.lookAtPoint;
this->position = other.position;
this->zFar = other.zFar;
this->zNear = other.zNear;
this->visionMatrix = other.visionMatrix;
this->projectionMatrix = other.projectionMatrix;
}
Camera::~Camera()
{
}
Camera* Camera::CreateCamera(glm::vec3 position, glm::vec3 lookAtPoint, GLfloat aspectRel)
{
Camera* camera = new Camera(position, lookAtPoint, aspectRel);
return camera;
}
#pragma region CONTROL
void Camera::Move(CAMERA_MOV_DIR movement, GLfloat speed)
{
glm::vec3 direction = glm::vec3(0.0f);
switch (movement)
{
case CAMERA_MOV_DIR::FORWARD:
direction = -front * speed;
break;
case CAMERA_MOV_DIR::RIGHTWARD:
direction = right * speed;
break;
case CAMERA_MOV_DIR::UPWARD:
direction = glm::vec3(0.0f, 1.0f, 0.0f) * speed;
break;
default:
break;
}
glm::mat4 translation = glm::translate(glm::mat4(1.0f), direction);
position = translation * glm::vec4(position, 1.0f);
lookAtPoint = translation * glm::vec4(lookAtPoint, 1.0f);
CalculateVisionMatrix();
}
void Camera::Zoom(GLfloat zoom)
{
fovX -= zoom;
fovX = glm::clamp(fovX, 0.01f, 2.0f);
CalculateVisionAngle();
CalculateProjectionMatrix();
}
void Camera::Rotate(GLfloat degreesX, GLfloat degreesY)
{
glm::mat4 rotationTilt = glm::rotate(glm::mat4(1.0f), glm::radians(degreesY), right);
glm::mat4 rotationPan = glm::rotate(glm::mat4(1.0f), glm::radians(-degreesX), up);
glm::mat4 transformation = glm::translate(glm::mat4(1.0f), position) * rotationTilt * rotationPan * glm::translate(glm::mat4(1.0f), -position);
lookAtPoint = transformation * glm::vec4(lookAtPoint, 1.0f);
CalculateLocalVectors();
CalculateVisionMatrix();
}
void Camera::RotateAround(GLfloat degreesX, GLfloat degreesY, glm::vec3 rotationPoint)
{
glm::mat4 rotationMatrixX = glm::rotate(glm::mat4(1.0f), glm::radians(degreesX), glm::normalize(up));
glm::mat4 rotationMatrixY = glm::rotate(glm::mat4(1.0f), glm::radians(degreesY), glm::normalize(right));
glm::mat4 transformation = glm::translate(glm::mat4(1.0f), rotationPoint) * rotationMatrixY * rotationMatrixX * glm::translate(glm::mat4(1.0f), -rotationPoint);
position = transformation * glm::vec4(position, 1.0f);
CalculateLocalVectors();
CalculateVisionMatrix();
}
#pragma endregion
#pragma region GETTERS
glm::vec3 Camera::GetPosition()
{
return position;
}
glm::vec3 Camera::GetLookAtPoint()
{
return lookAtPoint;
}
glm::vec3 Camera::GetWorldUp()
{
return worldUp;
}
glm::vec3 Camera::GetFront()
{
return front;
}
glm::vec3 Camera::GetRight()
{
return right;
}
glm::vec3 Camera::GetUp()
{
return up;
}
GLfloat Camera::GetFieldOfViewY()
{
return fovY;
}
GLfloat Camera::GetFieldOfViewX()
{
return fovX;
}
GLfloat Camera::GetZNear()
{
return zNear;
}
GLfloat Camera::GetZFar()
{
return zFar;
}
glm::mat4 Camera::GetVisionMatrix()
{
return visionMatrix;
}
glm::mat4 Camera::GetProjectionMatrix()
{
return projectionMatrix;
}
GLfloat Camera::GetAspectRel()
{
return aspectRel;
}
#pragma endregion
#pragma region SETTERS
void Camera::SetPosition(glm::vec3 position)
{
this->position = position;
CalculateLocalVectors();
CalculateVisionMatrix();
}
void Camera::SetLookAtPoint(glm::vec3 lookAtPoint)
{
this->lookAtPoint = lookAtPoint;
CalculateLocalVectors();
CalculateVisionMatrix();
}
void Camera::SetWorldUp(glm::vec3 worldUp)
{
this->worldUp = worldUp;
CalculateLocalVectors();
CalculateVisionMatrix();
}
void Camera::SetFieldOfViewX(GLfloat fovX)
{
this->fovX = fovX;
CalculateVisionAngle();
CalculateProjectionMatrix();
}
void Camera::SetFieldOfViewY(GLfloat fovY)
{
this->fovY = fovY;
CalculateProjectionMatrix();
}
void Camera::SetZNear(GLfloat zNear)
{
this->zNear = zNear;
CalculateProjectionMatrix();
}
void Camera::SetZFar(GLfloat zFar)
{
this->zFar = zFar;
CalculateProjectionMatrix();
}
void Camera::SetAspectRel(GLfloat aspecRel)
{
this->aspectRel = aspecRel;
CalculateProjectionMatrix();
}
#pragma endregion
#pragma region CALCULATIONS
void Camera::CalculateVisionAngle()
{
fovY = 2 * glm::atan(glm::tan(fovX / 2) / aspectRel);
}
void Camera::CalculateLocalVectors()
{
front = -glm::normalize((lookAtPoint - position));
right = glm::normalize(glm::cross(VectorUp(), front));
up = glm::normalize(glm::cross(front, right));
}
void Camera::CalculateVisionMatrix()
{
visionMatrix = glm::lookAt(position, lookAtPoint, up);
}
void Camera::CalculateProjectionMatrix()
{
projectionMatrix = glm::perspective(fovY, aspectRel, zNear, zFar);
}
glm::vec3 Camera::VectorUp()
{
glm::vec3 currentUp = worldUp;
if (glm::all(glm::epsilonEqual(front, worldUp, 0.001f)))
currentUp = glm::vec3(0, 0, 1);
else if (glm::all(glm::epsilonEqual(front, -worldUp, 0.001f)))
currentUp = glm::vec3(0, 0, -1);
return currentUp;
}
#pragma endregion
} | 21.214022 | 162 | 0.69299 | Delunado |
d2d035b211db4b777fb4eaa2c2c8a5053db810fe | 51 | cpp | C++ | third_party/vkmemalloc/src/VmaReplay/VmaUsage.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 7 | 2020-02-28T05:45:58.000Z | 2021-08-06T20:46:39.000Z | third_party/vkmemalloc/src/VmaReplay/VmaUsage.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 7 | 2019-08-23T17:54:13.000Z | 2020-02-01T06:59:52.000Z | third_party/vkmemalloc/src/VmaReplay/VmaUsage.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 3 | 2018-07-30T22:07:00.000Z | 2021-07-01T07:50:17.000Z | #define VMA_IMPLEMENTATION
#include "VmaUsage.h"
| 17 | 27 | 0.784314 | Alan-love |
d2d1b51c836e4bc7fac9141910f2eb66fcc9d4d9 | 733 | cpp | C++ | class/inheritance.cpp | learnMachining/cplus2test | 8cc0048627724bb967f27d5cd9860dbb5804a7d9 | [
"Apache-2.0"
] | null | null | null | class/inheritance.cpp | learnMachining/cplus2test | 8cc0048627724bb967f27d5cd9860dbb5804a7d9 | [
"Apache-2.0"
] | null | null | null | class/inheritance.cpp | learnMachining/cplus2test | 8cc0048627724bb967f27d5cd9860dbb5804a7d9 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <time.h>
using namespace std;
class B0
{
public:
B0(int n)
{
nV = n;
cout<<"constructing B0"<<endl;
}
int nV;
void fun()
{
cout<<"member of B0 "<<nV<<endl;
}
};
class B1:virtual public B0
{
public:
B1(int a):B0(a)
{
cout<<"constructing B1"<<endl;
}
int nV1;
};
class B2:virtual public B0
{
public:
B2(int a):B0(a)
{
cout<<"constructing B2"<<endl;
}
int nV2;
};
class D1:public B1, public B2
{
public:
D1(int a):B0(a), B1(a), B2(a)
{
}
int nVd;
void fund()
{
cout<<"member of D1"<<endl;
}
};
int main()
{
D1 d1(1);
d1.fun();
d1.nV = 2;
d1.fun();
return 0;
}
| 11.822581 | 40 | 0.491132 | learnMachining |
d2d85d784771d7da94b3474e8be152c7dbed7b53 | 3,063 | cpp | C++ | project-code/PictureDecoder/Slice/Slice.cpp | Bho007/MPEG-2-TS-Decoder | 6021af80f9a79b241da1db158b87ed3fe53f8e61 | [
"MIT"
] | null | null | null | project-code/PictureDecoder/Slice/Slice.cpp | Bho007/MPEG-2-TS-Decoder | 6021af80f9a79b241da1db158b87ed3fe53f8e61 | [
"MIT"
] | null | null | null | project-code/PictureDecoder/Slice/Slice.cpp | Bho007/MPEG-2-TS-Decoder | 6021af80f9a79b241da1db158b87ed3fe53f8e61 | [
"MIT"
] | null | null | null | //
// Created by elnsa on 2019-12-29.
//
#include "Slice.h"
Slice::Slice(Slice::initializerStruct init) {
stream_id = init.stream_id;
packet_type = ESPacket::start_code::slice;
slice_vertical_position_extension = init.slice_vertical_position_extension;
quantiser_scale_code = init.quantiser_scale_code;
slice_extension_flag = init.slice_extension_flag;
intra_slice = init.intra_slice;
slice_picture_id_enable = init.slice_picture_id_enable;
slice_picture_id = init.slice_picture_id;
numMacroblocks = init.numMacroblocks;
macroblocks = init.macroblocks;
}
void Slice::print() {
printf("Slice: id = %hhx, vpe = %hhu, qsc = %hhu, sef = %hhu, is = %hhu, spide = %hhu, spid = %hhu, numMacroblocks = %u\n",
stream_id, slice_vertical_position_extension, quantiser_scale_code, slice_extension_flag, intra_slice,
slice_picture_id_enable, slice_picture_id, numMacroblocks);
// for (size_t i = 0; i < numMacroblocks; i++) {
// macroblocks[i].print();
// }
}
bool Slice::operator==(const Slice &rhs) const {
bool eq = stream_id == rhs.stream_id &&
packet_type == rhs.packet_type &&
slice_vertical_position_extension == rhs.slice_vertical_position_extension &&
quantiser_scale_code == rhs.quantiser_scale_code &&
slice_extension_flag == rhs.slice_extension_flag &&
intra_slice == rhs.intra_slice &&
slice_picture_id_enable == rhs.slice_picture_id &&
slice_picture_id == rhs.slice_picture_id &&
numMacroblocks == rhs.numMacroblocks;
if (!eq)return eq;
for (int i = 0; i < numMacroblocks; i++) {
if (*macroblocks[i] != *rhs.macroblocks[i])return false;
}
return true;
}
bool Slice::operator!=(const Slice &rhs) const {
return !(rhs == *this);
}
Slice::~Slice() {
for (int i = 0; i < numMacroblocks; i++) {
delete (macroblocks[i]);
}
}
unsigned int Slice::getNumMacroblocks() const {
return numMacroblocks;
}
void Slice::setNumMacroblocks(unsigned int num) {
numMacroblocks = num;
}
Macroblock **Slice::getMacroblocks() const {
return macroblocks;
}
void Slice::setMacroblocks(Macroblock **m) {
macroblocks = m;
}
unsigned char Slice::getQuantiserScaleCode() const {
return quantiser_scale_code;
}
/**
* This function only handles chroma format 4:2:0
*/
void Slice::insertZeroVectorMacroblock(size_t index) {
Macroblock::initializerStruct init = {};
init.forwardMotionVectors = MotionVectors::buildZeroVectors(0); // NOLINT(modernize-use-bool-literals)
init.block_count = 6;
init.macroBlockModes = new MacroblockModes(MacroblockModes::initializerStruct{false, true});
init.macroBlockModes->setFrameMotionType(0b10);
numMacroblocks++;
macroblocks = (Macroblock **) realloc(macroblocks, sizeof(void *) * numMacroblocks);
for (size_t i = numMacroblocks - 2; i >= index; i--) {
macroblocks[i + 1] = macroblocks[i];
}
macroblocks[index] = new Macroblock(init);
}
| 33.293478 | 127 | 0.677114 | Bho007 |
d2d9c93538a0b3c819e97e696dfa2d7d54d06e05 | 3,307 | cpp | C++ | src/betomnita/gameplay/Vehicle.cpp | bilbosz/Betomnita | 23c4679a591bc64c40193fe0e661f35eec85f1b7 | [
"MIT"
] | null | null | null | src/betomnita/gameplay/Vehicle.cpp | bilbosz/Betomnita | 23c4679a591bc64c40193fe0e661f35eec85f1b7 | [
"MIT"
] | 1 | 2018-04-14T08:12:58.000Z | 2018-04-14T08:12:58.000Z | src/betomnita/gameplay/Vehicle.cpp | bilbosz/Betomnita | 23c4679a591bc64c40193fe0e661f35eec85f1b7 | [
"MIT"
] | null | null | null | #include "betomnita/gameplay/Vehicle.hpp"
#include "betomnita/gameplay/GamePlayLogic.hpp"
#include "betomnita/gameplay/Projectile.hpp"
#include "betomnita/gameplay/ProjectilePrototype.hpp"
#include "betomnita/gameplay/PrototypeDict.hpp"
#include "betomnita/gameplay/World.hpp"
#include "game/utils/Utils.hpp"
namespace Betomnita::GamePlay
{
Vehicle::Vehicle()
{
}
void Vehicle::InitPhysics()
{
Chassis.InitPhysics();
Gun.InitPhysics();
}
void Vehicle::Render( sf::RenderTarget& target, const sf::Transform& transform )
{
Chassis.Render( target, transform );
Gun.Render( target, transform );
}
void Vehicle::Update( const sf::Time& dt )
{
if( m_id == 1 )
{
auto physicalBody = Chassis.GetPhysicalBody();
float impulse = 370'000.0f * dt.asSeconds();
auto angle = physicalBody->GetAngle() + Game::Consts::Pi * 0.5f;
if( sf::Keyboard::isKeyPressed( sf::Keyboard::W ) )
{
physicalBody->ApplyLinearImpulseToCenter( b2Vec2( -impulse * cosf( angle ), -impulse * sinf( angle ) ), true );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::S ) )
{
physicalBody->ApplyLinearImpulseToCenter( b2Vec2( impulse * cosf( angle ), impulse * sinf( angle ) ), true );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::A ) )
{
physicalBody->ApplyAngularImpulse( -impulse, true );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::D ) )
{
physicalBody->ApplyAngularImpulse( impulse, true );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Num0 ) )
{
physicalBody->SetAngularVelocity( 0.0f );
physicalBody->SetLinearVelocity( b2Vec2( 0.0f, 0.0f ) );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
{
Gun.SetDirection( Gun.GetDirection() - 1.0f * dt.asSeconds() );
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
{
Gun.SetDirection( Gun.GetDirection() + 1.0f * dt.asSeconds() );
}
}
Chassis.Update( dt );
Gun.Update( dt );
}
void Vehicle::Shot()
{
auto projectile = World->AddProjectile( std::make_unique< Projectile >() );
projectile->LoadFromPrototype( World->GetCurrentLogic()->GetPrototypeDict().GetPrototypeByName( "res/vehicles/projectiles/armor-piercing.svg" ) );
projectile->AssignShooter( this );
projectile->World = World;
float angle = Chassis.GetPhysicalBody()->GetAngle() + Gun.GetDirection();
float impulse = 4'000.0f;
sf::Transform t;
t.rotate( angle * Game::Consts::RadToDeg );
projectile->SetInitialPosition( Gun.GetShotDirection().Destination - t.transformPoint( projectile->GetShotDirection().Source ) );
projectile->SetInitialAngle( angle );
projectile->InitPhysics();
angle += Game::Consts::Pi * 0.5f;
projectile->GetPhysicalBody()->ApplyLinearImpulseToCenter( b2Vec2( -impulse * cosf( angle ), -impulse * sinf( angle ) ), true );
}
}
| 36.340659 | 154 | 0.580284 | bilbosz |