hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10365b22e3bd41148d0f40ca25e38b55cf81651c | 1,517 | hpp | C++ | node_modules/grad-listbuymenu/cfgFunctions.hpp | gruppe-adler/TvT_HoldingPoint.Altis | 685a25e1cab315c877dcc0bbc41cf7d181fdd3f8 | [
"CC-BY-3.0"
] | 1 | 2020-08-31T15:48:28.000Z | 2020-08-31T15:48:28.000Z | node_modules/grad-listbuymenu/cfgFunctions.hpp | AdlerSalbei/TvT_HoldingPoint.Altis | 685a25e1cab315c877dcc0bbc41cf7d181fdd3f8 | [
"CC-BY-3.0"
] | 3 | 2017-01-16T09:25:39.000Z | 2017-02-15T08:35:16.000Z | node_modules/grad-listbuymenu/cfgFunctions.hpp | gruppe-adler/TvT_HoldingPoint.Altis | 685a25e1cab315c877dcc0bbc41cf7d181fdd3f8 | [
"CC-BY-3.0"
] | null | null | null | #ifndef MODULES_DIRECTORY
#define MODULES_DIRECTORY modules
#endif
class GRAD_lbm {
class common {
file = MODULES_DIRECTORY\grad-listBuymenu\functions\common;
class addFunds {};
class addInteraction {};
class checkCargoSpace {};
class getModuleRoot {};
class getPermissionLevel {};
class getPicturePath {};
class getStock {};
class isVehicle {};
class loadBuymenu {};
class rotateModel {};
class setPermissionLevel {};
};
class buy {
file = MODULES_DIRECTORY\grad-listBuymenu\functions\buy;
class buyClient {};
class buyItem {};
class buyServer {};
class buyUnit {};
class buyVehicle {};
class buyWeapon {};
class buyWearable {};
class callCodeClient {};
class callCodeServer {};
class reimburse {};
class vehicleMarker {};
};
class init {
file = MODULES_DIRECTORY\grad-listBuymenu\functions\init;
class initClient {
postInit = 1;
};
class initStocks {
postInit = 1;
};
class initVehicles {
postInit = 1;
};
};
class update {
file = MODULES_DIRECTORY\grad-listBuymenu\functions\update;
class updateBuyButton {};
class updateCategories {};
class updateFunds {};
class updateItemData {};
class updateList {};
class updatePicture {};
};
};
| 25.711864 | 67 | 0.562294 | gruppe-adler |
10377f4601e1190527cb32fa954e6b643ee279df | 36 | hpp | C++ | lib/include/drivers/adc.hpp | niclasberg/asfw | f836de1c0d6350541e3253863dedab6a3eb81df7 | [
"MIT"
] | null | null | null | lib/include/drivers/adc.hpp | niclasberg/asfw | f836de1c0d6350541e3253863dedab6a3eb81df7 | [
"MIT"
] | null | null | null | lib/include/drivers/adc.hpp | niclasberg/asfw | f836de1c0d6350541e3253863dedab6a3eb81df7 | [
"MIT"
] | null | null | null | #pragma once
#include "adc/make.hpp" | 18 | 23 | 0.75 | niclasberg |
103807b73b45150d29886c8b26abc609000a59bf | 9,356 | cpp | C++ | frameworks/render/modules/osg/dmzRenderModuleIsectOSG.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | 2 | 2015-11-05T03:03:43.000Z | 2017-05-15T12:55:39.000Z | frameworks/render/modules/osg/dmzRenderModuleIsectOSG.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | frameworks/render/modules/osg/dmzRenderModuleIsectOSG.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | #include <dmzRenderConsts.h>
#include "dmzRenderModuleIsectOSG.h"
#include <dmzRenderUtilOSG.h>
#include <dmzRenderObjectDataOSG.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzTypesHandleContainer.h>
#include <dmzTypesVector.h>
#include <dmzTypesString.h>
#include <osg/CullFace>
#include <osg/Drawable>
#include <osg/Group>
#include <osg/LineSegment>
#include <osg/Node>
#include <osgUtil/IntersectVisitor>
dmz::RenderModuleIsectOSG::RenderModuleIsectOSG (
const PluginInfo &Info,
const Config &Local) :
Plugin (Info),
RenderModuleIsect (Info),
_log (Info),
_core (0),
_defaultIsectMask (0) {
_init (Local);
}
dmz::RenderModuleIsectOSG::~RenderModuleIsectOSG () {
}
void
dmz::RenderModuleIsectOSG::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_core) {
_core = RenderModuleCoreOSG::cast (PluginPtr);
if (_core) {
_defaultIsectMask = _core->lookup_isect_mask (RenderIsectStaticName);
_defaultIsectMask |= _core->lookup_isect_mask (RenderIsectEntityName);
}
}
}
else if (Mode == PluginDiscoverRemove) {
if (_core && (_core == RenderModuleCoreOSG::cast (PluginPtr))) {
_core = 0;
_defaultIsectMask = 0;
}
}
}
dmz::Boolean
dmz::RenderModuleIsectOSG::do_isect (
const IsectParameters &Parameters,
const IsectTestContainer &TestValues,
IsectResultContainer &resultContainer) {
if (_core) {
osg::ref_ptr<osg::Group> scene = _core->get_isect ();
// osg::ref_ptr<osg::Group> scene = _core->get_static_objects ();
osg::BoundingSphere bs = scene->getBound();
std::vector<osg::LineSegment*> lsList;// = new osg::LineSegment[TestValues];
UInt32 mask (_defaultIsectMask);
HandleContainer attrList;
if (Parameters.get_isect_attributes (attrList)) {
mask = 0;
HandleContainerIterator it;
Handle attr (0);
while (attrList.get_next (it, attr)) { mask |= _core->lookup_isect_mask (attr); }
}
osgUtil::IntersectVisitor visitor;
visitor.setTraversalMask (mask);
UInt32 testHandle;
IsectTestTypeEnum testType;
Vector vec1, vec2;
std::vector<UInt32> handleArray;
std::vector<Vector> sourceArray;
TestValues.get_first_test (testHandle, testType, vec1, vec2);
do {
if (testType == IsectRayTest) {
vec2 = (vec1 + (vec2 * (bs.radius () * 2)));
}
osg::LineSegment *ls = new osg::LineSegment;
ls->set (to_osg_vector (vec1), to_osg_vector (vec2));
visitor.addLineSegment (ls);
lsList.push_back (ls);
handleArray.push_back (testHandle);
sourceArray.push_back (vec1);
} while (TestValues.get_next_test (testHandle, testType, vec1, vec2));
scene->accept (visitor);
IsectTestResultTypeEnum param = Parameters.get_test_result_type ();
bool closestPoint = (param == IsectClosestPoint);
bool firstPoint = (param == IsectFirstPoint);
if (closestPoint && !Parameters.get_calculate_distance ()) {
firstPoint = true;
closestPoint = false;
}
Boolean result (False);
for (unsigned int ix = 0; ix < lsList.size () && !result; ix++) {
osgUtil::IntersectVisitor::HitList resultHits;
resultHits = visitor.getHitList (lsList[ix]);
if (!resultHits.empty ()) {
for (unsigned int jy = 0; jy < resultHits.size (); jy++) {
Handle objHandle (0);
osgUtil::Hit currentHit = resultHits[jy];
Boolean disabled (False);
osg::CullFace *cf (0);
osg::NodePath path = currentHit.getNodePath ();
for (
osg::NodePath::iterator it = path.begin ();
(it != path.end ()) && !disabled;
it++) {
osg::Node *node (*it);
if (node) {
osg::StateSet *sSet = (node->getStateSet ());
if (sSet) {
osg::CullFace *cfTmp (
(osg::CullFace*)(sSet->getAttribute (
osg::StateAttribute::CULLFACE)));
if (cfTmp) { cf = cfTmp; }
}
osg::Referenced *r (node->getUserData ());
if (r) {
RenderObjectDataOSG *data (
dynamic_cast<RenderObjectDataOSG *> (r));
if (data) {
if (!data->do_isect ()) {
// Should never reach here now
disabled = True;
}
else { objHandle = data->get_handle (); }
}
}
}
}
if (!disabled) {
Vector lsPoint = to_dmz_vector (currentHit.getWorldIntersectPoint ());
IsectResult lsResult;
lsResult.set_isect_test_id (handleArray[ix]);
lsResult.set_point (lsPoint);
if (Parameters.get_calculate_object_handle ()) {
lsResult.set_object_handle (objHandle);
}
if (Parameters.get_calculate_normal ()) {
lsResult.set_normal (
to_dmz_vector (currentHit.getWorldIntersectNormal ()));
}
if (Parameters.get_calculate_distance ()) {
lsResult.set_distance ((lsPoint - sourceArray[ix]).magnitude ());
}
if (Parameters.get_calculate_cull_mode ()) {
UInt32 cullMask = 0;
if (cf) {
if (cf->getMode () == osg::CullFace::FRONT ||
cf->getMode () == osg::CullFace::FRONT_AND_BACK) {
cullMask |= IsectPolygonFrontCulledMask;
}
if (cf->getMode () == osg::CullFace::BACK ||
cf->getMode () == osg::CullFace::FRONT_AND_BACK) {
cullMask |= IsectPolygonBackCulledMask;
}
}
else { cullMask |= IsectPolygonBackCulledMask; }
lsResult.set_cull_mode (cullMask);
}
if (Parameters.get_calculate_object_handle ()) {
osg::Geode *hitObject = currentHit.getGeode ();
}
resultContainer.add_result (lsResult);
if (firstPoint) {
result = true;
}
}
}
}
}
if (closestPoint && resultContainer.get_result_count () > 1) {
IsectResult current;
resultContainer.get_first (current);
IsectResult closest (current);
double closestDist;
current.get_distance (closestDist);
while (resultContainer.get_next (current)) {
double testDist;
if (current.get_distance (testDist)) {
if (testDist < closestDist) {
closest = current;
}
}
}
IsectResultContainer closestContainer;
closestContainer.add_result (closest);
resultContainer = closestContainer;
}
}
return resultContainer.get_result_count () > 0;
}
dmz::UInt32
dmz::RenderModuleIsectOSG::enable_isect (const Handle ObjectHandle) {
UInt32 result (0);
if (_core) {
osg::Group *g (_core->lookup_dynamic_object (ObjectHandle));
if (g) {
RenderObjectDataOSG *data (
dynamic_cast<RenderObjectDataOSG *> (g->getUserData ()));
if (data) {
result = UInt32 (data->enable_isect ());
if (0 == result) {
UInt32 mask = g->getNodeMask ();
mask |= data->get_mask ();
g->setNodeMask (mask);
}
}
}
}
return result;
}
dmz::UInt32
dmz::RenderModuleIsectOSG::disable_isect (const Handle ObjectHandle) {
UInt32 result (0);
if (_core) {
osg::Group *g (_core->lookup_dynamic_object (ObjectHandle));
if (g) {
RenderObjectDataOSG *data (
dynamic_cast<RenderObjectDataOSG *> (g->getUserData ()));
if (data) {
result = UInt32 (data->disable_isect ());
if (1 == result) {
UInt32 mask = g->getNodeMask ();
data->set_mask (mask & _defaultIsectMask);
mask &= (~_defaultIsectMask);
g->setNodeMask (mask);
}
}
}
}
return result;
}
void
dmz::RenderModuleIsectOSG::_init (const Config &Local) {
}
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzRenderModuleIsectOSG (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::RenderModuleIsectOSG (Info, local);
}
};
| 25.016043 | 90 | 0.525973 | dmzgroup |
103902cac236f8a988d05f01197ad080a846cfd2 | 1,180 | cpp | C++ | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab Final/main(3).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab Final/main(3).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab Final/main(3).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | #include <iostream>
#include "binarysearchtree.h"
#include "binarysearchtree.cpp"
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = nullptr;
return node;
}
void inorder(Node* root)
{
if (root == nullptr)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
Node* insert(Node* root, int key)
{
if (root == nullptr)
return newNode(key);
if (key < root->data)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
int findSum(Node* root)
{
if (root == nullptr)
return 0;
return root->data + findSum(root->left) + findSum(root->right);
}
void update(Node* root, int &sum)
{
if (root == nullptr)
return;
update(root->left, sum);
sum = sum - root->data;
root->data += sum;
update(root->right, sum);
}
int main()
{
Node* root = nullptr;
int keys[] = { 5, 3, 2, 4, 6, 8, 10 };
int n = sizeof(keys)/sizeof(keys[0]);
for (int key : keys)
root = insert(root, key);
int sum = findSum(root);
update(root, sum);
inorder(root);
return 0;
}
| 12.967033 | 64 | 0.616949 | diptu |
103bba595724b6413cd8334d43d429aa9c5f1a98 | 1,410 | hpp | C++ | libs/dmlf/include/dmlf/collective_learning/client_params.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | null | null | null | libs/dmlf/include/dmlf/collective_learning/client_params.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | null | null | null | libs/dmlf/include/dmlf/collective_learning/client_params.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | null | null | null | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "math/base_types.hpp"
namespace fetch {
namespace dmlf {
namespace collective_learning {
template <typename DataType>
struct ClientParams
{
using SizeType = fetch::math::SizeType;
SizeType n_algorithms_per_client = 1;
SizeType batch_size{};
SizeType max_updates;
DataType learning_rate;
bool print_loss = false;
std::vector<std::string> input_names = {"Input"};
std::string label_name = "Label";
std::string error_name = "Error";
std::string results_dir = ".";
};
} // namespace collective_learning
} // namespace dmlf
} // namespace fetch
| 30 | 80 | 0.619858 | devjsc |
103c81feea8781325ba84e138b234bfbcf5721c1 | 598 | cc | C++ | erizoAPI/addon.cc | winlinvip/licode | ee4f012147264c29cc6d8282f2a573b801a2454b | [
"MIT"
] | 1 | 2018-08-21T03:59:44.000Z | 2018-08-21T03:59:44.000Z | erizoAPI/addon.cc | winlinvip/licode | ee4f012147264c29cc6d8282f2a573b801a2454b | [
"MIT"
] | null | null | null | erizoAPI/addon.cc | winlinvip/licode | ee4f012147264c29cc6d8282f2a573b801a2454b | [
"MIT"
] | 1 | 2018-08-21T03:59:47.000Z | 2018-08-21T03:59:47.000Z | #ifndef BUILDING_NODE_EXTENSION
#define BUILDING_NODE_EXTENSION
#endif
#include <nan.h>
#include "WebRtcConnection.h"
#include "OneToManyProcessor.h"
#include "OneToManyTranscoder.h"
#include "SyntheticInput.h"
#include "ExternalInput.h"
#include "ExternalOutput.h"
#include "ThreadPool.h"
#include "IOThreadPool.h"
NAN_MODULE_INIT(InitAll) {
WebRtcConnection::Init(target);
OneToManyProcessor::Init(target);
ExternalInput::Init(target);
ExternalOutput::Init(target);
SyntheticInput::Init(target);
ThreadPool::Init(target);
IOThreadPool::Init(target);
}
NODE_MODULE(addon, InitAll)
| 23.92 | 35 | 0.779264 | winlinvip |
103ca24d6f03bd2def6c7cb404e11020d3be086b | 22,248 | cpp | C++ | ngraph/test/backend/detection_output.in.cpp | MikhailPedus/openvino | 5f9ef0cf26543b3dde80b3b2bfc7e996e7c55d5b | [
"Apache-2.0"
] | null | null | null | ngraph/test/backend/detection_output.in.cpp | MikhailPedus/openvino | 5f9ef0cf26543b3dde80b3b2bfc7e996e7c55d5b | [
"Apache-2.0"
] | 27 | 2020-12-29T14:38:34.000Z | 2022-02-21T13:04:03.000Z | ngraph/test/backend/detection_output.in.cpp | dorloff/openvino | 1c3848a96fdd325b044babe6d5cd26db341cf85b | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2020 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.
//*****************************************************************************
// clang-format off
#ifdef ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#define DEFAULT_FLOAT_TOLERANCE_BITS ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#endif
#ifdef ${BACKEND_NAME}_DOUBLE_TOLERANCE_BITS
#define DEFAULT_DOUBLE_TOLERANCE_BITS ${BACKEND_NAME}_DOUBLE_TOLERANCE_BITS
#endif
// clang-format on
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/engine/test_engines.hpp"
#include "util/test_case.hpp"
#include "util/test_control.hpp"
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
using TestEngine = test::ENGINE_CLASS_NAME(${BACKEND_NAME});
NGRAPH_TEST(${BACKEND_NAME}, detection_output_3_inputs)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 3;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = true;
attrs.keep_top_k = {2};
attrs.code_type = "caffe.PriorBoxParameter.CORNER";
attrs.share_location = false;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 2;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
1, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto f = make_shared<Function>(make_shared<op::DetectionOutput>(loc, conf, prior_boxes, attrs),
ParameterVector{loc, conf, prior_boxes});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0, class 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 0, class 1
0.3,
0.2,
0.5,
0.3,
0.2,
0.1,
0.42,
0.66,
// batch 0, class 2
0.05,
0.1,
0.2,
0.3,
0.2,
0.1,
0.33,
0.44,
// batch 1, class 0
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
// batch 1, class 1
0.1,
0.2,
0.5,
0.3,
0.1,
0.1,
0.12,
0.34,
// batch 1, class 2
0.25,
0.11,
0.4,
0.32,
0.2,
0.12,
0.38,
0.24,
});
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
0,
0.2,
// batch 1
0.7,
0.8,
0.42,
0.33,
0.81,
0.2,
});
test_case.add_input<float>({
// prior box 0
0.0,
0.5,
0.1,
0.2,
// prior box 1
0.0,
0.3,
0.1,
0.35,
});
Shape output_shape{1, 1, num_images * static_cast<size_t>(attrs.keep_top_k[0]), 7};
test_case.add_expected_output<float>(
output_shape, {0, 0, 0.7, 0.2, 0.4, 0.52, 1, 0, 1, 0.9, 0, 0.6, 0.3, 0.35,
1, 1, 0.81, 0.25, 0.41, 0.5, 0.67, 1, 1, 0.8, 0.1, 0.55, 0.3, 0.45});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, detection_output_3_inputs_share_location)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 3;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = true;
attrs.keep_top_k = {2};
attrs.code_type = "caffe.PriorBoxParameter.CORNER";
attrs.share_location = true;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 2;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
num_images, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto f = make_shared<Function>(make_shared<op::DetectionOutput>(loc, conf, prior_boxes, attrs),
ParameterVector{loc, conf, prior_boxes});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 1
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
});
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
0,
0.2,
// batch 1
0.7,
0.8,
0.42,
0.33,
0.81,
0.2,
});
test_case.add_input<float>({
// batch 0
0.0,
0.5,
0.1,
0.2,
0.0,
0.3,
0.1,
0.35,
// batch 1
0.33,
0.2,
0.52,
0.37,
0.22,
0.1,
0.32,
0.36,
});
Shape output_shape{1, 1, num_images * static_cast<size_t>(attrs.keep_top_k[0]), 7};
test_case.add_expected_output<float>(output_shape,
{
0, 0, 0.7, 0, 0.4, 0.3, 0.5, 0, 1, 0.9,
0.1, 0.6, 0.3, 0.4, 1, 1, 0.81, 0.32, 0.15, 0.52,
0.61, 1, 1, 0.8, 0.53, 0.3, 0.92, 0.57,
});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, detection_output_3_inputs_normalized)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 3;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = true;
attrs.keep_top_k = {2};
attrs.code_type = "caffe.PriorBoxParameter.CORNER";
attrs.share_location = true;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 2;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
num_images, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto f = make_shared<Function>(make_shared<op::DetectionOutput>(loc, conf, prior_boxes, attrs),
ParameterVector{loc, conf, prior_boxes});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 1
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
});
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
0,
0.2,
// batch 1
0.7,
0.8,
0.42,
0.33,
0.81,
0.2,
});
test_case.add_input<float>({
// batch 0
0.0,
0.5,
0.1,
0.2,
0.0,
0.3,
0.1,
0.35,
// batch 1
0.33,
0.2,
0.52,
0.37,
0.22,
0.1,
0.32,
0.36,
});
Shape output_shape{1, 1, num_images * static_cast<size_t>(attrs.keep_top_k[0]), 7};
test_case.add_expected_output<float>(output_shape,
{
0, 0, 0.7, 0, 0.4, 0.3, 0.5, 0, 1, 0.9,
0.1, 0.6, 0.3, 0.4, 1, 1, 0.81, 0.32, 0.15, 0.52,
0.61, 1, 1, 0.8, 0.53, 0.3, 0.92, 0.57,
});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, detection_output_3_inputs_keep_all_bboxes)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 2;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = false;
attrs.keep_top_k = {-1};
attrs.code_type = "caffe.PriorBoxParameter.CORNER";
attrs.share_location = false;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 3;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
num_images, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto f = make_shared<Function>(make_shared<op::DetectionOutput>(loc, conf, prior_boxes, attrs),
ParameterVector{loc, conf, prior_boxes});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0, class 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 0, class 1
0.3,
0.2,
0.5,
0.3,
0.2,
0.1,
0.42,
0.66,
// batch 1, class 0
0.05,
0.1,
0.2,
0.3,
0.2,
0.1,
0.33,
0.44,
// batch 1, class 1
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
// batch 2, class 0
0.1,
0.2,
0.5,
0.3,
0.1,
0.1,
0.12,
0.34,
// batch 2, class 1
0.25,
0.11,
0.4,
0.32,
0.2,
0.12,
0.38,
0.24,
});
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
// batch 1
0.7,
0.8,
0.42,
0.33,
// batch 1
0.1,
0.2,
0.32,
0.43,
});
test_case.add_input<float>({
// batch 0 priors
0.0,
0.5,
0.1,
0.2,
0.0,
0.3,
0.1,
0.35,
// batch 0 variances
0.12,
0.11,
0.32,
0.02,
0.02,
0.20,
0.09,
0.71,
// batch 1 priors
0.33,
0.2,
0.52,
0.37,
0.22,
0.1,
0.32,
0.36,
// batch 1 variances
0.01,
0.07,
0.12,
0.13,
0.41,
0.33,
0.2,
0.1,
// batch 2 priors
0.0,
0.3,
0.1,
0.35,
0.22,
0.1,
0.32,
0.36,
// batch 2 variances
0.32,
0.02,
0.13,
0.41,
0.33,
0.2,
0.02,
0.20,
});
Shape output_shape{1, 1, num_images * attrs.num_classes * num_prior_boxes, 7};
test_case.add_expected_output<float>(
output_shape,
{
0, 0, 0.4, 0.006, 0.34, 0.145, 0.563, 0, 1, 0.9, 0, 0.511, 0.164, 0.203,
0, 1, 0.7, 0.004, 0.32, 0.1378, 0.8186, 1, 0, 0.7, 0.3305, 0.207, 0.544, 0.409,
1, 0, 0.42, 0.302, 0.133, 0.4, 0.38, 1, 1, 0.8, 0.332, 0.207, 0.5596, 0.4272,
1, 1, 0.33, 0.261, 0.1165, 0.36, 0.385, 2, 0, 0.32, 0.3025, 0.122, 0.328, 0.424,
2, 1, 0.43, 0.286, 0.124, 0.3276, 0.408, -1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, detection_output_3_inputs_center_size)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 3;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = true;
attrs.keep_top_k = {2};
attrs.code_type = "caffe.PriorBoxParameter.CENTER_SIZE";
attrs.share_location = false;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 2;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
num_images, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto f = make_shared<Function>(make_shared<op::DetectionOutput>(loc, conf, prior_boxes, attrs),
ParameterVector{loc, conf, prior_boxes});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0, class 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 0, class 1
0.3,
0.2,
0.5,
0.3,
0.2,
0.1,
0.42,
0.66,
// batch 0, class 2
0.05,
0.1,
0.2,
0.3,
0.2,
0.1,
0.33,
0.44,
// batch 1, class 0
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
// batch 1, class 1
0.1,
0.2,
0.5,
0.3,
0.1,
0.1,
0.12,
0.34,
// batch 1, class 2
0.25,
0.11,
0.4,
0.32,
0.2,
0.12,
0.38,
0.24,
});
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
0,
0.2,
// batch 1
0.7,
0.8,
0.42,
0.33,
0.81,
0.2,
});
test_case.add_input<float>({
// batch 0
0.0,
0.5,
0.1,
0.2,
0.0,
0.3,
0.1,
0.35,
// batch 1
0.33,
0.2,
0.52,
0.37,
0.22,
0.1,
0.32,
0.36,
});
Shape output_shape{1, 1, num_images * static_cast<size_t>(attrs.keep_top_k[0]), 7};
test_case.add_expected_output<float>(
output_shape,
{
0, 0, 0.7, 0, 0.28163019, 0.14609808, 0.37836978,
0, 1, 0.9, 0, 0.49427515, 0.11107014, 0.14572485,
1, 1, 0.81, 0.22040875, 0.079573378, 0.36959124, 0.4376266,
1, 1, 0.8, 0.32796675, 0.18435785, 0.56003326, 0.40264216,
});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, detection_output_5_inputs)
{
op::DetectionOutputAttrs attrs;
attrs.num_classes = 2;
attrs.background_label_id = -1;
attrs.top_k = -1;
attrs.variance_encoded_in_target = true;
attrs.keep_top_k = {2};
attrs.code_type = "caffe.PriorBoxParameter.CORNER";
attrs.share_location = false;
attrs.nms_threshold = 0.5;
attrs.confidence_threshold = 0.3;
attrs.clip_after_nms = false;
attrs.clip_before_nms = true;
attrs.decrease_label_id = false;
attrs.normalized = true;
attrs.input_height = 0;
attrs.input_width = 0;
attrs.objectness_score = 0.6;
size_t num_prior_boxes = 2;
size_t num_loc_classes = attrs.share_location ? 1 : attrs.num_classes;
size_t prior_box_size = attrs.normalized ? 4 : 5;
size_t num_images = 2;
Shape loc_shape{num_images, num_prior_boxes * num_loc_classes * prior_box_size};
Shape conf_shape{num_images, num_prior_boxes * attrs.num_classes};
Shape prior_boxes_shape{
num_images, attrs.variance_encoded_in_target ? 1UL : 2UL, num_prior_boxes * prior_box_size};
auto loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto prior_boxes = make_shared<op::Parameter>(element::f32, prior_boxes_shape);
auto aux_loc = make_shared<op::Parameter>(element::f32, loc_shape);
auto aux_conf = make_shared<op::Parameter>(element::f32, conf_shape);
auto f = make_shared<Function>(
make_shared<op::DetectionOutput>(loc, conf, prior_boxes, aux_conf, aux_loc, attrs),
ParameterVector{loc, conf, prior_boxes, aux_conf, aux_loc});
auto test_case = test::TestCase<TestEngine>(f);
// locations
test_case.add_input<float>({
// batch 0, class 0
0.1,
0.1,
0.2,
0.2,
0.0,
0.1,
0.2,
0.15,
// batch 0, class 1
0.3,
0.2,
0.5,
0.3,
0.2,
0.1,
0.42,
0.66,
// batch 1, class 0
0.2,
0.1,
0.4,
0.2,
0.1,
0.05,
0.2,
0.25,
// batch 1, class 1
0.1,
0.2,
0.5,
0.3,
0.1,
0.1,
0.12,
0.34,
});
// confidence
test_case.add_input<float>({
// batch 0
0.1,
0.9,
0.4,
0.7,
// batch 1
0.42,
0.33,
0.81,
0.2,
});
// prior boxes
test_case.add_input<float>({
// batch 0
0.0,
0.5,
0.1,
0.2,
0.0,
0.3,
0.1,
0.35,
// batch 1
0.33,
0.2,
0.52,
0.37,
0.22,
0.1,
0.32,
0.36,
});
// aux conf
test_case.add_input<float>({
// batch 0
0.1,
0.3,
0.5,
0.8,
// batch 1
0.5,
0.8,
0.01,
0.1,
});
// aux locations
test_case.add_input<float>({
// batch 0, class 0
0.1,
0.2,
0.5,
0.3,
0.1,
0.1,
0.12,
0.34,
// batch 0, class 1
0.25,
0.11,
0.4,
0.32,
0.2,
0.12,
0.38,
0.24,
// batch 1, class 0
0.3,
0.2,
0.5,
0.3,
0.2,
0.1,
0.42,
0.66,
// batch 1, class 1
0.05,
0.1,
0.2,
0.3,
0.2,
0.1,
0.33,
0.44,
});
Shape output_shape{1, 1, num_images * static_cast<size_t>(attrs.keep_top_k[0]), 7};
test_case.add_expected_output<float>(
output_shape,
{
0, 0, 0.4, 0.55, 0.61, 1, 0.97, 0, 1, 0.7, 0.4, 0.52, 0.9, 1,
1, 0, 0.42, 0.83, 0.5, 1, 0.87, 1, 1, 0.33, 0.63, 0.35, 1, 1,
});
test_case.run();
}
| 25.484536 | 100 | 0.502247 | MikhailPedus |
103cd6311a5b2270ba19ff696c286cc96cffd054 | 19,920 | cpp | C++ | Libraries/RobsJuceModules/rosic/_third_party/angelscript/as_module.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/rosic/_third_party/angelscript/as_module.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/rosic/_third_party/angelscript/as_module.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | /*
AngelCode Scripting Library
Copyright (c) 2003-2007 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_module.cpp
//
// A class that holds a script module
//
#include "as_config.h"
#include "as_module.h"
#include "as_builder.h"
#include "as_context.h"
BEGIN_AS_NAMESPACE
asCModule::asCModule(const char *name, int id, asCScriptEngine *engine)
{
this->name = name;
this->engine = engine;
this->moduleID = id;
builder = 0;
isDiscarded = false;
isBuildWithoutErrors = false;
contextCount = 0;
moduleCount = 0;
isGlobalVarInitialized = false;
initFunction = 0;
}
asCModule::~asCModule()
{
Reset();
if( builder )
{
DELETE(builder,asCBuilder);
builder = 0;
}
// Remove the module from the engine
if( engine )
{
if( engine->lastModule == this )
engine->lastModule = 0;
int index = (moduleID >> 16);
engine->scriptModules[index] = 0;
}
}
int asCModule::AddScriptSection(const char *name, const char *code, int codeLength, int lineOffset, bool makeCopy)
{
if( !builder )
builder = NEW(asCBuilder)(engine, this);
builder->AddCode(name, code, codeLength, lineOffset, (int)builder->scripts.GetLength(), makeCopy);
return asSUCCESS;
}
int asCModule::Build()
{
assert( contextCount == 0 );
Reset();
if( !builder )
return asSUCCESS;
// Store the section names
for( size_t n = 0; n < builder->scripts.GetLength(); n++ )
{
asCString *sectionName = NEW(asCString)(builder->scripts[n]->name);
scriptSections.PushLast(sectionName);
}
// Compile the script
int r = builder->Build();
DELETE(builder,asCBuilder);
builder = 0;
if( r < 0 )
{
// Reset module again
Reset();
isBuildWithoutErrors = false;
return r;
}
isBuildWithoutErrors = true;
engine->PrepareEngine();
CallInit();
return r;
}
int asCModule::ResetGlobalVars()
{
if( !isGlobalVarInitialized ) return asERROR;
CallExit();
CallInit();
return 0;
}
void asCModule::CallInit()
{
if( isGlobalVarInitialized ) return;
memset(globalMem.AddressOf(), 0, globalMem.GetLength()*sizeof(asDWORD));
if( initFunction && initFunction->byteCode.GetLength() == 0 ) return;
int id = asFUNC_INIT;
asIScriptContext *ctx = 0;
int r = engine->CreateContext(&ctx, true);
if( r >= 0 && ctx )
{
// TODO: Add error handling
((asCContext*)ctx)->PrepareSpecial(id, this);
ctx->Execute();
ctx->Release();
ctx = 0;
}
isGlobalVarInitialized = true;
}
void asCModule::CallExit()
{
if( !isGlobalVarInitialized ) return;
for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
{
if( scriptGlobals[n]->type.IsObject() )
{
void *obj = *(void**)(globalMem.AddressOf() + scriptGlobals[n]->index);
if( obj )
{
asCObjectType *ot = scriptGlobals[n]->type.GetObjectType();
if( ot->beh.release )
engine->CallObjectMethod(obj, ot->beh.release);
else
{
if( ot->beh.destruct )
engine->CallObjectMethod(obj, ot->beh.destruct);
engine->CallFree(ot, obj);
}
}
}
}
isGlobalVarInitialized = false;
}
void asCModule::Discard()
{
isDiscarded = true;
}
void asCModule::Reset()
{
assert( !IsUsed() );
CallExit();
// Free global variables
globalMem.SetLength(0);
globalVarPointers.SetLength(0);
isBuildWithoutErrors = true;
isDiscarded = false;
if( initFunction )
{
engine->DeleteScriptFunction(initFunction->id);
initFunction = 0;
}
size_t n;
for( n = 0; n < scriptFunctions.GetLength(); n++ )
engine->DeleteScriptFunction(scriptFunctions[n]->id);
scriptFunctions.SetLength(0);
for( n = 0; n < importedFunctions.GetLength(); n++ )
{
DELETE(importedFunctions[n],asCScriptFunction);
}
importedFunctions.SetLength(0);
// Release bound functions
for( n = 0; n < bindInformations.GetLength(); n++ )
{
int oldFuncID = bindInformations[n].importedFunction;
if( oldFuncID != -1 )
{
asCModule *oldModule = engine->GetModuleFromFuncId(oldFuncID);
if( oldModule != 0 )
{
// Release reference to the module
oldModule->ReleaseModuleRef();
}
}
}
bindInformations.SetLength(0);
for( n = 0; n < stringConstants.GetLength(); n++ )
{
DELETE(stringConstants[n],asCString);
}
stringConstants.SetLength(0);
for( n = 0; n < scriptGlobals.GetLength(); n++ )
{
DELETE(scriptGlobals[n],asCProperty);
}
scriptGlobals.SetLength(0);
for( n = 0; n < scriptSections.GetLength(); n++ )
{
DELETE(scriptSections[n],asCString);
}
scriptSections.SetLength(0);
for( n = 0; n < classTypes.GetLength(); n++ )
classTypes[n]->refCount--;
classTypes.SetLength(0);
// Release all used object types
for( n = 0; n < usedTypes.GetLength(); n++ )
usedTypes[n]->refCount--;
usedTypes.SetLength(0);
// Release all config groups
for( n = 0; n < configGroups.GetLength(); n++ )
configGroups[n]->Release();
configGroups.SetLength(0);
}
int asCModule::GetFunctionIDByName(const char *name)
{
if( isBuildWithoutErrors == false )
return asERROR;
// TODO: Improve linear search
// Find the function id
int id = -1;
for( size_t n = 0; n < scriptFunctions.GetLength(); n++ )
{
if( scriptFunctions[n]->name == name )
{
if( id == -1 )
id = scriptFunctions[n]->id;
else
return asMULTIPLE_FUNCTIONS;
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
int asCModule::GetMethodIDByDecl(asCObjectType *ot, const char *decl)
{
if( isBuildWithoutErrors == false )
return asERROR;
return engine->GetMethodIDByDecl(ot, decl, this);
}
int asCModule::GetImportedFunctionCount()
{
if( isBuildWithoutErrors == false )
return asERROR;
return (int)importedFunctions.GetLength();
}
int asCModule::GetImportedFunctionIndexByDecl(const char *decl)
{
if( isBuildWithoutErrors == false )
return asERROR;
asCBuilder bld(engine, this);
asCScriptFunction func(this);
bld.ParseFunctionDeclaration(decl, &func);
// TODO: Improve linear search
// Search script functions for matching interface
int id = -1;
for( asUINT n = 0; n < importedFunctions.GetLength(); ++n )
{
if( func.name == importedFunctions[n]->name &&
func.returnType == importedFunctions[n]->returnType &&
func.parameterTypes.GetLength() == importedFunctions[n]->parameterTypes.GetLength() )
{
bool match = true;
for( asUINT p = 0; p < func.parameterTypes.GetLength(); ++p )
{
if( func.parameterTypes[p] != importedFunctions[n]->parameterTypes[p] )
{
match = false;
break;
}
}
if( match )
{
if( id == -1 )
id = n;
else
return asMULTIPLE_FUNCTIONS;
}
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
int asCModule::GetFunctionCount()
{
if( isBuildWithoutErrors == false )
return asERROR;
return (int)scriptFunctions.GetLength();
}
int asCModule::GetFunctionIDByDecl(const char *decl)
{
if( isBuildWithoutErrors == false )
return asERROR;
asCBuilder bld(engine, this);
asCScriptFunction func(this);
int r = bld.ParseFunctionDeclaration(decl, &func);
if( r < 0 )
return asINVALID_DECLARATION;
// TODO: Improve linear search
// Search script functions for matching interface
int id = -1;
for( size_t n = 0; n < scriptFunctions.GetLength(); ++n )
{
if( scriptFunctions[n]->objectType == 0 &&
func.name == scriptFunctions[n]->name &&
func.returnType == scriptFunctions[n]->returnType &&
func.parameterTypes.GetLength() == scriptFunctions[n]->parameterTypes.GetLength() )
{
bool match = true;
for( size_t p = 0; p < func.parameterTypes.GetLength(); ++p )
{
if( func.parameterTypes[p] != scriptFunctions[n]->parameterTypes[p] )
{
match = false;
break;
}
}
if( match )
{
if( id == -1 )
id = scriptFunctions[n]->id;
else
return asMULTIPLE_FUNCTIONS;
}
}
}
if( id == -1 ) return asNO_FUNCTION;
return id;
}
int asCModule::GetGlobalVarCount()
{
if( isBuildWithoutErrors == false )
return asERROR;
return (int)scriptGlobals.GetLength();
}
int asCModule::GetGlobalVarIDByName(const char *name)
{
if( isBuildWithoutErrors == false )
return asERROR;
// Find the global var id
int id = -1;
for( size_t n = 0; n < scriptGlobals.GetLength(); n++ )
{
if( scriptGlobals[n]->name == name )
{
id = (int)n;
break;
}
}
if( id == -1 ) return asNO_GLOBAL_VAR;
return moduleID | id;
}
int asCModule::GetGlobalVarIDByDecl(const char *decl)
{
if( isBuildWithoutErrors == false )
return asERROR;
asCBuilder bld(engine, this);
asCProperty gvar;
bld.ParseVariableDeclaration(decl, &gvar);
// TODO: Improve linear search
// Search script functions for matching interface
int id = -1;
for( size_t n = 0; n < scriptGlobals.GetLength(); ++n )
{
if( gvar.name == scriptGlobals[n]->name &&
gvar.type == scriptGlobals[n]->type )
{
id = (int)n;
break;
}
}
if( id == -1 ) return asNO_GLOBAL_VAR;
return moduleID | id;
}
int asCModule::AddConstantString(const char *str, size_t len)
{
// The str may contain null chars, so we cannot use strlen, or strcmp, or strcpy
asCString *cstr = NEW(asCString)(str, len);
// TODO: Improve linear search
// Has the string been registered before?
for( size_t n = 0; n < stringConstants.GetLength(); n++ )
{
if( *stringConstants[n] == *cstr )
{
DELETE(cstr,asCString);
return (int)n;
}
}
// No match was found, add the string
stringConstants.PushLast(cstr);
return (int)stringConstants.GetLength() - 1;
}
const asCString &asCModule::GetConstantString(int id)
{
return *stringConstants[id];
}
int asCModule::GetNextFunctionId()
{
return engine->GetNextScriptFunctionId();
}
int asCModule::GetNextImportedFunctionId()
{
return FUNC_IMPORTED | (asUINT)importedFunctions.GetLength();
}
int asCModule::AddScriptFunction(int sectionIdx, int id, const char *name, const asCDataType &returnType, asCDataType *params, int *inOutFlags, int paramCount, bool isInterface, asCObjectType *objType)
{
assert(id >= 0);
// Store the function information
asCScriptFunction *func = NEW(asCScriptFunction)(this);
func->funcType = isInterface ? asFUNC_INTERFACE : asFUNC_SCRIPT;
func->name = name;
func->id = id;
func->returnType = returnType;
func->scriptSectionIdx = sectionIdx;
for( int n = 0; n < paramCount; n++ )
{
func->parameterTypes.PushLast(params[n]);
func->inOutFlags.PushLast(inOutFlags[n]);
}
func->objectType = objType;
scriptFunctions.PushLast(func);
engine->SetScriptFunction(func);
// Compute the signature id
if( objType )
func->ComputeSignatureId(engine);
return 0;
}
int asCModule::AddImportedFunction(int id, const char *name, const asCDataType &returnType, asCDataType *params, int *inOutFlags, int paramCount, int moduleNameStringID)
{
assert(id >= 0);
// Store the function information
asCScriptFunction *func = NEW(asCScriptFunction)(this);
func->funcType = asFUNC_IMPORTED;
func->name = name;
func->id = id;
func->returnType = returnType;
for( int n = 0; n < paramCount; n++ )
{
func->parameterTypes.PushLast(params[n]);
func->inOutFlags.PushLast(inOutFlags[n]);
}
func->objectType = 0;
importedFunctions.PushLast(func);
sBindInfo info;
info.importedFunction = -1;
info.importFrom = moduleNameStringID;
bindInformations.PushLast(info);
return 0;
}
asCScriptFunction *asCModule::GetScriptFunction(int funcID)
{
return engine->scriptFunctions[funcID & 0xFFFF];
}
asCScriptFunction *asCModule::GetImportedFunction(int funcID)
{
return importedFunctions[funcID & 0xFFFF];
}
asCScriptFunction *asCModule::GetSpecialFunction(int funcID)
{
if( funcID & FUNC_IMPORTED )
return importedFunctions[funcID & 0xFFFF];
else
{
if( (funcID & 0xFFFF) == asFUNC_INIT )
return initFunction;
else if( (funcID & 0xFFFF) == asFUNC_STRING )
{
assert(false);
}
return engine->scriptFunctions[funcID & 0xFFFF];
}
}
int asCModule::AllocGlobalMemory(int size)
{
int index = (int)globalMem.GetLength();
size_t *start = globalMem.AddressOf();
globalMem.SetLength(index + size);
// Update the addresses in the globalVarPointers
for( size_t n = 0; n < globalVarPointers.GetLength(); n++ )
{
if( globalVarPointers[n] >= start && globalVarPointers[n] < (start+index) )
globalVarPointers[n] = &globalMem[0] + (size_t(globalVarPointers[n]) - size_t(start))/sizeof(void*);
}
return index;
}
int asCModule::AddContextRef()
{
ENTERCRITICALSECTION(criticalSection);
int r = ++contextCount;
LEAVECRITICALSECTION(criticalSection);
return r;
}
int asCModule::ReleaseContextRef()
{
ENTERCRITICALSECTION(criticalSection);
int r = --contextCount;
LEAVECRITICALSECTION(criticalSection);
return r;
}
int asCModule::AddModuleRef()
{
ENTERCRITICALSECTION(criticalSection);
int r = ++moduleCount;
LEAVECRITICALSECTION(criticalSection);
return r;
}
int asCModule::ReleaseModuleRef()
{
ENTERCRITICALSECTION(criticalSection);
int r = --moduleCount;
LEAVECRITICALSECTION(criticalSection);
return r;
}
bool asCModule::CanDelete()
{
// Don't delete if not discarded
if( !isDiscarded ) return false;
// Are there any contexts still referencing the module?
if( contextCount ) return false;
// If there are modules referencing this one we need to check for circular referencing
if( moduleCount )
{
// Check if all the modules are without external reference
asCArray<asCModule*> modules;
if( CanDeleteAllReferences(modules) )
{
// Unbind all functions. This will break any circular references
for( size_t n = 0; n < bindInformations.GetLength(); n++ )
{
int oldFuncID = bindInformations[n].importedFunction;
if( oldFuncID != -1 )
{
asCModule *oldModule = engine->GetModuleFromFuncId(oldFuncID);
if( oldModule != 0 )
{
// Release reference to the module
oldModule->ReleaseModuleRef();
}
}
}
}
// Can't delete the module yet because the
// other modules haven't released this one
return false;
}
return true;
}
bool asCModule::CanDeleteAllReferences(asCArray<asCModule*> &modules)
{
if( !isDiscarded ) return false;
if( contextCount ) return false;
modules.PushLast(this);
// Check all bound functions for referenced modules
for( size_t n = 0; n < bindInformations.GetLength(); n++ )
{
int funcID = bindInformations[n].importedFunction;
asCModule *module = engine->GetModuleFromFuncId(funcID);
// If the module is already in the list don't check it again
bool inList = false;
for( size_t m = 0; m < modules.GetLength(); m++ )
{
if( modules[m] == module )
{
inList = true;
break;
}
}
if( !inList )
{
bool ret = module->CanDeleteAllReferences(modules);
if( ret == false ) return false;
}
}
// If no module has external references then all can be deleted
return true;
}
int asCModule::BindImportedFunction(int index, int sourceID)
{
// Remove reference to old module
int oldFuncID = bindInformations[index].importedFunction;
if( oldFuncID != -1 )
{
asCModule *oldModule = engine->GetModuleFromFuncId(oldFuncID);
if( oldModule != 0 )
{
// Release reference to the module
oldModule->ReleaseModuleRef();
}
}
if( sourceID == -1 )
{
bindInformations[index].importedFunction = -1;
return asSUCCESS;
}
// Must verify that the interfaces are equal
asCModule *srcModule = engine->GetModuleFromFuncId(sourceID);
if( srcModule == 0 ) return asNO_MODULE;
asCScriptFunction *dst = GetImportedFunction(index);
if( dst == 0 ) return asNO_FUNCTION;
asCScriptFunction *src = srcModule->GetScriptFunction(sourceID);
if( src == 0 ) return asNO_FUNCTION;
// Verify return type
if( dst->returnType != src->returnType )
return asINVALID_INTERFACE;
if( dst->parameterTypes.GetLength() != src->parameterTypes.GetLength() )
return asINVALID_INTERFACE;
for( size_t n = 0; n < dst->parameterTypes.GetLength(); ++n )
{
if( dst->parameterTypes[n] != src->parameterTypes[n] )
return asINVALID_INTERFACE;
}
// Add reference to new module
srcModule->AddModuleRef();
bindInformations[index].importedFunction = sourceID;
return asSUCCESS;
}
const char *asCModule::GetImportedFunctionSourceModule(int index)
{
if( index >= (int)bindInformations.GetLength() )
return 0;
index = bindInformations[index].importFrom;
return stringConstants[index]->AddressOf();
}
bool asCModule::IsUsed()
{
if( contextCount ) return true;
if( moduleCount ) return true;
return false;
}
asCObjectType *asCModule::GetObjectType(const char *type)
{
// TODO: Improve linear search
for( size_t n = 0; n < classTypes.GetLength(); n++ )
if( classTypes[n]->name == type )
return classTypes[n];
return 0;
}
asCObjectType *asCModule::RefObjectType(asCObjectType *type)
{
if( !type ) return 0;
// Determine the index local to the module
for( size_t n = 0; n < usedTypes.GetLength(); n++ )
if( usedTypes[n] == type ) return type;
usedTypes.PushLast(type);
type->refCount++;
RefConfigGroupForObjectType(type);
return type;
}
void asCModule::RefConfigGroupForFunction(int funcId)
{
// Find the config group where the function was registered
asCConfigGroup *group = engine->FindConfigGroupForFunction(funcId);
if( group == 0 )
return;
// Verify if the module is already referencing the config group
for( size_t n = 0; n < configGroups.GetLength(); n++ )
{
if( configGroups[n] == group )
return;
}
// Add reference to the group
configGroups.PushLast(group);
group->AddRef();
}
void asCModule::RefConfigGroupForGlobalVar(int gvarId)
{
// Find the config group where the function was registered
asCConfigGroup *group = engine->FindConfigGroupForGlobalVar(gvarId);
if( group == 0 )
return;
// Verify if the module is already referencing the config group
for( size_t n = 0; n < configGroups.GetLength(); n++ )
{
if( configGroups[n] == group )
return;
}
// Add reference to the group
configGroups.PushLast(group);
group->AddRef();
}
void asCModule::RefConfigGroupForObjectType(asCObjectType *type)
{
if( type == 0 ) return;
// Find the config group where the function was registered
asCConfigGroup *group = engine->FindConfigGroupForObjectType(type);
if( group == 0 )
return;
// Verify if the module is already referencing the config group
for( size_t n = 0; n < configGroups.GetLength(); n++ )
{
if( configGroups[n] == group )
return;
}
// Add reference to the group
configGroups.PushLast(group);
group->AddRef();
}
int asCModule::GetGlobalVarIndex(int propIdx)
{
void *ptr = 0;
if( propIdx < 0 )
ptr = engine->globalPropAddresses[-int(propIdx) - 1];
else
ptr = globalMem.AddressOf() + (propIdx & 0xFFFF);
for( int n = 0; n < (signed)globalVarPointers.GetLength(); n++ )
if( globalVarPointers[n] == ptr )
return n;
globalVarPointers.PushLast(ptr);
return (int)globalVarPointers.GetLength()-1;
}
void asCModule::UpdateGlobalVarPointer(void *pold, void *pnew)
{
for( asUINT n = 0; n < globalVarPointers.GetLength(); n++ )
if( globalVarPointers[n] == pold )
{
globalVarPointers[n] = pnew;
return;
}
}
END_AS_NAMESPACE
| 22.035398 | 201 | 0.689809 | RobinSchmidt |
103ff94c3f3d0fd8945df53e14902601760d9e72 | 5,287 | cpp | C++ | options/posix/generic/sys-socket-stubs.cpp | 64/mlibc | 81d17ab95b5b8a0bd7bf67cec8c7f773c6d762da | [
"MIT"
] | 1 | 2021-07-05T04:19:56.000Z | 2021-07-05T04:19:56.000Z | options/posix/generic/sys-socket-stubs.cpp | 64/mlibc | 81d17ab95b5b8a0bd7bf67cec8c7f773c6d762da | [
"MIT"
] | null | null | null | options/posix/generic/sys-socket-stubs.cpp | 64/mlibc | 81d17ab95b5b8a0bd7bf67cec8c7f773c6d762da | [
"MIT"
] | null | null | null |
#include <errno.h>
#include <sys/socket.h>
#include <bits/ensure.h>
#include <mlibc/debug.hpp>
#include <mlibc/posix-sysdeps.hpp>
int accept(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length) {
if(addr_ptr || addr_length)
mlibc::infoLogger() << "\e[35mmlibc: accept() does not fill struct sockaddr\e[39m"
<< frg::endlog;
int newfd;
if(!mlibc::sys_accept) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_accept(fd, &newfd); e) {
errno = e;
return -1;
}
return newfd;
}
int bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) {
if(!mlibc::sys_bind) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_bind(fd, addr_ptr, addr_len); e) {
errno = e;
return -1;
}
return 0;
}
int connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) {
if(!mlibc::sys_connect) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_connect(fd, addr_ptr, addr_len); e) {
errno = e;
return -1;
}
return 0;
}
int getpeername(int fd, struct sockaddr *addr_ptr, socklen_t *__restrict addr_length) {
socklen_t actual_length;
if(!mlibc::sys_peername) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_peername(fd, addr_ptr, *addr_length, &actual_length); e) {
errno = e;
return -1;
}
*addr_length = actual_length;
return 0;
}
int getsockname(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length) {
socklen_t actual_length;
if(!mlibc::sys_sockname) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_sockname(fd, addr_ptr, *addr_length, &actual_length); e) {
errno = e;
return -1;
}
*addr_length = actual_length;
return 0;
}
int getsockopt(int fd, int layer, int number,
void *__restrict buffer, socklen_t *__restrict size) {
if(!mlibc::sys_getsockopt) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
return mlibc::sys_getsockopt(fd, layer, number, buffer, size);
}
int listen(int fd, int backlog) {
if(!mlibc::sys_listen) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_listen(fd, backlog); e) {
errno = e;
return -1;
}
return 0;
}
ssize_t recv(int sockfd, void *__restrict buf, size_t len, int flags) {
return recvfrom(sockfd, buf, len, flags, NULL, NULL);
}
ssize_t recvfrom(int sockfd, void *__restrict buf, size_t len, int flags,
struct sockaddr *__restrict src_addr, socklen_t *__restrict addrlen) {
struct iovec iov = {};
iov.iov_base = buf;
iov.iov_len = len;
struct msghdr hdr = {};
hdr.msg_name = src_addr;
if (addrlen) {
hdr.msg_namelen = *addrlen;
}
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
int ret = recvmsg(sockfd, &hdr, flags);
if (ret < 0)
return ret;
if(addrlen)
*addrlen = hdr.msg_namelen;
return ret;
}
ssize_t recvmsg(int fd, struct msghdr *hdr, int flags) {
ssize_t length;
if(!mlibc::sys_msg_recv) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_msg_recv(fd, hdr, flags, &length); e) {
errno = e;
return -1;
}
return length;
}
int recvmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, int flags, struct timespec *timeout) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
ssize_t send(int fd, const void *buffer, size_t size, int flags) {
return sendto(fd, buffer, size, flags, nullptr, 0);
}
ssize_t sendto(int fd, const void *buffer, size_t size, int flags,
const struct sockaddr *sock_addr, socklen_t addr_length) {
struct iovec iov = {};
iov.iov_base = const_cast<void *>(buffer);
iov.iov_len = size;
struct msghdr hdr = {};
hdr.msg_name = const_cast<struct sockaddr *>(sock_addr);
hdr.msg_namelen = addr_length;
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
return sendmsg(fd, &hdr, flags);
}
ssize_t sendmsg(int fd, const struct msghdr *hdr, int flags) {
ssize_t length;
if(!mlibc::sys_msg_send) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_msg_send(fd, hdr, flags, &length); e) {
errno = e;
return -1;
}
return length;
}
int sendmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen, int flags) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int setsockopt(int fd, int layer, int number,
const void *buffer, socklen_t size) {
if(!mlibc::sys_setsockopt) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
return mlibc::sys_setsockopt(fd, layer, number, buffer, size);
}
int shutdown(int, int) {
mlibc::infoLogger() << "mlibc: shutdown() is a no-op!" << frg::endlog;
return 0;
}
int sockatmark(int) {
__ensure(!"Not implemented");
__builtin_unreachable();
}
int socket(int family, int type, int protocol) {
int fd;
if(!mlibc::sys_socket) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_socket(family, type, protocol, &fd); e) {
errno = e;
return -1;
}
return fd;
}
int socketpair(int domain, int type, int protocol, int sv[2]) {
if(!mlibc::sys_socketpair) {
MLIBC_MISSING_SYSDEP();
errno = ENOSYS;
return -1;
}
if(int e = mlibc::sys_socketpair(domain, type, protocol, sv); e) {
errno = e;
return -1;
}
return 0;
}
// connectpair() is provided by the platform
| 22.214286 | 106 | 0.680726 | 64 |
104a327f80da397e5fb8c252289e938fc8389797 | 8,166 | cpp | C++ | hardware/test/cpu_instruction_set_test.cpp | vinders/pandora_toolbox | f32e301ebaa2b281a1ffc3d6d0c556091420520a | [
"MIT"
] | 2 | 2020-11-19T03:23:35.000Z | 2021-02-25T03:34:40.000Z | hardware/test/cpu_instruction_set_test.cpp | vinders/pandora_toolbox | f32e301ebaa2b281a1ffc3d6d0c556091420520a | [
"MIT"
] | null | null | null | hardware/test/cpu_instruction_set_test.cpp | vinders/pandora_toolbox | f32e301ebaa2b281a1ffc3d6d0c556091420520a | [
"MIT"
] | null | null | null | /*******************************************************************************
MIT License
Copyright (c) 2021 Romain Vinders
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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO 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 <gtest/gtest.h>
#include <hardware/cpu_instruction_set.h>
using namespace pandora::hardware;
class CpuInstructionSetTest : public testing::Test {
public:
protected:
//static void SetUpTestCase() {}
//static void TearDownTestCase() {}
void SetUp() override {}
void TearDown() override {}
};
// -- enumerations --
TEST_F(CpuInstructionSetTest, instructionFamilySerializer) {
EXPECT_TRUE(*toString(CpuInstructionFamily::assembly));
EXPECT_TRUE(*toString(CpuInstructionFamily::mmx));
EXPECT_TRUE(*toString(CpuInstructionFamily::sse));
EXPECT_TRUE(*toString(CpuInstructionFamily::avx));
EXPECT_TRUE(*toString(CpuInstructionFamily::neon));
EXPECT_TRUE(CpuInstructionFamily_size() > 0);
CpuInstructionFamily converted = CpuInstructionFamily::assembly;
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::assembly), converted));
EXPECT_EQ(CpuInstructionFamily::assembly, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::mmx), converted));
EXPECT_EQ(CpuInstructionFamily::mmx, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::sse), converted));
EXPECT_EQ(CpuInstructionFamily::sse, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::avx), converted));
EXPECT_EQ(CpuInstructionFamily::avx, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::neon), converted));
EXPECT_EQ(CpuInstructionFamily::neon, converted);
}
TEST_F(CpuInstructionSetTest, instructionFamilyFlagOps) {
CpuInstructionFamily flag1 = CpuInstructionFamily::sse;
CpuInstructionFamily flag2 = CpuInstructionFamily::sse;
EXPECT_TRUE(flag1 == flag2);
EXPECT_FALSE(flag1 != flag2);
EXPECT_FALSE(flag1 < flag2);
EXPECT_TRUE(flag1 <= flag2);
EXPECT_FALSE(flag1 > flag2);
EXPECT_TRUE(flag1 >= flag2);
flag2 = CpuInstructionFamily::avx;
EXPECT_FALSE(flag1 == flag2);
EXPECT_TRUE(flag1 != flag2);
EXPECT_EQ((static_cast<uint32_t>(flag1) < static_cast<uint32_t>(flag2)), (flag1 < flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) <= static_cast<uint32_t>(flag2)), (flag1 <= flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) > static_cast<uint32_t>(flag2)), (flag1 > flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) >= static_cast<uint32_t>(flag2)), (flag1 >= flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) & static_cast<uint32_t>(flag2)), (flag1 & flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) | static_cast<uint32_t>(flag2)), (flag1 | flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) ^ static_cast<uint32_t>(flag2)), (flag1 ^ flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(~static_cast<uint32_t>(flag1)), (~flag1));
EXPECT_EQ((CpuInstructionFamily::sse | CpuInstructionFamily::avx), addFlag(flag1, flag2));
EXPECT_EQ((CpuInstructionFamily::sse | CpuInstructionFamily::avx), flag1);
EXPECT_EQ((CpuInstructionFamily::avx), removeFlag(flag1, CpuInstructionFamily::sse));
EXPECT_EQ((CpuInstructionFamily::avx), flag1);
}
TEST_F(CpuInstructionSetTest, instructionSetSerializer) {
CpuInstructionSet converted = CpuInstructionSet::cpp;
EXPECT_TRUE(*toString(CpuInstructionSet::cpp));
EXPECT_TRUE(fromString(toString(CpuInstructionSet::cpp), converted));
EXPECT_EQ(CpuInstructionSet::cpp, converted);
EXPECT_TRUE(CpuInstructionSet_size() > 0);
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_TRUE(*toString(instSet));
EXPECT_TRUE(fromString(toString(instSet), converted));
EXPECT_EQ(instSet, converted);
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_TRUE(*toString(instSet));
EXPECT_TRUE(fromString(toString(instSet), converted));
EXPECT_EQ(instSet, converted);
}
}
TEST_F(CpuInstructionSetTest, instructionSetFlagOps) {
CpuInstructionSet flag1 = CpuInstructionSet::sse;
CpuInstructionSet flag2 = CpuInstructionSet::sse;
EXPECT_TRUE(flag1 == flag2);
EXPECT_FALSE(flag1 != flag2);
EXPECT_FALSE(flag1 < flag2);
EXPECT_TRUE(flag1 <= flag2);
EXPECT_FALSE(flag1 > flag2);
EXPECT_TRUE(flag1 >= flag2);
flag2 = CpuInstructionSet::avx;
EXPECT_FALSE(flag1 == flag2);
EXPECT_TRUE(flag1 != flag2);
EXPECT_EQ((static_cast<uint32_t>(flag1) < static_cast<uint32_t>(flag2)), (flag1 < flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) <= static_cast<uint32_t>(flag2)), (flag1 <= flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) > static_cast<uint32_t>(flag2)), (flag1 > flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) >= static_cast<uint32_t>(flag2)), (flag1 >= flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) & static_cast<uint32_t>(flag2)), (flag1 & flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) | static_cast<uint32_t>(flag2)), (flag1 | flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) ^ static_cast<uint32_t>(flag2)), (flag1 ^ flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(~static_cast<uint32_t>(flag1)), (~flag1));
EXPECT_EQ((CpuInstructionSet::sse | CpuInstructionSet::avx), addFlag(flag1, flag2));
EXPECT_EQ((CpuInstructionSet::sse | CpuInstructionSet::avx), flag1);
}
TEST_F(CpuInstructionSetTest, instructionSetSubEnumValues) {
EXPECT_TRUE(CpuInstructionSet_size() > 0);
EXPECT_FALSE(CpuInstructionSet_x86_values().empty());
EXPECT_FALSE(CpuInstructionSet_x86_rvalues().empty());
EXPECT_FALSE(CpuInstructionSet_arm_values().empty());
EXPECT_FALSE(CpuInstructionSet_arm_rvalues().empty());
EXPECT_EQ(CpuInstructionSet_x86_values().size(), CpuInstructionSet_x86_rvalues().size());
EXPECT_EQ(CpuInstructionSet_arm_values().size(), CpuInstructionSet_arm_rvalues().size());
EXPECT_TRUE(CpuInstructionSet_x86_values().size() + CpuInstructionSet_arm_values().size() <= CpuInstructionSet_size());
}
// -- builder / extractors --
TEST_F(CpuInstructionSetTest, buildInstructionSet) {
EXPECT_EQ(CpuInstructionSet::sse, toCpuInstructionSet(pandora::system::CpuArchitecture::x86, CpuInstructionFamily::sse, 0x2));
}
TEST_F(CpuInstructionSetTest, extractInstructionFamily) {
EXPECT_EQ(CpuInstructionFamily::assembly, toCpuInstructionFamily(CpuInstructionSet::cpp));
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_TRUE(toCpuInstructionFamily(instSet) == CpuInstructionFamily::mmx
|| toCpuInstructionFamily(instSet) == CpuInstructionFamily::sse
|| toCpuInstructionFamily(instSet) == CpuInstructionFamily::avx);
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_EQ(CpuInstructionFamily::neon, toCpuInstructionFamily(instSet));
}
}
TEST_F(CpuInstructionSetTest, extractCpuArch) {
EXPECT_EQ(pandora::system::CpuArchitecture::all, toCpuArchitecture(CpuInstructionSet::cpp));
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_EQ(pandora::system::CpuArchitecture::x86, toCpuArchitecture(instSet));
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_EQ(pandora::system::CpuArchitecture::arm, toCpuArchitecture(instSet));
}
}
| 48.035294 | 128 | 0.75447 | vinders |
104b88ded841f8ea686069bd5c9fc4a560c0315a | 1,156 | cpp | C++ | huawei/binarysearch/binarysearch/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | 1 | 2017-03-16T09:38:48.000Z | 2017-03-16T09:38:48.000Z | huawei/binarysearch/binarysearch/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | null | null | null | huawei/binarysearch/binarysearch/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// binarysearch
//
// Created by Rain on 12/04/2017.
// Copyright © 2017 Rain. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int getPos(vector<int> A, int n, int val) {
// write code here
vector<int>count(10000,0);
for(int i=0;i<n;i++)
{
count[A[i]]++;
}
int low=0;
int high=n-1;
int result=0,mid=0;
while(low<=high)
{
mid=(high-low)/2+low;
if(A[mid]==val)
{
result=A[mid];
break;
}
if(A[mid]<val)
{
low=mid+1;
}
else{
high=mid-1;
}
}
if(count[A[mid]]==1)
return mid;
else
{
for(int i=mid;i>=0;i--)
{
if(A[i]!=A[mid])
return i;
}
}
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
vector<int> A={9,13,21,31};
cout<<getPos(A, 4, 9)<<endl;
return 0;
}
| 20.280702 | 47 | 0.390138 | RainChang |
104c4a39144277fd702a673cd41acae54291cf78 | 426 | cpp | C++ | level1/p02_isPrime/_isPrime.cpp | KenNN99/c2019 | a668b7aa67187c8ef44bdefe5e7813d665084ff3 | [
"MIT"
] | null | null | null | level1/p02_isPrime/_isPrime.cpp | KenNN99/c2019 | a668b7aa67187c8ef44bdefe5e7813d665084ff3 | [
"MIT"
] | null | null | null | level1/p02_isPrime/_isPrime.cpp | KenNN99/c2019 | a668b7aa67187c8ef44bdefe5e7813d665084ff3 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
void NotPrime();
int main()
{
int i;
scanf("%d", &i);
if (i == 1)
{
NotPrime();
}
for (int n = 2; n*n <= i; n++)
{
if (i%n == 0)
{
NotPrime();
return 0;
}
}
printf("This is a Prime.");
system("pause");
return 0;
}
void NotPrime()
{
printf("This is not a Prime!!!");
system("pause");
<<<<<<< HEAD
}
=======
}
>>>>>>> 2b6d759c8e10cfe17d315e90703734d5f6ddb2ff
| 11.833333 | 48 | 0.528169 | KenNN99 |
104c691c27d95e1ba124b9aec6463c2cd4d733d0 | 430 | hpp | C++ | NWNXLib/API/Mac/API/Schema.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Mac/API/Schema.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Mac/API/Schema.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include "Hash.hpp"
namespace NWNXLib {
namespace API {
// Forward class declarations (defined in the source file)
struct Table;
struct Schema
{
int32_t schema_cookie;
int32_t iGeneration;
Hash tblHash;
Hash idxHash;
Hash trigHash;
Hash fkeyHash;
Table* pSeqTab;
uint8_t file_format;
uint8_t enc;
uint16_t schemaFlags;
int32_t cache_size;
};
}
}
| 13.4375 | 58 | 0.686047 | Qowyn |
104dd44c38c2bb09a043d6c92870c7c210012d1f | 29,388 | cpp | C++ | Engine/source/Alux3D/shotgunprojectile.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | null | null | null | Engine/source/Alux3D/shotgunprojectile.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | null | null | null | Engine/source/Alux3D/shotgunprojectile.cpp | fr1tz/alux3d | 249a3b51751ce3184d52879b481f83eabe89e7e3 | [
"MIT"
] | 1 | 2018-10-26T03:18:22.000Z | 2018-10-26T03:18:22.000Z | // Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "platform/platform.h"
#include "Alux3D/shotgunprojectile.h"
#include "scene/sceneRenderState.h"
#include "scene/sceneManager.h"
#include "lighting/lightInfo.h"
#include "lighting/lightManager.h"
#include "console/consoleTypes.h"
#include "console/typeValidators.h"
#include "core/resourceManager.h"
#include "core/stream/bitStream.h"
#include "T3D/fx/explosion.h"
#include "T3D/shapeBase.h"
#include "ts/tsShapeInstance.h"
#include "sfx/sfxTrack.h"
#include "sfx/sfxSource.h"
#include "sfx/sfxSystem.h"
#include "sfx/sfxTypes.h"
#include "math/mathUtils.h"
#include "math/mathIO.h"
#include "sim/netConnection.h"
#include "T3D/fx/particleEmitter.h"
#include "T3D/fx/splash.h"
#include "T3D/physics/physicsPlugin.h"
#include "T3D/physics/physicsWorld.h"
#include "gfx/gfxTransformSaver.h"
#include "T3D/containerQuery.h"
#include "T3D/decal/decalManager.h"
#include "T3D/decal/decalData.h"
#include "T3D/lightDescription.h"
#include "console/engineAPI.h"
#include "T3D/gameBase/gameConnection.h"
static MRandomLCG sRandom(0x1);
//--------------------------------------------------------------------------
IMPLEMENT_CO_CLIENTEVENT_V1(CreateExplosionEvent);
CreateExplosionEvent::CreateExplosionEvent()
{
//mGuaranteeType = Guaranteed;
mData = NULL;
}
CreateExplosionEvent::CreateExplosionEvent(ExplosionData* data,
const Point3F& p, const Point3F &n)
{
mData = data;
mPos = p;
mNorm = n;
}
void CreateExplosionEvent::pack(NetConnection* conn, BitStream* bstream)
{
if(bstream->writeFlag(mData))
{
bstream->writeRangedU32(mData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
mathWrite(*bstream, mPos);
mathWrite(*bstream, mNorm);
}
}
void CreateExplosionEvent::unpack(NetConnection* conn, BitStream* bstream)
{
if(bstream->readFlag())
{
SimObject* ptr = NULL;
U32 id = bstream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
if(id != 0 && (ptr = Sim::findObject(id)))
mData = dynamic_cast<ExplosionData*>(ptr);
mathRead(*bstream, &mPos);
mathRead(*bstream, &mNorm);
}
}
void CreateExplosionEvent::write(NetConnection* conn, BitStream* bstream)
{
this->pack(conn,bstream);
}
void CreateExplosionEvent::process(NetConnection* conn)
{
if(!mData)
return;
Explosion* pExplosion = new Explosion;
pExplosion->onNewDataBlock(mData, false);
if( pExplosion )
{
MatrixF xform(true);
xform.setPosition(mPos);
pExplosion->setTransform(xform);
pExplosion->setInitialState(mPos, mNorm);
if (pExplosion->registerObject() == false)
{
Con::errorf(ConsoleLogEntry::General, "CreateExplosionEvent(): couldn't register explosion (%s)",
mData->getName() );
delete pExplosion;
pExplosion = NULL;
}
}
}
ConsoleFunction( createExplosionOnClient, bool, 5, 5, "(NetConnection conn, DataBlock datablock, Point3F pos, Point3F norm)")
{
NetConnection* nc = NULL;
if(Sim::findObject(argv[1], nc) == false)
{
Con::warnf(ConsoleLogEntry::General, "createExplosionOnClient: couldn't find object: %s", argv[1]);
return false;
}
ExplosionData* datablock = NULL;
if(Sim::findObject(argv[2], datablock) == false)
{
Con::warnf(ConsoleLogEntry::General, "createExplosionOnClient: couldn't find object: %s", argv[2]);
return false;
}
Point3F pos, norm;
dSscanf(argv[3], "%f %f %f", &pos.x, &pos.y, &pos.z);
dSscanf(argv[4], "%f %f %f", &norm.x, &norm.y, &norm.z);
if(datablock)
{
CreateExplosionEvent* event = new CreateExplosionEvent(datablock,pos,norm);
nc->postNetEvent(event);
}
return true;
}
//--------------------------------------------------------------------------
//
IMPLEMENT_CO_DATABLOCK_V1(ShotgunProjectileData);
ShotgunProjectileData::ShotgunProjectileData()
{
noFake = false;
energyDrain = 0;
numBullets = 10;
bulletDistMode = 0;
range = 1000.0f;
muzzleSpreadRadius = 0.0f;
referenceSpreadRadius = 0.0f;
referenceSpreadDistance = 0.0f;
}
//--------------------------------------------------------------------------
void ShotgunProjectileData::initPersistFields()
{
Parent::initPersistFields();
addField("noFake", TypeBool, Offset(noFake, ShotgunProjectileData));
addField("energyDrain", TypeS32, Offset(energyDrain, ShotgunProjectileData));
addField("numBullets", TypeS32, Offset(numBullets, ShotgunProjectileData));
addField("bulletDistMode", TypeS32, Offset(bulletDistMode, ShotgunProjectileData));
addField("range", TypeF32, Offset(range, ShotgunProjectileData));
addField("muzzleSpreadRadius", TypeF32, Offset(muzzleSpreadRadius, ShotgunProjectileData));
addField("referenceSpreadRadius", TypeF32, Offset(referenceSpreadRadius, ShotgunProjectileData));
addField("referenceSpreadDistance", TypeF32, Offset(referenceSpreadDistance, ShotgunProjectileData));
}
//--------------------------------------------------------------------------
bool ShotgunProjectileData::onAdd()
{
if(!Parent::onAdd())
return false;
return true;
}
bool ShotgunProjectileData::preload(bool server, String &errorStr)
{
if (Parent::preload(server, errorStr) == false)
return false;
return true;
}
//--------------------------------------------------------------------------
void ShotgunProjectileData::packData(BitStream* stream)
{
Parent::packData(stream);
stream->writeFlag(noFake);
stream->write(energyDrain);
stream->write(numBullets);
stream->write(bulletDistMode);
stream->write(range);
stream->write(muzzleSpreadRadius);
stream->write(referenceSpreadRadius);
stream->write(referenceSpreadDistance);
}
void ShotgunProjectileData::unpackData(BitStream* stream)
{
Parent::unpackData(stream);
noFake = stream->readFlag();
stream->read(&energyDrain);
stream->read(&numBullets);
stream->read(&bulletDistMode);
stream->read(&range);
stream->read(&muzzleSpreadRadius);
stream->read(&referenceSpreadRadius);
stream->read(&referenceSpreadDistance);
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(ShotgunProjectileTracer);
ShotgunProjectileTracer::ShotgunProjectileTracer(const Point3F* impactPos)
{
mNetFlags.clear();
mNetFlags.set(IsGhost);
if(impactPos)
mImpactPos.set(*impactPos);
mAtImpactPos = false;
}
ShotgunProjectileTracer::~ShotgunProjectileTracer()
{
}
bool ShotgunProjectileTracer::onAdd()
{
AssertFatal(isClientObject(), "ShotgunProjectileTracer on the server? - Someone fucked up!");
if(mDataBlock->muzzleVelocity <= 10)
{
mCurrVelocity = (mImpactPos - mCurrPosition) / mDataBlock->muzzleVelocity;
mCurrVelocity *= TickMs;
}
mInitialPosition = mCurrPosition;
mInitialVelocity = mCurrVelocity;
mCurrDeltaBase = mCurrPosition;
mCurrBackDelta = -mCurrVelocity;
if(!Parent::onAdd())
return false;
return true;
}
bool ShotgunProjectileTracer::onNewDataBlock(GameBaseData* dptr, bool reload)
{
mDataBlock = dynamic_cast<ShotgunProjectileData*>(dptr);
if(!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
return false;
return true;
}
void ShotgunProjectileTracer::processTick(const Move* move)
{
AssertFatal(isClientObject(), "ShotgunProjectileTracer on the server? - Someone fucked up!");
#if 0
mNumTicks++;
#endif
mCurrTick++;
if(mAtImpactPos)
this->deleteObject();
return;
// HACK HACK HACK
if(mDataBlock->muzzleVelocity > 9000)
{
#if 0
this->missedEnemiesCheck(mInitialPosition, mImpactPos);
if(mDataBlock->laserTail != NULL)
{
LaserBeam* beam = new LaserBeam();
beam->setSceneObjectColorization(this->getSceneObjectColorization());
beam->onNewDataBlock(mDataBlock->laserTail);
if(!beam->registerObject())
{
Con::warnf( ConsoleLogEntry::General, "Could not register laserTail for class: %s", mDataBlock->getName() );
delete beam;
}
else
{
beam->setRender(true);
F32 r = sRandom.randF();
Point3F v = (mImpactPos - mInitialPosition)*r;
Point3F vel = v; vel.normalize(); vel *= mDataBlock->muzzleVelocity;
beam->makeDisappear(mInitialPosition, mInitialPosition + v,
vel, mDataBlock->laserTailLen);
}
}
addLaserTrailNode(mInitialPosition, false);
addLaserTrailNode(mImpactPos, false);
for(S32 i = 0; i < NUM_LASERTRAILS; i++)
{
if( mLaserTrailList[i] != NULL )
{
mLaserTrailList[i]->setSceneObjectColorization(this->getSceneObjectColorization());
if(mDataBlock->smoothLaserTrail)
mLaserTrailList[i]->smooth();
if(mDataBlock->laserTrailFlagsList[i] & 1)
mLaserTrailList[i]->smoothReverseDist(mDataBlock->range);
if(mDataBlock->laserTrailFlagsList[i] & 2)
mLaserTrailList[i]->smooth();
if(mDataBlock->laserTrailFlagsList[i] & 4)
mLaserTrailList[i]->smoothDist(2);
}
}
#endif
this->deleteObject();
return;
}
if(mCurrTick >= mDataBlock->lifetime)
{
deleteObject();
return;
}
F32 timeLeft;
RayInfo rInfo;
Point3F oldPosition;
Point3F newPosition;
oldPosition = mCurrPosition;
newPosition = oldPosition + mCurrVelocity * TickSec;
F32 oldDist = (oldPosition-mImpactPos).len();
F32 newDist = (newPosition-mImpactPos).len();
if(newDist > oldDist) // going away from target?
newPosition = mImpactPos;
mCurrDeltaBase = newPosition;
mCurrBackDelta = mCurrPosition - newPosition;
this->emitParticles(oldPosition, newPosition, mCurrVelocity, TickMs);
#if 0
this->missedEnemiesCheck(oldPosition, newPosition);
//emitParticles(mCurrPosition, newPosition, mCurrVelocity, TickMs);
// update laser trail...
if( mEmissionCount == 0 )
{
addLaserTrailNode(mInitialPosition,false);
for( U8 i = 0; i < mNumBouncePoints; i++ )
{
//Con::printf("processTick(): (client) adding bouncePoint %u: %f %f %f",i,mBouncePoint[i].x,mBouncePoint[i].y,mBouncePoint[i].z);
addLaserTrailNode(mBouncePoint[i].pos, false);
createBounceExplosion(mBouncePoint[i].pos, mBouncePoint[i].norm, mBouncePoint[i].decal);
}
}
if( mFxLight != NULL )
mFxLight->setPosition(mCurrDeltaBase);
addLaserTrailNode(newPosition,false);
mEmissionCount++;
#endif
if(newPosition == mImpactPos)
{
this->deleteObject();
return;
}
mCurrPosition = newPosition;
MatrixF xform(true);
xform.setColumn(3, mCurrPosition);
setTransform(xform);
}
void ShotgunProjectileTracer::advanceTime(F32 dt)
{
Parent::advanceTime(dt);
if(mAtImpactPos)
return;
this->simulate(dt);
this->updateSound();
}
void ShotgunProjectileTracer::interpolateTick(F32 delta)
{
// ShotgunProjectileTracers use advanceTime() to
// advance their simulation (instead of ticks).
}
void ShotgunProjectileTracer::simulate(F32 dt)
{
F32 timeLeft;
RayInfo rInfo;
Point3F oldPosition;
Point3F newPosition;
oldPosition = mCurrPosition;
newPosition = oldPosition + mCurrVelocity * dt;
F32 oldDist = (oldPosition-mImpactPos).len();
F32 newDist = (newPosition-mImpactPos).len();
if(newDist > oldDist) // going away from target?
{
newPosition = mImpactPos;
mAtImpactPos = true;
}
mCurrDeltaBase = newPosition;
mCurrBackDelta = mCurrPosition - newPosition;
this->emitParticles(oldPosition, newPosition, mCurrVelocity, dt*1000);
mCurrPosition = newPosition;
Point3F dir = mCurrVelocity;
if(dir.isZero())
dir.set(0,0,1);
else
dir.normalize();
MatrixF xform(true);
xform = MathUtils::createOrientFromDir(dir);
xform.setPosition(mCurrPosition);
setTransform(xform);
}
//--------------------------------------------------------------------------
ShotgunHit::ShotgunHit()
{
object = NULL;
numImpacts = 0;
}
ShotgunHit::ShotgunHit(const ShotgunHit& hit)
{
object = hit.object;
objectPos = hit.objectPos;
numImpacts = hit.numImpacts;
impactCenterVec = hit.impactCenterVec;
impactVecs = hit.impactVecs;
impactNormals = hit.impactNormals;
}
ShotgunHit::~ShotgunHit()
{
}
void ShotgunHit::pack(NetConnection* con, BitStream* stream)
{
// send object id or object pos if the object does not exist anymore
if(stream->writeFlag(object.isNull()))
{
mathWrite(*stream, objectPos);
}
else
{
S32 ghostIndex = -1;
if(stream->writeFlag(object->isClientObject()))
ghostIndex = object->getNetIndex();
else
ghostIndex = con->getGhostIndex(object);
if(stream->writeFlag(ghostIndex != -1))
stream->writeRangedU32(U32(ghostIndex), 0, NetConnection::MaxGhostCount);
else
mathWrite(*stream, objectPos);
}
stream->write(numImpacts);
mathWrite(*stream, impactCenterVec);
for(U32 i = 0; i < numImpacts; i ++)
{
mathWrite(*stream, impactVecs[i]);
mathWrite(*stream, impactNormals[i]);
}
}
void ShotgunHit::unpack(NetConnection* con, BitStream* stream)
{
if(stream->readFlag())
{
mathRead(*stream, &objectPos);
}
else
{
bool onServer = stream->readFlag();
if(stream->readFlag())
{
U32 objectId = stream->readRangedU32(0, NetConnection::MaxGhostCount);
if(onServer)
{
NetObject* pObj = con->resolveObjectFromGhostIndex(objectId);
object = dynamic_cast<SceneObject*>(pObj);
}
else
{
NetObject* pObj = con->resolveGhost(objectId);
object = dynamic_cast<SceneObject*>(pObj);
}
if(object)
objectPos = object->getPosition();
}
else
mathRead(*stream, &objectPos);
}
stream->read(&numImpacts);
mathRead(*stream, &impactCenterVec);
for(U32 i = 0; i < numImpacts; i ++)
{
Point3F impactVec, impactNormal;
mathRead(*stream, &impactVec);
mathRead(*stream, &impactNormal);
impactVecs.push_back(impactVec);
impactNormals.push_back(impactNormal);
}
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(ShotgunProjectile);
ShotgunProjectile::ShotgunProjectile(bool onClient, bool findHits)
{
mFindHits = findHits;
mHitsSource = NULL;
mNetFlags.clear();
if(onClient)
{
mNetFlags.set(IsGhost);
}
else
{
mNetFlags.set(Ghostable);
}
}
ShotgunProjectile::~ShotgunProjectile()
{
U32 n = mHits.size();
while(n--)
delete mHits[n];
}
void ShotgunProjectile::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//--------------------------------------------------------------------------
void ShotgunProjectile::initPersistFields()
{
Parent::initPersistFields();
}
void ShotgunProjectile::consoleInit()
{
Parent::consoleInit();
}
//--------------------------------------------------------------------------
class ObjectDeleteEvent : public SimEvent
{
public:
void process(SimObject *object)
{
object->deleteObject();
}
};
bool ShotgunProjectile::onAdd()
{
if(!Parent::onAdd())
return false;
setProcessTick(false); // no need to process ticks
if(mFindHits)
{
this->findHits();
if(this->isClientObject())
this->transmitHitsToServer();
}
this->processHits();
if(isClientObject())
{
if(mFindHits)
{
this->deleteObject();
return true;
}
else
{
mHasExploded = true;
}
}
else
{
// Need valid transform for scoping.
Point3F dir = mCurrVelocity; dir.normalize();
MatrixF mat = MathUtils::createOrientFromDir(dir);
mat.setPosition(mCurrPosition);
this->setTransform(mat);
// Delete us after we've had some time to ghost.
Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + DeleteWaitTime);
}
return true;
}
void ShotgunProjectile::onRemove()
{
Parent::onRemove();
}
bool ShotgunProjectile::onNewDataBlock(GameBaseData* dptr, bool reload)
{
mDataBlock = dynamic_cast<ShotgunProjectileData*>( dptr );
if(!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
return false;
return true;
}
//----------------------------------------------------------------------------
void ShotgunProjectile::processTick(const Move* move)
{
AssertFatal(isClientObject(), "ShotgunProjectile::processTick() being called? - Someone fucked up!");
//mNumTicks++;
//mCurrTick++;
//if(isServerObject() && mCurrTick >= mDataBlock->lifetime)
// deleteObject();
}
void ShotgunProjectile::advanceTime(F32 dt)
{
Parent::advanceTime(dt);
}
void ShotgunProjectile::interpolateTick(F32 delta)
{
Parent::interpolateTick(delta);
}
//--------------------------------------------------------------------------
U32 ShotgunProjectile::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
// Transmit hits...
// Note: Don't send hits back to their source.
if(stream->writeFlag((mask & GameBase::InitialUpdateMask) && con != mHitsSource))
{
U32 n = mHits.size();
stream->write(n);
while(n--)
mHits[n]->pack(con, stream);
}
return retMask;
}
void ShotgunProjectile::unpackUpdate(NetConnection* con, BitStream* stream)
{
Parent::unpackUpdate(con, stream);
// Read hits?
if(stream->readFlag())
{
U32 n; stream->read(&n);
while(n--)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->unpack(con, stream);
mHits.push_back(newHit);
}
}
}
//--------------------------------------------------------------------------
void ShotgunProjectile::addHits(NetConnection* client, const ShotgunHits& hits)
{
mHitsSource = client;
U32 n = hits.size();
while(n--)
mHits.push_back(new ShotgunHit(*hits[n]));
}
void ShotgunProjectile::findHits()
{
mSourceObject->disableCollision();
Point3F muzzlePoint = mCurrPosition;
Point3F dir = mCurrVelocity; dir.normalize();
MatrixF transform = MathUtils::createOrientFromDir(dir);
Point3F zv; transform.getColumn(2, &zv);
zv.normalize();
Point3F startEdge = muzzlePoint
+ zv * mDataBlock->muzzleSpreadRadius;
Point3F refEdge = muzzlePoint + dir * mDataBlock->referenceSpreadDistance
+ zv * mDataBlock->referenceSpreadRadius;
Point3F vec = refEdge - startEdge; vec.normalize();
Point3F endEdge = startEdge + vec * mDataBlock->range;
Point3F startCenter = muzzlePoint;
Point3F endCenter = muzzlePoint + dir * mDataBlock->range;
//
// collect hits...
//
int totalImpacts = 0;
Vector<Point3F> misses;
if(mDataBlock->bulletDistMode == 0)
{
for(int i=0; i < mDataBlock->numBullets; i++)
{
Point3F startClockVec = startEdge - startCenter;
Point3F endClockVec = endEdge - endCenter;
MatrixF rotmat(EulerF(0, 6.28 * sRandom.randF(), 0));
rotmat.mulV(startClockVec);
rotmat.mulV(endClockVec);
Point3F startVec = startClockVec;
transform.mulV(startVec);
Point3F endVec = endClockVec;
transform.mulV(endVec);
F32 r = sRandom.randF();
Point3F start = startCenter + startVec * r;
Point3F end = endCenter + endVec * r;
RayInfo rInfo;
bool collision = getContainer()->castRay(start, end, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
if(collision)
{
ShotgunHit* hit = NULL;
for(int k=0; k<mHits.size(); k++)
{
if(mHits[k]->object == rInfo.object)
{
hit = mHits[k];
break;
}
}
if(hit == NULL)
{
hit = new ShotgunHit();
hit->object = rInfo.object;
hit->objectPos = hit->object->getPosition();
hit->numImpacts = 0;
mHits.push_back(hit);
}
hit->numImpacts++;
Point3F impactVec = rInfo.point - hit->objectPos;
hit->impactCenterVec += impactVec;
hit->impactCenterVec /= 2;
hit->impactVecs.push_back(impactVec);
hit->impactNormals.push_back(rInfo.normal);
totalImpacts++;
}
else
{
misses.push_back(end);
}
}
}
else
{
int numEdges = 40;
int numSegments = 20;
Point3F startClockVec = startEdge - startCenter;
Point3F endClockVec = endEdge - endCenter;
MatrixF rotmat(EulerF(0, 6.28 / numEdges, 0));
for(int i=0; i < numEdges; i++)
{
rotmat.mulV(startClockVec);
rotmat.mulV(endClockVec);
Point3F startVec = startClockVec;
transform.mulV(startVec);
Point3F endVec = endClockVec;
transform.mulV(endVec);
Point3F startVecSeg = startVec / numSegments;
Point3F endVecSeg = endVec / numSegments;
startVec = startVecSeg;
endVec = endVecSeg;
for(int j = 0; j < numSegments; j++)
{
Point3F start = startCenter + startVec;
Point3F end = endCenter + endVec;
RayInfo rInfo;
bool collision = getContainer()->castRay(start, end, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
if(collision)
{
ShotgunHit* hit = NULL;
for(int k=0; k<mHits.size(); k++)
{
if(mHits[k]->object == rInfo.object)
{
hit = mHits[k];
break;
}
}
if(hit == NULL)
{
hit = new ShotgunHit();
hit->object = rInfo.object;
hit->objectPos = hit->object->getPosition();
hit->numImpacts = 0;
mHits.push_back(hit);
}
hit->numImpacts++;
Point3F impactVec = rInfo.point - hit->objectPos;
hit->impactCenterVec += impactVec;
hit->impactCenterVec /= 2;
hit->impactVecs.push_back(impactVec);
hit->impactNormals.push_back(rInfo.normal);
}
else
{
misses.push_back(end);
}
startVec += startVecSeg;
endVec += endVecSeg;
}
}
// reduce number of impacts per hit according to the number
// of bullets that the shotgun is supposed to fire...
int totalBullets = numEdges * numSegments;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
//Con::printf("Number of actual impacts: %i of %i", hit->numImpacts, totalBullets);
hit->numImpacts = F32(hit->numImpacts) / (totalBullets / mDataBlock->numBullets);
hit->numImpacts = mClamp(hit->numImpacts + 1, 1, mDataBlock->numBullets);
totalImpacts += hit->numImpacts;
//Con::printf("Number of bullet impacts: %i of %i", hit->numImpacts, mDataBlock->numBullets);
Vector<Point3F> newImpactVecs, newImpactNormals;
for(int i = 0; i < hit->numImpacts; i++)
{
U32 idx = sRandom.randI(0, hit->impactVecs.size()-1);
newImpactVecs.push_back(hit->impactVecs[idx]);
newImpactNormals.push_back(hit->impactNormals[idx]);
}
hit->impactVecs = newImpactVecs;
hit->impactNormals = newImpactNormals;
}
}
// create a hit for the bullets that didn't hit anything
int numMisses = mDataBlock->numBullets - totalImpacts;
if(numMisses > 0)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->object = NULL;
newHit->objectPos.set(0, 0, 0);
newHit->impactCenterVec.set(0, 0, 0);
newHit->numImpacts = numMisses;
while(numMisses--)
{
Point3F impactVec;
if(mDataBlock->bulletDistMode == 0)
impactVec = misses[numMisses];
else
impactVec = misses[sRandom.randI(0, misses.size()-1)];
newHit->impactCenterVec += impactVec;
newHit->impactCenterVec /= 2;
newHit->impactVecs.push_back(impactVec);
newHit->impactNormals.push_back(Point3F(0, 0, 1));
}
mHits.push_back(newHit);
}
mSourceObject->enableCollision();
}
void ShotgunProjectile::processHits()
{
if(isServerObject())
this->serverProcessHits();
else
this->clientProcessHits();
}
void ShotgunProjectile::serverProcessHits()
{
Point3F muzzlePoint = mCurrPosition;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
Point3F objectPos;
if(hit->object.isNull())
objectPos = hit->objectPos;
else
objectPos = hit->object->getPosition();
for(int i = 0; i < hit->numImpacts; i++)
{
Point3F impactVec = hit->impactVecs[i];
Point3F impactNormal = hit->impactNormals[i];
Point3F impactPos = objectPos + impactVec;
#if 0
mTraveledDistance = (impactPos-mCurrPosition).len();
#endif
Parent::onCollision(impactPos, impactNormal, hit->object);
}
}
}
void ShotgunProjectile::clientProcessHits()
{
Point3F muzzlePoint = mCurrPosition;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
Point3F objectPos;
if(hit->object.isNull())
objectPos = hit->objectPos;
else
objectPos = hit->object->getPosition();
// eyecandy stuff...
for(int i = 0; i < hit->numImpacts; i++)
{
Point3F impactVec = hit->impactVecs[i];
Point3F impactNormal = hit->impactNormals[i];
Point3F impactPos = objectPos + impactVec;
Point3F velocity = impactPos - muzzlePoint;
F32 dist = velocity.len();
velocity.normalize();
//if(mDataBlock->spread == 0.0 && !hit->object.isNull())
// velocity *= dist / (mDataBlock->lifetime * (F32(TickMs) / 1000.0f));
//else
velocity *= mDataBlock->muzzleVelocity;
ShotgunProjectileTracer* prj = new ShotgunProjectileTracer(&impactPos);
prj->mCurrPosition = muzzlePoint;
prj->mCurrVelocity = velocity;
prj->mSourceObject = mSourceObject;
prj->mSourceObjectSlot = mSourceObjectSlot;
#if 0
prj->setSceneObjectColorization(this->getSceneObjectColorization());
#endif
prj->onNewDataBlock(mDataBlock, false);
if(!prj->registerObject())
{
Con::warnf(ConsoleLogEntry::General, "Could not register shotgun tracer projectile for image: %s", mDataBlock->getName());
delete prj;
prj = NULL;
}
if(hit->object.isNull())
{
#if 0
prj->disableLaserTrail(1);
#endif
continue;
}
SceneObject* sObj = hit->object.operator->();
#if 0
if( sObj->getType() & Projectile::csmDynamicCollisionMask )
{
if( ((ShapeBase*)sObj)->getTeamId() == mTeamId )
{
mExplosionType = Projectile::HitTeammateExplosion;
prj->disableLaserTrail(1);
}
else
{
mExplosionType = Projectile::HitEnemyExplosion;
prj->disableLaserTrail(0);
}
}
else
{
mExplosionType = Projectile::StandardExplosion;
prj->disableLaserTrail(1);
}
#endif
ExplosionData* datablock = mDataBlock->explosion;
#if 0
if( mExplosionType == HitEnemyExplosion && mDataBlock->hitEnemyExplosion != NULL )
datablock = mDataBlock->hitEnemyExplosion;
else if( mExplosionType == HitTeammateExplosion && mDataBlock->hitTeammateExplosion != NULL )
datablock = mDataBlock->hitTeammateExplosion;
#endif
if(datablock != NULL)
{
Explosion* pExplosion = new Explosion;
pExplosion->onNewDataBlock(datablock, false);
Point3F expPos = impactPos + impactNormal*0.1;
MatrixF xform(true);
xform.setPosition(expPos);
pExplosion->setTransform(xform);
pExplosion->setInitialState(expPos, impactNormal);
pExplosion->setCollideType(hit->object->getTypeMask());
if (pExplosion->registerObject() == false)
{
Con::errorf(ConsoleLogEntry::General, "ShotgunProjectile(%s)::explode: couldn't register explosion",
mDataBlock->getName() );
delete pExplosion;
pExplosion = NULL;
}
if(mDataBlock->decal
&& !(sObj->getTypeMask() & Projectile::csmDynamicCollisionMask)
&& (hit->object->getTypeMask() & Projectile::csmStaticCollisionMask))
gDecalManager->addDecal(impactPos, impactNormal, 0.0f, mDataBlock->decal );
}
}
}
}
void ShotgunProjectile::transmitHitsToServer()
{
ShotgunFireEvent* event = new ShotgunFireEvent();
event->datablock = mDataBlock;
event->source = mSourceObject;
event->sourceId = mSourceObject->getNetIndex();
event->sourceSlot = mSourceObjectSlot;
event->muzzlePoint = mCurrPosition;
event->muzzleVector = mCurrVelocity;
U32 n = mHits.size();
while(n--)
event->hits.push_back(new ShotgunHit(*mHits[n]));
GameConnection::getConnectionToServer()->postNetEvent(event);
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_SERVEREVENT_V1(ShotgunFireEvent);
ShotgunFireEvent::ShotgunFireEvent()
{
//mGuaranteeType = NetEvent::Guaranteed; // FIXME
datablock = NULL;
source = NULL;
sourceId = -1;
sourceSlot = -1;
}
ShotgunFireEvent::~ShotgunFireEvent()
{
U32 n = hits.size();
while(n--)
delete hits[n];
}
void ShotgunFireEvent::pack(NetConnection* conn, BitStream* bstream)
{
if(!bstream->writeFlag(datablock))
return;
// datablock
bstream->writeRangedU32(datablock->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
// source
if(bstream->writeFlag(sourceId != -1))
bstream->writeRangedU32(U32(sourceId), 0, NetConnection::MaxGhostCount);
// source slot
bstream->writeSignedInt(sourceSlot,4);
// muzzle point & vector
mathWrite(*bstream, muzzlePoint);
mathWrite(*bstream, muzzleVector);
// hits
U32 n = hits.size();
bstream->write(n);
while(n--)
hits[n]->pack(conn, bstream);
}
void ShotgunFireEvent::unpack(NetConnection* conn, BitStream* bstream)
{
if(!bstream->readFlag())
return;
// datablock
SimObject* ptr = NULL;
U32 id = bstream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
if(id != 0 && (ptr = Sim::findObject(id)))
datablock = dynamic_cast<ShotgunProjectileData*>(ptr);
// source
if(bstream->readFlag())
{
sourceId = bstream->readRangedU32(0, NetConnection::MaxGhostCount);
if(sourceId != -1)
{
NetObject* pObj = conn->resolveObjectFromGhostIndex(sourceId);
source = dynamic_cast<ShapeBase*>(pObj);
}
}
// source slot
sourceSlot = bstream->readSignedInt(4);
// muzzle point & vector
mathRead(*bstream, &muzzlePoint);
mathRead(*bstream, &muzzleVector);
// hits
U32 n; bstream->read(&n);
while(n--)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->unpack(conn, bstream);
hits.push_back(newHit);
}
}
void ShotgunFireEvent::write(NetConnection* conn, BitStream* bstream)
{
this->pack(conn, bstream);
}
void ShotgunFireEvent::process(NetConnection* conn)
{
if(!datablock)
return;
if(!source)
return;
source->clientFiredShotgun(
conn,
sourceSlot,
hits,
datablock,
muzzlePoint,
muzzleVector
);
}
| 23.757478 | 132 | 0.671124 | fr1tz |
10506bb2f6449ce70be8d9cd41f032a088a927da | 1,129 | hpp | C++ | include/dtc/cell/cell.hpp | tsung-wei-huang/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 69 | 2019-03-16T20:13:26.000Z | 2022-03-24T14:12:19.000Z | include/dtc/cell/cell.hpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2017-12-02T05:38:30.000Z | 2019-02-08T11:16:12.000Z | include/dtc/cell/cell.hpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2019-04-13T16:27:29.000Z | 2022-01-07T14:42:46.000Z | /******************************************************************************
* *
* Copyright (c) 2018, Tsung-Wei Huang, Chun-Xun Lin, and Martin D. F. Wong, *
* University of Illinois at Urbana-Champaign (UIUC), IL, USA. *
* *
* All Rights Reserved. *
* *
* This program is free software. You can redistribute and/or modify *
* it in accordance with the terms of the accompanying license agreement. *
* See LICENSE in the top-level directory for details. *
* *
******************************************************************************/
#ifndef DTC_CELL_CELL_HPP_
#define DTC_CELL_CELL_HPP_
#include <dtc/cell/visitor.hpp>
#include <dtc/cell/operator.hpp>
#include <dtc/cell/feeder/feeder.hpp>
#endif
| 49.086957 | 80 | 0.355182 | tsung-wei-huang |
1054d6d9d8f0cb216d372576bf8147d76d19b906 | 3,646 | cpp | C++ | kernel/node/Directory.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | 2 | 2020-07-14T21:16:54.000Z | 2020-10-08T08:40:47.000Z | kernel/node/Directory.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | null | null | null | kernel/node/Directory.cpp | busybox11/skift | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | [
"MIT"
] | null | null | null |
#include <libsystem/Logger.h>
#include <libsystem/Result.h>
#include <libsystem/core/CString.h>
#include "kernel/node/Directory.h"
#include "kernel/node/Handle.h"
static Result directory_open(FsDirectory *node, FsHandle *handle)
{
DirectoryListing *listing = (DirectoryListing *)malloc(sizeof(DirectoryListing) + sizeof(DirectoryEntry) * node->childs->count());
listing->count = node->childs->count();
int current_index = 0;
list_foreach(FsDirectoryEntry, entry, node->childs)
{
DirectoryEntry *record = &listing->entries[current_index];
FsNode *node = entry->node;
strcpy(record->name, entry->name);
record->stat.type = node->type;
if (node->size)
{
record->stat.size = node->size(entry->node, nullptr);
}
else
{
record->stat.size = 0;
}
current_index++;
};
handle->attached = listing;
return SUCCESS;
}
static void directory_close(FsDirectory *node, FsHandle *handle)
{
__unused(node);
free(handle->attached);
}
static Result directory_read(FsDirectory *node, FsHandle *handle, void *buffer, uint size, size_t *read)
{
__unused(node);
// FIXME: directories should no be read using read().
if (size == sizeof(DirectoryEntry))
{
size_t index = handle->offset / sizeof(DirectoryEntry);
DirectoryListing *listing = (DirectoryListing *)handle->attached;
if (index < listing->count)
{
*((DirectoryEntry *)buffer) = listing->entries[index];
*read = sizeof(DirectoryEntry);
}
}
return SUCCESS;
}
static FsNode *directory_find(FsDirectory *node, const char *name)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
return fsnode_ref(entry->node);
}
};
return nullptr;
}
static Result directory_link(FsDirectory *node, const char *name, FsNode *child)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
return ERR_FILE_EXISTS;
}
};
FsDirectoryEntry *new_entry = __create(FsDirectoryEntry);
new_entry->node = fsnode_ref(child);
strcpy(new_entry->name, name);
list_pushback(node->childs, new_entry);
return SUCCESS;
}
static void directory_entry_destroy(FsDirectoryEntry *entry)
{
fsnode_deref(entry->node);
free(entry);
}
static Result directory_unlink(FsDirectory *node, const char *name)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
list_remove(node->childs, entry);
directory_entry_destroy(entry);
return SUCCESS;
}
}
return ERR_NO_SUCH_FILE_OR_DIRECTORY;
}
static void directory_destroy(FsDirectory *node)
{
list_destroy_with_callback(node->childs, (ListDestroyElementCallback)directory_entry_destroy);
}
FsNode *directory_create()
{
FsDirectory *directory = __create(FsDirectory);
fsnode_init(directory, FILE_TYPE_DIRECTORY);
directory->open = (FsNodeOpenCallback)directory_open;
directory->close = (FsNodeCloseCallback)directory_close;
directory->read = (FsNodeReadCallback)directory_read;
directory->find = (FsNodeFindCallback)directory_find;
directory->link = (FsNodeLinkCallback)directory_link;
directory->unlink = (FsNodeUnlinkCallback)directory_unlink;
directory->destroy = (FsNodeDestroyCallback)directory_destroy;
directory->childs = list_create();
return (FsNode *)directory;
}
| 24.469799 | 134 | 0.657707 | busybox11 |
10563e7a19863fd6b7c1c62240c38c3222a06c1f | 1,488 | cpp | C++ | src/main_collector.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | 1 | 2021-08-21T12:49:27.000Z | 2021-08-21T12:49:27.000Z | src/main_collector.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | null | null | null | src/main_collector.cpp | despargy/KukaImplementation-kinetic | 3a9ab106b117acfc6478fbf3e60e49b7e94b2722 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <thread>
// #include <autharl_core/controller/gravity_compensation.h>
// #include <autharl_core/robot/robot_sim.h>
#include <autharl_core>
#include <lwr_robot/robot.h>
//
// #include <autharl_core/viz/ros_state_publisher.h>
// #include <autharl_core/robot/ros_model.h>
#include <kuka_implementation/collector.h>
int main(int argc, char** argv)
{
// Initialize the ROS node
ros::init(argc, argv, "get_desired_trajectory");
ros::NodeHandle n;
// Create the robot after you have launch the URDF on the parameter server
auto model = std::make_shared<arl::robot::ROSModel>();
// Create a simulated robot, use can use a real robot also
// auto robot = std::make_shared<arl::robot::RobotSim>(model, 1e-3);
auto robot = std::make_shared<arl::lwr::Robot>(model);
// Create a visualizater for see the result in rviz
auto rviz = std::make_shared<arl::viz::RosStatePublisher>(robot);
// Create the joint trajectory controller
// auto gravity_compensation_position = std::make_shared<arl::controller::GravityCompensation>(robot);
auto collector = std::make_shared<Collector>(robot);
std::thread rviz_thread(&arl::viz::RosStatePublisher::run, rviz);
//thread for keyboard inter
// Run the trajectory controller
collector->run();
ros::spin();
rviz_thread.join();
// // thread to collect Data
// robot->getJointPosition();
// store them by GravityX.txt , GravitY.txt GravityZ.txt under /data folder
return 0;
}
| 28.075472 | 104 | 0.719758 | despargy |
10584bac766b71c8bedf792af1ae53c0665fe320 | 612 | cpp | C++ | src/RE/TESContainer.cpp | FruitsBerriesMelons123/CommonLibSSE | 7ae21d11b9e9c86b0596fc1cfa58b6993a568125 | [
"MIT"
] | 1 | 2020-09-25T18:18:09.000Z | 2020-09-25T18:18:09.000Z | src/RE/TESContainer.cpp | FruitsBerriesMelons123/CommonLibSSE | 7ae21d11b9e9c86b0596fc1cfa58b6993a568125 | [
"MIT"
] | null | null | null | src/RE/TESContainer.cpp | FruitsBerriesMelons123/CommonLibSSE | 7ae21d11b9e9c86b0596fc1cfa58b6993a568125 | [
"MIT"
] | 1 | 2020-10-26T19:05:05.000Z | 2020-10-26T19:05:05.000Z | #include "RE/TESContainer.h"
#include "RE/FormTypes.h"
#include "RE/TESForm.h"
namespace RE
{
auto TESContainer::GetContainerObjectAt(UInt32 a_idx) const
-> std::optional<ContainerObject*>
{
if (a_idx < numContainerObjects) {
return std::make_optional(containerObjects[a_idx]);
} else {
return std::nullopt;
}
}
SInt32 TESContainer::CountObjectsInContainer(TESBoundObject* a_object) const
{
SInt32 count = 0;
ForEachContainerObject([&](ContainerObject* a_contObj)
{
if (a_contObj->obj == a_object) {
count += a_contObj->count;
}
return true;
});
return count;
}
}
| 18.545455 | 77 | 0.69281 | FruitsBerriesMelons123 |
105e8a8c8849240134205cbad4b48cc321374235 | 3,738 | cpp | C++ | src/eigensolve.cpp | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 18 | 2015-05-09T21:53:43.000Z | 2021-12-01T07:52:09.000Z | src/eigensolve.cpp | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 5 | 2016-05-29T09:02:09.000Z | 2021-05-07T16:36:38.000Z | src/eigensolve.cpp | norlab-ulaval/wmrde | 69e1f20bedd9c145878d44dbe17b3de405696fe3 | [
"BSD-2-Clause"
] | 11 | 2016-07-15T16:46:51.000Z | 2022-03-14T13:11:22.000Z | #include <wmrde/eigensolve.h>
void eigenSolveDynamic( const int nrows, const int ncols, Real* A, Real* b, Real* x ) {
Eigen::Map<MatrixXr> A_(A,nrows,ncols);
Eigen::Map<MatrixXr> b_(b,nrows,1);
Eigen::Map<MatrixXr> x_(x,ncols,1);
if ( nrows == ncols ) {
x_ = A_.llt().solve(b_); //requires positive definite
} else {
x_ = A_.householderQr().solve(b_);
}
}
void eigenSolveFixed( const int nrows, const int ncols, Real* A, Real* b, Real* x ) {
#ifdef FIXED_NROWS_0
if (FIXED_NROWS_0 == nrows && FIXED_NCOLS_0 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_0,FIXED_NCOLS_0>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_0,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_0,1>> x_(x);
#if FIXED_NROWS_0 == FIXED_NCOLS_0
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_1
if (FIXED_NROWS_1 == nrows && FIXED_NCOLS_1 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_1,FIXED_NCOLS_1>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_1,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_1,1>> x_(x);
#if FIXED_NROWS_1 == FIXED_NCOLS_1
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_2
if (FIXED_NROWS_2 == nrows && FIXED_NCOLS_2 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_2,FIXED_NCOLS_2>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_2,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_2,1>> x_(x);
#if FIXED_NROWS_2 == FIXED_NCOLS_2
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_3
if (FIXED_NROWS_3 == nrows && FIXED_NCOLS_3 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_3,FIXED_NCOLS_3>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_3,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_3,1>> x_(x);
#if FIXED_NROWS_3 == FIXED_NCOLS_3
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#if PRINT_MATRIX_SIZE_IF_DYNAMIC
std::cout << "resorting to eigenSolveDynamic, nrows = " << nrows << ", ncols = " << ncols << std::endl;
#endif
eigenSolveDynamic(nrows, ncols, A, b, x); //fail safe
}
//Cholesky decomposition
bool eigenCholDynamic( const int n, Real* A, Real* L) {
Eigen::Map<MatrixXr> A_(A,n,n);
Eigen::Map<MatrixXr> L_(L,n,n);
// L_ = A_.llt().matrixL();
Eigen::LLT<MatrixXr> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
bool eigenCholFixed( const int n, Real* A, Real* L) {
#ifdef FIXED_N_0
if (FIXED_N_0 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#ifdef FIXED_N_1
if (FIXED_N_1 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#ifdef FIXED_N_2
if (FIXED_N_2 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#if PRINT_MATRIX_SIZE_IF_DYNAMIC
std::cout << "resorting to eigenCholDynamic, n = " << n << std::endl;
#endif
return eigenCholDynamic(n,A,L); //fail safe
}
| 26.892086 | 104 | 0.67603 | norlab-ulaval |
105eae46a93cf2dfed9c56935880b1b46319e7b6 | 827 | cpp | C++ | src/StillDataTask.cpp | stefunkk/openstill | 17cc439fe9dbe7dea02588d77e51652fc1cc50ce | [
"MIT"
] | 1 | 2021-02-13T08:40:50.000Z | 2021-02-13T08:40:50.000Z | src/StillDataTask.cpp | stefunkk/openstill | 17cc439fe9dbe7dea02588d77e51652fc1cc50ce | [
"MIT"
] | null | null | null | src/StillDataTask.cpp | stefunkk/openstill | 17cc439fe9dbe7dea02588d77e51652fc1cc50ce | [
"MIT"
] | null | null | null | #include "StillDataTask.h"
StillDataTaskClass::StillDataTaskClass(StillDataContextClass &context, FileServiceClass &fileService, SensorDataClass &data, SettingsClass &settings) : _settings(settings), _data(data), _fileService(fileService), _context(context)
{
}
void StillDataTaskClass::exec()
{
if (_context.clearCsv)
{
_fileService.removeFile(_fileName);
_context.clearCsv = false;
}
char csvEntry[100];
sprintf(csvEntry, "%i;%.2f;%.2f;%.2f;%.2f;%i; %\n", (int)(millis()/1000) ,(float)_data.shelf10, (float)_data.header, (float)_data.tank, (float)_data.water, (int)_settings.percentagePower);
_fileService.saveFile(_fileName, csvEntry);
}
uint32_t StillDataTaskClass::timeOfNextCheck()
{
setTriggered(true);
return millisToMicros(_settings.csvTimeFrameInSeconds * 1000);
}
| 33.08 | 230 | 0.729141 | stefunkk |
105fe483961cb78caa1f8d264789e68c31b7447f | 6,327 | cpp | C++ | src/VAC/VectorAnimationComplex/ProperCycle.cpp | CELLINKAB/VPaint | 7f415b54bdaeff8b0bbd11f101d4aa34135a4404 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/VAC/VectorAnimationComplex/ProperCycle.cpp | CELLINKAB/VPaint | 7f415b54bdaeff8b0bbd11f101d4aa34135a4404 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2022-01-16T22:33:35.000Z | 2022-03-25T07:27:52.000Z | src/VAC/VectorAnimationComplex/ProperCycle.cpp | CELLINKAB/VPaint | 7f415b54bdaeff8b0bbd11f101d4aa34135a4404 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (C) 2012-2019 The VPaint Developers.
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT
//
// 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 "ProperCycle.h"
#include "KeyEdge.h"
#include "../SaveAndLoad.h"
#include <QMessageBox>
namespace VectorAnimationComplex
{
ProperCycle::ProperCycle()
{
// invalid by default, nothing to do (since edges_ is empty)
}
ProperCycle::ProperCycle(const KeyEdgeSet & edgeSetConst)
{
// If no edge, then invalid
if(edgeSetConst.isEmpty())
return;
// if not all edges at same time, then invalid
KeyEdge * first = *edgeSetConst.begin();
Time t = first->time();
for(KeyEdge * iedge: edgeSetConst)
{
if(iedge->time() != t)
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not all edges are on same time"));
return;
}
}
// copy the set to be able to modify it
KeyEdgeSet edgeSet = edgeSetConst;
// insert first edge
halfedges_ << KeyHalfedge(first, true);
edgeSet.erase(edgeSet.begin());
// check case where it's a pure loop
if(first->isClosed())
{
if(!edgeSet.isEmpty())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("more than one edge and one of them is a pure loop"));
halfedges_.clear();
return;
}
// else: good!
}
else
{
// not a pure loop, let's find the chain
while(!edgeSet.isEmpty())
{
KeyHalfedge lastAddedHalfedge = halfedges_.last(); // we know it's not a loop, otherwise couldn't be here
KeyVertex * lastVertex = lastAddedHalfedge.endVertex(); // hence this is a valid vertex
// find next
KeyHalfedge nextHalfedge;
auto it = edgeSet.begin();
auto itEnd = edgeSet.end();
for(;it!=itEnd;++it)
{
if((*it)->startVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, true);
break;
}
else if((*it)->endVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, false);
break;
}
}
// if found: great, insert it!
if(nextHalfedge.isValid())
{
halfedges_ << nextHalfedge;
edgeSet.erase(it);
}
else
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: no valid next edge found"));
halfedges_.clear();
return;
}
}
// So far, we've inserted all N edges, and every edge i in [0,N-2]
// satisfies edges_[i]->endVertex() == edges_[i+1]->startVertex()
// Check that it's looping
if(halfedges_.last().endVertex() != halfedges_.first().startVertex())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: last edge not compatible with first one"));
halfedges_.clear();
return;
}
// Check that it's simple
KeyVertexSet vertices;
for(KeyHalfedge he: qAsConst(halfedges_))
{
KeyVertex * vertex = he.startVertex();
if(vertices.contains(vertex))
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: not simple"));
halfedges_.clear();
return;
}
else
{
vertices << vertex;
}
}
// Done :-) If you're here you have a valid simple loop
}
}
bool ProperCycle::isValid() const
{
return !halfedges_.isEmpty();
}
Time ProperCycle::time() const
{
return halfedges_[0].time();
}
int ProperCycle::size() const
{
return halfedges_.size();
}
KeyHalfedge ProperCycle::operator[](int i) const
{
return halfedges_[i];
}
void ProperCycle::remapPointers(VAC * newVAC)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].remapPointers(newVAC);
}
void ProperCycle::convertTempIdsToPointers(VAC * vac)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].convertTempIdsToPointers(vac);
}
// Replace pointed edges
void ProperCycle::replaceEdges(KeyEdge * oldEdge, const KeyEdgeList & newEdges)
{
QList<KeyHalfedge> newHalfedges;
for(KeyHalfedge he: qAsConst(halfedges_))
{
if(he.edge == oldEdge)
{
// Replace halfedge
if(he.side)
{
for(int i=0; i<newEdges.size(); ++i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
else
{
for(int i=newEdges.size()-1; i>=0; --i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
}
else
{
// Keep halfedge as is
newHalfedges << he;
}
}
halfedges_ = newHalfedges;
}
} // end namespace VectorAnimationComplex
QTextStream & operator<<(QTextStream & out, const VectorAnimationComplex::ProperCycle & loop)
{
out << loop.halfedges_;
return out;
}
QTextStream & operator>>(QTextStream & in, VectorAnimationComplex::ProperCycle & loop)
{
in >> loop.halfedges_;
return in;
}
| 28.245536 | 117 | 0.549708 | CELLINKAB |
106028bea8c96f4985efaf4ab67d71352f11a2f7 | 1,473 | cpp | C++ | SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PlayerPawnTest_Male_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript
// ()
void APlayerPawnTest_Male_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript");
APlayerPawnTest_Male_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void APlayerPawnTest_Male_C::ExecuteUbergraph_PlayerPawnTest_Male(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male");
APlayerPawnTest_Male_C_ExecuteUbergraph_PlayerPawnTest_Male_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 25.842105 | 140 | 0.700611 | 2bite |
10602be24a2497a4266315d313a235479c764566 | 5,441 | cpp | C++ | l-ten/optimizer.cpp | adeobootpin/light-tensor | dfc2d19495848e773b7367427cf848e4ac30b29d | [
"MIT"
] | null | null | null | l-ten/optimizer.cpp | adeobootpin/light-tensor | dfc2d19495848e773b7367427cf848e4ac30b29d | [
"MIT"
] | null | null | null | l-ten/optimizer.cpp | adeobootpin/light-tensor | dfc2d19495848e773b7367427cf848e4ac30b29d | [
"MIT"
] | null | null | null | #include <cmath>
#include <string.h>
#include "tensor.h"
#include "layers.h"
#include "net.h"
#include "optimizer.h"
#include "error.h"
namespace lten {
void SGDOptimizer::setup_optimizer()
{
int i;
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
*network_params_ptr_[i].param_data_ = AllocateTensor(network_params_ptr_[i].param_->get_sizes(), network_params_ptr_[i].param_->get_ndims(),0); // allocate buffer for momentum/velocity
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels);
}
}
void SGDOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* velocity_ptr;
int i;
uint64_t j;
uint64_t numels;
device device_type;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
if (device_type == CPU)
{
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
for (j = 0; j < numels; j++)
{
weight_grad_ptr[j] = wd_ * weight_ptr[j] + weight_grad_ptr[j];
velocity_ptr[j] = velocity_ptr[j] * mo_ + (1.0f - mo_) * weight_grad_ptr[j];
weight_ptr[j] = weight_ptr[j] - (velocity_ptr[j] * lr_);
}
}
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
gpu_sgd_step(weight_ptr, weight_grad_ptr, velocity_ptr, numels, mo_, wd_, lr_);
}
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
void AdamOptimizer::setup_optimizer()
{
int i;
uint64_t dims[MAX_DIMS];
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
memcpy(dims, network_params_ptr_[i].param_->get_sizes(), sizeof(uint64_t) * network_params_ptr_[i].param_->get_ndims());
dims[0] *= 3; // make room for momentum, rmsprop histories and scratch space
*network_params_ptr_[i].param_data_ = AllocateTensor(dims, network_params_ptr_[i].param_->get_ndims(), 0); // allocate history buffer
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels * 3);
}
}
void AdamOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* v_dw;
float* s_dw;
float* scratch;
float epsilon;
uint64_t numels;
int i;
device device_type;
float bias_correction1;
float bias_correction2;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
iteration_++;
epsilon = 1.0e-8f;
for (i = 0; i < num_params_; i++)
{
weight_grad_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_grad_ptr());
if (!weight_grad_ptr)
{
continue;
}
weight_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_data_ptr());
numels = network_params_ptr_[i].param_->get_numels();
v_dw = static_cast<float*>(network_params_ptr_[i].param_data_->get_data_ptr());
s_dw = v_dw + (numels);
scratch = v_dw + (2 * numels);
bias_correction1 = 1.0f - powf(beta1_, static_cast<float>(iteration_));
bias_correction2 = 1.0f - powf(beta2_, static_cast<float>(iteration_));
if (device_type == CPU)
{
cpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
cpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
cpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
cpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
cpu_powx(numels, scratch, 0.5f, scratch);
cpu_add(numels, epsilon, scratch, scratch);
cpu_div(numels, v_dw, scratch, scratch);
cpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
gpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
gpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
gpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
gpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
gpu_powx(numels, scratch, 0.5f, scratch);
gpu_add(numels, epsilon, scratch, scratch);
gpu_div(numels, v_dw, scratch, scratch);
gpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
}
} // namespace btpn
| 28.78836 | 187 | 0.679287 | adeobootpin |
1060d8c918966a41ece1a66555cd052063418fbf | 46,376 | cpp | C++ | compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp | mariecwhite/iree | 6031ff4080f5755bcc52826a8d41ae7360106ffd | [
"Apache-2.0"
] | null | null | null | compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp | mariecwhite/iree | 6031ff4080f5755bcc52826a8d41ae7360106ffd | [
"Apache-2.0"
] | null | null | null | compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp | mariecwhite/iree | 6031ff4080f5755bcc52826a8d41ae7360106ffd | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/LLVMCPU/KernelDispatch.h"
#include <numeric>
#include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "iree/compiler/Codegen/Transforms/Transforms.h"
#include "iree/compiler/Codegen/Utils/MarkerUtils.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
namespace mlir {
namespace iree_compiler {
/// NOTE: None of these flags are supported in any form long term. This are
/// temporary hooks added for development purposes. They could be
/// changed/modified at any time.
/// TODO: Find a way to plumb this through to not rely on these flags.
static llvm::cl::opt<int> clNativeVectorSizeInBytes(
"iree-codegen-llvm-vector-size-in-bytes",
llvm::cl::desc("native vector size to use on the hardware"),
llvm::cl::init(16));
static llvm::cl::opt<int> clNumberOfRuntimeThreads(
"iree-codegen-llvm-number-of-threads",
llvm::cl::desc("number of threads that are used at runtime"),
llvm::cl::init(8));
static llvm::cl::list<int> mmt4dWorkgroupTileSizes(
"iree-codegen-llvm-mmt4d-workgroup-tile-sizes",
llvm::cl::desc("linalg.mmt4d workgroup tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dL1TileSizes(
"iree-codegen-llvm-mmt4d-l1-tile-size",
llvm::cl::desc("linalg.mmt4d L1 tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dVectorSizes(
"iree-codegen-llvm-mmt4d-vector-size",
llvm::cl::desc("linalg.mmt4d vector tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::opt<int> defaultWorkgroupTileSize(
"iree-codegen-llvm-generic-ops-workgroup-size",
llvm::cl::desc(
"linalg.generic and linalg.indexed_generic workgroup tile size"),
llvm::cl::init(64));
static llvm::cl::opt<bool> useLinalgTransformInterp(
"iree-codegen-use-linalg-transform-interp",
llvm::cl::desc(
"experimental path to use the linalg transform dialect interpreter"),
llvm::cl::init(false));
using IREE::Codegen::DispatchLoweringPassPipeline;
/// Looks for the `native_vector_size` attribute in the hal.executable.variant
/// op.
static Optional<int64_t> getNativeVectorSizeInBytes(func::FuncOp entryPointFn) {
auto variantOp =
entryPointFn->getParentOfType<IREE::HAL::ExecutableVariantOp>();
if (!variantOp) return llvm::None;
IREE::HAL::ExecutableTargetAttr targetAttr = variantOp.target();
if (!targetAttr) return llvm::None;
auto config = targetAttr.getConfiguration();
if (!config) return llvm::None;
auto nativeVectorSizeAttr = config.getAs<IntegerAttr>("native_vector_size");
if (!nativeVectorSizeAttr) return llvm::None;
int64_t nativeVectorSizeVal = nativeVectorSizeAttr.getInt();
if (!nativeVectorSizeVal) return llvm::None;
return nativeVectorSizeVal;
}
/// For a given `shapedType` or (`byteWidth` of element type) return the number
/// of elements that correspond to the native vector size. Returns 1 as the
/// fallback.
static int64_t getVectorSize(func::FuncOp entryPointFn, unsigned byteWidth) {
if (Optional<int64_t> nativeVectorSize =
getNativeVectorSizeInBytes(entryPointFn)) {
return nativeVectorSize.getValue() / byteWidth;
}
return clNativeVectorSizeInBytes / byteWidth;
}
static int64_t getVectorSize(func::FuncOp entryPointFn, ShapedType shapedType) {
Type elementType = shapedType.getElementType();
if (!elementType.isIntOrFloat()) return 1;
unsigned byteWidth = IREE::Util::getRoundedElementByteWidth(elementType);
return getVectorSize(entryPointFn, byteWidth);
}
/// Returns minimum tiling sizes for each dimension. One dimension is possible
/// to access at different element types. It determines the tiling sizes by
/// looking into all the operands.
static SmallVector<int64_t> getMinTilingSizesForEachDim(
func::FuncOp entryPointFn, linalg::LinalgOp op) {
unsigned numLoops = op.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
auto inputOutputOpOperands = op.getInputAndOutputOperands();
for (auto map : llvm::enumerate(op.getIndexingMaps())) {
// Check the fastest varying dimension of the operand. Set the vector size
// of the corresponding loop to the vector size.
if (map.value().getNumResults() == 0) continue;
auto fastestVaryingDimExpr =
map.value().getResults().back().dyn_cast<AffineDimExpr>();
if (!fastestVaryingDimExpr) continue;
unsigned fastestVaryingDim = fastestVaryingDimExpr.getPosition();
// If the indexing map has result it has to be a shaped type.
auto operandType =
inputOutputOpOperands[map.index()]->get().getType().cast<ShapedType>();
minTileSizes[fastestVaryingDim] =
std::max<int64_t>(minTileSizes[fastestVaryingDim],
getVectorSize(entryPointFn, operandType));
}
return minTileSizes;
}
/// Returns the type length in bytes. Looks through all the interface binding
/// ops to see the ABI types and guess-timates the type size to use. This is
/// used to convert the vector size in bytes to vector size in number of
/// elements.
static unsigned getReferenceTypeLengthInBytes(func::FuncOp entryPointFn) {
unsigned referenceTypeLengthInBytes = 4;
entryPointFn.walk([&](IREE::HAL::InterfaceBindingSubspanOp subSpanOp) {
Type type = subSpanOp.getResult().getType();
Type elementType = TypeSwitch<Type, Type>(type)
.Case<ShapedType, IREE::Flow::DispatchTensorType>(
[&](auto shapedType) -> Type {
// Ignore operands that are 0D tensors. These
// are not vector-loadable, so using these to
// get vector length would be a pessimization.
if (!shapedType.getRank()) return nullptr;
return shapedType.getElementType();
})
.Default([&](Type t) -> Type { return nullptr; });
if (!elementType || !elementType.isIntOrFloat()) return;
unsigned typeWidthInBytes =
IREE::Util::getRoundedElementByteWidth(elementType);
referenceTypeLengthInBytes =
std::min<unsigned>(referenceTypeLengthInBytes, typeWidthInBytes);
});
return referenceTypeLengthInBytes;
}
/// Returns the default tile sizes to use for the loops that are distributed at
/// Flow level.
static SmallVector<int64_t> getDefaultDistributedLoopTileSizes(
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs,
ArrayRef<int64_t> minTileSizes, ArrayRef<int64_t> maxTileSizes,
ArrayRef<int64_t> vectorSizeHints) {
assert(lbs.size() == ubs.size() && lbs.size() == minTileSizes.size() &&
lbs.size() == maxTileSizes.size() &&
"expected all vectors to be of equal size");
size_t numDims = lbs.size();
SmallVector<int64_t> distributedTileSizes(numDims, 1);
SmallVector<int64_t> numWorkgroupsPerDim(numDims, 1);
SmallVector<int64_t> workload(numDims, 1);
for (auto i : llvm::seq<size_t>(0, numDims)) {
if (maxTileSizes[i] == 0 || ShapedType::isDynamic(lbs[i]) ||
ShapedType::isDynamic(ubs[i])) {
distributedTileSizes[i] = maxTileSizes[i];
workload[i] = ShapedType::kDynamicSize;
continue;
}
assert(lbs[i] <= ubs[i]);
workload[i] = ubs[i] - lbs[i];
int64_t candidateTileSize = 1;
int64_t targetSize = std::min(workload[i] / 2, maxTileSizes[i]);
int64_t vectorSize = vectorSizeHints[i];
if (vectorSize > 1) {
// Pick the factor of dim which is closest to the target tile size and
// is a multiplier of vector size.
for (int64_t k = vectorSize; k <= targetSize; k += vectorSize) {
if (workload[i] % k == 0 && k >= minTileSizes[i]) {
candidateTileSize = k;
}
}
}
// Fallback to power of 2 if there's no hint or can't find the ideal size.
if (vectorSize <= 1 || candidateTileSize == 1) {
candidateTileSize =
std::max<int64_t>(llvm::PowerOf2Floor(targetSize), minTileSizes[i]);
}
// Limit the workload per workgroup to the default being the max to keep the
// work per invocation reasonable.
distributedTileSizes[i] =
std::min<int64_t>(candidateTileSize, maxTileSizes[i]);
numWorkgroupsPerDim[i] =
llvm::divideCeil(workload[i], distributedTileSizes[i]);
}
// Reduce the number of workgroups in cases where we are dividing the work too
// much. Over-provision the number of workgroups to twice the number of
// threads.
int64_t numWorkgroupsLimit = 2 * clNumberOfRuntimeThreads;
int64_t numWorkgroups =
std::accumulate(numWorkgroupsPerDim.begin(), numWorkgroupsPerDim.end(),
1LL, std::multiplies<int64_t>{});
unsigned currDim = numDims;
while (numWorkgroups > numWorkgroupsLimit && currDim > 0) {
unsigned index = currDim - 1;
int64_t currSize = distributedTileSizes[index];
if (currSize >= maxTileSizes[index] ||
workload[index] == ShapedType::kDynamicSize ||
currSize >= workload[index]) {
currDim--;
continue;
}
int64_t newSize = std::min<int64_t>(currSize * 2, maxTileSizes[index]);
int64_t vectorSize = vectorSizeHints[index];
// Chech if it's the ideal size with vector size hint. And skip if the new
// size will break the ideal size.
if (vectorSize > 1 &&
(currSize % vectorSize == 0 && workload[index] % currSize == 0) &&
(newSize % vectorSize != 0 || workload[index] % newSize != 0)) {
currDim--;
continue;
}
distributedTileSizes[index] = newSize;
int64_t nwg =
llvm::divideCeil(workload[index], distributedTileSizes[index]);
if (nwg < numWorkgroupsPerDim[index]) {
numWorkgroups /= numWorkgroupsPerDim[index];
numWorkgroups *= nwg;
} else {
currDim--;
}
}
return distributedTileSizes;
}
/// Adjusts the workload per workgroup to be a multiple of vector size to ensure
/// that the op vectorizes.
static int64_t getMaxTileSize(int64_t lb, int64_t ub, int64_t maxSize,
int64_t vectorSizeVal) {
if (ub == ShapedType::kDynamicSize || lb == ShapedType::kDynamicSize) {
return maxSize;
}
int64_t dim = ub - lb;
if (dim < vectorSizeVal) return dim;
for (int64_t i = std::min(maxSize, dim); i > 0; --i) {
if (dim % i == 0 && i % vectorSizeVal == 0) {
return i;
}
}
// If it can't be a multiple of vectorSizeVal, let's choose a factor of dim
// sizes heuristically.
int64_t start = std::min(maxSize, dim);
start = std::min(start, vectorSizeVal * 2);
for (int64_t i = start; i > 0; --i) {
if (dim % i == 0) {
return i;
}
}
return 1;
}
/// Returns the tile size to use for the Flow level.
///
/// The vectorSizeHints can be empty or as many as the number of loops. When not
/// empty, each hint should be 1 or the vector size. On the dimensions where the
/// hints != 1, it will try to find the tile sizes which are multipliers of the
/// hints.
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
ArrayRef<unsigned> partitionableLoops, ArrayRef<int64_t> lbs,
ArrayRef<int64_t> ubs, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
int64_t numLoops = lbs.size();
assert(numLoops == minTileSizes.size() && maxTileSizes.size() == numLoops &&
"expected as many min/max tile sizes as number of loops");
assert(
vectorSizeHints.empty() ||
vectorSizeHints.size() == numLoops &&
"vector size hints should be empty or equal to the number of loops");
// Only set values when the loop is partitionable.
SmallVector<int64_t> adjustedMinTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedMaxTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedVectorSizeHints(numLoops, 1);
for (auto i : partitionableLoops) {
adjustedMinTileSizes[i] = minTileSizes[i];
adjustedMaxTileSizes[i] = maxTileSizes[i];
if (!vectorSizeHints.empty()) {
adjustedVectorSizeHints[i] = vectorSizeHints[i];
}
}
SmallVector<int64_t> distributedTileSizes =
getDefaultDistributedLoopTileSizes(lbs, ubs, adjustedMinTileSizes,
adjustedMaxTileSizes,
adjustedVectorSizeHints);
// Final fix up of the tile sizes to make sure that they divide the problem
// size to make it vectorizable.
for (auto i : llvm::seq<unsigned>(0, distributedTileSizes.size())) {
if (!distributedTileSizes[i]) continue;
distributedTileSizes[i] = getMaxTileSize(
lbs[i], ubs[i], distributedTileSizes[i], minTileSizes[i]);
}
return distributedTileSizes;
}
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
linalg::LinalgOp linalgOp, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
OpBuilder builder(linalgOp.getContext());
builder.setInsertionPoint(linalgOp);
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
auto loops =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation())
.getPartitionableLoops(kNumMaxParallelDims);
return getDefaultDistributedLevelTileSizes(loops, lbs, ubs, minTileSizes,
maxTileSizes, vectorSizeHints);
}
/// Splits the tile sizes in `parallelSizes` into `reductionSizes` for the
/// reduction loops.
static void splitParallelAndReductionTiles(
linalg::LinalgOp op, SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
reductionSizes.assign(parallelSizes.begin(), parallelSizes.end());
for (auto iteratorType : llvm::enumerate(op.iterator_types())) {
if (iteratorType.value().cast<StringAttr>().getValue() ==
getParallelIteratorTypeName()) {
reductionSizes[iteratorType.index()] = 0;
} else {
parallelSizes[iteratorType.index()] = 0;
}
}
}
static void setAlwaysVectorizeSizes(linalg::LinalgOp op,
SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
SmallVector<int64_t, 4> staticLoopRanges = op.getStaticLoopRanges();
for (auto en :
llvm::enumerate(llvm::zip(staticLoopRanges, op.iterator_types()))) {
auto size = std::get<0>(en.value());
if (!ShapedType::isDynamic(size)) continue;
auto iterType = std::get<1>(en.value()).cast<StringAttr>().getValue();
if (iterType == getParallelIteratorTypeName()) {
parallelSizes[en.index()] = 1;
} else {
reductionSizes[en.index()] = 1;
}
}
}
/// Sets the default configuration to use for an operation that implements the
/// `PartitionableLoopsInterface`, given the `lbs` and `ubs` of all the loops.
static LogicalResult setDefaultRootConfig(
func::FuncOp entryPointFn,
IREE::Flow::PartitionableLoopsInterface partitionableLoopsInterfaceOp,
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs, bool hasTensorSemantics) {
if (getLoweringConfig(partitionableLoopsInterfaceOp)) return success();
SmallVector<unsigned> partitionableLoops =
partitionableLoopsInterfaceOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> minTileSizes(lbs.size(), 1);
SmallVector<int64_t> maxTileSizes(lbs.size(), 1);
if (!partitionableLoops.empty()) {
// TODO: Here the min tile size is just looking at the type of the data in
// the entry point function, and using a vector size that depends on just
// that. For `LinalgOp`s we can use the indexing map, find the loops that
// are fastest varying and set those to have a min tile size of vector
// length. A version of this is done for generic ops. Generalize that and
// use it for `LinalgOp`s.
unsigned typeWidthInBytes = getReferenceTypeLengthInBytes(entryPointFn);
minTileSizes[partitionableLoops.back()] =
getVectorSize(entryPointFn, typeWidthInBytes);
for (auto partitionableLoopId : partitionableLoops) {
maxTileSizes[partitionableLoopId] = defaultWorkgroupTileSize;
}
}
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
partitionableLoops, lbs, ubs, minTileSizes, maxTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(std::move(flowTileSizes));
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, partitionableLoopsInterfaceOp, tileSizes,
hasTensorSemantics ? DispatchLoweringPassPipeline::CPUDefault
: DispatchLoweringPassPipeline::CPUBufferOpsDefault);
}
static LogicalResult setSandboxRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
ArrayRef<int64_t> target2ndTileSizes,
int vectorSize) {
assert(target2ndTileSizes.size() == 3 &&
"the current configuration is driven by matmul which has exactly "
"three loops");
// The tiling for parallel dims and reduction dims should be separated.
SmallVector<int64_t> parallelTileSizes;
auto linalgOp = cast<linalg::LinalgOp>(op.getOperation());
int64_t nLoops = linalgOp.getNumLoops();
if (nLoops >= 3) {
parallelTileSizes.append(nLoops - 3, 1);
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 3], target2ndTileSizes[0], vectorSize));
}
if (nLoops >= 2) {
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 2], target2ndTileSizes[1], vectorSize));
}
parallelTileSizes.push_back(0);
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
SmallVector<int64_t> reductionTileSizes;
reductionTileSizes.append(nLoops - 1, 0);
reductionTileSizes.push_back(
getMaxTileSize(0, K, target2ndTileSizes[2], vectorSize));
setAlwaysVectorizeSizes(linalgOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUDoubleTilingExpert);
}
static LogicalResult setARMRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
int vectorSize) {
// Hardcoded tile sizes, where v is the native vector size.
// L1 tile sizes are {1, ..., 5v, v, 16v}.
// Vector tile sizes are {1, ..., v, v, v}
SmallVector<int64_t> l1TileSizes, vectorTileSizes;
int64_t nLoops = cast<linalg::LinalgOp>(op.getOperation()).getNumLoops();
if (nLoops >= 3) {
l1TileSizes.append(nLoops - 3, 1);
l1TileSizes.push_back(getMaxTileSize(0, flowTileSizes[nLoops - 3],
5 * vectorSize, vectorSize));
vectorTileSizes.append(nLoops - 3, 1);
vectorTileSizes.push_back(vectorSize);
}
if (nLoops >= 2) {
l1TileSizes.push_back(
getMaxTileSize(0, flowTileSizes[nLoops - 2], vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
}
// L1/vector tile size for k dimensions.
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
l1TileSizes.push_back(getMaxTileSize(0, K, 16 * vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(l1TileSizes);
tileSizes.push_back(vectorTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region with root op that
/// implements the contraction operation interface.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::ContractionOpInterface contractionOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
auto linalgOp = cast<linalg::LinalgOp>(contractionOp.getOperation());
unsigned numLoops = linalgOp.getNumLoops();
{
SmallVector<unsigned> dims;
linalgOp.getReductionDims(dims);
if (dims.size() != 1 || dims[0] != numLoops - 1) {
return contractionOp.emitOpError(
"expected to have exactly one reduction dim, and it is the innermost "
"dim");
}
}
// Consider all element types and use the smallest vector size. The tiling
// sizes are chosen based on the vector size.
auto lhsShapedType = contractionOp.lhs().getType().cast<ShapedType>();
auto rhsShapedType = contractionOp.rhs().getType().cast<ShapedType>();
auto resShapedType =
linalgOp.getOutputOperand(0)->get().getType().cast<ShapedType>();
int64_t vectorSize = getVectorSize(entryPointFn, lhsShapedType);
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, rhsShapedType));
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, resShapedType));
// Use the default distribution for the matmul loops.
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, linalgOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (numLoops > 3) {
minTileSizes[0] = 1;
maxTileSizes[0] = 1;
}
SmallVector<int64_t> flowTileSizes =
getDefaultDistributedLevelTileSizes(linalgOp, minTileSizes, maxTileSizes);
// TODO(dcaballe): Find better configurations for RISC-V backends.
if (isX86(entryPointFn) || isRISCV(entryPointFn)) {
SmallVector<int64_t> tileSizes = {8, 32, 16};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
}
// Fall back to ARM configurations.
bool isQuantized =
lhsShapedType.getElementType() != resShapedType.getElementType();
if (isQuantized) {
SmallVector<int64_t> tileSizes = {4, 16, 4};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
} else {
return setARMRootConfig(entryPointFn, contractionOp, flowTileSizes,
vectorSize);
}
}
/// Sets the lowering configuration for dispatch region for linalg.mmt4d root
/// op
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Mmt4DOp mmt4dOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// TODO(ataei): These are hand tuned for some performance benchmarks for
// now, we want to adapt the same strategy as matmul that dynamically sets
// tile size.
auto getWorkgroupTileSizes = [&]() -> SmallVector<int64_t> {
if (!mmt4dWorkgroupTileSizes.empty()) {
return SmallVector<int64_t>(mmt4dWorkgroupTileSizes.begin(),
mmt4dWorkgroupTileSizes.end());
}
return {48, 32};
};
auto getL1TileSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dL1TileSizes.empty()) {
return SmallVector<int64_t>(mmt4dL1TileSizes.begin(),
mmt4dL1TileSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
auto getVectorSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dVectorSizes.empty()) {
return SmallVector<int64_t>(mmt4dVectorSizes.begin(),
mmt4dVectorSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
SmallVector<int64_t> nativeVectorSize = getVectorSizes();
TileSizesListType tileSizes = {getWorkgroupTileSizes(), getL1TileSizes(),
nativeVectorSize};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, mmt4dOp, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region for linalg_ext.fft
/// root op.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, IREE::LinalgExt::FftOp fftOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
unsigned numLoops = fftOp.getLoopIteratorTypes().size();
auto partitionedLoops = fftOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> workgroupTileSizes(numLoops, defaultWorkgroupTileSize);
llvm::DenseSet<unsigned> partitionedLoopsSet(partitionedLoops.begin(),
partitionedLoops.end());
for (auto dim : llvm::seq<int64_t>(0, workgroupTileSizes.size())) {
if (!partitionedLoopsSet.count(dim)) {
workgroupTileSizes[dim] = 0;
}
}
auto rank = fftOp.getOperandRank();
if (workgroupTileSizes.size() >= rank && workgroupTileSizes[rank - 1] != 0) {
APInt value;
if (matchPattern(fftOp.getStage(), m_ConstantInt(&value))) {
workgroupTileSizes[rank - 1] = 1ll << value.getSExtValue();
workgroupTileSizes[rank - 1] =
std::max(workgroupTileSizes[rank - 1],
static_cast<int64_t>(defaultWorkgroupTileSize));
} else {
return fftOp.emitOpError("non-constant stage might not work for fft op");
}
}
TileSizesListType tileSizes = {workgroupTileSizes};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, fftOp, tileSizes, DispatchLoweringPassPipeline::CPUDefault);
}
static void setX86WorkgroupTileSizes(
linalg::GenericOp genericOp, unsigned numLoops,
ArrayRef<int64_t> flowTileSizes, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes,
SmallVectorImpl<int64_t> &workgroupTileSizes) {
workgroupTileSizes.append(numLoops, 0);
SmallVector<int64_t, 4> staticLoopRanges = genericOp.getStaticLoopRanges();
for (auto loopNum : llvm::seq<unsigned>(0, numLoops)) {
if (flowTileSizes[loopNum]) {
workgroupTileSizes[loopNum] =
getMaxTileSize(0, flowTileSizes[loopNum], minTileSizes[loopNum],
minTileSizes[loopNum]);
} else {
// If the flow level tile size is zero, and static loop range is 0 as
// well, set the tile sizes here to zero as well.
workgroupTileSizes[loopNum] =
staticLoopRanges[loopNum] == 1 ? 0 : minTileSizes[loopNum];
}
}
}
/// Returns true if the operation is a GenericOp implementing a supported
/// transposition.
static bool isSupportedTransposeOp(linalg::GenericOp genericOp) {
// Check that the op has at least 2 dimensions.
if (genericOp.getNumLoops() < 2) {
return false;
}
// Check that the op has only one input and one output.
// TODO(diegocaballero): Generalize to multiple inputs.
if ((genericOp.getNumInputs() != 1) || (genericOp.getNumOutputs() != 1)) {
return false;
}
// Check that all the iterators are parallel.
if (genericOp.getNumParallelLoops() != genericOp.getNumLoops()) {
return false;
}
// Check that the two indexing maps are a permutation of each other.
auto indexing_maps = genericOp.getIndexingMaps();
return !indexing_maps[0].isEmpty() && !indexing_maps[1].isEmpty() &&
((indexing_maps[0].isIdentity() && !indexing_maps[1].isIdentity() &&
indexing_maps[1].isPermutation()) ||
(!indexing_maps[0].isIdentity() && indexing_maps[0].isPermutation() &&
indexing_maps[1].isIdentity()));
}
/// Sets the default lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setDefaultGenericOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
// If there are no loops, there is nothing to do.
unsigned numLoops = genericOp.getNumLoops();
if (numLoops == 0) return success();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
SmallVector<int64_t> reductionTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
splitParallelAndReductionTiles(genericOp, parallelTileSizes,
reductionTileSizes);
setAlwaysVectorizeSizes(genericOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op implementing a
/// transposition to use CPUDoubleTilingExpert pipeline.
static LogicalResult setTransposeLikeOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
if (!hasAVX2Features(genericOp) || !isSupportedTransposeOp(genericOp)) {
return success();
}
unsigned numLoops = genericOp.getNumLoops();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
if (llvm::count_if(minTileSizes,
[](int64_t tileSize) { return tileSize > 1; }) != 2) {
// Transpose patterns are not applicable if vectorizing more or less than
// two dims.
return success();
}
// Make sure that the original tile sizes are multiple of the tile sizes
// to be used for the transpose op (i.e., 8x8).
// TODO(diegocaballero): Enable 4x8 tile sizes if we find it useful.
if (llvm::any_of(minTileSizes, [](int64_t tileSize) {
return tileSize > 1 && (tileSize % 8) != 0;
})) {
return success();
}
// Replace dims to be vectorized with the new 8x8 tile sizes.
std::replace_if(
minTileSizes.begin(), minTileSizes.end(),
[](int64_t tileSize) { return tileSize > 1; }, 8);
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(/*reduction tile sizes=*/{});
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (failed(
setTransposeLikeOpRootConfig(entryPointFn, genericOp, tiledLoops)) ||
failed(
setDefaultGenericOpRootConfig(entryPointFn, genericOp, tiledLoops))) {
return failure();
}
return success();
}
/// Sets the lowering configuration for linalg.conv_2d_nhwc_hwcf and
/// linalg.depthwise_conv_2d_nhwc_hwc operations.
static LogicalResult setConvRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops,
ArrayRef<int64_t> targetTileSizes, int64_t vectorSize) {
if (!isa<linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
convOp.getOperation())) {
return failure();
}
// Use the default distribution for the conv loops.
unsigned numLoops = convOp.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
SmallVector<int64_t> vectorSizeHints(numLoops, 1);
// Give the vector size hint on OC.
vectorSizeHints[3] = vectorSize;
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
convOp, minTileSizes, maxTileSizes, vectorSizeHints);
// Shapes of N, OH, OW, OC, KH, KW, (IC)
SmallVector<int64_t, 4> shapes = convOp.getStaticLoopRanges();
SmallVector<int64_t> parallelTileSizes(targetTileSizes.begin(),
targetTileSizes.end());
for (auto i : llvm::seq<unsigned>(0, parallelTileSizes.size())) {
auto tileSize = flowTileSizes[i] ? flowTileSizes[i] : shapes[i];
// If the tile size is intended to be 1, do not adjust it to `vectorSize`.
// The ops will be decomposed to lower-rank named ops.
if (parallelTileSizes[i] != 1) {
parallelTileSizes[i] =
getMaxTileSize(0, tileSize, parallelTileSizes[i], vectorSize);
}
}
SmallVector<int64_t> reductionTileSizes;
splitParallelAndReductionTiles(convOp, parallelTileSizes, reductionTileSizes);
setAlwaysVectorizeSizes(convOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, convOp, tileSizes,
DispatchLoweringPassPipeline::CPUConvTileAndDecomposeExpert);
}
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Conv2DNhwcHwcfOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 1, 8};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Sets the lowering configuration for linalg.depthwise_conv_2d_nhwc_hwc
/// operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::DepthwiseConv2DNhwcHwcOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 3};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Set default configuration for Linalg ops.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp linalgOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(linalgOp)) return success();
auto partitionableLoopOp =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation());
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
linalgOp.hasTensorSemantics());
}
/// Set the default configuration for operations that implement the
/// `TiledOpInterface`.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn,
IREE::LinalgExt::TiledOpInterface tiledOpInterfaceOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(tiledOpInterfaceOp)) return success();
auto partitionableLoopOp = cast<IREE::Flow::PartitionableLoopsInterface>(
tiledOpInterfaceOp.getOperation());
// TODO(hanchung): Implement getStaticLoopRanges method for TiledOpInterface.
OpBuilder builder(tiledOpInterfaceOp.getContext());
builder.setInsertionPoint(tiledOpInterfaceOp);
SmallVector<Range> iterationDomain =
tiledOpInterfaceOp.getIterationDomain(builder);
auto getStaticValue = [](Value v) -> int64_t {
IntegerAttr attr;
if (!matchPattern(v, m_Constant(&attr))) return ShapedType::kDynamicSize;
return attr.getInt();
};
auto lbs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.offset); }));
auto ubs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.size); }));
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
/*hasTensorSemantics=*/true);
}
/// Redirects to methods that set the configuration based on operation type.
static LogicalResult setRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// Do not overwrite default configuration.
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<IREE::LinalgExt::FftOp, linalg::GenericOp, linalg::Mmt4DOp,
linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::ContractionOpInterface>([&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Redirects to methods that set the configuration based on operation type for
/// VMVX backend.
static LogicalResult setVMVXRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Find the root operation for the dispatch region.
static FailureOr<Operation *> getRootOperation(
ArrayRef<Operation *> computeOps) {
Operation *rootOperation = nullptr;
auto updateRootOperation = [&](Operation *op) -> LogicalResult {
if (rootOperation) {
return op->emitOpError(
"unhandled multiple root operations in dispatch region");
}
rootOperation = op;
return success();
};
for (auto op : computeOps) {
if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) {
// Do not not treat linalg ops that are all parallel as root operations in
// this sweep.
if (linalgOp.getNumLoops() == linalgOp.getNumParallelLoops()) continue;
// All other linalg ops are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
if (auto tiledOpInterfaceOp =
dyn_cast<IREE::LinalgExt::TiledOpInterface>(op)) {
// TODO(ravishankarm): For now
// `tensor.extract_slice`/`tensor.insert_slice` implement the
// `tiledInterfaceOp`. With tile + distribute moved out of Flow
// dialect, this doesnt work anymore. Remove this when the external
// model implementation of
// `tensor.extract_slice`/`tensor.insert_slice` are dropped.
if (isa<tensor::ExtractSliceOp, tensor::InsertSliceOp>(op)) continue;
// All other operations that implement this interface are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
}
if (rootOperation) return rootOperation;
// If no root operation is found yet. Look for linalg generic ops.
for (auto op : llvm::reverse(computeOps)) {
if (isa<linalg::LinalgOp>(op)) {
if (failed(updateRootOperation(op))) return failure();
}
}
return rootOperation;
}
/// Finds the root operation in the given list of Linalg operations and sets
/// its configuration. Returns error for multiple root operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
FailureOr<Operation *> rootOp = getRootOperation(computeOps);
if (failed(rootOp)) {
return failure();
}
Operation *rootOperation = rootOp.getValue();
if (rootOperation) {
if (isVMVXBackend(entryPointFn)) {
if (failed(
setVMVXRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
} else {
if (failed(setRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
}
}
if (!getTranslationInfo(entryPointFn)) {
// Fall back, just set the translation to CPUDefault.
setTranslationInfo(entryPointFn, DispatchLoweringPassPipeline::CPUDefault,
/*workloadPerWorkgroup=*/ArrayRef<int64_t>{},
/*workgroupSize=*/ArrayRef<int64_t>{});
}
return success();
}
/// Sets the translation information to use for a dispatch region.
static LogicalResult setTranslationInfoAndRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// First check if the operations have a preset pipeline.
for (auto computeOp : computeOps) {
if (IREE::Codegen::CompilationInfoAttr compilationInfo =
getCompilationInfo(computeOp)) {
// If the function already has a translation, error out.
if (auto translationInfo = getTranslationInfo(entryPointFn)) {
return computeOp->emitOpError(
"multiple ops within dispatch trying to set the translation "
"info");
}
SmallVector<int64_t> workgroupSize =
compilationInfo.getWorkgroupSizeVals();
setTranslationInfo(entryPointFn, compilationInfo.getTranslationInfo(),
workgroupSize);
setLoweringConfig(computeOp, compilationInfo.getLoweringConfig());
eraseCompilationInfo(computeOp);
}
}
// Next set the configuration of the operations.
return setRootConfig(entryPointFn, computeOps, tiledLoops);
}
LogicalResult initCPULaunchConfig(ModuleOp moduleOp) {
llvm::StringMap<IREE::HAL::ExecutableEntryPointOp> entryPointOps =
getAllEntryPoints(moduleOp);
for (auto funcOp : moduleOp.getOps<func::FuncOp>()) {
auto entryPointOp = entryPointOps.lookup(funcOp.getName());
if (!entryPointOp) continue;
if (getTranslationInfo(entryPointOp)) continue;
// If using sandbox passes, currently set the workload_per_wg to be
// empty for single-threaded execution.
if (useLinalgTransformInterp) {
auto translationInfo = IREE::Codegen::TranslationInfoAttr::get(
moduleOp.getContext(), IREE::Codegen::DispatchLoweringPassPipeline::
LinalgTransformInterpCodegen);
setTranslationInfo(funcOp, translationInfo);
continue;
}
SmallVector<Operation *> computeOps;
SmallVector<LoopTilingAndDistributionInfo> tiledLoops;
// If there are no linalg ops, not using Linalg based lowering.
if (failed(getComputeOps(funcOp, computeOps, tiledLoops))) {
return failure();
}
if (failed(
setTranslationInfoAndRootConfig(funcOp, computeOps, tiledLoops))) {
return failure();
}
}
// The root confguration setting introduces `tensor.dim` operations. Resolve
// those away.
RewritePatternSet patterns(moduleOp.getContext());
memref::populateResolveRankedShapeTypeResultDimsPatterns(patterns);
return applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
} // namespace iree_compiler
} // namespace mlir
| 41.518353 | 80 | 0.697149 | mariecwhite |
1062ce617d1f9a3bdc8442fd27d859de02c7627b | 5,990 | cpp | C++ | src/array_list.cpp | Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004 | 8f61838429414fec507b26db48d2546d31066e94 | [
"MIT"
] | null | null | null | src/array_list.cpp | Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004 | 8f61838429414fec507b26db48d2546d31066e94 | [
"MIT"
] | null | null | null | src/array_list.cpp | Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004 | 8f61838429414fec507b26db48d2546d31066e94 | [
"MIT"
] | null | null | null | #include "array_list.hpp" // подключаем заголовочный файл с объявлениями
#include <algorithm> // copy, fill
#include <cassert> // assert
#include <stdexcept> // out_of_range, invalid_argument
#include "private/internal.hpp" // вспомогательные функции
namespace itis {
ArrayList::ArrayList(int capacity) : capacity_{capacity} {
if (capacity <= 0) {
throw std::invalid_argument("ArrayList::capacity must be positive");
}
// Tip 1: используйте std::fill для заполнения выделенных ячеек массива значением Element::UNINITIALIZED
// здесь должен быть ваш код ...
data_ = new Element[capacity_]{};
std::fill(data_, data_ + capacity_, Element::UNINITIALIZED);
}
ArrayList::~ArrayList() {
// Tip 1: высвободите выделенную память
// Tip 2: не забудьте про логическую целостность объекта (инвариантность)
if (data_ != nullptr) {
delete[] data_;
data_ = nullptr;
}
size_ = 0;
capacity_ = 0;
}
void ArrayList::Add(Element e) {
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// здесь должен быть ваш код ...
if (size_ == capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я здесь, чтобы не дать тебе сойти с правильного пути
// напишите свой код после расширения емкости массива здесь ...
data_[size_++] = e;
}
void ArrayList::Insert(int index, Element e) {
if (index != 0 && index != size_) {
// index = 0 и index == size это особые случаи, при которых всегда можно выполнить операцию вставки
internal::check_out_of_range(index, 0, size_);
}
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// напишите свой код здесь ...
if (size_ >= capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я ни в коем случае не дам вам совершить ошибку всей вашей жизни
// Tip 2: для свдига элементов вправо можете использовать std::copy
// напишите свой код после расширения емкости массива здесь ...
std::copy(data_ + index, data_ + size_, data_ + index + 1);
data_[index] = e;
size_ += 1;
}
void ArrayList::Set(int index, Element value) {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
data_[index] = value;
}
Element ArrayList::Remove(int index) {
internal::check_out_of_range(index, 0, size_);
// Tip 1: можете использовать std::copy для сдвига элементов влево
// Tip 2: не забудьте задать значение Element::UNINITIALIZED освободившейся ячейке
// напишите свой код здесь ...
Element element = data_[index];
std::copy(data_ + index + 1, data_+size_, data_+index );
data_[size_ - 1] = Element::UNINITIALIZED;
size_--;
return element;
}
void ArrayList::Clear() {
// Tip 1: можете использовать std::fill для заполнения ячеек массива значением Element::UNINITIALIZED
// напишите свой код здесь ...
std::fill(data_, data_+capacity_, Element::UNINITIALIZED);
size_ = 0;
}
Element ArrayList::Get(int index) const {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
return data_[index];
}
int ArrayList::IndexOf(Element e) const {
// напишите свой код здесь ...
for (int i = 0; i < size_; ++i) {
if (data_[i] == e){
return i;
}
}
return -1;
}
// === РЕАЛИЗОВАНО ===
bool ArrayList::Contains(Element e) const {
// здесь был Рамиль
return IndexOf(e) != kNotFoundElementIndex;
}
// это делегирующий конструктор если что
ArrayList::ArrayList() : ArrayList(kInitCapacity) {}
int ArrayList::GetSize() const {
return size_;
}
int ArrayList::GetCapacity() const {
return capacity_;
}
bool ArrayList::IsEmpty() const {
return size_ == 0;
}
// Легенда: давным давно на планете под названием Земля жил да был Аватар...
// Аватар мог управлять четырьмя стихиями, но никак не мог совладать с C++ (фейспалм).
// Помогите найти непростительную ошибку Аватара,
// которая привела к гибели десятков тысяч котиков (плак-плак, шмыгание носом, втягивание соплей).
// P.S. кол-во ошибок может быть более одной, порядку операций можно верить
void ArrayList::resize(int new_capacity) {
assert(new_capacity > capacity_); // не ошибается тот, кто ничего не делает ...
// 1. выделяем новый участок памяти
auto new_data = new Element[new_capacity];
// 2. копируем данные на новый участок
std::copy(data_, data_ + size_, new_data);
// 3. заполняем "свободные" ячейки памяти значением Element::UNINITIALIZED
std::fill(new_data + size_, new_data + new_capacity, Element::UNINITIALIZED);
// 4. высвобождаем старый участок памяти меньшего размера
delete[] data_;
// 5. пересылаем указатель на новый участок памяти
data_ = new_data;
// 6. не забываем посолить ... кхм... обновить емкость массива
capacity_ = new_capacity;
}
// === ЗОНА 51: необходимо для тестирования ===
ArrayList::ArrayList(Element *data, int size, int capacity) : size_{size}, capacity_{capacity} {
assert(capacity > 0 && size >= 0 && size <= capacity);
data_ = new Element[capacity];
std::fill(data_, data_ + capacity, Element::UNINITIALIZED);
if (data != nullptr) {
std::copy(data, data + size, data_);
}
}
std::ostream &operator<<(std::ostream &os, const ArrayList &list) {
if (list.data_ != nullptr) {
os << "{ ";
for (int index = 0; index < list.capacity_ - 1; index++) {
os << internal::elem_to_str(list.data_[index]) << ", ";
}
os << internal::elem_to_str(list.data_[list.capacity_ - 1]) << " }";
} else {
os << "{ nullptr }";
}
return os;
}
bool operator==(const ArrayList &list, const std::vector<Element> &elements) {
if (list.data_ == nullptr) return false;
if (list.capacity_ != static_cast<int>(elements.size())) return false;
for (int index = 0; index < list.capacity_; index++) {
if (list.data_[index] != elements.at(index)) return false;
}
return true;
}
} // namespace itis | 31.197917 | 106 | 0.676294 | Algorithms-and-Data-Structures-2021 |
10657de129cf0bec27e58132bad7f2a326edd139 | 17,327 | cpp | C++ | third/3rd_qwt/qwt_plot_spectrogram.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 3,095 | 2019-10-11T03:00:33.000Z | 2022-03-31T08:15:13.000Z | third/3rd_qwt/qwt_plot_spectrogram.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 28 | 2019-11-12T07:24:06.000Z | 2022-02-28T02:04:48.000Z | third/3rd_qwt/qwt_plot_spectrogram.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 1,023 | 2019-10-09T12:54:07.000Z | 2022-03-30T04:02:07.000Z | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_spectrogram.h"
#include "qwt_painter.h"
#include "qwt_interval.h"
#include "qwt_scale_map.h"
#include "qwt_color_map.h"
#include <qimage.h>
#include <qpen.h>
#include <qpainter.h>
#include <qmath.h>
#include <qalgorithms.h>
#if QT_VERSION >= 0x040400
#include <qthread.h>
#include <qfuture.h>
#include <qtconcurrentrun.h>
#endif
#define DEBUG_RENDER 0
#if DEBUG_RENDER
#include <QElapsedTimer>
#endif
class QwtPlotSpectrogram::PrivateData
{
public:
PrivateData():
data( NULL )
{
colorMap = new QwtLinearColorMap();
displayMode = ImageMode;
conrecFlags = QwtRasterData::IgnoreAllVerticesOnLevel;
#if 0
conrecFlags |= QwtRasterData::IgnoreOutOfRange;
#endif
}
~PrivateData()
{
delete data;
delete colorMap;
}
QwtRasterData *data;
QwtColorMap *colorMap;
DisplayModes displayMode;
QList<double> contourLevels;
QPen defaultContourPen;
QwtRasterData::ConrecFlags conrecFlags;
};
/*!
Sets the following item attributes:
- QwtPlotItem::AutoScale: true
- QwtPlotItem::Legend: false
The z value is initialized by 8.0.
\param title Title
\sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ()
*/
QwtPlotSpectrogram::QwtPlotSpectrogram( const QString &title ):
QwtPlotRasterItem( title )
{
d_data = new PrivateData();
setItemAttribute( QwtPlotItem::AutoScale, true );
setItemAttribute( QwtPlotItem::Legend, false );
setZ( 8.0 );
}
//! Destructor
QwtPlotSpectrogram::~QwtPlotSpectrogram()
{
delete d_data;
}
//! \return QwtPlotItem::Rtti_PlotSpectrogram
int QwtPlotSpectrogram::rtti() const
{
return QwtPlotItem::Rtti_PlotSpectrogram;
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\param on On/Off
The default setting enables ImageMode.
\sa DisplayMode, displayMode()
*/
void QwtPlotSpectrogram::setDisplayMode( DisplayMode mode, bool on )
{
if ( on != bool( mode & d_data->displayMode ) )
{
if ( on )
d_data->displayMode |= mode;
else
d_data->displayMode &= ~mode;
}
legendChanged();
itemChanged();
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\return true if mode is enabled
*/
bool QwtPlotSpectrogram::testDisplayMode( DisplayMode mode ) const
{
return ( d_data->displayMode & mode );
}
/*!
Change the color map
Often it is useful to display the mapping between intensities and
colors as an additional plot axis, showing a color bar.
\param colorMap Color Map
\sa colorMap(), QwtScaleWidget::setColorBarEnabled(),
QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectrogram::setColorMap( QwtColorMap *colorMap )
{
if ( d_data->colorMap != colorMap )
{
delete d_data->colorMap;
d_data->colorMap = colorMap;
}
invalidateCache();
legendChanged();
itemChanged();
}
/*!
\return Color Map used for mapping the intensity values to colors
\sa setColorMap()
*/
const QwtColorMap *QwtPlotSpectrogram::colorMap() const
{
return d_data->colorMap;
}
/*!
Build and assign the default pen for the contour lines
In Qt5 the default pen width is 1.0 ( 0.0 in Qt4 ) what makes it
non cosmetic ( see QPen::isCosmetic() ). This method has been introduced
to hide this incompatibility.
\param color Pen color
\param width Pen width
\param style Pen style
\sa pen(), brush()
*/
void QwtPlotSpectrogram::setDefaultContourPen(
const QColor &color, qreal width, Qt::PenStyle style )
{
setDefaultContourPen( QPen( color, width, style ) );
}
/*!
\brief Set the default pen for the contour lines
If the spectrogram has a valid default contour pen
a contour line is painted using the default contour pen.
Otherwise (pen.style() == Qt::NoPen) the pen is calculated
for each contour level using contourPen().
\sa defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::setDefaultContourPen( const QPen &pen )
{
if ( pen != d_data->defaultContourPen )
{
d_data->defaultContourPen = pen;
legendChanged();
itemChanged();
}
}
/*!
\return Default contour pen
\sa setDefaultContourPen()
*/
QPen QwtPlotSpectrogram::defaultContourPen() const
{
return d_data->defaultContourPen;
}
/*!
\brief Calculate the pen for a contour line
The color of the pen is the color for level calculated by the color map
\param level Contour level
\return Pen for the contour line
\note contourPen is only used if defaultContourPen().style() == Qt::NoPen
\sa setDefaultContourPen(), setColorMap(), setContourLevels()
*/
QPen QwtPlotSpectrogram::contourPen( double level ) const
{
if ( d_data->data == NULL || d_data->colorMap == NULL )
return QPen();
const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis);
const QColor c( d_data->colorMap->rgb( intensityRange, level ) );
return QPen( c );
}
/*!
Modify an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\param on On/Off
\sa testConrecFlag(), renderContourLines(),
QwtRasterData::contourLines()
*/
void QwtPlotSpectrogram::setConrecFlag(
QwtRasterData::ConrecFlag flag, bool on )
{
if ( bool( d_data->conrecFlags & flag ) == on )
return;
if ( on )
d_data->conrecFlags |= flag;
else
d_data->conrecFlags &= ~flag;
itemChanged();
}
/*!
Test an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\return true, is enabled
The default setting enables QwtRasterData::IgnoreAllVerticesOnLevel
\sa setConrecClag(), renderContourLines(),
QwtRasterData::contourLines()
*/
bool QwtPlotSpectrogram::testConrecFlag(
QwtRasterData::ConrecFlag flag ) const
{
return d_data->conrecFlags & flag;
}
/*!
Set the levels of the contour lines
\param levels Values of the contour levels
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
\note contourLevels returns the same levels but sorted.
*/
void QwtPlotSpectrogram::setContourLevels( const QList<double> &levels )
{
d_data->contourLevels = levels;
qSort( d_data->contourLevels );
legendChanged();
itemChanged();
}
/*!
\return Levels of the contour lines.
The levels are sorted in increasing order.
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
*/
QList<double> QwtPlotSpectrogram::contourLevels() const
{
return d_data->contourLevels;
}
/*!
Set the data to be displayed
\param data Spectrogram Data
\sa data()
*/
void QwtPlotSpectrogram::setData( QwtRasterData *data )
{
if ( data != d_data->data )
{
delete d_data->data;
d_data->data = data;
invalidateCache();
itemChanged();
}
}
/*!
\return Spectrogram data
\sa setData()
*/
const QwtRasterData *QwtPlotSpectrogram::data() const
{
return d_data->data;
}
/*!
\return Spectrogram data
\sa setData()
*/
QwtRasterData *QwtPlotSpectrogram::data()
{
return d_data->data;
}
/*!
\return Bounding interval for an axis
The default implementation returns the interval of the
associated raster data object.
\param axis X, Y, or Z axis
\sa QwtRasterData::interval()
*/
QwtInterval QwtPlotSpectrogram::interval(Qt::Axis axis) const
{
if ( d_data->data == NULL )
return QwtInterval();
return d_data->data->interval( axis );
}
/*!
\brief Pixel hint
The geometry of a pixel is used to calculated the resolution and
alignment of the rendered image.
The default implementation returns data()->pixelHint( rect );
\param area In most implementations the resolution of the data doesn't
depend on the requested area.
\return Bounding rectangle of a pixel
\sa QwtPlotRasterItem::pixelHint(), QwtRasterData::pixelHint(),
render(), renderImage()
*/
QRectF QwtPlotSpectrogram::pixelHint( const QRectF &area ) const
{
if ( d_data->data == NULL )
return QRectF();
return d_data->data->pixelHint( area );
}
/*!
\brief Render an image from data and color map.
For each pixel of area the value is mapped into a color.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param area Requested area for the image in scale coordinates
\param imageSize Size of the requested image
\return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending
on the color map.
\sa QwtRasterData::value(), QwtColorMap::rgb(),
QwtColorMap::colorIndex()
*/
QImage QwtPlotSpectrogram::renderImage(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &area, const QSize &imageSize ) const
{
if ( imageSize.isEmpty() || d_data->data == NULL
|| d_data->colorMap == NULL )
{
return QImage();
}
const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis );
if ( !intensityRange.isValid() )
return QImage();
QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB )
? QImage::Format_ARGB32 : QImage::Format_Indexed8;
QImage image( imageSize, format );
if ( d_data->colorMap->format() == QwtColorMap::Indexed )
image.setColorTable( d_data->colorMap->colorTable( intensityRange ) );
d_data->data->initRaster( area, image.size() );
#if DEBUG_RENDER
QElapsedTimer time;
time.start();
#endif
#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
uint numThreads = renderThreadCount();
if ( numThreads <= 0 )
numThreads = QThread::idealThreadCount();
if ( numThreads <= 0 )
numThreads = 1;
const int numRows = imageSize.height() / numThreads;
QList< QFuture<void> > futures;
for ( uint i = 0; i < numThreads; i++ )
{
QRect tile( 0, i * numRows, image.width(), numRows );
if ( i == numThreads - 1 )
{
tile.setHeight( image.height() - i * numRows );
renderTile( xMap, yMap, tile, &image );
}
else
{
futures += QtConcurrent::run(
this, &QwtPlotSpectrogram::renderTile,
xMap, yMap, tile, &image );
}
}
for ( int i = 0; i < futures.size(); i++ )
futures[i].waitForFinished();
#else // QT_VERSION < 0x040400
const QRect tile( 0, 0, image.width(), image.height() );
renderTile( xMap, yMap, tile, &image );
#endif
#if DEBUG_RENDER
const qint64 elapsed = time.elapsed();
qDebug() << "renderImage" << imageSize << elapsed;
#endif
d_data->data->discardRaster();
return image;
}
/*!
\brief Render a tile of an image.
Rendering in tiles can be used to composite an image in parallel
threads.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param tile Geometry of the tile in image coordinates
\param image Image to be rendered
*/
void QwtPlotSpectrogram::renderTile(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRect &tile, QImage *image ) const
{
const QwtInterval range = d_data->data->interval( Qt::ZAxis );
if ( !range.isValid() )
return;
if ( d_data->colorMap->format() == QwtColorMap::RGB )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
QRgb *line = reinterpret_cast<QRgb *>( image->scanLine( y ) );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->rgb( range,
d_data->data->value( tx, ty ) );
}
}
}
else if ( d_data->colorMap->format() == QwtColorMap::Indexed )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
unsigned char *line = image->scanLine( y );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->colorIndex( range,
d_data->data->value( tx, ty ) );
}
}
}
}
/*!
\brief Return the raster to be used by the CONREC contour algorithm.
A larger size will improve the precision of the CONREC algorithm,
but will slow down the time that is needed to calculate the lines.
The default implementation returns rect.size() / 2 bounded to
the resolution depending on pixelSize().
\param area Rectangle, where to calculate the contour lines
\param rect Rectangle in pixel coordinates, where to paint the contour lines
\return Raster to be used by the CONREC contour algorithm.
\note The size will be bounded to rect.size().
\sa drawContourLines(), QwtRasterData::contourLines()
*/
QSize QwtPlotSpectrogram::contourRasterSize(
const QRectF &area, const QRect &rect ) const
{
QSize raster = rect.size() / 2;
const QRectF pixelRect = pixelHint( area );
if ( !pixelRect.isEmpty() )
{
const QSize res( qCeil( rect.width() / pixelRect.width() ),
qCeil( rect.height() / pixelRect.height() ) );
raster = raster.boundedTo( res );
}
return raster;
}
/*!
Calculate contour lines
\param rect Rectangle, where to calculate the contour lines
\param raster Raster, used by the CONREC algorithm
\return Calculated contour lines
\sa contourLevels(), setConrecFlag(),
QwtRasterData::contourLines()
*/
QwtRasterData::ContourLines QwtPlotSpectrogram::renderContourLines(
const QRectF &rect, const QSize &raster ) const
{
if ( d_data->data == NULL )
return QwtRasterData::ContourLines();
return d_data->data->contourLines( rect, raster,
d_data->contourLevels, d_data->conrecFlags );
}
/*!
Paint the contour lines
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param contourLines Contour lines
\sa renderContourLines(), defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::drawContourLines( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QwtRasterData::ContourLines &contourLines ) const
{
if ( d_data->data == NULL )
return;
const int numLevels = d_data->contourLevels.size();
for ( int l = 0; l < numLevels; l++ )
{
const double level = d_data->contourLevels[l];
QPen pen = defaultContourPen();
if ( pen.style() == Qt::NoPen )
pen = contourPen( level );
if ( pen.style() == Qt::NoPen )
continue;
painter->setPen( pen );
const QPolygonF &lines = contourLines[level];
for ( int i = 0; i < lines.size(); i += 2 )
{
const QPointF p1( xMap.transform( lines[i].x() ),
yMap.transform( lines[i].y() ) );
const QPointF p2( xMap.transform( lines[i+1].x() ),
yMap.transform( lines[i+1].y() ) );
QwtPainter::drawLine( painter, p1, p2 );
}
}
}
/*!
\brief Draw the spectrogram
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param canvasRect Contents rectangle of the canvas in painter coordinates
\sa setDisplayMode(), renderImage(),
QwtPlotRasterItem::draw(), drawContourLines()
*/
void QwtPlotSpectrogram::draw( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &canvasRect ) const
{
if ( d_data->displayMode & ImageMode )
QwtPlotRasterItem::draw( painter, xMap, yMap, canvasRect );
if ( d_data->displayMode & ContourMode )
{
// Add some pixels at the borders
const int margin = 2;
QRectF rasterRect( canvasRect.x() - margin, canvasRect.y() - margin,
canvasRect.width() + 2 * margin, canvasRect.height() + 2 * margin );
QRectF area = QwtScaleMap::invTransform( xMap, yMap, rasterRect );
const QRectF br = boundingRect();
if ( br.isValid() )
{
area &= br;
if ( area.isEmpty() )
return;
rasterRect = QwtScaleMap::transform( xMap, yMap, area );
}
QSize raster = contourRasterSize( area, rasterRect.toRect() );
raster = raster.boundedTo( rasterRect.toRect().size() );
if ( raster.isValid() )
{
const QwtRasterData::ContourLines lines =
renderContourLines( area, raster );
drawContourLines( painter, xMap, yMap, lines );
}
}
}
| 25.593796 | 80 | 0.638656 | alexwang815 |
1065eeaf318f78ed4feed93033341be6eec19c41 | 1,077 | hpp | C++ | libs/core/include/fcppt/math/from_array.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/math/from_array.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/math/from_array.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#define FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#include <fcppt/math/to_array_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
/**
\brief Constructs an object with static storage from an array rvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> &&_value
)
{
return
Type{
typename
Type::storage_type{
std::move(
_value
)
}
};
}
/**
\brief Constructs an object with static storage from an array lvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> const &_value
)
{
return
Type{
typename
Type::storage_type{
_value
}
};
}
}
}
#endif
| 13.987013 | 68 | 0.702878 | pmiddend |
10677ee5952433bf423e50d1f02b932be93f7c50 | 2,067 | cpp | C++ | logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 1 | 2021-05-19T23:01:58.000Z | 2021-05-19T23:01:58.000Z | logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-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.
*/
#include "ServiceDiscoveryConfig.h"
#include <folly/Range.h>
#include "logdevice/common/debug.h"
#include "logdevice/common/types_internal.h"
namespace facebook { namespace logdevice { namespace configuration {
namespace nodes {
namespace {
template <typename F>
bool isFieldValid(const F& field, folly::StringPiece name) {
if (!field.valid()) {
RATELIMIT_ERROR(
std::chrono::seconds(10), 5, "invalid %s.", name.str().c_str());
return false;
}
return true;
}
template <typename F>
bool isOptionalFieldValid(const F& field, folly::StringPiece name) {
return !field.hasValue() || isFieldValid(field.value(), name);
}
} // namespace
bool NodeServiceDiscovery::isValid() const {
if (!isFieldValid(address, "address") &&
!isFieldValid(gossip_address, "gossip_address") &&
!isOptionalFieldValid(ssl_address, "ssl_address") &&
!isOptionalFieldValid(admin_address, "admin_address")) {
return false;
}
if (roles.count() == 0) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"no role is set. expect at least one role.");
return false;
}
return true;
}
template <>
bool ServiceDiscoveryConfig::attributeSpecificValidate() const {
// check for address duplication in service discovery
std::unordered_map<Sockaddr, node_index_t, Sockaddr::Hash> seen_addresses;
for (const auto& kv : node_states_) {
auto res =
seen_addresses.insert(std::make_pair(kv.second.address, kv.first));
if (!res.second) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"Multiple nodes with the same address (idx: %hd, %hd).",
res.first->second,
kv.first);
return false;
}
}
return true;
}
}}}} // namespace facebook::logdevice::configuration::nodes
| 27.56 | 78 | 0.652637 | mickvav |
1069154212618384b2b5d27c09594afb0fdf6f97 | 32,407 | cpp | C++ | filament/src/Engine.cpp | tombsar/filament | 20dadf06f1399fc03aaa7c8796daaf237f96416d | [
"Apache-2.0"
] | 1 | 2021-06-12T21:17:58.000Z | 2021-06-12T21:17:58.000Z | filament/src/Engine.cpp | tombsar/filament | 20dadf06f1399fc03aaa7c8796daaf237f96416d | [
"Apache-2.0"
] | null | null | null | filament/src/Engine.cpp | tombsar/filament | 20dadf06f1399fc03aaa7c8796daaf237f96416d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "details/Engine.h"
#include "MaterialParser.h"
#include "ResourceAllocator.h"
#include "backend/DriverEnums.h"
#include "details/DFG.h"
#include "details/VertexBuffer.h"
#include "details/Fence.h"
#include "details/Camera.h"
#include "details/IndexBuffer.h"
#include "details/IndirectLight.h"
#include "details/Material.h"
#include "details/Renderer.h"
#include "details/RenderPrimitive.h"
#include "details/Scene.h"
#include "details/Skybox.h"
#include "details/Stream.h"
#include "details/SwapChain.h"
#include "details/Texture.h"
#include "details/View.h"
#include <private/filament/SibGenerator.h>
#include <filament/MaterialEnums.h>
#include <utils/compiler.h>
#include <utils/Log.h>
#include <utils/Panic.h>
#include <utils/Systrace.h>
#include <utils/debug.h>
#include <memory>
#include "generated/resources/materials.h"
using namespace filament::math;
using namespace utils;
namespace filament {
using namespace backend;
using namespace filaflat;
FEngine* FEngine::create(Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// initialize all fields that need an instance of FEngine
// (this cannot be done safely in the ctor)
// Normally we launch a thread and create the context and Driver from there (see FEngine::loop).
// In the single-threaded case, we do so in the here and now.
if (!UTILS_HAS_THREADING) {
if (platform == nullptr) {
platform = DefaultPlatform::create(&instance->mBackend);
instance->mPlatform = platform;
instance->mOwnPlatform = true;
}
if (platform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
return nullptr;
}
instance->mDriver = platform->createDriver(sharedGLContext);
} else {
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// wait for the driver to be ready
instance->mDriverBarrier.await();
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
}
// now we can initialize the largest part of the engine
instance->init();
if (!UTILS_HAS_THREADING) {
instance->execute();
}
return instance;
}
#if UTILS_HAS_THREADING
void FEngine::createAsync(CreateCallback callback, void* user,
Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// launch a thread to call the callback -- so it can't do any damage.
std::thread callbackThread = std::thread([instance, callback, user]() {
instance->mDriverBarrier.await();
callback(user, instance);
});
// let the callback thread die on its own
callbackThread.detach();
}
FEngine* FEngine::getEngine(void* token) {
FEngine* instance = static_cast<FEngine*>(token);
ASSERT_PRECONDITION(instance->mMainThreadId == std::this_thread::get_id(),
"Engine::createAsync() and Engine::getEngine() must be called on the same thread.");
// we use mResourceAllocator as a proxy for "am I already initialized"
if (!instance->mResourceAllocator) {
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
// now we can initialize the largest part of the engine
instance->init();
}
return instance;
}
#endif
// these must be static because only a pointer is copied to the render stream
// Note that these coordinates are specified in OpenGL clip space. Other backends can transform
// these in the vertex shader as needed.
static constexpr float4 sFullScreenTriangleVertices[3] = {
{ -1.0f, -1.0f, 1.0f, 1.0f },
{ 3.0f, -1.0f, 1.0f, 1.0f },
{ -1.0f, 3.0f, 1.0f, 1.0f }
};
// these must be static because only a pointer is copied to the render stream
static const uint16_t sFullScreenTriangleIndices[3] = { 0, 1, 2 };
FEngine::FEngine(Backend backend, Platform* platform, void* sharedGLContext) :
mBackend(backend),
mPlatform(platform),
mSharedGLContext(sharedGLContext),
mPostProcessManager(*this),
mEntityManager(EntityManager::get()),
mRenderableManager(*this),
mTransformManager(),
mLightManager(*this),
mCameraManager(*this),
mCommandBufferQueue(CONFIG_MIN_COMMAND_BUFFERS_SIZE, CONFIG_COMMAND_BUFFERS_SIZE),
mPerRenderPassAllocator("per-renderpass allocator", CONFIG_PER_RENDER_PASS_ARENA_SIZE),
mEngineEpoch(std::chrono::steady_clock::now()),
mDriverBarrier(1),
mMainThreadId(std::this_thread::get_id())
{
// we're assuming we're on the main thread here.
// (it may not be the case)
mJobSystem.adopt();
slog.i << "FEngine (" << sizeof(void*) * 8 << " bits) created at " << this << " "
<< "(threading is " << (UTILS_HAS_THREADING ? "enabled)" : "disabled)") << io::endl;
}
/*
* init() is called just after the driver thread is initialized. Driver commands are therefore
* possible.
*/
void FEngine::init() {
SYSTRACE_CALL();
// this must be first.
mCommandStream = CommandStream(*mDriver, mCommandBufferQueue.getCircularBuffer());
DriverApi& driverApi = getDriverApi();
mResourceAllocator = new ResourceAllocator(driverApi);
mFullScreenTriangleVb = upcast(VertexBuffer::Builder()
.vertexCount(3)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT4, 0)
.build(*this));
mFullScreenTriangleVb->setBufferAt(*this, 0,
{ sFullScreenTriangleVertices, sizeof(sFullScreenTriangleVertices) });
mFullScreenTriangleIb = upcast(IndexBuffer::Builder()
.indexCount(3)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(*this));
mFullScreenTriangleIb->setBuffer(*this,
{ sFullScreenTriangleIndices, sizeof(sFullScreenTriangleIndices) });
mFullScreenTriangleRph = driverApi.createRenderPrimitive();
driverApi.setRenderPrimitiveBuffer(mFullScreenTriangleRph,
mFullScreenTriangleVb->getHwHandle(), mFullScreenTriangleIb->getHwHandle(),
mFullScreenTriangleVb->getDeclaredAttributes().getValue());
driverApi.setRenderPrimitiveRange(mFullScreenTriangleRph, PrimitiveType::TRIANGLES,
0, 0, 2, (uint32_t)mFullScreenTriangleIb->getIndexCount());
mDefaultIblTexture = upcast(Texture::Builder()
.width(1).height(1).levels(1)
.format(Texture::InternalFormat::RGBA8)
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.build(*this));
static uint32_t pixel = 0;
Texture::PixelBufferDescriptor buffer(
&pixel, 4, // 4 bytes in 1 RGBA pixel
Texture::Format::RGBA, Texture::Type::UBYTE);
Texture::FaceOffsets offsets = {};
mDefaultIblTexture->setImage(*this, 0, std::move(buffer), offsets);
// 3 bands = 9 float3
const float sh[9 * 3] = { 0.0f };
mDefaultIbl = upcast(IndirectLight::Builder()
.irradiance(3, reinterpret_cast<const float3*>(sh))
.build(*this));
mDefaultColorGrading = upcast(ColorGrading::Builder().build(*this));
// Always initialize the default material, most materials' depth shaders fallback on it.
mDefaultMaterial = upcast(
FMaterial::DefaultMaterialBuilder()
.package(MATERIALS_DEFAULTMATERIAL_DATA, MATERIALS_DEFAULTMATERIAL_SIZE)
.build(*const_cast<FEngine*>(this)));
mPostProcessManager.init();
mLightManager.init(*this);
mDFG = std::make_unique<DFG>(*this);
}
FEngine::~FEngine() noexcept {
SYSTRACE_CALL();
ASSERT_DESTRUCTOR(mTerminated, "Engine destroyed but not terminated!");
delete mResourceAllocator;
delete mDriver;
if (mOwnPlatform) {
DefaultPlatform::destroy((DefaultPlatform**)&mPlatform);
}
}
void FEngine::shutdown() {
SYSTRACE_CALL();
ASSERT_PRECONDITION(std::this_thread::get_id() == mMainThreadId,
"Engine::shutdown() called from the wrong thread!");
#ifndef NDEBUG
// print out some statistics about this run
size_t wm = mCommandBufferQueue.getHighWatermark();
size_t wmpct = wm / (CONFIG_COMMAND_BUFFERS_SIZE / 100);
slog.d << "CircularBuffer: High watermark "
<< wm / 1024 << " KiB (" << wmpct << "%)" << io::endl;
#endif
DriverApi& driver = getDriverApi();
/*
* Destroy our own state first
*/
mPostProcessManager.terminate(driver); // free-up post-process manager resources
mResourceAllocator->terminate();
mDFG->terminate(); // free-up the DFG
mRenderableManager.terminate(); // free-up all renderables
mLightManager.terminate(); // free-up all lights
mCameraManager.terminate(); // free-up all cameras
driver.destroyRenderPrimitive(mFullScreenTriangleRph);
destroy(mFullScreenTriangleIb);
destroy(mFullScreenTriangleVb);
destroy(mDefaultIblTexture);
destroy(mDefaultIbl);
destroy(mDefaultColorGrading);
destroy(mDefaultMaterial);
/*
* clean-up after the user -- we call terminate on each "leaked" object and clear each list.
*
* This should free up everything.
*/
// try to destroy objects in the inverse dependency
cleanupResourceList(mRenderers);
cleanupResourceList(mViews);
cleanupResourceList(mScenes);
cleanupResourceList(mSkyboxes);
cleanupResourceList(mColorGradings);
// this must be done after Skyboxes and before materials
destroy(mSkyboxMaterial);
cleanupResourceList(mIndexBuffers);
cleanupResourceList(mVertexBuffers);
cleanupResourceList(mTextures);
cleanupResourceList(mRenderTargets);
cleanupResourceList(mMaterials);
for (auto& item : mMaterialInstances) {
cleanupResourceList(item.second);
}
cleanupResourceList(mFences);
/*
* Shutdown the backend...
*/
// There might be commands added by the terminate() calls, so we need to flush all commands
// up to this point. After flushCommandBuffer() is called, all pending commands are guaranteed
// to be executed before the driver thread exits.
flushCommandBuffer(mCommandBufferQueue);
// now wait for all pending commands to be executed and the thread to exit
mCommandBufferQueue.requestExit();
if (!UTILS_HAS_THREADING) {
execute();
getDriverApi().terminate();
} else {
mDriverThread.join();
}
// Finally, call user callbacks that might have been scheduled.
// These callbacks CANNOT call driver APIs.
getDriver().purge();
/*
* Terminate the JobSystem...
*/
// detach this thread from the jobsystem
mJobSystem.emancipate();
mTerminated = true;
}
void FEngine::prepare() {
SYSTRACE_CALL();
// prepare() is called once per Renderer frame. Ideally we would upload the content of
// UBOs that are visible only. It's not such a big issue because the actual upload() is
// skipped is the UBO hasn't changed. Still we could have a lot of these.
FEngine::DriverApi& driver = getDriverApi();
for (auto& materialInstanceList : mMaterialInstances) {
for (const auto& item : materialInstanceList.second) {
item->commit(driver);
}
}
// Commit default material instances.
for (const auto& material : mMaterials) {
material->getDefaultInstance()->commit(driver);
}
}
void FEngine::gc() {
// Note: this runs in a Job
JobSystem& js = mJobSystem;
auto *parent = js.createJob();
auto em = std::ref(mEntityManager);
js.run(jobs::createJob(js, parent, &FRenderableManager::gc, &mRenderableManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FLightManager::gc, &mLightManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FTransformManager::gc, &mTransformManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FCameraManager::gc, &mCameraManager, em),
JobSystem::DONT_SIGNAL);
js.runAndWait(parent);
}
void FEngine::flush() {
// flush the command buffer
flushCommandBuffer(mCommandBufferQueue);
}
void FEngine::flushAndWait() {
#if defined(ANDROID)
// first make sure we've not terminated filament
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"calling Engine::flushAndWait() after Engine::shutdown()!");
#endif
// enqueue finish command -- this will stall in the driver until the GPU is done
getDriverApi().finish();
#if defined(ANDROID)
// then create a fence that will trigger when we're past the finish() above
size_t tryCount = 8;
FFence* fence = FEngine::createFence(FFence::Type::SOFT);
do {
FenceStatus status = fence->wait(FFence::Mode::FLUSH,250000000u);
// if the fence didn't trigger after 250ms, check that the command queue thread is still
// running (otherwise indicating a precondition violation).
if (UTILS_UNLIKELY(status == FenceStatus::TIMEOUT_EXPIRED)) {
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"called Engine::shutdown() WHILE in Engine::flushAndWait()!");
tryCount--;
ASSERT_POSTCONDITION(tryCount, "flushAndWait() failed inexplicably after 2s");
// if the thread is still running, maybe we just need to give it more time
continue;
}
break;
} while (true);
destroy(fence);
#else
FFence::waitAndDestroy(
FEngine::createFence(FFence::Type::SOFT), FFence::Mode::FLUSH);
#endif
// finally, execute callbacks that might have been scheduled
getDriver().purge();
}
// -----------------------------------------------------------------------------------------------
// Render thread / command queue
// -----------------------------------------------------------------------------------------------
int FEngine::loop() {
if (mPlatform == nullptr) {
mPlatform = DefaultPlatform::create(&mBackend);
mOwnPlatform = true;
const char* const backend = backendToString(mBackend);
slog.d << "FEngine resolved backend: " << backend << io::endl;
if (mPlatform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
mDriverBarrier.latch();
return 0;
}
}
#if FILAMENT_ENABLE_MATDBG
#ifdef ANDROID
const char* portString = "8081";
#else
const char* portString = getenv("FILAMENT_MATDBG_PORT");
#endif
if (portString != nullptr) {
const int port = atoi(portString);
debug.server = new matdbg::DebugServer(mBackend, port);
// Sometimes the server can fail to spin up (e.g. if the above port is already in use).
// When this occurs, carry onward, developers can look at civetweb.txt for details.
if (!debug.server->isReady()) {
delete debug.server;
debug.server = nullptr;
} else {
debug.server->setEditCallback(FMaterial::onEditCallback);
debug.server->setQueryCallback(FMaterial::onQueryCallback);
}
}
#endif
JobSystem::setThreadName("FEngine::loop");
JobSystem::setThreadPriority(JobSystem::Priority::DISPLAY);
mDriver = mPlatform->createDriver(mSharedGLContext);
mDriverBarrier.latch();
if (UTILS_UNLIKELY(!mDriver)) {
// if we get here, it's because the driver couldn't be initialized and the problem has
// been logged.
return 0;
}
// We use the highest affinity bit, assuming this is a Big core in a big.little
// configuration. This is also a core not used by the JobSystem.
// Either way the main reason to do this is to avoid this thread jumping from core to core
// and loose its caches in the process.
uint32_t id = std::thread::hardware_concurrency() - 1;
while (true) {
// looks like thread affinity needs to be reset regularly (on Android)
JobSystem::setThreadAffinityById(id);
if (!execute()) {
break;
}
}
// terminate() is a synchronous API
getDriverApi().terminate();
return 0;
}
void FEngine::flushCommandBuffer(CommandBufferQueue& commandQueue) {
getDriver().purge();
commandQueue.flush();
}
const FMaterial* FEngine::getSkyboxMaterial() const noexcept {
FMaterial const* material = mSkyboxMaterial;
if (UTILS_UNLIKELY(material == nullptr)) {
material = FSkybox::createMaterial(*const_cast<FEngine*>(this));
mSkyboxMaterial = material;
}
return material;
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
/*
* Object created from a Builder
*/
template <typename T>
inline T* FEngine::create(ResourceList<T>& list, typename T::Builder const& builder) noexcept {
T* p = mHeapAllocator.make<T>(*this, builder);
list.insert(p);
return p;
}
FVertexBuffer* FEngine::createVertexBuffer(const VertexBuffer::Builder& builder) noexcept {
return create(mVertexBuffers, builder);
}
FIndexBuffer* FEngine::createIndexBuffer(const IndexBuffer::Builder& builder) noexcept {
return create(mIndexBuffers, builder);
}
FTexture* FEngine::createTexture(const Texture::Builder& builder) noexcept {
return create(mTextures, builder);
}
FIndirectLight* FEngine::createIndirectLight(const IndirectLight::Builder& builder) noexcept {
return create(mIndirectLights, builder);
}
FMaterial* FEngine::createMaterial(const Material::Builder& builder) noexcept {
return create(mMaterials, builder);
}
FSkybox* FEngine::createSkybox(const Skybox::Builder& builder) noexcept {
return create(mSkyboxes, builder);
}
FColorGrading* FEngine::createColorGrading(const ColorGrading::Builder& builder) noexcept {
return create(mColorGradings, builder);
}
FStream* FEngine::createStream(const Stream::Builder& builder) noexcept {
return create(mStreams, builder);
}
FRenderTarget* FEngine::createRenderTarget(const RenderTarget::Builder& builder) noexcept {
return create(mRenderTargets, builder);
}
/*
* Special cases
*/
FRenderer* FEngine::createRenderer() noexcept {
FRenderer* p = mHeapAllocator.make<FRenderer>(*this);
if (p) {
mRenderers.insert(p);
p->init();
}
return p;
}
FMaterialInstance* FEngine::createMaterialInstance(const FMaterial* material,
const char* name) noexcept {
FMaterialInstance* p = mHeapAllocator.make<FMaterialInstance>(*this, material, name);
if (p) {
auto pos = mMaterialInstances.emplace(material, "MaterialInstance");
pos.first->second.insert(p);
}
return p;
}
/*
* Objects created without a Builder
*/
FScene* FEngine::createScene() noexcept {
FScene* p = mHeapAllocator.make<FScene>(*this);
if (p) {
mScenes.insert(p);
}
return p;
}
FView* FEngine::createView() noexcept {
FView* p = mHeapAllocator.make<FView>(*this);
if (p) {
mViews.insert(p);
}
return p;
}
FFence* FEngine::createFence(FFence::Type type) noexcept {
FFence* p = mHeapAllocator.make<FFence>(*this, type);
if (p) {
mFences.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
if (UTILS_UNLIKELY(flags & backend::SWAP_CHAIN_CONFIG_APPLE_CVPIXELBUFFER)) {
// If this flag is set, then the nativeWindow is a CVPixelBufferRef.
// The call to setupExternalImage is synchronous, and allows the driver to take ownership of
// the buffer on this thread.
// For non-Metal backends, this is a no-op.
getDriverApi().setupExternalImage(nativeWindow);
}
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, nativeWindow, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, width, height, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
/*
* Objects created with a component manager
*/
FCamera* FEngine::createCamera(Entity entity) noexcept {
return mCameraManager.create(entity);
}
FCamera* FEngine::getCameraComponent(Entity entity) noexcept {
auto ci = mCameraManager.getInstance(entity);
return ci ? mCameraManager.getCamera(ci) : nullptr;
}
void FEngine::destroyCameraComponent(utils::Entity entity) noexcept {
mCameraManager.destroy(entity);
}
void FEngine::createRenderable(const RenderableManager::Builder& builder, Entity entity) {
mRenderableManager.create(builder, entity);
auto& tcm = mTransformManager;
// if this entity doesn't have a transform component, add one.
if (!tcm.hasComponent(entity)) {
tcm.create(entity, 0, mat4f());
}
}
void FEngine::createLight(const LightManager::Builder& builder, Entity entity) {
mLightManager.create(builder, entity);
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
void FEngine::cleanupResourceList(ResourceList<T, L>& list) {
if (!list.empty()) {
#ifndef NDEBUG
slog.d << "cleaning up " << list.size()
<< " leaked " << CallStack::typeName<T>().c_str() << io::endl;
#endif
// Move the list (copy-and-clear). We can only modify/access the list from this
// thread, because it's not thread-safe.
auto copy(list.getListAndClear());
for (T* item : copy) {
item->terminate(*this);
mHeapAllocator.destroy(item);
}
}
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
bool FEngine::terminateAndDestroy(const T* ptr, ResourceList<T, L>& list) {
if (ptr == nullptr) return true;
bool success = list.remove(ptr);
if (ASSERT_PRECONDITION_NON_FATAL(success,
"Object %s at %p doesn't exist (double free?)",
CallStack::typeName<T>().c_str(), ptr)) {
const_cast<T*>(ptr)->terminate(*this);
mHeapAllocator.destroy(const_cast<T*>(ptr));
}
return success;
}
// -----------------------------------------------------------------------------------------------
bool FEngine::destroy(const FVertexBuffer* p) {
return terminateAndDestroy(p, mVertexBuffers);
}
bool FEngine::destroy(const FIndexBuffer* p) {
return terminateAndDestroy(p, mIndexBuffers);
}
inline bool FEngine::destroy(const FRenderer* p) {
return terminateAndDestroy(p, mRenderers);
}
inline bool FEngine::destroy(const FScene* p) {
return terminateAndDestroy(p, mScenes);
}
inline bool FEngine::destroy(const FSkybox* p) {
return terminateAndDestroy(p, mSkyboxes);
}
inline bool FEngine::destroy(const FColorGrading* p) {
return terminateAndDestroy(p, mColorGradings);
}
UTILS_NOINLINE
bool FEngine::destroy(const FTexture* p) {
return terminateAndDestroy(p, mTextures);
}
bool FEngine::destroy(const FRenderTarget* p) {
return terminateAndDestroy(p, mRenderTargets);
}
inline bool FEngine::destroy(const FView* p) {
return terminateAndDestroy(p, mViews);
}
inline bool FEngine::destroy(const FIndirectLight* p) {
return terminateAndDestroy(p, mIndirectLights);
}
UTILS_NOINLINE
bool FEngine::destroy(const FFence* p) {
return terminateAndDestroy(p, mFences);
}
bool FEngine::destroy(const FSwapChain* p) {
return terminateAndDestroy(p, mSwapChains);
}
bool FEngine::destroy(const FStream* p) {
return terminateAndDestroy(p, mStreams);
}
bool FEngine::destroy(const FMaterial* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr);
if (pos != mMaterialInstances.cend()) {
// ensure we've destroyed all instances before destroying the material
if (!ASSERT_PRECONDITION_NON_FATAL(pos->second.empty(),
"destroying material \"%s\" but %u instances still alive",
ptr->getName().c_str(), (*pos).second.size())) {
return false;
}
}
return terminateAndDestroy(ptr, mMaterials);
}
bool FEngine::destroy(const FMaterialInstance* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr->getMaterial());
assert_invariant(pos != mMaterialInstances.cend());
if (pos != mMaterialInstances.cend()) {
return terminateAndDestroy(ptr, pos->second);
}
// if we don't find this instance's material it might be because it's the default instance
// in which case it fine to ignore.
return true;
}
void FEngine::destroy(Entity e) {
mRenderableManager.destroy(e);
mLightManager.destroy(e);
mTransformManager.destroy(e);
mCameraManager.destroy(e);
}
void* FEngine::streamAlloc(size_t size, size_t alignment) noexcept {
// we allow this only for small allocations
if (size > 1024) {
return nullptr;
}
return getDriverApi().allocate(size, alignment);
}
bool FEngine::execute() {
// wait until we get command buffers to be executed (or thread exit requested)
auto buffers = mCommandBufferQueue.waitForCommands();
if (UTILS_UNLIKELY(buffers.empty())) {
return false;
}
// execute all command buffers
for (auto& item : buffers) {
if (UTILS_LIKELY(item.begin)) {
mCommandStream.execute(item.begin);
mCommandBufferQueue.releaseBuffer(item);
}
}
return true;
}
void FEngine::destroy(FEngine* engine) {
if (engine) {
engine->shutdown();
delete engine;
}
}
// ------------------------------------------------------------------------------------------------
// Trampoline calling into private implementation
// ------------------------------------------------------------------------------------------------
Engine* Engine::create(Backend backend, Platform* platform, void* sharedGLContext) {
return FEngine::create(backend, platform, sharedGLContext);
}
void Engine::destroy(Engine* engine) {
FEngine::destroy(upcast(engine));
}
#if UTILS_HAS_THREADING
void Engine::createAsync(Engine::CreateCallback callback, void* user, Backend backend,
Platform* platform, void* sharedGLContext) {
FEngine::createAsync(callback, user, backend, platform, sharedGLContext);
}
Engine* Engine::getEngine(void* token) {
return FEngine::getEngine(token);
}
#endif
void Engine::destroy(Engine** pEngine) {
if (pEngine) {
Engine* engine = *pEngine;
FEngine::destroy(upcast(engine));
*pEngine = nullptr;
}
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
const Material* Engine::getDefaultMaterial() const noexcept {
return upcast(this)->getDefaultMaterial();
}
Backend Engine::getBackend() const noexcept {
return upcast(this)->getBackend();
}
Renderer* Engine::createRenderer() noexcept {
return upcast(this)->createRenderer();
}
View* Engine::createView() noexcept {
return upcast(this)->createView();
}
Scene* Engine::createScene() noexcept {
return upcast(this)->createScene();
}
Camera* Engine::createCamera(Entity entity) noexcept {
return upcast(this)->createCamera(entity);
}
Camera* Engine::getCameraComponent(utils::Entity entity) noexcept {
return upcast(this)->getCameraComponent(entity);
}
void Engine::destroyCameraComponent(utils::Entity entity) noexcept {
upcast(this)->destroyCameraComponent(entity);
}
Fence* Engine::createFence() noexcept {
return upcast(this)->createFence(FFence::Type::SOFT);
}
SwapChain* Engine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(nativeWindow, flags);
}
SwapChain* Engine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(width, height, flags);
}
bool Engine::destroy(const VertexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndirectLight* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Material* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const MaterialInstance* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Renderer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const View* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Scene* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Skybox* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const ColorGrading* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Stream* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Texture* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const RenderTarget* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Fence* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const SwapChain* p) {
return upcast(this)->destroy(upcast(p));
}
void Engine::destroy(Entity e) {
upcast(this)->destroy(e);
}
void Engine::flushAndWait() {
upcast(this)->flushAndWait();
}
RenderableManager& Engine::getRenderableManager() noexcept {
return upcast(this)->getRenderableManager();
}
LightManager& Engine::getLightManager() noexcept {
return upcast(this)->getLightManager();
}
TransformManager& Engine::getTransformManager() noexcept {
return upcast(this)->getTransformManager();
}
void* Engine::streamAlloc(size_t size, size_t alignment) noexcept {
return upcast(this)->streamAlloc(size, alignment);
}
// The external-facing execute does a flush, and is meant only for single-threaded environments.
// It also discards the boolean return value, which would otherwise indicate a thread exit.
void Engine::execute() {
ASSERT_PRECONDITION(!UTILS_HAS_THREADING, "Execute is meant for single-threaded platforms.");
upcast(this)->flush();
upcast(this)->execute();
}
utils::JobSystem& Engine::getJobSystem() noexcept {
return upcast(this)->getJobSystem();
}
DebugRegistry& Engine::getDebugRegistry() noexcept {
return upcast(this)->getDebugRegistry();
}
Camera* Engine::createCamera() noexcept {
return createCamera(upcast(this)->getEntityManager().create());
}
void Engine::destroy(const Camera* camera) {
Entity e = camera->getEntity();
destroyCameraComponent(e);
upcast(this)->getEntityManager().destroy(e);
}
} // namespace filament
| 31.160577 | 100 | 0.654612 | tombsar |
106df08aa4f507ae607ea7a170e973388c577b8a | 651 | cc | C++ | src/include/XESystem/Entityx/help/Timer.cc | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 11 | 2017-01-17T15:02:25.000Z | 2020-11-27T16:54:42.000Z | src/include/XESystem/Entityx/help/Timer.cc | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 9 | 2016-10-23T20:15:38.000Z | 2018-02-06T11:23:17.000Z | src/include/XESystem/Entityx/help/Timer.cc | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 2 | 2019-08-29T10:23:51.000Z | 2020-04-03T06:08:34.000Z | /*
* Copyright (C) 2013 Antony Woods <antony@teamwoods.org>
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* Author: Antony Woods <antony@teamwoods.org>
*/
#include "Timer.h"
namespace entityx {
namespace help {
Timer::Timer() {
_start = std::chrono::system_clock::now();
}
Timer::~Timer() {
}
void Timer::restart() {
_start = std::chrono::system_clock::now();
}
double Timer::elapsed() {
return std::chrono::duration<double>(std::chrono::system_clock::now() - _start).count();
}
} // namespace help
} // namespace entityx
| 19.727273 | 90 | 0.680492 | devxkh |
106ffdd4c86ffa7dbfe8caeeb09fa5fa4ef75185 | 3,644 | hpp | C++ | Math/include/Extended/AABB3.hpp | C-And-Cpp-Libraries/handycpp | 85f4e4f93856988e729e1e81512eab99a02b5a5a | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 25 | 2017-12-28T22:09:11.000Z | 2020-04-02T15:49:51.000Z | Math/include/Extended/AABB3.hpp | C-And-Cpp-Libraries/handycpp | 85f4e4f93856988e729e1e81512eab99a02b5a5a | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2019-07-30T08:59:00.000Z | 2019-07-30T21:35:50.000Z | Math/include/Extended/AABB3.hpp | C-And-Cpp-Libraries/handycpp | 85f4e4f93856988e729e1e81512eab99a02b5a5a | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2021-12-26T14:14:09.000Z | 2021-12-26T14:14:09.000Z |
/// See ../../License.txt for license info.
#pragma once
#include <cmath>
#include <vector>
#include "../Core/Vector3.hpp"
namespace HANDYMATH_NS
{
struct AABB3
{
Vector3 Min;
Vector3 Max;
AABB3();
AABB3(Vector3 const & point);
AABB3(std::vector<Vector3> const & points);
AABB3(Vector3 const & min, Vector3 const & max);
bool IsEverything() const;
bool IsNothing() const;
bool IsPoint() const;
Vector3 PointCenter() const;
Vector3 Size() const;
Vector3 HalfSize() const;
float Volume() const;
float SurfaceArea() const;
void AddPoint(Vector3 const & p);
void AddPoints(std::vector<Vector3> const & ps);
void AddAABB(AABB3 const & aabb);
bool Envelopes (AABB3 const & aabb) const;
bool Intersects(AABB3 const & aabb) const;
bool Intersects(Vector3 const & v) const;
static AABB3 Everything();
static AABB3 Nothing();
};
FORCEINLINE AABB3::AABB3() : Min(Vector3::NaN()), Max(Vector3::NaN()) { }
FORCEINLINE AABB3::AABB3(Vector3 const & point) : AABB3() { AddPoint(point); }
FORCEINLINE AABB3::AABB3(std::vector<Vector3> const & points) : AABB3() { AddPoints(points); }
FORCEINLINE AABB3::AABB3(Vector3 const & min, Vector3 const & max) : Min(min), Max(max) { }
FORCEINLINE bool AABB3::IsEverything() const { return Min.IsNegativeInfinity() && Max.IsPositiveInfinity(); }
FORCEINLINE bool AABB3::IsNothing() const { return Min.IsNaN() || Max.IsNaN(); }
FORCEINLINE bool AABB3::IsPoint() const { return Min == Max; }
FORCEINLINE Vector3 AABB3::PointCenter() const { return (Min + Max) * 0.5f; }
FORCEINLINE Vector3 AABB3::Size() const { return (Max - Min); }
FORCEINLINE Vector3 AABB3::HalfSize() const { return (Max - Min) * 0.5f; }
FORCEINLINE float AABB3::Volume() const { return Size().Product(); }
FORCEINLINE float AABB3::SurfaceArea() const { Vector3 sz = Size(); return 2.0f * (sz.X * sz.Y + sz.Y * sz.Z + sz.X * sz.Z); }
FORCEINLINE void AABB3::AddPoint(Vector3 const & point)
{
if (point.HasNaN())
throw std::runtime_error("Cannot add NaN to AABB2.");
if (IsEverything())
return;
if (IsNothing())
{
Min = Max = point;
return;
}
Min = Min.Min(point);
Max = Max.Max(point);
}
FORCEINLINE void AABB3::AddPoints(std::vector<Vector3> const & points)
{
if (IsEverything())
return;
for (auto const & point : points)
AddPoint(point);
}
FORCEINLINE void AABB3::AddAABB(AABB3 const & aabb)
{
if (aabb.IsNothing() || IsEverything())
return;
if (aabb.IsEverything() || IsNothing())
{
*this = aabb;
return;
}
AddPoint(aabb.Min);
AddPoint(aabb.Max);
}
FORCEINLINE bool AABB3::Envelopes(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything())
return true;
return Min.X <= aabb.Min.X && Min.Y <= aabb.Min.Y && Min.Z <= aabb.Min.Z &&
Max.X >= aabb.Max.X && Max.Y >= aabb.Max.Y && Max.Z >= aabb.Max.Z;
}
FORCEINLINE bool AABB3::Intersects(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything() || aabb.IsEverything())
return true;
return !(Max.X < aabb.Min.X || Min.X > aabb.Max.X ||
Max.Y < aabb.Min.Y || Min.Y > aabb.Max.Y ||
Max.Z < aabb.Min.Z || Min.Z > aabb.Max.Z);
}
FORCEINLINE bool AABB3::Intersects(Vector3 const & v) const
{
return Intersects(AABB3(v));
}
FORCEINLINE /*static*/ AABB3 AABB3::Everything() { return AABB3(Vector3::NegativeInfinity(), Vector3::PositiveInfinity()); }
FORCEINLINE /*static*/ AABB3 AABB3::Nothing() { return AABB3(Vector3::NaN(), Vector3::NaN()); }
}
| 25.843972 | 130 | 0.642975 | C-And-Cpp-Libraries |
10719b53b8cce6cf10b9b0a139d37b6637b560a4 | 6,660 | cpp | C++ | examples/Cpp/RealSense.cpp | fangchuan/Open3D | 61f991ba5d9fe3ee1e4e195a607bf48f4695d821 | [
"MIT"
] | null | null | null | examples/Cpp/RealSense.cpp | fangchuan/Open3D | 61f991ba5d9fe3ee1e4e195a607bf48f4695d821 | [
"MIT"
] | null | null | null | examples/Cpp/RealSense.cpp | fangchuan/Open3D | 61f991ba5d9fe3ee1e4e195a607bf48f4695d821 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.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 <iostream>
#include <librealsense/rs.hpp>
#include <thread>
#include "Open3D/Open3D.h"
using namespace open3d;
int main(int argc, char **args) {
rs::context ctx;
utility::LogInfo("There are {:d} connected RealSense devices.",
ctx.get_device_count());
if (ctx.get_device_count() == 0) {
return 1;
}
rs::device *dev = ctx.get_device(0);
utility::LogInfo("Using device 0, an {}", dev->get_name());
utility::LogInfo(" Serial number: {}", dev->get_serial());
utility::LogInfo(" Firmware version: {}", dev->get_firmware_version());
dev->set_option(rs::option::color_enable_auto_exposure, 0.0);
dev->set_option(rs::option::color_exposure, 625);
dev->set_option(rs::option::color_gain, 128);
dev->set_option(rs::option::color_enable_auto_white_balance, 0.0);
dev->enable_stream(rs::stream::depth, 640, 480, rs::format::z16, 30);
dev->enable_stream(rs::stream::color, 1920, 1080, rs::format::rgb8, 30);
dev->start();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
dev->set_option(rs::option::color_white_balance, 2100.0);
auto depth_image_ptr = std::make_shared<geometry::Image>();
depth_image_ptr->Prepare(640, 480, 1, 2);
auto color_image_ptr = std::make_shared<geometry::Image>();
color_image_ptr->Prepare(1920, 1080, 3, 1);
utility::FPSTimer timer("Realsense stream");
rs::extrinsics extrinsics =
dev->get_extrinsics(rs::stream::depth, rs::stream::rectified_color);
for (int i = 0; i < 9; i++) {
utility::LogInfo("{:.6f} ", extrinsics.rotation[i]);
}
utility::LogInfo("");
for (int i = 0; i < 3; i++) {
utility::LogInfo("{:.6f} ", extrinsics.translation[i]);
}
utility::LogInfo("");
rs::intrinsics depth_intr = dev->get_stream_intrinsics(rs::stream::depth);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", depth_intr.width,
depth_intr.height, depth_intr.fx, depth_intr.fy,
depth_intr.ppx, depth_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", depth_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics color_intr = dev->get_stream_intrinsics(rs::stream::color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", color_intr.width,
color_intr.height, color_intr.fx, color_intr.fy,
color_intr.ppx, color_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", color_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics rect_intr =
dev->get_stream_intrinsics(rs::stream::rectified_color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", rect_intr.width,
rect_intr.height, rect_intr.fx, rect_intr.fy,
rect_intr.ppx, rect_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", rect_intr.coeffs[i]);
}
utility::LogInfo("");
visualization::Visualizer depth_vis, color_vis;
if (!depth_vis.CreateVisualizerWindow("Depth", 640, 480, 15, 50) ||
!depth_vis.AddGeometry(depth_image_ptr) ||
!color_vis.CreateVisualizerWindow("Color", 1920, 1080, 675, 50) ||
!color_vis.AddGeometry(color_image_ptr)) {
return 0;
}
while (depth_vis.PollEvents() && color_vis.PollEvents()) {
timer.Signal();
dev->wait_for_frames();
memcpy(depth_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::depth), 640 * 480 * 2);
memcpy(color_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::rectified_color),
1920 * 1080 * 3);
depth_vis.UpdateGeometry();
color_vis.UpdateGeometry();
utility::LogInfo("{:.2f}",
dev->get_option(rs::option::color_white_balance));
/*
rs::option opts[10] = {
rs::option::color_enable_auto_exposure,
rs::option::color_exposure,
rs::option::color_backlight_compensation,
rs::option::color_brightness,
rs::option::color_contrast,
rs::option::color_gain,
rs::option::color_gamma,
rs::option::color_saturation,
rs::option::color_sharpness,
rs::option::color_hue
};
double value[10];
dev->get_options((const rs::option *)opts, 10, (double *)value);
utility::LogInfo("{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}
{:.2f} {:.2f}
{:.2f}", value[0], value[1], value[2], value[3], value[4], value[5],
value[6], value[7], value[8], value[9]);
*/
}
// DrawGeometryWithAnimationCallback(depth_image_ptr,
// [&](Visualizer &vis) {
// timer.Signal();
// dev->wait_for_frames();
// memcpy(depth_image_ptr->data_.data(),
// dev->get_frame_data(rs::stream::depth), 640 * 480 *
// 2);
// return true;
// }, "Depth", 640, 480);
return 0;
}
| 41.886792 | 80 | 0.572823 | fangchuan |
10727506f5e0bdde87cb655c781abe724f11ae6c | 2,090 | cpp | C++ | clib/RecursiveMutex.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 8 | 2016-08-29T13:34:18.000Z | 2020-12-04T15:20:36.000Z | clib/RecursiveMutex.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 221 | 2016-06-20T19:51:48.000Z | 2022-03-29T20:46:46.000Z | clib/RecursiveMutex.cpp | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 13 | 2016-06-24T15:59:31.000Z | 2022-01-01T11:48:20.000Z | #include "StdAfx.h"
#include ".\recursivemutex.h"
#include "atlsync.h"
namespace clib
{
recursive_mutex::recursive_mutex() : m_lockCount(0)
{
}
recursive_mutex::~recursive_mutex()
{
}
LONG recursive_mutex::GetLockCount()
{
return m_lockCount;
}
void recursive_mutex::do_lock()
{
::InterlockedIncrement(&m_lockCount);
m_critSec.Lock();
}
void recursive_mutex::do_unlock()
{
m_critSec.Unlock();
::InterlockedDecrement(&m_lockCount);
}
rwrecursive_mutex::rwrecursive_mutex()
{
m_nReaders = 0;
m_nWriters = 0;
}
rwrecursive_mutex::~rwrecursive_mutex()
{
}
void rwrecursive_mutex::do_lockr()
{
for(;;)
{
::InterlockedIncrement(&m_nReaders);
if(m_nWriters == 0)
break;
::InterlockedDecrement(&m_nReaders);
::Sleep(0);
}
}
void rwrecursive_mutex::do_lockw()
{
for(;;)
{
if( ::InterlockedExchange( &m_nWriters, 1 ) == 1 )
::Sleep(0);
else
{
while(m_nReaders != 0)
::Sleep(0);
break;
}
}
}
void rwrecursive_mutex::do_unlockr()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nReaders);
}
void rwrecursive_mutex::do_unlockw()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nWriters);
}
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
rwscoped_lock_ref_counted::rwscoped_lock_ref_counted(CRWMutex &m)
{
m_lock = new rwscoped_mutex_lock(m);
}
rwscoped_lock_ref_counted::~rwscoped_lock_ref_counted()
{
delete(m_lock);
}
void CLockableUnknown::Lock(CComPtr<clib::scoped_lock_ref_counted> & lock)
{
lock = new clib::scoped_lock_ref_counted(m_mutex);
}
}
namespace boost
{
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
} | 17.131148 | 74 | 0.669378 | dehilsterlexis |
107329f5ce381018f781bb18961bc0a19004c420 | 7,386 | cpp | C++ | src/ObservableVectorUnitTest.cpp | k2snowman69/threadily-sample-cpp-test | 2edf49d11032ff8efa2dc77ea67cf7092c60b0b8 | [
"MIT"
] | null | null | null | src/ObservableVectorUnitTest.cpp | k2snowman69/threadily-sample-cpp-test | 2edf49d11032ff8efa2dc77ea67cf7092c60b0b8 | [
"MIT"
] | null | null | null | src/ObservableVectorUnitTest.cpp | k2snowman69/threadily-sample-cpp-test | 2edf49d11032ff8efa2dc77ea67cf7092c60b0b8 | [
"MIT"
] | null | null | null | // Main test framework
#include <bandit/bandit.h>
// std includes
#include <iostream>
#include <memory>
// Threadily includes
#include <ReadyEvent.h>
#include <Observable.h>
#include <ThreadManager.h>
#include <ThreadQueueItem.h>
#include <ThreadIds.h>
using namespace snowhouse;
using namespace bandit;
namespace threadily
{
namespace test
{
go_bandit([]() {
describe("ObservableVectorUnitTest", []() {
it("Observable_Vector_Int_Insert_1", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, 1);
observableVector.insert(1, 2);
observableVector.insert(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Insert_2", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(0, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Ptr_Insert_1", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, std::make_shared<int>(1));
observableVector.insert(1, std::make_shared<int>(2));
observableVector.insert(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Insert_2", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(observableVector.at(0).get(), IsNull());
AssertThat(observableVector.at(1).get(), IsNull());
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Subscription_Insert", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Insert, Equals(action));
});
observableVector.insert(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Remove", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isDeleted = false;
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded, &isDeleted](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Erase == action)
{
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
isDeleted = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.erase(2);
AssertThat((size_t)2, Equals(observableVector.size()));
AssertThat(isDeleted, IsTrue());
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Update", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isUpdated = false;
auto valueAdded = std::make_shared<int>(4);
auto valueUpdated = std::make_shared<int>(6);
auto subscribe = observableVector.subscribe([valueUpdated, &isUpdated](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Set == action)
{
AssertThat(valueUpdated, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Set, Equals(action));
isUpdated = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.set(2, valueUpdated);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(isUpdated, IsTrue());
observableVector.unsubscribe(subscribe);
});
});
});
}
} | 34.514019 | 149 | 0.69537 | k2snowman69 |
1076475f1860606c70a4de5c9685e6ccf0440147 | 46,677 | cpp | C++ | ocv/text/ocr_hmm_decoder.cpp | privet56/qRabbifier | 4289016f9ba40658ad444580818292456574ffb5 | [
"Apache-2.0"
] | 16 | 2016-07-04T10:32:22.000Z | 2021-11-10T11:26:45.000Z | ocv/text/ocr_hmm_decoder.cpp | privet56/qRabbifier | 4289016f9ba40658ad444580818292456574ffb5 | [
"Apache-2.0"
] | null | null | null | ocv/text/ocr_hmm_decoder.cpp | privet56/qRabbifier | 4289016f9ba40658ad444580818292456574ffb5 | [
"Apache-2.0"
] | 22 | 2015-10-23T19:36:18.000Z | 2021-02-02T12:20:32.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/ml.hpp"
#include <iostream>
#include <fstream>
#include <queue>
namespace cv
{
namespace text
{
using namespace std;
using namespace cv::ml;
/* OCR HMM Decoder */
void OCRHMMDecoder::run(Mat& image, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
void OCRHMMDecoder::run(Mat& image, Mat& mask, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
CV_WRAP String OCRHMMDecoder::run(InputArray image, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
run(image_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
//cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
CV_WRAP cv::String OCRHMMDecoder::run(InputArray image, InputArray mask, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
Mat mask_m = mask.getMat();
run(image_m, mask_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
void OCRHMMDecoder::ClassifierCallback::eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence)
{
CV_Assert(( image.getMat().type() == CV_8UC3 ) || ( image.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
}
bool sort_rect_horiz (Rect a,Rect b);
bool sort_rect_horiz (Rect a,Rect b) { return (a.x<b.x); }
class OCRHMMDecoderImpl : public OCRHMMDecoder
{
public:
//Default constructor
OCRHMMDecoderImpl( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_probabilities_table,
InputArray emission_probabilities_table,
decoder_mode _mode)
{
classifier = _classifier;
transition_p = transition_probabilities_table.getMat();
emission_p = emission_probabilities_table.getMat();
vocabulary = _vocabulary;
mode = _mode;
}
~OCRHMMDecoderImpl()
{
}
void run( Mat& image,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
image.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(image);
words_rect.push_back(Rect(0,0,image.cols,image.rows));
}
else
{
Mat_<float> vector_w((int)image.cols,1);
reduce(image, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
Mat tmp_mask;
words_mask[w](contours_rect.at(i)).copyTo(tmp_mask);
vector<int> out_class;
vector<double> out_conf;
classifier->eval(tmp_mask,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
observations.push_back(out_class);
confidences.push_back(out_conf);
//cout << " out class = " << vocabulary[out_class[0]] << endl;
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
void run( Mat& image,
Mat& mask,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( (image.cols == mask.cols) && (image.rows == mask.rows) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(mask);
words_rect.push_back(Rect(0,0,mask.cols,mask.rows));
}
else
{
Mat_<float> vector_w((int)mask.cols,1);
reduce(mask, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
vector<int> out_class;
vector<double> out_conf;
//take the center of the char rect and translate it to the real origin
Point char_center = Point(contours_rect.at(i).x+contours_rect.at(i).width/2,
contours_rect.at(i).y+contours_rect.at(i).height/2);
char_center.x += words_rect[w].x;
char_center.y += words_rect[w].y;
int win_size = max(contours_rect.at(i).width,contours_rect.at(i).height);
win_size += (int)(win_size*0.6); // add some pixels in the border TODO: is this a parameter for the user space?
Rect char_rect = Rect(char_center.x-win_size/2,char_center.y-win_size/2,win_size,win_size);
char_rect &= Rect(0,0,image.cols,image.rows);
Mat tmp_image;
image(char_rect).copyTo(tmp_image);
classifier->eval(tmp_image,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
//cout << " out class = " << vocabulary[out_class[0]] << "(" << out_conf[0] << ")" << endl;
observations.push_back(out_class);
confidences.push_back(out_conf);
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
};
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_p,
InputArray emission_p,
decoder_mode _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, _mode);
}
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const String& _vocabulary,
InputArray transition_p,
InputArray emission_p,
int _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, (decoder_mode)_mode);
}
class CV_EXPORTS OCRHMMClassifierKNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierKNN(const std::string& filename);
// Destructor
~OCRHMMClassifierKNN() {}
void eval( InputArray mask, vector<int>& out_class, vector<double>& out_confidence );
private:
Ptr<KNearest> knn;
};
OCRHMMClassifierKNN::OCRHMMClassifierKNN (const string& filename)
{
knn = KNearest::create();
if (ifstream(filename.c_str()))
{
Mat hus, labels;
cv::FileStorage storage(filename.c_str(), cv::FileStorage::READ);
storage["hus"] >> hus;
storage["labels"] >> labels;
storage.release();
knn->train(hus, ROW_SAMPLE, labels);
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
}
void OCRHMMClassifierKNN::eval( InputArray _mask, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert( _mask.getMat().type() == CV_8UC1 );
out_class.clear();
out_confidence.clear();
int image_height = 35;
int image_width = 35;
int num_features = 200;
Mat img = _mask.getMat();
Mat tmp;
img.copyTo(tmp);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.empty())
return;
int idx = 0;
if (contours.size() > 1)
{
// this is to make sure we have the mask with a single contour
// e.g "i" and "j" have two contours, but it may be also a part of a neighbour character
// we take the larger one and clean the outside in order to have a single contour
int max_area = 0;
for (int cc=0; cc<(int)contours.size(); cc++)
{
int area_c = boundingRect(contours[cc]).area();
if ( area_c > max_area)
{
idx = cc;
max_area = area_c;
}
}
// clean-up the outside of the contour
Mat tmp_c = Mat::zeros(tmp.rows, tmp.cols, CV_8UC1);
drawContours(tmp_c, contours, idx, Scalar(255), FILLED);
img = img & tmp_c;
}
Rect bbox = boundingRect(contours[idx]);
//Crop to fit the exact rect of the contour and resize to a fixed-sized matrix of 35 x 35 pixel, while retaining the centroid of the region and aspect ratio.
Mat mask = Mat::zeros(image_height,image_width,CV_8UC1);
img(bbox).copyTo(tmp);
if (tmp.cols>tmp.rows)
{
int height = image_width*tmp.rows/tmp.cols;
if(height == 0) height = 1;
resize(tmp,tmp,Size(image_width,height));
tmp.copyTo(mask(Rect(0,(image_height-height)/2,image_width,height)));
}
else
{
int width = image_height*tmp.cols/tmp.rows;
if(width == 0) width = 1;
resize(tmp,tmp,Size(width,image_height));
tmp.copyTo(mask(Rect((image_width-width)/2,0,width,image_height)));
}
//find contours again (now resized)
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Mat> maps;
for (int i=0; i<8; i++)
{
Mat map = Mat::zeros(image_height,image_width,CV_8UC1);
maps.push_back(map);
}
for (int c=0; c<(int)contours.size(); c++)
{
for (int i=0; i<(int)contours[c].size(); i++)
{
//cout << contours[c][i] << " -- " << contours[c][(i+1)%contours[c].size()] << endl;
double dy = contours[c][i].y - contours[c][(i+1)%contours[c].size()].y;
double dx = contours[c][i].x - contours[c][(i+1)%contours[c].size()].x;
double angle = atan2 (dy,dx) * 180 / 3.14159265;
//cout << " angle = " << angle << endl;
int idx_a = 0;
if ((angle>=157.5)||(angle<=-157.5))
idx_a = 0;
else if ((angle>=-157.5)&&(angle<=-112.5))
idx_a = 1;
else if ((angle>=-112.5)&&(angle<=-67.5))
idx_a = 2;
else if ((angle>=-67.5)&&(angle<=-22.5))
idx_a = 3;
else if ((angle>=-22.5)&&(angle<=22.5))
idx_a = 4;
else if ((angle>=22.5)&&(angle<=67.5))
idx_a = 5;
else if ((angle>=67.5)&&(angle<=112.5))
idx_a = 6;
else if ((angle>=112.5)&&(angle<=157.5))
idx_a = 7;
line(maps[idx_a],contours[c][i],contours[c][(i+1)%contours[c].size()],Scalar(255));
}
}
//On each bitmap a regular 7x7 Gaussian masks are evenly placed
for (int i=0; i<(int)maps.size(); i++)
{
copyMakeBorder(maps[i],maps[i],7,7,7,7,BORDER_CONSTANT,Scalar(0));
GaussianBlur(maps[i], maps[i], Size(7,7), 2, 2);
normalize(maps[i],maps[i],0,255,NORM_MINMAX);
resize(maps[i],maps[i],Size(image_width,image_height));
}
//Generate features for each bitmap
Mat sample = Mat(1,num_features,CV_32FC1);
Mat patch;
for (int i=0; i<(int)maps.size(); i++)
{
for(int y=0; y<image_height; y=y+7)
{
for(int x=0; x<image_width; x=x+7)
{
maps[i](Rect(x,y,7,7)).copyTo(patch);
Scalar mean,std;
meanStdDev(patch,mean,std);
sample.at<float>(0,i*25+((int)x/7)+((int)y/7)*5) = (float)(mean[0]/255);
//cout << " avg " << mean[0] << " in patch " << x << "," << y << " channel " << i << " idx = " << i*25+((int)x/7)+((int)y/7)*5<< endl;
}
}
}
Mat responses,dists,predictions;
knn->findNearest( sample, 11, predictions, responses, dists);
Scalar dist_sum = sum(dists);
Mat class_predictions = Mat::zeros(1,62,CV_64FC1);
vector<vector<int> > equivalency_mat(62);
equivalency_mat[2].push_back(28); // c -> C
equivalency_mat[28].push_back(2); // C -> c
equivalency_mat[8].push_back(34); // i -> I
equivalency_mat[8].push_back(11); // i -> l
equivalency_mat[11].push_back(8); // l -> i
equivalency_mat[11].push_back(34); // l -> I
equivalency_mat[34].push_back(8); // I -> i
equivalency_mat[34].push_back(11); // I -> l
equivalency_mat[9].push_back(35); // j -> J
equivalency_mat[35].push_back(9); // J -> j
equivalency_mat[14].push_back(40); // o -> O
equivalency_mat[14].push_back(52); // o -> 0
equivalency_mat[40].push_back(14); // O -> o
equivalency_mat[40].push_back(52); // O -> 0
equivalency_mat[52].push_back(14); // 0 -> o
equivalency_mat[52].push_back(40); // 0 -> O
equivalency_mat[15].push_back(41); // p -> P
equivalency_mat[41].push_back(15); // P -> p
equivalency_mat[18].push_back(44); // s -> S
equivalency_mat[44].push_back(18); // S -> s
equivalency_mat[20].push_back(46); // u -> U
equivalency_mat[46].push_back(20); // U -> u
equivalency_mat[21].push_back(47); // v -> V
equivalency_mat[47].push_back(21); // V -> v
equivalency_mat[22].push_back(48); // w -> W
equivalency_mat[48].push_back(22); // W -> w
equivalency_mat[23].push_back(49); // x -> X
equivalency_mat[49].push_back(23); // X -> x
equivalency_mat[25].push_back(51); // z -> Z
equivalency_mat[51].push_back(25); // Z -> z
for (int j=0; j<responses.cols; j++)
{
if (responses.at<float>(0,j)<0)
continue;
class_predictions.at<double>(0,(int)responses.at<float>(0,j)) += dists.at<float>(0,j);
for (int e=0; e<(int)equivalency_mat[(int)responses.at<float>(0,j)].size(); e++)
{
class_predictions.at<double>(0,equivalency_mat[(int)responses.at<float>(0,j)][e]) += dists.at<float>(0,j);
dist_sum[0] += dists.at<float>(0,j);
}
}
class_predictions = class_predictions/dist_sum[0];
out_class.push_back((int)predictions.at<float>(0,0));
out_confidence.push_back(class_predictions.at<double>(0,(int)predictions.at<float>(0,0)));
for (int i=0; i<class_predictions.cols; i++)
{
if ((class_predictions.at<double>(0,i) > 0) && (i != out_class[0]))
{
out_class.push_back(i);
out_confidence.push_back(class_predictions.at<double>(0,i));
}
}
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierNM(const String& filename)
{
return makePtr<OCRHMMClassifierKNN>(std::string(filename));
}
class CV_EXPORTS OCRHMMClassifierCNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierCNN(const std::string& filename);
// Destructor
~OCRHMMClassifierCNN() {}
void eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence );
protected:
void normalizeAndZCA(Mat& patches);
double eval_feature(Mat& feature, double* prob_estimates);
private:
int nr_class; // number of classes
int nr_feature; // number of features
Mat feature_min; // scale range
Mat feature_max;
Mat weights; // Logistic Regression weights
Mat kernels; // CNN kernels
Mat M, P; // ZCA Whitening parameters
int window_size; // window size
int quad_size;
int patch_size;
int num_quads; // extract 25 quads (12x12) from each image
int num_tiles; // extract 25 patches (8x8) from each quad
double alpha; // used in non-linear activation function z = max(0, |D*a| - alpha)
};
OCRHMMClassifierCNN::OCRHMMClassifierCNN (const string& filename)
{
if (ifstream(filename.c_str()))
{
FileStorage fs(filename, FileStorage::READ);
// Load kernels bank and withenning params
fs["kernels"] >> kernels;
fs["M"] >> M;
fs["P"] >> P;
// Load Logistic Regression weights
fs["weights"] >> weights;
// Load feature scaling ranges
fs["feature_min"] >> feature_min;
fs["feature_max"] >> feature_max;
fs.release();
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
// check all matrix dimensions match correctly and no one is empty
CV_Assert( (M.cols > 0) && (M.rows > 0) );
CV_Assert( (P.cols > 0) && (P.rows > 0) );
CV_Assert( (kernels.cols > 0) && (kernels.rows > 0) );
CV_Assert( (weights.cols > 0) && (weights.rows > 0) );
CV_Assert( (feature_min.cols > 0) && (feature_min.rows > 0) );
CV_Assert( (feature_max.cols > 0) && (feature_max.rows > 0) );
nr_feature = weights.rows;
nr_class = weights.cols;
patch_size = (int)sqrt((float)kernels.cols);
// algorithm internal parameters
window_size = 32;
num_quads = 25;
num_tiles = 25;
quad_size = 12;
alpha = 0.5;
}
void OCRHMMClassifierCNN::eval( InputArray _src, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert(( _src.getMat().type() == CV_8UC3 ) || ( _src.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
Mat img = _src.getMat();
if(img.type() == CV_8UC3)
{
cvtColor(img,img,COLOR_RGB2GRAY);
}
// shall we resize the input image or make a copy ?
resize(img,img,Size(window_size,window_size));
Mat quad;
Mat tmp;
int patch_count = 0;
vector< vector<double> > data_pool(9);
int quad_id = 1;
for (int q_x=0; q_x<=window_size-quad_size; q_x=q_x+(int)(quad_size/2-1))
{
for (int q_y=0; q_y<=window_size-quad_size; q_y=q_y+(int)(quad_size/2-1))
{
Rect quad_rect = Rect(q_x,q_y,quad_size,quad_size);
quad = img(quad_rect);
//start sliding window (8x8) in each tile and store the patch as row in data_pool
for (int w_x=0; w_x<=quad_size-patch_size; w_x++)
{
for (int w_y=0; w_y<=quad_size-patch_size; w_y++)
{
quad(Rect(w_x,w_y,patch_size,patch_size)).copyTo(tmp);
tmp = tmp.reshape(0,1);
tmp.convertTo(tmp, CV_64F);
normalizeAndZCA(tmp);
vector<double> patch;
tmp.copyTo(patch);
if ((quad_id == 1)||(quad_id == 2)||(quad_id == 6)||(quad_id == 7))
data_pool[0].insert(data_pool[0].end(),patch.begin(),patch.end());
if ((quad_id == 2)||(quad_id == 7)||(quad_id == 3)||(quad_id == 8)||(quad_id == 4)||(quad_id == 9))
data_pool[1].insert(data_pool[1].end(),patch.begin(),patch.end());
if ((quad_id == 4)||(quad_id == 9)||(quad_id == 5)||(quad_id == 10))
data_pool[2].insert(data_pool[2].end(),patch.begin(),patch.end());
if ((quad_id == 6)||(quad_id == 11)||(quad_id == 16)||(quad_id == 7)||(quad_id == 12)||(quad_id == 17))
data_pool[3].insert(data_pool[3].end(),patch.begin(),patch.end());
if ((quad_id == 7)||(quad_id == 12)||(quad_id == 17)||(quad_id == 8)||(quad_id == 13)||(quad_id == 18)||(quad_id == 9)||(quad_id == 14)||(quad_id == 19))
data_pool[4].insert(data_pool[4].end(),patch.begin(),patch.end());
if ((quad_id == 9)||(quad_id == 14)||(quad_id == 19)||(quad_id == 10)||(quad_id == 15)||(quad_id == 20))
data_pool[5].insert(data_pool[5].end(),patch.begin(),patch.end());
if ((quad_id == 16)||(quad_id == 21)||(quad_id == 17)||(quad_id == 22))
data_pool[6].insert(data_pool[6].end(),patch.begin(),patch.end());
if ((quad_id == 17)||(quad_id == 22)||(quad_id == 18)||(quad_id == 23)||(quad_id == 19)||(quad_id == 24))
data_pool[7].insert(data_pool[7].end(),patch.begin(),patch.end());
if ((quad_id == 19)||(quad_id == 24)||(quad_id == 20)||(quad_id == 25))
data_pool[8].insert(data_pool[8].end(),patch.begin(),patch.end());
patch_count++;
}
}
quad_id++;
}
}
//do dot product of each normalized and whitened patch
//each pool is averaged and this yields a representation of 9xD
Mat feature = Mat::zeros(9,kernels.rows,CV_64FC1);
for (int i=0; i<9; i++)
{
Mat pool = Mat(data_pool[i]);
pool = pool.reshape(0,(int)data_pool[i].size()/kernels.cols);
for (int p=0; p<pool.rows; p++)
{
for (int f=0; f<kernels.rows; f++)
{
feature.row(i).at<double>(0,f) = feature.row(i).at<double>(0,f) + max(0.0,std::abs(pool.row(p).dot(kernels.row(f)))-alpha);
}
}
}
feature = feature.reshape(0,1);
// data must be normalized within the range obtained during training
double lower = -1.0;
double upper = 1.0;
for (int k=0; k<feature.cols; k++)
{
feature.at<double>(0,k) = lower + (upper-lower) *
(feature.at<double>(0,k)-feature_min.at<double>(0,k))/
(feature_max.at<double>(0,k)-feature_min.at<double>(0,k));
}
double *p = new double[nr_class];
double predict_label = eval_feature(feature,p);
//cout << " Prediction: " << vocabulary[predict_label] << " with probability " << p[0] << endl;
if (predict_label < 0)
CV_Error(Error::StsInternal, "OCRHMMClassifierCNN::eval Error: unexpected prediction in eval_feature()");
out_class.push_back((int)predict_label);
out_confidence.push_back(p[(int)predict_label]);
for (int i = 0; i<nr_class; i++)
{
if ( (i != (int)predict_label) && (p[i] != 0.) )
{
out_class.push_back(i);
out_confidence.push_back(p[i]);
}
}
}
// normalize for contrast and apply ZCA whitening to a set of image patches
void OCRHMMClassifierCNN::normalizeAndZCA(Mat& patches)
{
//Normalize for contrast
for (int i=0; i<patches.rows; i++)
{
Scalar row_mean, row_std;
meanStdDev(patches.row(i),row_mean,row_std);
row_std[0] = sqrt(pow(row_std[0],2)*patches.cols/(patches.cols-1)+10);
patches.row(i) = (patches.row(i) - row_mean[0]) / row_std[0];
}
//ZCA whitening
if ((M.dims == 0) || (P.dims == 0))
{
Mat CC;
calcCovarMatrix(patches,CC,M,COVAR_NORMAL|COVAR_ROWS|COVAR_SCALE);
CC = CC * patches.rows / (patches.rows-1);
Mat e_val,e_vec;
eigen(CC.t(),e_val,e_vec);
e_vec = e_vec.t();
sqrt(1./(e_val + 0.1), e_val);
Mat V = Mat::zeros(e_vec.rows, e_vec.cols, CV_64FC1);
Mat D = Mat::eye(e_vec.rows, e_vec.cols, CV_64FC1);
for (int i=0; i<e_vec.cols; i++)
{
e_vec.col(e_vec.cols-i-1).copyTo(V.col(i));
D.col(i) = D.col(i) * e_val.at<double>(0,e_val.rows-i-1);
}
P = V * D * V.t();
}
for (int i=0; i<patches.rows; i++)
patches.row(i) = patches.row(i) - M;
patches = patches * P;
}
double OCRHMMClassifierCNN::eval_feature(Mat& feature, double* prob_estimates)
{
for(int i=0;i<nr_class;i++)
prob_estimates[i] = 0;
for(int idx=0; idx<nr_feature; idx++)
for(int i=0;i<nr_class;i++)
prob_estimates[i] += weights.at<float>(idx,i)*feature.at<double>(0,idx); //TODO use vectorized dot product
int dec_max_idx = 0;
for(int i=1;i<nr_class;i++)
{
if(prob_estimates[i] > prob_estimates[dec_max_idx])
dec_max_idx = i;
}
for(int i=0;i<nr_class;i++)
prob_estimates[i]=1/(1+exp(-prob_estimates[i]));
double sum=0;
for(int i=0; i<nr_class; i++)
sum+=prob_estimates[i];
for(int i=0; i<nr_class; i++)
prob_estimates[i]=prob_estimates[i]/sum;
return dec_max_idx;
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierCNN(const String& filename)
{
return makePtr<OCRHMMClassifierCNN>(std::string(filename));
}
/** @brief Utility function to create a tailored language model transitions table from a given list of words (lexicon).
@param vocabulary The language vocabulary (chars when ascii english text).
@param lexicon The list of words that are expected to be found in a particular image.
@param transition_probabilities_table Output table with transition probabilities between character pairs. cols == rows == vocabulary.size().
The function calculate frequency statistics of character pairs from the given lexicon and fills
the output transition_probabilities_table with them.
The transition_probabilities_table can be used as input in the OCRHMMDecoder::create() and OCRBeamSearchDecoder::create() methods.
@note
- (C++) An alternative would be to load the default generic language transition table provided in the text module samples folder (created from ispell 42869 english words list) :
<https://github.com/Itseez/opencv_contrib/blob/master/modules/text/samples/OCRHMM_transitions_table.xml>
*/
void createOCRHMMTransitionsTable(string& vocabulary, vector<string>& lexicon, OutputArray _transitions)
{
CV_Assert( vocabulary.size() > 0 );
CV_Assert( lexicon.size() > 0 );
if ( (_transitions.getMat().cols != (int)vocabulary.size()) ||
(_transitions.getMat().rows != (int)vocabulary.size()) ||
(_transitions.getMat().type() != CV_64F) )
{
_transitions.create((int)vocabulary.size(), (int)vocabulary.size(), CV_64F);
}
Mat transitions = _transitions.getMat();
transitions = Scalar(0);
Mat count_pairs = Mat::zeros(1, (int)vocabulary.size(), CV_64F);
for (size_t w=0; w<lexicon.size(); w++)
{
for (size_t i=0,j=1; i<lexicon[w].size()-1; i++,j++)
{
size_t idx_i = vocabulary.find(lexicon[w][i]);
size_t idx_j = vocabulary.find(lexicon[w][j]);
if ((idx_i == string::npos) || (idx_j == string::npos))
{
CV_Error(Error::StsBadArg, "Found a non-vocabulary char in lexicon!");
}
transitions.at<double>((int)idx_i,(int)idx_j) += 1;
count_pairs.at<double>(0,(int)idx_i) += 1;
}
}
for (int i=0; i<transitions.rows; i++)
{
transitions.row(i) = transitions.row(i) / count_pairs.at<double>(0,i); //normalize
}
return;
}
Mat createOCRHMMTransitionsTable(const String& vocabulary, vector<cv::String>& lexicon)
{
std::string voc(vocabulary);
vector<string> lex;
for(vector<cv::String>::iterator l = lexicon.begin(); l != lexicon.end(); l++)
lex.push_back(std::string(*l));
Mat _transitions;
createOCRHMMTransitionsTable(voc, lex, _transitions);
return _transitions;
}
}
}
| 36.869668 | 182 | 0.546715 | privet56 |
1079356793ededa288a040e9c60eda37a3c91ca1 | 6,989 | cpp | C++ | src/Master/Interface/GridCtrlSource/GridCell.cpp | averkhaturau/Tarificator | 90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5 | [
"MIT"
] | null | null | null | src/Master/Interface/GridCtrlSource/GridCell.cpp | averkhaturau/Tarificator | 90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5 | [
"MIT"
] | null | null | null | src/Master/Interface/GridCtrlSource/GridCell.cpp | averkhaturau/Tarificator | 90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5 | [
"MIT"
] | null | null | null | // GridCell.cpp : implementation file
//
// MFC Grid Control - Main grid cell class
//
// Provides the implementation for the "default" cell type of the
// grid control. Adds in cell editing.
//
// Written by Chris Maunder <cmaunder@mail.com>
// Copyright (c) 1998-2001. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20+
//
// History:
// Eric Woodruff - 20 Feb 2000 - Added PrintCell() plus other minor changes
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// <kenbertelson@hotmail.com>
// C Maunder - 17 Jun 2000 - Font handling optimsed, Added CGridDefaultCell
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCell.h"
#include "InPlaceEdit.h"
#include "GridCtrl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCell, CGridCellBase)
IMPLEMENT_DYNCREATE(CGridDefaultCell, CGridCell)
/////////////////////////////////////////////////////////////////////////////
// GridCell
CGridCell::CGridCell()
{
m_plfFont = NULL;
Reset();
}
CGridCell::~CGridCell()
{
delete m_plfFont;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
void CGridCell::operator=(const CGridCell& cell)
{
CGridCellBase::operator=( cell);
}
void CGridCell::Reset()
{
CGridCellBase::Reset();
m_strText.Empty();
m_nImage = -1;
m_pGrid = NULL;
m_bEditing = FALSE;
m_pEditWnd = NULL;
m_nFormat = (DWORD)-1; // Use default from CGridDefaultCell
m_crBkClr = CLR_DEFAULT; // Background colour (or CLR_DEFAULT)
m_crFgClr = CLR_DEFAULT; // Forground colour (or CLR_DEFAULT)
m_nMargin = (UINT)-1; // Use default from CGridDefaultCell
delete m_plfFont;
m_plfFont = NULL; // Cell font
}
void CGridCell::SetFont(const LOGFONT* plf)
{
if (plf == NULL)
{
delete m_plfFont;
m_plfFont = NULL;
}
else
{
if (!m_plfFont)
m_plfFont = new LOGFONT;
if (m_plfFont)
memcpy(m_plfFont, plf, sizeof(LOGFONT));
}
}
LOGFONT* CGridCell::GetFont() const
{
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFont();
}
return m_plfFont;
}
CFont* CGridCell::GetFontObject() const
{
// If the default font is specified, use the default cell implementation
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFontObject();
}
else
{
static CFont Font;
Font.DeleteObject();
Font.CreateFontIndirect(m_plfFont);
return &Font;
}
}
DWORD CGridCell::GetFormat() const
{
if (m_nFormat == (DWORD)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetFormat();
}
return m_nFormat;
}
UINT CGridCell::GetMargin() const
{
if (m_nMargin == (UINT)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetMargin();
}
return m_nMargin;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
BOOL CGridCell::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
if ( m_bEditing )
{
if (m_pEditWnd)
m_pEditWnd->SendMessage ( WM_CHAR, nChar );
}
else
{
DWORD dwStyle = ES_LEFT;
if (GetFormat() & DT_RIGHT)
dwStyle = ES_RIGHT;
else if (GetFormat() & DT_CENTER)
dwStyle = ES_CENTER;
m_bEditing = TRUE;
// InPlaceEdit auto-deletes itself
CGridCtrl* pGrid = GetGrid();
m_pEditWnd = new CInPlaceEdit(pGrid, rect, dwStyle, nID, nRow, nCol, GetText(), nChar);
}
return TRUE;
}
void CGridCell::EndEdit()
{
if (m_pEditWnd)
((CInPlaceEdit*)m_pEditWnd)->EndEdit();
}
void CGridCell::OnEndEdit()
{
m_bEditing = FALSE;
m_pEditWnd = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridDefaultCell
CGridDefaultCell::CGridDefaultCell()
{
#ifdef _WIN32_WCE
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
#else
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX | DT_END_ELLIPSIS;
#endif
m_crFgClr = CLR_DEFAULT;
m_crBkClr = CLR_DEFAULT;
m_Size = CSize(30,10);
m_dwStyle = 0;
#ifdef _WIN32_WCE
LOGFONT lf;
GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
SetFont(&lf);
#else // not CE
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
SetFont(&(ncm.lfMessageFont));
#endif
}
CGridDefaultCell::~CGridDefaultCell()
{
m_Font.DeleteObject();
}
void CGridDefaultCell::SetFont(const LOGFONT* plf)
{
ASSERT(plf);
if (!plf) return;
m_Font.DeleteObject();
m_Font.CreateFontIndirect(plf);
CGridCell::SetFont(plf);
// Get the font size and hence the default cell size
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
if (pDC)
{
CFont* pOldFont = pDC->SelectObject(&m_Font);
SetMargin(pDC->GetTextExtent(_T(" "), 1).cx);
m_Size = pDC->GetTextExtent(_T(" XXXXXXXXXXXX "), 14);
m_Size.cy = (m_Size.cy * 3) / 2;
pDC->SelectObject(pOldFont);
ReleaseDC(NULL, pDC->GetSafeHdc());
}
else
{
SetMargin(3);
m_Size = CSize(40,16);
}
}
LOGFONT* CGridDefaultCell::GetFont() const
{
ASSERT(m_plfFont); // This is the default - it CAN'T be NULL!
return m_plfFont;
}
CFont* CGridDefaultCell::GetFontObject() const
{
ASSERT(m_Font.GetSafeHandle());
return (CFont*) &m_Font;
}
| 25.050179 | 95 | 0.586922 | averkhaturau |
107b6ea10ec0c7ffabde63763b40b16f15bb4380 | 12,809 | hpp | C++ | include/GlobalNamespace/TutorialPause.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/TutorialPause.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/TutorialPause.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: IGamePause
#include "GlobalNamespace/IGamePause.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: TutorialSongController
class TutorialSongController;
// Forward declaring type: SaberManager
class SaberManager;
// Forward declaring type: AudioListenerController
class AudioListenerController;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: TutorialPause
class TutorialPause;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::TutorialPause);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::TutorialPause*, "", "TutorialPause");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x41
#pragma pack(push, 1)
// Autogenerated type: TutorialPause
// [TokenAttribute] Offset: FFFFFFFF
class TutorialPause : public ::Il2CppObject/*, public ::GlobalNamespace::IGamePause*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// [InjectAttribute] Offset: 0x12565E0
// private readonly TutorialSongController _tutorialSongController
// Size: 0x8
// Offset: 0x10
::GlobalNamespace::TutorialSongController* tutorialSongController;
// Field size check
static_assert(sizeof(::GlobalNamespace::TutorialSongController*) == 0x8);
// [InjectAttribute] Offset: 0x12565F0
// private readonly SaberManager _saberManager
// Size: 0x8
// Offset: 0x18
::GlobalNamespace::SaberManager* saberManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::SaberManager*) == 0x8);
// [InjectAttribute] Offset: 0x1256600
// private readonly AudioListenerController _audioListenerController
// Size: 0x8
// Offset: 0x20
::GlobalNamespace::AudioListenerController* audioListenerController;
// Field size check
static_assert(sizeof(::GlobalNamespace::AudioListenerController*) == 0x8);
// private System.Action didPauseEvent
// Size: 0x8
// Offset: 0x28
::System::Action* didPauseEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action willResumeEvent
// Size: 0x8
// Offset: 0x30
::System::Action* willResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action didResumeEvent
// Size: 0x8
// Offset: 0x38
::System::Action* didResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Boolean _pause
// Size: 0x1
// Offset: 0x40
bool pause;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Creating interface conversion operator: operator ::GlobalNamespace::IGamePause
operator ::GlobalNamespace::IGamePause() noexcept {
return *reinterpret_cast<::GlobalNamespace::IGamePause*>(this);
}
// Get instance field reference: private readonly TutorialSongController _tutorialSongController
::GlobalNamespace::TutorialSongController*& dyn__tutorialSongController();
// Get instance field reference: private readonly SaberManager _saberManager
::GlobalNamespace::SaberManager*& dyn__saberManager();
// Get instance field reference: private readonly AudioListenerController _audioListenerController
::GlobalNamespace::AudioListenerController*& dyn__audioListenerController();
// Get instance field reference: private System.Action didPauseEvent
::System::Action*& dyn_didPauseEvent();
// Get instance field reference: private System.Action willResumeEvent
::System::Action*& dyn_willResumeEvent();
// Get instance field reference: private System.Action didResumeEvent
::System::Action*& dyn_didResumeEvent();
// Get instance field reference: private System.Boolean _pause
bool& dyn__pause();
// public System.Boolean get_isPaused()
// Offset: 0x2AB2338
bool get_isPaused();
// public System.Void add_didPauseEvent(System.Action value)
// Offset: 0x2AB2340
void add_didPauseEvent(::System::Action* value);
// public System.Void remove_didPauseEvent(System.Action value)
// Offset: 0x2AB23E4
void remove_didPauseEvent(::System::Action* value);
// public System.Void add_willResumeEvent(System.Action value)
// Offset: 0x2AB2488
void add_willResumeEvent(::System::Action* value);
// public System.Void remove_willResumeEvent(System.Action value)
// Offset: 0x2AB252C
void remove_willResumeEvent(::System::Action* value);
// public System.Void add_didResumeEvent(System.Action value)
// Offset: 0x2AB25D0
void add_didResumeEvent(::System::Action* value);
// public System.Void remove_didResumeEvent(System.Action value)
// Offset: 0x2AB2674
void remove_didResumeEvent(::System::Action* value);
// public System.Void Pause()
// Offset: 0x2AB2718
void Pause();
// public System.Void WillResume()
// Offset: 0x2AB2798
void WillResume();
// public System.Void Resume()
// Offset: 0x2AB27AC
void Resume();
// public System.Void .ctor()
// Offset: 0x2AB2828
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TutorialPause* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::TutorialPause::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TutorialPause*, creationType>()));
}
}; // TutorialPause
#pragma pack(pop)
static check_size<sizeof(TutorialPause), 64 + sizeof(bool)> __GlobalNamespace_TutorialPauseSizeCheck;
static_assert(sizeof(TutorialPause) == 0x41);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::get_isPaused
// Il2CppName: get_isPaused
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::get_isPaused)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "get_isPaused", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didPauseEvent
// Il2CppName: add_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didPauseEvent
// Il2CppName: remove_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_willResumeEvent
// Il2CppName: add_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_willResumeEvent
// Il2CppName: remove_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didResumeEvent
// Il2CppName: add_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didResumeEvent
// Il2CppName: remove_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Pause
// Il2CppName: Pause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Pause)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Pause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::WillResume
// Il2CppName: WillResume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::WillResume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "WillResume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Resume
// Il2CppName: Resume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Resume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Resume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 50.231373 | 190 | 0.727145 | RedBrumbler |
107d7ec8a92c6a27de175150a6be5eda68ed18cc | 797 | cpp | C++ | nowcoder/9799B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | nowcoder/9799B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | nowcoder/9799B.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n; cin >> n;
vector<vector<int> > arr(n, vector<int>());
for(int i = 0; i < n; i++)
{
int nums = 0; cin >> nums;
for(int j = 0; j < nums; j++)
{
int v; cin >> v; arr[i].push_back(v);
}
sort(arr[i].begin(), arr[i].end());
}
int q; cin >> q;
while(q--)
{
int l, r, k, p;
cin >> l >> r >> k >> p;
l--;r--;k--;
int f = arr[k][arr[k].size()-p];
int ans = 0;
for(int i = l; i <= r; i++)
{
auto ret = upper_bound(arr[i].begin(), arr[i].end(), f);
ans += distance(ret, arr[i].end());
}
cout << ans+1 << endl;
}
return 0;
} | 22.771429 | 68 | 0.410289 | freedomDR |
1084b2d9e3d1eb38da6196c82593f51170b5a413 | 1,608 | cpp | C++ | src/poc/ncpp_build_exceptions.cpp | grendello/notcurses | a2cc5f096adb3991f264d96657b45a050fa8df2a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/poc/ncpp_build_exceptions.cpp | grendello/notcurses | a2cc5f096adb3991f264d96657b45a050fa8df2a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/poc/ncpp_build_exceptions.cpp | grendello/notcurses | a2cc5f096adb3991f264d96657b45a050fa8df2a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #define NCPP_EXCEPTIONS_PLEASE
//
// This is a **build** test - it does nothing else except ensure that all the C++ wrapper classes are included and that
// the program builds.
//
// Once there are demos which exercise all the C++ classes this "test" can be removed
//
#include <cstdlib>
#include <clocale>
#include <iostream>
#include <ncpp/NotCurses.hh>
#include <ncpp/Menu.hh>
#include <ncpp/Plane.hh>
#include <ncpp/Reel.hh>
#include <ncpp/MultiSelector.hh>
#include <ncpp/Selector.hh>
#include <ncpp/Visual.hh>
#include <ncpp/Direct.hh>
#include <ncpp/Plot.hh>
#include <ncpp/FDPlane.hh>
#include <ncpp/Subproc.hh>
using namespace ncpp;
int run ()
{
NotCurses nc;
const char *ncver = nc.version ();
{
Plane p1 (1, 1, 0, 0);
Plot plot1 (p1);
Plane p2 (1, 1, 0, 0);
PlotU plot2 (p2);
Plane p3 (1, 1, 0, 0);
PlotD plot3 (p3);
}
nc.stop ();
Direct direct (getenv ("TERM"));
direct.set_fg_rgb (0xb5, 0x0d, 0xff);
std::cout << "notcurses version: ";
direct.set_bg_rgb (0x05, 0x6e, 0xee);
direct.set_fg_rgb (0xe2, 0xbf, 0x00);
std::cout << ncver << std::endl;
return 0;
}
int main ()
{
if (!setlocale (LC_ALL, "")){
std::cerr << "Couldn't set locale based on user preferences" << std::endl;
return EXIT_FAILURE;
}
try {
return run ();
} catch (ncpp::init_error &e) {
std::cerr << "Initialization error: " << e.what () << std::endl;
} catch (ncpp::invalid_state_error &e) {
std::cerr << "Invalid state error: " << e.what () << std::endl;
} catch (ncpp::invalid_argument &e) {
std::cerr << "Invalid argument error: " << e.what () << std::endl;
}
return 1;
}
| 22.971429 | 119 | 0.648632 | grendello |
c8066f8a93d79afc2b8617619e8c4a6373223281 | 609 | cpp | C++ | Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp | wardimanxixv/CPP-Basic | 332adde53ebc73bef20080a7cf7f195820394c37 | [
"MIT"
] | null | null | null | Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp | wardimanxixv/CPP-Basic | 332adde53ebc73bef20080a7cf7f195820394c37 | [
"MIT"
] | null | null | null | Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp | wardimanxixv/CPP-Basic | 332adde53ebc73bef20080a7cf7f195820394c37 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
long int decimalNumber, remainder, quotient;
int i = 1, j, temp;
char hexadecimalNumber[100];
cout << "Masukkan Bilangan Decimal : "; cin >> decimalNumber;
quotient = decimalNumber;
while (quotient != 0)
{
temp = quotient % 16;
if (temp < 10) {
temp = temp + 48;
}
else {
temp = temp + 55;
}
hexadecimalNumber[i++] = temp;
quotient = quotient / 16;
}
cout << "Bilangan Hexadecimalnya adalah : ";
for (j = i; j > 0; j--)
{
cout << hexadecimalNumber[j];
}
return 0;
}
//@wardiman_xixv | 19.03125 | 63 | 0.584565 | wardimanxixv |
c807bd8d0fbb1cc985db83edcbc2d5d1384e1cf9 | 5,697 | hpp | C++ | include/engine/Logger.hpp | Mathieu-Lala/NewDimension | 9200692e79dc1d983f51043f3c195eb1b865a74d | [
"0BSD"
] | 4 | 2019-11-19T23:53:26.000Z | 2019-12-10T11:19:28.000Z | include/engine/Logger.hpp | Mathieu-Lala/NewDimension | 9200692e79dc1d983f51043f3c195eb1b865a74d | [
"0BSD"
] | null | null | null | include/engine/Logger.hpp | Mathieu-Lala/NewDimension | 9200692e79dc1d983f51043f3c195eb1b865a74d | [
"0BSD"
] | null | null | null | /*
** EPITECH PROJECT, 2019
** NewDimension
** File description:
** Logger
*/
#ifndef LOGGER_HPP_
# define LOGGER_HPP_
# include <ostream>
# include <iostream>
# include <array>
# include <ctime>
# include <functional>
# include "config/config.hpp"
namespace nd {
namespace engine {
class Logger {
public:
Logger() = delete;
static bool set_stream(const std::string_view filepath);
enum level {
DEBUG,
INFO,
NOTICE,
WARNING,
ERROR,
ALERT,
CRITIC,
EMERGENCY,
UNKNOWN,
};
inline static level get_current_level() noexcept
{ return s_current_level; }
inline static void set_current_level(level new_level) noexcept
{ s_current_level = new_level; }
struct data {
level msg_level;
const char *file;
int line;
const char *func;
std::time_t timestamp;
};
static std::ostream &dump_info(const data &data_info);
inline static void set_format(const std::string &new_format) noexcept
{ s_display_format = new_format; }
protected:
private:
static std::ostream *s_stream;
static level s_current_level;
static std::string s_display_format;
static constexpr std::ostream *DEFAULT_STREAM = &std::cerr;
static constexpr level DEFAULT_LEVEL = DEBUG;
static constexpr auto DEFAULT_DISPLAY_FORMAT =
"[${info:level}] id:${info:uid} at:${style:underline}${info:timestamp}${style:reset} "
"in file ${info:file} at line ${style:bold:underline}${info:line}${style:reset} "
"in function ${style:fg-blue:bold}${info:func}${style:reset}:\r\n";
using uid = std::size_t;
static uid s_current_msg_uid;
static constexpr std::array S_LEVEL_AS_STRING {
std::make_pair(DEBUG, "${style:fg-lightcyan}DEBUG${style:reset}"),
std::make_pair(INFO, "${style:fg-lightgreen}INFO${style:reset}"),
std::make_pair(NOTICE, "${style:fg-green}NOTICE${style:reset}"),
std::make_pair(WARNING, "${style:fg-lightyellow}WARNING${style:reset}"),
std::make_pair(ERROR, "${style:fg-red:bold}ERROR${style:reset}"),
std::make_pair(ALERT, "${style:fg-lightred:underline:bold}ALERT${style:reset}"),
std::make_pair(CRITIC, "${style:fg-black:blink:bg-yellow}CRITIC${style:reset}"),
std::make_pair(EMERGENCY, "${style:fg-black:blink:bold:underline:bg-lightred}EMERGENCY${style:reset}"),
};
static constexpr std::optional<const char *> level_as_string(level search);
using PairStyle = std::pair<const char *, const char *>;
static constexpr std::array<const PairStyle, 47> S_SUPPORTED_STYLE {
// Colors
std::make_pair("fg-red", "31"), std::make_pair("bg-red", "41"),
std::make_pair("fg-lightred", "91"), std::make_pair("bg-lightred", "101"),
std::make_pair("fg-green", "32"), std::make_pair("bg-green", "42"),
std::make_pair("fg-lightgreen", "92"), std::make_pair("bg-lightgreen", "102"),
std::make_pair("fg-blue", "34"), std::make_pair("bg-blue", "44"),
std::make_pair("fg-lightblue", "94"), std::make_pair("bg-lightblue", "104"),
std::make_pair("fg-yellow", "33"), std::make_pair("bg-yellow", "43"),
std::make_pair("fg-lightyellow", "93"), std::make_pair("bg-lightyellow", "103"),
std::make_pair("fg-magenta", "35"), std::make_pair("bg-magenta", "45"),
std::make_pair("fg-lightmagenta", "95"), std::make_pair("bg-lightmagenta", "105"),
std::make_pair("fg-cyan", "36"), std::make_pair("bg-cyan", "46"),
std::make_pair("fg-lightcyan", "96"), std::make_pair("bg-lightcyan", "106"),
std::make_pair("fg-white", "97"), std::make_pair("bg-white", "107"),
std::make_pair("fg-lightgrey", "37"), std::make_pair("bg-lightgrey", "47"),
std::make_pair("fg-darkgrey", "90"), std::make_pair("bg-drakgrey", "100"),
std::make_pair("fg-black", "30"), std::make_pair("bg-black", "40"),
std::make_pair("fg-default", "39"), std::make_pair("bg-default", "49"),
// ... complete me
// Styles / Effects
std::make_pair("bold", "1"), std::make_pair("bold-off", "21"),
std::make_pair("dim", "2"), std::make_pair("dim-off", "22"),
std::make_pair("underline", "4"), std::make_pair("underline-off", "24"),
std::make_pair("blink", "5"), std::make_pair("blink-off", "25"),
std::make_pair("inverse", "7"), std::make_pair("inverse-off", "27"),
std::make_pair("hidden", "8"), std::make_pair("hidden-off", "28"),
// ... complete me
std::make_pair("reset", "0"),
};
static constexpr std::optional<PairStyle> get_style_value(const char *search);
};
} // namespace engine
} // namespace new dimension
# define LOG(level, exp) do { \
if (nd::engine::Logger::get_current_level() <= level) \
nd::engine::Logger::dump_info({ level, __FILE__, __LINE__, __func__, std::time(nullptr) }) \
<< exp << std::endl; \
} while (false)
# if PROJECT_BUILD_TYPE == Debug
# define DEBUG(exp) LOG(nd::engine::Logger::DEBUG, exp)
# else
# define DEBUG(exp)
# endif
# define INFO(exp) LOG(nd::engine::Logger::INFO, exp)
# define NOTICE(exp) LOG(nd::engine::Logger::NOTICE, exp)
# define WARNING(exp) LOG(nd::engine::Logger::WARNING, exp)
# define ERROR(exp) LOG(nd::engine::Logger::ERROR, exp)
# define ALERT(exp) LOG(nd::engine::Logger::ALERT, exp)
# define CRITIC(exp) LOG(nd::engine::Logger::CRITIC, exp)
# define EMERGENCY(exp) LOG(nd::engine::Logger::EMERGENCY, exp)
#endif /* !LOGGER_HPP_ */
| 35.385093 | 111 | 0.610848 | Mathieu-Lala |
c807e185b44fcba37d206a60d9a6e874368e4074 | 16,032 | cpp | C++ | common.cpp | SBcodework/Minesweeper-in-C- | e2ca6364f5afc6faa3ca723a926c64603d0f4ffc | [
"BSD-2-Clause"
] | null | null | null | common.cpp | SBcodework/Minesweeper-in-C- | e2ca6364f5afc6faa3ca723a926c64603d0f4ffc | [
"BSD-2-Clause"
] | 4 | 2019-06-28T18:08:49.000Z | 2019-07-04T03:41:32.000Z | common.cpp | SBcodework/Minesweeper-in-C- | e2ca6364f5afc6faa3ca723a926c64603d0f4ffc | [
"BSD-2-Clause"
] | null | null | null | /**
BSD 2-Clause License
Copyright (c) 2019, SBcodework
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <iostream>
#include "common.h"
#include "Parameter.h"
#include "Gridtype.h"
#include "Cordtype.h"
#include <string>
#include <typeinfo>
#include <algorithm>
#include <vector>
#include <bitset>
#include <random>
#include <time.h>
#include <cmath>
int extractDigitInt( int digits, std::string input )
{
int result = 0;
int length = input.length();
if ( length == 0 || digits < 0 )
{
return -1;
}
/// Find the furthest index of the string representing the smallest digit (under 10) as string length permits.
int digitsFirstGuess = digits; //(length > digits) ? length : digits;
int digitsSecondGuess = 0; /// Below: find the first digit.
for ( int i = 0; (i < digitsFirstGuess) && (isdigit(input[i])) && (i < length); i++ )
{
digitsSecondGuess++;
}
if ( digitsSecondGuess == 0 )
{
return -1;
}
//float digit = digitsSecondGuess;
for ( int i = (digitsSecondGuess - 1), magnitude = 0, inputDigit = 0, power = 0; i >= 0; i--, power++ ) /// Start backwards from the furthest index
{
inputDigit = (int)(input[i] - '0');
magnitude = (int)(std::pow(10.0, (float)power));
result += (inputDigit * magnitude);
}
return result;
}
void askXYMinesLoop(Parameter& out_param)
{
int x, y, mines, area; // Output containers
std::string strx;
std::string stry;
std::string strMines;
for (;;)
{
std::cout << "Grid Length? ";
std::cin >> strx;
std::cout << "Grid Height? ";
std::cin >> stry;
std::cout << "Number of mines? ";
std::cin >> strMines;
x = extractDigitInt(2, strx);
y = extractDigitInt(2, stry);
mines = extractDigitInt(4, strMines); //4 digits
if ( x < 1 || y < 1 || mines < 1 || x > 99 || y > 99 || mines > 9801 ||
( x < 4 && y < 4 ) || ( mines > ((x*y)-9) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
out_param.length = x;
out_param.height = y;
out_param.mines = mines;
out_param.init_dimensions();
return;
break;
}
}
void dispEmpty(Parameter& in_param)
{
int length = in_param.length;
int height = in_param.height;
std::cout << " "; // 5 spaces
for (int i=0; i<length; i++)
{
std::cout << "{" << (i/10) << (i%10) << "}";
}
std::cout << "\n";
for (int i=0; i<height; i++)
{
std::cout << "{" << (i/10) << (i%10) << "} ";
for (int n=0; n<length; n++)
{
std::cout << "[ ]";
}
std::cout << "\n";
}
return;
}
int askStartXYLoop(Parameter& out_param)
{
int error = 0, length = 0;
std::string line; // "cin.get()" Is not used, as it skips the first character of input.
for (int skip = 0; ;skip = 0)
{
line = ""; // Reset the line each loop
std::cout << "Enter X cord, followed by a comma, and Y cord. Like '13,8'. \n";
std::cin >> line;
length = line.length();
//std::getline(std::cin, line); Old method, above worked better
if ( (length < 3) || ((line[1] != ',') && (line[2] != ',')) || !isdigit(line[0]) ||
(!isdigit(line[1]) && (line[1] != ',')) || (!isdigit(line[2]) && (line[2] != ',')) ||
((length > 3) && (line[2] == ',') && !isdigit(line[3]) ) )
{
std::cout << "Invalid! Try again. Line: " << line << "\n";
continue;
}
error = h_extractCoords(line, out_param.xStart, out_param.yStart, nullptr, ',');
if ((out_param.xStart >= out_param.length) || (out_param.yStart >= out_param.height))
{
std::cout << "Coordinates out of range! Try again. Line: " << line << "\n";
continue;
}
switch (error)
{
case 0:
break;
case 1:
std::cout << "Error in askStartXYLoop! ";
std::cout << "x, y: " << out_param.xStart << " " << out_param.yStart << "\n";
return 1;
case 2:
std::cout << "Invalid! Try again. Line: " << line << "\n";
skip = 1;
}
if (skip)
{
continue;
}
out_param.init_start();
return 0;
}
}
int h_extractCoords(std::string in_line, int& out_x, int& out_y, char* out_sep, char sep)
{
int length = in_line.length();
if ( (length < 3) || (length > 5) )
{
return 2; // Too long or too short; for legacy reasons 2 is the error code for user errors
}
int x = extractDigitInt( 2, in_line );
int slicedStart = (x < 10) ? 2 : 3;
if ( (x == -1) || (slicedStart > length) )
{
return 2; // Invalid X or string is too short for a separator to fit
}
char separator = in_line[slicedStart - 1];
if ( ( (separator != sep) && sep != '\0' ) || ( (sep == '\0') && isdigit(separator) ) )
{
return 2; // An invalid separator is found when it is defined in the arguments, or if the separator is a digit when searching for one.
}
std::string slicedString = in_line.substr( slicedStart, length );
int y = extractDigitInt( 2, slicedString );
if ( y == -1 )
{
return 2; // Invalid y
}
if ( out_sep != nullptr )
{
*out_sep = separator;
}
out_x = x;
out_y = y;
return 0;
}
void gengrid(Gridtype& out_grid)
{ // Parameters are declared below
srand(time(0)); // Init randomizer
Parameter* params = out_grid.pParams;
int w = params->length;
int h = params->height;
int area = h*w;
int xstart = params->xStart;
int ystart = params->yStart;
int istart = params->iStart; //Unneeded at the moment
int mines = params->mines;
char* rawGrid = new char[area];
std::fill_n(rawGrid, area, '0'); // Fill with zeros
int startSquare[9] {0}; // Indexes of the start square
getSquare(xstart, ystart, w, h, startSquare);
int clearCounter = 0;
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare
{
state = startSquare[i]; /*
if (state > -1 && state < area)
{
continue;
}*/
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = 'c';
clearCounter++; // Count the number of valid mine-less spots
}
}
int* mineList = new int[mines];
std::fill_n(mineList, mines, 0);
int mineLCounter = 0;
int mineCandidates[mines + 9] {0};
uniqueRand(mines+9, 0, area, mineCandidates); // mineCandidates now has a list of unique mines.
for (int i = 0; ((i < mines+9) && (mineLCounter < mines)) ; i++)
{
if ((rawGrid[mineCandidates[i]] != 'c') && mineLCounter < (mines))
{
mineList[mineLCounter] = mineCandidates[i];
rawGrid[mineList[mineLCounter]] = 'X';
mineLCounter++; /// This needs to be here, not in the above for() declaration.
}
}
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare, set back to 0's, we don't need 'c's anymore
{
state = startSquare[i];
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = '0';
}
}
for (int i = 0, square[9] {0}, currentMine; i < mines; i++) // Count numbers and put them in
{
currentMine = mineList[i];
getSquare(currentMine % w, currentMine / w, w, h, square); ///Watch in case of bug
for (int n = 0, state = 0; n < 9; n++)
{
state = square[n];
if ( state != -1 && rawGrid[state] != 'X' && rawGrid[state] >= '0' && rawGrid[state] < '8' )
{
rawGrid[state]++; // '0' goes to '1' and so on
}
}
}
out_grid.set_grid(rawGrid); // Return
out_grid.set_minelist(mineList);
out_grid.action( istart, 's' );
return;
}
void getSquare(int centerX, int centerY, int w, int h, int out_square[9])
{
int xpart = 0;
int ypart = 0;
int startX = centerX - 1;
int startY = centerY - 1;
for (int iy = 0, counter = 0; iy < 3 ; iy++)
{
for (int ix = 0; ix < 3; ix++, counter++)
{
xpart = startX + ix;
ypart = startY + iy;
out_square[counter] = toIndexCheck(xpart, ypart, w, h);
}
}
return;
}
int toIndexCheck(int x, int y, int w, int h)
{
if (outOfBounds(x, y, w, h))
{
return -1;
}
return ((y*w) + x );
}
int outOfBounds(int x, int y, int w, int h)
{
if (x >= 0 && y >= 0 && x < w && y <h)
{
return 0;
}
return 1;
}
// Numlimit is exclusive. Output must be of size "size".
int uniqueRand(int size, int start, int numlimit, int* output)
{
/// init srand
std::vector<bool> bvector(numlimit, 0);
int currentStart = 0;
int currentEnd = 0; // Inclusive
int currentMiddle = 0; // Exclusive; the inclusive start of the second sequence.
int currentSize = 0;
for (int counter = 0; counter < size; counter++)
{
currentStart = start;
currentEnd = numlimit;
currentMiddle = (numlimit / 2); // Seperator at right. -1 used to be here
currentSize = numlimit - start; /// changed from numlimit
for (int state = 0, choice = 0 ; ; )
{
if (currentStart == (currentEnd-1))
{
if (bvector[currentStart] == 1)
{
std::cout << "Duplicate error!\n";
}
output[counter] = currentStart; // We have found our number
bvector[currentStart] = true;
break;
}
state = allCheck(currentStart, currentMiddle, currentEnd, bvector);
switch (state)
{
case 0: // Choose a random element. 0 = left, 1 = right.
choice = (rand() % 2);
break;
case 1: // Choose left
choice = 0;
break;
case 2: // Choose right
choice = 1;
break;
case 3:
std::cout << "Array full! Size: " << currentSize << " Start: " << currentStart << " Middle: " << currentMiddle << " End: " << currentEnd << "\n";
for ( int n=0; n<size; n++)
{
std::cout << output[n];
}
std::cout << "\n";
return 1;
}
switch (choice)
{
case 0:
currentEnd = currentMiddle;
currentSize = currentEnd - currentStart; // removed +1
currentMiddle = currentStart + (currentSize / 2); // removed -1, added currentstart
break;
case 1:
currentStart = currentMiddle; //removed +1
currentSize = currentEnd - currentStart; //removed +1
currentMiddle = currentStart + (currentSize / 2); //removed -1
break;
}
}
}
return 0;
}
// OLD documentation:
// Include start and end. Middle refers to the seperatation RIGHT of the index. It is added one locally, same with end.
// Return 0 if neither left or right is all 1's. 1 if only the left one has a zero in it, 2 if it's right, and 3 for both.
// New documentation: Include start, in_middle includes the start of the second sequence, in_end is exclusive.
int allCheck(int start, int middle, int end, std::vector<bool>& in_vector)
{
int allLeft = 1; // 1 meaning all ones are in the bit array.
int allRight = 1;
///int middle = in_middle + 1; // LEFT of index; testing
//int end = in_end + 1; // Exclusive
//int middle = (end - start) / 2;
for (int currentStart = start, currentEnd = middle, *flag = &allLeft, t = 0;
t < 2;
t++, currentStart = middle, currentEnd = end, flag = &allRight) // Two times, go through left and right
{
for (int i = currentStart , size = currentEnd - currentStart; i < currentEnd; i++ ) // Commented out portion was unused
{
if (in_vector[i] == false) // Remember to init the vector with zeroes, else seg fault here
{
*flag = 0; // There's a zero in the bit array.
break;
}
}
}
switch (allLeft + allRight)
{
case 0: // Neither are ones
return 0;
case 1:
if (allLeft) // Right only has no ones
{
return 2;
}
return 1; // Left has no ones
case 2:
std::cout << "Sub-array full! Dump: \n";
for ( int n=0; n<(end-start); n++)
{
std::cout << in_vector[n];
}
std::cout << "\n";
return 3; // Both have ones
}
std::cout << "Error in allCheck(...)!\n"; // Shouldn't reach here, added to avoid compiler warning
return 0;
}
void askSelectionXYTLoop( Cordtype& out_cord )
{
// Gather input (h_extract_cords)
// Output trimmed input to out_cord
// Find the seperator, then run h_extractcords
std::string line = "\0" ;
int x = 0, y = 0 ;
char sep = '1';
for (int error = 1, loopError = 1; loopError ;)
{
std::cout << "\nSelect a point and an action. 's' to uncover, 'm' to middle click, and 'f' to flag. Like '13f7'. \n";
std::cin >> line;
error = h_extractCoords( line, x, y, &sep ) ;
if ( error || (x < 0) || (y < 0) || (x > (out_cord.pParams->length)) || (y > (out_cord.pParams->height) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
switch (sep)
{
case 's':
case 'm':
case 'f':
loopError = 0;
break;
default:
std::cout << "AskXYT Error, sep is invalid! Sep: " << sep << ". Try again.\n";
}
}
out_cord.setter(x, y, sep) ;
return ;
}
| 31.130097 | 162 | 0.515594 | SBcodework |
c808ab04bf668e3806d4b1e55823bf4a3b80a69c | 1,731 | cpp | C++ | ui/widget/ChangeFrontBackColorWidget.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | 5 | 2021-03-11T00:30:25.000Z | 2021-07-28T00:31:20.000Z | ui/widget/ChangeFrontBackColorWidget.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | null | null | null | ui/widget/ChangeFrontBackColorWidget.cpp | shinehanx/openphoto | e4466e5e80829385d2aa84813f2d5a8960053845 | [
"Apache-2.0"
] | 1 | 2021-09-14T16:28:26.000Z | 2021-09-14T16:28:26.000Z | #include "ChangeFrontBackColorWidget.h"
#include <QDebug>
#define CHANGEFRONTBACKCOLORWIDGET_MARGIN 3
#define CHANGEFRONTBACKCOLORWIDGET_BTN_W 12
#define CHANGEFRONTBACKCOLORWIDGET_BTN_H 12
ChangeFrontBackColorWidget::ChangeFrontBackColorWidget(QWidget *parent) : QWidget(parent)
{
setAutoFillBackground(true);
}
/**
* @brief ChangeFrontBackColorWidget::setup
* 初始化UI
*/
void ChangeFrontBackColorWidget::setup()
{
int x = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
w = CHANGEFRONTBACKCOLORWIDGET_BTN_W,
h = CHANGEFRONTBACKCOLORWIDGET_BTN_H;
QRect rect = geometry();
qDebug() << "ChangeFrontBackColorWidget this rect:" << rect;
//填充和描边按钮
fillStrokeBtn = new ImageView(this);
fillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.left rect:" << QRect(x,y,w,h);
//切换填充和描边按钮
x = rect.width() - CHANGEFRONTBACKCOLORWIDGET_MARGIN - CHANGEFRONTBACKCOLORWIDGET_BTN_W;
changeFillStrokeBtn = new ImageView(this);
changeFillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/change-fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.right rect:" << QRect(x,y,w,h);
//切换填充和描边控件
fillStrokeColorWidget = new FillStrokeColorWidget(this);
x = CHANGEFRONTBACKCOLORWIDGET_MARGIN;
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN * 3 + CHANGEFRONTBACKCOLORWIDGET_BTN_H;
w = rect.width() - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
h = rect.height() - y - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
fillStrokeColorWidget->setGeometry(x, y, w, h);
qDebug() << "ChangeFrontBackColorWidget.bottom rect:" << QRect(x,y,w,h);
fillStrokeColorWidget->setup();
}
| 36.829787 | 92 | 0.732525 | shinehanx |
c80b8970465cd21883aa8b06d13425182124e32c | 233 | cpp | C++ | test/po/gtest.cpp | JieDing/WasmEdge | b2f17c807ba2b4b6294af9e15113cca04919906e | [
"Apache-2.0"
] | 2,084 | 2021-04-30T11:20:17.000Z | 2022-03-31T21:31:47.000Z | test/po/gtest.cpp | JieDing/WasmEdge | b2f17c807ba2b4b6294af9e15113cca04919906e | [
"Apache-2.0"
] | 990 | 2021-04-29T18:43:51.000Z | 2022-03-31T15:32:51.000Z | test/po/gtest.cpp | JieDing/WasmEdge | b2f17c807ba2b4b6294af9e15113cca04919906e | [
"Apache-2.0"
] | 343 | 2021-05-04T20:27:10.000Z | 2022-03-29T03:31:26.000Z | // SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2019-2022 Second State INC
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 23.3 | 53 | 0.729614 | JieDing |
c80eb117a88136d8a488b4d0ae220c3ce70ceb17 | 5,486 | cc | C++ | src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 92 | 2015-02-09T22:42:11.000Z | 2022-03-25T09:14:50.000Z | src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 1,618 | 2015-01-05T19:39:13.000Z | 2022-03-27T20:28:45.000Z | src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 64 | 2015-02-20T17:51:23.000Z | 2021-11-19T07:08:08.000Z | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
// TODO: test with more field types...
namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
std::cout << "Basis # " << basis << std::endl;
FieldInformation lfi("LatVolMesh", basis, "double");
size_type sizex = 2, sizey = 3, sizez = 4;
Point minb(-1.0, -1.0, -1.0);
Point maxb(1.0, 1.0, 1.0);
MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
FieldHandle ofh = CreateField(lfi,mesh);
ofh->vfield()->clear_all_values();
GetFieldBoundaryAlgo algo;
FieldHandle boundary;
MatrixHandle mapping;
algo.run(ofh, boundary, mapping);
ASSERT_TRUE(boundary.get() != nullptr);
/// @todo: need assertions on boundary field
if (basis != -1)
{
ASSERT_TRUE(mapping != nullptr);
EXPECT_EQ(expectedMatrixRows, mapping->nrows());
EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
EXPECT_EQ(expectedMatrixString, matrix_to_string(*convertMatrix::toDense(mapping)));
}
}
const std::string matrixCells =
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n";
const std::string matrixNodes =
"1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}
TEST(GetFieldBoundaryTest, LatVolBoundary)
{
runTest(0, 22, 6, matrixCells);
runTest(-1, 0, 0);
runTest(1, 24, 24, matrixNodes);
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
GetFieldBoundaryAlgo algo;
FieldHandle input, output;
MatrixHandle mapping;
EXPECT_FALSE(algo.run(input, output, mapping));
EXPECT_FALSE(algo.run(input, output));
}
| 34.503145 | 153 | 0.644185 | Haydelj |
c8143f4acce02eb5866bb688628c0da88133b559 | 10,360 | cpp | C++ | src/sim/airframe/atmos.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/sim/airframe/atmos.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/sim/airframe/atmos.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | /******************************************************************************/
/* */
/* Unit Name : atmos.cpp */
/* */
/* Abstract : Calculates atmosphere at the current altitude */
/* */
/* Naming Conventions : */
/* */
/* Public Functions : Mixed case with no underscores */
/* Private Functions : Mixed case with no underscores */
/* Public Functions : Mixed case with no underscores */
/* Global Variables : Mixed case with no underscores */
/* Classless Functions : Mixed case with no underscores */
/* Classes : All upper case seperated by an underscore */
/* Defined Constants : All upper case seperated by an underscore */
/* Macros : All upper case seperated by an underscore */
/* Structs/Types : All upper case seperated by an underscore */
/* Private Variables : All lower case seperated by an underscore */
/* Public Variables : All lower case seperated by an underscore */
/* Local Variables : All lower case seperated by an underscore */
/* */
/* Development History : */
/* Date Programer Description */
/*----------------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/******************************************************************************/
#include "stdhdr.h"
#include "airframe.h"
#include "simdrive.h"
#include "ffeedbk.h"
#include "Graphics/Include/drawsgmt.h"
static float lastqBar = 0; // Note: This limits us to 1 ownship/Force feedback stick per machine
static const float tropoAlt = 36089.0F, tropoAlt2 = 65617;
extern bool g_bFFCenterFix;
/********************************************************************/
/* */
/* Routine: void AirframeClass::Atmosphere(void) */
/* */
/* Description: */
/* Calculates current state included pressure, mach, qbar and */
/* qsom for normalizing. */
/* */
/* Inputs: */
/* None */
/* */
/* Outputs: */
/* None */
/* */
/* Development History : */
/* Date Programer Description */
/*------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/********************************************************************/
void AirframeClass::Atmosphere(void)
{
float ttheta, rsigma;
float pdelta, sound;
float qpasl1, oper, pa, qc;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
sound = (float)sqrt(ttheta) * AASL;
rho = rsigma * RHOASL;
pa = pdelta * PASL;
if (IsSet(Trimming))
{
if (mach > 3.0)
//vt = CalcMach(mach, pdelta) * sound;
vt = mach * KNOTS_TO_FTPSEC;
else
vt = mach * sound;
}
/*----------------------------*/
/* calculate dynamic pressure */
/*----------------------------*/
mach = vt / ((float)sqrt(ttheta) * AASL);//ME123 CALCULATE A TRUE MACH...NOT JUST VT/SPEEDOFSOUND
if (fabs(vt) > 1.0F)
{
qbar = 0.5F * rho * vt * vt;
/*-------------------------------*/
/* calculate calibrated airspeed */
/*-------------------------------*/
if (mach <= 1.0F)
qc = ((float)pow((1.0F + 0.2F * mach * mach), 3.5F) - 1.0F) * pa;
else
qc = ((166.9F * mach * mach) / (float)(pow((7.0F - 1.0F / (mach * mach)), 2.5F)) - 1.0F) * pa;
qpasl1 = qc / PASL + 1.0F;
vcas = 1479.12F * (float)sqrt(pow(qpasl1, 0.285714F) - 1.0F);
if (qc > 1889.64F)
{
oper = qpasl1 * (float)pow((7.0F - AASLK * AASLK / (vcas * vcas)), 2.5F);
if (oper < 0.0F) oper = 0.1F;
vcas = 51.1987F * (float)sqrt(oper);
}
/*------------------------*/
/* normalizing parameters */
/*------------------------*/
qsom = qbar * area / mass;
qovt = qbar / vt;
}
else
{
vcas = max(vt * FTPSEC_TO_KNOTS, 0.001F);
qsom = 0.1F;
qovt = 0.1F;
qbar = 0.001F;
mach = 0.001F;
}
//Wombat778 12-02-2003 Removed
/*
if (platform == SimDriver.GetPlayerEntity())
{
if (g_bFFCenterFix) JoystickPlayEffect (JoyAutoCenter, 20000); //Wombat778 11-26-2003 Changed method of FFCenterfix. Added because of some reports that centering cuts out after an effect is played
{
if (qbar < 250)
{
if (fabs (qbar - lastqBar) > 5.0F)
{
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, FloatToInt32((qbar/250.0F * 0.5F + 0.5F) * 10000.0F));
//lastqBar = qbar; // JB 010301 FF would cut out < 250
}
lastqBar = qbar; // JB 010301 FF would cut out < 250
}
else
{
if (fabs (qbar - lastqBar) > 5.0F)
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, 10000);
lastqBar = qbar;
}
}
}*/
//Wombat778 12-02-2003 redid this section to be tighter. Also, this should fix centering properly. g_bFFCenterFix now means that a constant instead of variable FF force is used
if (platform == SimDriver.GetPlayerAircraft())
{
if ((fabs(qbar - lastqBar) > 5.0F) or not lastqBar)
{
if ((qbar > 250) or g_bFFCenterFix)
{
JoystickPlayEffect(JoyAutoCenter, 10000);
}
else
{
JoystickPlayEffect(JoyAutoCenter, FloatToInt32((qbar / 250.0F * 0.5F + 0.5F) * 10000.0F));
}
lastqBar = qbar;
}
}
}
float AirframeClass::CalcTASfromCAS(float cas)
{
float ttheta, rsigma;
float sound, pdelta, desMach;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
desMach = CalcMach(cas, pdelta);
sound = (float)sqrt(ttheta) * AASL;
return desMach * sound * 3600.0F / 6080.0F;
}
float AirframeClass::CalcMach(float GetKias, float press_ratio)
{
float a0 = 661.4785F;
float kiasa, qcp0, qcpa;
float u, fu, fpu;
kiasa = GetKias / a0;
qcp0 = (float)pow((1.0 + 0.2 * kiasa * kiasa), 3.5) - 1.0F;
if (kiasa >= 1.0)
qcp0 = 166.921F * (float)pow(kiasa, 7.0F) / (float)pow((7.0F * kiasa * kiasa - 1.0F), 2.5F) - 1.0F;
qcpa = qcp0 / press_ratio;
if (qcpa >= 0.892929F)
{
u = 2.0F;
do
{
fu = 166.921F * (float)pow(u, 7.0F) / (float)pow((7.0F * u * u - 1.0F), 2.5F) - (1.0F + qcpa);
fpu = 7.0F * 166.921F * (float)pow(u, 6.0F) * (2.0F * u * u - 1.0F) / (float)pow((7.0F * u * u - 1.0F), 3.5F);
u -= fu / fpu;
}
while (fabs(fu) > 0.001F);
return (u);
}
else
{
return ((float)sqrt((pow((qcpa + 1.0F), (1.0F / 3.5F)) - 1.0F) / 0.2F));
}
}
float AirframeClass::CalcPressureRatio(float alt, float* ttheta, float* rsigma)
{
/*-----------------------------------------------*/
/* calculate temperature ratio and density ratio */
/*-----------------------------------------------*/
if (alt <= tropoAlt)
{
*ttheta = 1.0F - 0.000006875F * alt;
*rsigma = (float)pow(*ttheta, 4.255876F);
}
else if (alt < tropoAlt2)
{
*ttheta = 0.751865F;
*rsigma = 0.297076F * (float)exp(0.00004806 * (tropoAlt - alt));
}
else
{
*ttheta = 0.682457f + alt / 945374.0f;
*rsigma = (float)pow(0.978261 + alt / 659515.0, -35.16319);
}
return (*ttheta) * (*rsigma);
}
// sort of atmospheric
float AirframeClass::EngineSmokeFactor()
{
switch (auxaeroData->engineSmokes)
{
default:
return 2;
case 1: // vortex
case 0: // nothing
return 1;
case 2: // light smoke
return 2;
case 3:
return 4;
}
}
int AirframeClass::EngineTrail()
{
switch (auxaeroData->engineSmokes)
{
case 0: // nothing
return -1;
case 1: // vortex
return TRAIL_VORTEX;
case 2: // light smoke
return TRAIL_SMOKE;
case 3:
return TRAIL_DARKSMOKE;
default:
/*if (auxaeroData->engineSmokes > 3 and auxaeroData->engineSmokes - 3 < TRAIL_MAX)
return auxaeroData->engineSmokes - 3;*/
if (auxaeroData->engineSmokes > 3)
return auxaeroData->engineSmokes;//Cobra Allow for more engine trails
else return -1;
}
}
| 35.479452 | 207 | 0.415444 | Terebinth |
c815d1e6895510162db703d82cf0f2cf848efa33 | 3,661 | cpp | C++ | Worms/src/InGame/Entity/World/World.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | 3 | 2020-03-05T06:56:51.000Z | 2020-03-12T09:36:20.000Z | Worms/src/InGame/Entity/World/World.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | 2 | 2020-03-05T15:40:28.000Z | 2020-03-11T16:04:44.000Z | Worms/src/InGame/Entity/World/World.cpp | GearEngine/GearEngine | fa5ed49ca6289a215799a7b84ece1241eb33bd36 | [
"Apache-2.0"
] | null | null | null | #include "wmpch.h"
#include "World.h"
namespace InGame {
float World::s_LimitTurnTime = 0;
int World::s_LimitSuddenDeathTurn = 0;
int World::s_CurrentTurn = 0;
World::World(const InitiateData& initData)
{
s_LimitSuddenDeathTurn = initData.LimitSuddenDeathTurn;
s_LimitTurnTime = initData.LimitTurnTime;
s_CurrentTurn = 0;
//Create Entity
m_ID = Gear::EntitySystem::CreateEntity(true, "World");
//Attach Component
Gear::EntitySystem::AttachComponent(m_ID, {
Gear::ComponentID::FSM, Gear::ComponentID::Status, Gear::ComponentID::Timer,
Gear::ComponentID::LateDrawer
});
//Set Component specific
Gear::EntitySystem::SetFSM(m_ID, {
{ WorldState::InGameStart, new InGemeStartHandler }, { WorldState::OnStart, new WorldOnStartHandler },
{ WorldState::OnPrepareRun, new WorldOnPrepareRunHandler }, { WorldState::OnRunning, new WorldOnRunningHandler},
{ WorldState::OnQuitWindow, new WorldOnQuitWindowHandler}, {WorldState::OnWaiting, new WorldOnWaitingHandler },
{ WorldState::OnGameVictory, new WorldOnVictoryHandler }, { WorldState::OnGameDraw, new WorldOnDrawHandler },
{WorldState::OnGameEnd, new WorldOnGameEndHandler }
});
Gear::EntitySystem::GetFSM(m_ID)->SetCurrentState(WorldState::InGameStart);
Gear::EntitySystem::SetStatus(m_ID, {
{ WorldInfo::CurrentWormName, std::string("") }, { WorldInfo::CurrentWormID, -1},
{ WorldInfo::DyeInfo, std::stack<int>()},
{ WorldInfo::CurrnetTeam, std::string("") }, { WorldInfo::CurrentTeamColor, TeamColor::Blue },
{ WorldInfo::TeamInfo, initData.Teams }, { WorldInfo::TeamInfoBlink, false }
});
Gear::EntitySystem::SetStatusHanlder(m_ID, {
{ WorldStatusHandleType::DisplayWaitingCount, Gear::CreateRef<WorldDisplayWaitingCountHandler>() },
{ WorldStatusHandleType::DisplayTeamInfo, Gear::CreateRef<WorldDisplayTeamInfoHandler>() },
{ WorldStatusHandleType::DisplayMassage, Gear::CreateRef<WorldDisplayMasageHandler>() },
});
auto status = Gear::EntitySystem::GetStatus(m_ID);
status->PushNeedHandleData(WorldStatusHandleType::DisplayTeamInfo,
Gear::Status::StatHandleData(WorldTeamInfoDenoteData(Gear::TextureStorage::GetTexture2D("WormNameBorder"))));
auto lateDrawer = Gear::EntitySystem::GetLateDrawer(m_ID);
glm::mat4 fogTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(glm::mat4(1.0f), glm::vec3(1000.0f, 1000.0f, 1.0f));
lateDrawer->UpLoadDrawStuff("Fog", Gear::LateDrawer::QuardStuff(fogTranslate, glm::vec4(0.0f, 0.0f, 0.001f, 1.0f)));
//Subscpribe EventChannel
//Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::World);
Gear::EventSystem::RegisterEventHandler(m_ID, EventChannel::World, Gear::CreateRef<WorldEventHandler>());
bgms.push_back("ingame-01-generic");
bgms.push_back("ingame-02-cavern");
bgms.push_back("ingame-03-jungle");
bgms.push_back("ingame-04-battlezone");
bgms.push_back("ingame-05-forest");
bgms.push_back("ingame-06-weird-alien-plan");
bgms.push_back("ingame-07-outerspace");
bgms.push_back("ingame-08-desert");
bgms.push_back("ingame-09-hell");
bgms.push_back("ingame-10-mech-workshop");
bgms.push_back("ingame-11-rain&surf");
}
World::~World()
{
Gear::EventSystem::UnSubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EntitySystem::DeleteEntity(m_ID);
}
void World::Update(Gear::Timestep ts)
{
if (!IS_PLAYING_SOUND(WormsSound::bgm) && !IS_PLAYING_SOUND(WormsSound::Hos))
{
PLAY_SOUND_NAME(bgms[Gear::Util::GetRndInt(11)], WormsSound::bgm);
Gear::SoundSystem::Get()->SetVolue(WormsSound::bgm, 0.5f);
}
}
} | 40.677778 | 153 | 0.734772 | GearEngine |
c81825bda8ba08b264adf5b80f6e9a3c5fe6a9d4 | 8,739 | cpp | C++ | src/mfx/pi/nzbl/FilterBank.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/nzbl/FilterBank.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | src/mfx/pi/nzbl/FilterBank.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | null | null | null | /*****************************************************************************
FilterBank.cpp
Author: Laurent de Soras, 2017
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/def.h"
#include "mfx/dsp/iir/DesignEq2p.h"
#include "mfx/dsp/iir/TransSZBilin.h"
#include "mfx/dsp/mix/Fpu.h"
#include "mfx/pi/nzbl/FilterBank.h"
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mfx
{
namespace pi
{
namespace nzbl
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
// Does not compute the latency if latency < 0 as input
void FilterBank::reset (double sample_freq, int max_buf_len, double &latency)
{
assert (sample_freq > 0);
assert (max_buf_len > 0);
fstb::unused (max_buf_len);
const bool lat_flag = (latency >= 0);
latency = 0;
_sample_freq = float ( sample_freq);
_inv_fs = float (1 / sample_freq);
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.set_sample_freq (sample_freq);
// Computes the envelope times.
// For the lowest band, we use 30 Hz as reference to make sure that the
// lowest frequencies are not distorded. Consequently, the gate will be
// slow to react. But low frequency rumble is generally steady (it comes
// from the power supply) therefore this is not a problem.
float f = 30;
if (band_cnt > 0)
{
f = compute_split_freq (band_cnt - 1);
}
const int mult = 16;
float t = float (mult / (2 * fstb::PI)) / f;
// Longer release helps preventing amplitude modulation on periodic
// noise bursts
const float min_at = 0.005f;
const float min_rt = 0.050f;
const float at = std::max (t, min_at);
const float rt = std::max (t, min_rt);
band._env.set_times (at, rt);
}
constexpr float k = 0.65f; // Thiele coefficient
const float alpha = float (sqrt (2 * (1 - k * k)));
static const float as [3] = { 1, alpha, 1 }; // Shared poles
static const float bls [_nbr_stages] [3] = { { 1, 0, 0 }, { 1, 0, k } };
static const float bhs [_nbr_stages] [3] = { { 0, 0, 1 }, { k, 0, 1 } };
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
const float f0 = compute_split_freq (split_cnt);
const float kf =
mfx::dsp::iir::TransSZBilin::compute_k_approx (f0 * _inv_fs);
for (int stage = 0; stage < _nbr_stages; ++stage)
{
float bz [3];
float az [3];
// LP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bls [stage], as, kf
);
split._lpf [stage].set_z_eq (bz, az);
split._fix [stage].set_z_eq (bz, az);
// HP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bhs [stage], as, kf
);
split._hpf [stage].set_z_eq (bz, az);
// Evaluates the group delay
if (lat_flag)
{
// Base frequency for latency evaluation. Hz
constexpr double f_lat = 700;
// Uses the HPs or LPs depending on the tested frequency
if (f0 < f_lat)
{
split._hpf [stage].get_z_eq (bz, az);
}
else
{
split._lpf [stage].get_z_eq (bz, az);
}
az [0] = 1;
const double gd = mfx::dsp::iir::DesignEq2p::compute_group_delay (
bz, az, sample_freq, f_lat
);
latency += gd;
}
}
}
clear_buffers ();
}
// thr is a linear value
void FilterBank::set_threshold (int band_idx, float thr)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (thr >= 0);
_band_arr [band_idx]._thr = thr;
}
// Can work in-place
void FilterBank::process_block (float dst_ptr [], const float src_ptr [], int nbr_spl)
{
assert (_sample_freq > 0);
assert (dst_ptr != nullptr);
assert (src_ptr != nullptr);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
// Splits the signal in several bands
for (int split_idx = 0; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
// The lower part goes to the current band, and the higher part
// propagates to the next band
float * lo_ptr = _band_arr [split_idx ]._buf.data ();
float * hi_ptr = _band_arr [split_idx + 1]._buf.data ();
split._hpf [0].process_block (hi_ptr, src_ptr, nbr_spl);
split._hpf [1].process_block (hi_ptr, hi_ptr, nbr_spl);
split._lpf [0].process_block (lo_ptr, src_ptr, nbr_spl);
split._lpf [1].process_block (lo_ptr, lo_ptr, nbr_spl);
// Next bands will be filtered in-place.
src_ptr = hi_ptr;
}
// Band processing
// Divides the current block in almost equal sub-blocks, fitting in
// the maximum processing length.
const int nbr_sub_blocks = (nbr_spl + _dspl_rate - 1) >> _dspl_rate_l2;
const int sub_block_len = (nbr_spl + nbr_sub_blocks - 1) / nbr_sub_blocks;
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
process_band (band_cnt, nbr_spl, sub_block_len);
}
// Band merging
for (int split_idx = 1; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
float * prv_ptr = _band_arr [split_idx - 1]._buf.data ();
float * cur_ptr = _band_arr [split_idx ]._buf.data ();
split._fix [0].process_block (prv_ptr, prv_ptr, nbr_spl);
split._fix [1].process_block (prv_ptr, prv_ptr, nbr_spl);
mfx::dsp::mix::Fpu::mix_1_1 (cur_ptr, prv_ptr, nbr_spl);
}
// The last two bands don't need compensation processing
mfx::dsp::mix::Fpu::copy_2_1 (
dst_ptr,
_band_arr [_nbr_bands - 2]._buf.data (),
_band_arr [_nbr_bands - 1]._buf.data (),
nbr_spl
);
}
void FilterBank::clear_buffers ()
{
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
for (int stage = 0; stage < _nbr_stages; ++stage)
{
split._lpf [stage].clear_buffers ();
split._hpf [stage].clear_buffers ();
split._fix [stage].clear_buffers ();
}
}
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.clear_buffers ();
}
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*
Other possible formula for the gain shape:
x = (limit (env / thr, 1, _thr_hi_rel) - 1) / (_thr_hi_rel - 1)
g = 0.5 * ((1 - (1 - x) ^ 8) ^ 2 + (1 - (1 - x) ^ 3) ^ 2)
No div, but 1 / thr must be precalculated too
*/
void FilterBank::process_band (int band_idx, int nbr_spl, int sub_block_len)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
assert (sub_block_len > 0);
assert (sub_block_len <= nbr_spl);
Band & band = _band_arr [band_idx];
if (band._thr >= 1e-9f)
{
float * buf_ptr = band._buf.data ();
const float thr = band._thr;
int block_pos = 0;
do
{
float * buf2_ptr = buf_ptr + block_pos;
const int block_len = std::min (nbr_spl - block_pos, sub_block_len);
const float blen_inv = fstb::rcp_uint <float> (block_len);
// Downsamples input^2 by averaging
float sum = 0;
for (int pos = 0; pos < block_len; ++pos)
{
const auto x = buf2_ptr [pos];
sum += x * x;
}
const float avg = sum * blen_inv;
const float e2 = band._env.analyse_block_raw_cst (avg, block_len);
const float env = sqrtf (e2);
// g0 = thr / max (env, thr)
const float g0 = thr / std::max (env, thr);
// gain = (1 - max ((_thr_hi_rel * g0 - 1) / (_thr_hi_rel - 1), 0)) ^ 4
float g = (_thr_hi_rel * g0 - 1) * _mul_thr_hi;
g = fstb::ipowpc <4> (1 - std::max (g, 0.f));
// Volume
mfx::dsp::mix::Fpu::scale_1_vlr (buf2_ptr, block_len, band._g_old, g);
// Next sub-block
band._g_old = g;
block_pos += block_len;
}
while (block_pos < nbr_spl);
}
}
constexpr float FilterBank::compute_split_freq (int split_idx)
{
return float (125 << split_idx);
}
} // namespace nzbl
} // namespace pi
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 26.164671 | 86 | 0.594347 | mikelange49 |
c81a8400836f894b503597b48b8c795fc7afccd0 | 36,032 | cxx | C++ | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx | Tingchenxi/AliPhysics | 16ea676341c0d417efa849673baa54bed717cd54 | [
"BSD-3-Clause"
] | null | null | null | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx | Tingchenxi/AliPhysics | 16ea676341c0d417efa849673baa54bed717cd54 | [
"BSD-3-Clause"
] | null | null | null | PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx | Tingchenxi/AliPhysics | 16ea676341c0d417efa849673baa54bed717cd54 | [
"BSD-3-Clause"
] | 1 | 2018-09-22T01:09:25.000Z | 2018-09-22T01:09:25.000Z | /*
***************************************************************************
*
* $Id$
*
*
***************************************************************************
*
*
*
*
***************************************************************************
*
* $Log$
* Revision 1.3 2007/05/22 09:01:42 akisiel
* Add the possibiloity to save cut settings in the ROOT file
*
* Revision 1.2 2007/05/21 10:38:25 akisiel
* More coding rule conformance
*
* Revision 1.1 2007/05/16 10:25:06 akisiel
* Making the directory structure of AliFemtoUser flat. All files go into one common directory
*
* Revision 1.4 2007/05/03 09:46:10 akisiel
* Fixing Effective C++ warnings
*
* Revision 1.3 2007/04/27 07:25:59 akisiel
* Make revisions needed for compilation from the main AliRoot tree
*
* Revision 1.1.1.1 2007/04/25 15:38:41 panos
* Importing the HBT code dir
*
* Revision 1.4 2007-04-03 16:00:08 mchojnacki
* Changes to iprove memory managing
*
* Revision 1.3 2007/03/13 15:30:03 mchojnacki
* adding reader for simulated data
*
* Revision 1.2 2007/03/08 14:58:03 mchojnacki
* adding some alice stuff
*
* Revision 1.1.1.1 2007/03/07 10:14:49 mchojnacki
* First version on CVS
*
**************************************************************************/
#include "AliFemtoESDTrackCut.h"
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoESDTrackCut);
/// \endcond
#endif
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
AliFemtoESDTrackCut::AliFemtoESDTrackCut():
fCharge(0), // takes both charges 0
fLabel(false),
fStatus(0),
fPIDMethod(knSigma),
fNsigmaTPCTOF(kFALSE),
fNsigmaTPConly(kFALSE),
fNsigma(3.),
fminTPCclsF(0),
fminTPCncls(0),
fminITScls(0),
fMaxITSchiNdof(1000.0),
fMaxTPCchiNdof(1000.0),
fMaxSigmaToVertex(1000.0),
fNTracksPassed(0),
fNTracksFailed(0),
fRemoveKinks(kFALSE),
fRemoveITSFake(kFALSE),
fMostProbable(0),
fMaxImpactXY(1000.0),
fMinImpactXY(-1000.0),
fMaxImpactZ(1000.0),
fMaxImpactXYPtOff(1000.0),
fMaxImpactXYPtNrm(1000.0),
fMaxImpactXYPtPow(1000.0),
fMinPforTOFpid(0.0),
fMaxPforTOFpid(10000.0),
fMinPforTPCpid(0.0),
fMaxPforTPCpid(10000.0),
fMinPforITSpid(0.0),
fMaxPforITSpid(10000.0),
fElectronRejection(0)
{
// Default constructor
fPt[0]=0.0; fPt[1] = 100.0;//100
fRapidity[0]=-2; fRapidity[1]=2;//-2 2
fEta[0]=-2; fEta[1]=2;//-2 2
// all Probabilities range from [-1.0, 2.0]
fPidProbElectron[0] = fPidProbPion[0] = fPidProbKaon[0] = fPidProbProton[0] = fPidProbMuon[0]=-1.0;
fPidProbElectron[1] = fPidProbPion[1] = fPidProbKaon[1] = fPidProbProton[1] = fPidProbMuon[1]=2.0;
for (Int_t i = 0; i < 3; i++)
fCutClusterRequirementITS[i] = AliESDtrackCuts::kOff;
}
//------------------------------
AliFemtoESDTrackCut::~AliFemtoESDTrackCut()
{
/* noop */
}
//------------------------------
bool AliFemtoESDTrackCut::Pass(const AliFemtoTrack* track)
{
//cout<<"AliFemtoESDTrackCut::Pass"<<endl;
// test the particle and return
// true if it meets all the criteria
// false if it doesn't meet at least one of the criteria
float tMost[5];
if (fStatus && (track->Flags() & fStatus) != fStatus) {
return false;
}
if (fRemoveKinks && (track->KinkIndex(0) || track->KinkIndex(1) || track->KinkIndex(2))) {
return false;
}
if (fRemoveITSFake && track->ITSncls() < 0) {
return false;
}
if (fminTPCclsF > track->TPCnclsF()) {
return false;
}
if (fminTPCncls > track->TPCncls()) {
return false;
}
if (fminITScls > track->ITSncls()) {
return false;
}
if (fMaxImpactXY < TMath::Abs(track->ImpactD())) {
return false;
}
if (fMinImpactXY > TMath::Abs(track->ImpactD())) {
return false;
}
if (fMaxImpactZ < TMath::Abs(track->ImpactZ())) {
return false;
}
if (fMaxSigmaToVertex < track->SigmaToVertex()) {
return false;
}
if (track->ITSncls() > 0 && (track->ITSchi2() / track->ITSncls()) > fMaxITSchiNdof) {
return false;
}
if (track->TPCncls() > 0 && (track->TPCchi2() / track->TPCncls()) > fMaxTPCchiNdof) {
return false;
}
// ITS cluster requirenments
for (Int_t i = 0; i < 3; i++) {
if (!CheckITSClusterRequirement(fCutClusterRequirementITS[i], track->HasPointOnITSLayer(i * 2), track->HasPointOnITSLayer(i*2+1))) {
return false;
}
}
if (fLabel) {
if (track->Label() < 0) {
fNTracksFailed++;
return false;
}
}
if (fCharge != 0 && (track->Charge() != fCharge)) {
fNTracksFailed++;
return false;
}
Bool_t tTPCPidIn = (track->Flags() & AliFemtoTrack::kTPCpid) > 0;
Bool_t tITSPidIn = (track->Flags() & AliFemtoTrack::kITSpid) > 0;
Bool_t tTOFPidIn = (track->Flags() & AliFemtoTrack::kTOFpid) > 0;
const double momentum = track->P().Mag();
if (fMinPforTOFpid > 0
&& fMinPforTOFpid < momentum && momentum < fMaxPforTOFpid
&& !tTOFPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforTPCpid > 0
&& fMinPforTPCpid < momentum && momentum < fMaxPforTPCpid
&& !tTPCPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforITSpid > 0
&& fMinPforITSpid < momentum && momentum < fMaxPforITSpid
&& !tITSPidIn) {
fNTracksFailed++;
return false;
}
float tEnergy = ::sqrt(track->P().Mag2() + fMass * fMass);
float tRapidity = 0;
if (tEnergy-track->P().z() != 0 && (tEnergy + track->P().z()) / (tEnergy-track->P().z()) > 0)
tRapidity = 0.5 * ::log((tEnergy + track->P().z())/(tEnergy-track->P().z()));
float tPt = track->P().Perp();
float tEta = track->P().PseudoRapidity();
if (fMaxImpactXYPtOff < 999.0) {
if ((fMaxImpactXYPtOff + fMaxImpactXYPtNrm*TMath::Power(tPt, fMaxImpactXYPtPow)) < TMath::Abs(track->ImpactD())) {
fNTracksFailed++;
return false;
}
}
if ((tRapidity < fRapidity[0]) || (tRapidity > fRapidity[1])) {
fNTracksFailed++;
return false;
}
if ((tEta < fEta[0]) || (tEta > fEta[1])) {
fNTracksFailed++;
return false;
}
if ((tPt < fPt[0]) || (tPt > fPt[1])) {
fNTracksFailed++;
return false;
}
// cout << "Track has pids: "
// << track->PidProbElectron() << " "
// << track->PidProbMuon() << " "
// << track->PidProbPion() << " "
// << track->PidProbKaon() << " "
// << track->PidProbProton() << " "
// << track->PidProbElectron()+track->PidProbMuon()+track->PidProbPion()+track->PidProbKaon()+track->PidProbProton() << endl;
if ((track->PidProbElectron() < fPidProbElectron[0]) || (track->PidProbElectron() > fPidProbElectron[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbPion() < fPidProbPion[0]) || (track->PidProbPion() > fPidProbPion[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbKaon() < fPidProbKaon[0]) || (track->PidProbKaon() > fPidProbKaon[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbProton() < fPidProbProton[0]) || (track->PidProbProton() > fPidProbProton[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbMuon() < fPidProbMuon[0]) || (track->PidProbMuon() > fPidProbMuon[1])) {
fNTracksFailed++;
return false;
}
//****N Sigma Method -- electron rejection****
if (fElectronRejection)
if (!IsElectron(track->NSigmaTPCE(),track->NSigmaTPCPi(),track->NSigmaTPCK(), track->NSigmaTPCP()))
return false;
if (fMostProbable) {
int imost=0;
tMost[0] = track->PidProbElectron()*PidFractionElectron(track->P().Mag());
tMost[1] = 0.0;
tMost[2] = track->PidProbPion()*PidFractionPion(track->P().Mag());
tMost[3] = track->PidProbKaon()*PidFractionKaon(track->P().Mag());
tMost[4] = track->PidProbProton()*PidFractionProton(track->P().Mag());
float ipidmax = 0.0;
//****N Sigma Method****
if (fPIDMethod==0) {
// Looking for pions
if (fMostProbable == 2) {
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi())) {
imost = 2;
}
}
else if (fMostProbable == 3) {
if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 3;
}
}
else if (fMostProbable == 4) { // proton nsigma-PID required contour adjusting (in LHC10h)
if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP())
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCPi()))
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCK()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFPi()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFK()))
// && IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())
) {
imost = 4;
}
}
else if (fMostProbable == 13) {
if (IsDeuteronNSigma(track->P().Mag(),track->MassTOF(), fNsigmaMass, track->NSigmaTPCD(), track->NSigmaTOFD()))
imost = 13;
if ((track->P().Mag() < 1) &&!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
}
else if (fMostProbable == 14) {
if (IsTritonNSigma(track->P().Mag(), track->NSigmaTPCT(), track->NSigmaTOFT())){
imost = 14;
}
}
else if (fMostProbable == 15) {
if ( IsHe3NSigma(track->P().Mag(), track->NSigmaTPCH(), track->NSigmaTOFH())
)
imost = 15;
}
else if (fMostProbable == 16) {
if ( IsAlphaNSigma(track->P().Mag(), track->NSigmaTPCA(), track->NSigmaTOFA())
)
imost = 16;
}
else if (fMostProbable == 5) { // no-protons
if ( !IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 5;
}
else if (fMostProbable == 6) { //pions OR kaons OR protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 6;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 6;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 6;
}
else if (fMostProbable == 7) { // pions OR kaons OR protons OR electrons or or or
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 7;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 7;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 7;
else if (TMath::Abs(track->NSigmaTPCE())<3)
imost = 7;
}
else if (fMostProbable == 8) { // TOF matching
if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 8;
}
}
else if (fMostProbable == 9) { // Other: no kaons, no pions, no protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = -1;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = -1;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = -1;
else if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 9;
}
}
if (fMostProbable == 10) {//cut on Nsigma in pT not p
if (IsPionNSigma(track->Pt(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 10;
}
else if (fMostProbable == 11) {//cut on Nsigma in pT not p
if (IsKaonNSigma(track->Pt(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 11;
}
}
else if (fMostProbable == 12) { //cut on Nsigma in pT not p
if ( IsProtonNSigma(track->Pt(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 12;
}
}
//****Contour Method****
if (fPIDMethod==1) {
for (int ip=0; ip<5; ip++) {
if (tMost[ip] > ipidmax) {
ipidmax = tMost[ip];
imost = ip;
}
}
// Looking for pions
if (fMostProbable == 2) {
if (imost == 2) {
// Using the TPC to reject non-pions
if (!(IsPionTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
}
if (0) {
// Using the TOF to reject non-pions
if (track->P().Mag() < 0.6) {
if (tTOFPidIn)
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
if (tTOFPidIn) {
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
imost = 0;
}
}
}
}
}
// Looking for kaons
else if (fMostProbable == 3) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.6) {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 3;
}
if (1) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (1) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
// }
}
// Looking for protons
else if (fMostProbable == 4) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.8) {
if (!(IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else imost = 4;
if (0) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (0) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
}
/**********************************/
else if (fMostProbable == 13) {
// if (imost == 3) {
// Using the TPC to reject non-deuterons
if (track->P().Mag() < 1) {
if (!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 13;
}
}
}
/*************************************/
}
if (imost != fMostProbable) {
return false;
}
}
//fan
//cout<<"****** Go Through the cut ******"<<endl;
// cout<<fLabel<<" Label="<<track->Label()<<endl;
// cout<<fCharge<<" Charge="<<track->Charge()<<endl;
// cout<<fPt[0]<<" < Pt ="<<Pt<<" <"<<fPt[1]<<endl;
//cout<<fRapidity[0]<<" < Rapidity ="<<tRapidity<<" <"<<fRapidity[1]<<endl;
//cout<<fPidProbElectron[0]<<" < e="<<track->PidProbElectron()<<" <"<<fPidProbElectron[1]<<endl;
//cout<<fPidProbPion[0]<<" < pi="<<track->PidProbPion()<<" <"<<fPidProbPion[1]<<endl;
//cout<<fPidProbKaon[0]<<" < k="<<track->PidProbKaon()<<" <"<<fPidProbKaon[1]<<endl;
//cout<<fPidProbProton[0]<<" < p="<<track->PidProbProton()<<" <"<<fPidProbProton[1]<<endl;
//cout<<fPidProbMuon[0]<<" < mi="<<track->PidProbMuon()<<" <"<<fPidProbMuon[1]<<endl;
fNTracksPassed++ ;
return true;
}
//------------------------------
AliFemtoString AliFemtoESDTrackCut::Report()
{
// Prepare report from the execution
string tStemp;
char tCtemp[100];
snprintf(tCtemp , 100, "Particle mass:\t%E\n",this->Mass());
tStemp=tCtemp;
snprintf(tCtemp , 100, "Particle charge:\t%d\n",fCharge);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle pT:\t%E - %E\n",fPt[0],fPt[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle rapidity:\t%E - %E\n",fRapidity[0],fRapidity[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle eta:\t%E - %E\n",fEta[0],fEta[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Number of tracks which passed:\t%ld Number which failed:\t%ld\n",fNTracksPassed,fNTracksFailed);
tStemp += tCtemp;
AliFemtoString returnThis = tStemp;
return returnThis;
}
TList *AliFemtoESDTrackCut::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
char buf[200];
snprintf(buf, 200, "AliFemtoESDTrackCut.mass=%f", this->Mass());
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.charge=%i", fCharge);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.minimum=%f", fPidProbPion[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.maximum=%f", fPidProbPion[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.minimum=%f", fPidProbKaon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.maximum=%f", fPidProbKaon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.minimum=%f", fPidProbProton[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.maximum=%f", fPidProbProton[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.minimum=%f", fPidProbElectron[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.maximum=%f", fPidProbElectron[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.minimum=%f", fPidProbMuon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.maximum=%f", fPidProbMuon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumtpcclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumitsclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.minimum=%f", fPt[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.maximum=%f", fPt[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.minimum=%f", fRapidity[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.maximum=%f", fRapidity[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.removekinks=%i", fRemoveKinks);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxitschindof=%f", fMaxITSchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxtpcchindof=%f", fMaxTPCchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxsigmatovertex=%f", fMaxSigmaToVertex);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactxy=%f", fMaxImpactXY);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactz=%f", fMaxImpactZ);
tListSetttings->AddLast(new TObjString(buf));
if (fMostProbable) {
if (fMostProbable == 2)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Pion");
if (fMostProbable == 3)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Kaon");
if (fMostProbable == 4)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Proton");
tListSetttings->AddLast(new TObjString(buf));
}
return tListSetttings;
}
void AliFemtoESDTrackCut::SetRemoveKinks(const bool& flag)
{
fRemoveKinks = flag;
}
void AliFemtoESDTrackCut::SetRemoveITSFake(const bool& flag)
{
fRemoveITSFake = flag;
}
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
float AliFemtoESDTrackCut::PidFractionElectron(float mom) const
{
// Provide a parameterized fraction of electrons dependent on momentum
if (mom<0.13)
return (7.594129e-02
-5.535827e-01*0.13
+1.728591e+00*0.13*0.13
-2.827893e+00*0.13*0.13*0.13
+2.503553e+00*0.13*0.13*0.13*0.13
-1.125965e+00*0.13*0.13*0.13*0.13*0.13
+2.009036e-01*0.13*0.13*0.13*0.13*0.13*0.13);
if (mom>1.8)
return (7.594129e-02
-5.535827e-01*1.8
+1.728591e+00*1.8*1.8
-2.827893e+00*1.8*1.8*1.8
+2.503553e+00*1.8*1.8*1.8*1.8
-1.125965e+00*1.8*1.8*1.8*1.8*1.8
+2.009036e-01*1.8*1.8*1.8*1.8*1.8*1.8);
return (7.594129e-02
-5.535827e-01*mom
+1.728591e+00*mom*mom
-2.827893e+00*mom*mom*mom
+2.503553e+00*mom*mom*mom*mom
-1.125965e+00*mom*mom*mom*mom*mom
+2.009036e-01*mom*mom*mom*mom*mom*mom);
}
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
float AliFemtoESDTrackCut::PidFractionPion(float mom) const
{
// Provide a parameterized fraction of pions dependent on momentum
if (mom<0.13)
return ( 1.063457e+00
-4.222208e-01*0.13
+1.042004e-01*0.0169);
if (mom>2.0)
return ( 1.063457e+00
-4.222208e-01*2.0
+1.042004e-01*4.0);
return ( 1.063457e+00
-4.222208e-01*mom
+1.042004e-01*mom*mom);
}
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
float AliFemtoESDTrackCut::PidFractionKaon(float mom) const
{
// Provide a parameterized fraction of kaons dependent on momentum
if (mom<0.18)
return (-7.289406e-02
+4.415666e-01*0.18
-2.996790e-01*0.18*0.18
+6.704652e-02*0.18*0.18*0.18);
if (mom>2.0)
return (-7.289406e-02
+4.415666e-01*2.0
-2.996790e-01*2.0*2.0
+6.704652e-02*2.0*2.0*2.0);
return (-7.289406e-02
+4.415666e-01*mom
-2.996790e-01*mom*mom
+6.704652e-02*mom*mom*mom);
}
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
float AliFemtoESDTrackCut::PidFractionProton(float mom) const
{
// Provide a parameterized fraction of protons dependent on momentum
if (mom<0.26) return 0.0;
if (mom>2.0)
return (-3.730200e-02
+1.163684e-01*2.0
+8.354116e-02*2.0*2.0
-4.608098e-02*2.0*2.0*2.0);
return (-3.730200e-02
+1.163684e-01*mom
+8.354116e-02*mom*mom
-4.608098e-02*mom*mom*mom);
}
void AliFemtoESDTrackCut::SetMomRangeTOFpidIs(const float& minp, const float& maxp)
{
fMinPforTOFpid = minp;
fMaxPforTOFpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeTPCpidIs(const float& minp, const float& maxp)
{
fMinPforTPCpid = minp;
fMaxPforTPCpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeITSpidIs(const float& minp, const float& maxp)
{
fMinPforITSpid = minp;
fMaxPforITSpid = maxp;
}
bool AliFemtoESDTrackCut::IsPionTPCdEdx(float mom, float dEdx)
{
// double a1 = -95.4545, b1 = 86.5455;
// double a2 = 0.0, b2 = 56.0;
double a1 = -343.75, b1 = 168.125;
double a2 = 0.0, b2 = 65.0;
if (mom < 0.32) {
if (dEdx < a1*mom+b1) return true;
}
if (dEdx < a2*mom+b2) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdx(float mom, float dEdx)
{
// double a1 = -547.0; double b1 = 297.0;
// double a2 = -125.0; double b2 = 145.0;
// double a3 = -420.0; double b3 = 357.0;
// double a4 = -110.0; double b4 = 171.0;
// double b5 = 72.0;
// if (mom<0.2) return false;
// if (mom<0.36) {
// if (dEdx < a1*mom+b1) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.6) {
// if (dEdx < a2*mom+b2) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.9) {
// if (dEdx > a4*mom+b4) return false;
// if (dEdx < b5) return false;
// }
// else
// return false;
// // else {
// // if (dEdx > b5) return false;
// // }
// return true;
double a1 = -268.896; double b1 = 198.669;
double a2 = -49.0012; double b2 = 88.7214;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.5) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<1.2) {
if (dEdx < a2*mom+b2) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsDeuteronTPCdEdx(float mom, float dEdx)
{
double a1 = -250.0, b1 = 400.0;
double a2 = 0.0, b2 = 30.0;
if (mom < 1) {
if (dEdx < a1*mom+b1) return false;
}
//if (dEdx < a2*mom+b2) return true;
return true;
}
bool AliFemtoESDTrackCut::IsProtonTPCdEdx(float mom, float dEdx)
{
double a1 = -1800.0; double b1 = 940.0;
double a2 = -500.0; double b2 = 420.0;
double a3 = -216.7; double b3 = 250.0;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.4) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<0.6) {
if (dEdx < a2*mom+b2) return false;
}
else if (mom<0.9) {
if (dEdx < a3*mom+b3) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsPionTOFTime(float mom, float ttof)
{
double a1 = -427.0; double b1 = 916.0;
double a2 = 327.0; double b2 = -888.0;
if (mom<0.3) return kFALSE;
if (mom>2.0) return kFALSE;
if (ttof > a1*mom+b1) return kFALSE;
if (ttof < a2*mom+b2) return kFALSE;
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -500.0;
double a2 = 000.0; double b2 = 500.0;
double a3 = 850.0; double b3 = -1503.0;
double a4 = -1637.0; double b4 = 3621.0;
if (mom<0.3) return kFALSE;
if (mom>2.06) return kFALSE;
if (mom<1.2) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<1.9) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
if (mom<2.06) {
if (ttof > a4*mom+b4) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsProtonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -915.0;
double a2 = 000.0; double b2 = 600.0;
double a3 = 572.0; double b3 = -1715.0;
if (mom<0.3) return kFALSE;
if (mom>3.0) return kFALSE;
if (mom<1.4) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<3.0) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
if (mom<0.35 && TMath::Abs(nsigmaK)<5.0) return true;
if (mom>=0.35 && mom<0.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=0.5 && mom<0.7 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTOFNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
//fan
// if (mom<1.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=1.5 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
/*
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (mom<0.5)
{
if (TMath::Abs(nsigmaTPCK)<2.0)
{
return true;
}
else
{
return false;
}
}
if (mom>=0.5)
{
if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
else
{
return false;
}
}
// if (mom>1.5 || mom<0.15) return false;
}
*/
//old
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFK, nsigmaTPCK ) < fNsigma)
return true;
}
else {
if (TMath::Abs(nsigmaTPCK) < fNsigma)
return true;
}
}
else {
if (mom<0.4)
{
if (nsigmaTOFK<-999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (mom>=0.4 && mom<=0.6)
{
if (nsigmaTOFK < -999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (nsigmaTOFK < -999.)
{
return false;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsPionNSigma(float mom, float nsigmaTPCPi, float nsigmaTOFPi)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
return TMath::Hypot( nsigmaTOFPi, nsigmaTPCPi ) < fNsigma;
}
return TMath::Abs(nsigmaTPCPi) < fNsigma;
}
if (mom < 0.65) {
if (nsigmaTOFPi < -999.) {
if (mom < 0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom<0.5 && mom>=0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom>=0.5 && TMath::Abs(nsigmaTPCPi)<2.0) return true;
else return false;
}
else if (TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<3.0) {
return true;
}
}
else if (nsigmaTOFPi < -999.) {
return false;
}
else if (mom<1.5 && TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
else if (mom>=1.5 && TMath::Abs(nsigmaTOFPi)<2.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsProtonNSigma(float mom, float nsigmaTPCP, float nsigmaTOFP)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP ) < fNsigma)
return true;
} else if (TMath::Abs(nsigmaTPCP) < fNsigma) {
return true;
}
}
else if (fNsigmaTPConly) {
if (TMath::Abs(nsigmaTPCP) < fNsigma)
return true;
}
else {
if (mom > 0.8 && mom < 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 3.0)
return true;
}
else if (mom > 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 2.0)
return true;
}
else {
if (TMath::Abs(nsigmaTPCP) < 3.0)
return true;
}
}
return false;
}
/***********************************************************************/
bool AliFemtoESDTrackCut::IsDeuteronNSigma(float mom, float massTOFPDG,float sigmaMass, float nsigmaTPCD, float nsigmaTOFD)
{
double massPDGD=1.8756;
if (fNsigmaTPCTOF) {
if (mom > 1) { //if TOF avaliable: && (nsigmaTOFD != -1000) --> always TOF
//if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if ((TMath::Hypot( nsigmaTOFD, nsigmaTPCD ) < fNsigma) && (TMath::Abs(massTOFPDG-massPDGD*massPDGD)<sigmaMass))
return true;
}
else {
if (TMath::Abs(nsigmaTPCD) < fNsigma)
return true;
}
}
return false;
}
bool AliFemtoESDTrackCut::IsTritonNSigma(float mom, float nsigmaTPCT, float nsigmaTOFT)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<2 && TMath::Abs(nsigmaTPCT)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsHe3NSigma(float mom, float nsigmaTPCH, float nsigmaTOFH)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCH)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsAlphaNSigma(float mom, float nsigmaTPCA, float nsigmaTOFA)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCA)<fNsigma) return true;
}
return false;
}
//
/*********************************************************************/
void AliFemtoESDTrackCut::SetPIDMethod(ReadPIDMethodType newMethod)
{
fPIDMethod = newMethod;
}
void AliFemtoESDTrackCut::SetNsigmaTPCTOF(Bool_t nsigma)
{
fNsigmaTPCTOF = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaTPConly(Bool_t nsigma)
{
fNsigmaTPConly = nsigma;
}
void AliFemtoESDTrackCut::SetNsigma(Double_t nsigma)
{
fNsigma = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaMass(Double_t nsigma)
{
fNsigmaMass = nsigma;
}
void AliFemtoESDTrackCut::SetClusterRequirementITS(AliESDtrackCuts::Detector det, AliESDtrackCuts::ITSClusterRequirement req)
{
fCutClusterRequirementITS[det] = req;
}
Bool_t AliFemtoESDTrackCut::CheckITSClusterRequirement(AliESDtrackCuts::ITSClusterRequirement req, Bool_t clusterL1, Bool_t clusterL2)
{
// checks if the cluster requirement is fullfilled (in this case: return kTRUE)
switch (req) {
case AliESDtrackCuts::kOff: return kTRUE;
case AliESDtrackCuts::kNone: return !clusterL1 && !clusterL2;
case AliESDtrackCuts::kAny: return clusterL1 || clusterL2;
case AliESDtrackCuts::kFirst: return clusterL1;
case AliESDtrackCuts::kOnlyFirst: return clusterL1 && !clusterL2;
case AliESDtrackCuts::kSecond: return clusterL2;
case AliESDtrackCuts::kOnlySecond: return clusterL2 && !clusterL1;
case AliESDtrackCuts::kBoth: return clusterL1 && clusterL2;
}
return kFALSE;
}
bool AliFemtoESDTrackCut::IsElectron(float nsigmaTPCE, float nsigmaTPCPi,float nsigmaTPCK, float nsigmaTPCP)
{
if (TMath::Abs(nsigmaTPCE)<3 && TMath::Abs(nsigmaTPCPi)>3 && TMath::Abs(nsigmaTPCK)>3 && TMath::Abs(nsigmaTPCP)>3)
return false;
else
return true;
}
| 29.437908 | 136 | 0.578264 | Tingchenxi |
c81d408903f8057f36faf3dace43172b0bced3b4 | 1,253 | cpp | C++ | MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* SignObjectImplementation.cpp
*
* Created on: Nov 20, 2010
* Author: crush
*/
#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h"
#include "server/zone/objects/building/BuildingObject.h"
int SignObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
switch (selectedID) {
case 20: //Read Sign
sendSignNameTo(player);
break;
default:
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
return 0;
}
void SignObjectImplementation::sendSignNameTo(CreatureObject* player) {
ManagedReference<SuiMessageBox*> suiBox = new SuiMessageBox(player, SuiWindowType::NONE);
suiBox->setPromptTitle("@sui:swg"); //Star Wars Galaxies
suiBox->setPromptText(getDisplayedName());
player->sendMessage(suiBox->generateMessage());
}
void SignObjectImplementation::initializeChildObject(SceneObject* controllerObject) {
if (controllerObject == nullptr)
return;
attachedObject = controllerObject;
if (controllerObject->isBuildingObject())
(cast<BuildingObject*>(controllerObject))->setSignObject(_this.getReferenceUnsafeStaticCast());
}
| 29.139535 | 97 | 0.782123 | V-Fib |
c81f7ec1089411b0df479216d500b675ca1b6ff4 | 399 | cpp | C++ | docs/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.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/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | // Performs the given work function on the data element of the tree and
// on each child.
template<class Function>
void tree::for_all(Function& action)
{
// Perform the action on each child.
parallel_for_each(begin(_children), end(_children), [&](tree& child) {
child.for_all(action);
});
// Perform the action on this node.
action(*this);
} | 30.692308 | 76 | 0.626566 | bobbrow |
c821041336f42b23b4131c3abccb6bced4e64d39 | 7,363 | cpp | C++ | winston/external/asio/src/examples/cpp11/operations/composed_3.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | 172 | 2018-10-31T13:47:10.000Z | 2022-02-21T12:08:20.000Z | winston/external/asio/src/examples/cpp11/operations/composed_3.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | 51 | 2018-11-01T12:46:25.000Z | 2021-12-14T15:16:15.000Z | winston/external/asio/src/examples/cpp11/operations/composed_3.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | 72 | 2018-10-31T13:50:02.000Z | 2022-03-14T09:10:35.000Z | //
// composed_3.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <asio/bind_executor.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. The asynchronous operation
// requirements are met by delegating responsibility to the underlying
// operation.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, const char* message) const
{
// The async_write operation has a completion handler signature of:
//
// void(std::error_code error, std::size n)
//
// This differs from our operation's signature in that it is also passed
// the number of bytes transferred as an argument of type std::size_t. We
// will adapt our completion handler to async_write's completion handler
// signature by using std::bind, which drops the additional argument.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the asio::bind_executor function.
asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(
completion_handler), std::placeholders::_1)));
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of CompletionToken type and the completion handler's signature. When the
// completion token is a simple callback, the return type is always void.
// In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would be also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>.
-> typename asio::async_result<
typename std::decay<CompletionToken>::type,
void(std::error_code)>::return_type
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
// Get the result of the operation.
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_future();
}
| 38.150259 | 80 | 0.682602 | danie1kr |
c82275b68ae3cee945f5187d4807aef8b105eea5 | 10,641 | cc | C++ | src/msgpass/GlobalSynchronizeDevThr.cc | cea-hpc/pattern4gpu | bf606708b6a8bad1041369814e8443b7f1dedcef | [
"Apache-2.0"
] | 1 | 2022-03-23T10:33:16.000Z | 2022-03-23T10:33:16.000Z | src/msgpass/GlobalSynchronizeDevThr.cc | cea-hpc/pattern4gpu | bf606708b6a8bad1041369814e8443b7f1dedcef | [
"Apache-2.0"
] | null | null | null | src/msgpass/GlobalSynchronizeDevThr.cc | cea-hpc/pattern4gpu | bf606708b6a8bad1041369814e8443b7f1dedcef | [
"Apache-2.0"
] | null | null | null | #include "msgpass/VarSyncMng.h"
#include "msgpass/PackTransfer.h"
#include <arcane/IParallelMng.h>
#include <arcane/MeshVariableScalarRef.h>
#include <arcane/MeshVariableArrayRef.h>
#include <arcane/VariableBuildInfo.h>
#include <thread>
#include <mpi.h>
/*---------------------------------------------------------------------------*/
/* Equivalent à un var.synchronize() où var est une variable globale */
/* (i.e. non multi-mat) en utilisant des comms non-bloquantes dans des taches*/
/*---------------------------------------------------------------------------*/
template<typename MeshVariableRefT>
void VarSyncMng::globalSynchronizeDevThr(MeshVariableRefT var)
{
if (m_nb_nei==0) {
return;
}
using ItemType = typename MeshVariableRefT::ItemType;
using DataType = typename MeshVariableRefT::DataType;
SyncItems<ItemType>* sync_items = getSyncItems<ItemType>();
auto nb_owned_item_idx_pn = sync_items->nbOwnedItemIdxPn();
auto nb_ghost_item_idx_pn = sync_items->nbGhostItemIdxPn();
auto owned_item_idx_pn = sync_items->ownedItemIdxPn();
auto ghost_item_idx_pn = sync_items->ghostItemIdxPn();
// Pour un ItemType donné, combien de DataType sont utilisés ? => degree
Integer degree = get_var_degree(var);
m_sync_buffers->resetBuf();
// On prévoit une taille max du buffer qui va contenir tous les messages
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_owned_item_idx_pn, degree);
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_ghost_item_idx_pn, degree);
// Le buffer de tous les messages est réalloué si pas assez de place
m_sync_buffers->allocIfNeeded();
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur l'HOTE (_h et LM_HostMem)
auto buf_snd_h = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 0);
auto buf_rcv_h = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 0);
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur le DEVICE (_d et LM_DevMem)
auto buf_snd_d = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 1);
auto buf_rcv_d = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 1);
#define USE_MPI_REQUEST
#ifdef USE_MPI_REQUEST
//#warning "USE_MPI_REQUEST"
using RequestType = MPI_Request;
#else
using RequestType = Parallel::Request;
#endif
// L'échange proprement dit des valeurs de var
Integer tag=1000;
UniqueArray<RequestType> requests(2*m_nb_nei);
IntegerUniqueArray msg_types(2*m_nb_nei); // nature des messages
// On amorce les réceptions
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
// On amorce la réception
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // le buffer de réception pour inei
#ifdef USE_MPI_REQUEST
MPI_Irecv(byte_buf_rcv_h.data(), byte_buf_rcv_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[inei]));
#else
requests[inei] = m_pm->recv(byte_buf_rcv_h, rank_nei, /*blocking=*/false);
#endif
msg_types[inei] = inei+1; // >0 pour la réception
}
// La tâche à effectuer pour un voisin
auto lbd_sender = [&](Integer inei, RunQueue& queue) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
auto byte_buf_snd_d = buf_snd_d.byteBuf(inei); // le buffer d'envoi pour inei sur le DEVICE
auto byte_buf_snd_h = buf_snd_h.byteBuf(inei); // le buffer d'envoi pour inei sur l'HOTE
// "byte_buf_snd_d <= var"
async_pack_var2buf(owned_item_idx_pn[inei], var, byte_buf_snd_d, queue);
// transfert buf_snd_d[inei] => buf_snd_h[inei]
async_transfer(byte_buf_snd_h, byte_buf_snd_d, queue);
// attendre que la copie sur l'hôte soit terminée pour envoyer les messages
queue.barrier();
// On amorce les envois
#ifdef USE_MPI_REQUEST
MPI_Isend(byte_buf_snd_h.data(), byte_buf_snd_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[m_nb_nei+inei]));
#else
requests[m_nb_nei+inei] = m_pm->send(byte_buf_snd_h, rank_nei, /*blocking=*/false);
#endif
msg_types[m_nb_nei+inei] = -inei-1; // <0 pour l'envoi
};
//#define USE_THR_SENDER
#ifdef USE_THR_SENDER
#warning "USE_THR_SENDER"
UniqueArray<std::thread*> thr_sender(m_nb_nei);
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
thr_sender[inei] =
new std::thread(lbd_sender, inei, std::ref(m_neigh_queues->queue(inei)));
}
// On attend la fin de tous les threads
for(auto thr : thr_sender) {
thr->join();
delete thr;
}
#else
// On lance en SEQUENTIEL
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
lbd_sender(inei, m_neigh_queues->queue(inei));
}
#endif
// Tache qui unpack les données du buffer reçues par un voisin inei
// copie de var_dev dans buf_dev
// puis transfert buf_dev => buf_hst
auto lbd_unpacker = [&](Integer inei, RunQueue& queue) {
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // buffer des données reçues sur l'HOTE
auto byte_buf_rcv_d = buf_rcv_d.byteBuf(inei); // buffer des données reçues à transférer sur le DEVICE
// transfert buf_rcv_h[inei] => buf_rcv_d[inei]
async_transfer(byte_buf_rcv_d, byte_buf_rcv_h, queue);
// "var <= buf_rcv_d[inei]"
async_unpack_buf2var(ghost_item_idx_pn[inei], byte_buf_rcv_d, var, queue);
// attendre que les copies soient terminées sur GPU
queue.barrier();
};
UniqueArray<std::thread*> thr_unpacker;
ARCANE_ASSERT(2*m_nb_nei==requests.size(),
("Le nb de requetes n'est pas egal à 2 fois le nb de voisins"));
UniqueArray<RequestType> requests2(2*m_nb_nei);
IntegerUniqueArray msg_types2(2*m_nb_nei);
UniqueArray<bool> is_done_req(2*m_nb_nei);
#ifdef USE_MPI_REQUEST
IntegerUniqueArray array_of_indices(2*m_nb_nei);
#endif
// On utilise des vues pour éviter de réallouer en permanence des tableaux
ArrayView<RequestType> pending_requests(requests.view());
ArrayView<Integer> pending_types(msg_types.view());
ArrayView<RequestType> upd_pending_requests(requests2.view());
ArrayView<Integer> upd_pending_types(msg_types2.view());
ArrayView<RequestType> tmp_pending_requests;
ArrayView<Integer> tmp_pending_types;
Integer nb_iter_wait_some = 0;
Integer nb_pending_rcv = m_nb_nei;
while(nb_pending_rcv>0) {
Integer nb_pending_req = pending_requests.size();
// On dimenensionne is_done_requests au nb de requêtes d'avant waitSomeRequests
// et on initialise à false
ArrayView<bool> is_done_requests(is_done_req.subView(0, nb_pending_req));
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
is_done_requests[ireq]=false;
}
// Attente de quelques requetes
#ifdef USE_MPI_REQUEST
Integer nb_req_done=0;
MPI_Waitsome(pending_requests.size(), pending_requests.data(),
&nb_req_done, array_of_indices.data(), MPI_STATUSES_IGNORE);
IntegerArrayView done_indexes(array_of_indices.subView(0, nb_req_done));
#else
IntegerUniqueArray done_indexes = m_pm->waitSomeRequests(pending_requests);
#endif
for(Integer idone_req : done_indexes) {
if (pending_types[idone_req] > 0) { // >0 signifie que c'est une requête de reception
nb_pending_rcv--; // on une requete de reception en moins
// On récupère l'indice du voisin
Integer inei = pending_types[idone_req]-1;
ARCANE_ASSERT(inei>=0 && inei<m_nb_nei, ("Mauvais indice de voisin"));
// Maintenant qu'on a reçu le buffer pour le inei-ième voisin,
// on unpack les donnees dans un thread
//#define USE_THR_UNPACKER
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER"
thr_unpacker.add(
new std::thread(lbd_unpacker, inei, std::ref(m_neigh_queues->queue(inei)))
);
#else
lbd_unpacker(inei, m_neigh_queues->queue(inei));
#endif
}
is_done_requests[idone_req] = true;
}
// Il faut créer le nouveau tableau de requêtes pending dans upd_*
Integer upd_nb_pending_req=0;
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
if (!is_done_requests[ireq]) {
upd_pending_requests[upd_nb_pending_req]=pending_requests[ireq];
upd_pending_types [upd_nb_pending_req]=pending_types[ireq];
upd_nb_pending_req++;
}
}
// On échange les vues pour qu'à l'itération suivante
// pending_requests pointe vers upd_pending_types
tmp_pending_requests = upd_pending_requests.subView(0, upd_nb_pending_req);
upd_pending_requests = pending_requests;
pending_requests = tmp_pending_requests;
tmp_pending_types = upd_pending_types.subView(0, upd_nb_pending_req);
upd_pending_types = pending_types;
pending_types = tmp_pending_types;
nb_iter_wait_some++;
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", iter_wait_some=" << nb_iter_wait_some
<< ", nb_done=" << done_indexes.size();
std::cout << ostr.str() << std::endl;
#endif
}
// Ici, toutes les requetes de receptions sont forcement terminées
// (condition de la boucle while précédente)
// Mais il peut rester encore des requetes d'envoi en cours
if (pending_requests.size()) {
// Normalement, il ne reste que des requêtes d'envois
ARCANE_ASSERT(pending_requests.size()<=m_nb_nei,
("Il ne peut pas rester un nb de requetes d'envoi supérieur au nb de voisins"));
for(Integer msg_type : pending_types) {
ARCANE_ASSERT(msg_type<0,
("Un message d'envoi doit avoir un type négatif ce qui n'est pas le cas"));
}
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", WaitAll pending_requests.size()=" << pending_requests.size();
std::cout << ostr.str() << std::endl;
#endif
#ifdef USE_MPI_REQUEST
MPI_Waitall(pending_requests.size(), pending_requests.data(), MPI_STATUSES_IGNORE);
#else
m_pm->waitAllRequests(pending_requests);
#endif
}
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER : join"
// On attend la fin de tous les threads unpackers
for(auto thr : thr_unpacker) {
thr->join();
delete thr;
}
#endif
}
/*---------------------------------------------------------------------------*/
/* INSTANCIATIONS STATIQUES */
/*---------------------------------------------------------------------------*/
#define INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(__MeshVariableRefT__) \
template void VarSyncMng::globalSynchronizeDevThr(__MeshVariableRefT__ var)
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableCellReal);
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableNodeReal3);
| 36.56701 | 106 | 0.698807 | cea-hpc |
c825e7f6b100bab1168fd79d5f5f1a856dc46b24 | 2,232 | cpp | C++ | OVFP426/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp | ACaesuraIsStillMusic/Open-Virtual-Film-Project | f4cfb901da32d8101b7635aa5caed3fc075d6dd7 | [
"Unlicense",
"MIT"
] | 15 | 2020-12-11T17:00:02.000Z | 2022-03-08T04:43:56.000Z | OVFP425/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp | ACaesuraIsStillMusic/Open-Virtual-Film-Project | f4cfb901da32d8101b7635aa5caed3fc075d6dd7 | [
"Unlicense",
"MIT"
] | null | null | null | OVFP425/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp | ACaesuraIsStillMusic/Open-Virtual-Film-Project | f4cfb901da32d8101b7635aa5caed3fc075d6dd7 | [
"Unlicense",
"MIT"
] | 2 | 2020-12-10T22:54:05.000Z | 2021-07-22T10:25:22.000Z | // Copyright Dan Corrigan 2020 All Rights Reserved.
#include "OVFPPluginStyle.h"
#include "OVFPPlugin.h"
#include "Framework/Application/SlateApplication.h"
#include "Styling/SlateStyleRegistry.h"
#include "Slate/SlateGameResources.h"
#include "Interfaces/IPluginManager.h"
TSharedPtr< FSlateStyleSet > FOVFPPluginStyle::StyleInstance = NULL;
void FOVFPPluginStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FOVFPPluginStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FOVFPPluginStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("OVFPPluginStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FOVFPPluginStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("OVFPPluginStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("OVFPPlugin")->GetBaseDir() / TEXT("Resources"));
Style->Set("OVFPPlugin.PluginAction", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FOVFPPluginStyle::ReloadTextures()
{
if (FSlateApplication::IsInitialized())
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
}
const ISlateStyle& FOVFPPluginStyle::Get()
{
return *StyleInstance;
}
| 31 | 129 | 0.765681 | ACaesuraIsStillMusic |
c826867517354d4f1c4da53834c26f2709b20b43 | 1,615 | cpp | C++ | Sample14_1/app/src/main/cpp/bndev/ThreadTask.cpp | luopan007/Vulkan_Develpment_Samples | 1be40631e3b2d44aae7140f0ef17c5643a86545e | [
"Unlicense"
] | 5 | 2020-11-20T00:06:30.000Z | 2021-12-07T11:39:17.000Z | Sample15_2/app/src/main/cpp/bndev/ThreadTask.cpp | luopan007/Vulkan_Develpment_Samples | 1be40631e3b2d44aae7140f0ef17c5643a86545e | [
"Unlicense"
] | null | null | null | Sample15_2/app/src/main/cpp/bndev/ThreadTask.cpp | luopan007/Vulkan_Develpment_Samples | 1be40631e3b2d44aae7140f0ef17c5643a86545e | [
"Unlicense"
] | 7 | 2021-01-01T10:54:58.000Z | 2022-01-13T02:21:54.000Z | #include "ThreadTask.h"
#include "MyVulkanManager.h"
#include "ShaderQueueSuit_CommonTexLight.h"
void ThreadTask::doTask()
{
MyVulkanManager::init_vulkan_instance();
MyVulkanManager::enumerate_vulkan_phy_devices();
MyVulkanManager::create_vulkan_devices();
MyVulkanManager::create_vulkan_CommandBuffer();
MyVulkanManager::init_queue();
MyVulkanManager::create_vulkan_swapChain();
MyVulkanManager::create_vulkan_DepthBuffer();
MyVulkanManager::create_vulkan_SelfColorBuffer();
MyVulkanManager::create_render_pass_screen();
MyVulkanManager::create_render_pass_self();
MyVulkanManager::create_frame_buffer_screen();
MyVulkanManager::create_frame_buffer_self();
MyVulkanManager::init_texture();
MyVulkanManager::createDrawableObject();
MyVulkanManager::initPipeline();
MyVulkanManager::createFence();
MyVulkanManager::initPresentInfo();
MyVulkanManager::initMatrixAndLight();
MyVulkanManager::drawObject();
MyVulkanManager::destroyPipeline();
MyVulkanManager::destroyDrawableObject();
MyVulkanManager::destroy_textures();
MyVulkanManager::destroy_vulkan_SelfColorBuffer();
MyVulkanManager::destroy_frame_buffer();
MyVulkanManager::destroy_render_pass_self();
MyVulkanManager::destroy_render_pass_screen();
MyVulkanManager::destroy_vulkan_DepthBuffer();
MyVulkanManager::destroy_vulkan_swapChain();
MyVulkanManager::destroy_vulkan_CommandBuffer();
MyVulkanManager::destroy_vulkan_devices();
MyVulkanManager::destroy_vulkan_instance();
}
ThreadTask::ThreadTask()
{
}
ThreadTask:: ~ThreadTask()
{
} | 37.55814 | 54 | 0.778947 | luopan007 |
c82831f16eef38e0e073485241d80aa03272da99 | 78 | cxx | C++ | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 3 | 2019-11-19T09:47:25.000Z | 2022-02-24T00:32:31.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 1 | 2019-03-18T14:19:49.000Z | 2020-01-11T13:54:33.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 1 | 2022-02-24T00:32:36.000Z | 2022-02-24T00:32:36.000Z | #include <vnl/vnl_matrix_fixed.hxx>
VNL_MATRIX_FIXED_INSTANTIATE(double,2,8);
| 26 | 41 | 0.833333 | rdsouza10 |
c829ca837e3e275e946ac03ba0341d1c7314fdec | 919 | cpp | C++ | ch16/ex16.5/main.cpp | regconfi/Cpp-Primer | 6e59f24f4c7f3be4f679b7d29084d9d859a463d9 | [
"CC0-1.0"
] | 46 | 2015-07-07T11:13:12.000Z | 2022-03-27T10:20:54.000Z | ch16/ex16.5/main.cpp | lafener/Cpp-Primer | 8cf1568f2d27622bce2d41493158f58527e5072f | [
"CC0-1.0"
] | 11 | 2015-03-10T12:52:06.000Z | 2015-04-20T12:24:00.000Z | ch16/ex16.5/main.cpp | lafener/Cpp-Primer | 8cf1568f2d27622bce2d41493158f58527e5072f | [
"CC0-1.0"
] | 65 | 2015-07-01T14:15:48.000Z | 2021-04-10T08:44:19.000Z | /***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* 13 Oct 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!
#include <iostream>
#include <string>
template<typename Arr>
void print(const Arr& a)
{
for(const auto& elem : a)
std::cout << elem << std::endl;
}
int main()
{
std::string p[] = {"ssss","aaa","ssssss"};
char c[] = {'a','b','c','d'};
int i[] = {1};
print(i);
print(c);
print(p);
std::cout << "\nexit normally\n";
return 0;
}
| 24.184211 | 77 | 0.460283 | regconfi |
c82bd1b45b8f3949576cb1a37c6c04ea1f32bbb7 | 21,098 | cpp | C++ | src/vm/contractimpl.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 6 | 2017-09-22T06:55:45.000Z | 2021-07-02T07:07:08.000Z | src/vm/contractimpl.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 3 | 2018-01-03T00:57:25.000Z | 2018-10-05T16:17:52.000Z | src/vm/contractimpl.cpp | danmosemsft/coreclr | 04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2 | [
"MIT"
] | 2 | 2017-06-04T15:47:12.000Z | 2020-03-16T07:01:47.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: contractimpl.cpp
//
// Keeps track of contract implementations, used primarily in stub dispatch.
//
//
//
// ============================================================================
#include "common.h" // Precompiled header
#include "contractimpl.h"
#include "virtualcallstub.h"
#include "decodemd.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif
#if defined(_DEBUG)
DummyGlobalContract ___contract;
#endif
#ifdef LOGGING
//----------------------------------------------------------------------------
StubDispatchStats g_sdStats = {0};
#endif // LOGGING
#ifndef DACCESS_COMPILE
//----------------------------------------------------------------------------
MethodDesc * DispatchSlot::GetMethodDesc()
{
WRAPPER_NO_CONTRACT;
if (IsNull())
return NULL;
else
return MethodTable::GetMethodDescForSlotAddress(GetTarget());
}
//------------------------------------------------------------------------
void TypeIDMap::Init(UINT32 idStartValue, UINT32 idIncrementValue, BOOL fUseFatTokensForUniqueness)
{
STANDARD_VM_CONTRACT;
LockOwner lock = {&m_lock, IsOwnerOfCrst};
m_idMap.Init(11, TRUE, &lock);
m_mtMap.Init(11, TRUE, &lock);
m_idProvider.Init(idStartValue, idIncrementValue);
m_entryCount = 0;
m_fUseFatIdsForUniqueness = fUseFatTokensForUniqueness;
}
#endif // !DACCESS_COMPILE
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
UINT32 TypeIDMap::LookupTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
} CONTRACTL_END;
UINT32 id = (UINT32) m_mtMap.LookupValue((UPTR)dac_cast<TADDR>(pMT), 0);
_ASSERTE(!m_fUseFatIdsForUniqueness || !pMT->RequiresFatDispatchTokens() || (DispatchToken::RequiresDispatchTokenFat(id, 0)));
return id;
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
PTR_MethodTable TypeIDMap::LookupType(UINT32 id)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
PRECONDITION(id <= TypeIDProvider::MAX_TYPE_ID);
} CONTRACTL_END;
if (!m_idProvider.OwnsID(id))
return NULL;
UPTR ret = m_idMap.LookupValue((UPTR)id, 0);
if (ret == static_cast<UPTR>(INVALIDENTRY))
return NULL;
ret <<= 1;
return PTR_MethodTable(ret);
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, assigns the ID and
// returns the new ID.
UINT32 TypeIDMap::GetTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// Lookup the value.
UINT32 id = LookupTypeID(pMT);
#ifndef DACCESS_COMPILE
// If the value is not in the table, take the lock, get a new ID, and
// insert the new pair.
if (id == TypeIDProvider::INVALID_TYPE_ID)
{
// Take the lock
CrstHolder lh(&m_lock);
// Check to see if someone beat us to the punch
id = LookupTypeID(pMT);
if (id != TypeIDProvider::INVALID_TYPE_ID)
{
return id;
}
// Get the next ID
if (m_fUseFatIdsForUniqueness && pMT->RequiresFatDispatchTokens())
{
id = GetNextFatID();
}
else
{
id = GetNextID();
}
CONSISTENCY_CHECK(id <= TypeIDProvider::MAX_TYPE_ID);
// Insert the pair, with lookups in both directions
CONSISTENCY_CHECK((((UPTR)pMT) & 0x1) == 0);
m_idMap.InsertValue((UPTR)id, (UPTR)pMT >> 1);
m_mtMap.InsertValue((UPTR)pMT, (UPTR)id);
m_entryCount++;
CONSISTENCY_CHECK(GetThread()->GetDomain()->IsCompilationDomain() ||
(LookupType(id) == pMT));
}
#else // DACCESS_COMPILE
if (id == TypeIDProvider::INVALID_TYPE_ID)
DacError(E_FAIL);
#endif // DACCESS_COMPILE
// Return the ID for this type.
return id;
} // TypeIDMap::GetTypeID
#ifndef DACCESS_COMPILE
//------------------------------------------------------------------------
// If TRUE, it points to a matching entry.
// If FALSE, it is at the insertion point.
BOOL
DispatchMapBuilder::Find(
DispatchMapTypeID typeID,
UINT32 slotNumber,
Iterator & it)
{
WRAPPER_NO_CONTRACT;
for (; it.IsValid(); it.Next())
{
if (typeID == it.GetTypeID())
{
if (slotNumber == it.GetSlotNumber())
{
return TRUE;
}
if (slotNumber < it.GetSlotNumber())
{
return FALSE;
}
}
else if (typeID < it.GetTypeID())
{
return FALSE;
}
}
return FALSE;
} // DispatchMapBuilder::Find
//------------------------------------------------------------------------
// If TRUE, contains such an entry.
// If FALSE, no such entry exists.
BOOL DispatchMapBuilder::Contains(DispatchMapTypeID typeID, UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
Iterator it(this);
return Find(typeID, slotNumber, it);
}
//------------------------------------------------------------------------
void
DispatchMapBuilder::InsertMDMapping(
DispatchMapTypeID typeID,
UINT32 slotNumber,
MethodDesc * pMDTarget,
BOOL fIsMethodImpl)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
// Find a matching entry, or move the iterator to insertion point.
Iterator it(this);
BOOL fFound = Find(typeID, slotNumber, it);
// If we find an existing matching entry, fail.
if (fFound)
{
_ASSERTE(false);
COMPlusThrowHR(COR_E_TYPELOAD);
}
// Create and initialize a new entry
DispatchMapBuilderNode * pNew = NewEntry();
pNew->Init(typeID, slotNumber, pMDTarget);
if (fIsMethodImpl)
pNew->SetIsMethodImpl();
// Insert at the point of the iterator
pNew->m_next = NULL;
if (it.IsValid())
{
pNew->m_next = it.EntryNode();
}
*(it.EntryNodePtr()) = pNew;
m_cEntries++;
} // DispatchMapBuilder::InsertMDMapping
//--------------------------------------------------------------------
UINT32 DispatchMapBuilder::Iterator::GetTargetSlot()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
if (GetTargetMD() != NULL)
{
return EntryNode()->m_pMDTarget->GetSlot();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------
DispatchMapBuilderNode * DispatchMapBuilder::NewEntry()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM());
} CONTRACTL_END;
return new (m_pAllocator) DispatchMapBuilderNode();
}
//----------------------------------------------------------------------------
DispatchMap::DispatchMap(
BYTE * pMap,
UINT32 cbMap)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(CheckPointer(pMap));
memcpyNoGCRefs(m_rgMap, pMap, cbMap);
}
//----------------------------------------------------------------------------
// This mapping consists of a list of the following entries.
// <type, [<slot, (index | slot)>]>. This is implemented as
//
// flag: 0 if the map is a part of a JIT'd module
// 1 if the map is a part of an NGEN'd module.
// count: number of types that have entries
// {
// type: The ID current type being mapped
// count: Number of subentries for the current type
// bool: Whether or not the target slot/index values can be negative.
// {
// slot: The slot of type that is being mapped
// index/slot: This is a slot mapping for the current type. The implementation search is
// modified to <this, slot> and the search is restarted from the initial type.
// }
// }
void
DispatchMap::CreateEncodedMapping(
MethodTable * pMT,
DispatchMapBuilder * pMapBuilder,
StackingAllocator * pAllocator,
BYTE ** ppbMap,
UINT32 * pcbMap)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pMapBuilder));
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(ppbMap));
PRECONDITION(CheckPointer(pcbMap));
} CONTRACTL_END;
/////////////////////////////////
// Phase 1 - gather entry counts
UINT32 cNumTypes = 0;
UINT32 cNumEntries = 0;
{
DispatchMapBuilder::Iterator it(pMapBuilder);
// We don't want to record overrides or methodImpls in the dispatch map since
// we have vtables to track this information.
it.SkipThisTypeEntries();
if (it.IsValid())
{
DispatchMapTypeID curType = DispatchMapTypeID::FromUINT32(INVALIDENTRY);
do
{
cNumEntries++;
if (curType != it.GetTypeID())
{
cNumTypes++;
curType = it.GetTypeID();
}
}
while (it.Next());
}
}
/////////////////////////////////
// Phase 2 - allocate space
// Now that we have stats about the overall absolute maximum map size, we can allocate
// some working space for createing the encoded map in.
// Sizes: flag==UINT32, typeID==UINT32, slot==UINT32, index/slot==UINT32
S_UINT32 scbMap = S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumTypes) * S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumEntries) * S_UINT32((sizeof(UINT32) + sizeof(UINT32)));
BYTE * pbMap = (BYTE *)pAllocator->Alloc(scbMap);
/////////////////////////////////
// Phase 3 - encode the map
{
// Create the encoder over the newly allocated memory
Encoder e(pbMap);
// Encode the count of type entries
e.Encode((unsigned)cNumTypes);
// Start encoding the map
DispatchMapBuilder::Iterator it(pMapBuilder);
it.SkipThisTypeEntries();
INT32 curType = -1;
INT32 prevType;
INT32 deltaType;
while (it.IsValid())
{
// Encode the type ID
prevType = curType;
curType = (INT32)it.GetTypeID().ToUINT32();
deltaType = curType - prevType - ENCODING_TYPE_DELTA;
CONSISTENCY_CHECK(0 <= deltaType);
e.Encode((unsigned)deltaType);
// Variables for slot delta calculations
BOOL fHasNegatives = FALSE;
// Source slot
INT32 curSlot = -1;
INT32 prevSlot = -1;
// Target slot for virtual mappings
INT32 curTargetSlot = -1;
INT32 prevTargetSlot = -1;
// Count and encode the number of sub entries for this type
UINT32 cSubEntries = 0;
DispatchMapBuilder::Iterator subIt(it);
do
{
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)subIt.GetTargetSlot();
INT32 deltaTargetSlot = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (deltaTargetSlot < 0)
{
fHasNegatives = TRUE;
}
cSubEntries++;
}
while (subIt.Next() && (subIt.GetTypeID().ToUINT32() == (UINT32)curType));
e.Encode((unsigned)cSubEntries);
e.Encode((unsigned)fHasNegatives);
e.ContainsNegatives(fHasNegatives);
// Iterate each subentry and encode it
curTargetSlot = -1;
do
{
// Only virtual targets can be mapped virtually.
CONSISTENCY_CHECK((it.GetTargetMD() == NULL) ||
it.GetTargetMD()->IsVirtual());
// Encode the slot
prevSlot = curSlot;
curSlot = it.GetSlotNumber();
INT32 deltaSlot = curSlot - prevSlot - ENCODING_SLOT_DELTA;
CONSISTENCY_CHECK(0 <= deltaSlot);
e.Encode((unsigned)deltaSlot);
// Calculate and encode the target slot delta
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)it.GetTargetSlot();
INT32 delta = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (fHasNegatives)
{
e.EncodeSigned((signed)delta);
}
else
{
CONSISTENCY_CHECK(0 <= delta);
e.Encode((unsigned)delta);
}
}
while (it.Next() && it.GetTypeID().ToUINT32() == (UINT32)curType);
} // while (it.IsValid())
// Finish and finalize the map, and set the out params.
e.Done();
*pcbMap = e.Contents(ppbMap);
}
#ifdef _DEBUG
// Let's verify the mapping
{
EncodedMapIterator itMap(*ppbMap);
DispatchMapBuilder::Iterator itBuilder(pMapBuilder);
itBuilder.SkipThisTypeEntries();
while (itMap.IsValid())
{
CONSISTENCY_CHECK(itBuilder.IsValid());
DispatchMapEntry * pEntryMap = itMap.Entry();
CONSISTENCY_CHECK(pEntryMap->GetTypeID() == itBuilder.GetTypeID());
CONSISTENCY_CHECK(pEntryMap->GetTargetSlotNumber() == itBuilder.GetTargetSlot());
itMap.Next();
itBuilder.Next();
}
CONSISTENCY_CHECK(!itBuilder.IsValid());
}
#endif //_DEBUG
} // DispatchMap::CreateEncodedMapping
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
//------------------------------------------------------------------------
void DispatchMap::Save(DataImage * image)
{
STANDARD_VM_CONTRACT;
CONSISTENCY_CHECK(!image->IsStored(this));
UINT32 cbMap = GetMapSize();
UINT32 cbObj = GetObjectSize(cbMap);
image->StoreInternedStructure(
this,
cbObj,
DataImage::ITEM_DISPATCH_MAP,
sizeof(void *));
#ifdef LOGGING
g_sdStats.m_cNGENDispatchMap++;
g_sdStats.m_cbNGENDispatchMap += cbObj;
#endif //LOGGING
}
//------------------------------------------------------------------------
void DispatchMap::Fixup(DataImage *image)
{
STANDARD_VM_CONTRACT;
}
#endif //FEATURE_NATIVE_IMAGE_GENERATION
#endif //!DACCESS_COMPILE
//------------------------------------------------------------------------
UINT32 DispatchMap::GetMapSize()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
EncodedMapIterator it(this);
for (; it.IsValid(); it.Next())
{
}
CONSISTENCY_CHECK(dac_cast<TADDR>(it.m_d.End()) > PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
return (UINT32)(dac_cast<TADDR>(it.m_d.End()) - PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
}
#ifdef DACCESS_COMPILE
//------------------------------------------------------------------------
void DispatchMap::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
EMEM_OUT(("MEM: %p DispatchMap\n", dac_cast<TADDR>(this)));
DacEnumMemoryRegion(PTR_HOST_MEMBER_TADDR(DispatchMap,this,m_rgMap), GetMapSize());
}
#endif // DACCESS_COMPILE
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Invalidate()
{
LIMITED_METHOD_DAC_CONTRACT;
m_numTypes = 0;
m_curType = 0;
m_numEntries = 0;
m_curEntry = 0;
}
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Init(PTR_BYTE pbMap)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pbMap, NULL_OK));
SUPPORTS_DAC;
} CONTRACTL_END;
if (pbMap != NULL)
{
// Initialize the map decoder
m_d.Init(pbMap);
m_numTypes = m_d.Next();
m_curType = -1;
m_curTypeId = DispatchMapTypeID::FromUINT32(static_cast<UINT32>(-1));
m_numEntries = 0;
m_curEntry = -1;
m_curTargetSlot = static_cast<UINT32>(-1);
}
else
{
Invalidate();
}
Next();
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(MethodTable * pMT)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (pMT->HasDispatchMap())
{
DispatchMap * pMap = pMT->GetDispatchMap();
Init(PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap, m_rgMap)));
}
else
{
Init(NULL);
}
}
//--------------------------------------------------------------------
// This should be used only when a dispatch map needs to be used
// separately from its MethodTable.
DispatchMap::EncodedMapIterator::EncodedMapIterator(DispatchMap * pMap)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
PTR_BYTE pBytes = NULL;
if (pMap != NULL)
{
pBytes = PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap,m_rgMap));
}
Init(pBytes);
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(PTR_BYTE pbMap)
{
LIMITED_METHOD_CONTRACT;
Init(pbMap);
}
//--------------------------------------------------------------------
BOOL DispatchMap::EncodedMapIterator::Next()
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (!IsValid())
{
return FALSE;
}
m_curEntry++;
if (m_curEntry == m_numEntries)
{
m_curType++;
if (m_curType == m_numTypes)
{
return FALSE;
}
m_curTypeId =
DispatchMapTypeID::FromUINT32(
(UINT32)((INT32)m_curTypeId.ToUINT32() +
(INT32)m_d.Next() +
ENCODING_TYPE_DELTA));
_ASSERTE(!m_curTypeId.IsThisClass());
m_curEntry = 0;
m_numEntries = m_d.Next();
m_fCurTypeHasNegativeEntries = (BOOL)m_d.Next();
m_curSlot = static_cast<UINT32>(-1);
m_curTargetSlot = static_cast<UINT32>(-1);
CONSISTENCY_CHECK(m_numEntries != 0);
}
// Now gather enough info to initialize the dispatch entry
// Get the source slot
m_curSlot = (UINT32)((INT32)m_curSlot + (INT32)m_d.Next() + ENCODING_SLOT_DELTA);
// If virtual, get the target virtual slot number
m_curTargetSlot =
(UINT32)((INT32)m_curTargetSlot +
ENCODING_TARGET_SLOT_DELTA +
(INT32)(m_fCurTypeHasNegativeEntries ? m_d.NextSigned() : m_d.Next()));
m_e.InitVirtualMapping(m_curTypeId, m_curSlot, m_curTargetSlot);
CONSISTENCY_CHECK(IsValid());
return TRUE;
} // DispatchMap::EncodedMapIterator::Next
//--------------------------------------------------------------------
DispatchMap::Iterator::Iterator(MethodTable * pMT)
: m_mapIt(pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::IsValid()
{
WRAPPER_NO_CONTRACT;
return m_mapIt.IsValid();
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::Next()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(!m_mapIt.Entry()->GetTypeID().IsThisClass());
if (m_mapIt.IsValid())
{
m_mapIt.Next();
CONSISTENCY_CHECK(!m_mapIt.IsValid() || !m_mapIt.Entry()->GetTypeID().IsThisClass());
}
return IsValid();
}
//--------------------------------------------------------------------
DispatchMapEntry * DispatchMap::Iterator::Entry()
{
/*
CONTRACTL {
INSTANCE_CHECK;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(IsValid());
} CONTRACTL_END;
*/
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
DispatchMapEntry * pEntry = NULL;
if (m_mapIt.IsValid())
{
pEntry = m_mapIt.Entry();
}
CONSISTENCY_CHECK(CheckPointer(pEntry));
return pEntry;
}
| 29.46648 | 130 | 0.545218 | danmosemsft |
c82c23f20625dffba354f9c06231149dcfc6c66d | 1,236 | cpp | C++ | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "token.h"
#include "instructions.h"
CInstrTable::CInstrTable()
{
currInstr = 0;
}
CInstrTable::~CInstrTable()
{
}
int CInstrTable::AddInstr(char *name,int token,int numParams)
{
if(strlen(name) >= MAX_INSTR_NAME)
return -1;
InstrLookup *func = (InstrLookup*)malloc(sizeof(InstrLookup));
strcpy(func->name,name);
func->token = token;
func->numParam = numParams;
func->opList = (Operand*)malloc((sizeof(Operand)) * numParams);
instr.push_back(func);
return currInstr++;
}
void CInstrTable::SetInstrOp(int instrIndex,int opIndex,int values)
{
InstrLookup* f = instr[instrIndex];
f->opList[opIndex].type = values;
}
InstrLookup* CInstrTable::GetInstrByIndex(int index)
{
for (int i=0; i<currInstr;i++)
{
if (i == index)
return instr[i];
}
return NULL;
}
InstrLookup* CInstrTable::GetInstrByName(char *name)
{
for (int i=0; i<currInstr;i++)
{
if (strcmp(instr[i]->name, name) == 0)
return instr[i];
}
return NULL;
}
bool CInstrTable::IsValidInstr(char *name)
{
char *t;
for (int i=0; i<currInstr;i++)
{
t = instr[i]->name;
if (strcmp(t, name) == 0)
return true;
}
return false;
} | 16.263158 | 67 | 0.66343 | kpatel122 |
c82e52aa23432987d4cbbe6b0d8d793b8d94b1f2 | 388 | cpp | C++ | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | /*
* ModbusReadCoils.cpp
*
* Created on: 09.02.2016
* Author: lode
*/
#include "ModbusReadCoils.h"
namespace Modbus
{
ReadCoils2Array::ReadCoils2Array(unsigned* array, uint16_t numOfBits, TxnReturnPath* rp)
: ReadBits2Array(FunctionCode, array, numOfBits, rp)
{}
//ReadCoils2Array::~ReadCoils2Array()
//{
// // Auto-generated destructor stub
//}
} /* namespace Modbus */
| 16.869565 | 88 | 0.701031 | joluxer |
c830df2e62804911cb559d62bbc6ec3fd8f12ea9 | 1,523 | hpp | C++ | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_RUNTIME_CORE_HPP
#define KAGOME_RUNTIME_CORE_HPP
#include <outcome/outcome.hpp>
#include <vector>
#include "primitives/authority.hpp"
#include "primitives/block.hpp"
#include "primitives/block_id.hpp"
#include "primitives/common.hpp"
#include "primitives/transaction_validity.hpp"
#include "primitives/version.hpp"
namespace kagome::runtime {
/**
* Core represents mandatory part of runtime api
*/
class Core {
public:
virtual ~Core() = default;
/**
* @brief Returns the version of the runtime
* @return runtime version
*/
virtual outcome::result<primitives::Version> version(
const boost::optional<primitives::BlockHash> &block_hash) = 0;
/**
* @brief Executes the given block
* @param block block to execute
*/
virtual outcome::result<void> execute_block(
const primitives::Block &block) = 0;
/**
* @brief Initialize a block with the given header.
* @param header header used for block initialization
*/
virtual outcome::result<void> initialise_block(
const primitives::BlockHeader &header) = 0;
/**
* Get current authorities
* @return collection of authorities
*/
virtual outcome::result<std::vector<primitives::AuthorityId>> authorities(
const primitives::BlockId &block_id) = 0;
};
} // namespace kagome::runtime
#endif // KAGOME_RUNTIME_CORE_HPP
| 25.813559 | 78 | 0.682206 | iceseer |
c83288fdd7892d0a685ab3eb3de7a91456d2e06e | 22,923 | cc | C++ | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 38 | 2017-07-26T14:48:12.000Z | 2022-03-24T23:48:55.000Z | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 74 | 2017-03-15T21:07:34.000Z | 2022-03-18T07:53:11.000Z | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 43 | 2017-03-10T15:27:28.000Z | 2022-03-05T10:55:38.000Z | /*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include "../../simdebug.h"
#include "../../simconst.h"
#include "../../bauer/vehikelbauer.h"
#include "../sound_desc.h"
#include "../vehicle_desc.h"
#include "../intro_dates.h"
#include "vehicle_reader.h"
#include "../obj_node_info.h"
#include "../../network/pakset_info.h"
void vehicle_reader_t::register_obj(obj_desc_t *&data)
{
vehicle_desc_t *desc = static_cast<vehicle_desc_t *>(data);
vehicle_builder_t::register_desc(desc);
obj_for_xref(get_type(), desc->get_name(), data);
checksum_t *chk = new checksum_t();
desc->calc_checksum(chk);
pakset_info_t::append(desc->get_name(), get_type(), chk);
}
bool vehicle_reader_t::successfully_loaded() const
{
return vehicle_builder_t::successfully_loaded();
}
obj_desc_t *vehicle_reader_t::read_node(FILE *fp, obj_node_info_t &node)
{
ALLOCA(char, desc_buf, node.size);
vehicle_desc_t *desc = new vehicle_desc_t();
// Read data
fread(desc_buf, node.size, 1, fp);
char * p = desc_buf;
// old versions of PAK files have no version stamp.
// But we know, the higher most bit was always cleared.
const uint16 v = decode_uint16(p);
int version = v & 0x8000 ? v & 0x7FFF : 0;
// Whether the read file is from Simutrans-Extended
//@author: jamespetts
const bool extended = version > 0 ? v & EX_VER : false;
uint16 extended_version = 0;
if(extended)
{
// Extended version to start at 0 and increment.
version = version & EX_VER ? version & 0x3FFF : 0;
while(version > 0x100)
{
version -= 0x100;
extended_version ++;
}
extended_version -= 1;
}
way_constraints_of_vehicle_t way_constraints;
if(version == 1) {
// Versioned node, version 1
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if(version == 2) {
// Versioned node, version 2
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if (version==3 || version==4 || version==5) {
// Versioned node, version 3 with retire date
// version 4 identical, just other values for the waytype
// version 5 just uses the new scheme for data calculation
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
}
else if (version==6) {
// version 5 just 32 bit for power and 16 Bit for gear
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==7) {
// different length of cars ...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==8) {
// multiple freight images...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 6)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >=4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version==9) {
// new: fixed_cost (previously Extended only), loading_time, axle_load
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
if(extended_version == 0)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if(extended_version == 0)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 7)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >= 4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
if(extended_version >= 7)
{
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
}
else
{
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version == 10 || version == 11) {
// new: weight in kgs
desc->base_cost = decode_uint32(p);
if (extended && extended_version >= 4)
{
// Multiple classes, therefore multiple capacities.
desc->classes = decode_uint8(p);
}
else
{
desc->classes = 1;
}
// Initialise the arrays
desc->capacity = new uint16[desc->classes];
desc->comfort = new uint8[desc->classes];
for (uint32 i = 0; i < desc->classes; i++)
{
desc->capacity[i] = decode_uint16(p);
}
if (!extended)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint32(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if (!extended)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
if (extended_version >= 3)
{
desc->sound = decode_sint16(p);
}
else
{
desc->sound = decode_sint8(p);
}
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version < 7)
{
// NOTE: Extended version reset to 1 with incrementing of
// Standard version to 10.
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
if (extended && extended_version >= 5)
{
desc->basic_constraint_prev = decode_uint8(p);
}
else {
desc->can_lead_from_rear = decode_uint8(p);
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
}
for (uint32 i = 0; i < desc->classes; i++)
{
desc->comfort[i] = decode_uint8(p);
}
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if (!extended && version == 10)
{
desc->base_fixed_cost = decode_uint16(p);
}
else
{
desc->base_fixed_cost = decode_uint32(p);
}
desc->tractive_effort = decode_uint16(p);
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
if (extended && extended_version >= 5)
{
desc->basic_constraint_next = decode_uint8(p);
}
else
{
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
}
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
desc->livery_image_type = decode_uint8(p);
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
if(extended_version == 0)
{
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
else
{
desc->range = decode_uint16(p);
desc->way_wear_factor = decode_uint32(p);
}
if (extended_version > 1)
{
desc->is_tall = decode_uint8(p);
}
else
{
desc->is_tall = false;
}
if (extended && extended_version >= 5)
{
desc->mixed_load_prohibition = decode_uint8(p);
}
else
{
desc->mixed_load_prohibition = false;
}
if (extended && extended_version >= 6)
{
desc->override_way_speed = decode_uint8(p);
}
else
{
desc->override_way_speed = false;
}
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else {
if( version!=0 ) {
dbg->fatal( "vehicle_reader_t::read_node()","Do not know how to handle version=%i", version );
}
// old node, version 0
desc->wtyp = (sint8)v;
desc->capacity[0] = decode_uint16(p);
desc->base_cost = decode_uint32(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->sound = decode_sint16(p);
desc->leader_count = (sint8)decode_uint16(p);
desc->trailer_count = (sint8)decode_uint16(p);
desc->intro_date = DEFAULT_INTRO_DATE*16;
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
desc->gear = 64;
}
// correct the engine type for old vehicles
if(version<2) {
// steam eangines usually have a sound of 3
// electric engines will be overridden further down ...
desc->engine_type = (desc->sound==3) ? vehicle_desc_t::steam : vehicle_desc_t::diesel;
}
//change the vehicle type
if(version<4) {
if(desc->wtyp==4) {
desc->engine_type = vehicle_desc_t::electric;
desc->wtyp = 1;
}
// convert to new standard
static const waytype_t convert_from_old[8]={road_wt, track_wt, water_wt, air_wt, invalid_wt, monorail_wt, invalid_wt, tram_wt };
desc->wtyp = convert_from_old[desc->wtyp];
}
// before version 5 dates were based on base 12 ...
if(version<5) {
uint16 date=desc->intro_date;
desc->intro_date = (date/16)*12 + (date%16);
date=desc->retire_date;
desc->retire_date = (date/16)*12 + (date%16);
}
// before the length was always 1/8 (=half a tile)
if(version<7) {
desc->len = CARUNITS_PER_TILE/2;
}
// adjust length for different offset step sizes (which may arise in future)
desc->len *= OBJECT_OFFSET_STEPS/CARUNITS_PER_TILE;
// before version 8 vehicles could only have one freight image in each direction
if(version<8) {
desc->freight_image_type=0;
}
if(!extended)
{
// Default values for items not in the standard vehicle format.
desc->classes = 1;
desc->is_tilting = false;
desc->catering_level = 0;
desc->bidirectional = false;
desc->can_lead_from_rear = false;
desc->comfort = new uint8[1];
desc->comfort[0] = 100;
desc->overcrowded_capacity = 0;
desc->tractive_effort = 0;
switch(desc->get_waytype())
{
default:
case tram_wt:
case road_wt:
desc->min_loading_time = desc->max_loading_time = 2000;
break;
case monorail_wt:
case maglev_wt:
case narrowgauge_wt:
case track_wt:
desc->min_loading_time = desc->max_loading_time = 4000;
break;
case water_wt:
desc->min_loading_time = desc->max_loading_time = 20000;
break;
case air_wt:
desc->min_loading_time = desc->max_loading_time = 30000;
break;
}
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->upgrades = 0;
desc->base_upgrade_price = desc->base_cost;
desc->available_only_as_upgrade = false;
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
desc->livery_image_type = 0;
desc->min_loading_time_seconds = 20;
desc->max_loading_time_seconds = 60;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->range = 0;
desc->way_wear_factor = 1;
desc->is_tall = false;
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
desc->mixed_load_prohibition = false;
desc->override_way_speed = false;
}
desc->set_way_constraints(way_constraints);
if(version<9) {
desc->base_fixed_cost = 0;
desc->axle_load = desc->weight;
}
// old weights were tons
if(version<10) {
desc->weight *= 1000;
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
// Convert flag
if (version<11 || (version == 11 && extended && extended_version < 5)) {
if (desc->can_lead_from_rear == true && desc->bidirectional == false) {
desc->bidirectional = true;
}
}
if(desc->sound==LOAD_SOUND) {
uint8 len=decode_sint8(p);
char wavname[256];
wavname[len] = 0;
for(uint8 i=0; i<len; i++) {
wavname[i] = decode_sint8(p);
}
desc->sound = (sint16)sound_desc_t::get_sound_id(wavname);
DBG_MESSAGE("vehicle_reader_t::register_obj()","sound %s to %i",wavname,desc->sound);
}
else if(desc->sound>=0 && desc->sound<=MAX_OLD_SOUNDS) {
sint16 old_id = desc->sound;
desc->sound = (sint16)sound_desc_t::get_compatible_sound_id(old_id);
DBG_MESSAGE("vehicle_reader_t::register_obj()","old sound %i to %i",old_id,desc->sound);
}
desc->loaded();
DBG_DEBUG("vehicle_reader_t::read_node()",
"version=%d "
"way=%d classes=%d capacity=%d comfort=%d cost=%d topspeed=%d weight=%g axle_load=%d power=%d "
"betrieb=%d sound=%d vor=%d nach=%d "
"date=%d/%d gear=%d engine_type=%d len=%d is_tilting=%d mixed_load_prohibition=%d catering_level=%d "
"way_constraints_permissive=%d way_constraints_prohibitive%d bidirectional%d can_lead_from_rear%d coupling_constraint%d",
version,
desc->wtyp,
desc->classes,
desc->capacity[0],
desc->comfort[0],
desc->base_cost,
desc->topspeed,
desc->weight/1000.0,
desc->axle_load,
desc->power,
desc->running_cost,
desc->sound,
desc->leader_count,
desc->trailer_count,
(desc->intro_date%12)+1,
desc->intro_date/12,
desc->gear,
desc->engine_type,
desc->len,
desc->is_tilting,
desc->mixed_load_prohibition,
desc->override_way_speed,
desc->catering_level,
desc->get_way_constraints().get_permissive(),
desc->get_way_constraints().get_prohibitive(),
desc->bidirectional,
desc->basic_constraint_prev,
desc->basic_constraint_next);
return desc;
}
| 29.886571 | 130 | 0.687781 | chris-nada |
c836c9307d38132c8e2b76b00aca51eb6fd1a0bb | 22 | cpp | C++ | tests/Issue127.cpp | galorojo/cppinsights | 52ecab4ddd8e36fb99893551cf0fb8b5d58589f2 | [
"MIT"
] | 1,853 | 2018-05-13T21:49:17.000Z | 2022-03-30T10:34:45.000Z | tests/Issue127.cpp | tiandaoafei/cppinsights | af78ac299121354101a5e506dafccaac95d27a77 | [
"MIT"
] | 398 | 2018-05-15T14:48:51.000Z | 2022-03-24T12:14:33.000Z | tests/Issue127.cpp | SammyEnigma/cppinsights | c984b8e68139bbcc244c094fd2463eeced8fd997 | [
"MIT"
] | 104 | 2018-05-15T04:00:59.000Z | 2022-03-17T02:04:15.000Z | auto f = [](auto) {};
| 11 | 21 | 0.409091 | galorojo |
c83704ba0ce11494af1fa548d82c86c5c4ebde9b | 473 | cpp | C++ | src/layer.cpp | shugaa/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 16 | 2015-03-26T22:44:23.000Z | 2021-05-09T12:31:24.000Z | src/layer.cpp | pekdon/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 3 | 2018-09-01T13:03:29.000Z | 2020-11-29T09:37:31.000Z | src/layer.cpp | pekdon/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 6 | 2017-02-12T05:46:32.000Z | 2020-08-31T06:48:11.000Z | #include <string>
#include <FL/Fl.H>
#include "layer.hpp"
florb::layer::layer() :
m_name("N/A"),
m_enabled(true)
{
add_instance(this);
};
florb::layer::~layer()
{
del_instance(this);
};
const std::string& florb::layer::name() const
{
return m_name;
};
bool florb::layer::enabled() const
{
return m_enabled;
};
void florb::layer::name(const std::string &name)
{
m_name = name;
};
void florb::layer::enable(bool en)
{
m_enabled = en;
};
| 13.138889 | 48 | 0.617336 | shugaa |
c838b9c3c72a457c98bdcff04fa3c0431c9170ff | 10,361 | cpp | C++ | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "storage/persistent_index.h"
#include <gtest/gtest.h>
#include "env/env_memory.h"
#include "storage/fs/file_block_manager.h"
#include "storage/fs/fs_util.h"
#include "storage/storage_engine.h"
#include "testutil/parallel_test.h"
#include "util/coding.h"
#include "util/faststring.h"
#include "util/file_utils.h"
namespace starrocks {
PARALLEL_TEST(PersistentIndexTest, test_mutable_index) {
using Key = uint64_t;
vector<Key> keys;
vector<IndexValue> values;
int N = 1000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// insert duplicate should return error
ASSERT_FALSE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// test get
vector<IndexValue> get_values(keys.size());
KeysInfo get_not_found;
size_t get_num_found = 0;
ASSERT_TRUE(idx->get(keys.size(), keys.data(), get_values.data(), &get_not_found, &get_num_found).ok());
ASSERT_EQ(keys.size(), get_num_found);
ASSERT_EQ(get_not_found.key_idxes.size(), 0);
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
vector<Key> get2_keys;
for (int i = 0; i < N; i++) {
get2_keys.emplace_back(i * 2);
}
vector<IndexValue> get2_values(get2_keys.size());
KeysInfo get2_not_found;
size_t get2_num_found = 0;
// should only find 0,2,..N-2, not found: N,N+2, .. N*2-2
ASSERT_TRUE(
idx->get(get2_keys.size(), get2_keys.data(), get2_values.data(), &get2_not_found, &get2_num_found).ok());
ASSERT_EQ(N / 2, get2_num_found);
// test erase
vector<Key> erase_keys;
for (int i = 0; i < N + 3; i += 3) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
KeysInfo erase_not_found;
size_t erase_num_found = 0;
ASSERT_TRUE(idx->erase(erase_keys.size(), erase_keys.data(), erase_old_values.data(), &erase_not_found,
&erase_num_found)
.ok());
ASSERT_EQ(erase_num_found, (N + 2) / 3);
// N+2 not found
ASSERT_EQ(erase_not_found.key_idxes.size(), 1);
// test upsert
vector<Key> upsert_keys(N, 0);
vector<IndexValue> upsert_values(upsert_keys.size());
size_t expect_exists = 0;
size_t expect_not_found = 0;
for (int i = 0; i < N; i++) {
upsert_keys[i] = i * 2;
if (i % 3 != 0 && i * 2 < N) {
expect_exists++;
}
if (i * 2 >= N && i * 2 != N + 2) {
expect_not_found++;
}
upsert_values[i] = i * 3;
}
vector<IndexValue> upsert_old_values(upsert_keys.size());
KeysInfo upsert_not_found;
size_t upsert_num_found = 0;
ASSERT_TRUE(idx->upsert(upsert_keys.size(), upsert_keys.data(), upsert_values.data(), upsert_old_values.data(),
&upsert_not_found, &upsert_num_found)
.ok());
ASSERT_EQ(upsert_num_found, expect_exists);
ASSERT_EQ(upsert_not_found.key_idxes.size(), expect_not_found);
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_index_wal) {
Env* env = Env::Default();
const std::string kPersistentIndexDir = "./ut_dir/persistent_index_test";
const std::string kIndexFile = "./ut_dir/persistent_index_test/index.l0.0.0";
ASSERT_TRUE(env->create_dir(kPersistentIndexDir).ok());
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({kIndexFile});
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
wblock->close();
using Key = uint64_t;
EditVersion version(0, 0);
PersistentIndexMetaPB index_meta;
index_meta.set_key_size(sizeof(Key));
index_meta.set_size(0);
version.to_pb(index_meta.mutable_version());
MutableIndexMetaPB* l0_meta = index_meta.mutable_l0_meta();
IndexSnapshotMetaPB* snapshot_meta = l0_meta->mutable_snapshot();
version.to_pb(snapshot_meta->mutable_version());
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), version).ok());
ASSERT_TRUE(index.load(index_meta).ok());
// insert
vector<Key> keys;
vector<IndexValue> values;
int N = 1000000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
ASSERT_TRUE(index.prepare(EditVersion(1, 0)).ok());
ASSERT_TRUE(index.insert(100, keys.data(), values.data(), false).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
{
std::vector<IndexValue> old_values(keys.size());
ASSERT_TRUE(index.prepare(EditVersion(2, 0)).ok());
ASSERT_TRUE(index.upsert(keys.size(), keys.data(), values.data(), old_values.data()).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
}
// erase
vector<Key> erase_keys;
for (int i = 0; i < N / 2; i++) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
ASSERT_TRUE(index.prepare(EditVersion(3, 0)).ok());
ASSERT_TRUE(index.erase(erase_keys.size(), erase_keys.data(), erase_old_values.data()).ok());
// update PersistentMetaPB in memory
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
// append invalid wal
std::vector<Key> invalid_keys;
std::vector<IndexValue> invalid_values;
faststring fixed_buf;
for (int i = 0; i < N / 2; i++) {
invalid_keys.emplace_back(i);
invalid_values.emplace_back(i * 2);
}
{
const uint8_t* fkeys = reinterpret_cast<const uint8_t*>(invalid_keys.data());
for (int i = 0; i < N / 2; i++) {
fixed_buf.append(fkeys + i * sizeof(Key), sizeof(Key));
put_fixed64_le(&fixed_buf, invalid_values[i]);
}
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({"./ut_dir/persistent_index_test/index.l0.1.0"});
wblock_opts.mode = Env::MUST_EXIST;
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
ASSERT_TRUE(wblock->append(fixed_buf).ok());
wblock->close();
}
// rebuild mutableindex according PersistentIndexMetaPB
PersistentIndex new_index(kPersistentIndexDir);
ASSERT_TRUE(new_index.create(sizeof(Key), EditVersion(3, 0)).ok());
//ASSERT_TRUE(new_index.load(index_meta).ok());
Status st = new_index.load(index_meta);
if (!st.ok()) {
LOG(WARNING) << "load failed, status is " << st.to_string();
ASSERT_TRUE(false);
}
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(new_index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < N / 2; i++) {
ASSERT_EQ(NullIndexValue, get_values[i]);
}
for (int i = N / 2; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
// upsert key/value to new_index
{
vector<IndexValue> old_values(invalid_keys.size());
ASSERT_TRUE(new_index.prepare(EditVersion(4, 0)).ok());
ASSERT_TRUE(new_index.upsert(invalid_keys.size(), invalid_keys.data(), invalid_values.data(), old_values.data())
.ok());
ASSERT_TRUE(new_index.commit(&index_meta).ok());
ASSERT_TRUE(new_index.on_commited().ok());
}
// rebuild mutableindex according to PersistentIndexMetaPB
{
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), EditVersion(4, 0)).ok());
ASSERT_TRUE(index.load(index_meta).ok());
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
}
ASSERT_TRUE(FileUtils::remove_all(kPersistentIndexDir).ok());
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_flush_to_immutable) {
using Key = uint64_t;
int N = 200000;
vector<Key> keys(N);
vector<IndexValue> values(N);
for (int i = 0; i < N; i++) {
keys[i] = i;
values[i] = i * 2;
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
ASSERT_TRUE(idx->flush_to_immutable_index(".", EditVersion(1, 1)).ok());
std::unique_ptr<fs::ReadableBlock> rb;
auto block_mgr = fs::fs_util::block_manager();
ASSERT_TRUE(block_mgr->open_block("./index.l1.1.1", &rb).ok());
auto st_load = ImmutableIndex::load(std::move(rb));
if (!st_load.ok()) {
LOG(WARNING) << st_load.status();
}
ASSERT_TRUE(st_load.ok());
auto& idx_loaded = st_load.value();
KeysInfo keys_info;
for (size_t i = 0; i < N; i++) {
keys_info.key_idxes.emplace_back(i);
uint64_t h = key_index_hash(&keys[i], sizeof(Key));
keys_info.hashes.emplace_back(h);
}
vector<IndexValue> get_values(N);
size_t num_found = 0;
auto st_get = idx_loaded->get(N, keys.data(), keys_info, get_values.data(), &num_found);
if (!st_get.ok()) {
LOG(WARNING) << st_get;
}
ASSERT_TRUE(st_get.ok());
ASSERT_EQ(N, num_found);
for (size_t i = 0; i < N; i++) {
ASSERT_EQ(values[i], get_values[i]);
}
ASSERT_TRUE(idx_loaded->check_not_exist(N, keys.data()).is_already_exist());
vector<Key> check_not_exist_keys(10);
for (int i = 0; i < 10; i++) {
check_not_exist_keys[i] = N + i;
}
ASSERT_TRUE(idx_loaded->check_not_exist(10, check_not_exist_keys.data()).ok());
}
} // namespace starrocks
| 37.136201 | 120 | 0.633144 | zhangboya1 |
c83a0d23657c910d8910539eee91fb66ae803d86 | 528 | cpp | C++ | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
typedef unsigned int uint;
void write_file(std::string path, uint number)
{
std::ofstream file;
file.open(path, std::ios::app);
if (file.is_open()){
file << number << ' ';
file.close();
}else{
std::cerr << "File isn't opened!";
}
}
int main()
{
std::string path = "file.txt";
for (uint number = 1; number < 31; number ++){
write_file(path, number);
}
std::cout << "File is created";
return 0;
}
| 18.206897 | 50 | 0.560606 | egorkaGubarev |
c83a88d0419cf2edc1feef83733fdff75625f036 | 13,156 | cpp | C++ | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 2 | 2019-11-11T21:17:14.000Z | 2019-11-11T22:07:26.000Z | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | null | null | null | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 1 | 2020-04-05T03:50:57.000Z | 2020-04-05T03:50:57.000Z | /*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* 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 "Molten/Renderer/OpenGL/OpenGLWin32Renderer.hpp"
#if defined(MOLTEN_ENABLE_OPENGL)
#if MOLTEN_PLATFORM == MOLTEN_PLATFORM_WINDOWS
#include "Molten/Renderer/OpenGL/OpengGLFunctions.hpp"
#include "Molten/Renderer/PushConstant.hpp"
#include "Molten/Window/Window.hpp"
#include "Molten/System/Exception.hpp"
#include <array>
namespace Molten
{
OpenGLWin32Renderer::OpenGLWin32Renderer() :
m_deviceContext(NULL),
m_context(NULL)
{}
OpenGLWin32Renderer::OpenGLWin32Renderer(RenderTarget& renderTarget, const Version& version, Logger* logger) :
OpenGLWin32Renderer()
{
Open(renderTarget, version, logger);
}
OpenGLWin32Renderer::~OpenGLWin32Renderer()
{
Close();
}
bool OpenGLWin32Renderer::Open(RenderTarget& renderTarget, const Version& version, Logger* /*logger*/)
{
HGLRC temporaryContext = NULL;
auto deviceContext = renderTarget.GetWin32DeviceContext();
if (deviceContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Device context of parameter \"window\" is null.");
}
try
{
static PIXELFORMATDESCRIPTOR pixelFormatDescriptor =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16, //DepthBits,
8, //StencilBits,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
// Choose and set the pixel format
GLuint pixelFormat;
if ((pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDescriptor)) == 0)
{
throw Exception("OpenGLWin32Renderer: Failed to choose pixel format for Win32 device context.");
}
if ((SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDescriptor)) == false)
{
throw Exception("OpenGLWin32Renderer: Failed to set pixel format for Win32 device context.");
}
temporaryContext = ::wglCreateContext(deviceContext);
if (temporaryContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Failed to create primitive Win32 OpenGL context.");
}
::wglMakeCurrent(NULL, NULL);
::wglMakeCurrent(deviceContext, temporaryContext);
if (version == Version::None)
{
Version openedVersion;
OpenBestVersion(deviceContext, openedVersion);
m_version = openedVersion;
}
else
{
OpenVersion(deviceContext, version);
m_version = version;
}
}
catch (Exception &)
{
if (temporaryContext)
{
::wglDeleteContext(temporaryContext);
}
::wglMakeCurrent(NULL, NULL);
throw;
}
catch (...)
{
throw;
}
OpenGL::BindOpenGLExtensions();
return false;
}
void OpenGLWin32Renderer::Close()
{
if (m_context)
{
// Release the context from the current thread
if (!wglMakeCurrent(NULL, NULL))
{
throw Exception("OpenGLWin32Renderer: Failed to set current context to null.");
}
// Delete the context
if (!wglDeleteContext(m_context))
{
throw Exception("OpenGLWin32Renderer: Failed to delete context.");
}
m_context = NULL;
}
}
bool OpenGLWin32Renderer::IsOpen() const
{
return false;
}
void OpenGLWin32Renderer::Resize(const Vector2ui32& /*size*/)
{
}
Renderer::BackendApi OpenGLWin32Renderer::GetBackendApi() const
{
return Renderer::BackendApi::OpenGL;
}
Version OpenGLWin32Renderer::GetVersion() const
{
return m_version;
}
const RendererCapabilities& OpenGLWin32Renderer::GetCapabilities() const
{
static RendererCapabilities tmpCapabilities = {};
return tmpCapabilities;
}
uint32_t OpenGLWin32Renderer::GetPushConstantLocation(Pipeline& /*pipeline*/, const uint32_t /*id*/)
{
return PushConstantLocation::UnknownLocation;
}
RenderResource<DescriptorSet> OpenGLWin32Renderer::CreateDescriptorSet(const DescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<FramedDescriptorSet> OpenGLWin32Renderer::CreateFramedDescriptorSet(const FramedDescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<IndexBuffer> OpenGLWin32Renderer::CreateIndexBuffer(const IndexBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<Pipeline> OpenGLWin32Renderer::CreatePipeline(const PipelineDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<RenderPass> OpenGLWin32Renderer::CreateRenderPass(const RenderPassDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler1D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler2D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler3D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<ShaderProgram> OpenGLWin32Renderer::CreateShaderProgram(const VisualShaderProgramDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture1D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture2D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture3D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture1D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture2D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture3D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
RenderResource<UniformBuffer> OpenGLWin32Renderer::CreateUniformBuffer(const UniformBufferDescriptor&)
{
return { };
}
RenderResource<FramedUniformBuffer> OpenGLWin32Renderer::CreateFramedUniformBuffer(const FramedUniformBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<VertexBuffer> OpenGLWin32Renderer::CreateVertexBuffer(const VertexBufferDescriptor&)
{
return { };
}
bool OpenGLWin32Renderer::UpdateRenderPass(RenderPass& /*renderPass*/, const RenderPassUpdateDescriptor& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture1D& /*texture1D*/, const TextureUpdateDescriptor1D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture2D& /*texture2D*/, const TextureUpdateDescriptor2D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture3D& /*texture3D*/, const TextureUpdateDescriptor3D& /*descriptor*/)
{
return false;
}
void OpenGLWin32Renderer::UpdateUniformBuffer(RenderResource<UniformBuffer>& /*uniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
void OpenGLWin32Renderer::UpdateFramedUniformBuffer(RenderResource<FramedUniformBuffer>& /*framedUniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
bool OpenGLWin32Renderer::DrawFrame(const RenderPasses& /*renderPasses*/)
{
return false;
}
void OpenGLWin32Renderer::Destroy(DescriptorSet& /*descriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedDescriptorSet& /*framedDescriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(IndexBuffer& /*indexBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(Pipeline& /*pipeline*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler1D& /*sampler1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler2D& /*sampler2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler3D& /*sampler3D*/)
{
}
void OpenGLWin32Renderer::Destroy(ShaderProgram& /*shaderProgram*/ )
{
}
void OpenGLWin32Renderer::Destroy(Texture1D& /*texture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture2D& /*texture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture3D& /*texture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture1D& /*framedTexture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture2D& /*framedTexture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture3D& /*framedTexture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(UniformBuffer& /*uniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedUniformBuffer& /*framedUniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(VertexBuffer& /*vertexBuffer*/)
{
}
void OpenGLWin32Renderer::WaitForDevice()
{
}
bool OpenGLWin32Renderer::OpenVersion(HDC deviceContext, const Version& version)
{
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
if ((wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB")) == NULL)
{
throw Exception("Cannot get address of wglCreateContextAttribsARB.");
}
const int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(version.Major),
WGL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(version.Minor),
0
};
if ((m_context = wglCreateContextAttribsARB(deviceContext, 0, attributes)) == NULL)
{
throw Exception("Failed to create OpenGL context version " + version.AsString());
}
return true;
}
void OpenGLWin32Renderer::OpenBestVersion(HDC deviceContext, Version& version)
{
static const std::array versions =
{
Version(4, 6),
Version(4, 5),
Version(4, 4),
Version(4, 3),
Version(4, 2),
Version(4, 1),
Version(4, 0),
Version(3, 3),
Version(3, 2),
Version(3, 1),
Version(3, 0),
Version(2, 1),
Version(2, 0)
};
version = Version::None;
for(auto it = versions.begin(); it != versions.end(); it++)
{
try
{
const Version& ver = *it;
if (OpenVersion(deviceContext, ver))
{
version = ver;
return;
}
}
catch (Exception & e)
{
if(std::next(it) != versions.end())
{
continue;
}
throw Exception("OpenGLWin32Renderer: Failed to create best OpenGL context, last error: " + e.GetMessage());
}
}
}
}
#endif
#endif | 28.537961 | 187 | 0.617741 | jimmiebergmann |
c83aeaa0239ea2a65bf9cc59b2846a10d9afe78a | 3,919 | cpp | C++ | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 2 | 2020-08-20T03:40:24.000Z | 2021-02-07T20:31:43.000Z | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | null | null | null | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Version: v2017.2.9 Build: 6726
Copyright (c) 2006-2019 Audiokinetic Inc.
*******************************************************************************/
//////////////////////////////////////////////////////////////////////
//
// AkDelayFX.cpp
//
// Sample delay FX implementation.
//
//////////////////////////////////////////////////////////////////////
#include "AkDelayFX.h"
#include <AK/Tools/Common/AkAssert.h>
#include <AK/AkWwiseSDKVersion.h>
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPlugin* CreateAkDelayFX( AK::IAkPluginMemAlloc * in_pAllocator )
{
return AK_PLUGIN_NEW( in_pAllocator, CAkDelayFX( ) );
}
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPluginParam * CreateAkDelayFXParams(AK::IAkPluginMemAlloc * in_pAllocator)
{
return AK_PLUGIN_NEW(in_pAllocator, CAkDelayFXParams());
}
AK_IMPLEMENT_PLUGIN_FACTORY(AkDelayFX, AkPluginTypeEffect, 0, 106)
/// Constructor.
CAkDelayFX::CAkDelayFX()
: m_pParams( NULL )
, m_pAllocator( NULL )
{
}
/// Destructor.
CAkDelayFX::~CAkDelayFX()
{
}
/// Initializes and allocate memory for the effect.
AKRESULT CAkDelayFX::Init( AK::IAkPluginMemAlloc * in_pAllocator, /// Memory allocator interface.
AK::IAkEffectPluginContext * in_pFXCtx, /// Sound engine plug-in execution context.
AK::IAkPluginParam * in_pParams, /// Associated effect parameters node.
AkAudioFormat & in_rFormat /// Input/output audio format.
)
{
m_pParams = (CAkDelayFXParams*)in_pParams;
m_pAllocator = in_pAllocator;
m_FXState.Setup( m_pParams, in_rFormat.uSampleRate );
AKRESULT eResult = m_FXState.InitDelay( in_pAllocator, m_pParams, in_rFormat.channelConfig );
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->NonRTPC.bHasChanged = false;
m_pParams->RTPC.bHasChanged = false;
AK_PERF_RECORDING_RESET();
return eResult;
}
/// Effect termination.
AKRESULT CAkDelayFX::Term( AK::IAkPluginMemAlloc * in_pAllocator )
{
m_FXState.TermDelay( in_pAllocator );
AK_PLUGIN_DELETE( in_pAllocator, this ); /// Effect must delete itself
return AK_Success;
}
/// Actions to perform on FX reset (example on bypass)
AKRESULT CAkDelayFX::Reset( )
{
m_FXState.ResetDelay();
return AK_Success;
}
/// Effect info query.
AKRESULT CAkDelayFX::GetPluginInfo( AkPluginInfo & out_rPluginInfo )
{
out_rPluginInfo.eType = AkPluginTypeEffect;
out_rPluginInfo.bIsInPlace = true;
out_rPluginInfo.uBuildVersion = AK_WWISESDK_VERSION_COMBINED;
return AK_Success;
}
/// Effect plug-in DSP processing
void CAkDelayFX::Execute( AkAudioBuffer * io_pBuffer )
{
if ( AK_EXPECT_FALSE( m_pParams->NonRTPC.bHasChanged ) )
{
AKRESULT eResult = m_FXState.InitDelay( m_pAllocator, m_pParams, io_pBuffer->GetChannelConfig() );
if ( eResult != AK_Success )
return; // passthrough
m_FXState.ResetDelay();
m_pParams->NonRTPC.bHasChanged = false;
}
if ( AK_EXPECT_FALSE( m_pParams->RTPC.bHasChanged ) )
{
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->RTPC.bHasChanged = false;
}
AK_PERF_RECORDING_START( "Delay", 25, 30 );
// Execute DSP processing synchronously here
m_FXState.Process( io_pBuffer, m_pParams );
AK_PERF_RECORDING_STOP( "Delay", 25, 30 );
}
| 32.38843 | 100 | 0.70222 | chrisinajar |
c83b37f18ec5a50cf411341f48e5efc86ab7b2e8 | 298 | cpp | C++ | tcp-plugin-qnx/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | 2 | 2021-08-10T13:55:05.000Z | 2021-10-21T10:14:24.000Z | tcp-plugin-ubuntu/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | null | null | null | tcp-plugin-ubuntu/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | null | null | null | #include <cligen/cligen.h>
#include <clixon/clixon.h>
#include "plugin_lifecycle.h"
int LifecycleManager::plugin_start(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_exit(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_daemon(clicon_handle h) {
return 0;
}
| 17.529412 | 54 | 0.738255 | mager-m |
c83c63f95f9a64f606c336de55d9627b161721e2 | 504 | cpp | C++ | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 3 | 2022-01-25T07:33:43.000Z | 2022-03-30T10:25:09.000Z | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | null | null | null | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 2 | 2022-01-17T13:39:12.000Z | 2022-03-30T10:25:12.000Z | #include <iostream>
struct [[nodiscard]] error_info { /*...*/ };
error_info enable_missile_safety_mode() { /*...*/ return {}; }
void launch_missiles() { /*...*/ }
void test_missiles()
{
enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
launch_missiles();
}
// nodiscard( string-literal ) (since C++20):
struct [[nodiscard("OneFLOW CFD")]] cfd_info { /*...*/ };
void test_cfd()
{
cfd_info();
}
int main ( int argc, char **argv )
{
{
}
return 0;
}
| 19.384615 | 85 | 0.621032 | eric2003 |
c83d447f34dfa877f0e0b330ca08fcee7449fca4 | 1,882 | cpp | C++ | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 50 | 2016-03-23T08:04:44.000Z | 2022-03-25T05:06:16.000Z | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 589 | 2016-04-01T04:09:09.000Z | 2022-03-31T00:38:10.000Z | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 234 | 2016-03-28T20:59:21.000Z | 2022-03-23T09:26:22.000Z | #include "NotificationFdbEvent.h"
#include "Meta.h"
#include "MetaTestSaiInterface.h"
#include "sairediscommon.h"
#include "sai_serialize.h"
#include <gtest/gtest.h>
#include <memory>
using namespace sairedis;
using namespace saimeta;
static std::string s =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x21000000000000\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string null =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x0\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string fullnull = "[]";
TEST(NotificationFdbEvent, ctr)
{
NotificationFdbEvent n(s);
}
TEST(NotificationFdbEvent, getSwitchId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getSwitchId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getSwitchId(), 0);
}
TEST(NotificationFdbEvent, getAnyObjectId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getAnyObjectId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getAnyObjectId(), 0x260000000005be);
NotificationFdbEvent n3(fullnull);
EXPECT_EQ(n3.getSwitchId(), 0x0);
EXPECT_EQ(n3.getAnyObjectId(), 0x0);
}
TEST(NotificationFdbEvent, processMetadata)
{
NotificationFdbEvent n(s);
auto sai = std::make_shared<MetaTestSaiInterface>();
auto meta = std::make_shared<Meta>(sai);
n.processMetadata(meta);
}
| 27.275362 | 175 | 0.675345 | vmittal-msft |
c83da0b0eb7e41bcb75a2418ba5e99f647d7d64a | 38,689 | cc | C++ | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <algorithm>
#include <cmath>
#include <functional>
#include <random>
#include <vector>
#include <xnnpack.h>
#include <benchmark/benchmark.h>
#include "bench/end2end.h"
#include "bench/utils.h"
#include "models/models.h"
#include <xnnpack/gemm.h>
#include <xnnpack/igemm.h>
#include <xnnpack/params.h>
static void GEMMEnd2EndBenchmark(
benchmark::State& state,
models::ExecutionPlanFactory model_factory,
xnn_f32_gemm_ukernel_function gemm,
xnn_f32_igemm_ukernel_function igemm,
xnn_f32_gemm_ukernel_function gemm1,
xnn_f32_igemm_ukernel_function igemm1,
uint8_t mr, uint8_t nr, uint8_t log2_kr = 0, uint8_t log2_sr = 0,
benchmark::utils::IsaCheckFunction isa_check = nullptr)
{
if (isa_check && !isa_check(state)) {
return;
}
if (xnn_initialize(nullptr /* allocator */) != xnn_status_success) {
state.SkipWithError("failed to initialize XNNPACK");
return;
}
// Override microkernels chosen in xnn_initialize
xnn_params.f32.gemm = (struct gemm_parameters) {
.gemm = xnn_gemm_ukernel_function(gemm),
.igemm = xnn_igemm_ukernel_function(igemm),
.gemm1 = xnn_gemm_ukernel_function(gemm1),
.igemm1 = xnn_igemm_ukernel_function(igemm1),
.mr = mr,
.nr = nr,
.log2_kr = log2_kr,
.log2_sr = log2_sr,
};
auto execution_plan = model_factory(nullptr);
if (execution_plan.empty()) {
state.SkipWithError("failed to create a model");
return;
}
for (auto _ : state) {
for (const std::unique_ptr<xnn_operator, decltype(&xnn_delete_operator)>& op : execution_plan) {
xnn_status status = xnn_run_operator(op.get(), nullptr);
if (status != xnn_status_success) {
state.SkipWithError("failed to run a model");
return;
}
}
}
state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency();
}
#if XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x12__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
4 /* mr */, 12 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a73(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld64)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld64);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a57)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a75)
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a53);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a73);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x12__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld128);
#endif // XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x8__aarch32_neon_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a53,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_pld_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_pld_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_ld64);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a53);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_pld_cortex_a75);
#endif // XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM || XNN_ARCH_ARM64
static void f32_gemm_4x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neon,
xnn_f32_igemm_ukernel_4x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neonfma,
xnn_f32_igemm_ukernel_4x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neon,
xnn_f32_igemm_ukernel_6x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neonfma,
xnn_f32_igemm_ukernel_6x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_8x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neon,
xnn_f32_igemm_ukernel_8x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_8x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neonfma,
xnn_f32_igemm_ukernel_8x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8s4__neon);
BENCHMARK_END2END(f32_gemm_6x8s4__neon);
BENCHMARK_END2END(f32_gemm_8x8s4__neon);
BENCHMARK_END2END(f32_gemm_4x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_6x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_8x8s4__neonfma);
#endif // XNN_ARCH_ARM || XNN_ARCH_ARM64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
static void f32_gemm_4x8__sse_load1(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_load1,
xnn_f32_igemm_ukernel_4x8__sse_load1,
xnn_f32_gemm_ukernel_1x8__sse_load1,
xnn_f32_igemm_ukernel_1x8__sse_load1,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__sse_dup(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_dup,
xnn_f32_igemm_ukernel_4x8__sse_dup,
xnn_f32_gemm_ukernel_1x8__sse_dup,
xnn_f32_igemm_ukernel_1x8__sse_dup,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__sse(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__sse,
xnn_f32_igemm_ukernel_4x8s4__sse,
xnn_f32_gemm_ukernel_1x8s4__sse,
xnn_f32_igemm_ukernel_1x8s4__sse,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_4x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__avx_broadcast,
xnn_f32_igemm_ukernel_4x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__avx_broadcast,
xnn_f32_igemm_ukernel_5x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_6x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__avx_broadcast,
xnn_f32_igemm_ukernel_6x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_7x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__avx_broadcast,
xnn_f32_igemm_ukernel_7x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_3x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__avx_broadcast,
xnn_f32_igemm_ukernel_3x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx_broadcast,
xnn_f32_igemm_ukernel_4x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx_broadcast,
xnn_f32_igemm_ukernel_5x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__fma3_broadcast,
xnn_f32_igemm_ukernel_4x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__fma3_broadcast,
xnn_f32_igemm_ukernel_5x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_6x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__fma3_broadcast,
xnn_f32_igemm_ukernel_6x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_7x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__fma3_broadcast,
xnn_f32_igemm_ukernel_7x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_8x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8__fma3_broadcast,
xnn_f32_igemm_ukernel_8x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
8 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_5x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_6x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
6 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_7x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
7 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_8x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
8 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
BENCHMARK_END2END(f32_gemm_4x8__sse_load1);
BENCHMARK_END2END(f32_gemm_4x8__sse_dup);
BENCHMARK_END2END(f32_gemm_4x8s4__sse);
BENCHMARK_END2END(f32_gemm_4x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_8x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_6x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_7x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_8x16__avx512f_broadcast);
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
static void f32_gemm_4x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_splat,
xnn_f32_igemm_ukernel_4x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_splat,
xnn_f32_igemm_ukernel_6x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__psimd,
xnn_f32_igemm_ukernel_4x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_6x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__psimd,
xnn_f32_igemm_ukernel_6x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
BENCHMARK_END2END(f32_gemm_4x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_4x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_4x8s4__psimd);
BENCHMARK_END2END(f32_gemm_6x8s4__psimd);
#endif // !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
#if XNN_ARCH_WASM
static void f32_gemm_2x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__wasm,
xnn_f32_igemm_ukernel_2x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__wasm,
xnn_f32_igemm_ukernel_4x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__wasm);
BENCHMARK_END2END(f32_gemm_4x4__wasm);
#endif // XNN_ARCH_WASM
static void f32_gemm_2x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__scalar,
xnn_f32_igemm_ukernel_2x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__scalar,
xnn_f32_igemm_ukernel_4x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__scalar);
BENCHMARK_END2END(f32_gemm_4x4__scalar);
#ifndef XNNPACK_BENCHMARK_NO_MAIN
BENCHMARK_MAIN();
#endif
| 42.468716 | 118 | 0.758975 | 8thwall |
c84d5d91ddc5761d0aee4e3392dfe62c2d0223a6 | 826 | cpp | C++ | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 46 | 2019-11-16T13:44:07.000Z | 2022-03-12T14:28:44.000Z | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 11 | 2020-05-12T17:20:51.000Z | 2022-02-04T10:04:59.000Z | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 22 | 2020-02-21T21:33:40.000Z | 2022-02-24T06:50:41.000Z | #include "fir.h"
//------------------------------------------------------------------------
// FIR
//------------------------------------------------------------------------
//SEPARATOR_FOR_MAIN
#include <stdlib.h>
#include "fir.h"
#define AMOUNT_OF_TEST 1
int fir (in_int_t d_i[1000], in_int_t idx[1000] ) {
int i;
int tmp=0;
For_Loop: for (i=0;i<1000;i++) {
tmp += idx [i] * d_i[999-i];
}
//out [0] = tmp;
return tmp;
}
int main(void){
in_int_t d_i[AMOUNT_OF_TEST][1000];
in_int_t idx[AMOUNT_OF_TEST][1000];
inout_int_t out[AMOUNT_OF_TEST][1000];
srand(13);
for(int i = 0; i < AMOUNT_OF_TEST; ++i){
for(int j = 0; j < 1000; ++j){
d_i[0][j] = rand() % 100;
idx[0][j] = rand() % 100;
}
}
for(int i = 0; i < 1; ++i){
fir(d_i[0], idx[0] );
}
}
//SEPARATOR_FOR_MAIN
| 17.574468 | 74 | 0.464891 | minseongg |
c84d7ff01803f6ae49544876486531a3c7ff4f53 | 3,388 | cc | C++ | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | 2 | 2020-04-26T02:42:56.000Z | 2021-01-15T00:25:16.000Z | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | null | null | null | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | 1 | 2017-01-19T10:33:37.000Z | 2017-01-19T10:33:37.000Z | /*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/util.h"
#include "vpx_scale/yv12config.h"
#include "vpx/vpx_integer.h"
#include "vp9/common/vp9_reconinter.h"
#include "vp9/encoder/vp9_context_tree.h"
#include "vp9/encoder/vp9_denoiser.h"
using libvpx_test::ACMRandom;
namespace {
const int kNumPixels = 64 * 64;
class VP9DenoiserTest : public ::testing::TestWithParam<BLOCK_SIZE> {
public:
virtual ~VP9DenoiserTest() {}
virtual void SetUp() {
bs_ = GetParam();
}
virtual void TearDown() { libvpx_test::ClearSystemState(); }
protected:
BLOCK_SIZE bs_;
};
TEST_P(VP9DenoiserTest, BitexactCheck) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 4000;
// Allocate the space for input and output,
// where sig_block is the block to be denoised,
// mc_avg_block is the denoised reference block,
// avg_block_c is the denoised result from C code,
// avg_block_sse2 is the denoised result from SSE2 code.
DECLARE_ALIGNED(16, uint8_t, sig_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, mc_avg_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_c[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_sse2[kNumPixels]);
for (int i = 0; i < count_test_block; ++i) {
// Generate random motion magnitude, 20% of which exceed the threshold.
const int motion_magnitude_random =
rnd.Rand8() % static_cast<int>(MOTION_MAGNITUDE_THRESHOLD * 1.2);
// Initialize a test block with random number in range [0, 255].
for (int j = 0; j < kNumPixels; ++j) {
int temp = 0;
sig_block[j] = rnd.Rand8();
// The pixels in mc_avg_block are generated by adding a random
// number in range [-19, 19] to corresponding pixels in sig_block.
temp = sig_block[j] + ((rnd.Rand8() % 2 == 0) ? -1 : 1) *
(rnd.Rand8() % 20);
// Clip.
mc_avg_block[j] = (temp < 0) ? 0 : ((temp > 255) ? 255 : temp);
}
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_c(
sig_block, 64, mc_avg_block, 64, avg_block_c,
64, 0, bs_, motion_magnitude_random));
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_sse2(
sig_block, 64, mc_avg_block, 64, avg_block_sse2,
64, 0, bs_, motion_magnitude_random));
// Test bitexactness.
for (int h = 0; h < (4 << b_height_log2_lookup[bs_]); ++h) {
for (int w = 0; w < (4 << b_width_log2_lookup[bs_]); ++w) {
EXPECT_EQ(avg_block_c[h * 64 + w], avg_block_sse2[h * 64 + w]);
}
}
}
}
// Test for all block size.
INSTANTIATE_TEST_CASE_P(
SSE2, VP9DenoiserTest,
::testing::Values(BLOCK_8X8, BLOCK_8X16, BLOCK_16X8, BLOCK_16X16,
BLOCK_16X32, BLOCK_32X16, BLOCK_32X32, BLOCK_32X64,
BLOCK_64X32, BLOCK_64X64));
} // namespace
| 33.544554 | 75 | 0.682113 | golden1232004 |
c8527afc64c8e8b9649e7a0cc4b36e40fac52203 | 3,244 | cpp | C++ | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | 2 | 2019-04-30T18:32:43.000Z | 2022-03-04T07:12:01.000Z | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | null | null | null | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | null | null | null | #define INSTANCIATE_UTILS
#include "utils.h"
// System Header
#include <stdio.h>
#include <windows.h>
#include <string>
void initUtils()
{
std::string tmp;
TCHAR szModuleName[MAX_PATH];
GetCurrentDirectory(MAX_PATH, szCurPath); // rootdir/test/
GetModuleFileName(NULL, szModuleName, MAX_PATH); // rootdir/test/bin/text.exe
tmp = io::Dirname(szModuleName); // rootdir/test/bin
strcpy_s(szExePath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
tmp = io::PathCombine(tmp, "tmp"); // rootdir/test/bin/tmp
strcpy_s(szTmpPath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
io::DirectoryDelete(tmp);
CreateDirectory(szTmpPath, NULL);
tmp = io::Dirname(tmp); // rootdir/test/
tmp = io::Dirname(tmp); // rootdir/
tmp = io::PathCombine(tmp, "isx"); // rootdir/isx
tmp = io::PathCombine(tmp, "bin"); // rootdir/isx/bin
strcpy_s(szLibPath, MAX_PATH, tmp.c_str());
}
void DbgOutput(const char* szFormat, ...) {
char szBuff[MAX_PATH];
va_list arg;
va_start(arg, szFormat);
_vsnprintf_s(szBuff, sizeof(szBuff), szFormat, arg);
va_end(arg);
strcat_s(szBuff, MAX_PATH, "\n");
OutputDebugString("isx-test > ");
OutputDebugString(szBuff);
printf_s(szBuff, MAX_PATH);
}
void DbgPopLastError() {
char buff[MAX_PATH];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buff, (sizeof(buff) / sizeof(wchar_t)), NULL);
MessageBox(NULL, buff, "error", MB_OK);
}
bool DirectoryExists(const std::string& path) {
DWORD ftyp = GetFileAttributes(path.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
bool DirectoryDelete(const std::string& path) {
if (path.empty()) return TRUE;
if (!DirectoryExists(path)) return TRUE;
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
std::string search = path + "\\*";
hFind = FindFirstFile(search.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) return FALSE;
while (TRUE)
{
/* end */
if (!FindNextFile(hFind, &FindFileData)) {
if (GetLastError() == ERROR_NO_MORE_FILES) break;
FindClose(hFind);
return FALSE;
}
/* skip '.' and '..' */
std::string item(FindFileData.cFileName);
if (item == "." || item == "..") continue;
std::string filename = path + "\\" + item;
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
/* item is a directory (recursive call) */
if (!DirectoryDelete(filename)) {
FindClose(hFind);
return FALSE;
}
}
else
{
/* item is a file, delete it */
if (!DeleteFile(filename.c_str())) {
FindClose(hFind);
return FALSE;
}
}
}
FindClose(hFind);
/* actual folder deletion */
if (!RemoveDirectory(path.c_str())) return FALSE;
return TRUE;
} | 30.603774 | 81 | 0.609433 | chtimi59 |
c856bac5a77f7b09329edd58f1f713976aeac8dc | 7,714 | cpp | C++ | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 1,562 | 2020-12-01T15:02:21.000Z | 2022-03-31T13:37:51.000Z | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 562 | 2020-12-01T20:10:13.000Z | 2022-03-31T22:57:13.000Z | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 184 | 2020-12-01T15:02:24.000Z | 2022-03-31T06:18:18.000Z | /*
* Copyright (c) 2018-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "private_data.hpp"
#include "wsi/wsi_factory.hpp"
#include <unordered_map>
namespace layer {
static std::mutex g_data_lock;
static std::unordered_map<void *, std::unique_ptr<instance_private_data>> g_instance_data;
static std::unordered_map<void *, std::unique_ptr<device_private_data>> g_device_data;
template <typename object_type, typename get_proc_type>
static PFN_vkVoidFunction get_proc_helper(object_type obj, get_proc_type get_proc,
const char *proc_name, bool required, bool &ok) {
PFN_vkVoidFunction ret = get_proc(obj, proc_name);
if (nullptr == ret && required) {
ok = false;
}
return ret;
}
VkResult instance_dispatch_table::populate(VkInstance instance,
PFN_vkGetInstanceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, false, ok));
INSTANCE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
VkResult device_dispatch_table::populate(VkDevice device, PFN_vkGetDeviceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, false, ok));
DEVICE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
instance_private_data::instance_private_data(const instance_dispatch_table &table,
PFN_vkSetInstanceLoaderData set_loader_data,
util::wsi_platform_set enabled_layer_platforms)
: disp(table), SetInstanceLoaderData(set_loader_data),
enabled_layer_platforms(enabled_layer_platforms) {}
template <typename dispatchable_type>
static inline void *get_key(dispatchable_type dispatchable_object) {
return *reinterpret_cast<void **>(dispatchable_object);
}
void instance_private_data::set(VkInstance inst, std::unique_ptr<instance_private_data> inst_data) {
scoped_mutex lock(g_data_lock);
g_instance_data[get_key(inst)] = std::move(inst_data);
}
template <typename dispatchable_type>
static instance_private_data &get_instance_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_instance_data[get_key(dispatchable_object)];
}
instance_private_data &instance_private_data::get(VkInstance instance) {
return get_instance_private_data(instance);
}
instance_private_data &instance_private_data::get(VkPhysicalDevice phys_dev) {
return get_instance_private_data(phys_dev);
}
static VkIcdWsiPlatform get_platform_of_surface(VkSurfaceKHR surface) {
VkIcdSurfaceBase *surface_base = reinterpret_cast<VkIcdSurfaceBase *>(surface);
return surface_base->platform;
}
bool instance_private_data::does_layer_support_surface(VkSurfaceKHR surface) {
return enabled_layer_platforms.contains(get_platform_of_surface(surface));
}
bool instance_private_data::do_icds_support_surface(VkPhysicalDevice, VkSurfaceKHR) {
/* For now assume ICDs do not support VK_KHR_surface. This means that the layer will handle all
* the surfaces it can handle (even if the ICDs can handle the surface) and only call down for
* surfaces it cannot handle. In the future we may allow system integrators to configure which
* ICDs have precedence handling which platforms.
*/
return false;
}
bool instance_private_data::should_layer_handle_surface(VkSurfaceKHR surface) {
return surfaces.find(surface) != surfaces.end();
}
void instance_private_data::destroy(VkInstance inst) {
scoped_mutex lock(g_data_lock);
g_instance_data.erase(get_key(inst));
}
void instance_private_data::add_surface(VkSurfaceKHR surface) {
scoped_mutex lock(g_data_lock);
surfaces.insert(surface);
}
device_private_data::device_private_data(instance_private_data &inst_data,
VkPhysicalDevice phys_dev, VkDevice dev,
const device_dispatch_table &table,
PFN_vkSetDeviceLoaderData set_loader_data)
: disp{table}, instance_data{inst_data}, SetDeviceLoaderData{set_loader_data},
physical_device{phys_dev}, device{dev} {}
void device_private_data::set(VkDevice dev, std::unique_ptr<device_private_data> dev_data) {
scoped_mutex lock(g_data_lock);
g_device_data[get_key(dev)] = std::move(dev_data);
}
template <typename dispatchable_type>
static device_private_data &get_device_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_device_data[get_key(dispatchable_object)];
}
device_private_data &device_private_data::get(VkDevice device) {
return get_device_private_data(device);
}
device_private_data &device_private_data::get(VkQueue queue) {
return get_device_private_data(queue);
}
void device_private_data::add_layer_swapchain(VkSwapchainKHR swapchain) {
scoped_mutex lock(swapchains_lock);
swapchains.insert(swapchain);
}
bool device_private_data::layer_owns_all_swapchains(const VkSwapchainKHR *swapchain,
uint32_t swapchain_count) const {
scoped_mutex lock(swapchains_lock);
for (uint32_t i = 0; i < swapchain_count; i++) {
if (swapchains.find(swapchain[i]) == swapchains.end()) {
return false;
}
}
return true;
}
bool device_private_data::should_layer_create_swapchain(VkSurfaceKHR vk_surface) {
return instance_data.should_layer_handle_surface(vk_surface);
}
bool device_private_data::can_icds_create_swapchain(VkSurfaceKHR vk_surface) {
return disp.CreateSwapchainKHR != nullptr;
}
void device_private_data::destroy(VkDevice dev) {
scoped_mutex lock(g_data_lock);
g_device_data.erase(get_key(dev));
}
} /* namespace layer */
| 40.814815 | 100 | 0.709619 | Firepal |
c858d5b84f4a9b98a6d232225b1b98321a9060cf | 1,040 | cpp | C++ | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#define max_nodes_size 100005
#define max_size 100005
#define ll long long int
#define mod 1000000007
#define sl(n) scanf("%lld", &n)
using namespace std;
ll grid[2005][2005];
ll vis[2005];
ll dfs(ll node, ll flag, ll n)
{
vis[node] = 1;
ll temp = 1;
for(ll i=0; i<n; i++)
{
if(i!=node && vis[i]==0)
{
if(flag)
{
if(grid[i][node]>0)
temp += dfs(i, flag, n);
}
else
{
if(grid[node][i]>0)
temp += dfs(i, flag, n);
}
}
}
//cout<<node<<" "<<temp<<endl;
return temp;
}
int main()
{
ll n, a;
cin>>n;
ll flag = 0;
for(ll i=0; i<n; i++)
{
for(ll j=0; j<n; j++)
{
sl(grid[i][j]);
}
}
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 0, n)==n)
flag++;
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 1, n)==n)
flag++;
if(flag==2)
cout<<"YES";
else
cout<<"NO";
return 0;
} | 12.682927 | 32 | 0.531731 | AmrARaouf |
c85bb28c08356971479658838a517e22bf5cbf98 | 31,037 | cpp | C++ | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <Eigen/Core>
#include <tudat/basics/testMacros.h>
#include <tudat/simulation/simulation.h>
#include <tudat/io/basicInputOutput.h>
#include <tudat/io/applicationOutput.h>
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h"
#include "tudat/astro/ephemerides/approximatePlanetPositions.h"
#include "tudat/simulation/simulation.h"
#include "tudat/interface/spice/spiceEphemeris.h"
using namespace tudat;
using namespace tudat::input_output;
using namespace tudat::simulation_setup;
using namespace tudat::shape_based_methods;
SystemOfBodies getBetBodyMap( )
{
// Create central, departure and arrival bodies.
std::vector< std::string > bodiesToCreate;
bodiesToCreate.push_back( "Sun" );
bodiesToCreate.push_back( "Earth" );
bodiesToCreate.push_back( "Mars" );
bodiesToCreate.push_back( "Jupiter" );
std::map< std::string, std::shared_ptr< simulation_setup::BodySettings > > bodySettings =
simulation_setup::getDefaultBodySettings( bodiesToCreate );
std::string frameOrigin = "SSB";
std::string frameOrientation = "ECLIPJ2000";
// Define central body ephemeris settings.
bodySettings[ "Sun" ]->ephemerisSettings = std::make_shared< simulation_setup::ConstantEphemerisSettings >(
( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );
bodySettings[ "Sun" ]->ephemerisSettings->resetFrameOrientation( frameOrientation );
bodySettings[ "Sun" ]->rotationModelSettings->resetOriginalFrame( frameOrientation );
// Create system of bodies.
simulation_setup::SystemOfBodies bodies = createBodies( bodySettings );
bodies[ "Borzi" ] = std::make_shared< simulation_setup::Body >( );
bodies.at( "Borzi" )->setSuppressDependentOrientationCalculatorWarning( true );
bodies.at( "Borzi" )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(
std::shared_ptr< interpolators::OneDimensionalInterpolator
< double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );
// Create radiation pressure settings
double referenceAreaRadiation = 4.0;
double radiationPressureCoefficient = 1.2;
std::vector< std::string > occultingBodies;
occultingBodies.push_back( "Earth" );
std::shared_ptr< RadiationPressureInterfaceSettings > asterixRadiationPressureSettings =
std::make_shared< CannonBallRadiationPressureInterfaceSettings >(
"Sun", referenceAreaRadiation, radiationPressureCoefficient, occultingBodies );
// Create and set radiation pressure settings
bodies[ "Borzi" ]->setRadiationPressureInterface(
"Sun", createRadiationPressureInterface(
asterixRadiationPressureSettings, "Borzi", bodies ) );
setGlobalFrameBodyEphemerides( bodies, frameOrigin, frameOrientation );
return bodies;
}
int main( )
{
std::string outputSubFolder = "ShapeBasedTrajectoriesExample/";
spice_interface::loadStandardSpiceKernels( );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE TRAJECTORY GLOBAL PARAMETERS ////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int numberOfRevolutions = 1;
double julianDateAtDeparture = 8174.5 * physical_constants::JULIAN_DAY;
double timeOfFlight = 580.0 * physical_constants::JULIAN_DAY;
double vehicleInitialMass = 2000.0;
double specificImpulse = 3000.0;
std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ){ return specificImpulse; };
// Retrieve cartesian state at departure and arrival.
ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );
ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );
Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDateAtDeparture );
Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( julianDateAtDeparture + timeOfFlight );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE HODOGRAPHIC SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;
double scaleFactor = 1.0 / timeOfFlight;
// Create base function settings for the components of the radial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the radial velocity composite function.
std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the normal velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the normal velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the axial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =
std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >
( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(
3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
// Create components for the axial velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );
// Initialize free coefficients vector for radial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for normal velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for axial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Create hodographic-shaping object with defined velocity functions and boundary conditions.
shape_based_methods::HodographicShaping hodographicShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ), 1,
radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,
freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,
vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE SPHERICAL SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).
std::shared_ptr< root_finders::RootFinderSettings > rootFinderSettings =
std::make_shared< root_finders::RootFinderSettings >( root_finders::bisection_root_finder, 1.0e-6, 30 );
// Compute shaped trajectory.
shape_based_methods::SphericalShaping sphericalShaping = shape_based_methods::SphericalShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ),
numberOfRevolutions, 0.000703,
rootFinderSettings, 1.0e-6, 1.0e-1, vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CREATE ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set vehicle mass.
SystemOfBodies bodies = getBetBodyMap( );
bodies[ "Borzi" ]->setConstantBodyMass( vehicleInitialMass );
// Define body to propagate and central body.
std::vector< std::string > bodiesToPropagate;
std::vector< std::string > centralBodies;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE PROPAGATION SETTINGS /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define integrator settings.
double stepSize = timeOfFlight / static_cast< double >( 8000.0 );
std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =
std::make_shared< numerical_integrators::IntegratorSettings< double > > ( numerical_integrators::rungeKutta4, 0.0, stepSize );
// Define list of dependent variables to save.
std::vector< std::shared_ptr< propagators::SingleDependentVariableSaveSettings > > dependentVariablesList;
// Create object with list of dependent variables
std::shared_ptr< propagators::DependentVariableSaveSettings > dependentVariablesToSave =
std::make_shared< propagators::DependentVariableSaveSettings >( dependentVariablesList, false );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// NUMERICALLY PROPAGATE THE SIMPLIFIED PROBLEM /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistory;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettings = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettings, hodographicShapingPropagationUnperturbedCase,
hodographicShapingAnalyticalResults, hodographicShapingDependentVariablesHistory );
std::map< double, Eigen::VectorXd > sphericalShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistory;
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettings = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettings, sphericalShapingPropagationUnperturbedCase,
sphericalShapingAnalyticalResults, sphericalShapingDependentVariablesHistory );
input_output::writeDataMapToTextFile( hodographicShapingAnalyticalResults,
"hodographicShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingAnalyticalResults,
"sphericalShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingPropagationUnperturbedCase,
"hodographicShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationUnperturbedCase,
"sphericalShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// RETRIEVE TRAJECTORY, MASS, THRUST AND THRUST ACCELERATION PROFILES //////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hodographic shaping
std::vector< double > epochsVectorHodographicShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = hodographicShapingAnalyticalResults.begin( ) ;
itr != hodographicShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorHodographicShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustAccelerationProfile;
hodographicShaping.getMassProfile(
epochsVectorHodographicShaping, hodographicShapingMassProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustForceProfile(
epochsVectorHodographicShaping, hodographicShapingThrustProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustAccelerationProfile(
epochsVectorHodographicShaping, hodographicShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
// Spherical shaping
std::vector< double > epochsVectorSphericalShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = sphericalShapingAnalyticalResults.begin( ) ;
itr != sphericalShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorSphericalShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > sphericalShapingMassProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustAccelerationProfile;
sphericalShaping.getMassProfile(
epochsVectorSphericalShaping, sphericalShapingMassProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustForceProfile(
epochsVectorSphericalShaping, sphericalShapingThrustProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustAccelerationProfile(
epochsVectorSphericalShaping, sphericalShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// DEFINE PERTURBED DYNAMICAL ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define propagation settings.
std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationSettingsPerturbedProblem;
accelerationSettingsPerturbedProblem[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Mars" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::cannon_ball_radiation_pressure ) );
SelectedAccelerationMap accelerationMap;
accelerationMap[ "Borzi" ] = accelerationSettingsPerturbedProblem;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
basic_astrodynamics::AccelerationMap perturbingAccelerationsMapPertubedProblem = createAccelerationModelsMap(
bodies, accelerationMap, bodiesToPropagate, centralBodies );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// PROPAGATE THE FULLY PERTURBED PROBLEM /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistoryPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistoryPerturbedCase;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettingsPerturbedCase = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettingsPerturbedCase, hodographicShapingPropagationPerturbedCase,
hodographicShapingAnalyticalResultsPerturbedCase, hodographicShapingDependentVariablesHistoryPerturbedCase );
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettingsPerturbedCase = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettingsPerturbedCase, sphericalShapingPropagationPerturbedCase,
sphericalShapingAnalyticalResultsPerturbedCase, sphericalShapingDependentVariablesHistoryPerturbedCase );
input_output::writeDataMapToTextFile( hodographicShapingPropagationPerturbedCase,
"hodographicShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationPerturbedCase,
"sphericalShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingMassProfile,
"hodographicShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustProfile,
"hodographicShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustAccelerationProfile,
"hodographicShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingMassProfile,
"sphericalShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustProfile,
"sphericalShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustAccelerationProfile,
"sphericalShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
std::cout << "deltaV hodographic shaping: " << hodographicShaping.computeDeltaV( ) << "\n\n";
std::cout << "deltaV spherical shaping: " << sphericalShaping.computeDeltaV( ) << "\n\n";
// Final statement.
// The exit code EXIT_SUCCESS indicates that the program was successfully executed.
return EXIT_SUCCESS;
}
| 63.470348 | 142 | 0.609949 | kimonito98 |
c85e4ec855416eb93759d2e634f17a74d0db0358 | 9,348 | cpp | C++ | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 18 | 2018-01-23T12:28:13.000Z | 2022-02-13T12:23:21.000Z | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 2 | 2018-11-29T01:51:25.000Z | 2022-03-22T14:14:22.000Z | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 6 | 2019-02-01T09:54:44.000Z | 2022-01-09T22:13:54.000Z | #include "vega/dicom/file_meta.h"
#include "vega/dicom/writer.h"
#include "vega/dicom/data_element.h"
#include "vega/manipulator.h"
#include <cassert>
namespace vega {
namespace dicom {
const Tag FileMeta::FileMetaInformationGroupLength = Tag{0x2, 0x0};
const Tag FileMeta::TransferSyntaxUID = Tag{0x2, 0x10};
FileMeta::FileMeta()
: m_transfer_syntax(TransferSyntax::EXPLICIT_VR_LITTLE_ENDIAN)
{}
FileMeta::FileMeta(const SOPClass& sop_class)
: FileMeta(sop_class, UID::generate())
{}
FileMeta::FileMeta(const SOPClass& sop_class, const UID& media_storage_instance_uid)
: m_data_set(std::make_shared<DataSet>())
{
this->fill_defaults(sop_class, media_storage_instance_uid);
}
FileMeta::FileMeta(Reader& reader)
: m_data_set(std::make_shared<DataSet>())
{
// File meta information is written in little endian
const Endian original_endian = reader.dicom_endian();
reader.set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = reader.vr_explicit();
reader.set_vr_explicit(true);
this->read(reader);
reader.set_dicom_endianness(original_endian);
reader.set_vr_explicit(original_vr_explicit);
}
const TransferSyntax& FileMeta::transfer_syntax() const { return m_transfer_syntax; }
void FileMeta::set_transfer_syntax(const TransferSyntax& other) {
m_transfer_syntax = other;
}
Endian FileMeta::transfer_syntax_endian() const { return m_transfer_syntax.endianness(); }
bool FileMeta::transfer_syntax_vr_explicit() const { return m_transfer_syntax.is_explicit_vr(); }
std::shared_ptr<const DataSet> FileMeta::data_set() const { return std::const_pointer_cast<const DataSet>(m_data_set); }
const SOPClass& FileMeta::sop_class() const { return m_sop_class; }
const UID& FileMeta::media_storage_instance_uid() const { return m_media_storage_instance_uid; }
bool FileMeta::present() const { return bool(m_data_set); }
size_t FileMeta::write(std::shared_ptr<Writer> writer) {
if (!this->present()) return 0;
// File meta information is written in little endian
const Endian original_endian = writer->dicom_endian();
writer->set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = writer->vr_explicit();
writer->set_vr_explicit(true);
uint32_t length_of_file_meta_length_element = 0;
uint32_t file_meta_bytes = 0;
// Write each data element
bool first = true;
std::streampos file_meta_length_pos;
std::streampos end_of_file_meta_pos;
for (auto data_element : *m_data_set) {
if (first) {
first = false;
length_of_file_meta_length_element += writer->write_element(data_element);
assert(data_element->tag() == Tag(0x00020000));
file_meta_length_pos = writer->tell() - std::streampos(sizeof(file_meta_bytes));
assert(data_element->manipulator()->raw_value()->size() == sizeof(file_meta_bytes));
}
else {
file_meta_bytes += writer->write_element(data_element);
}
}
end_of_file_meta_pos = writer->tell();
writer->seek_pos(file_meta_length_pos);
writer->raw_writer().write_from(file_meta_bytes);
writer->seek_pos(end_of_file_meta_pos);
writer->set_dicom_endianness(original_endian);
writer->set_vr_explicit(original_vr_explicit);
return length_of_file_meta_length_element + file_meta_bytes;
}
void FileMeta::read(Reader& reader) {
// Expect first data_element to be File Meta Information Group Length
auto maybe_group_length = reader.read_data_element(m_data_set);
if (maybe_group_length->tag() == FileMetaInformationGroupLength) {
// Has group length
auto group_length = maybe_group_length;
auto manipulator = group_length->get_manipulator<UL_Manipulator>();
std::streampos end_of_file_meta = reader.tell() + (std::streampos)(*manipulator)[0];
m_data_set->add_data_element(group_length);
// Read in rest of file meta elements
while (reader.tell() < end_of_file_meta) {
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
if (!data_element->tag().is_file_meta()) {
throw InvalidFileMeta("Encountered non file-meta DataElement in file meta header");
}
m_data_set->add_data_element(data_element);
}
assert(reader.tell() == end_of_file_meta);
}
else {
// Group length not present, but we would like to have one anyway for compliance so create
auto actual_group_length = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = actual_group_length->get_manipulator<UL_Manipulator>();
manipulator->push_back(0);
m_data_set->add_data_element(actual_group_length);
// Previously read in data_element still needs to be added
m_data_set->add_data_element(maybe_group_length);
// Read until no longer getting file meta elements
while (!reader.eof()) {
// Tentatively read in next tag
std::streampos cur_pos = reader.tell();
Tag temp_tag;
reader.raw_reader().read_into(&temp_tag);
reader.seek_pos(cur_pos);
if (!temp_tag.is_file_meta()) {
// Finished reading file meta
break;
}
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
m_data_set->add_data_element(data_element);
}
}
auto transfer_syntax_uid = m_data_set->data_element(TransferSyntaxUID);
if (!transfer_syntax_uid) {
throw InvalidFileMeta("Need TransferSyntaxUID element");
}
auto sop_class = m_data_set->data_element(SOPClass::TAG);
if (!sop_class) {
throw InvalidFileMeta("Need MediaStorageSOPClassUID element");
}
auto sop_class_manipulator = sop_class->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = SOPClass(sop_class_manipulator->uid());
auto sop_instance = m_data_set->data_element("MediaStorageSOPInstanceUID");
if (!sop_instance) {
throw InvalidFileMeta("Need MediaStorageSOPInstanceUID element");
}
auto sop_instance_manipulator = sop_instance->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = sop_instance_manipulator->uid();
this->set_transfer_syntax(TransferSyntax{UID{transfer_syntax_uid->str()}});
}
void FileMeta::fill_defaults(const SOPClass& sop_class, const UID& media_storage_instance_uid) {
// File meta group length
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = data_element->get_manipulator<manipulators::UnsignedLongManipulator>();
// Store dummy value of zero here -- only need this value when writing to file
manipulator->push_back(0);
m_data_set->add_data_element(data_element);
}
// File meta information version (0x00, 0x01)
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationVersion");
auto manipulator = data_element->get_manipulator<manipulators::OtherByteManipulator>();
manipulator->push_back(Byte{.u=0});
manipulator->push_back(Byte{.u=1});
m_data_set->add_data_element(data_element);
}
// SOP class uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = sop_class;
manipulator->uid() = m_sop_class.uid();
m_data_set->add_data_element(data_element);
}
// SOP instance uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPInstanceUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = media_storage_instance_uid;
manipulator->uid() = m_media_storage_instance_uid;
m_data_set->add_data_element(data_element);
}
// Transfer syntax we default to implicit VR little endian
{
auto data_element = std::make_shared<dicom::DataElement>("TransferSyntaxUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
this->set_transfer_syntax(TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN);
manipulator->uid() = TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN.uid();
m_data_set->add_data_element(data_element);
}
// Implementation class UID
{
auto data_element = std::make_shared<dicom::DataElement>("ImplementationClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
manipulator->uid() = UID::IMPLEMENTATION_CLASS_UID;
m_data_set->add_data_element(data_element);
}
}
}
}
| 39.277311 | 124 | 0.692127 | project-eutopia |
c85fc4816b086d7a5792ebfbaf8e167c338ccd1c | 2,582 | cpp | C++ | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 30 | 2016-09-06T06:58:43.000Z | 2021-12-23T11:59:38.000Z | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 17 | 2016-10-24T06:08:16.000Z | 2022-02-18T17:27:14.000Z | //===-- MipsMCExpr.cpp - Mips specific MC expression classes --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsMCExpr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectStreamer.h"
using namespace llvm;
#define DEBUG_TYPE "mipsmcexpr"
bool MipsMCExpr::isSupportedBinaryExpr(MCSymbolRefExpr::VariantKind VK,
const MCBinaryExpr *BE) {
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
case MCSymbolRefExpr::VK_Mips_ABS_HI:
case MCSymbolRefExpr::VK_Mips_HIGHER:
case MCSymbolRefExpr::VK_Mips_HIGHEST:
break;
default:
return false;
}
// We support expressions of the form "(sym1 binop1 sym2) binop2 const",
// where "binop2 const" is optional.
if (isa<MCBinaryExpr>(BE->getLHS())) {
if (!isa<MCConstantExpr>(BE->getRHS()))
return false;
BE = cast<MCBinaryExpr>(BE->getLHS());
}
return (isa<MCSymbolRefExpr>(BE->getLHS())
&& isa<MCSymbolRefExpr>(BE->getRHS()));
}
const MipsMCExpr*
MipsMCExpr::create(MCSymbolRefExpr::VariantKind VK, const MCExpr *Expr,
MCContext &Ctx) {
VariantKind Kind;
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
Kind = VK_Mips_LO;
break;
case MCSymbolRefExpr::VK_Mips_ABS_HI:
Kind = VK_Mips_HI;
break;
case MCSymbolRefExpr::VK_Mips_HIGHER:
Kind = VK_Mips_HIGHER;
break;
case MCSymbolRefExpr::VK_Mips_HIGHEST:
Kind = VK_Mips_HIGHEST;
break;
default:
llvm_unreachable("Invalid kind!");
}
return new (Ctx) MipsMCExpr(Kind, Expr);
}
void MipsMCExpr::printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const {
switch (Kind) {
default: llvm_unreachable("Invalid kind!");
case VK_Mips_LO: OS << "%lo"; break;
case VK_Mips_HI: OS << "%hi"; break;
case VK_Mips_HIGHER: OS << "%higher"; break;
case VK_Mips_HIGHEST: OS << "%highest"; break;
}
OS << '(';
Expr->print(OS, MAI);
OS << ')';
}
bool
MipsMCExpr::evaluateAsRelocatableImpl(MCValue &Res,
const MCAsmLayout *Layout,
const MCFixup *Fixup) const {
return getSubExpr()->evaluateAsRelocatable(Res, Layout, Fixup);
}
void MipsMCExpr::visitUsedExpr(MCStreamer &Streamer) const {
Streamer.visitUsedExpr(*getSubExpr());
}
| 28.373626 | 80 | 0.636716 | Cwc-Test |
c86489c7f75ba795436fbb5f3f7eb8ad84b1d0f9 | 11,186 | cpp | C++ | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | 1 | 2018-01-17T08:11:17.000Z | 2018-01-17T08:11:17.000Z | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | /*
* Copyright (C) 2010 DiamondCore <http://diamondcore.eu/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "RealmList.h"
#include "Config/Config.h"
#include "Log.h"
#include "AuthSocket.h"
#include "SystemConfig.h"
#include "revision_nr.h"
#include "Util.h"
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <ace/Get_Opt.h>
#include <ace/Dev_Poll_Reactor.h>
#include <ace/ACE.h>
#include <ace/Acceptor.h>
#include <ace/SOCK_Acceptor.h>
#ifdef WIN32
#include "ServiceWin32.h"
char serviceName[] = "LogonServer";
char serviceLongName[] = "DiamondCore Realm service";
char serviceDescription[] = "Massive Network Game Object Server";
/*
* -1 - not in service mode
* 0 - stopped
* 1 - running
* 2 - paused
*/
int m_ServiceStatus = -1;
#endif
bool StartDB();
void UnhookSignals();
void HookSignals();
bool stopEvent = false; ///< Setting it to true stops the server
DatabaseType loginDatabase; ///< Accessor to the realm server database
/// Print out the usage string for this program on the console.
void usage(const char *prog)
{
sLog.outString("Usage: \n %s [<options>]\n"
" -v, --version print version and exist\n\r"
" -c config_file use config_file as configuration file\n\r"
#ifdef WIN32
" Running as service functions:\n\r"
" -s run run as service\n\r"
" -s install install service\n\r"
" -s uninstall uninstall service\n\r"
#endif
,prog);
}
/// Launch the realm server
extern int main(int argc, char **argv)
{
///- Command line parsing
char const* cfg_file = _LOGON_CONFIG;
#ifdef WIN32
char const *options = ":c:s:";
#else
char const *options = ":c:";
#endif
ACE_Get_Opt cmd_opts(argc, argv, options);
cmd_opts.long_option("version", 'v');
int option;
while ((option = cmd_opts()) != EOF)
{
switch (option)
{
case 'c':
cfg_file = cmd_opts.opt_arg();
break;
case 'v':
printf("%s\n", _FULLVERSION);
return 0;
#ifdef WIN32
case 's':
{
const char *mode = cmd_opts.opt_arg();
if (!strcmp(mode, "install"))
{
if (WinServiceInstall())
sLog.outString("Installing service");
return 1;
}
else if (!strcmp(mode, "uninstall"))
{
if (WinServiceUninstall())
sLog.outString("Uninstalling service");
return 1;
}
else if (!strcmp(mode, "run"))
WinServiceRun();
else
{
sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
}
break;
}
#endif
case ':':
sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
usage(argv[0]);
return 1;
default:
sLog.outError("Runtime-Error: bad format of commandline arguments");
usage(argv[0]);
return 1;
}
}
if (!sConfig.SetSource(cfg_file))
{
sLog.outError("Could not find configuration file %s.", cfg_file);
return 1;
}
sLog.Initialize();
sLog.outString( "%s [realm-daemon]", _FULLVERSION);
sLog.outString( "<Ctrl-C> to stop.\n" );
sLog.outString("Using configuration file %s.", cfg_file);
///- Check the version of the configuration file
uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
if (confVersion < _LOGONCONFVERSION)
{
sLog.outError("*****************************************************************************");
sLog.outError(" WARNING: Your LogonServer.conf version indicates your conf file is out of date!");
sLog.outError(" Please check for updates, as your current default values may cause");
sLog.outError(" strange behavior.");
sLog.outError("*****************************************************************************");
clock_t pause = 3000 + clock();
while (pause > clock())
{
}
}
sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
if (SSLeay() < 0x009080bfL)
{
sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
}
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#endif
sLog.outBasic("Max allowed open files is %d", ACE::max_handles());
/// LogonServer PID file creation
std::string pidfile = sConfig.GetStringDefault("PidFile", "");
if (!pidfile.empty())
{
uint32 pid = CreatePIDFile(pidfile);
if (!pid )
{
sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str());
return 1;
}
sLog.outString("Daemon PID: %u\n", pid );
}
///- Initialize the database connection
if (!StartDB())
return 1;
///- Get the list of realms for the server
sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
if (sRealmList.size() == 0)
{
sLog.outError("No valid realms specified.");
return 1;
}
// cleanup query
// set expired bans to inactive
loginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
///- Launch the listening network socket
ACE_Acceptor<AuthSocket, ACE_SOCK_Acceptor> acceptor;
uint16 rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");
ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());
if(acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
{
sLog.outError("LogonServer can not bind to %s:%d", bind_ip.c_str(), rmport);
return 1;
}
///- Catch termination signals
HookSignals();
///- Handle affinity for multiple processors and process priority on Windows
#ifdef WIN32
{
HANDLE hProcess = GetCurrentProcess();
uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
if (Aff > 0)
{
ULONG_PTR appAff;
ULONG_PTR sysAff;
if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
{
ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
if (!curAff)
{
sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff,appAff);
}
else
{
if (SetProcessAffinityMask(hProcess, curAff))
sLog.outString("Using processors (bitmask, hex): %x", curAff);
else
sLog.outError("Can't set used processors (hex): %x", curAff);
}
}
sLog.outString();
}
bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
if (Prio)
{
if (SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
sLog.outString("LogonServer process priority class set to HIGH");
else
sLog.outError("ERROR: Can't set LogonServer process priority class.");
}
}
#endif
// maximum counter for next ping
uint32 numLoops = (sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
uint32 loopCounter = 0;
///- Wait for termination signal
while (!stopEvent)
{
// dont move this outside the loop, the reactor will modify it
ACE_Time_Value interval(0, 100000);
if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
break;
if ((++loopCounter) == numLoops)
{
loopCounter = 0;
sLog.outDetail("Ping MySQL to keep connection alive");
delete loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
}
#ifdef WIN32
if (m_ServiceStatus == 0)
stopEvent = true;
while (m_ServiceStatus == 2)
Sleep(1000);
#endif
}
///- Wait for the delay thread to exit
loginDatabase.HaltDelayThread();
///- Remove signal handling before leaving
UnhookSignals();
sLog.outString("Halting process...");
return 0;
}
/// Handle termination signals
/** Put the global variable stopEvent to 'true' if a termination signal is caught **/
void OnSignal(int s)
{
switch (s)
{
case SIGINT:
case SIGTERM:
stopEvent = true;
break;
#ifdef _WIN32
case SIGBREAK:
stopEvent = true;
break;
#endif
}
signal(s, OnSignal);
}
/// Initialize connection to the database
bool StartDB()
{
std::string dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if (dbstring.empty())
{
sLog.outError("Database not specified");
return false;
}
sLog.outString("Database: %s", dbstring.c_str() );
if (!loginDatabase.Initialize(dbstring.c_str()))
{
sLog.outError("Cannot connect to database");
return false;
}
return true;
}
/// Define hook 'OnSignal' for all termination signals
void HookSignals()
{
signal(SIGINT, OnSignal);
signal(SIGTERM, OnSignal);
#ifdef _WIN32
signal(SIGBREAK, OnSignal);
#endif
}
/// Unhook the signals before leaving
void UnhookSignals()
{
signal(SIGINT, 0);
signal(SIGTERM, 0);
#ifdef _WIN32
signal(SIGBREAK, 0);
#endif
}
/// @}
| 30.150943 | 168 | 0.576792 | Subv |
c8660f5f73268d82e6872869b178203676ec77f5 | 31,827 | hpp | C++ | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | 2 | 2022-03-03T16:34:03.000Z | 2022-03-20T13:08:56.000Z | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | #pragma once
#include "cgp/base/base.hpp"
#include "cgp/containers/buffer_stack/buffer_stack.hpp"
#include "cgp/containers/offset_grid/offset_grid.hpp"
#include <sstream>
#include <iomanip>
/* ************************************************** */
/* Header */
/* ************************************************** */
namespace cgp
{
/** Container for 2D-matrix structure storing elements on stack (fixed size known at compile time)
*
* Elements of matrix_stack are stored contiguously in stack memory as array of array and remain fully compatible with std::array and pointers.
* Elements are stored along rows
* matrix[0] ( 0:[0,0] 1:[0,1] 2:[0,2] ... N2-1:[0,N2-1] )
* matrix[1] ( N2:[1,0] N2+1:[1,1] ... 2*N2-1:[1,N2-1] )
* ...
* matrix[k1] k1*N2+k2:[k1,k2]
* ...
* matrix[N1-1] ( (N1-1)*N2:[N1-1,0] ... N1*N2-1:[N1-1,N2-1] )
**/
template <typename T, int N1, int N2>
struct matrix_stack
{
/** Internal storage as a 1D buffer */
buffer_stack< buffer_stack<T, N2>, N1> data;
/** Constructors */
matrix_stack();
matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements);
matrix_stack(buffer_stack<T, N1* N2> const& elements);
// Construct from a matrix with different size.
// Consider the min between (N1,N1_arg) and (N2,N2_arg)
template <int N1_arg, int N2_arg>
explicit matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M);
matrix_stack(std::initializer_list<T> const& arg);
matrix_stack(std::initializer_list<buffer_stack<T,N1> > const& arg);
static matrix_stack<T, N1, N2> build_identity();
static matrix_stack<T, N1, N2> diagonal(buffer_stack<T, std::min(N1,N2)> const& arg);
/** Total number of elements size = dimension[0] * dimension[1] */
int size() const;
/** Return {N1,N2} */
int2 dimension() const;
/** Fill all elements of the grid_2D with the same element*/
matrix_stack<T, N1, N2>& fill(T const& value);
/** Element access
* Bound checking is performed unless cgp_NO_DEBUG is defined. */
buffer_stack<T, N2> const& operator[](int k1) const;
buffer_stack<T, N2>& operator[](int k1);
buffer_stack<T, N2> const& operator()(int k1) const;
buffer_stack<T, N2>& operator()(int k1);
T const& operator()(int k1, int k2) const;
T& operator()(int k1, int k2);
T const& at_offset(int offset) const;
T& at_offset(int offset);
matrix_stack<T, N1 - 1, N2 - 1> remove_row_column(int k1, int k2) const;
/** Set a block within the matrix from a specific offset
* @block: the matrix to be copied in the current one
* @offset: the offsets where the block has to be writter. Default value are (0,0). The block is written on the top-left corner.
* Conditions:
* offset_1 + N1_arg < N1
* offset_2 + N2_arg < N2
*/
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1 = 0, int offset_2 = 0);
/** Iterators
* Iterators compatible with STL syntax and std::array */
T* begin();
T* end();
T const* begin() const;
T const* end() const;
T const* cbegin() const;
T const* cend() const;
inline T const& at(int k1, int k2) const;
inline T& at(int k1, int k2);
T const& at_unsafe(int k1, int k2) const;
T& at_unsafe(int k1, int k2);
buffer_stack<T, N2> const& at_unsafe(int k1) const;
buffer_stack<T, N2>& at_unsafe(int k1);
T const& at_offset_unsafe(int offset) const;
T& at_offset_unsafe(int offset);
};
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&);
/** Display all elements of the buffer.*/
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v);
/** Convert all elements of the matrix to a string.
* Default behavior: display all elements separated by a space as a 1D buffer
*
* [begin]
* [begin_line] v(0,0) [separator] v(0,1) [separator] ... v(0,N2-1) [end_line]
* [begin_line] v(1,0) [separator] v(1,1) [separator] ... v(1,N2-1) [end_line]
* ...
* [begin_line] v(N1-1,0) [separator] v(N1-1,1) [separator] ... v(N1-1,N2-1) [end_line]
* ...
* [end]
*/
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator = " ", std::string const& begin = "", std::string const& end = "", std::string const& begin_line="", std::string const& end_line=" ");
/** Convert element of the matrix to a string. Default set for pretty 2D display. */
template <typename T, int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator=" ", std::string const& begin="", std::string const& end="", std::string const& begin_line="(", std::string const& end_line=")\n");
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T,N1,N2> const& M);
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T,N1,N2> const& M);
/** Direct compiled-checked access to data */
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data);
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data);
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data);
/** Equality test between grid_2D */
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b);
/** Math operators
* Common mathematical operations between buffers, and scalar or element values. */
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b);
// Unary negation
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m);
// Componentwise multiplication between two matrices with the same size
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
// Matrix vector product
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b);
/** Transposition of matrix */
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m);
/** Trace of a square matrix*/
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m);
/** Componentwise norm : sqrt(sum_(i,j) a_ij^2) */
template <typename T, int N1, int N2> T norm(matrix_stack<T,N1,N2> const& m);
}
/* ************************************************** */
/* IMPLEMENTATION */
/* ************************************************** */
namespace cgp
{
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at(int k1, int k2) const
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at(int k1, int k2)
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::begin() { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::end() { return &at_unsafe(N1-1, N2-1)+1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::begin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::end() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cbegin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cend() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) const { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::at_unsafe(int k1) const { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> buffer_stack<T, N2>& matrix_stack<T, N1, N2>::at_unsafe(int k1) { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) const { return begin()[offset];}
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) { return begin()[offset]; }
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack()
: data()
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements)
:data(elements)
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack<T, N1* N2> const& elements)
: data()
{
int counter = 0;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = elements.at_unsafe(counter);
counter++;
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<T> const& arg)
: data()
{
assert_cgp(arg.size() >= N1 * N2, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = *it_arg;
++it_arg;
}
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<buffer_stack<T, N1> > const& arg)
:data()
{
assert_cgp(arg.size() >= N1, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
data.at_unsafe(k1) = *it_arg;
++it_arg;
}
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>::matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M)
:data()
{
int const N1m = std::min(N1, N1_arg);
int const N2m = std::min(N2, N2_arg);
for (int k1 = 0; k1 < N1m; ++k1)
for (int k2 = 0; k2 < N2m; ++k2)
at_unsafe(k1, k2) = M.at_unsafe(k1, k2);
}
template <typename T, int N1, int N2> int matrix_stack<T, N1, N2>::size() const { return N1 * N2; }
template <typename T, int N1, int N2> int2 matrix_stack<T, N1, N2>::dimension() const { return { N1,N2 }; }
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::fill(T const& value)
{
auto it = begin();
auto const it_end = end();
for (; it != it_end; ++it)
*it = value;
return *this;
}
template <typename T, int N1, int N2>
void check_index_bounds(int index1, int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index1 < 0 || index2 < 0 || index1 >= N1 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index1) + "," + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index1 < 0 || index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N1 == 0 || N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index1 == N1 || index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index1 >= N1 || index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_index_bounds(int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index2 < 0 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - maximal first index is = (" + str(N2-1) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_offset_bounds(int offset, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (offset < 0 || offset >= N1*N2 )
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack.at_offset(" + str(offset) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - the maximal offset is = (" + str(N1*N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (offset < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (offset == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (offset == N1*N2)
{
msg += "\t> Offset reached the maximal size of the buffer \n";
msg += "\t> The maximal possible offset should be (" + str( N1*N2 - 1) + ") \n";
}
else if (offset >= N1*N2 )
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator[](int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator[](int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator()(int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator()(int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::operator()(int k1, int k2) const {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1,k2);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::operator()(int k1, int k2) {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1, k2);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at_offset(int offset) const {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at_offset(int offset) {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1, int offset_2)
{
static_assert(N1_arg < N1, "Block size is too large for the current matrix");
static_assert(N2_arg < N2, "Block size is too large for the current matrix");
assert_cgp(N1_arg + offset_1 < N1, "Block size exceed current matrix size");
assert_cgp(N2_arg + offset_2 < N2, "Block size exceed current matrix size");
for (int k1 = 0; k1 < N1_arg; ++k1) {
int const idx_1 = k1 + offset_1;
for (int k2 = 0; k2 < N2_arg; ++k2) {
int const idx_2 = k2 + offset_2;
at_unsafe(idx_1, idx_2) = block.at_unsafe(k1, k2);
}
}
return *this;
}
}
namespace cgp
{
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&)
{
return "matrix_stack<" + type_str(T()) + "," + str(N1) + "," + str(N2) + ">";
}
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b)
{
if (Na1 != Nb1 || Na2 != Nb2)
return false;
return is_equal(a.data, b.data);
}
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T, N1, N2> const& M)
{
return &get<0,0>(M);
}
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T, N1, N2> const& )
{
return size_in_memory(T{})*N1*N2;
}
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert( (idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data)
{
static_assert((idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert(idx1<N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data)
{
static_assert(idx1 < N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data)
{
static_assert(offset<N1*N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data)
{
static_assert(offset < N1* N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v)
{
return s << v.data;
}
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
s += begin;
for (int k1 = 0; k1 < N1; ++k1) {
s += begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
s += str(v.at_unsafe(k1, k2));
if ( k2 != N2 - 1)
s += separator;
}
s += end_line;
}
s += end;
return s;
}
template <typename T,int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
std::stringstream ss;
ss << begin;
for (int k1 = 0; k1 < N1; ++k1) {
ss << begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
ss <<std::fixed<<std::setprecision(2) << std::setw(7) << M.at(k1,k2);
if ( k2 != N2 - 1 )
ss << separator;
}
ss << end_line;
}
ss << end;
return ss.str();
}
template <typename T, int N1, int N2> std::string str_2D(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
return str(v, separator, begin, end, begin_line, end_line);
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data += b;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data -= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a - b.data;
return res;
}
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b)
{
matrix_stack<T, N, N> res = a * b;
a = res;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b)
{
a.data *= b;
return a;
}
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b)
{
matrix_stack<T, N1, N3> res;
for (int k1 = 0; k1 < N1; ++k1)
{
for (int k3 = 0; k3 < N3; ++k3)
{
T s {};
for (int k2 = 0; k2 < N2; ++k2)
s += a.at(k1, k2) * b.at(k2, k3);
res(k1, k3) = s;
}
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a * b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b)
{
a.data /= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data / b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N1, N2> res = m;
res *= -1.0f;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b.data;
return res;
}
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b)
{
buffer_stack<T, N1> res = {};
for (int k1 = 0; k1 < N1; ++k1) {
auto& current = res.at_unsafe(k1);
for (int k2 = 0; k2 < N2; ++k2)
current += a.at(k1,k2) * b.at(k2);
res.at_unsafe(k1) = current;
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N2, N1> res;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2)
res(k2, k1) = m(k1, k2);
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1 - 1, N2 - 1> matrix_stack<T, N1, N2>::remove_row_column(int idx1, int idx2) const
{
assert_cgp( (idx1 < N1) && (idx2 < N2), "Incorrect index for removing row and column to matrix");
matrix_stack<T, N1 - 1, N2 - 1> res;
int k1_res = 0;
for (int k1 = 0; k1 < N1; ++k1) {
if (k1 != idx1) {
int k2_res = 0;
for (int k2 = 0; k2 < N2; ++k2) {
if (k2 != idx2){
res.at_unsafe(k1_res, k2_res) = at_unsafe(k1, k2);
++k2_res;
}
}
++k1_res;
}
}
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::build_identity()
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> id = {};
for (int k = 0; k < N; ++k)
id.at_unsafe(k, k) = cgp_trait<T>::one();
return id;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::diagonal(buffer_stack<T, std::min(N1, N2)> const& arg)
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> m = {};
for (int k = 0; k < N; ++k)
m.at_unsafe(k, k) = arg[k];
return m;
}
template <typename T, int N1, int N2> T norm(matrix_stack<T, N1, N2> const& m)
{
using std::sqrt;
T s{};
for(int k1=0; k1<N1; ++k1)
for(int k2=0; k2<N2; ++k2)
s += m.at_unsafe(k1,k2);
return sqrt(s);
}
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m)
{
T s = {};
for (int k = 0; k < N; ++k)
s += m(k, k);
return s;
}
}
#include "special_types/special_types.hpp" | 39.003676 | 259 | 0.555786 | drohmer |
c8673e69b1470516e7cba61fb507fb0b9ab9d0c6 | 11,923 | cc | C++ | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 29 | 2020-02-13T17:40:16.000Z | 2022-03-12T14:58:22.000Z | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 20 | 2020-03-20T18:06:31.000Z | 2022-02-25T08:38:08.000Z | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 9 | 2020-03-20T17:29:55.000Z | 2022-02-14T10:15:33.000Z | /*
*
* Copyright (C) 1994-2019, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Gerd Ehlers, Andreas Barth
*
* Purpose: Implementation of class DcmFloatingPointSingle
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/dcmdata/dcvrfl.h"
#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"
// ********************************
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag)
: DcmElement(tag, 0)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag,
const Uint32 len)
: DcmElement(tag, len)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmFloatingPointSingle &old)
: DcmElement(old)
{
}
DcmFloatingPointSingle::~DcmFloatingPointSingle()
{
}
DcmFloatingPointSingle &DcmFloatingPointSingle::operator=(const DcmFloatingPointSingle &obj)
{
DcmElement::operator=(obj);
return *this;
}
int DcmFloatingPointSingle::compare(const DcmElement& rhs) const
{
int result = DcmElement::compare(rhs);
if (result != 0)
{
return result;
}
/* cast away constness (dcmdata is not const correct...) */
DcmFloatingPointSingle* myThis = NULL;
DcmFloatingPointSingle* myRhs = NULL;
myThis = OFconst_cast(DcmFloatingPointSingle*, this);
myRhs = OFstatic_cast(DcmFloatingPointSingle*, OFconst_cast(DcmElement*, &rhs));
/* compare number of values */
unsigned long thisNumValues = myThis->getNumberOfValues();
unsigned long rhsNumValues = myRhs->getNumberOfValues();
if (thisNumValues < rhsNumValues)
{
return -1;
}
else if (thisNumValues > rhsNumValues)
{
return 1;
}
// iterate over all components and test equality */
for (unsigned long count = 0; count < thisNumValues; count++)
{
Float32 val = 0;
if (myThis->getFloat32(val, count).good())
{
Float32 rhsVal = 0;
if (myRhs->getFloat32(rhsVal, count).good())
{
if (val > rhsVal)
{
return 1;
}
else if (val < rhsVal)
{
return -1;
}
}
}
}
/* all values as well as VM equal: objects are equal */
return 0;
}
OFCondition DcmFloatingPointSingle::copyFrom(const DcmObject& rhs)
{
if (this != &rhs)
{
if (rhs.ident() != ident()) return EC_IllegalCall;
*this = OFstatic_cast(const DcmFloatingPointSingle &, rhs);
}
return EC_Normal;
}
// ********************************
DcmEVR DcmFloatingPointSingle::ident() const
{
return EVR_FL;
}
OFCondition DcmFloatingPointSingle::checkValue(const OFString &vm,
const OFBool /*oldFormat*/)
{
/* check VM only, further checks on the floating point values could be added later */
return DcmElement::checkVM(getVM(), vm);
}
unsigned long DcmFloatingPointSingle::getVM()
{
return getNumberOfValues();
}
unsigned long DcmFloatingPointSingle::getNumberOfValues()
{
return OFstatic_cast(unsigned long, getLengthField() / sizeof(Float32));
}
// ********************************
void DcmFloatingPointSingle::print(STD_NAMESPACE ostream &out,
const size_t flags,
const int level,
const char * /*pixelFileName*/,
size_t * /*pixelCounter*/)
{
if (valueLoaded())
{
/* get float data */
Float32 *floatVals;
errorFlag = getFloat32Array(floatVals);
if (floatVals != NULL)
{
/* do not use getVM() because derived classes might always return 1 */
const unsigned long count = getNumberOfValues();
/* double-check length field for valid value */
if (count > 0)
{
const unsigned long maxLength = (flags & DCMTypes::PF_shortenLongTagValues) ?
DCM_OptPrintLineLength : OFstatic_cast(unsigned long, -1) /*unlimited*/;
unsigned long printedLength = 0;
unsigned long newLength = 0;
char buffer[64];
/* print line start with tag and VR */
printInfoLineStart(out, flags, level);
/* print multiple values */
for (unsigned int i = 0; i < count; i++, floatVals++)
{
/* check whether first value is printed (omit delimiter) */
if (i == 0)
OFStandard::ftoa(buffer, sizeof(buffer), *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
else
{
buffer[0] = '\\';
OFStandard::ftoa(buffer + 1, sizeof(buffer) - 1, *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
}
/* check whether current value sticks to the length limit */
newLength = printedLength + OFstatic_cast(unsigned long, strlen(buffer));
if ((newLength <= maxLength) && ((i + 1 == count) || (newLength + 3 <= maxLength)))
{
out << buffer;
printedLength = newLength;
} else {
/* check whether output has been truncated */
if (i + 1 < count)
{
out << "...";
printedLength += 3;
}
break;
}
}
/* print line end with length, VM and tag name */
printInfoLineEnd(out, flags, printedLength);
} else {
/* count can be zero if we have an invalid element with less than four bytes length */
printInfoLine(out, flags, level, "(invalid value)");
}
} else
printInfoLine(out, flags, level, "(no value available)" );
} else
printInfoLine(out, flags, level, "(not loaded)" );
}
// ********************************
OFCondition DcmFloatingPointSingle::getFloat32(Float32 &floatVal,
const unsigned long pos)
{
/* get float data */
Float32 *floatValues = NULL;
errorFlag = getFloat32Array(floatValues);
/* check data before returning */
if (errorFlag.good())
{
if (floatValues == NULL)
errorFlag = EC_IllegalCall;
/* do not use getVM() because derived classes might always return 1 */
else if (pos >= getNumberOfValues())
errorFlag = EC_IllegalParameter;
else
floatVal = floatValues[pos];
}
/* clear value in case of error */
if (errorFlag.bad())
floatVal = 0;
return errorFlag;
}
OFCondition DcmFloatingPointSingle::getFloat32Array(Float32 *&floatVals)
{
floatVals = OFstatic_cast(Float32 *, getValue());
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::getOFString(OFString &value,
const unsigned long pos,
OFBool /*normalize*/)
{
Float32 floatVal;
/* get the specified numeric value */
errorFlag = getFloat32(floatVal, pos);
if (errorFlag.good())
{
/* ... and convert it to a character string */
char buffer[64];
OFStandard::ftoa(buffer, sizeof(buffer), floatVal, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
/* assign result */
value = buffer;
}
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putFloat32(const Float32 floatVal,
const unsigned long pos)
{
Float32 val = floatVal;
errorFlag = changeValue(&val, OFstatic_cast(Uint32, sizeof(Float32) * pos), OFstatic_cast(Uint32, sizeof(Float32)));
return errorFlag;
}
OFCondition DcmFloatingPointSingle::putFloat32Array(const Float32 *floatVals,
const unsigned long numFloats)
{
errorFlag = EC_Normal;
if (numFloats > 0)
{
/* check for valid float data */
if (floatVals != NULL)
errorFlag = putValue(floatVals, OFstatic_cast(Uint32, sizeof(Float32) * OFstatic_cast(size_t, numFloats)));
else
errorFlag = EC_CorruptedData;
} else
putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putString(const char *stringVal)
{
/* determine length of the string value */
const size_t stringLen = (stringVal != NULL) ? strlen(stringVal) : 0;
/* call the real function */
return putString(stringVal, OFstatic_cast(Uint32, stringLen));
}
OFCondition DcmFloatingPointSingle::putString(const char *stringVal,
const Uint32 stringLen)
{
errorFlag = EC_Normal;
/* determine VM of the string */
const unsigned long vm = DcmElement::determineVM(stringVal, stringLen);
if (vm > 0)
{
Float32 *field = new Float32[vm];
OFBool success = OFFalse;
OFString value;
size_t pos = 0;
/* retrieve float data from character string */
for (unsigned long i = 0; (i < vm) && errorFlag.good(); i++)
{
/* get specified value from multi-valued string */
pos = DcmElement::getValueFromString(stringVal, pos, stringLen, value);
if (!value.empty())
{
field[i] = OFstatic_cast(Float32, OFStandard::atof(value.c_str(), &success));
if (!success)
errorFlag = EC_CorruptedData;
} else
errorFlag = EC_CorruptedData;
}
/* set binary data as the element value */
if (errorFlag.good())
errorFlag = putFloat32Array(field, vm);
/* delete temporary buffer */
delete[] field;
} else
errorFlag = putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::verify(const OFBool autocorrect)
{
/* check for valid value length */
if (getLengthField() % (sizeof(Float32)) != 0)
{
errorFlag = EC_CorruptedData;
if (autocorrect)
{
/* strip to valid length */
setLengthField(getLengthField() - (getLengthField() % OFstatic_cast(Uint32, sizeof(Float32))));
}
} else
errorFlag = EC_Normal;
return errorFlag;
}
OFBool DcmFloatingPointSingle::matches(const DcmElement& candidate,
const OFBool enableWildCardMatching) const
{
OFstatic_cast(void,enableWildCardMatching);
if (ident() == candidate.ident())
{
// some const casts to call the getter functions, I do not modify the values, I promise!
DcmFloatingPointSingle& key = OFconst_cast(DcmFloatingPointSingle&,*this);
DcmElement& can = OFconst_cast(DcmElement&,candidate);
Float32 a, b;
for( unsigned long ui = 0; ui < key.getVM(); ++ui )
for( unsigned long uj = 0; uj < can.getVM(); ++uj )
if( key.getFloat32( a, ui ).good() && can.getFloat32( b, uj ).good() && a == b )
return OFTrue;
return key.getVM() == 0;
}
return OFFalse;
}
| 29.8075 | 125 | 0.551875 | henkdemarie |
c8685f738a8597338659385fc01ab15ffc2ee898 | 4,561 | cpp | C++ | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | null | null | null | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 1 | 2020-06-19T18:38:40.000Z | 2020-06-19T18:38:40.000Z | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 6 | 2020-06-04T07:32:59.000Z | 2021-05-17T15:41:30.000Z | #include "GpDateTimeOps.hpp"
#if defined(GP_USE_DATE_TIME)
#include <date/date.h> //TODO: remove with c++20
namespace GPlatform {
const microseconds_t GpDateTimeOps::sStartSteadyTS = GpDateTimeOps::SSteadyTS_us();
const GpArray<std::string, GpDateTimeFormat::SCount().As<size_t>()> GpDateTimeOps::sFormats =
{
"%FT%X+00:00", //ISO_8601: 2021-01-11T20:15:31+00:00
"%a, %d %b %Y %X +0000", //RFC_2822: Mon, 11 Jan 2021 20:15:31 +0000
"%F %X", //STD_DATE_TIME: 2021-01-11 20:15:31
"%FT%X", //STD_DATE_TIME_T,//2021-01-11T20:15:31
"%F", //STD_DATE: 2021-01-11
"%X" //STD_TIME: 20:15:31
};
unix_ts_ms_t GpDateTimeOps::SUnixTS_ms (void) noexcept
{
const auto val = std::chrono::system_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTS_s (void) noexcept
{
return SUnixTS_ms();
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
std::istringstream in{std::string(aStr.AsStringView())};
date::sys_time<std::chrono::milliseconds> tp;
in >> date::parse(std::string(aFormat), tp);
const auto val = tp.time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
return SUnixTsFromStr_ms(aStr, aFormat);
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
/*std::chrono::hh_mm_ss GpDateTimeOps::SUnixTsToHH_MM_SS (const unix_ts_ms_t aTs) noexcept
{
?
}*/
/*hours_t GpDateTimeOps::SUnixTsToHH (const unix_ts_ms_t aTs) noexcept
{
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
date::hh_mm_ss h(tp.time_since_epoch());
return hours_t::SMake(h.hours().count());
}*/
microseconds_t GpDateTimeOps::SSteadyTS_us (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
milliseconds_t GpDateTimeOps::SSteadyTS_ms (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return milliseconds_t::SMake(milliseconds_t::value_type(cnt));
}
seconds_t GpDateTimeOps::SSteadyTS_s (void) noexcept
{
return SSteadyTS_ms();
}
microseconds_t GpDateTimeOps::SHighResTS_us (void) noexcept
{
const auto val = std::chrono::high_resolution_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
std::string_view aFormat
)
{
std::ostringstream out;
//https://howardhinnant.github.io/date/date.html
//https://gitter.im/HowardHinnant/date?at=5e404b1fb612cc7bb1588132
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
out << date::format(std::string(aFormat), tp);
return out.str();
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
std::string_view aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), aFormat);
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs, sFormats.at(aFormat));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), sFormats.at(aFormat));
}
}//GPlatform
#endif//#if defined(GP_USE_DATE_TIME)
| 27.14881 | 94 | 0.653804 | ITBear |
c86b31acbddd68eea5aa5ebc1869399eeee3936a | 8,337 | cpp | C++ | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | #include "../World.h"
#include "../../Engine/Math.h"
#include "../Components/CBrain.h"
#include "../Entities/HeadersEntities.h"
#include "../Components/CWeapon.h"
#include "../UI/WLifebar.h"
#include "../Components/CAnimation.h"
#include "../../Engine/Audio/Audiosource.h"
#include "../Scene.h"
#include "Behaviors.h"
/* BEHAVIORS */
// ATTACK
Ptr<Attack> Attack::Create(Ptr<CBrain> BrainComponent)
{
return new Attack(BrainComponent);
}
Attack::Attack(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Attack::~Attack()
{
mOwnerBrain = nullptr;
}
Status Attack::Update(float Step)
{
// Try to attack with the secondary weapon (more powerful)
// If not, then try to attack with the primary weapon
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr)
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else if(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else
return eFail;
}
else
{
// Weapon in Cooldown
return eFail;
}
return eInvalid;
}
// MOVEMENT
Ptr<WantToMove> WantToMove::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new WantToMove(BrainComponent, TargetReachedRadius);
}
WantToMove::WantToMove(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
}
WantToMove::~WantToMove()
{
mOwnerBrain = nullptr;
}
Status WantToMove::Update(float Step)
{
// Only move if not inside the acceptance radius
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
return eFail;
else
return eSuccess;
}
return eInvalid;
}
Ptr<MoveToTarget> MoveToTarget::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new MoveToTarget(BrainComponent, TargetReachedRadius);
}
MoveToTarget::MoveToTarget(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
mAbortBehaviorTimer = 10.0f;
}
MoveToTarget::~MoveToTarget()
{
mOwnerBrain = nullptr;
}
Status MoveToTarget::Update(float Step)
{
if (mOwnerBrain != nullptr)
{
// In case the MoveTo behavior went wrong, abort it
if (mContAbortBehaviorTimer >= mAbortBehaviorTimer)
{
mOwnerBrain->SelectNewTargetPosition();
return eInvalid;
}
else if (World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
// Check if entity is inside the acceptance radius
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
{
// If inside acceptance radius, activate the linear inertia to decelerate
if (!mOwnerBrain->GetAILinearInertiaActivated())
{
mOwnerBrain->SetAILinearInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateLinearInertia();
}
return eSuccess;
}
else
{
// Set a linear steering on forward vector
mOwnerBrain->SetAILinearInertiaActivated(false);
mOwnerBrain->GetMyEntity()->DeactivateLinearInertia();
mOwnerBrain->GetMyEntity()->SetLinearSteering(vec2(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc(), mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc()));
return eRunning;
}
}
}
return eInvalid;
}
// TARGETING
Ptr<RotateToTarget> RotateToTarget::Create(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
return new RotateToTarget(BrainComponent, TargetingOpponent, TargetReachedValue);
}
RotateToTarget::RotateToTarget(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
mOwnerBrain = BrainComponent;
mTargetReachedValue = TargetReachedValue;
mStatus = eInvalid;
mTargetingOpponent = TargetingOpponent;
}
RotateToTarget::~RotateToTarget()
{
mOwnerBrain = nullptr;
}
Status RotateToTarget::Update(float Step)
{
if (mTargetingOpponent && !World::IsEntityValid(mOwnerBrain->GetMyOpponent().UpCast<Entity>()))
{
return eInvalid;
}
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()))
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (mOwnerBrain->GetNormDirectionToTarget(mTargetingOpponent) > 0)
{
// Calculate the angle from entity to target
float NewAngle = DegACos(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x + mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y);
if (NewAngle < mTargetReachedValue)
{
// If angle is minor acceptance value, activate angular inertia
mOwnerBrain->GetMyEntity()->SetAngularSteering(0.0f);
if (!mOwnerBrain->GetAIAngularInertiaActivated())
{
mOwnerBrain->SetAIAngularInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateAngularInertia();
}
return eSuccess;
}
else
{
// In case the entity has to turn, first get the turn direction (left/right) and then set an angular steering
float CrossProd = mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y - mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x;
int8 TurnDirection = 1;
if (CrossProd > 0)
TurnDirection = -1;
mOwnerBrain->GetMyEntity()->SetTurnDirection(TurnDirection);
mOwnerBrain->GetMyEntity()->DeactivateAngularInertia();
mOwnerBrain->SetAIAngularInertiaActivated(false);
mOwnerBrain->GetMyEntity()->SetAngularSteering(TurnDirection * mOwnerBrain->GetMyEntity()->GetMaxAngularAcc());
return eRunning;
}
}
}
}
return eInvalid;
}
// IDLE
Ptr<Idle> Idle::Create(Ptr<CBrain> BrainComponent)
{
return new Idle(BrainComponent);
}
Idle::Idle(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Idle::~Idle()
{
mOwnerBrain = nullptr;
}
Status Idle::Update(float Step)
{
return eSuccess;
} | 36.565789 | 264 | 0.652993 | tomasmartinsantos |
c86f426648f07506a6a67907139bdbc0b35cc4de | 2,242 | cpp | C++ | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | 5 | 2018-09-09T21:01:57.000Z | 2022-03-27T10:01:27.000Z | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | null | null | null | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | 5 | 2018-04-03T01:45:23.000Z | 2021-05-14T08:23:01.000Z | //****************************************
//effectpal.cpp
//****************************************
/*
Copyright 1999, Be Incorporated. All Rights Reserved.
This file may be used under the terms of the Be Sample Code License.
*/
#include <image.h>
#include "effectpal.h"
#include "effect.h"
#include <Application.h>
#include <Roster.h>
#include <Path.h>
#include <Directory.h>
#include <stdio.h>
//****************************************
//EffectPal class functions
//constructor
EffectPal::EffectPal( BRect frame, const char *title, window_type type, uint32 flags,
uint32 workspaces )
: BWindow( frame, title, type, flags, workspaces )
{
}
//destructor
EffectPal::~EffectPal()
{
}
//Init
void EffectPal::Init( void )
{
image_id addonId;
status_t err = B_NO_ERROR;
Effect* peffect = NULL;
BPoint point(0,0), apoint;
Effect* (*NewEffect)( image_id ); //addon function prototype
app_info info;
BPath path;
//look in app directory for effects
be_app->GetAppInfo(&info);
BEntry entry(&info.ref);
entry.GetPath(&path);
path.GetParent(&path);
path.Append("Effects");
BDirectory dir( path.Path() );
//load all effects
while( err == B_NO_ERROR ){
err = dir.GetNextEntry( (BEntry*)&entry, TRUE );
if( entry.InitCheck() != B_NO_ERROR ){
break;
}
if( entry.GetPath(&path) != B_NO_ERROR ){
printf( "entry.GetPath failed\n" );
}else{
addonId = load_add_on( path.Path() );
if( addonId < 0 ){
printf( "load_add_on( %s ) failed\n", path.Path() );
}else{
printf( "load_add_on( %s ) successful!\n", path.Path() );
if( get_image_symbol( addonId,
"NewEffect",
B_SYMBOL_TYPE_TEXT,
(void **)&NewEffect) ){
printf( "get_image_symbol( NewEffect ) failed\n" );
unload_add_on( addonId );
}else{
peffect = (*NewEffect)( addonId );
if( !peffect ){
printf( "failed to create new effect\n" );
}else{
peffect->Init( this, point );
peffect->GetButtonSize( (BPoint*) &apoint );
point.y += apoint.y;
}
}
}
}
}
}
bool EffectPal::QuitRequested()
{
be_app->PostMessage(B_QUIT_REQUESTED);
return(true);
}
//**************************************** | 23.6 | 86 | 0.580285 | return |
c872e430fe26113b027e010d5cedda4416119a14 | 492 | cpp | C++ | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | spompelio/qzxing | cfc728583b867e157bd27e8b7c239c05a081e562 | [
"Apache-2.0"
] | 608 | 2015-02-21T22:31:37.000Z | 2022-03-31T05:05:36.000Z | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | wqsemc/qzxing | f0a78867d697fd271528007c7b4c67e8fce75f90 | [
"Apache-2.0"
] | 512 | 2015-01-06T17:59:31.000Z | 2022-03-31T13:21:49.000Z | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | wqsemc/qzxing | f0a78867d697fd271528007c7b4c67e8fce75f90 | [
"Apache-2.0"
] | 114 | 2015-01-17T14:32:52.000Z | 2022-03-20T13:14:07.000Z | #include "AI01320xDecoder.h"
namespace zxing {
namespace oned {
namespace rss {
AI01320xDecoder::AI01320xDecoder(Ref<BitArray> information)
: AI013x0xDecoder(information)
{
}
void AI01320xDecoder::addWeightCode(String &buf, int weight)
{
if (weight < 10000) {
buf.append("(3202)");
} else {
buf.append("(3203)");
}
}
int AI01320xDecoder::checkWeight(int weight)
{
if (weight < 10000) {
return weight;
}
return weight - 10000;
}
}
}
}
| 14.909091 | 60 | 0.636179 | spompelio |
c873c2e80b0db915cdd2a7e51e677fe35ea12e47 | 532 | cpp | C++ | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int a, b;
cin >> a >> b;
vector<int> sequence(1, 1);
int sumRange = 0;
while (sequence.size() < 1000) {
int lastNumber = sequence.back();
for (int i = 0; i <= lastNumber; i++) {
sequence.push_back(lastNumber + 1);
}
}
for (int i = a - 1; i < b; i++) {
sumRange += sequence[i];
}
cout << sumRange << "\n";
return 0;
} | 17.16129 | 47 | 0.505639 | nbsp1221 |
c875e2ac5342ece0efb934a1c9c3f23ea48e638c | 1,303 | cpp | C++ | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | null | null | null | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | null | null | null | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | 2 | 2020-11-28T05:59:16.000Z | 2021-03-26T14:10:58.000Z | #include <bits/stdc++.h>
using namespace std;
//function to calculate range for given set of numeric data
template <typename T>
double range(T arr[], int start, int end)
{
double max = arr[start], min = arr[start];
for (int i = start; i < end; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
return max - min;
}
//function to calculate variance with respect to given mean for given range of numeric data types
template <typename T>
double variance(T arr[], int start, int end, double mean)
{
double temp, sum = 0;
for (int i = start; i < end; i++)
{
temp = mean - arr[i];
sum += (temp * temp);
}
return sum / (end - start);
}
//function to calculate standard deviation with respect to given mean for given range of numeric data types
template <typename T>
double standard_deviation(T arr[], int start, int end, double mean)
{
return sqrt(variance(arr, start, end, mean));
}
int main()
{
int i, n = 10;
int arr[] = {1, 2, 3, 4, 4, 6, 7, 8, 8, 10};
cout << "Range = " << range(arr, 0, n) << "\n";
cout << "Variance with respect to 5 = " << variance(arr, 0, n, 5) << "\n";
cout << "Standard Deviation with respect to 5 = " << standard_deviation(arr, 0, n, 5);
} | 31.02381 | 107 | 0.589409 | praharshjain |
c87be2746ba9c7e42f8dbd9b3a6818b5d9d6fca1 | 847 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/ETimeDilationOverride.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/TimeDilation_NodeTypeParam.hpp>
namespace RED4ext
{
namespace quest { struct TimeDilation_Operation; }
namespace quest {
struct TimeDilation_Player : quest::TimeDilation_NodeTypeParam
{
static constexpr const char* NAME = "questTimeDilation_Player";
static constexpr const char* ALIAS = NAME;
Handle<quest::TimeDilation_Operation> operation; // 30
quest::ETimeDilationOverride globalTimeDilationOverride; // 40
uint8_t unk44[0x48 - 0x44]; // 44
};
RED4EXT_ASSERT_SIZE(TimeDilation_Player, 0x48);
} // namespace quest
} // namespace RED4ext
| 30.25 | 83 | 0.780401 | jackhumbert |
c87c33e1e2775720bd69091add608f6e4ec6ce87 | 17,342 | cpp | C++ | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | #include "token_type.hpp"
#include <string>
#include <unordered_map>
#include <cassert>
#include <cstring>
namespace mt {
TokenType from_symbol(std::string_view s) {
static std::unordered_map<std::string, TokenType> symbol_map{
{"(", TokenType::left_parens},
{")", TokenType::right_parens},
{"[", TokenType::left_bracket},
{"]", TokenType::right_bracket},
{"{", TokenType::left_brace},
{"}", TokenType::right_brace},
{"=", TokenType::equal},
{"==", TokenType::equal_equal},
{"~=", TokenType::not_equal},
{"<", TokenType::less},
{">", TokenType::greater},
{"<=", TokenType::less_equal},
{">=", TokenType::greater_equal},
{"~", TokenType::tilde},
{":", TokenType::colon},
{";", TokenType::semicolon},
{".", TokenType::period},
{",", TokenType::comma},
{"+", TokenType::plus},
{"-", TokenType::minus},
{"*", TokenType::asterisk},
{"/", TokenType::forward_slash},
{"\\", TokenType::back_slash},
{"^", TokenType::carat},
{".*", TokenType::dot_asterisk},
{"./", TokenType::dot_forward_slash},
{".\\", TokenType::dot_back_slash},
{".^", TokenType::dot_carat},
{"@", TokenType::at},
{"\n", TokenType::new_line},
{"?", TokenType::question},
{"'", TokenType::apostrophe},
{"\"", TokenType::quote},
{"|", TokenType::vertical_bar},
{"&", TokenType::ampersand},
{"||", TokenType::double_vertical_bar},
{"&&", TokenType::double_ampersand},
{"break", TokenType::keyword_break},
{"case", TokenType::keyword_case},
{"catch", TokenType::keyword_catch},
{"classdef", TokenType::keyword_classdef},
{"continue", TokenType::keyword_continue},
{"else", TokenType::keyword_else},
{"elseif", TokenType::keyword_elseif},
{"end", TokenType::keyword_end},
{"for", TokenType::keyword_for},
{"function", TokenType::keyword_function},
{"fun", TokenType::keyword_fun_type},
{"global", TokenType::keyword_global},
{"if", TokenType::keyword_if},
{"otherwise", TokenType::keyword_otherwise},
{"parfor", TokenType::keyword_parfor},
{"persistent", TokenType::keyword_persistent},
{"return", TokenType::keyword_return},
{"spmd", TokenType::keyword_spmd},
{"switch", TokenType::keyword_switch},
{"try", TokenType::keyword_try},
{"while", TokenType::keyword_while},
{"enumeration", TokenType::keyword_enumeration},
{"events", TokenType::keyword_events},
{"methods", TokenType::keyword_methods},
{"properties", TokenType::keyword_properties},
{"import", TokenType::keyword_import},
{"begin", TokenType::keyword_begin},
{"export", TokenType::keyword_export},
{"given", TokenType::keyword_given},
{"let", TokenType::keyword_let},
{"namespace", TokenType::keyword_namespace},
{"struct", TokenType::keyword_struct},
{"record", TokenType::keyword_record},
{"@T", TokenType::type_annotation_macro},
{"::", TokenType::double_colon},
{"declare", TokenType::keyword_declare},
{"constructor", TokenType::keyword_constructor},
{"list", TokenType::keyword_list},
{"cast", TokenType::keyword_cast},
{"presume", TokenType::keyword_presume}
};
const auto it = symbol_map.find(std::string(s));
if (it == symbol_map.end()) {
return TokenType::null;
} else {
return it->second;
}
}
const char* to_symbol(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "(";
case TokenType::right_parens:
return ")";
case TokenType::left_brace:
return "{";
case TokenType::right_brace:
return "}";
case TokenType::left_bracket:
return "[";
case TokenType::right_bracket:
return "]";
// Punct
case TokenType::ellipsis:
return "...";
case TokenType::equal:
return "=";
case TokenType::equal_equal:
return "==";
case TokenType::not_equal:
return "~=";
case TokenType::less:
return "<";
case TokenType::greater:
return ">";
case TokenType::less_equal:
return "<=";
case TokenType::greater_equal:
return ">=";
case TokenType::tilde:
return "~";
case TokenType::colon:
return ":";
case TokenType::double_colon:
return "::";
case TokenType::semicolon:
return ";";
case TokenType::period:
return ".";
case TokenType::comma:
return ",";
case TokenType::plus:
return "+";
case TokenType::minus:
return "-";
case TokenType::asterisk:
return "*";
case TokenType::forward_slash:
return "/";
case TokenType::back_slash:
return "\\";
case TokenType::carat:
return "^";
case TokenType::dot_asterisk:
return ".*";
case TokenType::dot_forward_slash:
return "./";
case TokenType::dot_back_slash:
return ".\\";
case TokenType::dot_carat:
return ".^";
case TokenType::dot_apostrophe:
return ".'";
case TokenType::at:
return "@";
case TokenType::new_line:
return "\n";
case TokenType::question:
return "?";
case TokenType::apostrophe:
return "'";
case TokenType::quote:
return "\"";
case TokenType::vertical_bar:
return "|";
case TokenType::ampersand:
return "&";
case TokenType::double_vertical_bar:
return "||";
case TokenType::double_ampersand:
return "&&";
case TokenType::op_end:
return "end";
// Ident + literals
case TokenType::identifier:
return "<identifier>";
case TokenType::char_literal:
return "<char_literal>";
case TokenType::string_literal:
return "<string_literal>";
case TokenType::number_literal:
return "<number_literal>";
// Keywords
case TokenType::keyword_break:
return "break";
case TokenType::keyword_case:
return "case";
case TokenType::keyword_catch:
return "catch";
case TokenType::keyword_classdef:
return "classdef";
case TokenType::keyword_continue:
return "continue";
case TokenType::keyword_else:
return "else";
case TokenType::keyword_elseif:
return "elseif";
case TokenType::keyword_end:
return "end";
case TokenType::keyword_for:
return "for";
case TokenType::keyword_function:
return "function";
case TokenType::keyword_global:
return "global";
case TokenType::keyword_if:
return "if";
case TokenType::keyword_otherwise:
return "otherwise";
case TokenType::keyword_parfor:
return "parfor";
case TokenType::keyword_persistent:
return "persistent";
case TokenType::keyword_return:
return "return";
case TokenType::keyword_spmd:
return "spmd";
case TokenType::keyword_switch:
return "switch";
case TokenType::keyword_try:
return "try";
case TokenType::keyword_while:
return "while";
// Class keywords
case TokenType::keyword_enumeration:
return "enumeration";
case TokenType::keyword_events:
return "events";
case TokenType::keyword_methods:
return "methods";
case TokenType::keyword_properties:
return "properties";
case TokenType::keyword_import:
return "import";
// Typing keywords
case TokenType::keyword_begin:
return "begin";
case TokenType::keyword_export:
return "export";
case TokenType::keyword_given:
return "given";
case TokenType::keyword_let:
return "let";
case TokenType::keyword_namespace:
return "namespace";
case TokenType::keyword_struct:
return "struct";
case TokenType::keyword_record:
return "record";
case TokenType::keyword_function_type:
return "function";
case TokenType::keyword_fun_type:
return "fun";
case TokenType::keyword_end_type:
return "end";
case TokenType::type_annotation_macro:
return "@T";
case TokenType::keyword_declare:
return "declare";
case TokenType::keyword_constructor:
return "constructor";
case TokenType::keyword_list:
return "list";
case TokenType::keyword_cast:
return "cast";
case TokenType::keyword_presume:
return "presume";
case TokenType::null:
return "<null>";
}
assert(false);
return "<null>";
}
const char* to_string(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "left_parens";
case TokenType::right_parens:
return "right_parens";
case TokenType::left_brace:
return "left_brace";
case TokenType::right_brace:
return "right_brace";
case TokenType::left_bracket:
return "left_bracket";
case TokenType::right_bracket:
return "right_bracket";
// Punct
case TokenType::ellipsis:
return "ellipsis";
case TokenType::equal:
return "equal";
case TokenType::equal_equal:
return "equal_equal";
case TokenType::not_equal:
return "not_equal";
case TokenType::less:
return "less";
case TokenType::greater:
return "greater";
case TokenType::less_equal:
return "less_equal";
case TokenType::greater_equal:
return "greater_equal";
case TokenType::tilde:
return "tilde";
case TokenType::colon:
return "colon";
case TokenType::double_colon:
return "double_colon";
case TokenType::semicolon:
return "semicolon";
case TokenType::period:
return "period";
case TokenType::comma:
return "comma";
case TokenType::plus:
return "plus";
case TokenType::minus:
return "minus";
case TokenType::asterisk:
return "asterisk";
case TokenType::forward_slash:
return "forward_slash";
case TokenType::back_slash:
return "back_slash";
case TokenType::carat:
return "carat";
case TokenType::dot_apostrophe:
return "dot_apostrophe";
case TokenType::dot_asterisk:
return "dot_asterisk";
case TokenType::dot_forward_slash:
return "dot_forward_slash";
case TokenType::dot_back_slash:
return "dot_backslash";
case TokenType::dot_carat:
return "dot_carat";
case TokenType::at:
return "at";
case TokenType::new_line:
return "new_line";
case TokenType::question:
return "question";
case TokenType::apostrophe:
return "apostrophe";
case TokenType::quote:
return "quote";
case TokenType::vertical_bar:
return "vertical_bar";
case TokenType::ampersand:
return "ampersand";
case TokenType::double_vertical_bar:
return "double_vertical_bar";
case TokenType::double_ampersand:
return "double_ampersand";
case TokenType::op_end:
return "op_end";
// Ident + literals
case TokenType::identifier:
return "identifier";
case TokenType::char_literal:
return "char_literal";
case TokenType::string_literal:
return "string_literal";
case TokenType::number_literal:
return "number_literal";
// Keywords
case TokenType::keyword_break:
return "keyword_break";
case TokenType::keyword_case:
return "keyword_case";
case TokenType::keyword_catch:
return "keyword_catch";
case TokenType::keyword_classdef:
return "keyword_classdef";
case TokenType::keyword_continue:
return "keyword_continue";
case TokenType::keyword_else:
return "keyword_else";
case TokenType::keyword_elseif:
return "keyword_elseif";
case TokenType::keyword_end:
return "keyword_end";
case TokenType::keyword_for:
return "keyword_for";
case TokenType::keyword_function:
return "keyword_function";
case TokenType::keyword_global:
return "keyword_global";
case TokenType::keyword_if:
return "keyword_if";
case TokenType::keyword_otherwise:
return "keyword_otherwise";
case TokenType::keyword_parfor:
return "keyword_parfor";
case TokenType::keyword_persistent:
return "keyword_persistent";
case TokenType::keyword_return:
return "keyword_return";
case TokenType::keyword_spmd:
return "keyword_spmd";
case TokenType::keyword_switch:
return "keyword_switch";
case TokenType::keyword_try:
return "keyword_try";
case TokenType::keyword_while:
return "keyword_while";
// Class keywords
case TokenType::keyword_enumeration:
return "keyword_enumeration";
case TokenType::keyword_events:
return "keyword_events";
case TokenType::keyword_methods:
return "keyword_methods";
case TokenType::keyword_properties:
return "keyword_properties";
case TokenType::keyword_import:
return "keyword_import";
// Typing keywords
case TokenType::keyword_begin:
return "keyword_begin";
case TokenType::keyword_export:
return "keyword_export";
case TokenType::keyword_given:
return "keyword_given";
case TokenType::keyword_let:
return "keyword_let";
case TokenType::keyword_namespace:
return "keyword_namespace";
case TokenType::keyword_struct:
return "keyword_struct";
case TokenType::keyword_record:
return "keyword_record";
case TokenType::keyword_function_type:
return "keyword_function_type";
case TokenType::keyword_fun_type:
return "keyword_fun_type";
case TokenType::keyword_end_type:
return "keyword_end_type";
case TokenType::keyword_declare:
return "keyword_declare";
case TokenType::keyword_constructor:
return "keyword_constructor";
case TokenType::keyword_list:
return "keyword_list";
case TokenType::keyword_cast:
return "keyword_cast";
case TokenType::keyword_presume:
return "keyword_presume";
case TokenType::type_annotation_macro:
return "type_annotation_macro";
case TokenType::null:
return "null";
}
assert(false);
return "null";
}
bool unsafe_represents_keyword(TokenType type) {
// @TODO: Implement this more carefully.
// std::strlen("keyword")
return std::strncmp("keyword", to_string(type), 7) == 0;
}
bool represents_literal(TokenType type) {
return type == TokenType::string_literal || type == TokenType::char_literal ||
type == TokenType::number_literal;
}
bool represents_expr_terminator(TokenType type) {
return represents_stmt_terminator(type) || represents_grouping_terminator(type) || type == TokenType::equal;
}
bool represents_stmt_terminator(TokenType type) {
return type == TokenType::semicolon || type == TokenType::comma || type == TokenType::new_line ||
type == TokenType::null;
}
bool represents_grouping_component(TokenType type) {
const auto min = static_cast<unsigned int>(TokenType::left_parens);
const auto max = static_cast<unsigned int>(TokenType::right_bracket);
const auto t = static_cast<unsigned int>(type);
return t >= min && t <= max;
}
bool represents_grouping_initiator(TokenType type) {
return type == TokenType::left_parens || type == TokenType::left_brace ||
type == TokenType::left_bracket;
}
bool represents_grouping_terminator(TokenType type) {
return type == TokenType::right_parens || type == TokenType::right_brace ||
type == TokenType::right_bracket;
}
bool represents_binary_operator(TokenType type) {
// @Hack, first 21 token types are binary operators.
return static_cast<unsigned int>(type) < 21;
}
bool represents_unary_operator(TokenType type) {
return represents_postfix_unary_operator(type) || represents_prefix_unary_operator(type);
}
bool represents_prefix_unary_operator(TokenType type) {
return type == TokenType::plus || type == TokenType::minus || type == TokenType::tilde;
}
bool can_precede_prefix_unary_operator(TokenType type) {
switch (type) {
case TokenType::identifier:
case TokenType::string_literal:
case TokenType::char_literal:
case TokenType::number_literal:
case TokenType::keyword_end:
case TokenType::op_end:
return false;
default:
return !represents_grouping_terminator(type) && !represents_postfix_unary_operator(type);
}
}
bool can_be_skipped_in_classdef_block(TokenType type) {
switch (type) {
case TokenType::comma:
case TokenType::semicolon:
case TokenType::new_line:
return true;
default:
return false;
}
}
bool can_precede_postfix_unary_operator(TokenType type) {
return represents_literal(type) || represents_grouping_terminator(type) ||
type == TokenType::identifier || type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
bool represents_postfix_unary_operator(TokenType type) {
return type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
std::array<TokenType, 3> grouping_terminators() {
return {{TokenType::right_parens, TokenType::right_bracket, TokenType::right_bracket}};
}
TokenType grouping_terminator_for(TokenType initiator) {
switch (initiator) {
case TokenType::left_brace:
return TokenType::right_brace;
case TokenType::left_bracket:
return TokenType::right_bracket;
case TokenType::left_parens:
return TokenType::right_parens;
default:
assert(false && "No grouping terminator for type.");
return TokenType::null;
}
}
} | 30.16 | 110 | 0.661227 | nfagan |
c87cb139a11bc2d79c7fc9a779c71f2cebb692e3 | 385 | hpp | C++ | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 38 | 2020-04-09T03:17:16.000Z | 2022-03-21T06:33:05.000Z | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 6 | 2020-05-19T10:56:31.000Z | 2022-01-24T07:21:40.000Z | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 15 | 2020-06-26T09:31:32.000Z | 2021-09-01T15:22:00.000Z | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
namespace ARDUINOJSON_NAMESPACE {
struct NestingLimit {
NestingLimit() : value(ARDUINOJSON_DEFAULT_NESTING_LIMIT) {}
explicit NestingLimit(uint8_t n) : value(n) {}
uint8_t value;
};
} // namespace ARDUINOJSON_NAMESPACE
| 21.388889 | 63 | 0.727273 | wwmoo7 |
c87ec352920b8502108500d9aea45a3797591b07 | 1,373 | cpp | C++ | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 8,148 | 2017-10-29T10:51:20.000Z | 2022-03-31T12:52:51.000Z | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 2,270 | 2017-12-04T12:08:13.000Z | 2022-03-31T19:56:41.000Z | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 732 | 2017-11-28T13:08:15.000Z | 2022-03-31T21:05:59.000Z | #include <iostream>
#include <string>
#include <d3dcompiler.h>
#include <shellapi.h>
#include <windows.h>
#include <windowsx.h>
#include "../../src/util/com/com_pointer.h"
using namespace dxvk;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow) {
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(
GetCommandLineW(), &argc);
if (argc < 2 || argc > 3) {
std::cerr << "Usage: dxbc-disasm input.dxbc [output]" << std::endl;
return 1;
}
Com<ID3DBlob> assembly;
Com<ID3DBlob> binary;
// input file
if (FAILED(D3DReadFileToBlob(argv[1], &binary))) {
std::cerr << "Failed to read shader" << std::endl;
return 1;
}
HRESULT hr = D3DDisassemble(
binary->GetBufferPointer(),
binary->GetBufferSize(),
D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING, nullptr,
&assembly);
if (FAILED(hr)) {
std::cerr << "Failed to disassemble shader" << std::endl;
return 1;
}
// output file variant
if (argc == 3 && FAILED(D3DWriteBlobToFile(assembly.ptr(), argv[2], 1))) {
std::cerr << "Failed to write shader" << std::endl;
return 1;
}
// stdout variant
if (argc == 2) {
std::string data((const char *)assembly->GetBufferPointer(), assembly->GetBufferSize());
std::cout << data;
}
return 0;
}
| 22.508197 | 92 | 0.614712 | lacc97 |
c88331cf9e5b35677d9745bebea844389a49b0e9 | 12,373 | cpp | C++ | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2021-08-04T13:34:33.000Z | 2021-08-04T13:34:33.000Z | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2020-08-30T10:57:19.000Z | 2020-08-30T10:57:19.000Z | /*************************************************************************/
/* resource_importer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "resource_importer.h"
#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/variant/variant_parser.h"
bool ResourceFormatImporter::SortImporterByName::operator()(const Ref<ResourceImporter> &p_a, const Ref<ResourceImporter> &p_b) const {
return p_a->get_importer_name() < p_b->get_importer_name();
}
Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type, bool *r_valid) const {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
if (r_valid) {
*r_valid = false;
}
return err;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
if (r_valid) {
*r_valid = true;
}
int lines = 0;
String error_text;
bool path_found = false; //first match must have priority
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
if (assign != String()) {
if (!path_found && assign.begins_with("path.") && r_path_and_type.path == String()) {
String feature = assign.get_slicec('.', 1);
if (OS::get_singleton()->has_feature(feature)) {
r_path_and_type.path = value;
path_found = true; //first match must have priority
}
} else if (!path_found && assign == "path") {
r_path_and_type.path = value;
path_found = true; //first match must have priority
} else if (assign == "type") {
r_path_and_type.type = ClassDB::get_compatibility_remapped_class(value);
} else if (assign == "importer") {
r_path_and_type.importer = value;
} else if (assign == "group_file") {
r_path_and_type.group_file = value;
} else if (assign == "metadata") {
r_path_and_type.metadata = value;
} else if (assign == "valid") {
if (r_valid) {
*r_valid = value;
}
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
if (r_path_and_type.path == String() || r_path_and_type.type == String()) {
return ERR_FILE_CORRUPT;
}
return OK;
}
RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
if (r_error) {
*r_error = err;
}
return RES();
}
RES res = ResourceLoader::_load(pat.path, p_path, pat.type, p_no_cache, r_error, p_use_sub_threads, r_progress);
#ifdef TOOLS_ENABLED
if (res.is_valid()) {
res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used
res->set_import_path(pat.path);
}
#endif
return res;
}
void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const {
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
if (p_type == "") {
get_recognized_extensions(p_extensions);
return;
}
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (!ClassDB::is_parent_class(res_type, p_type)) {
continue;
}
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
bool ResourceFormatImporter::exists(const String &p_path) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::can_be_imported(const String &p_path) const {
return ResourceFormatLoader::recognize_path(p_path);
}
int ResourceFormatImporter::get_import_order(const String &p_path) const {
Ref<ResourceImporter> importer;
if (FileAccess::exists(p_path + ".import")) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err == OK) {
importer = get_importer_by_name(pat.importer);
}
} else {
importer = get_importer_by_extension(p_path.get_extension().to_lower());
}
if (importer.is_valid()) {
return importer->get_import_order();
}
return 0;
}
bool ResourceFormatImporter::handles_type(const String &p_type) const {
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (ClassDB::is_parent_class(res_type, p_type)) {
return true;
}
}
return true;
}
String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return String();
}
return pat.path;
}
void ResourceFormatImporter::get_internal_resource_path_list(const String &p_path, List<String> *r_paths) {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
return;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::get_internal_resource_path_list - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return;
}
if (assign != String()) {
if (assign.begins_with("path.")) {
r_paths->push_back(value);
} else if (assign == "path") {
r_paths->push_back(value);
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
}
String ResourceFormatImporter::get_import_group_file(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid ? pat.group_file : String();
}
bool ResourceFormatImporter::is_import_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid;
}
String ResourceFormatImporter::get_resource_type(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return "";
}
return pat.type;
}
Variant ResourceFormatImporter::get_resource_metadata(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return Variant();
}
return pat.metadata;
}
void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return;
}
ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types);
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) const {
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == p_name) {
return importers[i];
}
}
return Ref<ResourceImporter>();
}
void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter>> *r_importers) {
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get()) {
r_importers->push_back(importers[i]);
}
}
}
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) const {
Ref<ResourceImporter> importer;
float priority = 0;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get() && importers[i]->get_priority() > priority) {
importer = importers[i];
priority = importers[i]->get_priority();
}
}
}
return importer;
}
String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const {
return ProjectSettings::IMPORTED_FILES_PATH.plus_file(p_for_file.get_file() + "-" + p_for_file.md5_text());
}
bool ResourceFormatImporter::are_import_settings_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
if (!valid) {
return false;
}
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == pat.importer) {
if (!importers[i]->are_import_settings_valid(p_path)) { //importer thinks this is not valid
return false;
}
}
}
return true;
}
String ResourceFormatImporter::get_import_settings_hash() const {
Vector<Ref<ResourceImporter>> sorted_importers = importers;
sorted_importers.sort_custom<SortImporterByName>();
String hash;
for (int i = 0; i < sorted_importers.size(); i++) {
hash += ":" + sorted_importers[i]->get_importer_name() + ":" + sorted_importers[i]->get_import_settings_string();
}
return hash.md5_text();
}
ResourceFormatImporter *ResourceFormatImporter::singleton = nullptr;
ResourceFormatImporter::ResourceFormatImporter() {
singleton = this;
}
| 29.600478 | 163 | 0.649721 | shinyclaw |
c8836aeabab6bd7274fec72b2850b875afcacadb | 2,684 | cc | C++ | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | 1 | 2022-03-20T04:34:49.000Z | 2022-03-20T04:34:49.000Z | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | 1 | 2022-03-24T00:13:13.000Z | 2022-03-24T00:13:20.000Z | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/prefetch_autotuner.h"
#include <memory>
#include "tensorflow/core/framework/model.h"
namespace tensorflow {
namespace data {
PrefetchAutotuner::PrefetchAutotuner(std::shared_ptr<model::Model> model,
std::shared_ptr<model::Node> prefetch_node,
int64_t initial_buffer_size,
int64_t buffer_size_min)
: model_(model),
prefetch_node_(prefetch_node),
buffer_limit_(initial_buffer_size) {
if (initial_buffer_size == model::kAutotune) {
mode_ = Mode::kUpswing;
buffer_limit_ = std::max(int64_t{1}, buffer_size_min);
}
}
namespace {
// Determines what strategy to use for increasing the buffer size limit. For
// limits less than the threshold, an exponential increase is used, while for
// limits greater than or equal to the threshold, a linear increase is used.
size_t kBufferLimitThreshold = 2048;
} // namespace
void PrefetchAutotuner::RecordConsumption(size_t current_buffer_size) {
switch (mode_) {
case Mode::kDisabled:
return;
case Mode::kUpswing:
if (static_cast<int64_t>(current_buffer_size) == buffer_limit_) {
mode_ = Mode::kDownswing;
}
return;
case Mode::kDownswing:
if (current_buffer_size == 0) {
double new_buffer_limit = buffer_limit_;
if (buffer_limit_ >= static_cast<int64_t>(kBufferLimitThreshold)) {
new_buffer_limit += kBufferLimitThreshold;
} else {
new_buffer_limit *= 2;
}
if (model_ != nullptr && prefetch_node_ != nullptr &&
model_->AllocateBufferedBytes(
prefetch_node_->MaximumBufferedBytes() *
(new_buffer_limit - buffer_limit_) /
static_cast<double>(buffer_limit_))) {
buffer_limit_ = new_buffer_limit;
}
mode_ = Mode::kUpswing;
}
return;
}
}
} // namespace data
} // namespace tensorflow
| 34.410256 | 80 | 0.653502 | kim-com |
c884576ef618b792c52efeff13be551da01cebef | 2,318 | cpp | C++ | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 6 | 2020-10-12T05:07:03.000Z | 2021-09-11T14:54:58.000Z | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | null | null | null | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 2 | 2021-02-09T02:06:31.000Z | 2021-10-06T01:25:08.000Z | #include <bits/stdc++.h>
const int MAXN = 21;
typedef long double db;
const db eps = 1e-8;
const db g = 9.80665;
int A[MAXN][MAXN];
int H, W, R, V;
int pw(int x) { return x * x; }
std::pair<db, db> normal(db a, db b) {
db L = sqrtl(a * a + b * b);
return std::make_pair(a / L, b / L);
}
bool judge(int sx, int sy, int dx, int dy) {
db L = R * sqrtl(pw(sx - dx) + pw(sy - dy));
db c = A[dx][dy] - A[sx][sy];
db a = g * L * L / 2 / V / V;
c += a;
db b = -L;
db dta = b * b - 4 * a * c;
if (dta < -eps) return false;
if (dta < 0) dta = 0;
dta = sqrtl(dta);
db vx, vy;
std::tie(vx, vy) = normal(a * 2, -b + dta);
vx *= V, vy *= V;
db T = L / vx;
int l = std::min(sx, dx);
int r = std::max(sx, dx);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sx + 0.5)) / (dx - sx));
db t = T * sc;
db y = sc * (dy - sy) + sy + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) y - 1; j <= (int) y + 1; ++j)
if (j - eps <= y && y <= j + 1 + eps)
mh = std::max(mh, std::max(A[i][j], A[i + 1][j]));
if (h < mh - eps) return false;
}
l = std::min(sy, dy);
r = std::max(sy, dy);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sy + 0.5)) / (dy - sy));
db t = T * sc;
db x = sc * (dx - sx) + sx + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) x - 1; j <= (int) x + 1; ++j)
if (j - eps <= x && x <= j + 1 + eps)
mh = std::max(mh, std::max(A[j][i], A[j][i + 1]));
if (h < mh - eps) return false;
}
return true;
}
int dis[MAXN][MAXN];
int main() {
std::ios_base::sync_with_stdio(false), std::cin.tie(0);
int sx, sy;
std::cin >> W >> H >> R >> V >> sy >> sx;
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
std::cin >> A[i][j];
memset(dis, -1, sizeof dis);
dis[sx][sy] = 0;
std::queue<std::pair<int, int> > que;
que.emplace(sx, sy);
while (!que.empty()) {
int x, y;
std::tie(x, y) = que.front();
que.pop();
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
if (dis[i][j] == -1 && judge(x, y, i, j)) {
dis[i][j] = dis[x][y] + 1;
que.emplace(i, j);
}
}
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j) {
if (dis[i][j] == -1)
std::cout << 'X';
else
std::cout << dis[i][j];
std::cout << (" \n" [j == W]);
}
return 0;
}
| 26.044944 | 56 | 0.443054 | daklqw |
c8866e929e52292f1151f1a1e7830e9a194ccccd | 58 | cpp | C++ | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | //
// Created by Saxion on 10/12/2018.
//
int main(){
}
| 7.25 | 35 | 0.551724 | JohnyJohnes |
c886d1e99ae0c39db9519edec147e5de1610f3ed | 14,414 | cpp | C++ | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "UserGroup.h"
#include "../Player.h"
#include "../guis/UIList.h"
typedef sdPair< const char*, userPermissionFlags_t > permissionName_t;
permissionName_t permissionNames[] = {
permissionName_t( "adminKick", PF_ADMIN_KICK ),
permissionName_t( "adminBan", PF_ADMIN_BAN ),
permissionName_t( "adminSetTeam", PF_ADMIN_SETTEAM ),
permissionName_t( "adminChangeCampaign", PF_ADMIN_CHANGE_CAMPAIGN ),
permissionName_t( "adminChangeMap", PF_ADMIN_CHANGE_MAP ),
permissionName_t( "adminGlobalMute", PF_ADMIN_GLOBAL_MUTE ),
permissionName_t( "adminGlobalVOIPMute", PF_ADMIN_GLOBAL_MUTE_VOIP ),
permissionName_t( "adminPlayerMute", PF_ADMIN_PLAYER_MUTE ),
permissionName_t( "adminPlayerVOIPMute", PF_ADMIN_PLAYER_MUTE_VOIP ),
permissionName_t( "adminWarn", PF_ADMIN_WARN ),
permissionName_t( "adminRestartMap", PF_ADMIN_RESTART_MAP ),
permissionName_t( "adminRestartCampaign", PF_ADMIN_RESTART_CAMPAIGN ),
permissionName_t( "adminStartMatch", PF_ADMIN_START_MATCH ),
permissionName_t( "adminExecConfig", PF_ADMIN_EXEC_CONFIG ),
permissionName_t( "adminShuffleTeams", PF_ADMIN_SHUFFLE_TEAMS ),
permissionName_t( "adminAddBot", PF_ADMIN_ADD_BOT ),
permissionName_t( "adminAdjustBots", PF_ADMIN_ADJUST_BOTS ),
permissionName_t( "adminDisableProficiency", PF_ADMIN_DISABLE_PROFICIENCY ),
permissionName_t( "adminSetTimeLimit", PF_ADMIN_SET_TIMELIMIT ),
permissionName_t( "adminSetTeamDamage", PF_ADMIN_SET_TEAMDAMAGE ),
permissionName_t( "adminSetTeamBalance", PF_ADMIN_SET_TEAMBALANCE ),
permissionName_t( "noBan", PF_NO_BAN ),
permissionName_t( "noKick", PF_NO_KICK ),
permissionName_t( "noMute", PF_NO_MUTE ),
permissionName_t( "noMuteVOIP", PF_NO_MUTE_VOIP ),
permissionName_t( "noWarn", PF_NO_WARN ),
permissionName_t( "quietLogin", PF_QUIET_LOGIN )
};
int numPermissionNames = _arraycount( permissionNames );
/*
===============================================================================
sdUserGroup
===============================================================================
*/
/*
============
sdUserGroup::sdUserGroup
============
*/
sdUserGroup::sdUserGroup( void ) : superUser( false ), voteLevel( -1 ), needsLogin( false ) {
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idBitMsg& msg ) const {
msg.WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
msg.WriteLong( flags.GetDirect()[ i ] );
}
msg.WriteLong( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
msg.WriteLong( controlGroups[ i ].second );
}
msg.WriteLong( voteLevel );
msg.WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( const idBitMsg& msg ) {
char buffer[ 512 ];
msg.ReadString( buffer, sizeof( buffer ) );
SetName( buffer );
for ( int i = 0; i < flags.Size(); i++ ) {
flags.GetDirect()[ i ] = msg.ReadLong();
}
controlGroups.SetNum( msg.ReadLong() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
controlGroups[ i ].second = msg.ReadLong();
}
voteLevel = msg.ReadLong();
needsLogin = msg.ReadBool();
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idFile* file ) const {
file->WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
file->WriteInt( flags.GetDirect()[ i ] );
}
file->WriteInt( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->WriteInt( controlGroups[ i ].second );
}
file->WriteInt( voteLevel );
file->WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( idFile* file ) {
file->ReadString( name );
for ( int i = 0; i < flags.Size(); i++ ) {
file->ReadInt( flags.GetDirect()[ i ] );
}
int count;
file->ReadInt( count );
controlGroups.SetNum( count );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->ReadInt( controlGroups[ i ].second );
}
file->ReadInt( voteLevel );
file->ReadBool( needsLogin );
}
/*
============
sdUserGroup::ParseControl
============
*/
bool sdUserGroup::ParseControl( idLexer& src ) {
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
sdPair< idStr, int >& control = controlGroups.Alloc();
control.first = token;
control.second = -1;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
bool sdUserGroup::Parse( idLexer& src ) {
idToken token;
if ( !src.ReadToken( &token ) ) {
src.Warning( "No Name Specified" );
return false;
}
SetName( token );
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
if ( token.Icmp( "password" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
// Gordon: The example file will have password set to password, this should never be a valid password
if ( token.Icmp( "password" ) != 0 ) {
SetPassword( token );
}
continue;
}
if ( token.Icmp( "control" ) == 0 ) {
if ( !ParseControl( src ) ) {
src.Warning( "Failed to parse control groups" );
return false;
}
continue;
}
if ( token.Icmp( "voteLevel" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Failed to parse voteLevel" );
return false;
}
voteLevel = token.GetIntValue();
continue;
}
int i;
for ( i = 0; i < numPermissionNames; i++ ) {
if ( idStr::Icmp( permissionNames[ i ].first, token ) ) {
continue;
}
GivePermission( permissionNames[ i ].second );
break;
}
if ( i != numPermissionNames ) {
continue;
}
src.Warning( "Unexpected token '%s'", token.c_str() );
return false;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
void sdUserGroup::PostParseFixup( void ) {
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
sdPair< idStr, int >& control = controlGroups[ i ];
control.second = groupManager.FindGroup( control.first );
if ( control.second == -1 ) {
gameLocal.Warning( "sdUserGroup::PostParseFixup Control Group '%s' not found", control.first.c_str() );
}
}
}
/*
============
sdUserGroup::CanControl
============
*/
bool sdUserGroup::CanControl( const sdUserGroup& group ) const {
if ( superUser ) {
return true;
}
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
int index = controlGroups[ i ].second;
if ( index == -1 ) {
continue;
}
if ( &groupManager.GetGroup( index ) == &group ) {
return true;
}
}
return false;
}
/*
===============================================================================
sdUserGroupManagerLocal
===============================================================================
*/
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::sdUserGroupManagerLocal( void ) {
consoleGroup.SetName( "<CONSOLE>" ); // users coming from the console will use this user group which has full permissions
consoleGroup.MakeSuperUser();
defaultGroup = -1;
}
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::~sdUserGroupManagerLocal( void ) {
}
/*
============
sdUserGroupManagerLocal::Init
============
*/
void sdUserGroupManagerLocal::Init( void ) {
idStr groupNames[ MAX_CLIENTS ];
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
nextLoginTime[ i ] = 0;
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
groupNames[ i ] = GetGroup( player->GetUserGroup() ).GetName();
}
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
configs.Clear();
votes.Clear();
// load user groups
idLexer src( LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT | LEXFL_NOFATALERRORS );
src.LoadFile( "usergroups.dat" );
if ( !src.IsLoaded() ) {
return;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
break;
}
if ( !token.Icmp( "group" ) ) {
sdUserGroup& group = userGroups.Alloc();
if ( !group.Parse( src ) ) {
src.Warning( "Error Parsing Group" );
break;
}
} else if ( !token.Icmp( "configs" ) ) {
if ( !configs.Parse( src ) ) {
src.Warning( "Error Parsing configs" );
break;
}
} else if ( !token.Icmp( "votes" ) ) {
if ( !votes.Parse( src ) ) {
src.Warning( "Error Parsing votes" );
break;
}
} else {
src.Warning( "Invalid Token '%s'", token.c_str() );
break;
}
}
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
player->SetUserGroup( FindGroup( groupNames[ i ] ) );
}
for ( int i = 0; i < userGroups.Num(); i++ ) {
userGroups[ i ].PostParseFixup();
}
if ( gameLocal.isServer ) {
WriteNetworkData( sdReliableMessageClientInfoAll() );
}
}
/*
============
sdUserGroupManagerLocal::FindGroup
============
*/
int sdUserGroupManagerLocal::FindGroup( const char* name ) {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( idStr::Icmp( userGroups[ i ].GetName(), name ) ) {
continue;
}
return i;
}
return -1;
}
/*
============
sdUserGroupManagerLocal::Login
============
*/
bool sdUserGroupManagerLocal::Login( idPlayer* player, const char* password ) {
int now = MS2SEC( sys->Milliseconds() );
if ( now < nextLoginTime[ player->entityNumber ] ) {
return false;
}
nextLoginTime[ player->entityNumber ] = now + 5; // Gordon: limit password brute forcing
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( !userGroups[ i ].CheckPassword( password ) ) {
continue;
}
player->SetUserGroup( i );
return true;
}
return false;
}
/*
============
sdUserGroupManagerLocal::CanLogin
============
*/
bool sdUserGroupManagerLocal::CanLogin() const {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if( userGroups[ i ].HasPassword() ) {
return true;
}
}
return false;
}
/*
============
sdUserGroupManagerLocal::ReadNetworkData
============
*/
void sdUserGroupManagerLocal::ReadNetworkData( const idBitMsg& msg ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count = msg.ReadLong();
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( msg );
}
msg.ReadDeltaDict( configs, NULL );
msg.ReadDeltaDict( votes, NULL );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::WriteNetworkData
============
*/
void sdUserGroupManagerLocal::WriteNetworkData( const sdReliableMessageClientInfoBase& target ) {
sdReliableServerMessage msg( GAME_RELIABLE_SMESSAGE_USERGROUPS );
msg.WriteLong( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUserGroup& group = userGroups[ i ];
group.Write( msg );
}
msg.WriteDeltaDict( configs, NULL );
msg.WriteDeltaDict( votes, NULL );
msg.Send( target );
}
/*
============
sdUserGroupManagerLocal::CreateUserGroupList
============
*/
void sdUserGroupManagerLocal::CreateUserGroupList( sdUIList* list ) {
sdUIList::ClearItems( list );
idPlayer* localPlayer = gameLocal.GetLocalPlayer();
if ( !localPlayer ) {
return;
}
const sdUserGroup& localGroup = gameLocal.isClient ? GetGroup( localPlayer->GetUserGroup() ) : GetConsoleGroup();
int index = 0;
for ( int i = 1; i < userGroups.Num(); i++ ) {
if ( !localGroup.CanControl( userGroups[ i ] ) ) {
continue;
}
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), index, 0 );
index++;
}
/*
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), i - 1, 0 );
}
*/
}
/*
============
sdUserGroupManagerLocal::CreateServerConfigList
============
*/
void sdUserGroupManagerLocal::CreateServerConfigList( sdUIList* list ) {
sdUIList::ClearItems( list );
for ( int i = 0; i < configs.GetNumKeyVals(); i++ ) {
const idKeyValue* kv = configs.GetKeyVal( i );
sdUIList::InsertItem( list, va( L"%hs", kv->GetKey().c_str() ), i, 0 );
}
}
/*
============
sdUserGroupManagerLocal::Write
============
*/
void sdUserGroupManagerLocal::Write( idFile* file ) const {
file->WriteInt( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
const sdUserGroup& group = userGroups[ i ];
group.Write( file );
}
configs.WriteToFileHandle( file );
votes.WriteToFileHandle( file );
}
/*
============
sdUserGroupManagerLocal::Read
============
*/
void sdUserGroupManagerLocal::Read( idFile* file ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count;
file->ReadInt( count );
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( file );
}
configs.ReadFromFileHandle( file );
votes.ReadFromFileHandle( file );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::GetVoteLevel
============
*/
int sdUserGroupManagerLocal::GetVoteLevel( const char* voteName ) {
return votes.GetInt( voteName, "-1" );
}
| 23.47557 | 177 | 0.594769 | JasonHutton |
c88703d91472e8d16bc83873acf6e26e15aa076a | 432 | cpp | C++ | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | #include "binary_tree/binary_tree.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Binary tree tests with simple value type (int)", "[unit][binaryTree][binary_tree]") {
esc::data::BinaryTreeHeap<int> heap;
SECTION("Simple adding") {
heap.push(120);
heap.push(42);
heap.push(12);
heap.push(13);
heap.push(43);
heap.push(121);
REQUIRE(heap.size() == 6);
}
} | 27 | 96 | 0.604167 | Tomcus |
c88a47dd948b4abaade3bb380ab9606dab9b80ed | 2,394 | cc | C++ | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 20 | 2020-12-04T12:20:57.000Z | 2022-03-31T00:40:15.000Z | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 6 | 2020-03-06T18:13:55.000Z | 2020-07-20T05:10:20.000Z | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 113 | 2020-10-08T07:37:05.000Z | 2022-02-12T04:26:34.000Z | #include "window.hpp"
#include "selfdrive/hardware/hw.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
main_layout = new QStackedLayout;
main_layout->setMargin(0);
homeWindow = new HomeWindow(this);
main_layout->addWidget(homeWindow);
settingsWindow = new SettingsWindow(this);
main_layout->addWidget(settingsWindow);
onboardingWindow = new OnboardingWindow(this);
main_layout->addWidget(onboardingWindow);
QObject::connect(homeWindow, SIGNAL(openSettings()), this, SLOT(openSettings()));
QObject::connect(homeWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), this, SLOT(offroadTransition(bool)));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), settingsWindow, SIGNAL(offroadTransition(bool)));
QObject::connect(settingsWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(settingsWindow, SIGNAL(reviewTrainingGuide()), this, SLOT(reviewTrainingGuide()));
// start at onboarding
main_layout->setCurrentWidget(onboardingWindow);
QObject::connect(onboardingWindow, SIGNAL(onboardingDone()), this, SLOT(closeSettings()));
onboardingWindow->updateActiveScreen();
// no outline to prevent the focus rectangle
setLayout(main_layout);
setStyleSheet(R"(
* {
font-family: Inter;
outline: none;
}
)");
}
void MainWindow::offroadTransition(bool offroad){
if(!offroad){
closeSettings();
}
}
void MainWindow::openSettings() {
main_layout->setCurrentWidget(settingsWindow);
}
void MainWindow::closeSettings() {
main_layout->setCurrentWidget(homeWindow);
}
void MainWindow::reviewTrainingGuide() {
main_layout->setCurrentWidget(onboardingWindow);
onboardingWindow->updateActiveScreen();
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event){
// wake screen on tap
if (event->type() == QEvent::MouseButtonPress) {
homeWindow->glWindow->wake();
}
// filter out touches while in android activity
#ifdef QCOM
const QList<QEvent::Type> filter_events = {QEvent::MouseButtonPress, QEvent::MouseMove, QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd};
if (HardwareEon::launched_activity && filter_events.contains(event->type())) {
HardwareEon::check_activity();
if (HardwareEon::launched_activity) {
return true;
}
}
#endif
return false;
}
| 31.5 | 149 | 0.739766 | SamuelSandoval |