hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ad6a534d4317cf46d3e5f89cc2e0b726e1c7df00
2,034
cpp
C++
examples/load.cpp
kant/hilma
13592d7705bd84624329889fa6c82815c007cc68
[ "BSD-3-Clause" ]
70
2020-04-29T00:44:37.000Z
2022-01-17T16:54:48.000Z
examples/load.cpp
kant/hilma
13592d7705bd84624329889fa6c82815c007cc68
[ "BSD-3-Clause" ]
2
2020-05-18T23:26:18.000Z
2020-06-12T22:20:45.000Z
examples/load.cpp
kant/hilma
13592d7705bd84624329889fa6c82815c007cc68
[ "BSD-3-Clause" ]
6
2020-05-20T15:22:25.000Z
2022-01-15T17:19:05.000Z
#include <string> #include <sstream> #include <unistd.h> #include <iostream> #include "hilma/types/Mesh.h" #include "hilma/ops/compute.h" #include "hilma/ops/convert_path.h" #include "hilma/ops/convert_image.h" #include "hilma/ops/generate.h" #include "hilma/io/auto.h" #include "hilma/io/gltf.h" #include "hilma/io/stl.h" #include "hilma/io/obj.h" #include "hilma/io/ply.h" #include "hilma/io/png.h" #include "hilma/timer.h" #include "hilma/text.h" int main(int argc, char **argv) { hilma::Mesh mesh; // hilma::load("head.ply", mesh); // hilma::load("CornellBox.obj", mesh); hilma::load("BoomBox.glb", mesh); // hilma::load("Duck.glb", mesh); // hilma::load("dragon.obj", mesh); // mesh = hilma::icosphere(1, 2); std::cout << "vertices: " << mesh.getVerticesTotal() << std::endl; std::cout << "colors: " << mesh.getColorsTotal() << std::endl; std::cout << "tangents: " << mesh.getTangetsTotal() << std::endl; std::cout << "normals: " << mesh.getNormalsTotal() << std::endl; std::cout << "texcoords: " << mesh.getTexCoordsTotal() << std::endl; std::cout << "indices: " << mesh.getFaceIndicesTotal() << std::endl; // std::vector<hilma::Line> lines = hilma::toLines(getBoundingBox(mesh)); // mesh.addEdges(&lines[0], lines.size()); // hilma::saveObj("out.obj", mesh); // hilma::savePly("out.ply", mesh, false); // hilma::savePly("out_bin.ply", mesh, true); // hilma::saveStl("out.stl", mesh, false); // hilma::saveStl("out_bin.stl", mesh, true); hilma::saveGltf("out.glb", mesh); // hilma::saveGltf("out.gltf", mesh); // hilma::Timer timer; // timer.start(); // std::vector<hilma::Image> sdf = hilma::toSdf(mesh, 5.0f, true); // timer.stop(); // const float seconds = timer.get() / 1000.f; // std::cout << " Processing time : " << seconds << " secs" << std::endl; // for (size_t i = 0; i < sdf.size(); i++) // hilma::savePng("sdf_" + hilma::toString(i, 4, '0') + ".png", sdf[i]); return 1; }
30.358209
80
0.598328
kant
ad6f2706088d8c9ed98fa62921d6e8a60dd4f2ce
8,364
cpp
C++
src/app/base/level.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
5
2018-03-28T09:14:55.000Z
2018-04-02T11:54:33.000Z
src/app/base/level.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
src/app/base/level.cpp
nomadsinteractive/ark
52f84c6dbd5ca6bdd07d450b3911be1ffd995922
[ "Apache-2.0" ]
null
null
null
#include "app/base/level.h" #include <unordered_map> #include "core/ark.h" #include "graphics/base/render_object.h" #include "graphics/base/transform.h" #include "graphics/util/vec3_type.h" #include "app/base/application_context.h" #include "app/base/application_resource.h" #include "app/base/rigid_body.h" #include "app/inf/collider.h" namespace ark { Level::Level(std::map<String, sp<Camera>> cameras, std::map<String, sp<Vec3>> lights, std::map<String, RenderObjectLibrary::Instance> renderObjects, std::map<String, RigidBodyLibrary::Instance> rigidBodies) : _cameras(std::move(cameras)), _lights(std::move(lights)), _render_object_libraries(std::move(renderObjects)), _rigid_body_libraries(std::move(rigidBodies)) { } void Level::load(const String& src) { const document manifest = Ark::instance().applicationContext()->applicationResource()->loadDocument(src); std::unordered_map<int32_t, Library> libraryMapping; for(const document& i : manifest->children("library")) { const String& name = Documents::ensureAttribute(i, Constants::Attributes::NAME); const String& dimensions = Documents::ensureAttribute(i, "dimensions"); const int32_t id = Documents::ensureAttribute<int32_t>(i, Constants::Attributes::ID); DWARN(libraryMapping.find(id) == libraryMapping.end(), "Overwriting instance library mapping(%d), originally mapped to type(%d)", id, libraryMapping.find(id)->second._render_object_instance->_type); const auto it1 = _render_object_libraries.find(name); DCHECK(it1 != _render_object_libraries.end(), "Cannot find instance library(%s)", name.c_str()); const auto it2 = _rigid_body_libraries.find(name); libraryMapping.insert(std::make_pair(id, Library(it1->second, it2 == _rigid_body_libraries.end() ? nullptr : &it2->second, parseVector<V3>(dimensions)))); } for(const document& i : manifest->children("layer")) { for(const document& j : i->children("render-object")) { int32_t instanceOf = Documents::getAttribute<int32_t>(j, "instance-of", -1); const String clazz = Documents::getAttribute(j, "class"); if(instanceOf != -1) { const auto it1 = libraryMapping.find(instanceOf); DASSERT(it1 != libraryMapping.end()); const Level::RenderObjectLibrary::Instance* instance = it1->second._render_object_instance; int32_t type = instance->_type; const sp<Layer>& layer = instance->_object; String name = Documents::getAttribute(j, "name"); const String& position = Documents::ensureAttribute(j, "position"); const String& scale = Documents::ensureAttribute(j, "scale"); const String& rotation = Documents::ensureAttribute(j, "rotation"); sp<Transform> transform = makeTransform(rotation, scale); sp<RenderObject> renderObject = sp<RenderObject>::make(type, sp<Vec3::Const>::make(parseVector<V3>(position)), nullptr, transform); sp<RigidBody> rigidBody = makeRigidBody(it1->second, renderObject); if(name) _render_objects[name] = renderObject; if(rigidBody) { if(name) _rigid_objects[name] = std::move(rigidBody); else _unnamed_rigid_objects.push_back(std::move(rigidBody)); } layer->addRenderObject(renderObject); } else if(clazz == "CAMERA") { const String& name = Documents::ensureAttribute(j, "name"); const String& position = Documents::ensureAttribute(j, "position"); const String& rotation = Documents::ensureAttribute(j, "rotation"); const sp<Transform> transform = makeTransform(rotation, ""); const sp<Camera> camera = getCamera(name); DWARN(camera, "Undefined camera(%s) in \"%s\"", name.c_str(), src.c_str()); if(camera) { const V3 p = parseVector<V3>(position); const Transform::Snapshot ts = transform->snapshot(V3(0)); camera->lookAt(p, ts.transform(V3(0, 0, -1)) + p, ts.transform(V3(0, 1, 0))); } } else if(clazz == "LIGHT") { const String& name = Documents::ensureAttribute(j, Constants::Attributes::NAME); const sp<Vec3> light = getLight(name); DWARN(light, "Undefined light(%s) in \"%s\"", name.c_str(), src.c_str()); if(light) { const V3 position = parseVector<V3>(Documents::ensureAttribute(j, Constants::Attributes::POSITION)); Vec3Type::set(light, position); } } } } } sp<Camera> Level::getCamera(const String& name) const { const auto iter = _cameras.find(name); return iter != _cameras.end() ? iter->second : nullptr; } sp<Vec3> Level::getLight(const String& name) const { const auto iter = _lights.find(name); return iter != _lights.end() ? iter->second : nullptr; } sp<RenderObject> Level::getRenderObject(const String& name) const { const auto iter = _render_objects.find(name); return iter != _render_objects.end() ? iter->second : nullptr; } sp<RigidBody> Level::getRigidBody(const String& name) const { const auto iter = _rigid_objects.find(name); return iter != _rigid_objects.end() ? iter->second : nullptr; } sp<RigidBody> Level::makeRigidBody(const Library& library, const sp<RenderObject>& renderObject) const { const RigidBodyLibrary::Instance* rigidBodyLibray = library._rigid_body_instance; if(!rigidBodyLibray) return nullptr; const V3& dimension = library._dimensions; sp<RigidBody> rigidBody = rigidBodyLibray->_object->createBody(Collider::BODY_TYPE_STATIC, rigidBodyLibray->_type, renderObject->position(), sp<Size>::make(dimension.x(), dimension.y(), dimension.z()), renderObject->transform()->rotation()); rigidBody->bind(renderObject); return rigidBody; } sp<Transform> Level::makeTransform(const String& rotation, const String& scale) const { const V3 s = scale ? parseVector<V3>(scale) : V3(1.0f); const V4 rot = parseVector<V4>(rotation); return sp<Transform>::make(Transform::TYPE_LINEAR_3D, sp<Rotation>::make(nullptr, nullptr, sp<Vec4::Const>::make(V4(rot.y(), rot.z(), rot.w(), rot.x()))), sp<Vec3::Const>::make(s)); } Level::BUILDER::BUILDER(BeanFactory& factory, const document& manifest) : _render_object_libraries(loadNamedTypes<Layer>(factory, manifest, Constants::Attributes::RENDER_OBJECT, Constants::Attributes::LAYER)), _rigid_object_libraries(loadNamedTypes<Collider>(factory, manifest, "rigid-body", "collider")) { for(const document& i : manifest->children("camera")) _cameras.push_back({Documents::ensureAttribute(i, Constants::Attributes::NAME), factory.ensureBuilder<Camera>(i, Constants::Attributes::REF)}); for(const document& i : manifest->children("light")) _lights.push_back({Documents::ensureAttribute(i, Constants::Attributes::NAME), factory.ensureBuilder<Vec3>(i, Constants::Attributes::REF)}); } sp<Level> Level::BUILDER::build(const Scope& args) { std::map<String, sp<Camera>> cameras; for(const auto& i : _cameras) cameras[i.first] = i.second->build(args); std::map<String, sp<Vec3>> lights; for(const auto& i : _lights) lights[i.first] = i.second->build(args); std::map<String, RenderObjectLibrary::Instance> instanceLibraries = loadNamedTypeInstances<Layer>(_render_object_libraries, args); std::map<String, RigidBodyLibrary::Instance> rigidBodies = loadNamedTypeInstances<Collider>(_rigid_object_libraries, args); return sp<Level>::make(std::move(cameras), std::move(lights), std::move(instanceLibraries), std::move(rigidBodies)); } Level::Library::Library(const RenderObjectLibrary::Instance& renderObjectInstance, const RigidBodyLibrary::Instance* rigidBodyInstance, const V3& dimensions) : _render_object_instance(&renderObjectInstance), _rigid_body_instance(rigidBodyInstance), _dimensions(dimensions) { } }
46.726257
245
0.650765
nomadsinteractive
ad74c256718a0e83b6b2e2c032c9e8d99cc66578
75
hpp
C++
src/ImageView/path_utility.hpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
1
2021-06-24T12:19:41.000Z
2021-06-24T12:19:41.000Z
src/ImageView/path_utility.hpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
null
null
null
src/ImageView/path_utility.hpp
miere43/imageview
a264fa44ba0140a8171913be763abdddbc531b4a
[ "Unlicense" ]
null
null
null
#pragma once struct Path_Utility { //static wchar_t* combine_path() };
12.5
36
0.706667
miere43
ad779e76c9574369a44afc64f9fd0eddd338d796
232
cpp
C++
tools/performance-benchmarks/message-cat/core/src/engine.io/transporters/tcp.cpp
iot-dsa-v2/engine.io.poc
631f996d0a78d33c907fcb610126b4e3969ee3af
[ "Apache-2.0" ]
null
null
null
tools/performance-benchmarks/message-cat/core/src/engine.io/transporters/tcp.cpp
iot-dsa-v2/engine.io.poc
631f996d0a78d33c907fcb610126b4e3969ee3af
[ "Apache-2.0" ]
null
null
null
tools/performance-benchmarks/message-cat/core/src/engine.io/transporters/tcp.cpp
iot-dsa-v2/engine.io.poc
631f996d0a78d33c907fcb610126b4e3969ee3af
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "tcp.h" TransporterTCP::TransporterTCP() { } TransporterTCP::~TransporterTCP() { } void TransporterTCP::enableTCPClient() { tcpIOMonitor(UV_TCP); tcpIOMonitor.establishConnection(); }
14.5
39
0.702586
iot-dsa-v2
ad7e015ba2fc5b30857de7d3a598e9dbc8745c89
658
hpp
C++
example/generated-src/cwrapper/cw__hello.hpp
ubook-editora/finn
9a2b0e442c94e7311f85d2892dd33b1e3579bb1f
[ "Apache-2.0" ]
null
null
null
example/generated-src/cwrapper/cw__hello.hpp
ubook-editora/finn
9a2b0e442c94e7311f85d2892dd33b1e3579bb1f
[ "Apache-2.0" ]
null
null
null
example/generated-src/cwrapper/cw__hello.hpp
ubook-editora/finn
9a2b0e442c94e7311f85d2892dd33b1e3579bb1f
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from example.djinni #pragma once #include <atomic> #include <optional> #include "hello.hpp" #ifdef __cplusplus extern "C" { #endif #include "cw__hello.h" #ifdef __cplusplus } #endif struct DjinniWrapperHello final { DjinniWrapperHello(std::shared_ptr<::textsort::Hello>wo): wrapped_obj(wo) {}; static std::shared_ptr<::textsort::Hello> get(djinni::Handle<DjinniWrapperHello> dw); static djinni::Handle<DjinniWrapperHello> wrap(std::shared_ptr<::textsort::Hello> obj); const std::shared_ptr<::textsort::Hello> wrapped_obj; std::atomic<size_t> ref_count {1}; };
24.37037
91
0.729483
ubook-editora
ad7e46d3c5c40c3c119d36ad6ac07576b490f5be
2,979
cc
C++
cpp/test-harness/ta1/row-hash-aggregator.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
37
2017-06-09T13:55:23.000Z
2022-01-28T12:51:17.000Z
cpp/test-harness/ta1/row-hash-aggregator.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
null
null
null
cpp/test-harness/ta1/row-hash-aggregator.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
5
2017-06-09T13:55:26.000Z
2021-11-11T03:51:56.000Z
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Implementation of RowHashAggregator. // // Modifications: // Date Name Modification // ---- ---- ------------ // 26 Nov 2012 omd Original Version //***************************************************************** #include "row-hash-aggregator.h" #include <openssl/md5.h> #include <string> using std::string; // start/end delimiter is what bounds a row entry. // For results, this is ROW/ENDROW // For inserts, this is INSERT/ENDINSERT void RowHashAggregator::AddPartialResult(const Knot& data) { switch (state_) { case WAITING_FOR_ROW: if (data == startdelimiter_) { state_ = WAITING_FOR_ID; } else { CHECK(data == "FAILED"); results_.Append(data); results_.AppendOwned("\n", 1); state_ = HANDLING_FAILURE; } break; case WAITING_FOR_ID: results_.Append(data); state_= COMPUTING_HASH; break; case COMPUTING_HASH: if (data == enddelimiter_) { FinalizeHash(); state_ = WAITING_FOR_ROW; } else { AddToHash(data); } break; case HANDLING_FAILURE: results_.Append(data); results_.AppendOwned("\n", 1); if (data == "ENDFAILED") { LOG(WARNING) << "FAILED message received from SUT:\n" << results_; state_ = WAITING_FOR_ROW; } break; default: LOG(FATAL) << "This shouldn't ever happen!"; } } void RowHashAggregator::AddToHash(const Knot& data) { if (!hash_started_) { EVP_DigestInit(&md_ctx_, EVP_md5()); hash_started_ = true; } // TODO(odain) This ends up copying the data (though at least it gets copied // into small chunks whose size is known in advance). It would be more // efficient if we could iterate through the strands and add each strand to // the hash directly. That would require adding a strand iterator or something // to Knot. string data_str; data.ToString(&data_str); EVP_DigestUpdate(&md_ctx_, data_str.data(), data_str.size()); } void RowHashAggregator::FinalizeHash() { if (hash_started_) { hash_started_ = false; unsigned char hash_value[EVP_MAX_MD_SIZE]; unsigned int hash_size; EVP_DigestFinal(&md_ctx_, hash_value, &hash_size); DCHECK(hash_size < EVP_MAX_MD_SIZE); // 2 * hash_size as each byte becomes 2 hex digits. Add one for the initial // space and one for the terminating \n size_t result_len = 2 * hash_size + 2; char* hex_result = new char[result_len]; hex_result[0] = ' '; for (unsigned int i = 0; i < hash_size; ++i) { sprintf(hex_result + 2 * i + 1, "%02x", hash_value[i]); } hex_result[result_len - 1] = '\n'; results_.Append(hex_result, result_len); } else { results_.AppendOwned("\n", 1); } }
30.397959
80
0.597516
nathanawmk
ad7fab15fcf28893be06071e98fb4264e663002b
288
cpp
C++
day13/C++/day13a.cpp
Grace0Hud/dailycodebase
3c48b376f0acd2a65605d601b6b09996b725045b
[ "MIT" ]
249
2018-12-17T16:13:06.000Z
2022-03-31T04:39:14.000Z
day13/C++/day13a.cpp
Grace0Hud/dailycodebase
3c48b376f0acd2a65605d601b6b09996b725045b
[ "MIT" ]
203
2018-12-19T11:03:27.000Z
2021-06-09T16:10:30.000Z
day13/C++/day13a.cpp
Grace0Hud/dailycodebase
3c48b376f0acd2a65605d601b6b09996b725045b
[ "MIT" ]
211
2018-12-19T10:08:20.000Z
2022-03-22T20:01:28.000Z
/* * @author : dhruv-gupta14 * @date : 8/01/2019 */ #include <bits/stdc++.h> using namespace std; long long calc_fact(long long n) { if (n <= 1) return 1; return n*calc_fact(n-1); } int main() { long long n; cin>>n; cout<<calc_fact(n)<<endl; return 0; }
13.090909
32
0.5625
Grace0Hud
ad81f548c629a05d4d2f5237e9c7dc6cdeaf0e1c
6,087
hpp
C++
bindings/python/multibody/joint/joints-models.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
8
2021-05-12T03:04:59.000Z
2021-08-10T11:43:36.000Z
bindings/python/multibody/joint/joints-models.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
bindings/python/multibody/joint/joints-models.hpp
thanhndv212/pinocchio
3b4d272bf4e8a231954b71201ee7e0963c944aef
[ "BSD-2-Clause-FreeBSD" ]
2
2021-04-21T16:00:21.000Z
2022-02-03T06:24:52.000Z
// // Copyright (c) 2015-2020 CNRS INRIA // #ifndef __pinocchio_python_joints_models_hpp__ #define __pinocchio_python_joints_models_hpp__ #include <boost/python.hpp> #include "pinocchio/multibody/joint/joint-collection.hpp" #include "pinocchio/multibody/joint/joint-composite.hpp" #include <eigenpy/eigen-to-python.hpp> namespace pinocchio { namespace python { namespace bp = boost::python; // generic expose_joint_model : do nothing special template <class T> inline bp::class_<T>& expose_joint_model(bp::class_<T>& cl) { return cl; } // specialization for JointModelRevoluteUnaligned template<> inline bp::class_<JointModelRevoluteUnaligned>& expose_joint_model<JointModelRevoluteUnaligned> (bp::class_<JointModelRevoluteUnaligned> & cl) { return cl .def(bp::init<double, double, double> (bp::args("x", "y", "z"), "Init JointModelRevoluteUnaligned from the components x, y, z of the axis")) .def(bp::init<Eigen::Vector3d> (bp::args("axis"), "Init JointModelRevoluteUnaligned from an axis with x-y-z components")) .def_readwrite("axis",&JointModelRevoluteUnaligned::axis, "Rotation axis of the JointModelRevoluteUnaligned.") ; } // specialization for JointModelPrismaticUnaligned template<> inline bp::class_<JointModelPrismaticUnaligned>& expose_joint_model<JointModelPrismaticUnaligned> (bp::class_<JointModelPrismaticUnaligned> & cl) { return cl .def(bp::init<double, double, double> (bp::args("x", "y", "z"), "Init JointModelPrismaticUnaligned from the components x, y, z of the axis")) .def(bp::init<Eigen::Vector3d> (bp::args("axis"), "Init JointModelPrismaticUnaligned from an axis with x-y-z components")) .def_readwrite("axis",&JointModelPrismaticUnaligned::axis, "Translation axis of the JointModelPrismaticUnaligned.") ; } // specialization for JointModelComposite struct JointModelCompositeAddJointVisitor : public boost::static_visitor<JointModelComposite &> { JointModelComposite & m_joint_composite; const SE3 & m_joint_placement; JointModelCompositeAddJointVisitor(JointModelComposite & joint_composite, const SE3 & joint_placement) : m_joint_composite(joint_composite) , m_joint_placement(joint_placement) {} template <typename JointModelDerived> JointModelComposite & operator()(JointModelDerived & jmodel) const { return m_joint_composite.addJoint(jmodel,m_joint_placement); } }; // struct JointModelCompositeAddJointVisitor static JointModelComposite & addJoint_proxy(JointModelComposite & joint_composite, const JointModelVariant & jmodel_variant, const SE3 & joint_placement = SE3::Identity()) { return boost::apply_visitor(JointModelCompositeAddJointVisitor(joint_composite,joint_placement), jmodel_variant); } BOOST_PYTHON_FUNCTION_OVERLOADS(addJoint_proxy_overloads,addJoint_proxy,2,3) struct JointModelCompositeConstructorVisitor : public boost::static_visitor<JointModelComposite* > { const SE3 & m_joint_placement; JointModelCompositeConstructorVisitor(const SE3 & joint_placement) : m_joint_placement(joint_placement) {} template <typename JointModelDerived> JointModelComposite* operator()(JointModelDerived & jmodel) const { return new JointModelComposite(jmodel,m_joint_placement); } }; // struct JointModelCompositeConstructorVisitor static JointModelComposite* init_proxy1(const JointModelVariant & jmodel_variant) { return boost::apply_visitor(JointModelCompositeConstructorVisitor(SE3::Identity()), jmodel_variant); } static JointModelComposite* init_proxy2(const JointModelVariant & jmodel_variant, const SE3 & joint_placement) { return boost::apply_visitor(JointModelCompositeConstructorVisitor(joint_placement), jmodel_variant); } template<> inline bp::class_<JointModelComposite>& expose_joint_model<JointModelComposite> (bp::class_<JointModelComposite> & cl) { return cl .def(bp::init<const size_t> (bp::args("size"), "Init JointModelComposite with a defined size")) .def("__init__", bp::make_constructor(init_proxy1, bp::default_call_policies(), bp::args("joint_model") ), "Init JointModelComposite from a joint" ) .def("__init__", bp::make_constructor(init_proxy2, bp::default_call_policies(), bp::args("joint_model","joint_placement") ), "Init JointModelComposite from a joint and a placement" ) .add_property("joints",&JointModelComposite::joints) .add_property("jointPlacements",&JointModelComposite::jointPlacements) .add_property("njoints",&JointModelComposite::njoints) .def("addJoint", &addJoint_proxy, addJoint_proxy_overloads(bp::args("joint_model","joint_placement"), "Add a joint to the vector of joints." )[bp::return_internal_reference<>()] ) ; } } // namespace python } // namespace pinocchio #endif // ifndef __pinocchio_python_joint_models_hpp__
41.97931
155
0.611631
thanhndv212
ad879d14f474f56434bb46142ea101b6600c53e1
17,253
cpp
C++
nTA/Source/unit_Object.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2020-05-09T20:50:12.000Z
2021-06-20T08:34:58.000Z
nTA/Source/unit_Object.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
null
null
null
nTA/Source/unit_Object.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2018-01-08T00:12:04.000Z
2020-06-14T10:56:50.000Z
// unit_Object.cpp // \author Logan Jones //////////////////// \date 12/29/2001 /// \file /// \brief ... ///////////////////////////////////////////////////////////////////// #include "unit.h" #include "unit_Object.h" #include "game.h" #include "gfx.h" #include "snd.h" #include "object.h" // Include inline implementaions here for a debug build #ifdef _DEBUG #include "unit_Object.inl" #endif // defined( _DEBUG ) ///////////////////////////////////////////////////////////////////// // Default Construction/Destruction // unit_Object::unit_Object( unit_Factory& Manager ): physics_Object( OBJ_Unit ), scene_Object( OBJ_Unit ), m_Manager( Manager ) {} unit_Object::~unit_Object() {} // ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::Create() // \author Logan Jones ////////////////////////// \date 2/24/2002 // //==================================================================== // Parameters: // const std_Point& ptPosition - // const unit_Type* pUnitType - // // Return: BOOL - // BOOL unit_Object::Create( const std_Point& ptPosition, const unit_Type* pUnitType, game_Player* pPlayer ) { m_BaseRect.Set( ptPosition, pUnitType->FootPrint * 16 ); m_Orientation.Set( 0, 0, fPI/2 ); m_Direction.Set( 0, 1 ); // Set the type and host player m_pUnitType = pUnitType; m_pPlayer = pPlayer; // Create an model instance for this unit m_pUnitType->Model->NewInstance( &m_Model ); // Create the script proccess and run the create module if( bFAILED(theGame.Units.m_ScriptMachine.CreateProccess( m_pUnitType->pScript, this, m_Model, &m_Script )) ) { //Destroy(); return FALSE; } // Initialize the model verts and states m_Model->SynchronizeVertices(); m_Model->SynchronizeStates(); // If the unit can build let the initial menu be athe first build menu m_LastMenu = (m_pUnitType->Abilities & unit_Type::CanBuild) ? 1 : 0; m_LastBuildPage = 1; // Set the initial orders m_FireOrder = m_pUnitType->InitialFireOrder; m_MoveOrder = m_pUnitType->InitialMoveOrder; m_Cloaked = FALSE; m_Activation = FALSE; // Initialize m_BuildOrders = NULL; m_bSelected = FALSE; m_ReadyToBuild = 0; m_PrimaryJob = m_ProductionJob = NULL; m_AttachedProject = NULL; // Call the create script and the creation event m_Script->Create(); OnCreate(); // Attach to physics and scene systems m_SceneSortKey = m_VisibleRect.top; AddToPhysicsSystem(); AttachToScene(); return TRUE; } // End unit_Object::Create() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::Update() // \author Logan Jones ////////////////////////// \date 3/3/2002 // //==================================================================== // void unit_Object::Update() { if( !m_Script->IsAnimating() ) MakeAnimator( false ); /* Order_t* pOrder = m_OrderQueue.empty() ? NULL : &m_OrderQueue.front(); switch( m_CurrentTask ) { case TASK_Nothing: case TASK_BeingBuilt: break; case TASK_Pathing: if( pOrder && !pOrder->Waypoints.empty() && m_BaseRect.PointInRect(pOrder->Waypoints.back()) ) { pOrder->Waypoints.pop_back(); if( pOrder->Waypoints.empty() ) PathFinished( pOrder ); else ComputeMotion(); } break; } // end switch( m_CurrentTask )*/ } // End unit_Object::Update() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::Animate() // \author Logan Jones /////////////////////////// \date 6/11/2002 // //==================================================================== // void unit_Object::Animate() { m_Script->Animate(); } // End unit_Object::Animate() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::Render() // \author Logan Jones ////////////////////////// \date 2/2/2002 // //==================================================================== // Parameters: // std_Vector2 vOffset - // void unit_Object::Render( std_Vector2 vOffset ) const { const std_RectF ScreenRect( m_BaseRect - vOffset/* - m_HeightOffset*/ ); //const DWORD Flags = (m_bSelected ? gfx_Model::Selected : 0) | // (m_Elevation < theGame.Terrain.GetSeaLevel() ? gfx_Model::InWater : 0) | // (TRUE ? gfx_Model::SubmergedVisible : 0); /* m_pUnitType->Model->Render( m_Script->GetPieces(), ScreenRect.Center(), m_MoveInfo.GetOrientation() + std_Vector3(0,0,fPI/2), theGame.Terrain.GetSeaLevel() - m_Elevation, Flags, this );*/ #ifdef VISUAL_PATHFIND unit_Factory::PathFind_t* pPath = m_Manager.GetPathInProgress( (unit_Object*)((DWORD)this) ); if( pPath!=NULL ) { std_RectF rct; unit_Factory::SearchNodeBank_t::iterator it = pPath->NodeBank.begin(); unit_Factory::SearchNodeBank_t::iterator end= pPath->NodeBank.end(); for( ; it!=end; ++it ) { unit_Factory::SearchNode_t* pNode = ((*it).second); rct.Set( pNode->Location * 16, 16, 16 ); if( pNode==pPath->pBest ) gfx->DrawRect( rct - vOffset, 0xFFFFFF77 ); else if( pNode==pPath->pProccessee ) gfx->DrawRect( rct - vOffset, 0xFFFF0077 ); else if( pNode->InOpen ) gfx->DrawRect( rct - vOffset, 0x0000FF77 ); else if( pNode->InClosed ) gfx->DrawRect( rct - vOffset, 0xFF000077 ); else gfx->DrawRect( rct - vOffset, 0x00000077 ); } } #endif #ifdef VISUAL_PATHFIND_RESULT /*if( !m_OrderQueue.empty() ) { const Order_t* pOrder = &m_OrderQueue.front(); Waypoints_t::const_iterator it = pOrder->Waypoints.begin(); Waypoints_t::const_iterator end= pOrder->Waypoints.end(); for( ; it!=end; ++it) gfx->DrawRect( std_RectF( (*it) - vOffset - std_Vector2( 0, theGame.Terrain.GetHeight((*it)/16) * 0.5f ), std_SizeF(16,16)), DWORD(0xFFFFFF99) ); }*/ #endif } // End unit_Object::Render() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::Render() // \author Logan Jones ////////////////////////// \date 5/29/2002 // //==================================================================== // void unit_Object::Render() { //const DWORD Flags = (m_bSelected ? gfx_Model::Selected : 0) | // (m_Elevation < theGame.Terrain.GetSeaLevel() ? gfx_Model::InWater : 0) | // (TRUE ? gfx_Model::SubmergedVisible : 0); //m_pUnitType->Model->Render( // m_Script->GetPieces(), // m_VisibleRect.Center(), // m_MoveInfo.GetOrientation() + std_Vector3(0,0,fPI/2), // 0, // theGame.Terrain.GetSeaLevel() - m_Elevation, // Flags, // this ); m_Model->Render( m_VisibleRect.Center(), m_Orientation + std_Vector3(0,0,fPI/2) ); if( m_PrimaryJob && m_PrimaryJob->Active ) { gfx_ModelPiece* pFrom= m_Script->QueryNanoPiece(); gfx_ModelPiece* pTo = m_PrimaryJob->Project->Target->m_Script->SweetSpot(); std_Vector3 From = pFrom->ScreenPosition(); std_Vector2 To = pTo->ScreenPosition(); gfx->DrawLine( m_VisibleRect.Center() + From, m_PrimaryJob->Project->Target->m_VisibleRect.Center() + To, 0xFFFFFFFF ); } } // End unit_Object::Render() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::SetPath() // \author Logan Jones /////////////////////////// \date 3/5/2002 // //==================================================================== // void unit_Object::SetPath() { // m_OrderQueue.front().Waypoints.pop_back(); ComputeMotion(); // Move( m_pUnitType->MaxSpeed ); // MakeMover(); MakeMeDynamic(); } // End unit_Object::SetPath() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::ComputeMotion() // \author Logan Jones ///////////////////////////////// \date 2/24/2002 // //==================================================================== // void unit_Object::ComputeMotion() { // std_Vector2 Dir( m_Path.front() - m_BaseRect.Center() ); std_Vector2 Dir( Waypoint() - m_BaseRect.Center() ); Dir.Normalize(); // Turn( Dir ); //m_Direction = m_Path.front() - m_BaseRect.Center(); //m_Direction.Normalize(); } // End unit_Object::ComputeMotion() ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // unit_Object::DoJobStep() // \author Logan Jones ///////////////////////////// \date 02-12-2003 // //=================================================================== // Parameters: // unit_Job* pJob - // bool bStep - // void unit_Object::DoJobStep( unit_Job* pJob, bool bStep ) { // TEMP //if( bStep ) // if( ((pJob->Project->AppliedTime+=pJob->Worker->m_pUnitType->WorkerTime)>=pJob->Project->TargetType->BuildTime) ) // { // if( pJob->Project->WorkerCount==1 ) delete pJob->Project; // m_Project = NULL; // m_pPlayer->KillJob( this ), // m_Script->Deactivate(), // m_pPlayer->Update( Metal, Consumption, 0, pJob->Project->TargetType->BuildCostMetal / ), // m_pPlayer->Update( Energy,Consumption, 0, pJob->EnergyCost); // } } // End unit_Object::DoJobStep() ///////////////////////////////////////////////////////////////////// static long _yard_open = 0; ///////////////////////////////////////////////////////////////////// // unit_Object::SetUnitValue() // \author Logan Jones //////////////////////////////// \date 02-13-2003 // //=================================================================== // Parameters: // const long& lUnitValueID - // long lDesiredValue - // void unit_Object::SetUnitValue( const long& lUnitValueID, long lDesiredValue ) { switch( lUnitValueID ) { case INBUILDSTANCE: if( m_ReadyToBuild=lDesiredValue ) ReadyToWork(); break; case BUSY: break; case YARD_OPEN: _yard_open = lDesiredValue; case BUGGER_OFF: case ARMORED: break; default: break; } } // End unit_Object::SetUnitValue() ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // unit_Object::GetUnitValue() // \author Logan Jones //////////////////////////////// \date 4/18/2002 // //==================================================================== // Parameters: // const long lUnitValueID - // // Return: const long - // const long unit_Object::GetUnitValue( const long lUnitValueID ) const { switch( lUnitValueID ) { case ACTIVATION: return m_Activation; case STANDINGMOVEORDERS: return m_MoveOrder; case STANDINGFIREORDERS: return m_FireOrder; case HEALTH: return 0; case INBUILDSTANCE: return m_ReadyToBuild; case BUSY: case PIECE_XZ: case PIECE_Y: case UNIT_XZ: case UNIT_Y: case UNIT_HEIGHT: case GROUND_HEIGHT: case BUILD_PERCENT_LEFT: return 0; case YARD_OPEN: return _yard_open; case BUGGER_OFF: case ARMORED: return 0; case IN_WATER: return theGame.Terrain.GetElevation(m_BaseRect.Center()) < theGame.Terrain.GetSeaLevel(); case CURRENT_SPEED: return long(m_Velocity.Magnitude() * LINEAR_CONSTANT); case VETERAN_LEVEL: return 0; default: return 0; } } // End unit_Object::GetUnitValue() ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // unit_Object::AbsoluteHealth() // \author Logan Jones ////////////////////////////////// \date 03-06-2003 // //=================================================================== // Return: float - // float unit_Object::AbsoluteHealth() const { if( m_AttachedProject ) return m_AttachedProject->AppliedTime / m_pUnitType->BuildTime; else return 1; } // End unit_Object::AbsoluteHealth() ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // unit_Object::EconomicActivity() // \author Logan Jones //////////////////////////////////// \date 03-03-2003 // //=================================================================== // Parameters: // float& fMetalProduction - // float& fMetalConsumtion - // float& fEnergyProduction - // float& fEnergyConsumtion - // void unit_Object::EconomicActivity( float& fMetalProduction, float& fMetalConsumtion, float& fEnergyProduction, float& fEnergyConsumtion ) const { fMetalProduction = m_pUnitType->MetalMake; fEnergyProduction= m_pUnitType->EnergyMake; fMetalConsumtion = m_PrimaryJob ? m_PrimaryJob->MetalCost : 0; fEnergyConsumtion= m_PrimaryJob ? m_PrimaryJob->EnergyCost: 0; if( m_ProductionJob ) { if( m_ProductionJob->Active ) fMetalProduction += m_ProductionJob->MetalIncome, fEnergyProduction+= m_ProductionJob->EnergyIncome; if( Active() ) fMetalConsumtion += m_ProductionJob->MetalCost, fEnergyConsumtion+= m_ProductionJob->EnergyCost; } } // End unit_Object::EconomicActivity() ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // unit_Object::DoMovement() // \author Logan Jones ////////////////////////////// \date 05-15-2003 // //=================================================================== // Return: bool - return true if unit is still alive // bool unit_Object::DoMovement() { // Save the old base rect m_MovementBox = m_BaseRect; // Steering // Accumulate steering vector // Locomotion // Apply steering vector // Update move state Locomotion( Steering() ); // Make a movement box that encompasses the old and new position m_MovementBox.Encompass( m_BaseRect ); // Validation // Net return false; } // End unit_Object::DoMovement() ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // unit_Object::Steering() // \author Logan Jones //////////////////////////// \date 05-21-2003 // //=================================================================== // Return: std_Vector2 - // std_Vector2 unit_Object::Steering() { std_Vector2 target = Waypoint(); std_Vector2 position = m_BaseRect.Center(); const std_Vector2 Offset = target - position; //return ((math_Normalize(Offset) * m_pUnitType->MaxSpeed) - m_Velocity); const float Distance = Offset.Magnitude(); const float SlowingDistance = sqr(m_pUnitType->MaxSpeed) / m_pUnitType->BrakeRate; const float RampedSpeed = m_pUnitType->MaxSpeed * Distance / SlowingDistance; const float ClippedSpeed = min( RampedSpeed, m_pUnitType->MaxSpeed ); const std_Vector2 DesiredVelocity = Offset * (ClippedSpeed / Distance); return (DesiredVelocity - m_Velocity); } // End unit_Object::Steering() ///////////////////////////////////////////////////////////////////// /* ///////////////////////////////////////////////////////////////////// // unit_Object::Locomotion() // \author Logan Jones ////////////////////////////// \date 05-21-2003 // //=================================================================== // Parameters: // const std_Vector2& vSteering - // void unit_Object::Locomotion( const std_Vector2& vSteering ) { switch( m_pUnitType->Behaviour ) { case unit_Type::Structure: break; case unit_Type::Groundcraft: break; case unit_Type::Seacraft: break; case unit_Type::Aircraft: break; case unit_Type::Hovercraft: break; default: // This shouldn't happen assert( !"Invalid unit type behaviour." ); } } // End unit_Object::Locomotion() ///////////////////////////////////////////////////////////////////// */ ///////////////////////////////////////////////////////////////////// // End - unit_Object.cpp // //////////////////////////
31.773481
149
0.481539
loganjones
ad87c23de6f39f0fb10bed8be5ad7df3465829b8
176
cpp
C++
FM_Client/Connessione.cpp
mikymaione/FilmManager
be2dd1342a497dcefd89f2003d2ecbeb0e5e07a1
[ "MIT" ]
1
2020-03-20T09:49:50.000Z
2020-03-20T09:49:50.000Z
FM_Client/Connessione.cpp
mikymaione/FilmManager
be2dd1342a497dcefd89f2003d2ecbeb0e5e07a1
[ "MIT" ]
null
null
null
FM_Client/Connessione.cpp
mikymaione/FilmManager
be2dd1342a497dcefd89f2003d2ecbeb0e5e07a1
[ "MIT" ]
null
null
null
/* * File: Connessione.cpp * Author: michele * * Created on 11 ottobre 2014, 11.30 */ #include "Connessione.h" Connessione::Connessione() { widget.setupUi(this); }
13.538462
36
0.653409
mikymaione
ad8a21d767ceb6b12c7f6d522fe35878e65422c6
737
cpp
C++
engine/src/engine/utils/timer.cpp
L4ZZA/city-uni-engine
9f94a0fd404cf7832a98fd5436d84b44000c4add
[ "MIT" ]
null
null
null
engine/src/engine/utils/timer.cpp
L4ZZA/city-uni-engine
9f94a0fd404cf7832a98fd5436d84b44000c4add
[ "MIT" ]
null
null
null
engine/src/engine/utils/timer.cpp
L4ZZA/city-uni-engine
9f94a0fd404cf7832a98fd5436d84b44000c4add
[ "MIT" ]
null
null
null
#include "pch.h" #include "timer.h" #include <GLFW/glfw3.h> void engine::timer::start() { m_started = true; reset(); } void engine::timer::reset() { // current time in seconds m_start_time = glfwGetTime(); m_last_frame = m_start_time; } double engine::timer::elapsed() { if(!m_started) return 0.0; // current time in seconds const double currentFrame = glfwGetTime(); m_delta_time = currentFrame - m_last_frame; m_last_frame = currentFrame; return m_delta_time; } double engine::timer::elapsed_millis() { return elapsed() * 1000.f; } double engine::timer::total() const { // current time in seconds const double current = glfwGetTime(); return current - m_start_time; }
17.139535
45
0.666214
L4ZZA
ad8a345a76febdef3fb5fff7e4ba1058b618ec3c
1,741
cpp
C++
src/core/path_controller_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/core/path_controller_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/core/path_controller_component.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "core/path_controller_component.h" PathControllerComponent::PathControllerComponent() : mNextAttackTimer(0.0) , mNextAttackTimerMax(3.0) , mDamage(10) , mAggroDist(800) , mPeaceDist(1200) { } void PathControllerComponent::SetNextAttackTimer( double nextAttackTimer ) { mNextAttackTimer = nextAttackTimer; } double PathControllerComponent::GetNextAttackTimer() const { return mNextAttackTimer; } void PathControllerComponent::SetNextAttackTimerMax( double nextAttackTimerMax ) { mNextAttackTimerMax = nextAttackTimerMax; } double PathControllerComponent::GetNextAttackTimerMax() const { return mNextAttackTimerMax; } void PathControllerComponent::SetDamage( int32_t damage ) { mDamage = damage; } int32_t PathControllerComponent::GetDamage() const { return mDamage; } void PathControllerComponent::SetAggroDist( int32_t aggroDist ) { mAggroDist = aggroDist; } int32_t PathControllerComponent::GetAggroDist() const { return mAggroDist; } void PathControllerComponent::SetPeaceDist( int32_t peaceDist ) { mPeaceDist = peaceDist; } int32_t PathControllerComponent::GetPeaceDist() const { return mPeaceDist; } void PathControllerComponentLoader::BindValues() { Bind( "aggro_distance", func_int32_t( &PathControllerComponent::SetAggroDist ) ); Bind( "next_attack_timer", func_int32_t( &PathControllerComponent::SetNextAttackTimerMax ) ); Bind( "damage", func_int32_t( &PathControllerComponent::SetDamage ) ); Bind( "peace_distance", func_int32_t( &PathControllerComponent::SetPeaceDist ) ); } PathControllerComponentLoader::PathControllerComponentLoader() { } REAPING2_CLASS_EXPORT_IMPLEMENT( PathControllerComponent, PathControllerComponent );
22.320513
97
0.775416
MrPepperoni
ad8d113f348e1ad3a516bbea7f09a2dfd13db202
8,918
hpp
C++
src/scripting/ScriptSymbolStorage.hpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
399
2019-01-06T17:55:18.000Z
2022-03-21T17:41:18.000Z
src/scripting/ScriptSymbolStorage.hpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
101
2019-04-18T21:03:53.000Z
2022-01-08T13:27:01.000Z
src/scripting/ScriptSymbolStorage.hpp
KirmesBude/REGoth-bs
2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a
[ "MIT" ]
56
2019-04-10T10:18:27.000Z
2022-02-08T01:23:31.000Z
#pragma once #include "ScriptSymbols.hpp" #include <BsPrerequisites.h> #include <RTTI/RTTIUtil.hpp> namespace REGoth { namespace Scripting { /** * Holds the list of all created symbols and their data. * * This is the only place where symbols should created and have * their types and names be set. */ class ScriptSymbolStorage : public bs::IReflectable { public: ScriptSymbolStorage() = default; /** * Appends a symbol of the given type to the storage. * * @tparam T Type of the symbol to create and append. * @param name Name of the symbol to append. * * @return Index of the created symbol. */ template <typename T> SymbolIndex appendSymbol(const bs::String& name) { bs::SPtr<SymbolBase> symbol = bs::bs_shared_ptr_new<T>(); mStorage.emplace_back(std::move(symbol)); SymbolIndex index = (SymbolIndex)(mStorage.size() - 1); mStorage.back()->name = name; mStorage.back()->index = index; mStorage.back()->type = T::TYPE; if (mStorage.size() >= SYMBOL_INDEX_MAX) { using namespace bs; BS_EXCEPT(InvalidStateException, "Symbol Index limit reached!"); } mSymbolsByName[name] = index; return index; } /** * Looks up the symbol at the given index. * * This will also do sanity checks on whether the given index is pointing to * a valid object and throws if not. * * HOWEVER, this will not do any type checking, and you should only up-cast the * resulting reference if you know what you are doing. * * Use the type-save variant getSymbol() instead! * * @param index Index of the symbol to look up. * * @return Reference to the symbol with the given index. */ SymbolBase& getSymbolBase(SymbolIndex index) const { throwOnInvalidSymbol(index); return getTypedSymbolReference<SymbolBase>(index); } /** * Looks up the name of the symbol at the given index. * * This will also do sanity checks on whether the given index is pointing to * a valid object and throws if not. * * @param index Index of the symbol to look up. * * @return Name of the symbol with the given index. */ const bs::String& getSymbolName(SymbolIndex index) const { return getSymbolBase(index).name; } /** * Looks up the symbol at the given index. * * This will also do sanity checks on whether the given index is pointing to * a valid object of the correct type. Throws if not. * * @tparam T Type of symbol to look up. * @param index Index of the symbol to look up. * * @return Reference to the symbol with the given index. */ template <class T> T& getSymbol(SymbolIndex index) const { throwOnInvalidSymbol(index); throwOnMismatchingType<T>(*mStorage[index]); return getTypedSymbolReference<T>(index); } /** * Looks up the symbol with the given name. * * This will also do sanity checks on whether the given name is referring * to an existing symbol. Throws if not. * * @tparam T Type of symbol to look up. * @param name Name of the symbol to look up. * * @return Reference to the symbol with the given name. */ template <class T> T& getSymbol(const bs::String& name) const { SymbolIndex index = findIndexBySymbolName(name); throwOnInvalidSymbol(index); throwOnMismatchingType<T>(*mStorage[index]); return getTypedSymbolReference<T>(index); } /** * Runs a query agains the symbol storage. Assembles a list of all symbols * for which the given function returned true. * * @param addIf Predicate function. If this returns true, the symbols index will * be added to the result list. * * @return List of indices of all symbols where the predicate function returned true. */ bs::Vector<SymbolIndex> query(std::function<bool(const SymbolBase&)> addIf) const { bs::Vector<SymbolIndex> result; for (const auto& s : mStorage) { if (addIf(*s)) { result.push_back(s->index); } } return result; } /** * Looks up the type of the symbol with the given index. * * This will also do sanity checks on whether the given index is pointing to * a valid object of the correct type. Throws if not. * * @param index Index of the symbol to lookup the type from. * * @return Type of the symbol with the given index. */ SymbolType getSymbolType(SymbolIndex index) const { throwOnInvalidSymbol(index); return mStorage[index]->type; } /** * Looks up the type of the symbol with the given name. * * This will also do sanity checks on whether the given name is referring to * a valid object of the correct type. Throws if not. * * @param index Index of the symbol to lookup the type from. * * @return Type of the symbol with the given name. */ SymbolType getSymbolType(const bs::String& name) const { SymbolIndex index = findIndexBySymbolName(name); throwOnInvalidSymbol(index); return mStorage[index]->type; } /** * @return Whether a symbol with the given name exists. */ bool hasSymbolWithName(const bs::String& name) const { return mSymbolsByName.find(name) != mSymbolsByName.end(); } /** * Tries to find the index of the symbol with the given name. * * Throws if no such symbol exists. * * @param name Name of the symbol to look for. * * @return Index of the symbol with the given name. */ SymbolIndex findIndexBySymbolName(const bs::String& name) const { auto it = mSymbolsByName.find(name); if (it == mSymbolsByName.end()) { using namespace bs; BS_EXCEPT(InvalidStateException, "Symbol with name " + name + " does not exist!"); } return it->second; } /** * Registers a mapping of script address -> symbol index so we can get the script * Symbol from an address. This might not fit here, since the symbol storage doesn't * know the types of the other symbols, but this seems to be the best place... */ void registerFunctionAddress(SymbolIndex index) { SymbolScriptFunction& fn = getSymbol<SymbolScriptFunction>(index); mFunctionsByAddress[fn.address] = index; } /** * @return Symbol of the function with the given address. */ SymbolIndex findFunctionByAddress(bs::UINT32 scriptAddress) { auto it = mFunctionsByAddress.find(scriptAddress); if (it == mFunctionsByAddress.end()) { return SYMBOL_INDEX_INVALID; } return it->second; } private: /** * @return The symbol at the given index cast to the passed type. */ template <class T> T& getTypedSymbolReference(SymbolIndex index) const { return *(T*)(mStorage[index].get()); } template <class T> void throwOnMismatchingType(const SymbolBase& symbol) const { if (T::TYPE != symbol.type) { using namespace bs; BS_EXCEPT( InvalidStateException, bs::StringUtil::format("Symbol Type does not match expectation! Expected {0}, got {1}", (int)T::TYPE, (int)symbol.type)); } } void throwOnInvalidSymbol(SymbolIndex index) const { using namespace bs; if (index == SYMBOL_INDEX_INVALID) { BS_EXCEPT(InvalidStateException, "Symbol Index is set to INVALID!"); } if (index >= mStorage.size()) { BS_EXCEPT(InvalidStateException, "Symbol Index out of range!"); } if (!mStorage[index]) { BS_EXCEPT(InvalidStateException, "Symbol index " + bs::toString(index) + " pointing to NULL!"); } } bs::Vector<bs::SPtr<SymbolBase>> mStorage; bs::Map<bs::String, SymbolIndex> mSymbolsByName; bs::Map<bs::UINT32, SymbolIndex> mFunctionsByAddress; public: REGOTH_DECLARE_RTTI_FOR_REFLECTABLE(ScriptSymbolStorage) }; } // namespace Scripting } // namespace REGoth
29.726667
101
0.585445
KirmesBude
ad8fb0e01a72a0613953eda5874e61e3c3fd85bb
1,905
cpp
C++
aed2122_p06/Tests/game.cpp
gpe0/AED2021
4f36c7b62f53ecba5b813c61f0f88064df4792ca
[ "MIT" ]
null
null
null
aed2122_p06/Tests/game.cpp
gpe0/AED2021
4f36c7b62f53ecba5b813c61f0f88064df4792ca
[ "MIT" ]
null
null
null
aed2122_p06/Tests/game.cpp
gpe0/AED2021
4f36c7b62f53ecba5b813c61f0f88064df4792ca
[ "MIT" ]
null
null
null
#include "game.h" #include <cmath> #include <sstream> Circle::Circle(int p, bool s): points(p), state(s), nVisits(0) {} int Circle::getPoints() const { return points; } bool Circle::getState() const { return state; } void Circle::changeState() { if (state == false) state = true; else state = false; } int Circle::getNVisits() const { return nVisits; } void Circle::incNVisits() { nVisits++; } BinaryTree<Circle>& Game::getGame() { return game; } //----------------------------------------------------------------- BinaryTree<Circle> createTree(int height, vector<int>& points, vector<bool>& states, int index) { if (height == 0) { return BinaryTree<Circle>(Circle(points[index], states[index])); } return BinaryTree<Circle>(Circle(points[index], states[index]), createTree(height - 1, points, states, 2 * index + 1), createTree(height - 1, points, states, 2 * index + 2)); } //TODO Game::Game(int height, vector<int>& points, vector<bool>& states) { game = createTree(height, points, states, 0); } //TODO int Game::play() { BTItrLevel<Circle> it(game); int ind = 0; int index = 0; int points; while (!it.isAtEnd()) { if (ind == index) { Circle &c = it.retrieve(); c.incNVisits(); if (!c.getState()) { index = 2 * ind + 1; } else { index = 2 * ind + 2; } c.changeState(); points = c.getPoints(); } ind++; it.advance(); } return points; } //TODO int Game::mostVisited() const { BTItrLevel<Circle> it(game); it.advance(); int max = -1; while (!it.isAtEnd()) { Circle &c = it.retrieve(); if (c.getNVisits() > max) { max = c.getNVisits(); } it.advance(); } return max; }
18.495146
178
0.52021
gpe0
ad919e3ed28214b572b6dcbb72c5c28e7dbf4a85
9,045
cpp
C++
ANode/test/TestExprRepeatDateArithmetic.cpp
ecmwf/ecflow
2498d0401d3d1133613d600d5c0e0a8a30b7b8eb
[ "Apache-2.0" ]
11
2020-08-07T14:42:45.000Z
2021-10-21T01:59:59.000Z
ANode/test/TestExprRepeatDateArithmetic.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
10
2020-08-07T14:36:27.000Z
2022-02-22T06:51:24.000Z
ANode/test/TestExprRepeatDateArithmetic.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
6
2020-08-07T14:34:38.000Z
2022-01-10T12:06:27.000Z
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #10 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 #include <boost/test/unit_test.hpp> #include "Defs.hpp" #include "Suite.hpp" #include "Task.hpp" #include "ExprAst.hpp" using namespace std; using namespace ecf; BOOST_AUTO_TEST_SUITE( NodeTestSuite ) BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic ) { cout << "ANode:: ...test_repeat_data_arithmetic\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Get the trigger AST AstTop* trigger = t2->triggerAst(); BOOST_REQUIRE_MESSAGE(trigger,"Expected trigger"); // check evaluation BOOST_CHECK_MESSAGE(trigger->evaluate(),"Expected trigger to evaluate i.e 20090101 >= 20080601"); // Check date arithmetic. Basics, end of months t2->changeTrigger("t1:YMD - 1 eq 20081231"); // 20090101 - 1 == 20081231 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic for evaluation"); t2->changeTrigger("t1:YMD + 1 eq 20090102"); // 20090101 + 1 == 20090102 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic for evaluation"); } BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic_add_to_end_of_month ) { cout << "ANode:: ...test_repeat_data_arithmetic_add_to_end_of_month\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Check the end of each month + 1 t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090131,20101231,1)); // jan t2->changeTrigger("t1:YMD + 1 eq 20090201"); // 20090131 + 1 == 20090201 BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090228,20101231,1)); // feb t2->changeTrigger("t1:YMD + 1 eq 20090301"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090331,20101231,1)); // mar t2->changeTrigger("t1:YMD + 1 eq 20090401"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090430,20101231,1)); // apr t2->changeTrigger("t1:YMD + 1 eq 20090501"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090531,20101231,1)); // may t2->changeTrigger("t1:YMD + 1 eq 20090601"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090630,20101231,1)); // June t2->changeTrigger("t1:YMD + 1 eq 20090701"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090731,20101231,1)); // July t2->changeTrigger("t1:YMD + 1 eq 20090801"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090831,20101231,1)); // Aug t2->changeTrigger("t1:YMD + 1 eq 20090901"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090930,20101231,1)); // Sept t2->changeTrigger("t1:YMD + 1 eq 20091001"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091031,20101231,1)); // Oct t2->changeTrigger("t1:YMD + 1 eq 20091101"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091130,20101231,1)); // Nov t2->changeTrigger("t1:YMD + 1 eq 20091201"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091231,20101231,1)); // Dec t2->changeTrigger("t1:YMD + 1 eq 20100101"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); } BOOST_AUTO_TEST_CASE( test_repeat_data_arithmetic_take_from_end_of_month ) { cout << "ANode:: ...test_repeat_data_arithmetic_take_from_end_of_month\n" ; Defs theDefs; task_ptr t2,t1; { suite_ptr s1 = theDefs.add_suite("s1"); t1 = s1->add_task("t1"); t1->addRepeat( RepeatDate("YMD",20090101,20091231,1)); t2 = s1->add_task("t2"); t2->add_trigger("t1:YMD ge 20080601"); } theDefs.beginAll(); // Check trigger expressions std::string errorMsg, warningMsg; BOOST_REQUIRE_MESSAGE(theDefs.check(errorMsg,warningMsg),"Expected triggers expressions to parse " << errorMsg); // Check the end of each month - 1 t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090201,20101231,1)); // jan t2->changeTrigger("t1:YMD - 1 eq 20090131"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090301,20101231,1)); // feb t2->changeTrigger("t1:YMD - 1 eq 20090228"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090401,20101231,1)); // mar t2->changeTrigger("t1:YMD - 1 eq 20090331"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090501,20101231,1)); // apr t2->changeTrigger("t1:YMD - 1 eq 20090430"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090601,20101231,1)); // may t2->changeTrigger("t1:YMD - 1 eq 20090531"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090701,20101231,1)); // June t2->changeTrigger("t1:YMD - 1 eq 20090630"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090801,20101231,1)); // July t2->changeTrigger("t1:YMD - 1 eq 20090731"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20090901,20101231,1)); // Aug t2->changeTrigger("t1:YMD - 1 eq 20090831"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091001 ,20101231,1)); // Sept t2->changeTrigger("t1:YMD - 1 eq 20090930"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091101 ,20101231,1)); // Oct t2->changeTrigger("t1:YMD - 1 eq 20091031"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20091201 ,20101231,1)); // Nov t2->changeTrigger("t1:YMD - 1 eq 20091130"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); t1->deleteRepeat(); t1->addRepeat( RepeatDate("YMD",20100101 ,20101231,1)); // Dec t2->changeTrigger("t1:YMD - 1 eq 20091231"); BOOST_CHECK_MESSAGE(t2->triggerAst()->evaluate(),"Expected trigger to use date arithmetic"); } BOOST_AUTO_TEST_SUITE_END()
41.682028
115
0.687673
ecmwf
ad921d2f399675026a97643637b9127d4abf1282
1,871
cpp
C++
tests/Core/TestStaticVector.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
9
2015-03-10T10:20:14.000Z
2020-12-29T15:49:14.000Z
tests/Core/TestStaticVector.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
null
null
null
tests/Core/TestStaticVector.cpp
nsf/nextgame
a2d2f21341489792bafa2519f33287a0b89927ee
[ "MIT" ]
2
2019-12-23T17:36:37.000Z
2021-06-18T13:21:46.000Z
#include "stf.h" #include "Core/Defer.h" #include "Core/StaticVector.h" STF_SUITE_NAME("Core.StaticVector") /* _ _ | | | | | |_ ___ __| | ___ | __/ _ \ / _` |/ _ \ | || (_) | (_| | (_) | \__\___/ \__,_|\___/ #define CHECK_VECTOR(v, len, cap, data) \ do { \ STF_ASSERT(v.Length() == len); \ STF_ASSERT(v.Capacity() == cap); \ STF_ASSERT(v.Data() data); \ } while (0) #define CHECK_VECTOR_CONTENTS(v, ...) \ STF_ASSERT(v.Sub() == Slice<const int>({__VA_ARGS__})) STF_TEST("StaticVector::Init()") { StaticVector<int, 4> v; v.Init(); CHECK_VECTOR(v, 0, 4, == v.m_static); v.Free(); } STF_TEST("StaticVector::Append(const T&)") { StaticVector<int, 4> v = StaticVector<int, 4>().Init(); DEFER { v.Free(); }; CHECK_VECTOR(v, 0, 4, == v.m_static); v.Append(1); CHECK_VECTOR(v, 1, 4, == v.m_static); CHECK_VECTOR_CONTENTS(v, 1); v.Append(2); v.Append(3); v.Append(4); CHECK_VECTOR(v, 4, 4, == v.m_static); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4); v.Append(5); STF_ASSERT(v.Length() == 5); STF_ASSERT(v.Capacity() >= 5); STF_ASSERT(v.Data() == v.m_dynamic.m_data); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5); v.Append(6); v.Append(7); v.Append(8); STF_ASSERT(v.Length() == 8); STF_ASSERT(v.Capacity() >= 8); STF_ASSERT(v.Data() == v.m_dynamic.m_data); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6, 7, 8); } STF_TEST("StaticVector::Append(const T&)") { StaticVector<int, 4> v = StaticVector<int, 4>().Init(); DEFER { v.Free(); }; v.Append(1); v.Append(2); CHECK_VECTOR_CONTENTS(v, 1, 2); v.QuickRemove(1); CHECK_VECTOR_CONTENTS(v, 1); v.Append(2); v.Append(3); v.Append(4); v.Append(5); v.Append(6); CHECK_VECTOR_CONTENTS(v, 1, 2, 3, 4, 5, 6); v.QuickRemove(0); v.QuickRemove(0); STF_ASSERT(v.Data() == v.m_static); CHECK_VECTOR_CONTENTS(v, 5, 2, 3, 4); } */
23.683544
56
0.592731
nsf
ad92680ad9447ec6d2038228c3d1060402add554
14,252
cpp
C++
buildcc/lib/target/test/target/test_target_sync.cpp
coder137/build_in_cpp
296b0312eb0f4773fb2d40b01ed302f74f26f7a8
[ "Apache-2.0" ]
48
2021-06-15T08:34:42.000Z
2022-03-24T20:35:54.000Z
buildcc/lib/target/test/target/test_target_sync.cpp
coder137/build_in_cpp
296b0312eb0f4773fb2d40b01ed302f74f26f7a8
[ "Apache-2.0" ]
100
2021-06-14T00:21:49.000Z
2022-03-29T03:59:42.000Z
buildcc/lib/target/test/target/test_target_sync.cpp
coder137/build_in_cpp
296b0312eb0f4773fb2d40b01ed302f74f26f7a8
[ "Apache-2.0" ]
1
2021-06-17T01:03:36.000Z
2021-06-17T01:03:36.000Z
#include "constants.h" #include "target/target.h" #include "env/env.h" // NOTE, Make sure all these includes are AFTER the system and header includes #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/MemoryLeakDetectorNewMacros.h" #include "CppUTest/TestHarness.h" #include "CppUTest/Utest.h" #include "CppUTestExt/MockSupport.h" // clang-format off TEST_GROUP(TargetTestSyncGroup) { void teardown() { } }; // clang-format on buildcc::base::Toolchain gcc(buildcc::base::Toolchain::Id::Gcc, "gcc", "as", "gcc", "g++", "ar", "ldd"); TEST(TargetTestSyncGroup, CopyByConstRef) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Copy(srcTarget, { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, CopyByMove) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Copy(std::move(srcTarget), { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, CopyCrash) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); CHECK_THROWS(std::exception, destTarget.Copy(srcTarget, { (buildcc::base::SyncOption)65535, })); } TEST(TargetTestSyncGroup, InsertByConstRef) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Insert(srcTarget, { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, InsertByMove) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); srcTarget.AddSource("dummy_main.c"); srcTarget.AddIncludeDir("include", true); srcTarget.AddPch("include/include_header.h"); srcTarget.AddLibDep(srcTarget); srcTarget.AddLibDep("testLib.a"); srcTarget.AddLibDir("include"); srcTarget.AddPreprocessorFlag("-DTEST"); srcTarget.AddCommonCompileFlag("-O0"); srcTarget.AddPchCompileFlag("-pch_compile"); srcTarget.AddPchObjectFlag("-pch_object"); srcTarget.AddAsmCompileFlag("-march=test"); srcTarget.AddCCompileFlag("-std=c11"); srcTarget.AddCppCompileFlag("-std=c++17"); srcTarget.AddLinkFlag("-nostdinc"); srcTarget.AddCompileDependency("new_source.cpp"); srcTarget.AddLinkDependency("new_source.cpp"); destTarget.Insert(std::move(srcTarget), { buildcc::base::SyncOption::SourceFiles, buildcc::base::SyncOption::HeaderFiles, buildcc::base::SyncOption::PchFiles, buildcc::base::SyncOption::LibDeps, buildcc::base::SyncOption::IncludeDirs, buildcc::base::SyncOption::LibDirs, buildcc::base::SyncOption::ExternalLibDeps, buildcc::base::SyncOption::PreprocessorFlags, buildcc::base::SyncOption::CommonCompileFlags, buildcc::base::SyncOption::PchCompileFlags, buildcc::base::SyncOption::PchObjectFlags, buildcc::base::SyncOption::AsmCompileFlags, buildcc::base::SyncOption::CCompileFlags, buildcc::base::SyncOption::CppCompileFlags, buildcc::base::SyncOption::LinkFlags, buildcc::base::SyncOption::CompileDependencies, buildcc::base::SyncOption::LinkDependencies, }); CHECK_EQUAL(destTarget.GetSourceFiles().size(), 1); CHECK_EQUAL(destTarget.GetHeaderFiles().size(), 1); CHECK_EQUAL(destTarget.GetPchFiles().size(), 1); CHECK_EQUAL(destTarget.GetLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetExternalLibDeps().size(), 1); CHECK_EQUAL(destTarget.GetIncludeDirs().size(), 1); CHECK_EQUAL(destTarget.GetLibDirs().size(), 1); CHECK_EQUAL(destTarget.GetPreprocessorFlags().size(), 1); CHECK_EQUAL(destTarget.GetCommonCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetPchObjectFlags().size(), 1); CHECK_EQUAL(destTarget.GetAsmCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetCppCompileFlags().size(), 1); CHECK_EQUAL(destTarget.GetLinkFlags().size(), 1); CHECK_EQUAL(destTarget.GetCompileDependencies().size(), 1); CHECK_EQUAL(destTarget.GetLinkDependencies().size(), 1); } TEST(TargetTestSyncGroup, InsertCrash) { buildcc::base::Target srcTarget( "srcTarget", buildcc::base::TargetType::Executable, gcc, "data"); buildcc::base::Target destTarget( "destTarget", buildcc::base::TargetType::Executable, gcc, "data"); CHECK_THROWS( std::exception, destTarget.Insert(srcTarget, { (buildcc::base::SyncOption)65535, })); } int main(int ac, char **av) { buildcc::env::init(BUILD_SCRIPT_SOURCE, BUILD_TARGET_SYNC_INTERMEDIATE_DIR); fs::remove_all(buildcc::env::get_project_build_dir()); return CommandLineTestRunner::RunAllTests(ac, av); }
43.717791
80
0.643489
coder137
ad92d8b87b81e135a743d279b9d2394a1e5980ef
1,267
cpp
C++
Practice/2018/2018.9.20/HDU3401.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.9.20/HDU3401.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.9.20/HDU3401.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=2020; const int inf=1000000000; int n,mxP,W; int F[maxN][maxN]; int Q[maxN]; int main(){ int TTT;scanf("%d",&TTT); while (TTT--){ scanf("%d%d%d",&n,&mxP,&W); for (int i=0;i<=n;i++) for (int j=0;j<=mxP;j++) F[i][j]=-inf; F[0][0]=0; for (int i=1;i<=n;i++){ int as,bs,ap,bp;scanf("%d%d%d%d",&ap,&bp,&as,&bs); int lst=max(0,i-W-1); for (int j=0;j<=mxP;j++) F[i][j]=max(F[i][j],F[i-1][j]); int L=1,R=0; for (int j=0;j<=mxP;j++){ while ((L<=R)&&(Q[L]<j-as)) L++; if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+ap*Q[L]-ap*j); while ((L<=R)&&(F[lst][Q[R]]+ap*Q[R]<=F[lst][j]+ap*j)) R--; Q[++R]=j; } L=1;R=0; for (int j=mxP;j>=0;j--){ while ((L<=R)&&(Q[L]>j+bs)) L++; if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+bp*Q[L]-bp*j); while ((L<=R)&&(F[lst][Q[R]]+bp*Q[R]<=F[lst][j]+bp*j)) R--; Q[++R]=j; } } /* for (int i=1;i<=n;i++){ for (int j=0;j<=mxP;j++) cout<<F[i][j]<<" "; cout<<endl; } //*/ int Ans=0; for (int i=0;i<=mxP;i++) Ans=max(Ans,F[n][i]); printf("%d\n",Ans); } return 0; }
21.844828
63
0.488556
SYCstudio
74e9d4d61b88ce15b98c91641534eff6ce020164
36,023
cpp
C++
src/blas/backends/mklcpu/cpu_level1.cpp
codeplaysoftware/oneMKL
87f4feaf67f84f02c63834ad82030d3e86a476d4
[ "Apache-2.0" ]
null
null
null
src/blas/backends/mklcpu/cpu_level1.cpp
codeplaysoftware/oneMKL
87f4feaf67f84f02c63834ad82030d3e86a476d4
[ "Apache-2.0" ]
null
null
null
src/blas/backends/mklcpu/cpu_level1.cpp
codeplaysoftware/oneMKL
87f4feaf67f84f02c63834ad82030d3e86a476d4
[ "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. * * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ #include <CL/sycl.hpp> #include "cpu_common.hpp" namespace onemkl { namespace mklcpu { void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sasum>(cgh, [=]() { accessor_result[0] = ::sasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dasum>(cgh, [=]() { accessor_result[0] = ::dasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_scasum>(cgh, [=]() { accessor_result[0] = ::scasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void asum(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dzasum>(cgh, [=]() { accessor_result[0] = ::dzasum((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_saxpy>(cgh, [=]() { ::saxpy((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_daxpy>(cgh, [=]() { ::daxpy((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, std::complex<float> alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { float alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_caxpy>(cgh, [=]() { MKL_Complex8 alpha_ = { alpha_real, alpha_imag }; ::caxpy((const MKL_INT *)&n, (const MKL_Complex8 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void axpy(cl::sycl::queue &queue, int64_t n, std::complex<double> alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { double alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zaxpy>(cgh, [=]() { MKL_Complex16 alpha_ = { alpha_real, alpha_imag }; ::zaxpy((const MKL_INT *)&n, (const MKL_Complex16 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_scopy>(cgh, [=]() { ::scopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dcopy>(cgh, [=]() { ::dcopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_ccopy>(cgh, [=]() { ::ccopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void copy(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zcopy>(cgh, [=]() { ::zcopy((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sdot>(cgh, [=]() { accessor_result[0] = ::sdot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_ddot>(cgh, [=]() { accessor_result[0] = ::ddot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dsdot>(cgh, [=]() { accessor_result[0] = ::dsdot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotc(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<float>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cdotc>(cgh, [=]() { ::cdotc(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotc(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<double>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdotc>(cgh, [=]() { ::zdotc(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotu(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<float>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cdotu>(cgh, [=]() { ::cdotu(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void dotu(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, cl::sycl::buffer<std::complex<double>, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdotu>(cgh, [=]() { ::zdotu(accessor_result.get_pointer(), (const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_isamin>(cgh, [=]() { accessor_result[0] = ::cblas_isamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.template get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.template get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_idamin>(cgh, [=]() { accessor_result[0] = ::cblas_idamin((const MKL_INT)n, accessor_x.get_pointer(), (const MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_icamin>(cgh, [=]() { accessor_result[0] = ::cblas_icamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamin(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_izamin>(cgh, [=]() { accessor_result[0] = ::cblas_izamin((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_isamax>(cgh, [=]() { accessor_result[0] = ::cblas_isamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_idamax>(cgh, [=]() { accessor_result[0] = ::cblas_idamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_icamax>(cgh, [=]() { accessor_result[0] = ::cblas_icamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void iamax(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<int64_t, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_izamax>(cgh, [=]() { accessor_result[0] = ::cblas_izamax((MKL_INT)n, accessor_x.get_pointer(), (MKL_INT)incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.template get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.template get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_snrm2>(cgh, [=]() { accessor_result[0] = ::snrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dnrm2>(cgh, [=]() { accessor_result[0] = ::dnrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_scnrm2>(cgh, [=]() { accessor_result[0] = ::scnrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void nrm2(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_dznrm2>(cgh, [=]() { accessor_result[0] = ::dznrm2((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, float c, float s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srot>(cgh, [=]() { ::srot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, double c, double s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drot>(cgh, [=]() { ::drot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy, float c, float s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_csrot>(cgh, [=]() { ::csrot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rot(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy, double c, double s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdrot>(cgh, [=]() { ::zdrot((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, &c, &s); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<float, 1> &a, cl::sycl::buffer<float, 1> &b, cl::sycl::buffer<float, 1> &c, cl::sycl::buffer<float, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srotg>(cgh, [=]() { ::srotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<double, 1> &a, cl::sycl::buffer<double, 1> &b, cl::sycl::buffer<double, 1> &c, cl::sycl::buffer<double, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drotg>(cgh, [=]() { ::drotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<std::complex<float>, 1> &a, cl::sycl::buffer<std::complex<float>, 1> &b, cl::sycl::buffer<float, 1> &c, cl::sycl::buffer<std::complex<float>, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_crotg>(cgh, [=]() { ::crotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotg(cl::sycl::queue &queue, cl::sycl::buffer<std::complex<double>, 1> &a, cl::sycl::buffer<std::complex<double>, 1> &b, cl::sycl::buffer<double, 1> &c, cl::sycl::buffer<std::complex<double>, 1> &s) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_a = a.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_b = b.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_c = c.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_s = s.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zrotg>(cgh, [=]() { ::zrotg(accessor_a.get_pointer(), accessor_b.get_pointer(), accessor_c.get_pointer(), accessor_s.get_pointer()); }); }); } void rotm(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read>(cgh); host_task<class mkl_kernel_srotm>(cgh, [=]() { ::srotm((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, accessor_param.get_pointer()); }); }); } void rotm(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy, cl::sycl::buffer<double, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read>(cgh); host_task<class mkl_kernel_drotm>(cgh, [=]() { ::drotm((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy, accessor_param.get_pointer()); }); }); } void rotmg(cl::sycl::queue &queue, cl::sycl::buffer<float, 1> &d1, cl::sycl::buffer<float, 1> &d2, cl::sycl::buffer<float, 1> &x1, float y1, cl::sycl::buffer<float, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_d1 = d1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_d2 = d2.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_x1 = x1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_srotmg>(cgh, [=]() { ::srotmg(accessor_d1.get_pointer(), accessor_d2.get_pointer(), accessor_x1.get_pointer(), (float *)&y1, accessor_param.get_pointer()); }); }); } void rotmg(cl::sycl::queue &queue, cl::sycl::buffer<double, 1> &d1, cl::sycl::buffer<double, 1> &d2, cl::sycl::buffer<double, 1> &x1, double y1, cl::sycl::buffer<double, 1> &param) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_d1 = d1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_d2 = d2.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_x1 = x1.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_param = param.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_drotmg>(cgh, [=]() { ::drotmg(accessor_d1.get_pointer(), accessor_d2.get_pointer(), accessor_x1.get_pointer(), (double *)&y1, accessor_param.get_pointer()); }); }); } void scal(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<float, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_sscal>(cgh, [=]() { ::sscal((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<double, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dscal>(cgh, [=]() { ::dscal((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, std::complex<float> alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { float alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cscal>(cgh, [=]() { MKL_Complex8 alpha_ = { alpha_real, alpha_imag }; ::cscal((const MKL_INT *)&n, (const MKL_Complex8 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, float alpha, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_csscal>(cgh, [=]() { ::csscal((const MKL_INT *)&n, (const float *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, std::complex<double> alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { double alpha_real = alpha.real(), alpha_imag = alpha.imag(); auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zscal>(cgh, [=]() { MKL_Complex16 alpha_ = { alpha_real, alpha_imag }; ::zscal((const MKL_INT *)&n, (const MKL_Complex16 *)&alpha_, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void scal(cl::sycl::queue &queue, int64_t n, double alpha, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zdscal>(cgh, [=]() { ::zdscal((const MKL_INT *)&n, (const double *)&alpha, accessor_x.get_pointer(), (const MKL_INT *)&incx); }); }); } void sdsdot(cl::sycl::queue &queue, int64_t n, float sb, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy, cl::sycl::buffer<float, 1> &result) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read>(cgh); auto accessor_result = result.get_access<cl::sycl::access::mode::write>(cgh); host_task<class mkl_kernel_sdsdot>(cgh, [=]() { accessor_result[0] = ::sdsdot((const MKL_INT *)&n, (const float *)&sb, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<float, 1> &x, int64_t incx, cl::sycl::buffer<float, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_sswap>(cgh, [=]() { ::sswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<double, 1> &x, int64_t incx, cl::sycl::buffer<double, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_dswap>(cgh, [=]() { ::dswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<float>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<float>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_cswap>(cgh, [=]() { ::cswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } void swap(cl::sycl::queue &queue, int64_t n, cl::sycl::buffer<std::complex<double>, 1> &x, int64_t incx, cl::sycl::buffer<std::complex<double>, 1> &y, int64_t incy) { queue.submit([&](cl::sycl::handler &cgh) { auto accessor_x = x.get_access<cl::sycl::access::mode::read_write>(cgh); auto accessor_y = y.get_access<cl::sycl::access::mode::read_write>(cgh); host_task<class mkl_kernel_zswap>(cgh, [=]() { ::zswap((const MKL_INT *)&n, accessor_x.get_pointer(), (const MKL_INT *)&incx, accessor_y.get_pointer(), (const MKL_INT *)&incy); }); }); } } // namespace mklcpu } // namespace onemkl
50.311453
100
0.593621
codeplaysoftware
74eb16ecdaec46a2353f1cac77e1ede012497221
2,722
hh
C++
StRoot/StTrsMaker/include/StTrsAnalogSignal.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StTrsMaker/include/StTrsAnalogSignal.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StTrsMaker/include/StTrsAnalogSignal.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/***************************************************************** * * $Id: StTrsAnalogSignal.hh,v 1.7 2005/09/09 22:12:48 perev Exp $ * * Author: brian Nov 1, 1998 * ***************************************************************** * Description: * ***************************************************************** * * $Log: StTrsAnalogSignal.hh,v $ * Revision 1.7 2005/09/09 22:12:48 perev * Bug fix + IdTruth added * * Revision 1.6 2003/12/24 13:44:51 fisyak * Add (GEANT) track Id information in Trs; propagate it via St_tpcdaq_Maker; account interface change in StTrsZeroSuppressedReaded in StMixerMaker * * Revision 1.5 2003/09/02 17:59:16 perev * gcc 3.2 updates + WarnOff * * Revision 1.4 2000/01/10 23:11:30 lasiuk * Include MACROS for compatibility with SUN CC5.0 * * Revision 1.3 1999/01/15 11:03:14 lasiuk * modify << operator for STL use * * Revision 1.2 1998/11/13 21:29:46 lasiuk * << operator * * Revision 1.1 1998/11/10 17:12:08 fisyak * Put Brian trs versin into StRoot * * Revision 1.1 1998/11/01 13:46:43 lasiuk * Initial Revision * ******************************************************************/ #ifndef ST_TRS_ANALOGSIGNAL_HH #define ST_TRS_ANALOGSIGNAL_HH #include <assert.h> #include <Stiostream.h> #include <utility> #if defined (__SUNPRO_CC) && __SUNPRO_CC >= 0x500 using std::pair; #endif class StTrsAnalogSignal { public: StTrsAnalogSignal(); StTrsAnalogSignal(float, float, int id=0); ~StTrsAnalogSignal(); //StTrsAnalogSignal(const StTrsAnalogSignal&); // use default //StTrsAnalogSignal& operator=(const StTrsAnalogSignal&); // use default StTrsAnalogSignal& operator+=(const StTrsAnalogSignal&); // access functions float time() const; float amplitude() const; int id() const {return mId;} void setTime(float); void setAmplitude(float); void scaleAmplitude(float); void setId(int id) {mId = id;} protected: int mId; // geant track no. float mTime; float mAmp; }; inline float StTrsAnalogSignal::time() const {return mTime;} inline float StTrsAnalogSignal::amplitude() const {return mAmp; } inline void StTrsAnalogSignal::setTime(float t) { mTime = t; } inline void StTrsAnalogSignal::setAmplitude(float a) { mAmp = a; } inline void StTrsAnalogSignal::scaleAmplitude(float fac){ mAmp *= fac;} // Non-member function ostream& operator<<(ostream&, const StTrsAnalogSignal&); class StTrsAnalogSignalComparator { public: bool operator()(StTrsAnalogSignal x, StTrsAnalogSignal y) { return (x.time() < y.time()); } }; #endif
29.912088
147
0.596988
xiaohaijin
74ec603469299cc223e9acc4b38b1f65f655f6f3
7,128
cpp
C++
src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// null_polarity_generator.cpp // // Anton Betten // December 11, 2015 #include "foundations.h" using namespace std; namespace orbiter { namespace foundations { null_polarity_generator::null_polarity_generator() { null(); } null_polarity_generator::~null_polarity_generator() { freeself(); } void null_polarity_generator::null() { nb_candidates = NULL; cur_candidate = NULL; candidates = NULL; Mtx = NULL; v = NULL; w = NULL; Points = NULL; nb_gens = 0; Data = NULL; transversal_length = NULL; } void null_polarity_generator::freeself() { int i; if (nb_candidates) { FREE_int(nb_candidates); } if (cur_candidate) { FREE_int(cur_candidate); } if (candidates) { for (i = 0; i < n + 1; i++) { FREE_int(candidates[i]); } FREE_pint(candidates); } if (Mtx) { FREE_int(Mtx); } if (v) { FREE_int(v); } if (w) { FREE_int(w); } if (Points) { FREE_int(Points); } if (Data) { FREE_int(Data); } if (transversal_length) { FREE_int(transversal_length); } null(); } void null_polarity_generator::init(finite_field *F, int n, int verbose_level) { int f_v = (verbose_level >= 1); int i; number_theory_domain NT; geometry_global Gg; if (f_v) { cout << "null_polarity_generator::init" << endl; } null_polarity_generator::F = F; null_polarity_generator::n = n; q = F->q; qn = NT.i_power_j(q, n); nb_candidates = NEW_int(n + 1); cur_candidate = NEW_int(n); candidates = NEW_pint(n + 1); for (i = 0; i < n + 1; i++) { candidates[i] = NEW_int(qn); } Mtx = NEW_int(n * n); v = NEW_int(n); w = NEW_int(n); Points = NEW_int(qn * n); for (i = 0; i < qn; i++) { Gg.AG_element_unrank(q, Points + i * n, 1, n, i); } create_first_candidate_set(verbose_level); if (f_v) { cout << "first candidate set has size " << nb_candidates[0] << endl; } //backtrack_search(0 /* depth */, verbose_level); int first_moved = n; int nb; nb_gens = 0; first_moved = n; transversal_length = NEW_int(n); for (i = 0; i < n; i++) { transversal_length[i] = 1; } count_strong_generators(nb_gens, transversal_length, first_moved, 0, verbose_level); if (f_v) { cout << "We found " << nb_gens << " strong generators" << endl; cout << "transversal_length = "; Orbiter->Int_vec.print(cout, transversal_length, n); cout << endl; cout << "group order: "; print_longinteger_after_multiplying(cout, transversal_length, n); cout << endl; } Data = NEW_int(nb_gens * n * n); nb = 0; first_moved = n; get_strong_generators(Data, nb, first_moved, 0, verbose_level); if (nb != nb_gens) { cout << "nb != nb_gens" << endl; exit(1); } if (f_v) { cout << "The strong generators are:" << endl; for (i = 0; i < nb_gens; i++) { cout << "generator " << i << " / " << nb_gens << ":" << endl; Orbiter->Int_vec.matrix_print(Data + i * n * n, n, n); } } if (f_v) { cout << "null_polarity_generator::init done" << endl; } } int null_polarity_generator::count_strong_generators( int &nb, int *transversal_length, int &first_moved, int depth, int verbose_level) { //int f_v = (verbose_level >= 1); int a; if (depth == n) { //cout << "solution " << nb << endl; //int_matrix_print(Mtx, n, n); if (first_moved < n) { transversal_length[first_moved]++; } nb++; return FALSE; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { if (cur_candidate[depth] && depth < first_moved) { first_moved = depth; } a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); if (!count_strong_generators(nb, transversal_length, first_moved, depth + 1, verbose_level) && depth > first_moved) { return FALSE; } } return TRUE; } int null_polarity_generator::get_strong_generators( int *Data, int &nb, int &first_moved, int depth, int verbose_level) { //int f_v = (verbose_level >= 1); int a; if (depth == n) { //cout << "solution " << nb << endl; //int_matrix_print(Mtx, n, n); Orbiter->Int_vec.copy(Mtx, Data + nb * n * n, n * n); nb++; return FALSE; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { if (cur_candidate[depth] && depth < first_moved) { first_moved = depth; } a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); if (!get_strong_generators(Data, nb, first_moved, depth + 1, verbose_level) && depth > first_moved) { return FALSE; } } return TRUE; } void null_polarity_generator::backtrack_search( int &nb_sol, int depth, int verbose_level) { int f_v = (verbose_level >= 1); int a; if (depth == n) { if (f_v) { cout << "solution " << nb_sol << endl; Orbiter->Int_vec.matrix_print(Mtx, n, n); } nb_sol++; return; } for (cur_candidate[depth] = 0; cur_candidate[depth] < nb_candidates[depth]; cur_candidate[depth]++) { a = candidates[depth][cur_candidate[depth]]; if (FALSE) { cout << "depth " << depth << " " << cur_candidate[depth] << " / " << nb_candidates[depth] << " which is " << a << endl; } Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n); create_next_candidate_set(depth, 0 /* verbose_level */); backtrack_search(nb_sol, depth + 1, verbose_level); } } void null_polarity_generator::create_first_candidate_set( int verbose_level) { int f_v = (verbose_level >= 1); int i, nb; if (f_v) { cout << "null_polarity_generator::create_" "first_candidate_set" << endl; } nb = 0; for (i = 0; i < qn; i++) { Orbiter->Int_vec.copy(Points + i * n, v, n); if (dot_product(v, v) == 1) { candidates[0][nb++] = i; } } nb_candidates[0] = nb; if (f_v) { cout << "null_polarity_generator::create_" "first_candidate_set done" << endl; } } void null_polarity_generator::create_next_candidate_set( int level, int verbose_level) { int f_v = (verbose_level >= 1); int i, ai, nb; if (f_v) { cout << "null_polarity_generator::create_next_candidate_set " "level=" << level << endl; } nb = 0; Orbiter->Int_vec.copy(Mtx + level * n, v, n); for (i = 0; i < nb_candidates[level]; i++) { ai = candidates[level][i]; Orbiter->Int_vec.copy(Points + ai * n, w, n); if (dot_product(v, w) == 0) { candidates[level + 1][nb++] = ai; } } nb_candidates[level + 1] = nb; if (f_v) { cout << "null_polarity_generator::create_next_candidate_set " "done, found " << nb_candidates[level + 1] << " candidates at level " << level + 1 << endl; } } int null_polarity_generator::dot_product(int *u1, int *u2) { return F->dot_product(n, u1, u2); } } }
21.46988
77
0.621633
abetten
74eee9b62a2bd412cc6a87a05fd4f4edc0834614
1,204
cpp
C++
advent_of_code/2021/src/2120b.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
advent_of_code/2021/src/2120b.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
advent_of_code/2021/src/2120b.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#include "common/stl/base.h" #include "common/vector/read_lines.h" #include "common/vector/sum.h" int main_2120b() { auto vs = nvector::ReadLines(); vector<unsigned> vm; for (auto c : vs[0]) vm.push_back((c == '#') ? 1 : 0); unsigned steps = 50, shift = steps + 2, n = vs.size() - 2, m = vs[2].size(); unsigned N = n + 2 * shift, M = m + 2 * shift; vector<vector<unsigned>> v(N, vector<unsigned>(M, 0)); for (unsigned i = 0; i < n; ++i) { auto& s = vs[i + 2]; for (unsigned j = 0; j < s.size(); ++j) v[i + shift][j + shift] = ((s[j] == '#') ? 1 : 0); } auto v2 = v; unsigned d = 0; for (unsigned is = 0; is < steps; ++is) { for (unsigned i = 0; i + 2 < N; ++i) { for (unsigned j = 0; j + 2 < M; ++j) { unsigned x = 0; for (unsigned di = 0; di < 3; ++di) { for (unsigned dj = 0; dj < 3; ++dj) { x = 2 * x + v[i + di][j + dj]; } } v2[i + 1][j + 1] = vm[x]; } } d = vm[d * 511]; for (unsigned i = 0; i < N; ++i) v2[i][0] = v2[i][M - 1] = d; for (unsigned j = 0; j < M; ++j) v2[0][j] = v2[N - 1][j] = d; v.swap(v2); } cout << nvector::SumVV(v) << endl; return 0; }
30.871795
78
0.457641
Loks-
74f0c8a1d5da6817ae2eb75fa412eb8d051f6cfa
8,707
cpp
C++
libraries/DueFlash/efc.cpp
sschiesser/Arduino_MPU9150
59f338eab642bd15970d929fd939312b1b5b2576
[ "MIT" ]
65
2015-01-22T15:34:13.000Z
2022-03-24T17:29:07.000Z
libraries/DueFlash/efc.cpp
sschiesser/Arduino_MPU9150
59f338eab642bd15970d929fd939312b1b5b2576
[ "MIT" ]
16
2015-04-30T01:50:04.000Z
2021-03-18T11:01:56.000Z
libraries/DueFlash/efc.cpp
sschiesser/Arduino_MPU9150
59f338eab642bd15970d929fd939312b1b5b2576
[ "MIT" ]
44
2015-02-23T11:01:45.000Z
2021-05-01T07:11:13.000Z
/** * \file * * \brief Enhanced Embedded Flash Controller (EEFC) driver for SAM. * * Copyright (c) 2011-2012 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #include "efc.h" /// @cond 0 /**INDENT-OFF**/ #ifdef __cplusplus extern "C" { #endif /**INDENT-ON**/ /// @endcond /** * \defgroup sam_drivers_efc_group Enhanced Embedded Flash Controller (EEFC) * * The Enhanced Embedded Flash Controller ensures the interface of the Flash * block with the 32-bit internal bus. * * @{ */ /* Address definition for read operation */ # define READ_BUFF_ADDR0 IFLASH0_ADDR # define READ_BUFF_ADDR1 IFLASH1_ADDR /* Flash Writing Protection Key */ #define FWP_KEY 0x5Au #if (SAM4S || SAM4E) #define EEFC_FCR_FCMD(value) \ ((EEFC_FCR_FCMD_Msk & ((value) << EEFC_FCR_FCMD_Pos))) #define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE | EEFC_FSR_FLERR) #else #define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE) #endif /* * Local function declaration. * Because they are RAM functions, they need 'extern' declaration. */ extern void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr); extern uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr); /** * \brief Initialize the EFC controller. * * \param ul_access_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. * \param ul_fws The number of wait states in cycle (no shift). * * \return 0 if successful. */ uint32_t efc_init(Efc *p_efc, uint32_t ul_access_mode, uint32_t ul_fws) { efc_write_fmr(p_efc, ul_access_mode | EEFC_FMR_FWS(ul_fws)); return EFC_RC_OK; } /** * \brief Enable the flash ready interrupt. * * \param p_efc Pointer to an EFC instance. */ void efc_enable_frdy_interrupt(Efc *p_efc) { uint32_t ul_fmr = p_efc->EEFC_FMR; efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FRDY); } /** * \brief Disable the flash ready interrupt. * * \param p_efc Pointer to an EFC instance. */ void efc_disable_frdy_interrupt(Efc *p_efc) { uint32_t ul_fmr = p_efc->EEFC_FMR; efc_write_fmr(p_efc, ul_fmr & (~EEFC_FMR_FRDY)); } /** * \brief Set flash access mode. * * \param p_efc Pointer to an EFC instance. * \param ul_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit. */ void efc_set_flash_access_mode(Efc *p_efc, uint32_t ul_mode) { uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FAM); efc_write_fmr(p_efc, ul_fmr | ul_mode); } /** * \brief Get flash access mode. * * \param p_efc Pointer to an EFC instance. * * \return 0 for 128-bit or EEFC_FMR_FAM for 64-bit. */ uint32_t efc_get_flash_access_mode(Efc *p_efc) { return (p_efc->EEFC_FMR & EEFC_FMR_FAM); } /** * \brief Set flash wait state. * * \param p_efc Pointer to an EFC instance. * \param ul_fws The number of wait states in cycle (no shift). */ void efc_set_wait_state(Efc *p_efc, uint32_t ul_fws) { uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FWS_Msk); efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FWS(ul_fws)); } /** * \brief Get flash wait state. * * \param p_efc Pointer to an EFC instance. * * \return The number of wait states in cycle (no shift). */ uint32_t efc_get_wait_state(Efc *p_efc) { return ((p_efc->EEFC_FMR & EEFC_FMR_FWS_Msk) >> EEFC_FMR_FWS_Pos); } /** * \brief Perform the given command and wait until its completion (or an error). * * \note Unique ID commands are not supported, use efc_read_unique_id. * * \param p_efc Pointer to an EFC instance. * \param ul_command Command to perform. * \param ul_argument Optional command argument. * * \note This function will automatically choose to use IAP function. * * \return 0 if successful, otherwise returns an error code. */ uint32_t efc_perform_command(Efc *p_efc, uint32_t ul_command, uint32_t ul_argument) { /* Unique ID commands are not supported. */ if (ul_command == EFC_FCMD_STUI || ul_command == EFC_FCMD_SPUI) { return EFC_RC_NOT_SUPPORT; } /* Use IAP function with 2 parameters in ROM. */ static uint32_t(*iap_perform_command) (uint32_t, uint32_t); uint32_t ul_efc_nb = (p_efc == EFC0) ? 0 : 1; iap_perform_command = (uint32_t(*)(uint32_t, uint32_t)) *((uint32_t *) CHIP_FLASH_IAP_ADDRESS); iap_perform_command(ul_efc_nb, EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(ul_argument) | EEFC_FCR_FCMD(ul_command)); return (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS); } /** * \brief Get the current status of the EEFC. * * \note This function clears the value of some status bits (FLOCKE, FCMDE). * * \param p_efc Pointer to an EFC instance. * * \return The current status. */ uint32_t efc_get_status(Efc *p_efc) { return p_efc->EEFC_FSR; } /** * \brief Get the result of the last executed command. * * \param p_efc Pointer to an EFC instance. * * \return The result of the last executed command. */ uint32_t efc_get_result(Efc *p_efc) { return p_efc->EEFC_FRR; } /** * \brief Perform read sequence. Supported sequences are read Unique ID and * read User Signature * * \param p_efc Pointer to an EFC instance. * \param ul_cmd_st Start command to perform. * \param ul_cmd_sp Stop command to perform. * \param p_ul_buf Pointer to an data buffer. * \param ul_size Buffer size. * * \return 0 if successful, otherwise returns an error code. */ RAMFUNC uint32_t efc_perform_read_sequence(Efc *p_efc, uint32_t ul_cmd_st, uint32_t ul_cmd_sp, uint32_t *p_ul_buf, uint32_t ul_size) { volatile uint32_t ul_status; uint32_t ul_cnt; uint32_t *p_ul_data = (uint32_t *) ((p_efc == EFC0) ? READ_BUFF_ADDR0 : READ_BUFF_ADDR1); if (p_ul_buf == NULL) { return EFC_RC_INVALID; } p_efc->EEFC_FMR |= (0x1u << 16); /* Send the Start Read command */ p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) | EEFC_FCR_FCMD(ul_cmd_st); /* Wait for the FRDY bit in the Flash Programming Status Register * (EEFC_FSR) falls. */ do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) == EEFC_FSR_FRDY); /* The data is located in the first address of the Flash * memory mapping. */ for (ul_cnt = 0; ul_cnt < ul_size; ul_cnt++) { p_ul_buf[ul_cnt] = p_ul_data[ul_cnt]; } /* To stop the read mode */ p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) | EEFC_FCR_FCMD(ul_cmd_sp); /* Wait for the FRDY bit in the Flash Programming Status Register (EEFC_FSR) * rises. */ do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); p_efc->EEFC_FMR &= ~(0x1u << 16); return EFC_RC_OK; } /** * \brief Set mode register. * * \param p_efc Pointer to an EFC instance. * \param ul_fmr Value of mode register */ RAMFUNC void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr) { p_efc->EEFC_FMR = ul_fmr; } /** * \brief Perform command. * * \param p_efc Pointer to an EFC instance. * \param ul_fcr Flash command. * * \return The current status. */ RAMFUNC uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr) { volatile uint32_t ul_status; p_efc->EEFC_FCR = ul_fcr; do { ul_status = p_efc->EEFC_FSR; } while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY); return (ul_status & EEFC_ERROR_FLAGS); } //@} /// @cond 0 /**INDENT-OFF**/ #ifdef __cplusplus } #endif /**INDENT-ON**/ /// @endcond
25.533724
80
0.718847
sschiesser
74f0dc372993a6eb967f8ac3bcacaef6bf33825f
825
cpp
C++
SkimaServer/SkimaServer/LightningPumpkinSkill.cpp
dlakwwkd/CommitAgain
3fdad38f7951b1a58ae244bd5d68f5a92e97f633
[ "MIT" ]
1
2015-04-07T06:08:11.000Z
2015-04-07T06:08:11.000Z
SkimaServer/SkimaServer/LightningPumpkinSkill.cpp
dlakwwkd/CommitAgain
3fdad38f7951b1a58ae244bd5d68f5a92e97f633
[ "MIT" ]
1
2015-01-01T11:14:29.000Z
2015-01-01T12:19:04.000Z
SkimaServer/SkimaServer/LightningPumpkinSkill.cpp
dlakwwkd/CommitAgain
3fdad38f7951b1a58ae244bd5d68f5a92e97f633
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "LightningPumpkinSkill.h" #include "ClientSession.h" #include "Game.h" #include "Player.h" #include "Unit.h" #include "Timer.h" #include <time.h> LightningPumpkinSkill::LightningPumpkinSkill(Player* owner) { m_Owner = owner; m_Damage = 64; m_Scale = Reduce(80.0f); } LightningPumpkinSkill::~LightningPumpkinSkill() { } void LightningPumpkinSkill::SkillCast(SkillKey key, const b2Vec2& heroPos, const b2Vec2& targetPos) { auto hero = m_Owner->GetMyHero(); hero->EndMove(); m_TaretPos = targetPos; auto client = m_Owner->GetClient(); client->SkillBroadCast(hero->GetUnitID(), heroPos, targetPos, key); auto game = m_Owner->GetGame(); Timer::Push(game, 200, 10, this, &LightningPumpkinSkill::RandomAttack, Reduce(200.0f), 200, 5, 10, EF_LIGHTNING); }
22.916667
117
0.705455
dlakwwkd
74f16202df8325fc25e2f9fc9cad20384e7b4fd9
5,707
cc
C++
L1TriggerConfig/RPCTriggerConfig/src/L1RPCConeDefinitionProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1TriggerConfig/RPCTriggerConfig/src/L1RPCConeDefinitionProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1TriggerConfig/RPCTriggerConfig/src/L1RPCConeDefinitionProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // // Package: L1RPCConeDefinitionProducer // Class: L1RPCConeDefinitionProducer // /**\class L1RPCConeDefinitionProducer L1RPCConeDefinitionProducer.h L1TriggerConfig/L1RPCConeDefinitionProducer/src/L1RPCConeDefinitionProducer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Tomasz Maciej Frueboes // Created: Mon Feb 23 12:09:06 CET 2009 // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "CondFormats/L1TObjects/interface/L1RPCConeDefinition.h" #include "CondFormats/DataRecord/interface/L1RPCConeDefinitionRcd.h" // // class decleration // class L1RPCConeDefinitionProducer : public edm::ESProducer { public: L1RPCConeDefinitionProducer(const edm::ParameterSet&); ~L1RPCConeDefinitionProducer() override; using ReturnType = std::unique_ptr<L1RPCConeDefinition>; ReturnType produce(const L1RPCConeDefinitionRcd&); private: // ----------member data --------------------------- int m_towerBeg; int m_towerEnd; int m_rollBeg; int m_rollEnd; int m_hwPlaneBeg; int m_hwPlaneEnd; //L1RPCConeDefinition::TLPSizesInTowers m_LPSizesInTowers; L1RPCConeDefinition::TLPSizeVec m_LPSizeVec; //L1RPCConeDefinition::TRingsToTowers m_RingsToTowers; L1RPCConeDefinition::TRingToTowerVec m_ringToTowerVec; //L1RPCConeDefinition::TRingsToLP m_RingsToLP; L1RPCConeDefinition::TRingToLPVec m_ringToLPVec; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // L1RPCConeDefinitionProducer::L1RPCConeDefinitionProducer(const edm::ParameterSet& iConfig) : m_towerBeg(iConfig.getParameter<int>("towerBeg")), m_towerEnd(iConfig.getParameter<int>("towerEnd")), m_rollBeg(iConfig.getParameter<int>("rollBeg")), m_rollEnd(iConfig.getParameter<int>("rollEnd")), m_hwPlaneBeg(iConfig.getParameter<int>("hwPlaneBeg")), m_hwPlaneEnd(iConfig.getParameter<int>("hwPlaneEnd")) { //the following line is needed to tell the framework what // data is being produced setWhatProduced(this); for (int t = m_towerBeg; t <= m_towerEnd; ++t) { std::stringstream name; name << "lpSizeTower" << t; std::vector<int> newSizes = iConfig.getParameter<std::vector<int> >(name.str().c_str()); for (unsigned int lp = 0; lp < newSizes.size(); ++lp) { // L1RPCConeDefinition::TLPSize lps(t, lp, newSizes[lp]); L1RPCConeDefinition::TLPSize lps; lps.m_tower = t; lps.m_LP = lp; lps.m_size = newSizes[lp]; m_LPSizeVec.push_back(lps); } } //now do what ever other initialization is needed // hw planes numbered from 0 to 5 // rolls from 0 to 17 (etaPartition) // // rollConnLP_[roll]_[hwPlane-1] // rollConnLP_5_3 = cms.vint32(6, 0, 0), // ----- roll 5, hwPlane 4 (3+1) is logplane 6 (OK) // // rollConnT_[roll]_[hwPlane-1] // rollConnT_5_3 = cms.vint32(4, -1, -1), // ----- roll 5, hwPlane 4 (3+1) contirubtes to tower 4 (OK) for (int roll = m_rollBeg; roll <= m_rollEnd; ++roll) { //L1RPCConeDefinition::THWplaneToTower newHwPlToTower; //L1RPCConeDefinition::THWplaneToLP newHWplaneToLP; for (int hwpl = m_hwPlaneBeg; hwpl <= m_hwPlaneEnd; ++hwpl) { std::stringstream name; name << "rollConnLP_" << roll << "_" << hwpl; std::vector<int> hwPl2LPVec = iConfig.getParameter<std::vector<int> >(name.str().c_str()); //newHWplaneToLP.push_back(newListLP); for (unsigned int i = 0; i < hwPl2LPVec.size(); ++i) { if (hwPl2LPVec[i] >= 0) { // L1RPCConeDefinition::TRingToLP lp(roll, hwpl, hwPl2LPVec[i],i); L1RPCConeDefinition::TRingToLP lp; lp.m_etaPart = roll; lp.m_hwPlane = hwpl; lp.m_LP = hwPl2LPVec[i]; lp.m_index = i; m_ringToLPVec.push_back(lp); } } std::stringstream name1; name1 << "rollConnT_" << roll << "_" << hwpl; /*L1RPCConeDefinition::TLPList newListT = iConfig.getParameter<std::vector<int> >(name1.str().c_str()); newHwPlToTower.push_back(newListT);*/ std::vector<int> hwPl2TowerVec = iConfig.getParameter<std::vector<int> >(name1.str().c_str()); for (unsigned int i = 0; i < hwPl2TowerVec.size(); ++i) { if (hwPl2TowerVec[i] >= 0) { // L1RPCConeDefinition::TRingToTower rt(roll, hwpl, hwPl2TowerVec[i],i); L1RPCConeDefinition::TRingToTower rt; rt.m_etaPart = roll; rt.m_hwPlane = hwpl; rt.m_tower = hwPl2TowerVec[i]; rt.m_index = i; m_ringToTowerVec.push_back(rt); } } } //m_RingsToTowers.push_back(newHwPlToTower); //m_RingsToLP.push_back(newHWplaneToLP); } } L1RPCConeDefinitionProducer::~L1RPCConeDefinitionProducer() {} // // member functions // // ------------ method called to produce the data ------------ L1RPCConeDefinitionProducer::ReturnType L1RPCConeDefinitionProducer::produce(const L1RPCConeDefinitionRcd& iRecord) { auto pL1RPCConeDefinition = std::make_unique<L1RPCConeDefinition>(); pL1RPCConeDefinition->setFirstTower(m_towerBeg); pL1RPCConeDefinition->setLastTower(m_towerEnd); pL1RPCConeDefinition->setLPSizeVec(m_LPSizeVec); pL1RPCConeDefinition->setRingToLPVec(m_ringToLPVec); pL1RPCConeDefinition->setRingToTowerVec(m_ringToTowerVec); return pL1RPCConeDefinition; } //define this as a plug-in DEFINE_FWK_EVENTSETUP_MODULE(L1RPCConeDefinitionProducer);
31.185792
146
0.682846
ckamtsikis
74f1e26951ff8f3e4bd62a2c05e4f1abc80f4fed
6,575
cpp
C++
Source/WebCore/platform/graphics/chromium/FontCustomPlatformData.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/platform/graphics/chromium/FontCustomPlatformData.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Source/WebCore/platform/graphics/chromium/FontCustomPlatformData.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* * Copyright (C) 2007 Apple Computer, Inc. * Copyright (c) 2007, 2008, 2009, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "FontCustomPlatformData.h" #if OS(WINDOWS) #include "Base64.h" #include "ChromiumBridge.h" #include "OpenTypeUtilities.h" #elif OS(LINUX) #include "SkStream.h" #endif #include "FontPlatformData.h" #include "NotImplemented.h" #include "OpenTypeSanitizer.h" #include "SharedBuffer.h" #if OS(WINDOWS) #include <objbase.h> #elif OS(LINUX) #include <cstring> #endif namespace WebCore { FontCustomPlatformData::~FontCustomPlatformData() { #if OS(WINDOWS) if (m_fontReference) RemoveFontMemResourceEx(m_fontReference); #elif OS(LINUX) if (m_fontReference) m_fontReference->unref(); #endif } FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic, FontRenderingMode mode) { #if OS(WINDOWS) ASSERT(m_fontReference); LOGFONT logFont; // m_name comes from createUniqueFontName, which, in turn, gets // it from base64-encoded uuid (128-bit). So, m_name // can never be longer than LF_FACESIZE (32). if (m_name.length() + 1 >= LF_FACESIZE) { ASSERT_NOT_REACHED(); return FontPlatformData(); } memcpy(logFont.lfFaceName, m_name.charactersWithNullTermination(), sizeof(logFont.lfFaceName[0]) * (1 + m_name.length())); // FIXME: almost identical to FillLogFont in FontCacheWin.cpp. // Need to refactor. logFont.lfHeight = -size; logFont.lfWidth = 0; logFont.lfEscapement = 0; logFont.lfOrientation = 0; logFont.lfUnderline = false; logFont.lfStrikeOut = false; logFont.lfCharSet = DEFAULT_CHARSET; logFont.lfOutPrecision = OUT_TT_ONLY_PRECIS; logFont.lfQuality = ChromiumBridge::layoutTestMode() ? NONANTIALIASED_QUALITY : DEFAULT_QUALITY; // Honor user's desktop settings. logFont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; logFont.lfItalic = italic; logFont.lfWeight = bold ? 700 : 400; HFONT hfont = CreateFontIndirect(&logFont); return FontPlatformData(hfont, size); #elif OS(LINUX) ASSERT(m_fontReference); return FontPlatformData(m_fontReference, "", size, bold && !m_fontReference->isBold(), italic && !m_fontReference->isItalic()); #else notImplemented(); return FontPlatformData(); #endif } #if OS(WINDOWS) // Creates a unique and unpredictable font name, in order to avoid collisions and to // not allow access from CSS. static String createUniqueFontName() { Vector<char> fontUuid(sizeof(GUID)); CoCreateGuid(reinterpret_cast<GUID*>(fontUuid.data())); Vector<char> fontNameVector; base64Encode(fontUuid, fontNameVector); ASSERT(fontNameVector.size() < LF_FACESIZE); return String(fontNameVector.data(), fontNameVector.size()); } #endif #if OS(LINUX) class RemoteFontStream : public SkStream { public: explicit RemoteFontStream(PassRefPtr<SharedBuffer> buffer) : m_buffer(buffer) , m_offset(0) { } virtual ~RemoteFontStream() { } virtual bool rewind() { m_offset = 0; return true; } virtual size_t read(void* buffer, size_t size) { if (!buffer && !size) { // This is request for the length of the stream. return m_buffer->size(); } if (!buffer) { // This is a request to skip bytes. This operation is not supported. return 0; } // This is a request to read bytes. if (!m_buffer->data() || !m_buffer->size()) return 0; size_t left = m_buffer->size() - m_offset; size_t toRead = (left > size) ? size : left; std::memcpy(buffer, m_buffer->data() + m_offset, toRead); m_offset += toRead; return toRead; } private: RefPtr<SharedBuffer> m_buffer; size_t m_offset; }; #endif FontCustomPlatformData* createFontCustomPlatformData(SharedBuffer* buffer) { ASSERT_ARG(buffer, buffer); #if ENABLE(OPENTYPE_SANITIZER) OpenTypeSanitizer sanitizer(buffer); RefPtr<SharedBuffer> transcodeBuffer = sanitizer.sanitize(); if (!transcodeBuffer) return 0; // validation failed. buffer = transcodeBuffer.get(); #endif #if OS(WINDOWS) // Introduce the font to GDI. AddFontMemResourceEx should be used with care, because it will pollute the process's // font namespace (Windows has no API for creating an HFONT from data without exposing the font to the // entire process first). String fontName = createUniqueFontName(); HANDLE fontReference = renameAndActivateFont(buffer, fontName); if (!fontReference) return 0; return new FontCustomPlatformData(fontReference, fontName); #elif OS(LINUX) RemoteFontStream* stream = new RemoteFontStream(buffer); SkTypeface* typeface = SkTypeface::CreateFromStream(stream); if (!typeface) return 0; return new FontCustomPlatformData(typeface); #else notImplemented(); return 0; #endif } }
32.073171
131
0.698251
VincentWei
74f306a640ce5f8555d7c7dc46484aab8ccfd823
7,166
cpp
C++
openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "SurfacePropertyOtherSideConditionsModel.hpp" #include "SurfacePropertyOtherSideConditionsModel_Impl.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/OS_SurfaceProperty_OtherSideConditionsModel_FieldEnums.hxx> #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType()); } SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType()); } SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const SurfacePropertyOtherSideConditionsModel_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& SurfacePropertyOtherSideConditionsModel_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType SurfacePropertyOtherSideConditionsModel_Impl::iddObjectType() const { return SurfacePropertyOtherSideConditionsModel::iddObjectType(); } std::string SurfacePropertyOtherSideConditionsModel_Impl::typeOfModeling() const { boost::optional<std::string> value = getString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling,true); OS_ASSERT(value); return value.get(); } bool SurfacePropertyOtherSideConditionsModel_Impl::isTypeOfModelingDefaulted() const { return isEmpty(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling); } bool SurfacePropertyOtherSideConditionsModel_Impl::setTypeOfModeling(const std::string& typeOfModeling) { bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, typeOfModeling); return result; } void SurfacePropertyOtherSideConditionsModel_Impl::resetTypeOfModeling() { bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, ""); OS_ASSERT(result); } } // detail SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(const Model& model) : ResourceObject(SurfacePropertyOtherSideConditionsModel::iddObjectType(),model) { OS_ASSERT(getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()); // TODO: Appropriately handle the following required object-list fields. bool ok = true; // ok = setHandle(); OS_ASSERT(ok); } IddObjectType SurfacePropertyOtherSideConditionsModel::iddObjectType() { return IddObjectType(IddObjectType::OS_SurfaceProperty_OtherSideConditionsModel); } std::vector<std::string> SurfacePropertyOtherSideConditionsModel::typeOfModelingValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling); } std::string SurfacePropertyOtherSideConditionsModel::typeOfModeling() const { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->typeOfModeling(); } bool SurfacePropertyOtherSideConditionsModel::isTypeOfModelingDefaulted() const { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->isTypeOfModelingDefaulted(); } bool SurfacePropertyOtherSideConditionsModel::setTypeOfModeling(const std::string& typeOfModeling) { return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->setTypeOfModeling(typeOfModeling); } void SurfacePropertyOtherSideConditionsModel::resetTypeOfModeling() { getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->resetTypeOfModeling(); } /// @cond SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(std::shared_ptr<detail::SurfacePropertyOtherSideConditionsModel_Impl> impl) : ResourceObject(std::move(impl)) {} /// @endcond } // model } // openstudio
49.763889
156
0.712113
hongyuanjia
74f4e52256959b567d49b7873b885854d31ccd61
743
cpp
C++
modules/arm_plugin/src/opset/mvn_arm.cpp
pelszkow/openvino_contrib
345788490bd9cdf00c6c1282ceb100aa9d559fe9
[ "Apache-2.0" ]
56
2020-11-19T15:04:30.000Z
2022-03-30T20:06:07.000Z
modules/arm_plugin/src/opset/mvn_arm.cpp
pelszkow/openvino_contrib
345788490bd9cdf00c6c1282ceb100aa9d559fe9
[ "Apache-2.0" ]
130
2020-11-06T12:35:13.000Z
2022-03-31T11:04:27.000Z
modules/arm_plugin/src/opset/mvn_arm.cpp
pelszkow/openvino_contrib
345788490bd9cdf00c6c1282ceb100aa9d559fe9
[ "Apache-2.0" ]
60
2020-11-02T16:40:22.000Z
2022-03-30T20:06:11.000Z
// Copyright (C) 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "mvn_arm.hpp" using namespace ngraph; using namespace ArmPlugin; NGRAPH_RTTI_DEFINITION(opset::ArmMVN, "ArmMVN", 0); opset::ArmMVN::~ArmMVN() {} opset::ArmMVN::ArmMVN(const ngraph::Output<ngraph::Node>& data, float eps) : Op({data}), m_eps(eps) { constructor_validate_and_infer_types(); } std::shared_ptr<ngraph::Node> opset::ArmMVN::clone_with_new_inputs(const ngraph::OutputVector& new_args) const { auto num_args = new_args.size(); if (num_args == 1) { return std::make_shared<ArmMVN>(new_args.at(0), m_eps); } else { throw ngraph_error("Unsupported number of arguments for ArmMVN operation"); } }
27.518519
112
0.701211
pelszkow
74fb4f9a9e6e4b1e55690f043bf843f1d514fa01
493
hpp
C++
libs/common/include/zia/common/Network.hpp
IamBlueSlime/Zia
14aeccaa817171ca9fbd8221c6d9a32ea203a221
[ "MIT" ]
1
2020-03-09T12:17:55.000Z
2020-03-09T12:17:55.000Z
libs/common/include/zia/common/Network.hpp
IamBlueSlime/Zia
14aeccaa817171ca9fbd8221c6d9a32ea203a221
[ "MIT" ]
null
null
null
libs/common/include/zia/common/Network.hpp
IamBlueSlime/Zia
14aeccaa817171ca9fbd8221c6d9a32ea203a221
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2020 ** CPP_zia_2019 ** File description: ** zia common Network.hpp */ #pragma once #include "openZia/OperatingSystem.hpp" #if defined(SYSTEM_LINUX) || defined(SYSTEM_DARWIN) #include <arpa/inet.h> #include <unistd.h> typedef int socket_t; #elif defined(SYSTEM_WINDOWS) #define _WINSOCKAPI_ #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #include <BaseTsd.h> #include <io.h> typedef SOCKET socket_t; #endif
18.259259
51
0.681542
IamBlueSlime
74ffcc1aececed48317c8333de4994d83b35f0fa
1,576
cpp
C++
src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "chapter_07_concurrency/problem_064_parallel_sort_algorithm.h" #include <algorithm> // shuffle, sort #include <fmt/ostream.h> #include <fmt/ranges.h> #include <iostream> // cout #include <numeric> // iota #include <ostream> #include <random> // default_random_engine, random_device #include <vector> void problem_64_main(std::ostream& os) { std::vector<int> v(20); std::iota(std::begin(v), std::end(v), -10); std::ranges::shuffle(v, std::default_random_engine{ std::random_device{}() }); fmt::print(os, "v = {}\n\n", v); { auto w{ v }; std::sort(std::begin(w), std::end(w)); fmt::print(os, "std::sort(v); v = {}\n", w); } { auto w{ v }; tmcppc::algorithm::quicksort(std::begin(w), std::end(w)); fmt::print(os, "quicksort(v); v = {}\n", w); } { auto w{ v }; tmcppc::algorithm::parallel_quicksort(std::begin(w), std::end(w)); fmt::print(os, "parallel_quicksort; v = {}\n\n", w); } } // Parallel sort algorithm // // Write a parallel version of the sort algorithm // as defined for problem "57. Sort Algorithm", in "Chapter 6, Algorithms and Data Structures", // which, given a pair of random access iterators to define its lower and upper bounds, // sorts the elements of the range using the quicksort algorithm. // The function should use the comparison operators for comparing the elements of the range. // The level of parallelism and the way to achieve it is an implementation detail. void problem_64_main() { problem_64_main(std::cout); }
33.531915
95
0.645939
rturrado
2d0217af5b5ef2ba1846bb426344741cd144532b
830
hpp
C++
src/user/Session.hpp
hephaisto/sharebuy
12a14aba0f7119d6db59f57e067d1f438f7a6329
[ "MIT" ]
null
null
null
src/user/Session.hpp
hephaisto/sharebuy
12a14aba0f7119d6db59f57e067d1f438f7a6329
[ "MIT" ]
9
2016-02-15T22:33:31.000Z
2017-06-18T20:00:30.000Z
src/user/Session.hpp
hephaisto/sharebuy
12a14aba0f7119d6db59f57e067d1f438f7a6329
[ "MIT" ]
null
null
null
#ifndef H_SHAREBUY_SESSION #define H_SHAREBUY_SESSION #include <Wt/Dbo/Session> #include <Wt/Dbo/ptr> #include <Wt/Dbo/backend/Sqlite3> #include <Wt/Auth/Login> #include <Wt/Auth/PasswordService> #include "User.hpp" namespace dbo = Wt::Dbo; typedef Wt::Auth::Dbo::UserDatabase<AuthInfo> UserDatabase; class Session : public dbo::Session { public: Session(const std::string& sqliteDb); virtual ~Session(); Wt::Auth::AbstractUserDatabase& users(); Wt::Auth::Login& login() { return login_; } static void configureAuth(); static const Wt::Auth::AuthService& auth(); static const Wt::Auth::PasswordService& passwordAuth(); static const std::vector<const Wt::Auth::OAuthService *>& oAuth(); dbo::ptr<User> user(); private: dbo::backend::Sqlite3 connection_; UserDatabase *users_; Wt::Auth::Login login_; }; #endif
21.842105
67
0.728916
hephaisto
2d04a20ace6f1ce3782ca36e1139c1e13ed135cc
5,934
hpp
C++
engine/include/ph/config/GlobalConfig.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/config/GlobalConfig.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/config/GlobalConfig.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // 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. #pragma once #include <sfz/containers/DynArray.hpp> #include <sfz/memory/Allocator.hpp> #include "ph/config/Setting.hpp" namespace ph { using sfz::Allocator; using sfz::DynArray; // GlobalConfig // ------------------------------------------------------------------------------------------------ struct GlobalConfigImpl; // Pimpl pattern /// A global configuration class /// /// The singleton instance should be acquired from the Phantasy Engine global context /// /// Setting invariants: /// 1, All settings are owned by the singleton instance, no one else may delete the memory. /// 2, A setting, once created, can never be destroyed or removed during runtime. /// 3, A setting will occupy the same place in memory for the duration of the program's runtime. /// 4, A setting can not change section or key identifiers once created. /// /// These invariants mean that it is safe (and expected) to store direct pointers to settings and /// read/write to them when needed. However, settings may change type during runtime. So it is /// recommended to store a pointer to the setting itself and not its internal int value for /// example. /// /// Settings are expected to stay relatively static during the runtime of a program. They are not /// meant for communication and should not be changed unless the user specifically requests for /// them to be changed. class GlobalConfig { public: // Constructors & destructors // -------------------------------------------------------------------------------------------- inline GlobalConfig() noexcept : mImpl(nullptr) {} // Compile fix for Emscripten GlobalConfig(const GlobalConfig&) = delete; GlobalConfig& operator= (const GlobalConfig&) = delete; GlobalConfig(GlobalConfig&&) = delete; GlobalConfig& operator= (GlobalConfig&&) = delete; ~GlobalConfig() noexcept; // Methods // -------------------------------------------------------------------------------------------- void init(const char* basePath, const char* fileName, Allocator* allocator) noexcept; void destroy() noexcept; void load() noexcept; bool save() noexcept; /// Gets the specified Setting. If it does not exist it will be created (type int with value 0). /// The optional parameter "created" returns whether the Setting was created or already existed. Setting* createSetting(const char* section, const char* key, bool* created = nullptr) noexcept; // Getters // -------------------------------------------------------------------------------------------- /// Gets the specified Setting. Returns nullptr if it does not exist. Setting* getSetting(const char* section, const char* key) noexcept; Setting* getSetting(const char* key) noexcept; /// Returns pointers to all available settings void getAllSettings(DynArray<Setting*>& settings) noexcept; /// Returns all sections available void getSections(DynArray<str32>& sections) noexcept; /// Returns all settings available in a given section void getSectionSettings(const char* section, DynArray<Setting*>& settings) noexcept; // Sanitizers // -------------------------------------------------------------------------------------------- /// A sanitizer is basically a wrapper around createSetting, with the addition that it also /// ensures that the Setting is of the requested type and with values conforming to the /// specified bounds. If the setting does not exist or is of an incompatible type it will be /// set to the specified default value. Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, const IntBounds& bounds = IntBounds(0)) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, const FloatBounds& bounds = FloatBounds(0.0f)) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, const BoolBounds& bounds = BoolBounds(false)) noexcept; Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, int32_t defaultValue = 0, int32_t minValue = INT32_MIN, int32_t maxValue = INT32_MAX, int32_t step = 1) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, float defaultValue = 0.0f, float minValue = FLT_MIN, float maxValue = FLT_MAX) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, bool defaultValue = false) noexcept; private: // Private members // -------------------------------------------------------------------------------------------- GlobalConfigImpl* mImpl; }; // Statically owned global config // ------------------------------------------------------------------------------------------------ /// Statically owned global config. Default constructed. Only to be used for setContext() in /// PhantasyEngineMain.cpp during boot. GlobalConfig* getStaticGlobalConfigBoot() noexcept; } // namespace ph
38.283871
99
0.6606
PetorSFZ
2d0610dac0adb339db6413db131b63d509369c40
1,866
cpp
C++
Source/doom.cpp
louistio/devilution
093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22
[ "Unlicense" ]
1
2018-07-13T13:53:54.000Z
2018-07-13T13:53:54.000Z
Source/doom.cpp
louistio/devilution
093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22
[ "Unlicense" ]
null
null
null
Source/doom.cpp
louistio/devilution
093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22
[ "Unlicense" ]
1
2018-07-13T13:54:03.000Z
2018-07-13T13:54:03.000Z
//HEADER_GOES_HERE #include "../types.h" int doom_quest_time; // weak int doom_stars_drawn; // weak void *pDoomCel; int doomflag; // weak int DoomQuestState; // idb int __cdecl doom_get_frame_from_time() { int result; // eax if ( DoomQuestState == 36001 ) result = 31; else result = DoomQuestState / 1200; return result; } void __cdecl doom_alloc_cel() { pDoomCel = DiabloAllocPtr(229376); } void __cdecl doom_cleanup() { void *v0; // ecx v0 = pDoomCel; pDoomCel = 0; mem_free_dbg(v0); } void __cdecl doom_load_graphics() { if ( doom_quest_time == 31 ) { strcpy(tempstr, "Items\\Map\\MapZDoom.CEL"); } else if ( doom_quest_time >= 10 ) { sprintf(tempstr, "Items\\Map\\MapZ00%i.CEL", doom_quest_time); } else { sprintf(tempstr, "Items\\Map\\MapZ000%i.CEL", doom_quest_time); } LoadFileWithMem(tempstr, pDoomCel); } // 525750: using guessed type int doom_quest_time; void __cdecl doom_init() { int v0; // eax doomflag = 1; doom_alloc_cel(); v0 = -(doom_get_frame_from_time() != 31); _LOBYTE(v0) = v0 & 0xE1; doom_quest_time = v0 + 31; doom_load_graphics(); } // 525750: using guessed type int doom_quest_time; // 52575C: using guessed type int doomflag; void __cdecl doom_close() { if ( doomflag ) { doomflag = 0; doom_cleanup(); } } // 52575C: using guessed type int doomflag; void __cdecl doom_draw() { if ( doomflag ) { if ( doom_quest_time != 31 && ++doom_stars_drawn >= 5 ) { doom_stars_drawn = 0; if ( ++doom_quest_time > doom_get_frame_from_time() ) doom_quest_time = 0; doom_load_graphics(); } CelDecodeOnly(64, 511, pDoomCel, 1, 640); } } // 525750: using guessed type int doom_quest_time; // 525754: using guessed type int doom_stars_drawn; // 52575C: using guessed type int doomflag;
19.642105
66
0.652197
louistio
2d074bbd96dc9d758388298efe25c1b5a9a5c03e
45,898
cpp
C++
src/pathfinder.cpp
ctu-mrs/mrs_octomap_planner
4ce6b91bdd7e67265536431d159c2fd05d467939
[ "BSD-3-Clause" ]
1
2022-02-22T02:45:40.000Z
2022-02-22T02:45:40.000Z
src/pathfinder.cpp
ctu-mrs/mrs_octomap_planner
4ce6b91bdd7e67265536431d159c2fd05d467939
[ "BSD-3-Clause" ]
null
null
null
src/pathfinder.cpp
ctu-mrs/mrs_octomap_planner
4ce6b91bdd7e67265536431d159c2fd05d467939
[ "BSD-3-Clause" ]
null
null
null
/* includes //{ */ #include <memory> #include <ros/init.h> #include <ros/ros.h> #include <ros/package.h> #include <nodelet/nodelet.h> #include <octomap/OcTree.h> #include <octomap_msgs/Octomap.h> #include <octomap_msgs/conversions.h> #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <numeric> #include <mrs_lib/attitude_converter.h> #include <mrs_lib/batch_visualizer.h> #include <mrs_lib/param_loader.h> #include <mrs_lib/subscribe_handler.h> #include <mrs_lib/mutex.h> #include <mrs_lib/scope_timer.h> #include <mrs_lib/service_client_handler.h> #include <mrs_lib/transformer.h> #include <mrs_lib/geometry/misc.h> #include <mrs_lib/geometry/cyclic.h> #include <mrs_msgs/PositionCommand.h> #include <mrs_msgs/Vec4.h> #include <mrs_msgs/ReferenceStampedSrv.h> #include <mrs_msgs/GetPathSrv.h> #include <mrs_msgs/MpcPredictionFullState.h> #include <mrs_msgs/TrajectoryReferenceSrv.h> #include <mrs_msgs/ControlManagerDiagnostics.h> #include <mrs_msgs/DynamicsConstraints.h> #include <mrs_msgs/TrajectoryReference.h> #include <mrs_msgs/PathfinderDiagnostics.h> #include <std_srvs/Trigger.h> #include <pathfinder/astar_planner.hpp> //} namespace pathfinder { /* defines //{ */ typedef enum { STATE_IDLE, STATE_PLANNING, STATE_MOVING, } State_t; const std::string _state_names_[] = {"IDLE", "PLANNING", "MOVING"}; using OcTree_t = octomap::OcTree; using OcTreePtr_t = std::shared_ptr<octomap::OcTree>; using OcTreeMsgConstPtr_t = octomap_msgs::OctomapConstPtr; //} /* class Pathfinder //{ */ class Pathfinder : public nodelet::Nodelet { public: virtual void onInit(); private: ros::NodeHandle nh_; bool is_initialized_ = false; std::atomic<bool> ready_to_plan_ = false; std::string _uav_name_; // params double _euclidean_distance_cutoff_; double _safe_obstacle_distance_; double _distance_penalty_; double _greedy_penalty_; int _planning_tree_fractor_; double _map_resolution_; double _timeout_threshold_; double _time_for_trajectory_generator_; double _max_waypoint_distance_; double _min_altitude_; double _max_altitude_; double _rate_main_timer_; double _rate_diagnostics_timer_; double _rate_future_check_timer_; double _replan_after_; bool _unknown_is_occupied_; double planning_tree_resolution_; octomap_msgs::OctomapConstPtr octree_msg_ptr_; std::string octree_frame_; std::mutex mutex_octree_msg_ptr_; // visualizer params double _points_scale_; double _lines_scale_; // initial condition octomap::point3d initial_pos_; double initial_heading_; std::mutex mutex_initial_condition_; std::atomic<bool> got_initial_pos_; mrs_lib::BatchVisualizer bv_input_; std::mutex mutex_bv_input_; std::shared_ptr<mrs_lib::BatchVisualizer> bv_planner_; bool bv_planner_frame_set_ = false; mrs_lib::BatchVisualizer bv_processed_; std::mutex mutex_bv_processed_; // subscribers mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand> sh_position_cmd_; mrs_lib::SubscribeHandler<octomap_msgs::Octomap> sh_octomap_; mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState> sh_mpc_prediction_; mrs_lib::SubscribeHandler<mrs_msgs::ControlManagerDiagnostics> sh_control_manager_diag_; mrs_lib::SubscribeHandler<mrs_msgs::DynamicsConstraints> sh_constraints_; // publishers ros::Publisher pub_diagnostics_; // subscriber callbacks void callbackPositionCmd(mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>& wrp); void callbackOctomap(mrs_lib::SubscribeHandler<octomap_msgs::Octomap>& wrp); void callbackMpcPrediction(mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>& wrp); // service servers ros::ServiceServer service_server_goto_; ros::ServiceServer service_server_reference_; // service server callbacks bool callbackGoto([[maybe_unused]] mrs_msgs::Vec4::Request& req, mrs_msgs::Vec4::Response& res); bool callbackReference([[maybe_unused]] mrs_msgs::ReferenceStampedSrv::Request& req, mrs_msgs::ReferenceStampedSrv::Response& res); // service clients mrs_lib::ServiceClientHandler<mrs_msgs::GetPathSrv> sc_get_trajectory_; mrs_lib::ServiceClientHandler<mrs_msgs::TrajectoryReferenceSrv> sc_trajectory_reference_; mrs_lib::ServiceClientHandler<std_srvs::Trigger> sc_hover_; // timers ros::Timer timer_main_; void timerMain([[maybe_unused]] const ros::TimerEvent& evt); ros::Timer timer_diagnostics_; void timerDiagnostics([[maybe_unused]] const ros::TimerEvent& evt); ros::Timer timer_future_check_; void timerFutureCheck([[maybe_unused]] const ros::TimerEvent& evt); // diagnostics mrs_msgs::PathfinderDiagnostics diagnostics_; std::mutex mutex_diagnostics_; // timeouts void timeoutOctomap(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutPositionCmd(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutMpcPrediction(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); void timeoutControlManagerDiag(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs); // transformer std::unique_ptr<mrs_lib::Transformer> transformer_; std::string current_control_frame_; std::mutex mutex_current_control_frame_; // planning std::atomic<int> replanning_counter_ = 0; ros::Time time_last_plan_; // state machine std::atomic<State_t> state_; void changeState(const State_t new_state); mrs_msgs::Reference user_goal_; std::mutex mutex_user_goal_; octomap::point3d internal_goal_; std::atomic<bool> set_timepoints_ = false; ros::Time replanning_start_timepoint_; ros::Time replanning_end_timepoint_; octomap::point3d replanning_point_; std::mutex mutex_replanning_point_; // routines void setReplanningPoint(const mrs_msgs::TrajectoryReference& traj); std::vector<double> estimateSegmentTimes(const std::vector<Eigen::Vector4d>& vertices, const bool use_heading); std::optional<OcTreePtr_t> msgToMap(const octomap_msgs::OctomapConstPtr octomap); /** * @brief returns planning initial condition for a given future time based on the MPC prediction horizon * * @param time * * @return x, y, z, heading reference */ std::optional<mrs_msgs::ReferenceStamped> getInitialCondition(const ros::Time time); void hover(void); }; //} /* onInit() //{ */ void Pathfinder::onInit() { nh_ = nodelet::Nodelet::getMTPrivateNodeHandle(); ros::Time::waitForValid(); ROS_INFO("[Pathfinder]: initializing"); mrs_lib::ParamLoader param_loader(nh_, "Pathfinder"); param_loader.loadParam("uav_name", _uav_name_); param_loader.loadParam("main_timer/rate", _rate_main_timer_); param_loader.loadParam("diagnostics_timer/rate", _rate_diagnostics_timer_); param_loader.loadParam("future_check_timer/rate", _rate_future_check_timer_); param_loader.loadParam("euclidean_distance_cutoff", _euclidean_distance_cutoff_); param_loader.loadParam("safe_obstacle_distance", _safe_obstacle_distance_); param_loader.loadParam("distance_penalty", _distance_penalty_); param_loader.loadParam("greedy_penalty", _greedy_penalty_); param_loader.loadParam("planning_tree_fractor", _planning_tree_fractor_); param_loader.loadParam("map_resolution", _map_resolution_); param_loader.loadParam("unknown_is_occupied", _unknown_is_occupied_); param_loader.loadParam("points_scale", _points_scale_); param_loader.loadParam("lines_scale", _lines_scale_); param_loader.loadParam("max_waypoint_distance", _max_waypoint_distance_); param_loader.loadParam("min_altitude", _min_altitude_); param_loader.loadParam("max_altitude", _max_altitude_); param_loader.loadParam("timeout_threshold", _timeout_threshold_); param_loader.loadParam("replan_after", _replan_after_); param_loader.loadParam("time_for_trajectory_generator", _time_for_trajectory_generator_); if (!param_loader.loadedSuccessfully()) { ROS_ERROR("[Pathfinder]: could not load all parameters"); ros::shutdown(); } planning_tree_resolution_ = _map_resolution_ * pow(2, _planning_tree_fractor_); // | ---------------------- state machine --------------------- | state_ = STATE_IDLE; // | ----------------------- publishers ----------------------- | pub_diagnostics_ = nh_.advertise<mrs_msgs::PathfinderDiagnostics>("diagnostics_out", 1); // | ----------------------- subscribers ---------------------- | mrs_lib::SubscribeHandlerOptions shopts; shopts.nh = nh_; shopts.node_name = "Pathfinder"; shopts.no_message_timeout = mrs_lib::no_timeout; shopts.threadsafe = true; shopts.autostart = true; shopts.queue_size = 1; shopts.transport_hints = ros::TransportHints().tcpNoDelay(); sh_position_cmd_ = mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>(shopts, "position_cmd_in", ros::Duration(3.0), &Pathfinder::timeoutPositionCmd, this, &Pathfinder::callbackPositionCmd, this); sh_octomap_ = mrs_lib::SubscribeHandler<octomap_msgs::Octomap>(shopts, "octomap_in", ros::Duration(5.0), &Pathfinder::timeoutOctomap, this, &Pathfinder::callbackOctomap, this); sh_mpc_prediction_ = mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>( shopts, "mpc_prediction_in", ros::Duration(3.0), &Pathfinder::timeoutMpcPrediction, this, &Pathfinder::callbackMpcPrediction, this); sh_control_manager_diag_ = mrs_lib::SubscribeHandler<mrs_msgs::ControlManagerDiagnostics>(shopts, "control_manager_diag_in", ros::Duration(3.0), &Pathfinder::timeoutControlManagerDiag, this); sh_constraints_ = mrs_lib::SubscribeHandler<mrs_msgs::DynamicsConstraints>(shopts, "constraints_in"); // | --------------------- service clients -------------------- | sc_get_trajectory_ = mrs_lib::ServiceClientHandler<mrs_msgs::GetPathSrv>(nh_, "trajectory_generation_out"); sc_trajectory_reference_ = mrs_lib::ServiceClientHandler<mrs_msgs::TrajectoryReferenceSrv>(nh_, "trajectory_reference_out"); sc_hover_ = mrs_lib::ServiceClientHandler<std_srvs::Trigger>(nh_, "hover_out"); // | --------------------- service servers -------------------- | service_server_goto_ = nh_.advertiseService("goto_in", &Pathfinder::callbackGoto, this); service_server_reference_ = nh_.advertiseService("reference_in", &Pathfinder::callbackReference, this); // | ----------------------- transformer ---------------------- | transformer_ = std::make_unique<mrs_lib::Transformer>("Pathfinder"); transformer_->setDefaultPrefix(_uav_name_); transformer_->retryLookupNewest(true); // | -------------------- batch visualiuzer ------------------- | bv_input_ = mrs_lib::BatchVisualizer(nh_, "visualize_input", ""); bv_input_.setPointsScale(_points_scale_); bv_input_.setLinesScale(_lines_scale_); bv_planner_ = std::make_shared<mrs_lib::BatchVisualizer>(nh_, "visualize_planner", ""); bv_planner_->setPointsScale(_points_scale_); bv_planner_->setLinesScale(_lines_scale_); bv_processed_ = mrs_lib::BatchVisualizer(nh_, "visualize_processed", ""); bv_processed_.setPointsScale(_points_scale_); bv_processed_.setLinesScale(_lines_scale_); // | ------------------------- timers ------------------------- | timer_main_ = nh_.createTimer(ros::Rate(_rate_main_timer_), &Pathfinder::timerMain, this); timer_future_check_ = nh_.createTimer(ros::Rate(_rate_future_check_timer_), &Pathfinder::timerFutureCheck, this); timer_diagnostics_ = nh_.createTimer(ros::Rate(_rate_diagnostics_timer_), &Pathfinder::timerDiagnostics, this); // | --------------------- finish the init -------------------- | is_initialized_ = true; ROS_INFO("[Pathfinder]: initialized"); } //} // | ------------------------ callbacks ----------------------- | /* callbackPositionCmd() //{ */ void Pathfinder::callbackPositionCmd(mrs_lib::SubscribeHandler<mrs_msgs::PositionCommand>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting position cmd"); } //} /* timeoutPositionCmd() //{ */ void Pathfinder::timeoutPositionCmd(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_position_cmd_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: position cmd timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackOctomap() //{ */ void Pathfinder::callbackOctomap(mrs_lib::SubscribeHandler<octomap_msgs::Octomap>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting octomap"); OcTreeMsgConstPtr_t octomap_ptr = wrp.getMsg(); { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr_ = octomap_ptr; octree_frame_ = octomap_ptr->header.frame_id; } if (!bv_planner_frame_set_) { bv_planner_->setParentFrame(octomap_ptr->header.frame_id); bv_planner_frame_set_ = true; } { std::scoped_lock lock(mutex_bv_input_); bv_input_.setParentFrame(octomap_ptr->header.frame_id); } { std::scoped_lock lock(mutex_bv_processed_); bv_processed_.setParentFrame(octomap_ptr->header.frame_id); } } //} /* timeoutOctomap() //{ */ void Pathfinder::timeoutOctomap(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_octomap_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: octomap timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackMpcPrediction() //{ */ void Pathfinder::callbackMpcPrediction(mrs_lib::SubscribeHandler<mrs_msgs::MpcPredictionFullState>& wrp) { if (!is_initialized_) { return; } ROS_INFO_ONCE("[Pathfinder]: getting mpc prediction"); } //} /* timeoutMpcPrediction() //{ */ void Pathfinder::timeoutMpcPrediction(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: MPC prediction timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* timeoutControlManagerDiag() //{ */ void Pathfinder::timeoutControlManagerDiag(const std::string& topic, const ros::Time& last_msg, [[maybe_unused]] const int n_pubs) { if (!is_initialized_) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } if (state_ != STATE_IDLE) { ROS_WARN_THROTTLE(1.0, "[Pathfinder]: Control manager diag timeouted!"); ready_to_plan_ = false; changeState(STATE_IDLE); hover(); } } //} /* callbackGoto() //{ */ bool Pathfinder::callbackGoto([[maybe_unused]] mrs_msgs::Vec4::Request& req, mrs_msgs::Vec4::Response& res) { /* prerequisities //{ */ if (!is_initialized_) { return false; } if (!ready_to_plan_) { std::stringstream ss; ss << "not ready to plan, missing data"; ROS_ERROR_STREAM_THROTTLE(0.5, "[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } //} // | -------- transform the reference to the map frame -------- | { mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); mrs_msgs::ReferenceStamped reference; reference.header.frame_id = position_cmd->header.frame_id; reference.reference.position.x = req.goal[0]; reference.reference.position.y = req.goal[1]; reference.reference.position.z = req.goal[2]; reference.reference.heading = req.goal[3]; auto result = transformer_->transformSingle(reference, octree_frame_); if (result) { std::scoped_lock lock(mutex_user_goal_); user_goal_ = result.value().reference; } else { std::stringstream ss; ss << "could not transform the reference from " << position_cmd->header.frame_id << " to " << octree_frame_; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } } changeState(STATE_PLANNING); { std::scoped_lock lock(mutex_bv_input_, mutex_user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal_.position.x, user_goal_.position.y, user_goal_.position.z)); bv_input_.publish(); } res.success = true; res.message = "goal set"; return true; } //} /* callbackReference() //{ */ bool Pathfinder::callbackReference([[maybe_unused]] mrs_msgs::ReferenceStampedSrv::Request& req, mrs_msgs::ReferenceStampedSrv::Response& res) { /* prerequisities //{ */ if (!is_initialized_) { return false; } if (!ready_to_plan_) { std::stringstream ss; ss << "not ready to plan, missing data"; ROS_ERROR_STREAM_THROTTLE(0.5, "[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } //} // | -------- transform the reference to the map frame -------- | { mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); mrs_msgs::ReferenceStamped reference; reference.header = req.header; reference.reference = req.reference; auto result = transformer_->transformSingle(reference, octree_frame_); if (result) { std::scoped_lock lock(mutex_user_goal_); user_goal_ = result.value().reference; } else { std::stringstream ss; ss << "could not transform the reference from " << req.header.frame_id << " to " << octree_frame_; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); res.success = false; res.message = ss.str(); return true; } } changeState(STATE_PLANNING); { std::scoped_lock lock(mutex_bv_input_, mutex_user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal_.position.x, user_goal_.position.y, user_goal_.position.z)); bv_input_.publish(); } res.success = true; res.message = "reference set"; return true; } //} // | ------------------------- timers ------------------------- | /* timerMain() //{ */ void Pathfinder::timerMain([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } /* prerequsitioes //{ */ const bool got_octomap = sh_octomap_.hasMsg() && (ros::Time::now() - sh_octomap_.lastMsgTime()).toSec() < 2.0; const bool got_position_cmd = sh_position_cmd_.hasMsg() && (ros::Time::now() - sh_position_cmd_.lastMsgTime()).toSec() < 2.0; const bool got_mpc_prediction = sh_mpc_prediction_.hasMsg() && (ros::Time::now() - sh_mpc_prediction_.lastMsgTime()).toSec() < 2.0; const bool got_control_manager_diag = sh_control_manager_diag_.hasMsg() && (ros::Time::now() - sh_control_manager_diag_.lastMsgTime()).toSec() < 2.0; const bool got_constraints = sh_constraints_.hasMsg() && (ros::Time::now() - sh_constraints_.lastMsgTime()).toSec() < 2.0; if (!got_octomap || !got_position_cmd || !got_mpc_prediction || !got_control_manager_diag || !got_constraints) { ROS_INFO_THROTTLE(1.0, "[Pathfinder]: waiting for data: octomap = %s, position cmd = %s, MPC prediction = %s, ControlManager diag = %s, constraints = %s", got_octomap ? "TRUE" : "FALSE", got_position_cmd ? "TRUE" : "FALSE", got_mpc_prediction ? "TRUE" : "FALSE", got_control_manager_diag ? "TRUE" : "FALSE", got_constraints ? "TRUE" : "FALSE"); return; } else { ready_to_plan_ = true; } //} ROS_INFO_ONCE("[Pathfinder]: main timer spinning"); const auto user_goal = mrs_lib::get_mutexed(mutex_user_goal_, user_goal_); const mrs_msgs::ControlManagerDiagnosticsConstPtr control_manager_diag = sh_control_manager_diag_.getMsg(); const mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); octomap::point3d user_goal_octpoint; user_goal_octpoint.x() = user_goal.position.x; user_goal_octpoint.y() = user_goal.position.y; user_goal_octpoint.z() = user_goal.position.z; { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.header.stamp = ros::Time::now(); diagnostics_.header.frame_id = octree_frame_; diagnostics_.idle = false; diagnostics_.desired_reference.x = user_goal.position.x; diagnostics_.desired_reference.y = user_goal.position.y; diagnostics_.desired_reference.z = user_goal.position.z; } switch (state_) { /* STATE_IDLE //{ */ case STATE_IDLE: { { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = true; } break; } //} /* STATE_PLANNING //{ */ case STATE_PLANNING: { // copy the octomap locally OcTreeMsgConstPtr_t octree_msg_ptr; std::string octree_frame; { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr = octree_msg_ptr_; octree_frame = octree_frame_; } std::optional<OcTreePtr_t> octree = msgToMap(octree_msg_ptr); if (!octree) { ROS_ERROR("[Pathfinder]: don't have a map"); break; } { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = false; } if (replanning_counter_ >= 2) { ROS_ERROR("[Pathfinder]: planning failed, the uav is stuck"); changeState(STATE_IDLE); break; } // get the initial condition double time_for_planning; if (control_manager_diag->tracker_status.have_goal) { time_for_planning = _timeout_threshold_; } else { time_for_planning = _timeout_threshold_ + pow(1.5, float(replanning_counter_)); } ROS_INFO("[Pathfinder]: planning timeout %.2f s", time_for_planning); ros::Time init_cond_time = ros::Time::now() + ros::Duration(time_for_planning + _time_for_trajectory_generator_); ROS_INFO("[Pathfinder]: init cond time %.2f s", init_cond_time.toSec()); auto initial_condition = getInitialCondition(init_cond_time); if (!initial_condition) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not obtain initial condition for planning"); hover(); changeState(STATE_IDLE); break; } ROS_INFO("[Pathfinder]: init cond time stamp %.2f", initial_condition.value().header.stamp.toSec()); octomap::point3d plan_from; plan_from.x() = initial_condition.value().reference.position.x; plan_from.y() = initial_condition.value().reference.position.y; plan_from.z() = initial_condition.value().reference.position.z; pathfinder::AstarPlanner planner = pathfinder::AstarPlanner(_safe_obstacle_distance_, _euclidean_distance_cutoff_, planning_tree_resolution_, _planning_tree_fractor_, _distance_penalty_, _greedy_penalty_, _timeout_threshold_, _max_waypoint_distance_, _min_altitude_, _max_altitude_, _unknown_is_occupied_, bv_planner_); std::pair<std::vector<octomap::point3d>, bool> waypoints = planner.findPath(plan_from, user_goal_octpoint, octree.value(), time_for_planning); // path is complete if (waypoints.second) { replanning_counter_ = 0; waypoints.first.push_back(user_goal_octpoint); } else { if (waypoints.first.size() < 2) { ROS_WARN("[Pathfinder]: path not found"); replanning_counter_++; break; } double front_x = waypoints.first.front().x(); double front_y = waypoints.first.front().y(); double front_z = waypoints.first.front().z(); double back_x = waypoints.first.back().x(); double back_y = waypoints.first.back().y(); double back_z = waypoints.first.back().z(); double path_start_end_dist = sqrt(pow(front_x - back_x, 2) + pow(front_y - back_y, 2) + pow(front_z - back_z, 2)); if (path_start_end_dist < 0.1) { ROS_WARN("[Pathfinder]: path too short"); replanning_counter_++; changeState(STATE_PLANNING); break; } } time_last_plan_ = ros::Time::now(); diagnostics_.best_goal.x = waypoints.first.back().x(); diagnostics_.best_goal.y = waypoints.first.back().y(); diagnostics_.best_goal.z = waypoints.first.back().z(); { std::scoped_lock lock(mutex_initial_condition_); mrs_msgs::PositionCommandConstPtr position_cmd = sh_position_cmd_.getMsg(); auto octree_frame = mrs_lib::get_mutexed(mutex_octree_msg_ptr_, octree_frame_); // transform the position cmd to the map frame mrs_msgs::ReferenceStamped position_cmd_ref; position_cmd_ref.header = position_cmd->header; position_cmd_ref.reference.position.x = position_cmd->position.x; position_cmd_ref.reference.position.y = position_cmd->position.y; position_cmd_ref.reference.position.z = position_cmd->position.z; position_cmd_ref.reference.heading = position_cmd->heading; auto res = transformer_->transformSingle(position_cmd_ref, octree_frame); if (!res) { ROS_ERROR("[Pathfinder]: could not transform position cmd to the map frame"); return; } initial_pos_.x() = res.value().reference.position.x; initial_pos_.y() = res.value().reference.position.y; initial_pos_.z() = res.value().reference.position.z; initial_heading_ = res.value().reference.heading; } ros::Time path_stamp = initial_condition.value().header.stamp; if (ros::Time::now() > path_stamp || !control_manager_diag->tracker_status.have_goal) { path_stamp = ros::Time(0); } mrs_msgs::GetPathSrv srv_get_path; srv_get_path.request.path.header.frame_id = octree_frame_; srv_get_path.request.path.header.stamp = path_stamp; srv_get_path.request.path.fly_now = false; srv_get_path.request.path.relax_heading = true; srv_get_path.request.path.use_heading = true; std::vector<Eigen::Vector4d> eig_waypoints; // create an array of Eigen waypoints for (auto& w : waypoints.first) { Eigen::Vector4d eig_waypoint; eig_waypoint[0] = w.x(); eig_waypoint[1] = w.y(); eig_waypoint[2] = w.z(); eig_waypoint[4] = user_goal.heading; eig_waypoints.push_back(eig_waypoint); } std::vector<double> segment_times = estimateSegmentTimes(eig_waypoints, false); double cum_time = 0; for (int i = 0; i < waypoints.first.size(); i++) { mrs_msgs::Reference ref; ref.position.x = waypoints.first[i].x(); ref.position.y = waypoints.first[i].y(); ref.position.z = waypoints.first[i].z(); ref.heading = user_goal.heading; srv_get_path.request.path.points.push_back(ref); cum_time += segment_times[i]; if (i > 1 && cum_time > 15.0) { ROS_INFO("[Pathfinder]: cutting path in waypoint %d out of %d", i, int(waypoints.first.size())); break; } } ROS_INFO("[Pathfinder]: calling trajectory generation"); { bool success = sc_get_trajectory_.call(srv_get_path); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory failed"); break; } else { if (!srv_get_path.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory failed: '%s'", srv_get_path.response.message.c_str()); break; } } } { std::scoped_lock lock(mutex_bv_processed_); bv_processed_.clearBuffers(); for (auto& p : srv_get_path.response.trajectory.points) { auto v = Eigen::Vector3d(p.position.x, p.position.y, p.position.z); bv_processed_.addPoint(v, 0, 1, 0, 1); } bv_processed_.publish(); } auto trajectory = srv_get_path.response.trajectory; ROS_INFO("[Pathfinder]: Setting replanning point"); setReplanningPoint(trajectory); set_timepoints_ = true; ROS_INFO("[Pathfinder]: publishing trajectory reference"); mrs_msgs::TrajectoryReferenceSrv srv_trajectory_reference; srv_trajectory_reference.request.trajectory = srv_get_path.response.trajectory; srv_trajectory_reference.request.trajectory.fly_now = true; { bool success = sc_trajectory_reference_.call(srv_trajectory_reference); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed"); break; } else { if (!srv_trajectory_reference.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed: '%s'", srv_get_path.response.message.c_str()); break; } else { } } } changeState(STATE_MOVING); break; } //} /* STATE_MOVING //{ */ case STATE_MOVING: { { std::scoped_lock lock(mutex_diagnostics_); diagnostics_.idle = false; } auto initial_pos = mrs_lib::get_mutexed(mutex_initial_condition_, initial_pos_); double dist_to_goal = (initial_pos - user_goal_octpoint).norm(); ROS_INFO_THROTTLE(1.0, "[Pathfinder]: dist to goal: %.2f m", dist_to_goal); if (dist_to_goal < 2 * planning_tree_resolution_) { ROS_INFO("[Pathfinder]: user goal reached"); changeState(STATE_IDLE); break; } if ((ros::Time::now() - (time_last_plan_ + ros::Duration(_replan_after_))).toSec() > 0) { ROS_INFO("[Pathfinder]: triggering replanning"); changeState(STATE_PLANNING); } break; } //} } } //} /* timerFutureCheck() //{ */ void Pathfinder::timerFutureCheck([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } /* preconditions //{ */ if (!sh_control_manager_diag_.hasMsg()) { return; } if (!sh_octomap_.hasMsg()) { return; } if (!sh_mpc_prediction_.hasMsg()) { return; } //} if (state_ == STATE_IDLE) { return; } ROS_INFO_ONCE("[Pathfinder]: future check timer spinning"); // | ----------- check if the prediction is feasible ---------- | // copy the octomap locally OcTreeMsgConstPtr_t octree_msg_ptr; std::string octree_frame; { std::scoped_lock lock(mutex_octree_msg_ptr_); octree_msg_ptr = octree_msg_ptr_; octree_frame = octree_frame_; } auto octree_opt = msgToMap(octree_msg_ptr); if (!octree_opt) { ROS_ERROR("[Pathfinder]: cannot check for collision, don't have a map"); return; } OcTreePtr_t octree = octree_opt.value(); mrs_msgs::MpcPredictionFullStateConstPtr prediction = sh_mpc_prediction_.getMsg(); mrs_msgs::ControlManagerDiagnosticsConstPtr control_manager_diag = sh_control_manager_diag_.getMsg(); if (control_manager_diag->flying_normally && control_manager_diag->tracker_status.have_goal) { geometry_msgs::TransformStamped tf; auto ret = transformer_->getTransform(prediction->header.frame_id, octree_frame, prediction->header.stamp); if (!ret) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not transform position cmd to the map frame! can not check for potential collisions!"); return; } tf = ret.value(); // prepare the potential future trajectory mrs_msgs::TrajectoryReference trajectory; trajectory.header.stamp = ret.value().header.stamp; trajectory.header.frame_id = transformer_->frame_to(ret.value()); trajectory.fly_now = true; trajectory.use_heading = true; trajectory.dt = 0.2; for (int i = 1; i < prediction->position.size(); i++) { mrs_msgs::ReferenceStamped pose; pose.header = prediction->header; pose.reference.position.x = prediction->position[i].x; pose.reference.position.y = prediction->position[i].y; pose.reference.position.z = prediction->position[i].z; pose.reference.heading = prediction->heading[i]; auto transformed_pose = transformer_->transform(pose, tf); if (!transformed_pose) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not transform position cmd to the map frame! can not check for potential collisions!"); return; } trajectory.points.push_back(transformed_pose->reference); } // check if the trajectory is safe for (int i = 0; i < trajectory.points.size() - 1; i++) { octomap::point3d point1(trajectory.points[i].position.x, trajectory.points[i].position.y, trajectory.points[i].position.z); octomap::point3d point2(trajectory.points[i + 1].position.x, trajectory.points[i + 1].position.y, trajectory.points[i + 1].position.z); octomap::KeyRay key_ray; if (octree->computeRayKeys(point1, point2, key_ray)) { bool ray_is_cool = true; for (octomap::KeyRay::iterator it1 = key_ray.begin(), end = key_ray.end(); it1 != end; ++it1) { auto node = octree->search(*it1); if (node && octree->isNodeOccupied(node)) { ray_is_cool = false; break; } } if (!ray_is_cool) { ROS_ERROR_THROTTLE(0.1, "[Pathfinder]: future check found collision with prediction horizon between %d and %d, hovering!", i, i + 1); // shorten the trajectory for (int j = int(trajectory.points.size()) - 1; j >= floor(i / 2.0); j--) { trajectory.points.pop_back(); } mrs_msgs::TrajectoryReferenceSrv srv_trajectory_reference; srv_trajectory_reference.request.trajectory = trajectory; bool success = sc_trajectory_reference_.call(srv_trajectory_reference); if (!success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed"); break; } else { if (!srv_trajectory_reference.response.success) { ROS_ERROR("[Pathfinder]: service call for trajectory reference failed: '%s'", srv_trajectory_reference.response.message.c_str()); break; } } break; } } else { ROS_ERROR_THROTTLE(0.1, "[Pathfinder]: future check failed, could not raytrace!"); hover(); break; } } } } //} /* timerDiagnostics() //{ */ void Pathfinder::timerDiagnostics([[maybe_unused]] const ros::TimerEvent& evt) { if (!is_initialized_) { return; } auto diagnostics = mrs_lib::get_mutexed(mutex_diagnostics_, diagnostics_); try { pub_diagnostics_.publish(diagnostics); } catch (...) { ROS_ERROR("exception caught during publishing topic '%s'", pub_diagnostics_.getTopic().c_str()); } } //} // | ------------------------ routines ------------------------ | /* setReplanningPoint() //{ */ void Pathfinder::setReplanningPoint(const mrs_msgs::TrajectoryReference& traj) { const float x = traj.points.back().position.x; const float y = traj.points.back().position.y; const float z = traj.points.back().position.z; { std::scoped_lock lock(mutex_replanning_point_); replanning_point_.x() = x; replanning_point_.y() = y; replanning_point_.z() = z; } mrs_lib::geometry::Cuboid c(Eigen::Vector3d(x, y, z), Eigen::Vector3d(0.4, 0.4, 0.4), Eigen::Quaterniond::Identity()); { std::scoped_lock lock(mutex_bv_input_); auto user_goal = mrs_lib::get_mutexed(mutex_user_goal_, user_goal_); bv_input_.clearBuffers(); bv_input_.addPoint(Eigen::Vector3d(user_goal.position.x, user_goal.position.y, user_goal.position.z), 0, 1, 0, 1); bv_input_.addCuboid(c, 0.5, 1.0, 1.0, 0.8, true); bv_input_.publish(); } } //} /* changeState() //{ */ void Pathfinder::changeState(const State_t new_state) { const State_t old_state = state_; switch (new_state) { case STATE_PLANNING: { if (old_state == STATE_IDLE) { replanning_counter_ = 0; } } default: { break; } } ROS_INFO("[Pathfinder]: changing state '%s' -> '%s'", _state_names_[old_state].c_str(), _state_names_[new_state].c_str()); state_ = new_state; } //} /* getInitialCondition() //{ */ std::optional<mrs_msgs::ReferenceStamped> Pathfinder::getInitialCondition(const ros::Time des_time) { const mrs_msgs::MpcPredictionFullStateConstPtr prediction_full_state = sh_mpc_prediction_.getMsg(); if ((des_time - prediction_full_state->stamps.back()).toSec() > 0) { ROS_ERROR_THROTTLE(1.0, "[Pathfinder]: could not obtain initial condition, the desired time is too far in the future"); return {}; } mrs_msgs::ReferenceStamped orig_reference; orig_reference.header = prediction_full_state->header; ros::Time future_time_stamp; for (int i = 0; i < prediction_full_state->stamps.size(); i++) { if ((prediction_full_state->stamps[i] - des_time).toSec() > 0) { orig_reference.reference.position.x = prediction_full_state->position[i].x; orig_reference.reference.position.y = prediction_full_state->position[i].y; orig_reference.reference.position.z = prediction_full_state->position[i].z; orig_reference.reference.heading = prediction_full_state->heading[i]; future_time_stamp = prediction_full_state->stamps[i]; break; } } // transform the initial condition to the current map frame auto result = transformer_->transformSingle(orig_reference, octree_frame_); if (result) { mrs_msgs::ReferenceStamped transfomed_reference = result.value(); transfomed_reference.header.stamp = future_time_stamp; return transfomed_reference; } else { std::stringstream ss; ss << "could not transform initial condition to the map frame"; ROS_ERROR_STREAM("[Pathfinder]: " << ss.str()); return {}; } } //} /* hover() //{ */ void Pathfinder::hover(void) { ROS_INFO("[Pathfinder]: triggering hover"); std_srvs::Trigger srv_out; sc_hover_.call(srv_out); } //} /* estimateSegmentTimes() //{ */ std::vector<double> Pathfinder::estimateSegmentTimes(const std::vector<Eigen::Vector4d>& vertices, const bool use_heading) { if (vertices.size() <= 1) { return std::vector<double>(0); } const mrs_msgs::DynamicsConstraintsConstPtr constraints = sh_constraints_.getMsg(); const double v_max_vertical = std::min(constraints->vertical_ascending_speed, constraints->vertical_descending_speed); const double a_max_vertical = std::min(constraints->vertical_ascending_acceleration, constraints->vertical_descending_acceleration); const double j_max_vertical = std::min(constraints->vertical_ascending_jerk, constraints->vertical_descending_jerk); const double v_max_horizontal = constraints->horizontal_speed; const double a_max_horizontal = constraints->horizontal_acceleration; const double j_max_horizontal = constraints->horizontal_jerk; const double heading_acc_max = constraints->heading_acceleration; const double heading_speed_max = constraints->heading_speed; std::vector<double> segment_times; segment_times.reserve(vertices.size() - 1); // for each vertex in the path for (size_t i = 0; i < vertices.size() - 1; i++) { Eigen::Vector3d start = vertices[i].head(3); Eigen::Vector3d end = vertices[i + 1].head(3); double start_hdg = vertices[i](3); double end_hdg = vertices[i + 1](3); double acceleration_time_1 = 0; double acceleration_time_2 = 0; double jerk_time_1 = 0; double jerk_time_2 = 0; double acc_1_coeff = 0; double acc_2_coeff = 0; double distance = (end - start).norm(); double inclinator = atan2(end(2) - start(2), sqrt(pow(end(0) - start(0), 2) + pow(end(1) - start(1), 2))); double v_max, a_max, j_max; if (inclinator > atan2(v_max_vertical, v_max_horizontal) || inclinator < -atan2(v_max_vertical, v_max_horizontal)) { v_max = fabs(v_max_vertical / sin(inclinator)); } else { v_max = fabs(v_max_horizontal / cos(inclinator)); } if (inclinator > atan2(a_max_vertical, a_max_horizontal) || inclinator < -atan2(a_max_vertical, a_max_horizontal)) { a_max = fabs(a_max_vertical / sin(inclinator)); } else { a_max = fabs(a_max_horizontal / cos(inclinator)); } if (inclinator > atan2(j_max_vertical, j_max_horizontal) || inclinator < -atan2(j_max_vertical, j_max_horizontal)) { j_max = fabs(j_max_vertical / sin(inclinator)); } else { j_max = fabs(j_max_horizontal / cos(inclinator)); } if (i >= 1) { Eigen::Vector3d pre = vertices[i - 1].head(3); Eigen::Vector3d vec1 = start - pre; Eigen::Vector3d vec2 = end - start; vec1.normalize(); vec2.normalize(); double scalar = vec1.dot(vec2) < 0 ? 0.0 : vec1.dot(vec2); acc_1_coeff = (1 - scalar); acceleration_time_1 = acc_1_coeff * ((v_max / a_max) + (a_max / j_max)); jerk_time_1 = acc_1_coeff * (2 * (a_max / j_max)); } // the first vertex if (i == 0) { acc_1_coeff = 1.0; acceleration_time_1 = (v_max / a_max) + (a_max / j_max); jerk_time_1 = (2 * (a_max / j_max)); } // last vertex if (i == vertices.size() - 2) { acc_2_coeff = 1.0; acceleration_time_2 = (v_max / a_max) + (a_max / j_max); jerk_time_2 = (2 * (a_max / j_max)); } // a vertex if (i < vertices.size() - 2) { Eigen::Vector3d post = vertices[i + 2].head(3); Eigen::Vector3d vec1 = end - start; Eigen::Vector3d vec2 = post - end; vec1.normalize(); vec2.normalize(); double scalar = vec1.dot(vec2) < 0 ? 0.0 : vec1.dot(vec2); acc_2_coeff = (1 - scalar); acceleration_time_2 = acc_2_coeff * ((v_max / a_max) + (a_max / j_max)); jerk_time_2 = acc_2_coeff * (2 * (a_max / j_max)); } if (acceleration_time_1 > sqrt(2 * distance / a_max)) { acceleration_time_1 = sqrt(2 * distance / a_max); } if (jerk_time_1 > sqrt(2 * v_max / j_max)) { jerk_time_1 = sqrt(2 * v_max / j_max); } if (acceleration_time_2 > sqrt(2 * distance / a_max)) { acceleration_time_2 = sqrt(2 * distance / a_max); } if (jerk_time_2 > sqrt(2 * v_max / j_max)) { jerk_time_2 = sqrt(2 * v_max / j_max); } double max_velocity_time; if (((distance - (2 * (v_max * v_max) / a_max)) / v_max) < 0) { max_velocity_time = ((distance) / v_max); } else { max_velocity_time = ((distance - (2 * (v_max * v_max) / a_max)) / v_max); } /* double t = max_velocity_time + acceleration_time_1 + acceleration_time_2 + jerk_time_1 + jerk_time_2; */ double t = max_velocity_time + acceleration_time_1 + acceleration_time_2; /* printf("segment %d, [%.2f %.2f %.2f] - > [%.2f %.2f %.2f] = %.2f\n", i, start(0), start(1), start(2), end(0), end(1), end(2), distance); */ /* printf("segment %d time %.2f, distance %.2f, %.2f, %.2f, %.2f, vmax: %.2f, amax: %.2f, jmax: %.2f\n", i, t, distance, max_velocity_time, */ /* acceleration_time_1, acceleration_time_2, v_max, a_max, j_max); */ if (t < 0.01) { t = 0.01; } // | ------------- check the heading rotation time ------------ | double angular_distance = fabs(mrs_lib::geometry::radians::dist(start_hdg, end_hdg)); double hdg_velocity_time = 0; double hdg_acceleration_time = 0; if (use_heading) { if (heading_speed_max < std::numeric_limits<float>::max() && heading_acc_max < std::numeric_limits<float>::max()) { if (((angular_distance - (2 * (heading_speed_max * heading_speed_max) / heading_acc_max)) / heading_speed_max) < 0) { hdg_velocity_time = ((angular_distance) / heading_speed_max); } else { hdg_velocity_time = ((angular_distance - (2 * (heading_speed_max * heading_speed_max) / heading_acc_max)) / heading_speed_max); } if (angular_distance > M_PI / 4) { hdg_acceleration_time = 2 * (heading_speed_max / heading_acc_max); } } } // what will take longer? to fix the lateral or the heading double heading_fix_time = 1.5 * (hdg_velocity_time + hdg_acceleration_time); if (heading_fix_time > t) { t = heading_fix_time; } segment_times.push_back(t); } return segment_times; } //} /* msgToMap() //{ */ std::optional<OcTreePtr_t> Pathfinder::msgToMap(const octomap_msgs::OctomapConstPtr octomap) { octomap::AbstractOcTree* abstract_tree = octomap_msgs::binaryMsgToMap(*octomap); if (!abstract_tree) { ROS_WARN("[Pathfinder]: octomap message is empty!"); return {}; } else { OcTreePtr_t octree_out = OcTreePtr_t(dynamic_cast<OcTree_t*>(abstract_tree)); return {octree_out}; } } //} } // namespace pathfinder #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(pathfinder::Pathfinder, nodelet::Nodelet)
29.939987
159
0.658765
ctu-mrs
2d0b27b4ad205dcfd07a552d479c53877489bc22
1,859
hpp
C++
src/lattices/bravias/offset.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
1
2019-09-25T05:35:07.000Z
2019-09-25T05:35:07.000Z
src/lattices/bravias/offset.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
null
null
null
src/lattices/bravias/offset.hpp
yangqi137/lattices
91e270fd4e0899f2fc00940ef5ca6f21b0357ab8
[ "MIT" ]
null
null
null
#ifndef LATTICES_BRAVIAS_OFFSET_HPP #define LATTICES_BRAVIAS_OFFSET_HPP #include "lattice.hpp" #include <type_traits> #include <cassert> #include <algorithm> namespace lattices { namespace bravias { template <typename TAG, typename SIZE_TYPE> struct OffsetCat { typedef TAG Tag; typedef SIZE_TYPE VSize; typedef LatticeCat<TAG, VSize> LatticeCat; typedef typename LatticeCat::Lattice Lattice; typedef typename LatticeCat::Vertex Vertex; typedef typename LatticeCat::Vid Vid; typedef typename std::make_signed<Vid>::type OffsetType; static void offset_rewind(Vid& x, OffsetType dx, Vid l) { assert(dx > -((OffsetType)l)); if (dx < 0) dx += l; x += dx; x %= l; } struct Offset { OffsetType dx; OffsetType dy; }; static Vid dx_max(const Lattice& l) { return l.lx / 2; } static Vid dy_max(const Lattice& l) { return l.ly / 2; } static void shift(Vertex& v, const Vertex& dv, const Lattice& l) { v.x += dv.x; v.x %= l.lx; v.y += dv.y; v.y %= l.ly; } static void shift(Vertex& v, const Offset& dv, const Lattice& l) { offset_rewind(v.x, dv.dx, l.lx); offset_rewind(v.y, dv.dy, l.ly); } static void shift(Vid& vid, Vid dvid, const Lattice& l) { Vertex v = LatticeCat::vertex(vid, l); Vertex dv = LatticeCat::vertex(dvid, l); shift(v, dv, l); vid = LatticeCat::vid(v, l); } static Offset offset(const Vertex& v0, const Vertex& v1) { Offset dv = {v1.x - v0.x, v1.y - v0.y}; return dv; } static Vid dv2id(const Offset& dv, const Lattice& l) { Vertex v = LatticeCat::vertex(0, l); shift(v, dv, l); return LatticeCat::vid(v, l); } static Offset reverse_offset(const Offset& dv, const Lattice& l) { Offset dv2 = {-dv.dx, -dv.dy}; return dv2; } }; } } #endif
23.2375
72
0.622916
yangqi137
2d0b3f3347cebe7280af21004e83d21a90347051
946
cpp
C++
src/dialogs/asknamedialog.cpp
Phoenard/Phoenard-Toolkit
395ce79a3c56701073531cb2caad3637312d906c
[ "MIT" ]
2
2016-04-03T19:15:10.000Z
2020-04-19T16:06:54.000Z
src/dialogs/asknamedialog.cpp
Phoenard/Phoenard-Toolkit
395ce79a3c56701073531cb2caad3637312d906c
[ "MIT" ]
null
null
null
src/dialogs/asknamedialog.cpp
Phoenard/Phoenard-Toolkit
395ce79a3c56701073531cb2caad3637312d906c
[ "MIT" ]
1
2020-04-19T16:06:17.000Z
2020-04-19T16:06:17.000Z
#include "asknamedialog.h" #include "ui_asknamedialog.h" AskNameDialog::AskNameDialog(QWidget *parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::AskNameDialog) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); this->setFixedSize(this->size()); } AskNameDialog::~AskNameDialog() { delete ui; } void AskNameDialog::setHelpTitle(const QString &title) { ui->helpLabel->setText(title); } void AskNameDialog::on_lineEdit_textChanged(const QString &text) { bool isValid = (text.length() > 0); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(isValid); } QString AskNameDialog::name() { return ui->lineEdit->text(); } void AskNameDialog::setName(const QString &name) { ui->lineEdit->setText(name); } void AskNameDialog::setMaxLength(int maxLength) { ui->lineEdit->setMaxLength(maxLength); }
23.073171
96
0.714588
Phoenard
2d0c2ec0bcebf82902dbbf03d97d4003c6dd190c
2,884
cc
C++
test/cagey/math/MatrixTest.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
test/cagey/math/MatrixTest.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
test/cagey/math/MatrixTest.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // cagey-engine - Toy 3D Engine // Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> // // The MIT License (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 <cagey/math/Matrix.hh> #include "gtest/gtest.h" #include <algorithm> #include <type_traits> using namespace cagey::math; TEST(Matrix, DefaultConstructor) { typedef Matrix<int, 5, 5> Mat5f; Mat5f ident; EXPECT_EQ(1, ident(2,2)); EXPECT_EQ(0, ident(2,3)); } TEST(Matrix, FillConstructor) { Mat4<int> mat(4,4); EXPECT_EQ(4, mat(3,0)); EXPECT_EQ(0, mat(0,1)); Mat4<int> mata(2); EXPECT_EQ(2, mata(3,0)); } TEST(Matrix, ArrayConstructor) { Mat2i ma{{{1, 2, 3, 4}}}; EXPECT_EQ(4, ma(1,1)); std::array<int, 4> b{{1, 2, 3, 4}}; Mat2i mb{b}; EXPECT_EQ(4, mb(1,1)); } TEST(Matrix, DifferentTypeConstructor) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; Mat2i mb{ma}; EXPECT_EQ(4, mb(1,1)); } TEST(Matrix, PodTest) { EXPECT_EQ(false, std::is_pod<Mat2f>::value); } TEST(Matrix, operatorScale) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; ma *= 2.0f; EXPECT_EQ(8, ma(1,1)); } TEST(Matrix, operatorDivide) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; EXPECT_THROW(ma/=0.0f, cagey::core::DivideByZeroException); } TEST(Matrix, operatorNegate) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; ma = -ma; EXPECT_EQ(-4, ma(1,1)); } TEST(Matrix, adjugateTest) { Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}}; auto adj = adjugate(ma); EXPECT_EQ(1, adj(1,1)); EXPECT_EQ(4, adj(0,0)); } TEST(Matrix, makeScaleTest) { auto scale = makeScale(2.0f, 2.0f, 2.0f); EXPECT_EQ(2, scale(1,1)); } TEST(Matrix, makeTranslationTest) { auto trans = makeTranslation(2.0f, 2.0f, 2.0f); EXPECT_EQ(2, trans(0,3)); }
27.207547
80
0.638696
theycallmecoach
2d0d006e1c698d81a04fb7663967dffe944ca42f
1,813
cpp
C++
core/src/view/special/CallbackScreenShooter.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
core/src/view/special/CallbackScreenShooter.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
core/src/view/special/CallbackScreenShooter.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * CallbackScreenShooter.cpp * * Copyright (C) 2019 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/job/TickCall.h" #include "mmcore/view/special/CallbackScreenShooter.h" #include <functional> namespace megamol { namespace core { namespace view { namespace special { CallbackScreenShooter::CallbackScreenShooter() : ScreenShooter(true), AbstractWriterParams(std::bind(&CallbackScreenShooter::MakeSlotAvailable, this, std::placeholders::_1)), inputSlot("inputSlot", "Slot for registering the screen shot callback function"), tickSlot("tickSlot", "Slot for receiving a tick") { // In- and output slots this->inputSlot.SetCompatibleCall<CallbackScreenShooterCall::CallbackScreenShooterDescription>(); Module::MakeSlotAvailable(&this->inputSlot); this->tickSlot.SetCallback(job::TickCall::ClassName(), job::TickCall::FunctionName(0), &CallbackScreenShooter::Run); this->MakeSlotAvailable(&this->tickSlot); } CallbackScreenShooter::~CallbackScreenShooter() { Module::Release(); } bool CallbackScreenShooter::create() { return true; } void CallbackScreenShooter::release() { } bool CallbackScreenShooter::Run(Call&) { auto* call = this->inputSlot.CallAs<CallbackScreenShooterCall>(); if (call != nullptr) { call->SetCallback(std::bind(&CallbackScreenShooter::CreateScreenshot, this)); return (*call)(); } return true; } void CallbackScreenShooter::CreateScreenshot() { const auto filename = AbstractWriterParams::getNextFilename(); if (filename.first) { ScreenShooter::createScreenshot(filename.second); } } } } } }
27.059701
124
0.670712
azuki-monster
2d0f62a563712a1182849fd8dc43349f6996a42e
11,860
hpp
C++
externals/kokkos/core/src/impl/Kokkos_TaskBase.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
externals/kokkos/core/src/impl/Kokkos_TaskBase.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
externals/kokkos/core/src/impl/Kokkos_TaskBase.hpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
null
null
null
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ // Experimental unified task-data parallel manycore LDRD #ifndef KOKKOS_IMPL_TASKBASE_HPP #define KOKKOS_IMPL_TASKBASE_HPP #include <Kokkos_Macros.hpp> #if defined(KOKKOS_ENABLE_TASKDAG) #include <Kokkos_TaskScheduler_fwd.hpp> #include <Kokkos_Core_fwd.hpp> #include <impl/Kokkos_LIFO.hpp> #include <string> #include <typeinfo> #include <stdexcept> //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { /** \brief Base class for task management, access, and execution. * * Inheritance structure to allow static_cast from the task root type * and a task's FunctorType. * * // Enable a functor to access the base class * // and provide memory for result value. * TaskBase< Space , ResultType , FunctorType > * : TaskBase< void , void , void > * , FunctorType * { ... }; * Followed by memory allocated for result value. * * * States of a task: * * Constructing State, NOT IN a linked list * m_wait == 0 * m_next == 0 * * Scheduling transition : Constructing -> Waiting * before: * m_wait == 0 * m_next == this task's initial dependence, 0 if none * after: * m_wait == EndTag * m_next == EndTag * * Waiting State, IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == next of linked list of tasks * * transition : Waiting -> Executing * before: * m_next == EndTag * after:: * m_next == LockTag * * Executing State, NOT IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == LockTag * * Respawn transition : Executing -> Executing-Respawn * before: * m_next == LockTag * after: * m_next == this task's updated dependence, 0 if none * * Executing-Respawn State, NOT IN a linked list * m_apply != 0 * m_queue != 0 * m_ref_count > 0 * m_wait == head of linked list of tasks waiting on this task * m_next == this task's updated dependence, 0 if none * * transition : Executing -> Complete * before: * m_wait == head of linked list * after: * m_wait == LockTag * * Complete State, NOT IN a linked list * m_wait == LockTag: cannot add dependence (<=> complete) * m_next == LockTag: not a member of a wait queue * */ class TaskBase { public: enum : int16_t { TaskTeam = 0, TaskSingle = 1, Aggregate = 2 }; enum : uintptr_t { LockTag = ~uintptr_t(0), EndTag = ~uintptr_t(1) }; template <typename, typename> friend class Kokkos::BasicTaskScheduler; using queue_type = TaskQueueBase; using function_type = void (*)(TaskBase*, void*); using destroy_type = void (*)(TaskBase*); // sizeof(TaskBase) == 48 function_type m_apply = nullptr; ///< Apply function pointer queue_type* m_queue = nullptr; ///< Pointer to the scheduler TaskBase* m_next = nullptr; ///< next in linked list of ready tasks TaskBase* m_wait = nullptr; ///< Queue of tasks waiting on this int32_t m_ref_count = 0; int32_t m_alloc_size = 0; int32_t m_dep_count; ///< Aggregate's number of dependences int16_t m_task_type; ///< Type of task int16_t m_priority; ///< Priority of runnable task TaskBase(TaskBase&&) = delete; TaskBase(const TaskBase&) = delete; TaskBase& operator=(TaskBase&&) = delete; TaskBase& operator=(const TaskBase&) = delete; KOKKOS_DEFAULTED_FUNCTION ~TaskBase() = default; KOKKOS_INLINE_FUNCTION constexpr TaskBase() : m_apply(nullptr), m_queue(nullptr), m_next(nullptr), m_wait(nullptr), m_ref_count(0), m_alloc_size(0), m_dep_count(0), m_task_type(0), m_priority(0) {} //---------------------------------------- KOKKOS_INLINE_FUNCTION TaskBase* volatile* aggregate_dependences() volatile { return reinterpret_cast<TaskBase* volatile*>(this + 1); } KOKKOS_INLINE_FUNCTION bool requested_respawn() { // This should only be called when a task has finished executing and is // in the transition to either the complete or executing-respawn state. TaskBase* const lock = reinterpret_cast<TaskBase*>(LockTag); return lock != m_next; } KOKKOS_INLINE_FUNCTION void add_dependence(TaskBase* dep) { // Precondition: lock == m_next TaskBase* const lock = (TaskBase*)LockTag; // Assign dependence to m_next. It will be processed in the subsequent // call to schedule. Error if the dependence is reset. if (lock != Kokkos::atomic_exchange(&m_next, dep)) { Kokkos::abort("TaskScheduler ERROR: resetting task dependence"); } if (nullptr != dep) { // The future may be destroyed upon returning from this call // so increment reference count to track this assignment. Kokkos::atomic_increment(&(dep->m_ref_count)); } } //---------------------------------------- KOKKOS_INLINE_FUNCTION int32_t reference_count() const { return *((int32_t volatile*)(&m_ref_count)); } }; //------------------------------------------------------------------------------ // <editor-fold desc="Verify the size of TaskBase is as expected"> {{{2 // Workaround: some compilers implement int16_t as 4 bytes, so the size might // not actually be 48 bytes. // There's not a lot of reason to keep checking this here; the program will // work fine if this isn't true. I think this check was originally here to // emphasize the fact that adding to the size of TaskBase could have a // significant performance penalty, since doing so could substantially decrease // the number of full task types that fit into a cache line. We'll leave it // here for now, though, since we're probably going to be ripping all of the // old TaskBase stuff out eventually anyway. constexpr size_t unpadded_task_base_size = 44 + 2 * sizeof(int16_t); // don't forget padding: constexpr size_t task_base_misalignment = unpadded_task_base_size % alignof(void*); constexpr size_t task_base_padding_size = (alignof(void*) - task_base_misalignment) % alignof(void*); constexpr size_t expected_task_base_size = unpadded_task_base_size + task_base_padding_size; // Produce a more readable compiler error message than the plain static assert template <size_t Size> struct verify_task_base_size_is_48_note_actual_size_is_ {}; template <> struct verify_task_base_size_is_48_note_actual_size_is_< expected_task_base_size> { using type = int; }; static constexpr typename verify_task_base_size_is_48_note_actual_size_is_<sizeof( TaskBase)>::type verify = {}; static_assert(sizeof(TaskBase) == expected_task_base_size, "Verifying expected sizeof(TaskBase)"); // </editor-fold> end Verify the size of TaskBase is as expected }}}2 //------------------------------------------------------------------------------ } /* namespace Impl */ } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- namespace Kokkos { namespace Impl { template <class Scheduler, typename ResultType, class FunctorType> class Task : public TaskBase, public FunctorType { public: Task() = delete; Task(Task&&) = delete; Task(const Task&) = delete; Task& operator=(Task&&) = delete; Task& operator=(const Task&) = delete; using root_type = TaskBase; using functor_type = FunctorType; using result_type = ResultType; using specialization = TaskQueueSpecialization<Scheduler>; using member_type = typename specialization::member_type; KOKKOS_INLINE_FUNCTION void apply_functor(member_type* const member, void*) { this->functor_type::operator()(*member); } template <typename T> KOKKOS_INLINE_FUNCTION void apply_functor(member_type* const member, T* const result) { this->functor_type::operator()(*member, *result); } KOKKOS_FUNCTION static void destroy(root_type* root) { TaskResult<result_type>::destroy(root); } KOKKOS_FUNCTION static void apply(root_type* root, void* exec) { Task* const task = static_cast<Task*>(root); member_type* const member = reinterpret_cast<member_type*>(exec); result_type* const result = TaskResult<result_type>::ptr(task); // Task may be serial or team. // If team then must synchronize before querying if respawn was requested. // If team then only one thread calls destructor. const bool only_one_thread = #if defined(KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_CUDA) 0 == threadIdx.x && 0 == threadIdx.y; #else 0 == member->team_rank(); #endif task->apply_functor(member, result); member->team_barrier(); if (only_one_thread && !(task->requested_respawn())) { // Did not respawn, destroy the functor to free memory. task->functor_type::~functor_type(); // Cannot destroy and deallocate the task until its dependences // have been processed. } } // Constructor for runnable task KOKKOS_INLINE_FUNCTION constexpr Task(FunctorType&& arg_functor) : root_type(), functor_type(std::move(arg_functor)) {} KOKKOS_INLINE_FUNCTION ~Task() = delete; }; } /* namespace Impl */ } /* namespace Kokkos */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- #endif /* #if defined( KOKKOS_ENABLE_TASKDAG ) */ #endif /* #ifndef KOKKOS_IMPL_TASKBASE_HPP */
34.08046
80
0.636509
meng630
2d0fd219a742e6ea3c9d909ba4ad663b160acf58
2,149
cpp
C++
PA1/main.cpp
sameer-h/Data-Structures-Algos
8f0db3cb58298f0da964a8bb2a3b201176a52cb4
[ "MIT" ]
null
null
null
PA1/main.cpp
sameer-h/Data-Structures-Algos
8f0db3cb58298f0da964a8bb2a3b201176a52cb4
[ "MIT" ]
null
null
null
PA1/main.cpp
sameer-h/Data-Structures-Algos
8f0db3cb58298f0da964a8bb2a3b201176a52cb4
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /* Sameer Hussain - CSCE 221 – PA 1*/ enum class Stress_ball_colors { // enum for stress ball colors red, blue, yellow, green }; enum class Stress_ball_sizes { // enum for stress ball sizes small, medium, large }; class Stress_ball { private: Stress_ball_colors color; Stress_ball_sizes size; public: Stress_ball() : color(Stress_ball_colors(rand() % 4)), size(Stress_ball_sizes(rand() % 3)) {} // random generation for the vals Stress_ball(Stress_ball_colors col, Stress_ball_sizes siz) : color(col), size(siz) {} Stress_ball_colors get_color() const { return color; } Stress_ball_sizes get_size() const { return size; } bool operator==(Stress_ball &c) { // operator for getting color and size bool c1 = false; bool c2 = false; if (get_color() == c.get_color()) { c1 = true; } if (get_size() == c.get_size()) { c2 = true; } return c1 && c2; } }; inline std::ostream &operator<<( std::ostream &os, const Stress_ball &sb ) { switch (sb.get_color()) { case Stress_ball_colors::red: // using switch statements to run through the different cases of color/size and outputting os << "(red,"; break; case Stress_ball_colors::blue: os << "(blue,"; break; case Stress_ball_colors::yellow: os << "(yellow,"; break; case Stress_ball_colors::green: os << "(green,"; } switch(sb.get_size()) { case Stress_ball_sizes::small: os << "small)"; break; case Stress_ball_sizes::medium: os << "medium)"; break; case Stress_ball_sizes::large: os << "large)"; break; } return os; // returning os which has both color and size } int main() { // setting a stress ball Stress_ball s1(Stress_ball_colors::red, Stress_ball_sizes::small); //printing stress ball cout << s1; return 0; }
21.068627
135
0.566775
sameer-h
2d11d16b1f3b6779c29af33d80cff9f46b0da413
21,704
cpp
C++
src/mbgl/style/style.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/style/style.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/style/style.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/style/style.hpp> #include <mbgl/style/observer.hpp> #include <mbgl/style/source_impl.hpp> #include <mbgl/style/layers/symbol_layer.hpp> #include <mbgl/style/layers/symbol_layer_impl.hpp> #include <mbgl/style/layers/custom_layer.hpp> #include <mbgl/style/layers/custom_layer_impl.hpp> #include <mbgl/style/layers/background_layer.hpp> #include <mbgl/style/layers/background_layer_impl.hpp> #include <mbgl/style/layers/fill_layer.hpp> #include <mbgl/style/layers/fill_extrusion_layer.hpp> #include <mbgl/style/layers/line_layer.hpp> #include <mbgl/style/layers/circle_layer.hpp> #include <mbgl/style/layers/raster_layer.hpp> #include <mbgl/style/layer_impl.hpp> #include <mbgl/style/parser.hpp> #include <mbgl/style/query_parameters.hpp> #include <mbgl/style/transition_options.hpp> #include <mbgl/style/class_dictionary.hpp> #include <mbgl/style/update_parameters.hpp> #include <mbgl/style/cascade_parameters.hpp> #include <mbgl/style/property_evaluation_parameters.hpp> #include <mbgl/sprite/sprite_atlas.hpp> #include <mbgl/text/glyph_atlas.hpp> #include <mbgl/geometry/line_atlas.hpp> #include <mbgl/renderer/render_item.hpp> #include <mbgl/renderer/render_tile.hpp> #include <mbgl/util/constants.hpp> #include <mbgl/util/string.hpp> #include <mbgl/util/logging.hpp> #include <mbgl/math/minmax.hpp> #include <algorithm> namespace mbgl { namespace style { static Observer nullObserver; Style::Style(FileSource& fileSource_, float pixelRatio) : fileSource(fileSource_), glyphAtlas(std::make_unique<GlyphAtlas>(Size{ 2048, 2048 }, fileSource)), spriteAtlas(std::make_unique<SpriteAtlas>(Size{ 1024, 1024 }, pixelRatio)), lineAtlas(std::make_unique<LineAtlas>(Size{ 256, 512 })), observer(&nullObserver) { glyphAtlas->setObserver(this); spriteAtlas->setObserver(this); } Style::~Style() { for (const auto& source : sources) { source->baseImpl->setObserver(nullptr); } for (const auto& layer : layers) { if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->deinitialize(); } } glyphAtlas->setObserver(nullptr); spriteAtlas->setObserver(nullptr); } bool Style::addClass(const std::string& className) { if (hasClass(className)) return false; classes.push_back(className); return true; } bool Style::hasClass(const std::string& className) const { return std::find(classes.begin(), classes.end(), className) != classes.end(); } bool Style::removeClass(const std::string& className) { const auto it = std::find(classes.begin(), classes.end(), className); if (it != classes.end()) { classes.erase(it); return true; } return false; } void Style::setClasses(const std::vector<std::string>& classNames) { classes = classNames; } std::vector<std::string> Style::getClasses() const { return classes; } void Style::setTransitionOptions(const TransitionOptions& options) { transitionOptions = options; } TransitionOptions Style::getTransitionOptions() const { return transitionOptions; } void Style::setJSON(const std::string& json) { sources.clear(); layers.clear(); classes.clear(); transitionOptions = {}; updateBatch = {}; Parser parser; auto error = parser.parse(json); if (error) { Log::Error(Event::ParseStyle, "Failed to parse style: %s", util::toString(error).c_str()); observer->onStyleError(); observer->onResourceError(error); return; } for (auto& source : parser.sources) { addSource(std::move(source)); } for (auto& layer : parser.layers) { addLayer(std::move(layer)); } name = parser.name; defaultLatLng = parser.latLng; defaultZoom = parser.zoom; defaultBearing = parser.bearing; defaultPitch = parser.pitch; glyphAtlas->setURL(parser.glyphURL); spriteAtlas->load(parser.spriteURL, fileSource); loaded = true; observer->onStyleLoaded(); } void Style::addSource(std::unique_ptr<Source> source) { //Guard against duplicate source ids auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& existing) { return existing->getID() == source->getID(); }); if (it != sources.end()) { std::string msg = "Source " + source->getID() + " already exists"; throw std::runtime_error(msg.c_str()); } source->baseImpl->setObserver(this); sources.emplace_back(std::move(source)); } std::unique_ptr<Source> Style::removeSource(const std::string& id) { auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) { return source->getID() == id; }); if (it == sources.end()) { throw std::runtime_error("no such source"); } auto source = std::move(*it); sources.erase(it); updateBatch.sourceIDs.erase(id); return source; } std::vector<const Layer*> Style::getLayers() const { std::vector<const Layer*> result; result.reserve(layers.size()); for (const auto& layer : layers) { result.push_back(layer.get()); } return result; } std::vector<Layer*> Style::getLayers() { std::vector<Layer*> result; result.reserve(layers.size()); for (auto& layer : layers) { result.push_back(layer.get()); } return result; } std::vector<std::unique_ptr<Layer>>::const_iterator Style::findLayer(const std::string& id) const { return std::find_if(layers.begin(), layers.end(), [&](const auto& layer) { return layer->baseImpl->id == id; }); } Layer* Style::getLayer(const std::string& id) const { auto it = findLayer(id); return it != layers.end() ? it->get() : nullptr; } Layer* Style::addLayer(std::unique_ptr<Layer> layer, optional<std::string> before) { // TODO: verify source // Guard against duplicate layer ids auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& existing) { return existing->getID() == layer->getID(); }); if (it != layers.end()) { throw std::runtime_error(std::string{"Layer "} + layer->getID() + " already exists"); } if (SymbolLayer* symbolLayer = layer->as<SymbolLayer>()) { if (!symbolLayer->impl->spriteAtlas) { symbolLayer->impl->spriteAtlas = spriteAtlas.get(); } } if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->initialize(); } layer->baseImpl->setObserver(this); return layers.emplace(before ? findLayer(*before) : layers.end(), std::move(layer))->get(); } std::unique_ptr<Layer> Style::removeLayer(const std::string& id) { auto it = std::find_if(layers.begin(), layers.end(), [&](const auto& layer) { return layer->baseImpl->id == id; }); if (it == layers.end()) throw std::runtime_error("no such layer"); auto layer = std::move(*it); if (CustomLayer* customLayer = layer->as<CustomLayer>()) { customLayer->impl->deinitialize(); } layers.erase(it); return layer; } std::string Style::getName() const { return name; } LatLng Style::getDefaultLatLng() const { return defaultLatLng; } double Style::getDefaultZoom() const { return defaultZoom; } double Style::getDefaultBearing() const { return defaultBearing; } double Style::getDefaultPitch() const { return defaultPitch; } void Style::updateTiles(const UpdateParameters& parameters) { for (const auto& source : sources) { if (source->baseImpl->enabled) { source->baseImpl->updateTiles(parameters); } } } void Style::updateSymbolDependentTiles() { for (const auto& source : sources) { source->baseImpl->updateSymbolDependentTiles(); } } void Style::relayout() { for (const auto& sourceID : updateBatch.sourceIDs) { Source* source = getSource(sourceID); if (source && source->baseImpl->enabled) { source->baseImpl->reloadTiles(); } } updateBatch.sourceIDs.clear(); } void Style::cascade(const TimePoint& timePoint, MapMode mode) { // When in continuous mode, we can either have user- or style-defined // transitions. Still mode is always immediate. static const TransitionOptions immediateTransition {}; std::vector<ClassID> classIDs; for (const auto& className : classes) { classIDs.push_back(ClassDictionary::Get().lookup(className)); } classIDs.push_back(ClassID::Default); const CascadeParameters parameters { classIDs, mode == MapMode::Continuous ? timePoint : Clock::time_point::max(), mode == MapMode::Continuous ? transitionOptions : immediateTransition }; for (const auto& layer : layers) { layer->baseImpl->cascade(parameters); } } void Style::recalculate(float z, const TimePoint& timePoint, MapMode mode) { // Disable all sources first. If we find an enabled layer that uses this source, we will // re-enable it later. for (const auto& source : sources) { source->baseImpl->enabled = false; } zoomHistory.update(z, timePoint); const PropertyEvaluationParameters parameters { z, mode == MapMode::Continuous ? timePoint : Clock::time_point::max(), zoomHistory, mode == MapMode::Continuous ? util::DEFAULT_FADE_DURATION : Duration::zero() }; hasPendingTransitions = false; for (const auto& layer : layers) { const bool hasTransitions = layer->baseImpl->evaluate(parameters); // Disable this layer if it doesn't need to be rendered. const bool needsRendering = layer->baseImpl->needsRendering(zoomHistory.lastZoom); if (!needsRendering) { continue; } hasPendingTransitions |= hasTransitions; // If this layer has a source, make sure that it gets loaded. if (Source* source = getSource(layer->baseImpl->source)) { source->baseImpl->enabled = true; if (!source->baseImpl->loaded) { source->baseImpl->loadDescription(fileSource); } } } // Remove the existing tiles if we didn't end up re-enabling the source. for (const auto& source : sources) { if (!source->baseImpl->enabled) { source->baseImpl->removeTiles(); } } } std::vector<const Source*> Style::getSources() const { std::vector<const Source*> result; result.reserve(sources.size()); for (const auto& source : sources) { result.push_back(source.get()); } return result; } std::vector<Source*> Style::getSources() { std::vector<Source*> result; result.reserve(sources.size()); for (auto& source : sources) { result.push_back(source.get()); } return result; } Source* Style::getSource(const std::string& id) const { const auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& source) { return source->getID() == id; }); return it != sources.end() ? it->get() : nullptr; } bool Style::hasTransitions() const { return hasPendingTransitions; } bool Style::isLoaded() const { if (!loaded) { return false; } for (const auto& source: sources) { if (source->baseImpl->enabled && !source->baseImpl->isLoaded()) { return false; } } if (!spriteAtlas->isLoaded()) { return false; } return true; } RenderData Style::getRenderData(MapDebugOptions debugOptions, float angle) const { RenderData result; for (const auto& source : sources) { if (source->baseImpl->enabled) { result.sources.insert(source.get()); } } const bool isLeft = std::abs(angle) > M_PI_2; const bool isBottom = angle < 0; for (const auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } if (const BackgroundLayer* background = layer->as<BackgroundLayer>()) { if (debugOptions & MapDebugOptions::Overdraw) { // We want to skip glClear optimization in overdraw mode. result.order.emplace_back(*layer); continue; } const BackgroundPaintProperties::Evaluated& paint = background->impl->paint.evaluated; if (layer.get() == layers[0].get() && paint.get<BackgroundPattern>().from.empty()) { // This is a solid background. We can use glClear(). result.backgroundColor = paint.get<BackgroundColor>() * paint.get<BackgroundOpacity>(); } else { // This is a textured background, or not the bottommost layer. We need to render it with a quad. result.order.emplace_back(*layer); } continue; } if (layer->is<CustomLayer>()) { result.order.emplace_back(*layer); continue; } Source* source = getSource(layer->baseImpl->source); if (!source) { Log::Warning(Event::Render, "can't find source for layer '%s'", layer->baseImpl->id.c_str()); continue; } auto& renderTiles = source->baseImpl->getRenderTiles(); const bool symbolLayer = layer->is<SymbolLayer>(); // Sort symbol tiles in opposite y position, so tiles with overlapping // symbols are drawn on top of each other, with lower symbols being // drawn on top of higher symbols. std::vector<std::reference_wrapper<RenderTile>> sortedTiles; std::transform(renderTiles.begin(), renderTiles.end(), std::back_inserter(sortedTiles), [](auto& pair) { return std::ref(pair.second); }); if (symbolLayer) { std::sort(sortedTiles.begin(), sortedTiles.end(), [isLeft, isBottom](const RenderTile& a, const RenderTile& b) { bool sortX = a.id.canonical.x > b.id.canonical.x; bool sortW = a.id.wrap > b.id.wrap; bool sortY = a.id.canonical.y > b.id.canonical.y; return a.id.canonical.y != b.id.canonical.y ? (isLeft ? sortY : !sortY) : a.id.wrap != b.id.wrap ? (isBottom ? sortW : !sortW) : (isBottom ? sortX : !sortX); }); } for (auto& tileRef : sortedTiles) { auto& tile = tileRef.get(); if (!tile.tile.isRenderable()) { continue; } // We're not clipping symbol layers, so when we have both parents and children of symbol // layers, we drop all children in favor of their parent to avoid duplicate labels. // See https://github.com/mapbox/mapbox-gl-native/issues/2482 if (symbolLayer) { bool skip = false; // Look back through the buckets we decided to render to find out whether there is // already a bucket from this layer that is a parent of this tile. Tiles are ordered // by zoom level when we obtain them from getTiles(). for (auto it = result.order.rbegin(); it != result.order.rend() && (&it->layer == layer.get()); ++it) { if (tile.tile.id.isChildOf(it->tile->tile.id)) { skip = true; break; } } if (skip) { continue; } } auto bucket = tile.tile.getBucket(*layer); if (bucket) { result.order.emplace_back(*layer, &tile, bucket); tile.used = true; } } } return result; } std::vector<Feature> Style::queryRenderedFeatures(const QueryParameters& parameters) const { std::unordered_set<std::string> sourceFilter; if (parameters.layerIDs) { for (const auto& layerID : *parameters.layerIDs) { auto layer = getLayer(layerID); if (layer) sourceFilter.emplace(layer->baseImpl->source); } } std::vector<Feature> result; std::unordered_map<std::string, std::vector<Feature>> resultsByLayer; for (const auto& source : sources) { if (!sourceFilter.empty() && sourceFilter.find(source->getID()) == sourceFilter.end()) { continue; } auto sourceResults = source->baseImpl->queryRenderedFeatures(parameters); std::move(sourceResults.begin(), sourceResults.end(), std::inserter(resultsByLayer, resultsByLayer.begin())); } if (resultsByLayer.empty()) { return result; } // Combine all results based on the style layer order. for (const auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } auto it = resultsByLayer.find(layer->baseImpl->id); if (it != resultsByLayer.end()) { std::move(it->second.begin(), it->second.end(), std::back_inserter(result)); } } return result; } float Style::getQueryRadius() const { float additionalRadius = 0; for (auto& layer : layers) { if (!layer->baseImpl->needsRendering(zoomHistory.lastZoom)) { continue; } additionalRadius = util::max(additionalRadius, layer->baseImpl->getQueryRadius()); } return additionalRadius; } void Style::setSourceTileCacheSize(size_t size) { for (const auto& source : sources) { source->baseImpl->setCacheSize(size); } } void Style::onLowMemory() { for (const auto& source : sources) { source->baseImpl->onLowMemory(); } } void Style::setObserver(style::Observer* observer_) { observer = observer_; } void Style::onGlyphsLoaded(const FontStack& fontStack, const GlyphRange& glyphRange) { observer->onGlyphsLoaded(fontStack, glyphRange); updateSymbolDependentTiles(); } void Style::onGlyphsError(const FontStack& fontStack, const GlyphRange& glyphRange, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load glyph range %d-%d for font stack %s: %s", glyphRange.first, glyphRange.second, fontStackToString(fontStack).c_str(), util::toString(error).c_str()); observer->onGlyphsError(fontStack, glyphRange, error); observer->onResourceError(error); } void Style::onSourceLoaded(Source& source) { observer->onSourceLoaded(source); observer->onUpdate(Update::Repaint); } void Style::onSourceAttributionChanged(Source& source, const std::string& attribution) { observer->onSourceAttributionChanged(source, attribution); } void Style::onSourceError(Source& source, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load source %s: %s", source.getID().c_str(), util::toString(error).c_str()); observer->onSourceError(source, error); observer->onResourceError(error); } void Style::onSourceDescriptionChanged(Source& source) { observer->onSourceDescriptionChanged(source); if (!source.baseImpl->loaded) { source.baseImpl->loadDescription(fileSource); } } void Style::onTileChanged(Source& source, const OverscaledTileID& tileID) { observer->onTileChanged(source, tileID); observer->onUpdate(Update::Repaint); } void Style::onTileError(Source& source, const OverscaledTileID& tileID, std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load tile %s for source %s: %s", util::toString(tileID).c_str(), source.getID().c_str(), util::toString(error).c_str()); observer->onTileError(source, tileID, error); observer->onResourceError(error); } void Style::onSpriteLoaded() { observer->onSpriteLoaded(); observer->onUpdate(Update::Repaint); // For *-pattern properties. updateSymbolDependentTiles(); } void Style::onSpriteError(std::exception_ptr error) { lastError = error; Log::Error(Event::Style, "Failed to load sprite: %s", util::toString(error).c_str()); observer->onSpriteError(error); observer->onResourceError(error); } struct QueueSourceReloadVisitor { UpdateBatch& updateBatch; // No need to reload sources for these types; their visibility can change but // they don't participate in layout. void operator()(CustomLayer&) {} void operator()(RasterLayer&) {} void operator()(BackgroundLayer&) {} template <class VectorLayer> void operator()(VectorLayer& layer) { updateBatch.sourceIDs.insert(layer.getSourceID()); } }; void Style::onLayerFilterChanged(Layer& layer) { layer.accept(QueueSourceReloadVisitor { updateBatch }); observer->onUpdate(Update::Layout); } void Style::onLayerVisibilityChanged(Layer& layer) { layer.accept(QueueSourceReloadVisitor { updateBatch }); observer->onUpdate(Update::RecalculateStyle | Update::Layout); } void Style::onLayerPaintPropertyChanged(Layer&) { observer->onUpdate(Update::RecalculateStyle | Update::Classes); } void Style::onLayerLayoutPropertyChanged(Layer& layer, const char * property) { layer.accept(QueueSourceReloadVisitor { updateBatch }); auto update = Update::Layout; //Recalculate the style for certain properties bool needsRecalculation = strcmp(property, "icon-size") == 0 || strcmp(property, "text-size") == 0; if (needsRecalculation) { update |= Update::RecalculateStyle; } observer->onUpdate(update); } void Style::dumpDebugLogs() const { for (const auto& source : sources) { source->baseImpl->dumpDebugLogs(); } spriteAtlas->dumpDebugLogs(); } } // namespace style } // namespace mbgl
31.546512
121
0.636196
mapzak
2d16b5a3cf4673ab64997dc53e89963724b50405
1,163
cpp
C++
find-duplicates-o1.cpp
whynesspower/best-of-GFG-questions
90ef96c38965e11c0fc0987955f662d2665b4ff3
[ "MIT" ]
1
2021-11-06T14:03:06.000Z
2021-11-06T14:03:06.000Z
find-duplicates-o1.cpp
whynesspower/best-of-GFG-questions
90ef96c38965e11c0fc0987955f662d2665b4ff3
[ "MIT" ]
null
null
null
find-duplicates-o1.cpp
whynesspower/best-of-GFG-questions
90ef96c38965e11c0fc0987955f662d2665b4ff3
[ "MIT" ]
2
2021-09-12T10:15:54.000Z
2021-09-26T20:47:19.000Z
// https://practice.geeksforgeeks.org/problems/find-duplicates-in-an-array/1# #include <bits/stdc++.h> using namespace std; class Solution{ public: vector<int> duplicates(int arr[], int n) { int count=0; //raverse the given array from i= 0 to n-1 elements // Go to index arr[i]%n and increment its value by n. for(int i=0;i<n;i++){ int index=arr[i]%n; arr[index]+=n; } vector<int>ans; // Now traverse the array again and print all those // indexes i for which arr[i]/n is greater than 1 for(int i=0;i<n;i++){ if(arr[i]/n>=2){ ans.push_back(i); count++; } } if(count==0)ans.push_back(-1); return ans; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t-- > 0) { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; Solution obj; vector<int> ans = obj.duplicates(a, n); for (int i : ans) cout << i << ' '; cout << endl; } return 0; } // } Driver Code Ends
24.744681
77
0.483233
whynesspower
2d175c80d238f813e290181e28568bdf12d8ecc5
847
cpp
C++
C++/0023-Merge-k-Sorted-Lists/soln-1.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0023-Merge-k-Sorted-Lists/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0023-Merge-k-Sorted-Lists/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode * dummy = new ListNode(0); ListNode * cur = dummy; priority_queue<pair<int, ListNode *>> pq; for(auto head : lists) { if (head != nullptr) { pq.push({-head->val, head}); } } while (!pq.empty()) { ListNode * node = pq.top().second; pq.pop(); cur->next = node; cur = cur->next; if (node->next != nullptr) { pq.push({-node->next->val, node->next}); } } cur->next = nullptr; return dummy->next; } };
25.666667
56
0.46281
wyaadarsh
2d1cf4110ddaa389048aef7e90547f912f684f48
11,954
hpp
C++
Tensile/Source/client/include/ResultComparison.hpp
micmelesse/Tensile
62fb9a16909ddef08010915cfefe4c0341f48daa
[ "MIT" ]
1
2021-12-03T09:42:10.000Z
2021-12-03T09:42:10.000Z
Tensile/Source/client/include/ResultComparison.hpp
micmelesse/Tensile
62fb9a16909ddef08010915cfefe4c0341f48daa
[ "MIT" ]
null
null
null
Tensile/Source/client/include/ResultComparison.hpp
micmelesse/Tensile
62fb9a16909ddef08010915cfefe4c0341f48daa
[ "MIT" ]
null
null
null
/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #pragma once #include <iostream> #include "Reference.hpp" namespace Tensile { namespace Client { template <typename T> struct NullComparison { inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { } template <typename... Args> inline void before(T value, size_t elemIndex, size_t elemCount) { } inline void inside(T value, size_t elemIndex, size_t elemCount) { } template <typename... Args> inline void after(T value, size_t elemIndex, size_t elemCount) { } void report() const {} bool error() const { return false; } }; template <typename T> class PointwiseComparison { public: PointwiseComparison(bool printValids, size_t printMax, bool printReport) : m_printValids(printValids), m_printMax(printMax), m_doPrint(printMax > 0), m_printReport(printReport) { } inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { m_values++; bool match = AlmostEqual(referenceValue, resultValue); if(!match) m_errors++; if(!match || m_printValids) { if(m_doPrint) { if(m_printed == 0) { std::cout << "Index: Device | Reference" << std::endl; } std::cout << "[" << (m_printed) << "] " << " elem=" << elemNumber << " idx=" << elemIndex << ": " << resultValue << (match ? "==" : "!=") << referenceValue << std::endl; m_printed++; if(m_printMax >= 0 && m_printed >= m_printMax) m_doPrint = false; } } } void report() const { if(0 && m_printReport) std::cout << "Found " << m_errors << " incorrect values in " << m_values << " total values compared." << std::endl; } bool error() const { return m_errors != 0; } private: size_t m_errors = 0; size_t m_values = 0; bool m_printValids = 0; size_t m_printMax = 0; size_t m_printed = 0; bool m_doPrint = false; bool m_printReport = false; }; template <typename T> struct Magnitude { inline static T abs(T val) { return std::abs(val); } }; template <typename T> struct Magnitude<std::complex<T>> { inline static T abs(std::complex<T> val) { return std::abs(val); } }; template <> struct Magnitude<Half> { inline static Half abs(Half val) { return static_cast<Half>(std::abs(static_cast<float>(val))); } }; template <typename T> class RMSComparison { public: RMSComparison(double threshold, bool printReport) : m_threshold(threshold), m_printReport(printReport) { } inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber) { m_values++; using m = Magnitude<T>; m_maxReference = std::max(m_maxReference, static_cast<double>(m::abs(referenceValue))); m_maxResult = std::max(m_maxResult, static_cast<double>(m::abs(resultValue))); auto diff = m::abs(referenceValue - resultValue); m_squareDifference += static_cast<double>(diff * diff); } inline void report() const { if(m_printReport) { std::cout << "Max reference value: " << m_maxReference << ", max result value: " << m_maxResult << " (" << m_values << " values)" << std::endl; std::cout << "RMS Error: " << errorValue() << " (threshold: " << m_threshold << ")" << std::endl; } } bool error() const { auto value = errorValue(); return value > m_threshold; } double errorValue() const { double maxMagnitude = std::max({m_maxReference, m_maxResult, std::numeric_limits<double>::min()}); double denom = std::sqrt(static_cast<double>(m_values)) * maxMagnitude; return std::sqrt(m_squareDifference) / denom; } private: size_t m_values = 0; bool m_printReport = false; double m_maxReference = 0; double m_maxResult = 0; double m_squareDifference = 0; double m_threshold = 1e-7; }; template <typename T> class InvalidComparison { public: InvalidComparison(size_t printMax, bool printReport) : m_printMax(printMax), m_printReport(printReport), m_doPrintBefore(printMax > 0), m_doPrintInside(printMax > 0), m_doPrintAfter(printMax > 0) { } inline void before(T value, size_t elemIndex, size_t elemCount) { m_checkedBefore++; if(!DataInitialization::isBadOutput(value)) { m_errorsBefore++; if(m_doPrintBefore) { if(m_printedBefore == 0) { std::cout << "Value written before output buffer:" << std::endl; m_printedBefore++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedBefore >= m_printMax) m_doPrintBefore = false; } } } inline void inside(T value, size_t elemIndex, size_t elemCount) { m_checkedInside++; if(!DataInitialization::isBadOutput(value)) { m_errorsInside++; if(m_doPrintInside) { if(m_printedInside == 0) { std::cout << "Value written inside output buffer, ouside tensor:" << std::endl; m_printedInside++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedInside >= m_printMax) m_doPrintInside = false; } } } inline void after(T value, size_t elemIndex, size_t elemCount) { m_checkedAfter++; if(!DataInitialization::isBadOutput(value)) { m_errorsAfter++; if(m_doPrintAfter) { if(m_printedAfter == 0) { std::cout << "Value written after output buffer:" << std::endl; m_printedAfter++; } std::cout << "Index " << elemIndex << " / " << elemCount << ": found " << value << " instead of " << DataInitialization::getValue<T, InitMode::BadOutput>() << std::endl; if(m_printedAfter >= m_printMax) m_doPrintAfter = false; } } } void report() const { if(m_printReport && (m_checkedBefore > 0 || m_checkedInside > 0 || m_checkedAfter > 0)) { std::cout << "BOUNDS CHECK:" << std::endl; std::cout << "Before buffer: found " << m_errorsBefore << " errors in " << m_checkedBefore << " values checked." << std::endl; std::cout << "Inside buffer: found " << m_errorsInside << " errors in " << m_checkedInside << " values checked." << std::endl; std::cout << "After buffer: found " << m_errorsAfter << " errors in " << m_checkedAfter << " values checked." << std::endl; } } bool error() const { return m_errorsBefore != 0 || m_errorsInside != 0 || m_errorsAfter != 0; } private: size_t m_printMax = 0; bool m_printReport = false; size_t m_checkedBefore = 0; size_t m_checkedInside = 0; size_t m_checkedAfter = 0; size_t m_errorsBefore = 0; size_t m_errorsInside = 0; size_t m_errorsAfter = 0; size_t m_printedBefore = 0; size_t m_printedInside = 0; size_t m_printedAfter = 0; bool m_doPrintBefore = false; bool m_doPrintInside = false; bool m_doPrintAfter = false; }; } }
34.449568
146
0.446127
micmelesse
2d1f101de73447676d581f3bb6a24b5a97f99fd2
3,450
cpp
C++
Tests/UnitTests/ArrayView2Tests.cpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
216
2017-01-25T04:34:30.000Z
2021-07-15T12:36:06.000Z
Tests/UnitTests/ArrayView2Tests.cpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
323
2017-01-26T13:53:13.000Z
2021-07-14T16:03:38.000Z
Tests/UnitTests/ArrayView2Tests.cpp
ADMTec/CubbyFlow
c71457fd04ccfaf3ef22772bab9bcec4a0a3b611
[ "MIT" ]
33
2017-01-25T05:05:49.000Z
2021-06-17T17:30:56.000Z
#include "gtest/gtest.h" #include <Core/Array/Array.hpp> #include <Core/Array/ArrayView.hpp> using namespace CubbyFlow; TEST(ArrayView2, Constructors) { double data[20]; for (int i = 0; i < 20; ++i) { data[i] = static_cast<double>(i); } ArrayView2<double> acc(data, Vector2UZ(5, 4)); EXPECT_EQ(5u, acc.Size().x); EXPECT_EQ(4u, acc.Size().y); EXPECT_EQ(data, acc.data()); } TEST(ArrayView2, Iterators) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); float cnt = 1.f; for (float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } cnt = 1.f; for (const float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } } TEST(ArrayView2, ForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); ForEachIndex(arr1.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), arr1(i, j)); }); } TEST(ArrayView2, ParallelForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); ParallelForEachIndex(arr1.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), arr1(i, j)); }); } TEST(ConstArrayView2, Constructors) { double data[20]; for (int i = 0; i < 20; ++i) { data[i] = static_cast<double>(i); } // Construct with ArrayView2 ArrayView2<double> acc(data, Vector2UZ(5, 4)); ConstArrayView2<double> cacc(acc); EXPECT_EQ(5u, cacc.Size().x); EXPECT_EQ(4u, cacc.Size().y); EXPECT_EQ(data, cacc.data()); } TEST(ConstArrayView2, Iterators) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); float cnt = 1.f; for (const float& elem : acc) { EXPECT_FLOAT_EQ(cnt, elem); cnt += 1.f; } } TEST(ConstArrayView2, ForEach) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); size_t i = 0; std::for_each(acc.begin(), acc.end(), [&](float val) { EXPECT_FLOAT_EQ(acc[i], val); ++i; }); } TEST(ConstArrayView2, ForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); ForEachIndex(acc.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), acc(i, j)); }); } TEST(ConstArrayView2, ParallelForEachIndex) { Array2<float> arr1({ { 1.f, 2.f, 3.f, 4.f }, { 5.f, 6.f, 7.f, 8.f }, { 9.f, 10.f, 11.f, 12.f } }); auto acc = arr1.View(); ParallelForEachIndex(acc.Size(), [&](size_t i, size_t j) { size_t idx = i + (4 * j) + 1; EXPECT_FLOAT_EQ(static_cast<float>(idx), acc(i, j)); }); }
24.820144
63
0.476232
ADMTec
2d21e82648854d56ca83632f57c4237e4e4eafea
2,292
cpp
C++
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_not_in.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_not_in.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_not_in.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "sql/engine/expr/ob_expr_not_in.h" #include "sql/engine/expr/ob_expr_in.h" #include "sql/session/ob_sql_session_info.h" namespace oceanbase { using namespace common; namespace sql { // ObExprNotIn::ObExprNotIn(ObIAllocator &alloc) // :ObVectorExprOperator(alloc, T_OP_NOT_IN, N_NOT_IN, 2, 1) {}; // // int ObExprNotIn::calc_result_typeN(ObExprResType &type, // ObExprResType *types, // int64_t param_num, // common::ObExprTypeCtx &type_ctx) const //{ // int ret = ObVectorExprOperator::calc_result_typeN(type, types, param_num, type_ctx); // type.set_scale(DEFAULT_SCALE_FOR_INTEGER); // type.set_precision(DEFAULT_PRECISION_FOR_BOOL); // return ret; //} // // int ObExprNotIn::calc_resultN(common::ObObj &result, const common::ObObj *objs, // int64_t param_num, ObExprCtx &expr_ctx) const //{ // int ret = OB_SUCCESS; // int64_t bv = 0; // EXPR_DEFINE_CAST_CTX(expr_ctx, CM_NONE); // const ObIArray<ObExprCalcType> &cmp_types = result_type_.get_row_calc_cmp_types(); // if (OB_FAIL(ObExprIn::calc(result, // objs, // cmp_types, // param_num, // real_param_num_, // row_dimension_, // cast_ctx))) { // LOG_WARN("not in op failed", K(ret)); // } else if (OB_UNLIKELY(result.is_null())) { // //do nothing // } else if (OB_FAIL(result.get_int(bv))) { // LOG_WARN("get int failed", K(ret), K(result)); // } else { // result.set_int(!bv); // } // return ret; //} } } // namespace oceanbase
36.967742
88
0.616928
wangcy6
2d2230b10b1b8157f66c3780792c25aab530aebd
15,878
cpp
C++
Demos/Tests/TestBase/ImGuiAdapter.cpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
null
null
null
Demos/Tests/TestBase/ImGuiAdapter.cpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
1
2021-10-30T11:19:53.000Z
2021-10-30T11:19:54.000Z
Demos/Tests/TestBase/ImGuiAdapter.cpp
DhirajWishal/Flint
0750bd515de0b5cc3d23f7c2282c50ca483dff24
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Dhiraj Wishal // SPDX-License-Identifier: Apache-2.0 #include "ImGuiAdapter.hpp" #include "GraphicsCore/ScreenBoundRenderTarget.hpp" #include "GraphicsCore/ResourcePackager.hpp" #include "Graphics/Tools/ShaderCompiler.hpp" #include <optick.h> constexpr Flint::uint64 ElementCount = 2500; namespace Flint { ImGuiAdapter::ImGuiAdapter() : pDynamicStateContainer(std::make_shared<DynamicStateContainer>()) { } void ImGuiAdapter::Initialize(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ScreenBoundRenderTarget>& pRenderTarget) { OPTICK_EVENT(); this->pDevice = pDevice; this->pRenderTarget = pRenderTarget; if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.vert")), ShaderCodeType::GLSL, ShaderType::Vertex); pVertexShader = shaderCompiler.CreateShader(pDevice); pVertexShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc")); } else pVertexShader = pDevice->CreateShader(ShaderType::Vertex, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))); if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.frag")), ShaderCodeType::GLSL, ShaderType::Fragment); pFragmentShader = shaderCompiler.CreateShader(pDevice); pFragmentShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc")); } else pFragmentShader = pDevice->CreateShader(ShaderType::Fragment, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))); SetupImGui(); SetupGeometryStore(); SetupPipeline(pRenderTarget); SetupImage(); pVertexShader->Terminate(); pFragmentShader->Terminate(); } void ImGuiAdapter::Initialize(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<OffScreenRenderTarget>& pRenderTarget) { OPTICK_EVENT(); this->pDevice = pDevice; this->pRenderTarget = pRenderTarget; if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.vert")), ShaderCodeType::GLSL, ShaderType::Vertex); pVertexShader = shaderCompiler.CreateShader(pDevice); pVertexShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc")); } else pVertexShader = pDevice->CreateShader(ShaderType::Vertex, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.vert.fsc"))); if (!std::filesystem::exists(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))) { ShaderCompiler shaderCompiler(std::filesystem::path(NormalizePath("Shaders\\ImGui\\UI.frag")), ShaderCodeType::GLSL, ShaderType::Fragment); pFragmentShader = shaderCompiler.CreateShader(pDevice); pFragmentShader->CreateCache(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc")); } else pFragmentShader = pDevice->CreateShader(ShaderType::Fragment, std::filesystem::path(NormalizePath("Flint\\Shaders\\ImGui.frag.fsc"))); SetupImGui(); SetupGeometryStore(); SetupPipeline(pRenderTarget); SetupImage(); pVertexShader->Terminate(); pFragmentShader->Terminate(); } void ImGuiAdapter::Render(const std::shared_ptr<CommandBuffer>& pCommandBuffer, const uint32 index) { OPTICK_EVENT(); ImGui::Render(); UpdateGeometryStore(); ImGuiIO& io = ImGui::GetIO(); ImDrawData* pDrawData = ImGui::GetDrawData(); if (!pDrawData) return; // Update and Render additional Platform Windows if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); } pushConstants.mScale = glm::vec2(2.0f / io.DisplaySize.x, 2.0f / io.DisplaySize.y); pushConstants.mTranslate = glm::vec2(-1.0f); pDynamicStateContainer->SetViewPort(FExtent2D<float>(io.DisplaySize.x, io.DisplaySize.y), FExtent2D<float>(0.0f, 1.0f), FExtent2D<float>()); pDynamicStateContainer->SetConstantData(ShaderType::Vertex, &pushConstants, sizeof(PushConstants)); if (pDrawData->CmdListsCount) { pCommandBuffer->BindGeometryStore(pGeometryStore.get()); pCommandBuffer->BindGraphicsPipeline(pPipeline.get()); uint64 vertexOffset = 0, indexOffset = 0; for (int32 i = 0; i < pDrawData->CmdListsCount; i++) { const auto pCommandList = pDrawData->CmdLists[i]; for (int32 j = 0; j < pCommandList->CmdBuffer.Size; j++) { const auto& pCommand = pCommandList->CmdBuffer[j]; pDynamicStateContainer->SetScissor( FBox2D(static_cast<uint32>(pCommand.ClipRect.z - pCommand.ClipRect.x), static_cast<uint32>(pCommand.ClipRect.w - pCommand.ClipRect.y)), FBox2D(std::max(static_cast<int32>(pCommand.ClipRect.x), 0), std::max(static_cast<int32>(pCommand.ClipRect.y), 0))); // Handle the texture. if (pCommand.TextureId != nullptr) { const ImGuiTextureContainer* pContainer = static_cast<ImGuiTextureContainer*>(pCommand.TextureId); pCommandBuffer->BindResourcePackage(pPipeline.get(), pContainer->pResourcePackage.get()); } else pCommandBuffer->BindResourcePackage(pPipeline.get(), pResourcePacks[index].get()); pCommandBuffer->BindDynamicStates(pPipeline.get(), pDynamicStateContainer.get()); pCommandBuffer->IssueDrawCall(WireFrame("", vertexOffset, 0, indexOffset, pCommand.ElemCount)); indexOffset += pCommand.ElemCount; } vertexOffset += pCommandList->VtxBuffer.Size; } } } void ImGuiAdapter::SetupPipeline(const std::shared_ptr<ScreenBoundRenderTarget>& pRenderTarget) { OPTICK_EVENT(); GraphicsPipelineSpecification specification = {}; specification.mRasterizationSamples = MultiSampleCount::One; specification.mDynamicStateFlags = DynamicStateFlags::ViewPort | DynamicStateFlags::Scissor; specification.mCullMode = CullMode::None; specification.mColorBlendAttachments[0].mEnableBlend = true; specification.mColorBlendAttachments[0].mSrcBlendFactor = ColorBlendFactor::SourceAlpha; specification.mColorBlendAttachments[0].mDstBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mSrcAlphaBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mDstAlphaBlendFactor = ColorBlendFactor::Zero; specification.mDepthCompareLogic = DepthCompareLogic::LessOrEqual; specification.mColorBlendConstants[0] = 0.0f; specification.mColorBlendConstants[1] = 0.0f; specification.mColorBlendConstants[2] = 0.0f; specification.mColorBlendConstants[3] = 0.0f; specification.bEnableSampleShading = false; specification.mMinSampleShading = 0.0f; specification.mVertexInputAttributeMap[0] = pVertexShader->GetInputAttributes(); pPipeline = pDevice->CreateGraphicsPipeline("ImGUI", pRenderTarget, pVertexShader, nullptr, nullptr, nullptr, pFragmentShader, specification); } void ImGuiAdapter::SetupPipeline(const std::shared_ptr<OffScreenRenderTarget>& pRenderTarget) { OPTICK_EVENT(); GraphicsPipelineSpecification specification = {}; //specification.mRasterizationSamples = pDevice->GetSupportedMultiSampleCount(); specification.mRasterizationSamples = MultiSampleCount::One; specification.mDynamicStateFlags = DynamicStateFlags::ViewPort | DynamicStateFlags::Scissor; specification.mCullMode = CullMode::None; specification.mColorBlendAttachments[0].mEnableBlend = true; specification.mColorBlendAttachments[0].mSrcBlendFactor = ColorBlendFactor::SourceAlpha; specification.mColorBlendAttachments[0].mDstBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mSrcAlphaBlendFactor = ColorBlendFactor::OneMinusSourceAlpha; specification.mColorBlendAttachments[0].mDstAlphaBlendFactor = ColorBlendFactor::Zero; specification.mDepthCompareLogic = DepthCompareLogic::LessOrEqual; specification.mColorBlendConstants[0] = 0.0f; specification.mColorBlendConstants[1] = 0.0f; specification.mColorBlendConstants[2] = 0.0f; specification.mColorBlendConstants[3] = 0.0f; specification.bEnableSampleShading = false; specification.mMinSampleShading = 0.0f; specification.mVertexInputAttributeMap[0] = pVertexShader->GetInputAttributes(); pPipeline = pDevice->CreateGraphicsPipeline("ImGUI", pRenderTarget, pVertexShader, nullptr, nullptr, nullptr, pFragmentShader, specification); } void ImGuiAdapter::Terminate() { pPipeline->Terminate(); pGeometryStore->UnmapVertexBuffer(); pGeometryStore->UnmapIndexBuffer(); pGeometryStore->Terminate(); pFontImage->Terminate(); pFontSampler->Terminate(); } void ImGuiAdapter::SetupImGui() { OPTICK_EVENT(); ImGui::CreateContext(); ImGuiStyle& style = ImGui::GetStyle(); style.Colors[ImGuiCol_TitleBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.75f); style.Colors[ImGuiCol_WindowBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.25f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(CreateColor256(34), CreateColor256(40), CreateColor256(49), 0.25f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.8f); style.Colors[ImGuiCol_Header] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.6f); style.Colors[ImGuiCol_TabActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.25f); style.Colors[ImGuiCol_TabUnfocusedActive] = ImVec4(CreateColor256(57), CreateColor256(62), CreateColor256(70), 0.25f); style.Colors[ImGuiCol_TabHovered] = ImVec4(CreateColor256(0), CreateColor256(173), CreateColor256(181), 1.0f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(CreateColor256(0), CreateColor256(173), CreateColor256(181), 0.5f); style.ChildRounding = 6.0f; style.FrameRounding = 3.0f; style.PopupRounding = 3.0f; style.TabRounding = 3.0f; style.WindowRounding = 3.0f; ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(static_cast<float>(pRenderTarget->GetExtent().mWidth), static_cast<float>(pRenderTarget->GetExtent().mHeight)); io.DisplayFramebufferScale = ImVec2(16.0f, 9.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 8.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 14.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/simvoni-font/Simvoni-d9vV6.otf").string().c_str(), 16.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/azonix-font/Azonix-1VB0.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/a-atomic-md-font/AtomicMd-OVJ4A.otf").string().c_str(), 10.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/josefin-sans-font/JosefinSansRegular-x3LYV.ttf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/salma-alfasans-font/SalmaalfasansLight-d9MJx.otf").string().c_str(), 12.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/swansea-font/Swansea-q3pd.ttf").string().c_str(), 6.0f); io.Fonts->AddFontFromFileTTF(NormalizePath("Fonts/rawengulk-font/RawengulkBold-r8o9.otf").string().c_str(), 13.0f); //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows } void ImGuiAdapter::SetupGeometryStore() { OPTICK_EVENT(); pGeometryStore = pDevice->CreateGeometryStore(pVertexShader->GetInputAttributes(), sizeof(uint16), BufferMemoryProfile::TransferFriendly); } void ImGuiAdapter::SetupImage() { OPTICK_EVENT(); ImGuiIO& imGuiIO = ImGui::GetIO(); unsigned char* pFontImageData = nullptr; int width = 0, height = 0, bitsPerPixel = 0; imGuiIO.Fonts->GetTexDataAsRGBA32(&pFontImageData, &width, &height, &bitsPerPixel); for (uint64 i = 0; i < pRenderTarget->GetBufferCount(); i++) { pFontImage = pDevice->CreateImage(ImageType::TwoDimension, ImageUsage::Graphics, FBox3D(width, height, 1), PixelFormat::R8G8B8A8_SRGB, 1, 1, pFontImageData); ImageSamplerSpecification specification = {}; specification.mBorderColor = BorderColor::OpaqueWhiteFLOAT; specification.mAddressModeU = AddressMode::ClampToEdge; specification.mAddressModeV = AddressMode::ClampToEdge; specification.mAddressModeW = AddressMode::ClampToEdge; pFontSampler = pDevice->CreateImageSampler(specification); auto pResourcePack = pPipeline->CreateResourcePackage(0); pResourcePack->BindResource(0, pFontImage, pFontImage->CreateImageView(0, pFontImage->GetLayerCount(), 0, pFontImage->GetMipLevels(), ImageUsage::Graphics), pFontSampler); pResourcePacks.push_back(pResourcePack); } } void ImGuiAdapter::UpdateGeometryStore() { OPTICK_EVENT(); ImDrawData* pDrawData = ImGui::GetDrawData(); if (!pDrawData) return; const uint64 vertexSize = GetNewVertexBufferSize(pDrawData->TotalVtxCount * sizeof(ImDrawVert)), indexSize = GetNewIndexBufferSize(pDrawData->TotalIdxCount * sizeof(ImDrawIdx)); if ((vertexSize == 0) || (indexSize == 0)) return; std::shared_ptr<Buffer> pVertexBuffer = nullptr; std::shared_ptr<Buffer> pIndexBuffer = nullptr; bool bShouldWaitIdle = false; if (pGeometryStore->GetVertexCount() < pDrawData->TotalVtxCount || pDrawData->TotalVtxCount < (pGeometryStore->GetVertexCount() - ElementCount)) { pGeometryStore->UnmapVertexBuffer(); pVertexBuffer = pDevice->CreateBuffer(BufferType::Staging, vertexSize); pVertexData = static_cast<ImDrawVert*>(pVertexBuffer->MapMemory(vertexSize)); bShouldWaitIdle = true; } if (pGeometryStore->GetIndexCount() < pDrawData->TotalIdxCount || pDrawData->TotalIdxCount < (pGeometryStore->GetIndexCount() - ElementCount)) { pGeometryStore->UnmapIndexBuffer(); pIndexBuffer = pDevice->CreateBuffer(BufferType::Staging, indexSize); pIndexData = static_cast<ImDrawIdx*>(pIndexBuffer->MapMemory(indexSize)); bShouldWaitIdle = true; } auto pCopyVertexPointer = pVertexData; auto pCopyIndexPointer = pIndexData; for (int32 i = 0; i < pDrawData->CmdListsCount; i++) { const ImDrawList* pCommandList = pDrawData->CmdLists[i]; std::copy_n(pCommandList->VtxBuffer.Data, pCommandList->VtxBuffer.Size, pCopyVertexPointer); std::copy_n(pCommandList->IdxBuffer.Data, pCommandList->IdxBuffer.Size, pCopyIndexPointer); pCopyVertexPointer += pCommandList->VtxBuffer.Size; pCopyIndexPointer += pCommandList->IdxBuffer.Size; } if (pVertexBuffer) pVertexBuffer->UnmapMemory(); if (pIndexBuffer) pIndexBuffer->UnmapMemory(); if (bShouldWaitIdle) pDevice->WaitForQueue(); pGeometryStore->SetData(pVertexBuffer.get(), pIndexBuffer.get()); if (pVertexBuffer) { pVertexBuffer->Terminate(); pVertexData = static_cast<ImDrawVert*>(pGeometryStore->MapVertexBuffer()); } if (pIndexBuffer) { pIndexBuffer->Terminate(); pIndexData = static_cast<ImDrawIdx*>(pGeometryStore->MapIndexBuffer()); } } uint64 ImGuiAdapter::GetNewVertexBufferSize(const uint64 newSize) const { constexpr uint64 VertexFactor = ElementCount * sizeof(ImDrawVert); const auto count = (newSize / VertexFactor) + 1; return count * VertexFactor; } uint64 ImGuiAdapter::GetNewIndexBufferSize(const uint64 newSize) const { constexpr uint64 IndexFactor = ElementCount * sizeof(ImDrawIdx); const auto count = (newSize / IndexFactor) + 1; return count * IndexFactor; } }
40.817481
179
0.758534
DhirajWishal
2d2267ed5d622867ccea91a7d7a5fab5a7da71ab
6,676
cpp
C++
exportNF/release/windows/obj/src/resources/__res_49.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/src/resources/__res_49.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/src/resources/__res_49.cpp
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
// Generated by Haxe 4.2.1+bf9ff69 namespace hx { unsigned char __res_49[] = { 0x80, 0x00, 0x00, 0x80, 60,63,120,109,108,32,118,101,114,115, 105,111,110,61,34,49,46,48,34,32, 101,110,99,111,100,105,110,103,61,34, 117,116,102,45,56,34,32,63,62,13, 10,60,100,97,116,97,62,9,13,10, 9,60,115,112,114,105,116,101,32,105, 100,61,34,98,108,97,99,107,34,32, 120,61,34,48,34,32,121,61,34,48, 34,32,119,105,100,116,104,61,34,49, 48,48,37,34,32,104,101,105,103,104, 116,61,34,49,48,48,37,34,32,99, 111,108,111,114,61,34,48,120,56,56, 48,48,48,48,48,48,34,47,62,13, 10,9,13,10,9,60,99,104,114,111, 109,101,32,105,100,61,34,98,97,99, 107,34,32,99,101,110,116,101,114,95, 120,61,34,116,114,117,101,34,32,99, 101,110,116,101,114,95,121,61,34,116, 114,117,101,34,32,119,105,100,116,104, 61,34,52,48,48,34,32,104,101,105, 103,104,116,61,34,49,48,48,34,47, 62,9,9,13,10,9,13,10,9,60, 116,101,120,116,32,105,100,61,34,116, 105,116,108,101,34,32,120,61,34,48, 34,32,121,61,34,53,34,32,119,105, 100,116,104,61,34,98,97,99,107,46, 119,105,100,116,104,34,32,116,101,120, 116,61,34,36,80,79,80,85,80,95, 84,73,84,76,69,95,68,69,70,65, 85,76,84,34,32,97,108,105,103,110, 61,34,99,101,110,116,101,114,34,62, 13,10,9,9,60,97,110,99,104,111, 114,32,120,61,34,98,97,99,107,46, 108,101,102,116,34,32,120,45,102,108, 117,115,104,61,34,108,101,102,116,34, 32,121,61,34,98,97,99,107,46,116, 111,112,34,32,121,45,102,108,117,115, 104,61,34,116,111,112,34,47,62,9, 9,13,10,9,60,47,116,101,120,116, 62,13,10,9,13,10,9,60,116,101, 120,116,32,105,100,61,34,98,111,100, 121,34,32,120,61,34,53,34,32,121, 61,34,53,34,32,119,105,100,116,104, 61,34,98,97,99,107,46,119,105,100, 116,104,45,49,48,34,32,116,101,120, 116,61,34,36,80,79,80,85,80,95, 66,79,68,89,95,68,69,70,65,85, 76,84,34,32,97,108,105,103,110,61, 34,108,101,102,116,34,62,13,10,9, 9,60,97,110,99,104,111,114,32,120, 61,34,98,97,99,107,46,108,101,102, 116,34,32,120,45,102,108,117,115,104, 61,34,108,101,102,116,34,32,121,61, 34,116,105,116,108,101,46,98,111,116, 116,111,109,34,32,121,45,102,108,117, 115,104,61,34,116,111,112,34,47,62, 9,9,13,10,9,60,47,116,101,120, 116,62,13,10,9,13,10,9,60,98, 117,116,116,111,110,32,105,100,61,34, 98,116,110,48,34,32,121,61,34,45, 53,34,32,108,97,98,101,108,61,34, 36,80,79,80,85,80,95,89,69,83, 34,62,13,10,9,9,60,97,110,99, 104,111,114,32,121,61,34,98,97,99, 107,46,98,111,116,116,111,109,34,32, 121,45,102,108,117,115,104,61,34,98, 111,116,116,111,109,34,47,62,13,10, 9,9,60,112,97,114,97,109,32,116, 121,112,101,61,34,105,110,116,34,32, 118,97,108,117,101,61,34,48,34,47, 62,9,9,13,10,9,60,47,98,117, 116,116,111,110,62,13,10,9,13,10, 9,60,98,117,116,116,111,110,32,105, 100,61,34,98,116,110,49,34,32,108, 97,98,101,108,61,34,36,80,79,80, 85,80,95,78,79,34,62,13,10,9, 9,60,97,110,99,104,111,114,32,121, 61,34,98,116,110,48,46,116,111,112, 34,32,121,45,102,108,117,115,104,61, 34,116,111,112,34,47,62,13,10,9, 9,60,112,97,114,97,109,32,116,121, 112,101,61,34,105,110,116,34,32,118, 97,108,117,101,61,34,49,34,47,62, 13,10,9,60,47,98,117,116,116,111, 110,62,13,10,9,9,13,10,9,60, 98,117,116,116,111,110,32,105,100,61, 34,98,116,110,50,34,32,108,97,98, 101,108,61,34,36,80,79,80,85,80, 95,67,65,78,67,69,76,34,62,13, 10,9,9,60,97,110,99,104,111,114, 32,121,61,34,98,116,110,48,46,116, 111,112,34,32,121,45,102,108,117,115, 104,61,34,116,111,112,34,47,62,9, 9,13,10,9,9,60,112,97,114,97, 109,32,116,121,112,101,61,34,105,110, 116,34,32,118,97,108,117,101,61,34, 50,34,47,62,13,10,9,60,47,98, 117,116,116,111,110,62,13,10,9,13, 10,9,60,109,111,100,101,32,105,100, 61,34,49,98,116,110,34,32,105,115, 95,100,101,102,97,117,108,116,61,34, 116,114,117,101,34,62,13,10,9,9, 60,115,104,111,119,32,105,100,61,34, 98,116,110,48,34,47,62,13,10,9, 9,60,104,105,100,101,32,105,100,61, 34,98,116,110,49,44,98,116,110,50, 34,47,62,13,10,9,9,60,99,104, 97,110,103,101,32,105,100,61,34,98, 116,110,48,34,32,108,97,98,101,108, 61,34,36,80,79,80,85,80,95,79, 75,34,32,119,105,100,116,104,61,34, 98,97,99,107,46,119,105,100,116,104, 42,48,46,50,53,34,47,62,13,10, 9,9,60,112,111,115,105,116,105,111, 110,32,105,100,61,34,98,116,110,48, 34,62,13,10,9,9,9,60,97,110, 99,104,111,114,32,120,61,34,98,97, 99,107,46,99,101,110,116,101,114,34, 32,120,45,102,108,117,115,104,61,34, 99,101,110,116,101,114,34,47,62,13, 10,9,9,60,47,112,111,115,105,116, 105,111,110,62,13,10,9,60,47,109, 111,100,101,62,13,10,9,13,10,9, 60,109,111,100,101,32,105,100,61,34, 50,98,116,110,34,62,13,10,9,9, 60,115,104,111,119,32,105,100,61,34, 98,116,110,48,44,98,116,110,49,34, 47,62,13,10,9,9,60,104,105,100, 101,32,105,100,61,34,98,116,110,50, 34,47,62,13,10,9,9,60,97,108, 105,103,110,32,97,120,105,115,61,34, 104,111,114,105,122,111,110,116,97,108, 34,32,115,112,97,99,105,110,103,61, 34,49,48,34,32,114,101,115,105,122, 101,61,34,116,114,117,101,34,62,13, 10,9,9,9,60,98,111,117,110,100, 115,32,108,101,102,116,61,34,98,97, 99,107,46,108,101,102,116,34,32,114, 105,103,104,116,61,34,98,97,99,107, 46,114,105,103,104,116,45,49,48,34, 47,62,9,9,13,10,9,9,9,60, 111,98,106,101,99,116,115,32,118,97, 108,117,101,61,34,98,116,110,48,44, 98,116,110,49,34,47,62,13,10,9, 9,60,47,97,108,105,103,110,62,13, 10,9,9,60,99,104,97,110,103,101, 32,105,100,61,34,98,116,110,48,34, 32,108,97,98,101,108,61,34,36,80, 79,80,85,80,95,79,75,34,47,62, 13,10,9,9,60,99,104,97,110,103, 101,32,105,100,61,34,98,116,110,49, 34,32,108,97,98,101,108,61,34,36, 80,79,80,85,80,95,67,65,78,67, 69,76,34,47,62,13,10,9,60,47, 109,111,100,101,62,13,10,9,9,13, 10,9,60,109,111,100,101,32,105,100, 61,34,51,98,116,110,34,62,13,10, 9,9,60,115,104,111,119,32,105,100, 61,34,98,116,110,48,44,98,116,110, 49,44,98,116,110,50,34,47,62,13, 10,9,9,60,97,108,105,103,110,32, 97,120,105,115,61,34,104,111,114,105, 122,111,110,116,97,108,34,32,115,112, 97,99,105,110,103,61,34,53,34,32, 114,101,115,105,122,101,61,34,116,114, 117,101,34,62,13,10,9,9,9,60, 98,111,117,110,100,115,32,108,101,102, 116,61,34,98,97,99,107,46,108,101, 102,116,43,53,34,32,114,105,103,104, 116,61,34,98,97,99,107,46,114,105, 103,104,116,45,53,34,47,62,9,9, 13,10,9,9,9,60,111,98,106,101, 99,116,115,32,118,97,108,117,101,61, 34,98,116,110,48,44,98,116,110,49, 44,98,116,110,50,34,47,62,13,10, 9,9,60,47,97,108,105,103,110,62, 13,10,9,9,60,99,104,97,110,103, 101,32,105,100,61,34,98,116,110,48, 34,32,108,97,98,101,108,61,34,36, 80,79,80,85,80,95,89,69,83,34, 47,62,13,10,9,9,60,99,104,97, 110,103,101,32,105,100,61,34,98,116, 110,49,34,32,108,97,98,101,108,61, 34,36,80,79,80,85,80,95,78,79, 34,47,62,13,10,9,9,60,99,104, 97,110,103,101,32,105,100,61,34,98, 116,110,50,34,32,108,97,98,101,108, 61,34,36,80,79,80,85,80,95,67, 65,78,67,69,76,34,47,62,13,10, 9,60,47,109,111,100,101,62,13,10, 60,47,100,97,116,97,62,0x00 }; }
33.888325
39
0.680348
theblobscp
2d22a488af91700dbdde75bec12f7c3a600d90dc
551
cpp
C++
hdoj/hdu4841.cpp
songhn233/ACM_Steps
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
hdoj/hdu4841.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
hdoj/hdu4841.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<vector> using namespace std; const int maxn=100000; int n,m; vector<int> a; int main() { while(cin>>n>>m) { a.clear(); for(int i=0;i<2*n;i++) a.push_back(i); int pos=0; for(int i=0;i<n;i++) { pos=(pos+m-1)%a.size(); a.erase(a.begin()+pos); } int temp=0; for(int i=0;i<2*n;i++) { if((i%50==0)&&i!=0) puts(""); if(temp<a.size()&&a[temp]==i) { cout<<'G'; temp++; } else cout<<'B'; } puts("");puts(""); } return 0; }
14.891892
40
0.53539
songhn233
2d22aaba97ced5a101977b949e833bbe27571bdf
4,193
cc
C++
slvn-tech/src/slvn_buffer.cc
Planksu/slvn-tech
628565e26b0f83f34337937f4bc0b5abf26afe5d
[ "BSD-2-Clause" ]
null
null
null
slvn-tech/src/slvn_buffer.cc
Planksu/slvn-tech
628565e26b0f83f34337937f4bc0b5abf26afe5d
[ "BSD-2-Clause" ]
null
null
null
slvn-tech/src/slvn_buffer.cc
Planksu/slvn-tech
628565e26b0f83f34337937f4bc0b5abf26afe5d
[ "BSD-2-Clause" ]
null
null
null
// BSD 2-Clause License // // Copyright (c) 2021, Antton Jokinen // 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 <slvn_buffer.h> #include <slvn_debug.h> namespace slvn_tech { SlvnBuffer::SlvnBuffer(VkDevice* device, uint32_t bufferSize, VkBufferUsageFlags usage, VkSharingMode sharingMode) { VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.size = bufferSize; info.usage = usage; info.sharingMode = sharingMode; VkResult result = vkCreateBuffer(*device, &info, nullptr, &mBuffer); assert(result == VK_SUCCESS); } SlvnBuffer::SlvnBuffer() { SLVN_PRINT("ENTER"); } SlvnBuffer::~SlvnBuffer() { } SlvnResult SlvnBuffer::Deinitialize(VkDevice* device) { vkDestroyBuffer(*device, mBuffer, nullptr); vkFreeMemory(*device, mMemory, nullptr); return SlvnResult::cOk; } std::optional<VkDeviceSize> SlvnBuffer::getAllocationSize(VkDevice* device) const { VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs); return std::make_optional<VkDeviceSize>(memReqs.size); } std::optional<uint32_t> SlvnBuffer::getMemoryTypeIndex(VkDevice* device, VkPhysicalDevice* physDev, uint32_t wantedFlags) const { VkMemoryRequirements memReqs; vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs); VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(*physDev, &memProperties); std::optional<uint32_t> value = std::nullopt; for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((memReqs.memoryTypeBits & (1 << i)) && ((memProperties.memoryTypes[i].propertyFlags & wantedFlags) == wantedFlags)) { value = i; break; } } return value; } SlvnResult SlvnBuffer::Insert(VkDevice* device, VkPhysicalDevice* physDev, uint32_t size, const void* data) { uint32_t memFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; mBufferByteSize = size; std::optional<VkDeviceSize> bufferSize = getAllocationSize(device); assert(bufferSize); std::optional<uint32_t> bufferMemIndex = getMemoryTypeIndex(device, physDev, memFlags); assert(bufferMemIndex); VkMemoryAllocateInfo allocateInfo = {}; allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocateInfo.allocationSize = *bufferSize; allocateInfo.memoryTypeIndex = *bufferMemIndex; VkResult result = vkAllocateMemory(*device, &allocateInfo, nullptr, &mMemory); assert(result == VK_SUCCESS); result = vkBindBufferMemory(*device, mBuffer, mMemory, 0); assert(result == VK_SUCCESS); void* bufferMemory; result = vkMapMemory(*device, mMemory, 0, size, 0, &bufferMemory); assert(result == VK_SUCCESS); std::memcpy(bufferMemory, data, size); vkUnmapMemory(*device, mMemory); return SlvnResult::cOk; } }
34.941667
127
0.740281
Planksu
2d22b7af185dfcd5848585b115ea9be503cc7190
41
hpp
C++
src/_Internals/hsl_ma86z.hpp
GitBytes/hiop
8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f
[ "BSD-3-Clause" ]
126
2017-12-30T13:06:07.000Z
2022-03-27T03:30:46.000Z
src/_Internals/hsl_ma86z.hpp
GitBytes/hiop
8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f
[ "BSD-3-Clause" ]
344
2018-01-24T22:05:38.000Z
2022-03-31T17:49:52.000Z
src/_Internals/hsl_ma86z.hpp
GitBytes/hiop
8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f
[ "BSD-3-Clause" ]
30
2018-01-20T00:16:06.000Z
2022-03-18T12:57:19.000Z
#define HSL_MA86Z_HEADER_NOT_CPP_READY 1
20.5
40
0.902439
GitBytes
2d245a07a632f00c2b9329b9290fda3b96c39bbf
269
hpp
C++
pythran/pythonic/operator_/__ge__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/operator_/__ge__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/operator_/__ge__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_OPERATOR_GE__HPP #define PYTHONIC_OPERATOR_GE__HPP #include "pythonic/include/operator_/__ge__.hpp" #include "pythonic/operator_/ge.hpp" namespace pythonic { namespace operator_ { FPROXY_IMPL(pythonic::operator_, __ge__, ge); } } #endif
14.944444
49
0.769517
artas360
2d247cd0a8f5408a4c3257dcc636fc5140146b64
11,226
cpp
C++
BGFXWidget.cpp
PetrPPetrov/bgfx-qt5-win
1008de71ef2cb061a02ec8c7aaf9ba1a74799f16
[ "MIT" ]
6
2019-12-12T09:56:36.000Z
2021-09-04T02:40:27.000Z
BGFXWidget.cpp
PetrPPetrov/bgfx-qt5-win
1008de71ef2cb061a02ec8c7aaf9ba1a74799f16
[ "MIT" ]
null
null
null
BGFXWidget.cpp
PetrPPetrov/bgfx-qt5-win
1008de71ef2cb061a02ec8c7aaf9ba1a74799f16
[ "MIT" ]
3
2019-12-13T10:42:30.000Z
2020-11-12T12:51:41.000Z
#include <cassert> #include <fstream> #include "BGFXWidget.h" struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_layout .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexLayout ms_layout; }; bgfx::VertexLayout PosColorVertex::ms_layout; static PosColorVertex s_cubeVertices[] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeTriList[] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; inline const bgfx::Memory* loadMem(const std::string& filename) { std::ifstream in(filename.c_str(), std::ios_base::binary); in.exceptions(std::ifstream::failbit | std::ifstream::badbit); in.seekg(0, std::ifstream::end); const uint32_t file_size(static_cast<uint32_t>(in.tellg())); in.seekg(0, std::ifstream::beg); const bgfx::Memory* mem = bgfx::alloc(file_size + 1); if (mem && file_size > 0) { in.read(reinterpret_cast<char*>(mem->data), file_size); mem->data[mem->size - 1] = '\0'; } return mem; } inline bgfx::ShaderHandle loadShader(const std::string& filename) { std::string shader_path; switch (bgfx::getRendererType()) { default: case bgfx::RendererType::Noop: assert(false); case bgfx::RendererType::Direct3D9: shader_path = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: case bgfx::RendererType::Direct3D12: shader_path = "shaders/dx11/"; break; case bgfx::RendererType::Gnm: shader_path = "shaders/pssl/"; break; case bgfx::RendererType::Metal: shader_path = "shaders/metal/"; break; case bgfx::RendererType::Nvn: shader_path = "shaders/nvn/"; break; case bgfx::RendererType::OpenGL: shader_path = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES: shader_path = "shaders/essl/"; break; case bgfx::RendererType::Vulkan: shader_path = "shaders/spirv/"; break; } std::string file_path = shader_path + filename + ".bin"; bgfx::ShaderHandle handle = bgfx::createShader(loadMem(file_path)); bgfx::setName(handle, filename.c_str()); return handle; } inline bgfx::ProgramHandle loadProgram(const std::string& vs_name, const std::string& fs_name) { bgfx::ShaderHandle vsh = loadShader(vs_name); bgfx::ShaderHandle fsh = BGFX_INVALID_HANDLE; if (!fs_name.empty()) { fsh = loadShader(fs_name); } return bgfx::createProgram(vsh, fsh); } BGFXWidget::BGFXWidget(QWidget *parent) : QOpenGLWidget(parent) { setDefaultCamera(); } void BGFXWidget::initializeBGFX(int width, int height, void* native_window_handle) { initial_width = width; initial_height = height; debug = BGFX_DEBUG_NONE; reset = BGFX_RESET_NONE; bgfx::Init init; init.type = bgfx::RendererType::Direct3D9; // Or OpenGL or Direct3D11 init.vendorId = BGFX_PCI_ID_NONE; init.resolution.width = width; init.resolution.height = height; init.resolution.reset = reset; init.platformData.nwh = native_window_handle; bgfx::init(init); bgfx::setDebug(debug); bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0); PosColorVertex::init(); // Create static vertex buffer. m_vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices)) , PosColorVertex::ms_layout ); // Create static index buffer for triangle list rendering. m_ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeTriList, sizeof(s_cubeTriList)) ); // Create program from shaders. m_program = loadProgram("vs_cubes", "fs_cubes"); } BGFXWidget::~BGFXWidget() { bgfx::destroy(m_ibh); bgfx::destroy(m_vbh); bgfx::destroy(m_program); bgfx::shutdown(); } void BGFXWidget::setDefaultCamera() { viewer_pos = bx::Vec3(0, 0, 10); viewer_target = bx::Vec3(0, 0, 0); viewer_up = bx::Vec3(0, 1, 0); rotation_radius = bx::length(sub(viewer_pos, viewer_target)); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; minimum_rotation_radius = 0.1; maximum_rotation_radius = 1000.0; } void BGFXWidget::paintEvent(QPaintEvent* event) { float view_matrix[16]; bx::mtxLookAt( view_matrix, viewer_pos, viewer_target, viewer_up ); float projection_matrix[16]; bx::mtxProj( projection_matrix, 50.0f, static_cast<float>(width()) / static_cast<float>(height()), 1.0f, 1024.0f, bgfx::getCaps()->homogeneousDepth ); bgfx::setViewTransform(0, view_matrix, projection_matrix); bgfx::setViewRect(0, 0, 0, width(), height()); bgfx::touch(0); // Set vertex and index buffer. bgfx::setVertexBuffer(0, m_vbh); bgfx::setIndexBuffer(m_ibh); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0, m_program); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } void BGFXWidget::resizeEvent(QResizeEvent* event) { // TODO: } void BGFXWidget::mouseMoveEvent(QMouseEvent *event) { if (left_mouse_pressed && right_mouse_pressed) { // Pan mode QPointF current_point = event->localPos(); const double effective_rotation_radius = std::max(rotation_radius, 10.0); double delta_x = (current_point.x() - previous_point.x()) / width() * effective_rotation_radius; double delta_y = (current_point.y() - previous_point.y()) / height() * effective_rotation_radius; auto user_position = sub(viewer_previous_pos, viewer_previous_target); auto right = normalize(cross(viewer_up, user_position)); auto offset = add(mul(right, delta_x), mul(viewer_up, delta_y)); viewer_pos = add(viewer_previous_pos, offset); viewer_target = add(viewer_previous_target, offset); // Restore rotation orbit radius viewer_target = add(viewer_pos, mul(normalize(sub(viewer_target, viewer_pos)), rotation_radius)); update(); } else if (left_mouse_pressed) { // Rotation mode QPointF current_point = event->localPos(); double delta_x = previous_point.x() - current_point.x(); double delta_y = previous_point.y() - current_point.y(); double x_rotation_angle = delta_x / width() * bx::kPi; double y_rotation_angle = delta_y / height() * bx::kPi; auto user_position = sub(viewer_previous_pos, viewer_previous_target); auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle); bx::Vec3 temp_user_position = mul(user_position, rotation_x); auto left = normalize(cross(temp_user_position, viewer_previous_up)); auto rotation_y = bx::rotateAxis(left, y_rotation_angle); bx::Quaternion result_rotation = mul(rotation_x, rotation_y); auto rotated_user_position = mul(normalize(mul(user_position, result_rotation)), rotation_radius); viewer_pos = add(viewer_previous_target, rotated_user_position); viewer_up = normalize(mul(viewer_previous_up, result_rotation)); // Restore up vector property: up vector must be orthogonal to direction vector auto new_left = cross(rotated_user_position, viewer_up); viewer_up = normalize(cross(new_left, rotated_user_position)); update(); } else if (right_mouse_pressed) { // First person look mode QPointF current_point = event->localPos(); double delta_x = current_point.x() - previous_point.x(); double delta_y = current_point.y() - previous_point.y(); double x_rotation_angle = delta_x / width() * bx::kPi; double y_rotation_angle = delta_y / height() * bx::kPi; auto view_direction = sub(viewer_previous_target, viewer_previous_pos); auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle); bx::Vec3 temp_view_direction = mul(view_direction, rotation_x); auto left = normalize(cross(viewer_previous_up, temp_view_direction)); auto rotation_y = bx::rotateAxis(left, y_rotation_angle); bx::Quaternion result_rotation = mul(rotation_y, rotation_x); auto rotated_view_direction = mul(normalize(mul(view_direction, result_rotation)), rotation_radius); viewer_target = add(viewer_previous_pos, rotated_view_direction); viewer_up = normalize(mul(viewer_previous_up, result_rotation)); // Restore up vector property: up vector must be orthogonal to direction vector auto new_left = cross(viewer_up, rotated_view_direction); viewer_up = normalize(cross(rotated_view_direction, new_left)); update(); } } void BGFXWidget::mousePressEvent(QMouseEvent *event) { bool left_or_right = false; if (event->buttons() & Qt::LeftButton) { left_mouse_pressed = true; left_or_right = true; } if (event->buttons() & Qt::RightButton) { right_mouse_pressed = true; left_or_right = true; } if (left_or_right) { previous_point = event->localPos(); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; } } void BGFXWidget::mouseReleaseEvent(QMouseEvent *event) { bool left_or_right = false; if (!(event->buttons() & Qt::LeftButton)) { left_mouse_pressed = false; left_or_right = true; } if (!(event->buttons() & Qt::RightButton)) { right_mouse_pressed = false; left_or_right = true; } if (left_or_right) { previous_point = event->localPos(); viewer_previous_pos = viewer_pos; viewer_previous_target = viewer_target; viewer_previous_up = viewer_up; } } void BGFXWidget::wheelEvent(QWheelEvent *event) { QPoint delta = event->angleDelta(); rotation_radius += delta.y() / 1000.0f * rotation_radius; if (rotation_radius < minimum_rotation_radius) { rotation_radius = minimum_rotation_radius; } if (rotation_radius > maximum_rotation_radius) { rotation_radius = maximum_rotation_radius; } auto user_position = sub(viewer_pos, viewer_target); auto new_user_position = mul(normalize(user_position), rotation_radius); viewer_pos = add(viewer_target, new_user_position); update(); }
33.017647
108
0.656155
PetrPPetrov
2d25ff4876071ba76ab86ad68633157e3eabee35
956
hpp
C++
android-28/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../os/ParcelFileDescriptor_AutoCloseOutputStream.hpp" class JByteArray; namespace android::content::res { class AssetFileDescriptor; } namespace android::content::res { class AssetFileDescriptor_AutoCloseOutputStream : public android::os::ParcelFileDescriptor_AutoCloseOutputStream { public: // Fields // QJniObject forward template<typename ...Ts> explicit AssetFileDescriptor_AutoCloseOutputStream(const char *className, const char *sig, Ts...agv) : android::os::ParcelFileDescriptor_AutoCloseOutputStream(className, sig, std::forward<Ts>(agv)...) {} AssetFileDescriptor_AutoCloseOutputStream(QJniObject obj); // Constructors AssetFileDescriptor_AutoCloseOutputStream(android::content::res::AssetFileDescriptor arg0); // Methods void write(JByteArray arg0) const; void write(jint arg0) const; void write(JByteArray arg0, jint arg1, jint arg2) const; }; } // namespace android::content::res
29.875
230
0.775105
YJBeetle
2d261fc49eb26146deb080dcd097a5bdaccac955
12,375
cxx
C++
PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. * * * * Author: R. Haake. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <iostream> #include <TRandom3.h> #include <AliLog.h> #include <TString.h> #include <TMath.h> #include <TClonesArray.h> #include <AliAODTrack.h> #include <AliPicoTrack.h> #include <AliEmcalJet.h> #include <AliRhoParameter.h> #include "TH1D.h" #include "TH2D.h" #include "AliAnalysisTaskEmcal.h" #include "AliAnalysisTaskParticleRandomizer.h" /// \cond CLASSIMP ClassImp(AliAnalysisTaskParticleRandomizer) /// \endcond //_____________________________________________________________________________________________________ AliAnalysisTaskParticleRandomizer::AliAnalysisTaskParticleRandomizer() : AliAnalysisTaskEmcal("AliAnalysisTaskParticleRandomizer", kFALSE), fRandomizeInPhi(1), fRandomizeInEta(0), fRandomizeInTheta(0), fRandomizeInPt(0), fMinPhi(0), fMaxPhi(TMath::TwoPi()), fMinEta(-0.9), fMaxEta(+0.9), fMinPt(0), fMaxPt(120), fDistributionV2(0), fDistributionV3(0), fDistributionV4(0), fDistributionV5(0), fInputArrayName(), fOutputArrayName(), fInputArray(0), fOutputArray(0), fJetRemovalRhoObj(), fJetRemovalArrayName(), fJetRemovalArray(0), fJetRemovalPtThreshold(999.), fJetEmbeddingArrayName(), fJetEmbeddingArray(0), fRandomPsi3(0), fRandom() { // constructor } //_____________________________________________________________________________________________________ AliAnalysisTaskParticleRandomizer::~AliAnalysisTaskParticleRandomizer() { // destructor } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::UserCreateOutputObjects() { // Check user input if(fInputArrayName.IsNull()) AliWarning(Form("Name of input array not given!")); if(fOutputArrayName.IsNull()) AliFatal(Form("Name of output array not given!")); fRandom = new TRandom3(0); } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::ExecOnce() { // Check if arrays are OK fInputArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fInputArrayName.Data()))); if(!fInputArrayName.IsNull() && !fInputArray) AliFatal(Form("Input array '%s' not found!", fInputArrayName.Data())); // On demand, load also jets if(!fJetRemovalArrayName.IsNull()) { fJetRemovalArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetRemovalArrayName.Data()))); if(!fJetRemovalArray) AliError(Form("Jet array '%s' demanded but not found in event!", fJetRemovalArrayName.Data())); } // On demand, load array for embedding if(!fJetEmbeddingArrayName.IsNull()) { fJetEmbeddingArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetEmbeddingArrayName.Data()))); if(!fJetEmbeddingArray) AliError(Form("Embedding array '%s' demanded but not found in event!", fJetEmbeddingArrayName.Data())); } if((InputEvent()->FindListObject(Form("%s", fOutputArrayName.Data())))) AliFatal(Form("Output array '%s' already exists in the event! Rename it.", fInputArrayName.Data())); if(fInputArray) if(strcmp(fInputArray->GetClass()->GetName(), "AliAODTrack")) AliError(Form("Track type %s not yet supported. Use AliAODTrack", fInputArray->GetClass()->GetName())); // Copy the input array to the output array fOutputArray = new TClonesArray("AliAODTrack"); fOutputArray->SetName(fOutputArrayName.Data()); InputEvent()->AddObject(fOutputArray); AliAnalysisTaskEmcal::ExecOnce(); } //_____________________________________________________________________________________________________ Bool_t AliAnalysisTaskParticleRandomizer::Run() { fRandomPsi3 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi3 fRandomPsi4 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi4 fRandomPsi5 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi5 Int_t accTracks = 0; // Add events in input array if(fInputArray) for(Int_t iPart=0; iPart<fInputArray->GetEntries(); iPart++) { // Remove particles contained in jet array (on demand) if(fJetRemovalArray && IsParticleInJet(iPart)) continue; // Take only particles from the randomization acceptance AliAODTrack* inputParticle = static_cast<AliAODTrack*>(fInputArray->At(iPart)); if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) ) continue; if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) ) continue; new ((*fOutputArray)[accTracks]) AliAODTrack(*((AliAODTrack*)fInputArray->At(iPart))); // Randomize on demand AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks)); RandomizeTrack(particle); accTracks++; } // Add particles for embedding (on demand) if(fJetEmbeddingArray) for(Int_t iPart=0; iPart<fJetEmbeddingArray->GetEntries(); iPart++) { // Take only particles from the randomization acceptance AliPicoTrack* inputParticle = static_cast<AliPicoTrack*>(fJetEmbeddingArray->At(iPart)); if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) ) continue; if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) ) continue; new ((*fOutputArray)[accTracks]) AliAODTrack(*(GetAODTrack(inputParticle))); // Randomize on demand AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks)); RandomizeTrack(particle); accTracks++; } // std::cout << Form("%i particles from jets removed out of %i tracks. ", fInputArray->GetEntries()-accTracks, fInputArray->GetEntries()) << std::endl; return kTRUE; } //_____________________________________________________________________________________________________ void AliAnalysisTaskParticleRandomizer::RandomizeTrack(AliAODTrack* particle) { if(fRandomizeInPhi) particle->SetPhi(fMinPhi + fRandom->Rndm()*(fMaxPhi-fMinPhi)); if(fRandomizeInTheta) { Double_t minTheta = 2.*atan(exp(-fMinEta)); Double_t maxTheta = 2.*atan(exp(-fMaxEta)); particle->SetTheta(minTheta + fRandom->Rndm()*(maxTheta-minTheta)); } if(fRandomizeInEta) { Double_t randomEta = fMinEta + fRandom->Rndm()*(fMaxEta-fMinEta); Double_t randomTheta = 2.*atan(exp(-randomEta)); particle->SetTheta(randomTheta); } if(fRandomizeInPt) particle->SetPt(fMinPt + fRandom->Rndm()*(fMaxPt-fMinPt)); if(fDistributionV2 || fDistributionV3 || fDistributionV4 || fDistributionV5) particle->SetPhi(AddFlow(particle->Phi(), particle->Pt())); } //_____________________________________________________________________________________________________ AliAODTrack* AliAnalysisTaskParticleRandomizer::GetAODTrack(AliPicoTrack* track) { AliAODTrack* newTrack = new AliAODTrack(); newTrack->SetPt(track->Pt()); newTrack->SetTheta(2.*atan(exp(-track->Eta()))); // there is no setter for eta newTrack->SetPhi(track->Phi()); newTrack->SetCharge(track->Charge()); newTrack->SetLabel(track->GetLabel()); // Hybrid tracks (compatible with LHC11h) UInt_t filterMap = BIT(8) | BIT(9); newTrack->SetIsHybridGlobalConstrainedGlobal(); newTrack->SetFilterMap(filterMap); return newTrack; } //_____________________________________________________________________________________________________ Bool_t AliAnalysisTaskParticleRandomizer::IsParticleInJet(Int_t part) { for(Int_t i=0; i<fJetRemovalArray->GetEntries(); i++) { AliEmcalJet* tmpJet = static_cast<AliEmcalJet*>(fJetRemovalArray->At(i)); Double_t tmpPt = tmpJet->Pt() - tmpJet->Area()*GetExternalRho(); if(tmpPt >= fJetRemovalPtThreshold) if(tmpJet->ContainsTrack(part)>=0) return kTRUE; } return kFALSE; } //_____________________________________________________________________________________________________ Double_t AliAnalysisTaskParticleRandomizer::GetExternalRho() { // Get rho from event. AliRhoParameter* rho = 0; if (!fJetRemovalRhoObj.IsNull()) { rho = dynamic_cast<AliRhoParameter*>(InputEvent()->FindListObject(fJetRemovalRhoObj.Data())); if (!rho) { AliError(Form("%s: Could not retrieve rho with name %s!", GetName(), fJetRemovalRhoObj.Data())); return 0; } } else return 0; return (rho->GetVal()); } //_____________________________________________________________________________________________________ Double_t AliAnalysisTaskParticleRandomizer::AddFlow(Double_t phi, Double_t pt) { // adapted from AliFlowTrackSimple Double_t precisionPhi = 1e-10; Int_t maxNumberOfIterations = 200; Double_t phi0=phi; Double_t f=0.; Double_t fp=0.; Double_t phiprev=0.; Int_t ptBin = 0; // Evaluate V2 for track pt/centrality Double_t v2 = 0; if(fDistributionV2) { ptBin = fDistributionV2->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV2->GetNbinsX()) v2 = fDistributionV2->GetBinContent(fDistributionV2->GetNbinsX(), fDistributionV2->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v2 = fDistributionV2->GetBinContent(ptBin, fDistributionV2->GetYaxis()->FindBin(fCent)); } // Evaluate V3 for track pt/centrality Double_t v3 = 0; if(fDistributionV3) { ptBin = fDistributionV3->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV3->GetNbinsX()) v3 = fDistributionV3->GetBinContent(fDistributionV3->GetNbinsX(), fDistributionV3->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v3 = fDistributionV3->GetBinContent(ptBin, fDistributionV3->GetYaxis()->FindBin(fCent)); } // Evaluate V4 for track pt/centrality Double_t v4 = 0; if(fDistributionV4) { ptBin = fDistributionV4->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV4->GetNbinsX()) v4 = fDistributionV4->GetBinContent(fDistributionV4->GetNbinsX(), fDistributionV4->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v4 = fDistributionV4->GetBinContent(ptBin, fDistributionV4->GetYaxis()->FindBin(fCent)); } // Evaluate V5 for track pt/centrality Double_t v5 = 0; if(fDistributionV5) { ptBin = fDistributionV5->GetXaxis()->FindBin(pt); if(ptBin>fDistributionV5->GetNbinsX()) v5 = fDistributionV5->GetBinContent(fDistributionV5->GetNbinsX(), fDistributionV5->GetYaxis()->FindBin(fCent)); else if(ptBin>0) v5 = fDistributionV5->GetBinContent(ptBin, fDistributionV5->GetYaxis()->FindBin(fCent)); } // Add all v's for (Int_t i=0; i<maxNumberOfIterations; i++) { phiprev=phi; //store last value for comparison f = phi-phi0 + v2*TMath::Sin(2.*(phi-(fEPV0+(TMath::Pi()/2.)))) +2./3.*v3*TMath::Sin(3.*(phi-fRandomPsi3)) +0.5 *v4*TMath::Sin(4.*(phi-fRandomPsi4)) +0.4 *v5*TMath::Sin(5.*(phi-fRandomPsi5)); fp = 1.0+2.0*( +v2*TMath::Cos(2.*(phi-(fEPV0+(TMath::Pi()/2.)))) +v3*TMath::Cos(3.*(phi-fRandomPsi3)) +v4*TMath::Cos(4.*(phi-fRandomPsi4)) +v5*TMath::Cos(5.*(phi-fRandomPsi5))); //first derivative phi -= f/fp; if (TMath::AreEqualAbs(phiprev,phi,precisionPhi)) break; } return phi; }
39.410828
563
0.699879
wiechula
2d2884437496b2c91a3f8220043be5a0bbd28c58
357
hpp
C++
srook/config/disable_warnings/push/Wvariadic-macros.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
1
2018-07-01T07:54:37.000Z
2018-07-01T07:54:37.000Z
srook/config/disable_warnings/push/Wvariadic-macros.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
srook/config/disable_warnings/push/Wvariadic-macros.hpp
falgon/srookCppLibraries
ebcfacafa56026f6558bcd1c584ec774cc751e57
[ "MIT" ]
null
null
null
#ifndef INCLUDED_SROOK_CONFIG_PRAGMA_PUSH_WVARIADIC_MACROS_HPP #define INCLUDED_SROOK_CONFIG_PRAGMA_PUSH_WVARIADIC_MACROS_HPP #ifdef __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wvariadic-macros" #elif defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wvariadic-macros" #endif #endif
27.461538
62
0.826331
falgon
2d2deae69a783d4d2876eaaada6bcafba490e52d
6,002
cc
C++
paddle/fluid/operators/batch_fc_op.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/operators/batch_fc_op.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
paddle/fluid/operators/batch_fc_op.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/batch_fc_op.h" #include <string> namespace paddle { namespace operators { class BatchFCOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("Input"), true, platform::errors::InvalidArgument( "X(Input) of Batch Fully Connected should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("Out"), true, platform::errors::InvalidArgument( "Out(Output) of Batch Fully Connected should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("W"), true, platform::errors::InvalidArgument( "W(Input) of Batch Fully Connected should not be null.")); auto input_dims = ctx->GetInputDim("Input"); auto w_dims = ctx->GetInputDim("W"); PADDLE_ENFORCE_EQ(input_dims.size(), 3, platform::errors::InvalidArgument( "Input of BatchFCOp should have 3D.")); PADDLE_ENFORCE_EQ( w_dims.size(), 3, platform::errors::InvalidArgument("W of BatchFCOp should have 3D.")); PADDLE_ENFORCE_EQ( input_dims[0], w_dims[0], platform::errors::InvalidArgument( "Input.dim[0] and W.dim[0] of BatchFCOp should be same.")); PADDLE_ENFORCE_EQ( input_dims[2], w_dims[1], platform::errors::InvalidArgument( "Input.dim[2] and W.dim[1] of BatchFCOp should be same.")); auto bias_dims = ctx->GetInputDim("Bias"); PADDLE_ENFORCE_EQ(bias_dims[0], input_dims[0], platform::errors::InvalidArgument( "Bias.dim[0] should be same as input.dim[0].")); PADDLE_ENFORCE_EQ(bias_dims[1], w_dims[2], platform::errors::InvalidArgument( "Bias.dim[1] should be same as input.dim[2].")); ctx->SetOutputDim("Out", {input_dims[0], input_dims[1], w_dims[2]}); ctx->ShareLoD("Input", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.device_context()); } }; class BatchFCGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("Input"), true, platform::errors::InvalidArgument("Input should not be null")); PADDLE_ENFORCE_EQ( ctx->HasInput("W"), true, platform::errors::InvalidArgument("Input(W) should not be null")); ctx->SetOutputDim(framework::GradVarName("Input"), ctx->GetInputDim("Input")); ctx->SetOutputDim(framework::GradVarName("W"), ctx->GetInputDim("W")); ctx->SetOutputDim(framework::GradVarName("Bias"), ctx->GetInputDim("Bias")); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("Out")), ctx.device_context()); } }; class BatchFCOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Input", "(Tensor) Input tensor of batch_fc_op operator."); AddInput("W", "(Tensor) Input tensor of batch_fc_op operator."); AddInput("Bias", "(Tensor) Input tensor of batch_fc_op operator."); AddOutput("Out", "Output tensor of batch_fc_op operator."); AddComment(R"DOC( BatchFC Operator. Notice: It currently supports GPU device. This Op exists in contrib, which means that it is not shown to the public. )DOC"); } }; template <typename T> class BatchFCGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("batch_fc_grad"); op->SetInput("Input", this->Input("Input")); op->SetInput("W", this->Input("W")); op->SetInput("Bias", this->Input("Bias")); op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); op->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input")); op->SetOutput(framework::GradVarName("W"), this->InputGrad("W")); op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias")); op->SetAttrMap(this->Attrs()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERER(BatchFCGradOpNoNeedBufferVarsInferer, "Bias"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(batch_fc, ops::BatchFCOp, ops::BatchFCOpMaker, ops::BatchFCGradOpMaker<paddle::framework::OpDesc>, ops::BatchFCGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(batch_fc_grad, ops::BatchFCGradOp, ops::BatchFCGradOpNoNeedBufferVarsInferer); REGISTER_OP_CPU_KERNEL( batch_fc, ops::BatchFCKernel<paddle::platform::CPUDeviceContext, float>, ops::BatchFCKernel<paddle::platform::CPUDeviceContext, double>);
37.987342
80
0.670776
L-Net-1992
2d2f774b81f3dc61938649d8e53c4b5b0ea13480
6,246
cpp
C++
Source/ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.cpp
fjpavm/ChilliSource
11c38bada3fff8f4701dee5ad7718c8bc150c3b6
[ "MIT" ]
null
null
null
Source/ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.cpp
fjpavm/ChilliSource
11c38bada3fff8f4701dee5ad7718c8bc150c3b6
[ "MIT" ]
null
null
null
Source/ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.cpp
fjpavm/ChilliSource
11c38bada3fff8f4701dee5ad7718c8bc150c3b6
[ "MIT" ]
null
null
null
// // Cone2DParticleEmitter.cpp // Chilli Source // Created by Ian Copland on 03/12/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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 <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitter.h> #include <ChilliSource/Core/Math/Random.h> #include <ChilliSource/Rendering/Particle/ParticleEffect.h> #include <ChilliSource/Rendering/Particle/Emitter/Cone2DParticleEmitterDef.h> #include <cmath> namespace ChilliSource { namespace Rendering { namespace { //---------------------------------------------------------------- /// Generates a 2D direction within the given angle range with even /// distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithinAngle(f32 in_angle) { f32 angle = Core::MathUtils::k_pi * 0.5f + Core::Random::GenerateNormalised<f32>() * in_angle - 0.5f * in_angle; Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a direction with the given angle with even /// distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GenerateDirectionWithAngle(f32 in_angle) { f32 angle = 0.0f; if (Core::Random::Generate<u32>(0, 1) == 0) { angle = Core::MathUtils::k_pi * 0.5f - 0.5f * in_angle; } else { angle = Core::MathUtils::k_pi * 0.5f + 0.5f * in_angle; } Core::Vector2 direction(std::cos(angle), std::sin(angle)); return direction; } //---------------------------------------------------------------- /// Generates a position in a unit 2D cone with the given angle, with /// even distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The position. //---------------------------------------------------------------- Core::Vector2 GeneratePositionInUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithinAngle(in_angle) * dist; } //---------------------------------------------------------------- /// Generates a position on a the surface of a unit 2D cone with the /// given angle, with even distribution. /// /// @author Ian Copland /// /// @param The angle. /// /// @return The direction. //---------------------------------------------------------------- Core::Vector2 GeneratePositionOnUnitCone2D(f32 in_angle) { f32 dist = std::sqrt(Core::Random::GenerateNormalised<f32>()); return GenerateDirectionWithAngle(in_angle) * dist; } } //---------------------------------------------------------------- //---------------------------------------------------------------- Cone2DParticleEmitter::Cone2DParticleEmitter(const ParticleEmitterDef* in_particleEmitter, Core::dynamic_array<Particle>* in_particleArray) : ParticleEmitter(in_particleEmitter, in_particleArray) { //Only the sphere emitter def can create this, so this is safe. m_coneParticleEmitterDef = static_cast<const Cone2DParticleEmitterDef*>(in_particleEmitter); } //---------------------------------------------------------------- //---------------------------------------------------------------- void Cone2DParticleEmitter::GenerateEmission(f32 in_normalisedEmissionTime, Core::Vector3& out_position, Core::Vector3& out_direction) { f32 radius = m_coneParticleEmitterDef->GetRadiusProperty()->GenerateValue(in_normalisedEmissionTime); f32 angle = m_coneParticleEmitterDef->GetAngleProperty()->GenerateValue(in_normalisedEmissionTime); //calculate the position. switch (m_coneParticleEmitterDef->GetEmitFromType()) { case Cone2DParticleEmitterDef::EmitFromType::k_inside: out_position = Core::Vector3(GeneratePositionInUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_edge: out_position = Core::Vector3(GeneratePositionOnUnitCone2D(angle) * radius, 0.0f); break; case Cone2DParticleEmitterDef::EmitFromType::k_base: out_position = Core::Vector3::k_zero; break; default: CS_LOG_FATAL("Invalid 'Emit From' type."); break; } //calculate the direction. switch (m_coneParticleEmitterDef->GetEmitDirectionType()) { case Cone2DParticleEmitterDef::EmitDirectionType::k_random: out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); break; case Cone2DParticleEmitterDef::EmitDirectionType::k_awayFromBase: if (out_position != Core::Vector3::k_zero) { out_direction = Core::Vector3(Core::Vector2::Normalise(out_position.XY()), 0.0f); } else { out_direction = Core::Vector3(GenerateDirectionWithinAngle(angle), 0.0f); } break; default: CS_LOG_FATAL("Invalid 'Emit Direction' type."); break; } } } }
36.95858
141
0.612552
fjpavm
2d2fcf75265b7dd8ae80f7c1aa8c2d470c62703f
1,564
cc
C++
chrome/browser/ui/ash/stub_user_accounts_delegate.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
chrome/browser/ui/ash/stub_user_accounts_delegate.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
chrome/browser/ui/ash/stub_user_accounts_delegate.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T06:34:36.000Z
2020-11-04T06:34:36.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/stub_user_accounts_delegate.h" #include <cctype> #include "base/logging.h" StubUserAccountsDelegate::StubUserAccountsDelegate(const std::string& owner_id) : primary_account_(owner_id) {} StubUserAccountsDelegate::~StubUserAccountsDelegate() {} std::string StubUserAccountsDelegate::GetPrimaryAccountId() { return primary_account_; } std::vector<std::string> StubUserAccountsDelegate::GetSecondaryAccountIds() { return secondary_accounts_; } std::string StubUserAccountsDelegate::GetAccountDisplayName( const std::string& account_id) { std::string res(1, std::toupper(account_id[0])); res += account_id.substr(1); return res; } void StubUserAccountsDelegate::DeleteAccount(const std::string& account_id) { secondary_accounts_.erase( std::remove( secondary_accounts_.begin(), secondary_accounts_.end(), account_id), secondary_accounts_.end()); NotifyAccountListChanged(); } void StubUserAccountsDelegate::AddAccount(const std::string& account_id) { if (primary_account_ == account_id) return; if (std::find(secondary_accounts_.begin(), secondary_accounts_.end(), account_id) != secondary_accounts_.end()) return; secondary_accounts_.push_back(account_id); NotifyAccountListChanged(); } void StubUserAccountsDelegate::LaunchAddAccountDialog() { NOTIMPLEMENTED(); }
29.509434
79
0.748721
Fusion-Rom
2d303bab77750a62a03e74edfd4860b26dc3417a
1,739
cpp
C++
dbms/src/Storages/ColumnDefault.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Storages/ColumnDefault.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Storages/ColumnDefault.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Parsers/queryToString.h> #include <Storages/ColumnDefault.h> namespace DB { ColumnDefaultKind columnDefaultKindFromString(const std::string & str) { static const std::unordered_map<std::string, ColumnDefaultKind> map{ { "DEFAULT", ColumnDefaultKind::Default }, { "MATERIALIZED", ColumnDefaultKind::Materialized }, { "ALIAS", ColumnDefaultKind::Alias } }; const auto it = map.find(str); return it != std::end(map) ? it->second : throw Exception{"Unknown column default specifier: " + str}; } std::string toString(const ColumnDefaultKind kind) { static const std::unordered_map<ColumnDefaultKind, std::string> map{ { ColumnDefaultKind::Default, "DEFAULT" }, { ColumnDefaultKind::Materialized, "MATERIALIZED" }, { ColumnDefaultKind::Alias, "ALIAS" } }; const auto it = map.find(kind); return it != std::end(map) ? it->second : throw Exception{"Invalid ColumnDefaultKind"}; } bool operator==(const ColumnDefault & lhs, const ColumnDefault & rhs) { return lhs.kind == rhs.kind && queryToString(lhs.expression) == queryToString(rhs.expression); } }
31.618182
106
0.703853
solotzg
2d30b3d309054efc52f95ba15b4c8f01d5f6c495
8,498
cpp
C++
trikScriptRunner/src/pythonEngineWorker.cpp
DCNick3/trikRuntime
25b14816d3d49c67f0e71a78f278065eca188a69
[ "Apache-2.0" ]
null
null
null
trikScriptRunner/src/pythonEngineWorker.cpp
DCNick3/trikRuntime
25b14816d3d49c67f0e71a78f278065eca188a69
[ "Apache-2.0" ]
null
null
null
trikScriptRunner/src/pythonEngineWorker.cpp
DCNick3/trikRuntime
25b14816d3d49c67f0e71a78f278065eca188a69
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Iakov Kirilenko, CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QProcess> #include <QsLog.h> #include <QVector> #include <trikNetwork/mailboxInterface.h> #include <trikKernel/paths.h> #include <trikKernel/exceptions/internalErrorException.h> #include <trikScriptRunnerInterface.h> #include "pythonEngineWorker.h" #include <Python.h> #include "PythonQtConversion.h" using namespace trikScriptRunner; QAtomicInt PythonEngineWorker::initCounter = 0; static int quitFromPython(void*) { PyErr_SetInterrupt(); return 0; } static void abortPythonInterpreter() { if(!Py_IsInitialized()) { return; } PythonQtGILScope _; Py_AddPendingCall(&quitFromPython, nullptr); } PythonEngineWorker::PythonEngineWorker(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox ) : mBrick(brick) , mScriptExecutionControl(new ScriptExecutionControl(brick)) , mMailbox(mailbox) , mWorkingDirectory(trikKernel::Paths::userScriptsPath()) {} PythonEngineWorker::~PythonEngineWorker() { stopScript(); { // In python at least before 3.7 (3.5,3.6) // we need to make all pending calls before the context // is destroyed, otherwise python crashes PythonQtGILScope _; Py_MakePendingCalls(); mMainContext = nullptr; if (mPyInterpreter) { Py_EndInterpreter(mPyInterpreter); mPyInterpreter = nullptr; } } if (--initCounter == 0) { Py_Finalize(); PyMem_RawFree(mProgramName); PyMem_RawFree(mPythonPath); if (PythonQt::self()) { PythonQt::cleanup(); } } } void PythonEngineWorker::init() { if (initCounter++ == 0) { mProgramName = Py_DecodeLocale("trikPythonRuntime", nullptr); Py_SetProgramName(mProgramName); constexpr auto varName = "TRIK_PYTHONPATH"; auto const &path = QProcessEnvironment::systemEnvironment().value(varName); if (path.isEmpty()) { auto const &e = QString("%1 must be set to correct value").arg(varName); QLOG_FATAL() << e; throw trikKernel::InternalErrorException(e); } else { QLOG_INFO() << varName << ":" << path; } /// TODO: Must point to local .zip file mPythonPath = Py_DecodeLocale(path.toStdString().data(), nullptr); Py_SetPath(mPythonPath); /* uncomment for verbosity Py_VerboseFlag = 3; Py_InspectFlag = 1; Py_DebugFlag = 2; // */ Py_IsolatedFlag = 1; Py_BytesWarningFlag = 3; Py_DontWriteBytecodeFlag = 1; Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_Initialize(); PyEval_InitThreads(); // For Python < 3.7 } if (!mPyInterpreter) { // mPyInterpreter = Py_NewInterpreter(); } if (!PythonQt::self()) { PythonQt::setEnableThreadSupport(true); PythonQtGILScope _; PythonQt::init(PythonQt::RedirectStdOut | PythonQt::PythonAlreadyInitialized); connect(PythonQt::self(), &PythonQt::pythonStdErr, this, &PythonEngineWorker::updateErrorMessage); connect(PythonQt::self(), &PythonQt::pythonStdOut, this, [this](const QString& str){ QTimer::singleShot(0, this, [this, str](){ Q_EMIT this->textInStdOut(str);}); mScriptExecutionControl->wait(0); }); PythonQtRegisterListTemplateConverter(QVector, uint8_t) PythonQt_QtAll::init(); } if (!mMainContext) { mMainContext = PythonQt::self()->getMainModule(); recreateContext(); } emit inited(); } bool PythonEngineWorker::recreateContext() { { PythonQtGILScope _; Py_MakePendingCalls(); PyErr_CheckSignals(); PyErr_Clear(); } PythonQt::self()->clearError(); return initTrik(); } bool PythonEngineWorker::evalSystemPy() { const QString systemPyPath = trikKernel::Paths::systemScriptsPath() + "system.py"; if (!QFileInfo::exists(systemPyPath)) { QLOG_ERROR() << "system.py not found, path:" << systemPyPath; return false; } // HACK: to avoid duplicate system.py try to check if basic feature like script.wait works. mMainContext.evalScript("script.wait(0)"); if (PythonQt::self()->hadError()) { // HACK: no script.wait means usually a problem with system.py, let's try to include it PythonQt::self()->clearError(); mMainContext.evalFile(systemPyPath); if (PythonQt::self()->hadError()) { QLOG_ERROR() << "Failed to eval system.py"; return false; } } return true; } void PythonEngineWorker::addSearchModuleDirectory(const QDir &path) { if (path.path().indexOf("'") != -1) return; mMainContext.evalScript("import sys; (lambda x: sys.path.append(x) if not x in sys.path else None)('" + path.path() + "')"); } bool PythonEngineWorker::initTrik() { PythonQt_init_PyTrikControl(mMainContext); mMainContext.addObject("brick", &mBrick); mMainContext.addObject("script_cpp", mScriptExecutionControl.data()); mMainContext.addObject("mailbox", mMailbox); return evalSystemPy(); } void PythonEngineWorker::resetBrick() { QLOG_INFO() << "Stopping robot"; if (mMailbox) { mMailbox->stopWaiting(); mMailbox->clearQueue(); } mBrick.reset(); } void PythonEngineWorker::brickBeep() { mBrick.playSound(trikKernel::Paths::mediaPath() + "media/beep_soft.wav"); } void PythonEngineWorker::stopScript() { QMutexLocker locker(&mScriptStateMutex); if (mState == stopping) { // Already stopping, so we can do nothing. return; } if (mState == ready) { // Engine is ready for execution. return; } QLOG_INFO() << "PythonEngineWorker: stopping script"; mState = stopping; if (QThread::currentThread() != thread()) { abortPythonInterpreter(); } else { QLOG_FATAL() << "Attempt to abort Python from main thread."; } if (mMailbox) { mMailbox->stopWaiting(); } mState = ready; /// @todo: is it actually stopped? QLOG_INFO() << "PythonEngineWorker: stopping complete"; } QStringList PythonEngineWorker::knownNames() const { QSet<QString> result = {"brick", "script", "threading"}; TrikScriptRunnerInterface::Helper::collectMethodNames(result, &trikControl::BrickInterface::staticMetaObject); /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mScriptControl.metaObject()); if (mMailbox) { result.insert("mailbox"); TrikScriptRunnerInterface::Helper::collectMethodNames(result, mMailbox->metaObject()); } /// TODO: TrikScriptRunnerInterface::Helper::collectMethodNames(result, mThreading.metaObject()); return result.toList(); } void PythonEngineWorker::setWorkingDirectory(const QDir &workingDir) { mWorkingDirectory = workingDir; } void PythonEngineWorker::run(const QString &script, const QFileInfo &scriptFile) { QMutexLocker locker(&mScriptStateMutex); mState = starting; QMetaObject::invokeMethod(this, [this, script, scriptFile](){this->doRun(script, scriptFile);}); } void PythonEngineWorker::doRun(const QString &script, const QFileInfo &scriptFile) { emit startedScript("", 0); mErrorMessage.clear(); /// When starting script execution (by any means), clear button states. mBrick.keys()->reset(); mState = running; auto ok = recreateContext(); if (!ok) { emit completed(mErrorMessage,0); return; } addSearchModuleDirectory(mWorkingDirectory.canonicalPath()); if (scriptFile.isFile()) { addSearchModuleDirectory(scriptFile.canonicalPath()); } mMainContext.evalScript(script); QLOG_INFO() << "PythonEngineWorker: evaluation ended"; auto wasError = mState != ready && PythonQt::self()->hadError(); mState = ready; if (wasError) { emit completed(mErrorMessage, 0); } else { emit completed("", 0); } } void PythonEngineWorker::runDirect(const QString &command) { QMutexLocker locker(&mScriptStateMutex); QMetaObject::invokeMethod(this, "doRunDirect", Q_ARG(QString, command)); } void PythonEngineWorker::doRunDirect(const QString &command) { emit startedDirectScript(0); if (PythonQt::self()->hadError()) { PythonQt::self()->clearError(); mErrorMessage.clear(); recreateContext(); } mMainContext.evalScript(command); emit completed(mErrorMessage, 0); } void PythonEngineWorker::updateErrorMessage(const QString &err) { mErrorMessage += err; } void PythonEngineWorker::onScriptRequestingToQuit() { throw std::logic_error("Not implemented"); }
25.829787
111
0.725465
DCNick3
2d331816394adba21c6cc67f263984cd71d3eda2
4,202
hpp
C++
src/sparse/KokkosSparse_spgemm.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
src/sparse/KokkosSparse_spgemm.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
7
2020-05-04T16:43:08.000Z
2022-01-13T16:31:17.000Z
src/sparse/KokkosSparse_spgemm.hpp
NexGenAnalytics/kokkos-kernels
8381db0486674c1be943de23974821ddfb9e6c29
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef _KOKKOS_SPGEMM_HPP #define _KOKKOS_SPGEMM_HPP #include "KokkosSparse_spgemm_numeric.hpp" #include "KokkosSparse_spgemm_symbolic.hpp" #include "KokkosSparse_spgemm_jacobi.hpp" namespace KokkosSparse { template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix> void spgemm_symbolic(KernelHandle& kh, const AMatrix& A, const bool Amode, const BMatrix& B, const bool Bmode, CMatrix& C) { using row_map_type = typename CMatrix::row_map_type::non_const_type; using entries_type = typename CMatrix::index_type::non_const_type; using values_type = typename CMatrix::values_type::non_const_type; row_map_type row_mapC( Kokkos::view_alloc(Kokkos::WithoutInitializing, "non_const_lnow_row"), A.numRows() + 1); entries_type entriesC; values_type valuesC; KokkosSparse::Experimental::spgemm_symbolic( &kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map, A.graph.entries, Amode, B.graph.row_map, B.graph.entries, Bmode, row_mapC); const size_t c_nnz_size = kh.get_spgemm_handle()->get_c_nnz(); if (c_nnz_size) { entriesC = entries_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "entriesC"), c_nnz_size); valuesC = values_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "valuesC"), c_nnz_size); } C = CMatrix("C=AB", A.numRows(), B.numCols(), c_nnz_size, valuesC, row_mapC, entriesC); } template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix> void spgemm_numeric(KernelHandle& kh, const AMatrix& A, const bool Amode, const BMatrix& B, const bool Bmode, CMatrix& C) { // using row_map_type = typename CMatrix::index_type::non_const_type; // using entries_type = typename CMatrix::row_map_type::non_const_type; // using values_type = typename CMatrix::values_type::non_const_type; KokkosSparse::Experimental::spgemm_numeric( &kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map, A.graph.entries, A.values, Amode, B.graph.row_map, B.graph.entries, B.values, Bmode, C.graph.row_map, C.graph.entries, C.values); kh.destroy_spgemm_handle(); } } // namespace KokkosSparse #endif
42.444444
89
0.700857
NexGenAnalytics
2d3627a8ecae455148a72785237d69dac685b9f4
3,834
cpp
C++
cryptarithmetic-puzzles/main.cpp
enesdemirag/graph-algorithms
7eec0833feaa3b60e2aad098f49f0483435cc841
[ "MIT" ]
2
2021-04-23T23:07:13.000Z
2021-11-08T11:54:18.000Z
cryptarithmetic-puzzles/main.cpp
enesdemirag/graph-algorithms
7eec0833feaa3b60e2aad098f49f0483435cc841
[ "MIT" ]
null
null
null
cryptarithmetic-puzzles/main.cpp
enesdemirag/graph-algorithms
7eec0833feaa3b60e2aad098f49f0483435cc841
[ "MIT" ]
null
null
null
/* @Author Student Name: Enes Demirag Student ID : 504201571 Mail : ensdmrg@gmail.com Date : 06.04.2021 Dear sir/madam, This projects consist of a Node class, two graph traverse algorithms (BFS and DFS) and other utility functions. In order to compile and run this project, first you need to link files under include/ directory. Below commands can be used to build and run this project with g++. >> g++ -std=c++11 -Iinclude -c src/* >> g++ -std=c++11 -Iinclude -g *.o -o executable main.cpp >> ./executable DFS TWO TWO FOUR solution.txt All of the standard libraries used in this project is given below. <list> : To implement a FIFO type Queue structure. <stack> : To implement a LIFO type Stack structure. <string> : String operations. <vector> : Storing some elements and accessing them. <iostream> : To print things to the terminal. <algorithm> : To find element positions inside lists and vectors. <cmath> : Numaric operations like power and max. <chrono> : To calculate running time. If you encounter any problem regarding this projects, feel free to reach me. Thanks and kind regards, Enes */ #include "Node.hpp" #include "Utils.hpp" #include "Search.hpp" /* This is the main function. * It takes arguments from program call and using those, * First creates a tree. * Then search a valid solution in that tree using specified algorithm. */ int main(int argc, char** argv) { // Checking if there is an unexpected input argument // And if there is, stop the program. if (!checkArguments(argv)) { return -1; } // Create the root note (with no parent, ' ' key and -1 value. Node root(' ', -1); // Parse input arguments into variables. std::string str1 = argv[2]; std::string str2 = argv[3]; std::string sum = argv[4]; // Find first letters of each word from inputs std::list<char> first_chars{ str1[0], str2[0], sum[0] }; first_chars.sort(); first_chars.unique(); // Find unique character list from inputs std::list<char> unique_keys; for (char c : str1 + str2 + sum) { // If c is not in unique_keys list, add c into the list. if (std::find(unique_keys.begin(), unique_keys.end(), c) == unique_keys.end()) { unique_keys.push_back(c); } } // Recursively create the tree from root node. addNewLayer(&root, unique_keys, first_chars); // Define output variables int number_of_visited_nodes, max_nodes_in_memory; double running_time; std::list<int> solution; // BFS algorithm if (std::string("BFS") == argv[1]) { solution = BFS(&root, unique_keys, str1, str2, sum, number_of_visited_nodes, max_nodes_in_memory, running_time); // If there is a solution. if (!solution.empty()) { // Print results and write matrix to file. printResults("BFS", unique_keys, solution, number_of_visited_nodes, max_nodes_in_memory, running_time); printMatrix(argv[5], unique_keys, solution); } // If no solution was found. else { std::cout << "No solution found." << std::endl; } } // DFS algorithm else { solution = DFS(&root, unique_keys, str1, str2, sum, number_of_visited_nodes, max_nodes_in_memory, running_time); // If there is a solution. if (!solution.empty()) { // Print results and write matrix to file. printResults("DFS", unique_keys, solution, number_of_visited_nodes, max_nodes_in_memory, running_time); printMatrix(argv[5], unique_keys, solution); } // If no solution was found. else { std::cout << "No solution found." << std::endl; } } return 0; }
30.919355
120
0.638498
enesdemirag
2d3777ba79e78170975462232ac50090c9850def
820
cpp
C++
src/Actions/Action_Help.cpp
PoetaKodu/cpp-pkg
3d5cabf4e015f4727328db430a003c189aeed88a
[ "MIT" ]
9
2021-05-07T21:18:26.000Z
2022-02-01T20:44:13.000Z
src/Actions/Action_Help.cpp
PoetaKodu/pacc
3d5cabf4e015f4727328db430a003c189aeed88a
[ "MIT" ]
null
null
null
src/Actions/Action_Help.cpp
PoetaKodu/pacc
3d5cabf4e015f4727328db430a003c189aeed88a
[ "MIT" ]
null
null
null
#include PACC_PCH #include <Pacc/App/App.hpp> #include <Pacc/App/Help.hpp> #include <Pacc/Helpers/Formatting.hpp> /////////////////////////////////////////////////// void PaccApp::displayHelp(bool abbrev_) { auto programName = fs::u8path(args[0]).stem(); auto const& style = fmt_args::s(); // Introduction: fmt::print( "pacc v{} - a C++ package manager.\n\n" "{USAGE}: {} [action] <params>\n\n", PaccApp::PaccVersion, programName.string(), FMT_INLINE_ARG("USAGE", style.Yellow, "USAGE") ); // if (abbrev_) { fmt::print("Use \"{} help\" for more information\n", programName.string()); } else { // Display actions std::cout << "ACTIONS\n"; for (auto action : help::actions) { fmt::print("\t{:16}{}\n", action.first, action.second); } std::cout << std::endl; } }
20.5
77
0.576829
PoetaKodu
2d379748b834826a6358363cff27d9df11d693af
15,303
cpp
C++
Splendor/Splendor/UIGameSession.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
Splendor/Splendor/UIGameSession.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
Splendor/Splendor/UIGameSession.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
#include "UIGameSession.h" #include "UISelectedCard.h" #include "SoundSystem.h" #include <iostream> UIGameSession::UIGameSession(const sf::Vector2u& windowSize, const PregameSetup& pregameSetup, std::vector<Player>* pPlayers, Board* pBoard, std::reference_wrapper<Player>& rActivePlayer) : // instantiate Logic p_board(pBoard), r_activePlayer(rActivePlayer), // instantiate UI panels m_infoPanel(sf::Vector2f(0, 0), sf::Vector2f(windowSize.x, windowSize.y * 0.05)), m_playersPanel(pPlayers, sf::Vector2f(0, windowSize.y * 0.05), sf::Vector2f(windowSize.x * 0.3, windowSize.y * 0.95)), m_tokensPanel(sf::Vector2f(windowSize.x * 0.3, windowSize.y * 0.05), sf::Vector2f(0.1 * windowSize.x, windowSize.y * 0.95)), m_noblesPanel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.05), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.26)), m_expansionsL3Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.31), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_expansionsL2Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.54), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_expansionsL1Panel(5, sf::Vector2f(windowSize.x * 0.4, windowSize.y * 0.77), sf::Vector2f(windowSize.x * 0.6, windowSize.y * 0.23)), m_handPanel(static_cast<sf::Vector2f>(windowSize), false), m_tokenAlertPanel(static_cast<sf::Vector2f>(windowSize), false), p_exceedingHand(nullptr), // instantiate Pregame Set-up m_pregameSetup(pregameSetup) { // Instantiate UI Card Rows m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble), 0, true); m_noblesPanel.ReverseDrawOrder(); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL3Panel.ReverseDrawOrder(); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL2Panel.ReverseDrawOrder(); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); m_expansionsL1Panel.ReverseDrawOrder(); m_expansionPanels.emplace_back(std::ref(m_expansionsL3Panel)); m_expansionPanels.emplace_back(std::ref(m_expansionsL2Panel)); m_expansionPanels.emplace_back(std::ref(m_expansionsL1Panel)); // Populate panel vector m_panels.push_back(dynamic_cast<UIPanel*>(&m_infoPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_playersPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_tokensPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL1Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL2Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_expansionsL3Panel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_noblesPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_tokenAlertPanel)); m_panels.push_back(dynamic_cast<UIPanel*>(&m_handPanel)); } void UIGameSession::StartGame() { m_infoPanel.StartTimer(); } void UIGameSession::StopGame() { m_infoPanel.StopTimer(); } void UIGameSession::UpdateGame() { // Info m_infoPanel.UpdateTime(); // Tokens Panel m_tokensPanel.UpdateTokens(p_board->GetTokensData()); if (m_tokensPanel.GetLastPicked().has_value()) { auto& token = m_tokensPanel.GetLastPicked(); r_activePlayer.get().GetHand().AddToken(token.value()); p_board->TakeToken(token.value()); token.reset(); } if (m_tokensPanel.GetHasPicked()) { m_tokensPanel.SetHasPicked(false); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); } // Card Panels std::optional<std::pair<UICard*, UICard::State>> pickedCard; for (auto& expansionPanel : m_expansionPanels) { if (pickedCard.has_value()) continue; pickedCard = expansionPanel.get().CheckForPickedCard(); } if (pickedCard.has_value()) { switch (pickedCard.value().second) { case UICard::State::LeftRelease:/// Buy Card std::cout << "Picked card LEFT CLICK\n"; // Background if (pickedCard->first->GetType() == UICard::Type::Background) break; // Expansion Card try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedCard.value().first->GetType())), pickedCard.value().first->GetID()); // Save picked card data const auto prestigePoints = pickedCardLogicPiece.GetPrestigePoints(); const auto level = pickedCardLogicPiece.GetLevel(); const auto id = pickedCardLogicPiece.GetId(); // Return & sync tokens p_board->ReturnTokens(r_activePlayer.get().GetHand().BuyExpansionCard(std::move(pickedCardLogicPiece))); m_tokensPanel.SyncTokens(p_board->GetTokensData()); // Replace card in board p_board->ReplaceExpansion(level, id); // Add card's prestige points r_activePlayer.get().AddPrestigePoints(prestigePoints); m_playersPanel.AddPrestigePointsToCurrentPlayer(prestigePoints); // Deactivate UI pickedCard->first->Deactivate(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::BuyCardSFX); } catch (std::length_error & exception) { // Not enough resources std::cout << exception.what() << "\n"; pickedCard->first->TriggerWarning(); } catch (std::exception & exception) { // Other possible exception std::cout << exception.what() << "\n"; } break; case UICard::State::RightRelease:/// Hold Card std::cout << "Picked card RIGHT CLICK\n"; // Background if (pickedCard->first->GetType() == UICard::Type::Background) { // Hand is full if (r_activePlayer.get().GetHand().IsFull()) { pickedCard->first->TriggerWarning(); break; } // Transfer expansion card from board to active player hand try { r_activePlayer.get().GetHand().AddExpansionCard(p_board->DrawExpansionFromDeck(pickedCard->first->GetID())); } catch (std::out_of_range & exception) { // Empty Deck std::cout << exception.what() << "\n"; pickedCard.value().first->TriggerWarning(); break; } // Pick a gold token try { p_board->TakeToken(IToken::Type::Gold); r_activePlayer.get().GetHand().AddToken(IToken::Type::Gold); m_tokensPanel.TakeGoldToken(); } catch (std::out_of_range & exception) { // Not enough gold tokens on board } // Deactivate UI pickedCard->first->OnMouseLeave(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::HoldCardSFX); break; } // Expansion Card try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedCard.value().first->GetType())), pickedCard.value().first->GetID()); // Save picked card data const auto level = pickedCardLogicPiece.GetLevel(); const auto id = pickedCardLogicPiece.GetId(); // Transfer card to hand r_activePlayer.get().GetHand().AddExpansionCard(std::move(pickedCardLogicPiece)); // Replace card in board p_board->ReplaceExpansion(level, id); // Pick a gold token try { p_board->TakeToken(IToken::Type::Gold); r_activePlayer.get().GetHand().AddToken(IToken::Type::Gold); m_tokensPanel.TakeGoldToken(); } catch (std::out_of_range & exception) { // Not enough gold tokens on board } // Deactivate UI pickedCard->first->Deactivate(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::HoldCardSFX); } catch (std::out_of_range & exception) { // Hand Full std::cout << exception.what() << "\n"; pickedCard->first->TriggerWarning(); } break; default: break; } std::cout << "\n"; } // Player Hand Panel const auto triggeredPanel = m_playersPanel.GetIfTriggered(); if (triggeredPanel != nullptr) { std::for_each(m_panels.begin(), m_panels.end(), [](UIPanel* panel) {panel->SetInteractable(false); }); m_handPanel.SetUpHand(*triggeredPanel); m_handPanel.SetActive(true); if (triggeredPanel->GetPlayer()->GetId() == r_activePlayer.get().GetId()) m_handPanel.SetInteractable(true); } if (m_handPanel.CheckForClose())// closed { std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(true); }); } else if (m_handPanel.IsActive())// opened { if (!m_tokensPanel.IsNumb())// allowed to buy { auto pickedExpansion = m_handPanel.GetPickedExpansion(); if (pickedExpansion.has_value()) { // Buy ExpansionCard from hand try { // Create logic ExpansionCard for pickedCard ExpansionCard pickedCardLogicPiece(static_cast<ExpansionCard::Level>(static_cast<uint16_t>(pickedExpansion.value()->GetType())), pickedExpansion.value()->GetID()); // Save picked card data const auto prestigePoints = pickedCardLogicPiece.GetPrestigePoints(); // Return & sync tokens p_board->ReturnTokens(r_activePlayer.get().GetHand().BuyExpansionCard(std::move(pickedCardLogicPiece))); m_tokensPanel.SyncTokens(p_board->GetTokensData()); // Add card's prestige points r_activePlayer.get().AddPrestigePoints(prestigePoints); m_playersPanel.AddPrestigePointsToCurrentPlayer(prestigePoints); // Sync Hand r_activePlayer.get().GetHand().RemoveExpansionCard(pickedExpansion.value()->GetID()); m_handPanel.SyncHand(); // Deactivate UI pickedExpansion.value()->Deactivate(); m_handPanel.NumbAllExpansions(); m_tokensPanel.NumbAll(); std::for_each(m_expansionPanels.begin(), m_expansionPanels.end(), [](std::reference_wrapper<UICardsRowPanel>& panel) {panel.get().NumbAll(); }); // Sound SFX SoundSystem::PlaySFX(SoundSystem::SoundType::BuyCardSFX); } catch (std::length_error & exception) { // Not enough resources std::cout << exception.what() << "\n"; pickedExpansion.value()->TriggerWarning(); } } } else// not allowed to buy { m_handPanel.NumbAllExpansions(); } } // Token Alert Panel if (m_tokensPanel.IsActive()) { m_tokenAlertPanel.Update(); if (m_tokenAlertPanel.GetConfirmed()) { // Transfer tokens p_board->ReturnTokens(m_tokenAlertPanel.GetTokensToReturn()); p_exceedingHand->RemoveTokens(m_tokenAlertPanel.GetTokensToReturn()); p_exceedingHand = nullptr; m_tokensPanel.SyncTokens(p_board->GetTokensData()); // UI std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(true); }); m_tokenAlertPanel.SetConfirmed(false); m_tokenAlertPanel.SetActive(false); m_tokenAlertPanel.SetInteractable(false); } } } void UIGameSession::NextTurn() { // Validate Active Player Changes ValidateActivePlayerChanges(); CheckForExceedingTokens(); // UI Logic m_infoPanel.IncrementTurn(); PointToNextPlayer(); PrepareUI(); } void UIGameSession::NextTurnOnline() { // Validate Active Player Changes ValidateActivePlayerChanges(); CheckForExceedingTokens(); // UI Logic m_infoPanel.IncrementTurn(); PrepareUI(); } void UIGameSession::PointToNextPlayer() { m_playersPanel.PointToNextPlayer(); } void UIGameSession::CheckForExceedingTokens() { // Check if active player token stock exceeds token limit if (r_activePlayer.get().GetHand().ExceedsTokenLimit()) { std::for_each(m_panels.begin(), m_panels.end() - 1, [](UIPanel* panel) {panel->SetInteractable(false); }); m_tokenAlertPanel.SetActive(true); m_tokenAlertPanel.SetInteractable(true); p_exceedingHand = &r_activePlayer.get().GetHand(); m_tokenAlertPanel.SetInitialTokens(p_exceedingHand->GetTokensData()); } } void UIGameSession::SetActivePlayer(std::reference_wrapper<Player> activePlayerReference) { r_activePlayer = activePlayerReference; } void UIGameSession::SyncBoard() { m_tokensPanel.SyncTokens(p_board->GetTokensData()); m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble)); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); } void UIGameSession::SyncOnlineAdversaryPlayerPanel(uint16_t adversaryPrestigePoints) { m_playersPanel.SyncAdversaryPlayerPrestigePoints(adversaryPrestigePoints); } void UIGameSession::PassEvent(const sf::Event& event) { // iterate panel vector and handle events std::for_each(m_panels.begin(), m_panels.end(), [&event](UIPanel* panel) { panel->HandleEvent(event); }); } UIGameSession::Events UIGameSession::GetEvent() const { // Info Panel if (m_infoPanel.MenuButtonTriggered()) return Events::MenuButton; if (m_infoPanel.PassButtonTriggered()) return Events::PassButton; return Events::None; } void UIGameSession::draw(sf::RenderTarget& target, sf::RenderStates states) const { // iterate panel vector and draw panels std::for_each(m_panels.begin(), m_panels.end(), [&target](UIPanel* panel) { target.draw(*panel); }); // re-draw selected card on top of all drawables if (UISelectedCard::Get().first != nullptr) { target.draw(*UISelectedCard::Get().first); } // draw selected card text if (UISelectedCard::Get().second != nullptr) { target.draw(*UISelectedCard::Get().second); } } void UIGameSession::ValidateActivePlayerChanges() { // Nobles const auto wonNoble = m_noblesPanel.CheckForWonNoble(r_activePlayer.get().GetHand().GetResourcesData()); if (wonNoble.has_value()) { auto&& nobleCard = p_board->WinNoble(wonNoble.value().id); m_noblesPanel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::Noble), 0, true); r_activePlayer.get().AddPrestigePoints(nobleCard.GetPrestigePoints()); m_playersPanel.AddPrestigePointsToCurrentPlayer(nobleCard.GetPrestigePoints()); r_activePlayer.get().GetHand().AddNobleCard(std::move(nobleCard)); SoundSystem::PlaySFX(SoundSystem::SoundType::WinNobleSFX); std::cout << "WON NOBLE\n"; } // Reset picked Tokens buffer auto& pickedTokens = m_tokensPanel.ExtractPickedTokens(); for (auto& token : pickedTokens) { if (token.has_value()) { token.reset(); } } } void UIGameSession::PrepareUI() { // Prepare UI for next turn m_tokensPanel.UnNumb(); m_expansionsL3Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL3), 3); m_expansionsL2Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL2), 2); m_expansionsL1Panel.SetCardsData(p_board->GetCardSlotsData(CardDAO::Type::ExpansionL1), 1); if (p_board->IsExpansionDeckEmpty(3)) { m_expansionsL3Panel.DisableDeckBackground(); } if (p_board->IsExpansionDeckEmpty(2)) { m_expansionsL2Panel.DisableDeckBackground(); } if (p_board->IsExpansionDeckEmpty(1)) { m_expansionsL1Panel.DisableDeckBackground(); } }
33.123377
189
0.723453
TFphoenix
2d38326ecddd1ff283a1a92c94cfe031469d6bc7
56
hh
C++
RAVL2/MSVC/include/Ravl/SourceTools/RCSFile.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/SourceTools/RCSFile.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/SourceTools/RCSFile.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././SourceTools/CodeManager/RCSFile.hh"
14
53
0.678571
isuhao
2d3a08f639ed2b9648dd61a154dd07fec0631e68
1,294
cpp
C++
Game!/main.cpp
leonore13/Game-
d984379f5e301700f973a692fc6b92e3ef852764
[ "Apache-2.0" ]
null
null
null
Game!/main.cpp
leonore13/Game-
d984379f5e301700f973a692fc6b92e3ef852764
[ "Apache-2.0" ]
null
null
null
Game!/main.cpp
leonore13/Game-
d984379f5e301700f973a692fc6b92e3ef852764
[ "Apache-2.0" ]
null
null
null
// // main.cpp // Game! // // Created by Sophia Nguyen on 2016-05-05. // Copyright © 2016 Sophia Nguyen. All rights reserved. // // The story! #include <iostream> #include <string> #include <cctype> #include <vector> #include "Character.hpp" using namespace std; int main() { string char_name; int age; string command; Character Char_1(char_name, age); cout << "Greetings. What is your name?" << "\n"; getline(cin, char_name); // get character's name cout << "How many years have you existed in this world?" << "\n"; cin >> age; // get character's age Char_1.setName(char_name); Char_1.setAge(age); cout << "\n\n" << "Hello, " << Char_1.getName() << ". A wise soul you are, your " << Char_1.getAge() << " years on this Earth will come in useful as you navigate through this adventure. To proceed, type in short commands as you think they might pretain to the environment and story you find yourself in. Have fun!" << "\n\n" << "You are in dark room, empty except for the wooden chair you sit on, a bare twin-sized bed in one corner, and a dim oil lamp sitting on a rickety night stand." << "\n\n"; while (command != "QUIT") { command.clear(); cin >> command; } return 0; }
28.130435
502
0.623648
leonore13
2d3c4a6ec4f2c2c3a8e7522af43e7e1c1601aeee
1,312
hpp
C++
game/include/Components/PieceComponent.hpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
game/include/Components/PieceComponent.hpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
game/include/Components/PieceComponent.hpp
Hvvang/Puzzle
0f798e3d1f4388b255a7a393b8671e4d1930cdb0
[ "MIT" ]
null
null
null
#pragma once #include <EntityManager.hpp> #include <Components/Sprite.hpp> #include <Components/TileComponent.hpp> #include <array> #include <memory> class TileComponent; using ::Engine::ECS::Entity; using ::Engine::ECS::Component; using ::Engine::ECS::Sprite; using ::Engine::Math::Vector2i; using ::Engine::Math::operator+=; using ::Engine::Math::operator+; struct PieceComponent : Component { enum class Shape : uint8_t { I = 73, O = 79, J = 74, L = 76, T = 84, Z = 90, S = 83 } shape; PieceComponent() { for (auto &tile : tiles) { tile = ::std::make_unique<Entity>(entityManager->createEntity()); tile->addComponent<TileComponent>(); } } void activate() { for (auto &tile : tiles) { tile->activate(); tile->getComponent<TileComponent>().instance->activate(); } } void deactivate() { for (auto &tile : tiles) { tile->deactivate(); tile->getComponent<TileComponent>().instance->deactivate(); } } private: ::std::array<::std::unique_ptr<Entity>, 4> tiles{ nullptr }; Color color {0.1, 0.1, 0.1}; friend class PieceController; friend class CollisionSystem; friend class GridController; friend class GameController; };
24.296296
77
0.603659
Hvvang
2d3e51c7d7d3345024272f6b973d84b86d115a67
6,126
cpp
C++
src/graphics/deferredrenderer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/graphics/deferredrenderer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
src/graphics/deferredrenderer.cpp
Eae02/tank-game
0c526b177ccc15dd49e3228489163f13335040db
[ "Zlib" ]
null
null
null
#include "deferredrenderer.h" #include "irenderer.h" #include "quadmesh.h" #include "gl/shadermodule.h" #include "../utils/ioutils.h" #include "../settings.h" namespace TankGame { constexpr GLenum DeferredRenderer::COLOR_FORMAT; constexpr GLenum DeferredRenderer::NORMALS_AND_SPECULAR_FORMAT; constexpr GLenum DeferredRenderer::DISTORTION_BUFFER_FORMAT; constexpr GLenum DeferredRenderer::LIGHT_ACC_FORMAT; static ShaderProgram LoadCompositionShader() { ShaderModule fragmentShader = ShaderModule::FromFile( GetResDirectory() / "shaders" / "lighting" / "composition.fs.glsl", GL_FRAGMENT_SHADER); return ShaderProgram({ &QuadMesh::GetVertexShader(), &fragmentShader }); } DeferredRenderer::DeferredRenderer() : m_compositionShader(LoadCompositionShader()) { } void DeferredRenderer::CreateFramebuffer(int width, int height) { m_resolutionScale = Settings::GetInstance().GetResolutionScale(); double resScale = static_cast<double>(Settings::GetInstance().GetResolutionScale()) / 100.0; int scaledW = static_cast<double>(width) * resScale; int scaledH = static_cast<double>(height) * resScale; m_geometryFramebuffer = std::make_unique<Framebuffer>(); m_depthBuffer = std::make_unique<Renderbuffer>(scaledW, scaledH, GL_DEPTH_COMPONENT16); m_colorBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, COLOR_FORMAT); m_colorBuffer->SetupMipmapping(false); m_colorBuffer->SetWrapS(GL_CLAMP_TO_EDGE); m_colorBuffer->SetWrapT(GL_CLAMP_TO_EDGE); m_colorBuffer->SetMinFilter(GL_LINEAR); m_colorBuffer->SetMagFilter(GL_LINEAR); m_normalsAndSpecBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, NORMALS_AND_SPECULAR_FORMAT); m_normalsAndSpecBuffer->SetupMipmapping(false); m_normalsAndSpecBuffer->SetWrapS(GL_CLAMP_TO_EDGE); m_normalsAndSpecBuffer->SetWrapT(GL_CLAMP_TO_EDGE); m_normalsAndSpecBuffer->SetMinFilter(GL_LINEAR); m_normalsAndSpecBuffer->SetMagFilter(GL_LINEAR); m_distortionBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, DISTORTION_BUFFER_FORMAT); m_distortionBuffer->SetupMipmapping(false); m_distortionBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); m_distortionBuffer->SetMinFilter(GL_LINEAR); m_distortionBuffer->SetMagFilter(GL_LINEAR); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_colorBuffer->GetID(), 0); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT1, m_normalsAndSpecBuffer->GetID(), 0); glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2, m_distortionBuffer->GetID(), 0); glNamedFramebufferRenderbuffer(m_geometryFramebuffer->GetID(), GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer->GetID()); m_lightFramebuffer = std::make_unique<Framebuffer>(); m_lightAccBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, LIGHT_ACC_FORMAT); m_lightAccBuffer->SetupMipmapping(false); m_lightAccBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); m_lightAccBuffer->SetMinFilter(GL_LINEAR); m_lightAccBuffer->SetMagFilter(GL_LINEAR); glNamedFramebufferTexture(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_lightAccBuffer->GetID(), 0); glNamedFramebufferDrawBuffer(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); m_outputFramebuffer = std::make_unique<Framebuffer>(); m_outputBuffer = std::make_unique<Texture2D>(width, height, 1, LIGHT_ACC_FORMAT); m_outputBuffer->SetupMipmapping(false); m_outputBuffer->SetWrapMode(GL_CLAMP_TO_EDGE); glNamedFramebufferTexture(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_outputBuffer->GetID(), 0); glNamedFramebufferDrawBuffer(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); m_postProcessor.OnResize(width, height); } bool DeferredRenderer::FramebufferOutOfDate() const { return m_resolutionScale != Settings::GetInstance().GetResolutionScale(); } void DeferredRenderer::Draw(const IRenderer& renderer, const class ViewInfo& viewInfo) const { Framebuffer::Save(); Framebuffer::Bind(*m_geometryFramebuffer, 0, 0, m_colorBuffer->GetWidth(), m_colorBuffer->GetHeight()); const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; const float depthClear = 1.0f; glEnable(GL_DEPTH_TEST); // ** Geometry pass ** GLenum geometryDrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glNamedFramebufferDrawBuffers(m_geometryFramebuffer->GetID(), 2, geometryDrawBuffers); glDepthMask(GL_TRUE); glClearBufferfv(GL_COLOR, 0, clearColor); glClearBufferfv(GL_COLOR, 1, clearColor); glClearBufferfv(GL_DEPTH, 0, &depthClear); renderer.DrawGeometry(viewInfo); glEnablei(GL_BLEND, 0); glBlendFuncSeparatei(0, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0); renderer.DrawTranslucentGeometry(viewInfo); // ** Distortion pass ** glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2); //Enables additive blending for this pass and the light accumulation pass glBlendFuncSeparatei(0, GL_ONE, GL_ONE, GL_ZERO, GL_ZERO); glClearBufferfv(GL_COLOR, 0, clearColor); renderer.DrawDistortions(viewInfo); glDisable(GL_DEPTH_TEST); // ** Light pass ** Framebuffer::Bind(*m_lightFramebuffer, 0, 0, m_lightAccBuffer->GetWidth(), m_lightAccBuffer->GetHeight()); m_normalsAndSpecBuffer->Bind(0); glClearBufferfv(GL_COLOR, 0, clearColor); renderer.DrawLighting(viewInfo); glDisablei(GL_BLEND, 0); // ** Composition pass ** Framebuffer::Bind(*m_outputFramebuffer, 0, 0, m_outputBuffer->GetWidth(), m_outputBuffer->GetHeight()); m_colorBuffer->Bind(0); m_lightAccBuffer->Bind(1); m_compositionShader.Use(); QuadMesh::GetInstance().GetVAO().Bind(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_particleRenderer.Begin(*m_lightAccBuffer); renderer.DrawParticles(viewInfo, m_particleRenderer); m_particleRenderer.End(); Framebuffer::Restore(); m_postProcessor.DoPostProcessing(*m_outputBuffer, *m_distortionBuffer); } }
37.353659
127
0.773425
Eae02
2d42214c1315403d801c760de700eb2f2bf6f190
14,820
cpp
C++
SRC/DVD/MountSDK.cpp
ogamespec/dolwin
7aaa864f9070ec14193f39f2e387087ccd5d0a93
[ "CC0-1.0" ]
107
2015-09-07T21:28:32.000Z
2022-02-14T03:13:01.000Z
SRC/DVD/MountSDK.cpp
emu-russia/dolwin
7aaa864f9070ec14193f39f2e387087ccd5d0a93
[ "CC0-1.0" ]
116
2020-03-11T16:42:02.000Z
2021-05-27T17:05:40.000Z
SRC/DVD/MountSDK.cpp
ogamespec/dolwin
7aaa864f9070ec14193f39f2e387087ccd5d0a93
[ "CC0-1.0" ]
8
2017-05-18T21:01:19.000Z
2021-04-30T11:28:14.000Z
/* Code for mounting the Dolphin SDK folder as a virtual disk. All the necessary data (BI2, Appldr, some DOL executable, we take from the SDK). If they are not there, then the disk is simply not mounted. */ #include "pch.h" using namespace Debug; namespace DVD { MountDolphinSdk::MountDolphinSdk(const wchar_t * DolphinSDKPath) { wcscpy(directory, DolphinSDKPath); // Load dvddata structure. // TODO: Generate Json dynamically auto dvdDataInfoText = Util::FileLoad(DvdDataJson); if (dvdDataInfoText.empty()) { Report(Channel::Norm, "Failed to load DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str()); return; } try { DvdDataInfo.Deserialize(dvdDataInfoText.data(), dvdDataInfoText.size()); } catch (...) { Report(Channel::Norm, "Failed to Deserialize DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str()); return; } // Generate data blobs if (!GenDiskId()) { Report(Channel::Norm, "Failed to GenDiskId\n"); return; } if (!GenApploader()) { Report(Channel::Norm, "Failed to GenApploader\n"); return; } if (!GenBi2()) { Report(Channel::Norm, "Failed to GenBi2\n"); return; } if (!GenFst()) { Report(Channel::Norm, "Failed to GenFst\n"); return; } if (!GenDol()) { Report(Channel::Norm, "Failed to GenDol\n"); return; } if (!GenBb2()) { Report(Channel::Norm, "Failed to GenBb2\n"); return; } // Generate mapping if (!GenMap()) { Report(Channel::Norm, "Failed to GenMap\n"); return; } if (!GenFileMap()) { Report(Channel::Norm, "Failed to GenFileMap\n"); return; } Report(Channel::DVD, "DolphinSDK mounted!\n"); mounted = true; } MountDolphinSdk::~MountDolphinSdk() { } void MountDolphinSdk::MapVector(std::vector<uint8_t>& v, uint32_t offset) { std::tuple<std::vector<uint8_t>&, uint32_t, size_t> entry(v, offset, v.size()); mapping.push_back(entry); } void MountDolphinSdk::MapFile(wchar_t* path, uint32_t offset) { size_t size = Util::FileSize(path); std::tuple<wchar_t*, uint32_t, size_t> entry(path, offset, size); fileMapping.push_back(entry); } // Check memory mapping uint8_t* MountDolphinSdk::TranslateMemory(uint32_t offset, size_t requestedSize, size_t& maxSize) { for (auto it = mapping.begin(); it != mapping.end(); ++it) { uint8_t * ptr = std::get<0>(*it).data(); uint32_t startingOffset = std::get<1>(*it); size_t size = std::get<2>(*it); if (startingOffset <= offset && offset < (startingOffset + size)) { maxSize = my_min(requestedSize, (startingOffset + size) - offset); return ptr + (offset - startingOffset); } } return nullptr; } // Check file mapping FILE * MountDolphinSdk::TranslateFile(uint32_t offset, size_t requestedSize, size_t& maxSize) { for (auto it = fileMapping.begin(); it != fileMapping.end(); ++it) { wchar_t* file = std::get<0>(*it); uint32_t startingOffset = std::get<1>(*it); size_t size = std::get<2>(*it); if (startingOffset <= offset && offset < (startingOffset + size)) { maxSize = my_min(requestedSize, (startingOffset + size) - offset); FILE* f; f = fopen( Util::WstringToString(file).c_str(), "rb"); assert(f); fseek(f, offset - startingOffset, SEEK_SET); return f; } } return nullptr; } void MountDolphinSdk::Seek(int position) { if (!mounted) return; assert(position >= 0 && position < DVD_SIZE); currentSeek = (uint32_t)position; } bool MountDolphinSdk::Read(void* buffer, size_t length) { bool result = true; assert(buffer); if (!mounted) { memset(buffer, 0, length); return true; } if (currentSeek >= DVD_SIZE) { memset(buffer, 0, length); return false; } size_t maxLength = 0; // First, try to enter the mapped binary blob, if it doesn't work, try the mapped file. uint8_t* ptr = TranslateMemory(currentSeek, length, maxLength); if (ptr != nullptr) { memcpy(buffer, ptr, maxLength); if (maxLength < length) { memset((uint8_t *)buffer + maxLength, 0, length - maxLength); } } else { FILE* f = TranslateFile(currentSeek, length, maxLength); if (f != nullptr) { fread(buffer, 1, maxLength, f); if (maxLength < length) { memset((uint8_t*)buffer + maxLength, 0, length - maxLength); } fclose(f); } else { // None of the options came up - return zeros. memset(buffer, 0, length); result = false; } } currentSeek += (uint32_t)length; return result; } #pragma region "Data Generators" // In addition to the actual files, the DVD image also contains a number of important binary data: DiskID, Apploader image, main program (DOL), BootInfo2 and BootBlock2 structures and FST. // Generating almost all blobs is straightforward, with the exception of the FST, which will have to tinker with. bool MountDolphinSdk::GenDiskId() { DiskId.resize(sizeof(DiskID)); DiskID* id = (DiskID*)DiskId.data(); id->gameName[0] = 'S'; id->gameName[1] = 'D'; id->gameName[2] = 'K'; id->gameName[3] = 'E'; id->company[0] = '0'; id->company[1] = '1'; id->magicNumber = _BYTESWAP_UINT32(DVD_DISKID_MAGIC); GameName.resize(0x400); memset(GameName.data(), 0, GameName.size()); strcpy((char *)GameName.data(), "GameCube SDK"); return true; } bool MountDolphinSdk::GenApploader() { auto path = fmt::format(L"{:s}{:s}", directory, AppldrPath); AppldrData = Util::FileLoad(path); return true; } /// <summary> /// Unfortunately, all demos in the SDK are in ELF format. Therefore, we will use PONG.DOL as the main program, which is included in each Dolwin release and is a full resident of the project :p /// </summary> /// <returns></returns> bool MountDolphinSdk::GenDol() { Dol = Util::FileLoad(DolPath); return true; } bool MountDolphinSdk::GenBi2() { auto path = fmt::format(L"{:s}{:s}", directory, Bi2Path); Bi2Data = Util::FileLoad(path); return true; } /// <summary> /// Add a string with the name of the entry (directory or file name) to the NameTable. /// </summary> /// <param name="str"></param> void MountDolphinSdk::AddString(std::string str) { for (auto& c : str) { NameTableData.push_back(c); } NameTableData.push_back(0); } /// <summary> /// Process original Json with dvddata directory structure. The Json structure is designed to accommodate the weird FST feature when a directory is in the middle of files. /// For a more detailed description of this oddity, see `dolwin-docs\RE\DVD\FSTNotes.md`. /// The method is recursive tree descent. /// In the process, meta information is added to the original Json structure, which is used by the `WalkAndGenerateFst` method to create the final binary FST blob. /// </summary> /// <param name="entry"></param> void MountDolphinSdk::ParseDvdDataEntryForFst(Json::Value* entry) { Json::Value* parent = nullptr; if (entry->type != Json::ValueType::Object) { return; } if (entry->children.size() != 0) { // Directory // Save directory name offset size_t nameOffset = NameTableData.size(); if (entry->name) { // Root has no name AddString(entry->name); } entry->AddInt("nameOffset", (int)nameOffset); entry->AddBool("dir", true); // Save current FST index for directory entry->AddInt("entryId", entryCounter); entryCounter++; // Reset totalChildren counter entry->AddInt("totalChildren", 0); } else { // File. // Differs from a directory in that it has no descendants assert(entry->name); std::string path = entry->name; size_t nameOffset = NameTableData.size(); AddString(path); parent = entry->parent; // Save file name offset entry->AddInt("nameOffset", (int)nameOffset); // Generate full path to file do { if (parent->ByName("dir")) { path = (parent->name ? parent->name + std::string("/") : "/") + path; } parent = parent->parent; } while (parent != nullptr); assert(path.size() < DVD_MAXPATH); wchar_t filePath[0x1000] = { 0, }; wcscat(filePath, directory); wcscat(filePath, FilesRoot); wchar_t* filePathPtr = filePath + wcslen(filePath); for (size_t i = 0; i < path.size(); i++) { *filePathPtr++ = (wchar_t)path[i]; } *filePathPtr++ = 0; //Report(Channel::Norm, "Processing file: %s\n", path.c_str()); // Save file offset entry->AddInt("fileOffset", userFilesStart + userFilesOffset); // Save file size size_t fileSize = Util::FileSize(filePath); entry->AddInt("fileSize", (int)fileSize); userFilesOffset += RoundUp32((uint32_t)fileSize); // Save file path entry->AddString("filePath", filePath); // Adjust entry counter entry->AddInt("entryId", entryCounter); entryCounter++; } // Update parent sibling counters parent = entry->parent; while (parent) { Json::Value* totalChildren = parent->ByName("totalChildren"); if (totalChildren) totalChildren->value.AsInt++; parent = parent->parent; // :p } // Recursively process descendants if (entry->ByName("dir") != nullptr) { for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { ParseDvdDataEntryForFst(*it); } } } /// <summary> /// Based on the Json structure with the data of the dvddata directory tree, in which meta-information is added, the final FST binary blob is built. /// </summary> /// <param name="entry"></param> void MountDolphinSdk::WalkAndGenerateFst(Json::Value* entry) { DVDFileEntry fstEntry = { 0 }; if (entry->type != Json::ValueType::Object) { return; } Json::Value* isDir = entry->ByName("dir"); if (isDir) { // Directory fstEntry.isDir = 1; Json::Value* nameOffset = entry->ByName("nameOffset"); assert(nameOffset); if (nameOffset) { fstEntry.nameOffsetHi = (uint8_t)(nameOffset->value.AsInt >> 16); fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset->value.AsInt); } if (entry->parent) { Json::Value* parentId = entry->parent->ByName("entryId"); if (parentId) { fstEntry.parentOffset = _BYTESWAP_UINT32((uint32_t)parentId->value.AsInt); } } Json::Value* entryId = entry->ByName("entryId"); Json::Value* totalChildren = entry->ByName("totalChildren"); if (entryId && totalChildren) { fstEntry.nextOffset = _BYTESWAP_UINT32((uint32_t)(entryId->value.AsInt + totalChildren->value.AsInt) + 1); } FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry)); if (logMount) { Report(Channel::Norm, "%d: directory: %s. nextOffset: %d\n", entryId->value.AsInt, entry->name, _BYTESWAP_UINT32(fstEntry.nextOffset)); } for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { WalkAndGenerateFst(*it); } } else { // File Json::Value* entryId = entry->ByName("entryId"); Json::Value* nameOffsetValue = entry->ByName("nameOffset"); Json::Value* fileOffsetValue = entry->ByName("fileOffset"); Json::Value* fileSizeValue = entry->ByName("fileSize"); assert(nameOffsetValue && fileOffsetValue && fileSizeValue); fstEntry.isDir = 0; uint32_t nameOffset = (uint32_t)(nameOffsetValue->value.AsInt); uint32_t fileOffset = (uint32_t)(fileOffsetValue->value.AsInt); uint32_t fileSize = (uint32_t)(fileSizeValue->value.AsInt); fstEntry.nameOffsetHi = (uint8_t)(nameOffset >> 16); fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset); fstEntry.fileOffset = _BYTESWAP_UINT32(fileOffset); fstEntry.fileLength = _BYTESWAP_UINT32(fileSize); FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry)); if (logMount) { Report(Channel::Norm, "%d: file: %s\n", entryId->value.AsInt, entry->name); } } } // The basic idea behind generating FST is to walk by DvdDataJson. // When traversing a structure a specific meta-information is attached to each node. // After generation, this meta-information is collected in a final collection (FST). bool MountDolphinSdk::GenFst() { try { ParseDvdDataEntryForFst(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "ParseDvdDataEntryForFst failed!\n"); return false; } if (logMount) { JDI::Hub.Dump(DvdDataInfo.root.children.back()); } try { WalkAndGenerateFst(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "WalkAndGenerateFst failed!\n"); return false; } // Add Name Table to the end FstData.insert(FstData.end(), NameTableData.begin(), NameTableData.end()); Util::FileSave(L"Data/DolphinSdkFST.bin", FstData); return true; } bool MountDolphinSdk::GenBb2() { DVDBB2 bb2 = { 0 }; bb2.bootFilePosition = RoundUpSector(DVD_APPLDR_OFFSET + (uint32_t)AppldrData.size()); bb2.FSTLength = (uint32_t)FstData.size(); bb2.FSTMaxLength = bb2.FSTLength; bb2.FSTPosition = RoundUpSector(bb2.bootFilePosition + (uint32_t)Dol.size() + DVD_SECTOR_SIZE); bb2.userPosition = 0x80030000; // Ignored bb2.userLength = RoundUpSector(bb2.FSTLength); Bb2Data.resize(sizeof(DVDBB2)); memcpy(Bb2Data.data(), &bb2, sizeof(bb2)); return true; } bool MountDolphinSdk::GenMap() { MapVector(DiskId, DVD_ID_OFFSET); MapVector(GameName, sizeof(DiskID)); MapVector(Bb2Data, DVD_BB2_OFFSET); MapVector(Bi2Data, DVD_BI2_OFFSET); MapVector(AppldrData, DVD_APPLDR_OFFSET); DVDBB2* bb2 = (DVDBB2 *)Bb2Data.data(); MapVector(Dol, bb2->bootFilePosition); MapVector(FstData, bb2->FSTPosition); SwapArea(bb2, sizeof(DVDBB2)); return true; } void MountDolphinSdk::WalkAndMapFiles(Json::Value* entry) { if (entry->type != Json::ValueType::Object) { return; } Json::Value* isDir = entry->ByName("dir"); if (!isDir) { Json::Value* filePath = entry->ByName("filePath"); Json::Value* fileOffset = entry->ByName("fileOffset"); assert(filePath && fileOffset); MapFile(filePath->value.AsString, (uint32_t)(fileOffset->value.AsInt)); } else { for (auto it = entry->children.begin(); it != entry->children.end(); ++it) { WalkAndMapFiles(*it); } } } bool MountDolphinSdk::GenFileMap() { userFilesOffset = 0; try { WalkAndMapFiles(DvdDataInfo.root.children.back()); } catch (...) { Report(Channel::Norm, "WalkAndMapFiles failed!\n"); return false; } return true; } void MountDolphinSdk::SwapArea(void* _addr, int sizeInBytes) { uint32_t* addr = (uint32_t*)_addr; uint32_t* until = addr + sizeInBytes / sizeof(uint32_t); while (addr != until) { *addr = _BYTESWAP_UINT32(*addr); addr++; } } #pragma endregion "Data Generators" }
23.449367
194
0.65803
ogamespec
2d43135d6fbc1a59c5f322668622952109189dd4
1,240
cpp
C++
tests/inputreader_tests.cpp
Stellaris-code/PEGLib
e106be64c9b2b5ad91b5a580e5c0a722082ef79b
[ "MIT" ]
1
2017-08-18T11:31:33.000Z
2017-08-18T11:31:33.000Z
tests/inputreader_tests.cpp
Stellaris-code/PEGLib
e106be64c9b2b5ad91b5a580e5c0a722082ef79b
[ "MIT" ]
null
null
null
tests/inputreader_tests.cpp
Stellaris-code/PEGLib
e106be64c9b2b5ad91b5a580e5c0a722082ef79b
[ "MIT" ]
null
null
null
/* inputreader_tests.cpp %{Cpp:License:ClassName} - Yann BOUCHER (yann) 20 ** ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** Version 2, December 2004 ** ** Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> ** ** Everyone is permitted to copy and distribute verbatim or modified ** copies of this license document, and changing it is allowed as long ** as the name is changed. ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ** ** 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include "gtest/gtest.h" #include "inputreader.hpp" #include "terminal.hpp" MAKE_TERMINAL(DummyToken) MAKE_TERMINAL(TargetToken) namespace { TEST(InputReaderFailure, NoMoreTokens) { InputReader reader; EXPECT_THROW(reader.fetch<Terminal>(), ParseError); } TEST(InputReaderFailure, InvalidToken) { std::vector<std::unique_ptr<Terminal>> tokens; tokens.emplace_back(std::make_unique<DummyToken>()); InputReader reader(std::move(tokens)); reader.set_failure_policy(InputReader::FailurePolicy::Strict); EXPECT_THROW(reader.fetch<TargetToken>(), ParseError); } }
26.382979
75
0.679032
Stellaris-code
2d446a4cf725b8535908871c9e316e9f9f518747
604
hpp
C++
android-31/android/app/appsearch/SetSchemaResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/app/appsearch/SetSchemaResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/app/appsearch/SetSchemaResponse.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" namespace android::app::appsearch { class SetSchemaResponse : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit SetSchemaResponse(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} SetSchemaResponse(QJniObject obj); // Constructors // Methods JObject getDeletedTypes() const; JObject getIncompatibleTypes() const; JObject getMigratedTypes() const; JObject getMigrationFailures() const; }; } // namespace android::app::appsearch
23.230769
158
0.706954
YJBeetle
2d4577a61f63ba366c8fa2aca81a7e3dc355fe10
1,711
cpp
C++
util/qtAbstractSetting.cpp
BetsyMcPhail/qtextensions
b2848e06ebba4c39dc63caa2363abc50db75f9d9
[ "BSD-3-Clause" ]
1
2017-07-31T07:08:05.000Z
2017-07-31T07:08:05.000Z
util/qtAbstractSetting.cpp
BetsyMcPhail/qtextensions
b2848e06ebba4c39dc63caa2363abc50db75f9d9
[ "BSD-3-Clause" ]
null
null
null
util/qtAbstractSetting.cpp
BetsyMcPhail/qtextensions
b2848e06ebba4c39dc63caa2363abc50db75f9d9
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +5 * Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "qtAbstractSetting.h" #include <QSettings> //----------------------------------------------------------------------------- qtAbstractSetting::qtAbstractSetting() : modified(false) { } //----------------------------------------------------------------------------- qtAbstractSetting::~qtAbstractSetting() { } //----------------------------------------------------------------------------- void qtAbstractSetting::initialize(const QSettings&) { this->currentValue = this->originalValue; } //----------------------------------------------------------------------------- bool qtAbstractSetting::isModified() { return this->modified; } //----------------------------------------------------------------------------- QVariant qtAbstractSetting::value() const { return this->currentValue; } //----------------------------------------------------------------------------- void qtAbstractSetting::setValue(const QVariant& value) { this->currentValue = value; this->modified = (this->currentValue != this->originalValue); } //----------------------------------------------------------------------------- void qtAbstractSetting::commit(QSettings& store) { store.setValue(this->key(), this->currentValue); this->originalValue = this->currentValue; this->modified = false; } //----------------------------------------------------------------------------- void qtAbstractSetting::discard() { this->currentValue = this->originalValue; this->modified = false; }
28.516667
79
0.462887
BetsyMcPhail
2d45bbd5e06e0a437259e7fa31a2cf68738d2740
1,290
cc
C++
auditd/src/audit_interface.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
null
null
null
auditd/src/audit_interface.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
null
null
null
auditd/src/audit_interface.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "audit.h" #include <logger/logger.h> #include <memcached/audit_interface.h> #include <platform/socket.h> #include <stdexcept> namespace cb::audit { UniqueAuditPtr create_audit_daemon(const std::string& config_file, ServerCookieIface* server_cookie_api) { if (!cb::logger::isInitialized()) { throw std::invalid_argument( "create_audit_daemon: logger must have been created"); } try { return std::make_unique<AuditImpl>( config_file, server_cookie_api, cb::net::getHostname()); } catch (std::runtime_error& err) { LOG_WARNING("{}", err.what()); } catch (std::bad_alloc&) { LOG_WARNING("Failed to start audit: Out of memory"); } return {}; } } // namespace cb::audit
31.463415
79
0.646512
BenHuddleston
2d4b67aa7abca789a228727007652cbab13a2a27
1,837
cpp
C++
Data_Structures/C++/Graph/snake_ladder.cpp
ankit1414/DS_with_hacktoberfest
9f005b923f18a0db7d97f93eeb098099ea32d2d2
[ "Apache-2.0" ]
null
null
null
Data_Structures/C++/Graph/snake_ladder.cpp
ankit1414/DS_with_hacktoberfest
9f005b923f18a0db7d97f93eeb098099ea32d2d2
[ "Apache-2.0" ]
null
null
null
Data_Structures/C++/Graph/snake_ladder.cpp
ankit1414/DS_with_hacktoberfest
9f005b923f18a0db7d97f93eeb098099ea32d2d2
[ "Apache-2.0" ]
1
2020-10-03T03:55:52.000Z
2020-10-03T03:55:52.000Z
#include"competitive.h" using namespace std; template<typename T> class Graph{ map<T,list<T>>m; public: void insert(T u,T v){ m[u].push_back(v); } void bfs(T src,T dest){ deque<T>q; map<T,int>dist; map<T,T>parent; q.push_back(src); for(auto &i : m){ T node = i.first; dist[node] = INT_MAX; } dist[src]=0; parent[src] = src; //cout<<dist[src]<<endl; while(!q.empty()){ const list<T> &bucket = m[q.front()]; for( const auto &i: bucket){ int d = dist[q.front()]; if(dist[i]==INT_MAX){ q.push_back(i); dist[i] = d+1; parent[i] = q.front(); } } //cout<<q.front()<<" "; q.pop_front(); } //cout<<endl; // for(auto i: m){ // T node = i.first; // cout<<src<<"-"<<node<<"="<<dist[node]<<endl; // } cout<<dist[dest]<<endl; int par = dest; while(par!=src){ cout<<par<<"<-"; par = parent[par]; } cout<<par<<endl; } }; int main(){ IOS; //ladder and snakes int board[50]{0}; board[2] = 13; board[5] = 2; board[9] = 18; board[17] = -13; board[18] = 11; board[20] = -14; board[24] = -8; board[25] = 10; board[32] = -2; board[34] = -22; //Graph Graph<int>g; for(int i=0;i<=36;i++){ if(board[i]!=0){ continue; } for(int dice=1;dice<=6;dice++){ int j = i+dice; j+=board[j]; if(j<=36) g.insert(i,j); } } g.insert(36,36); g.bfs(0,36); return 0; }
22.402439
59
0.392488
ankit1414
2d4c24308bdb7e7553f8c70d8eeff07c8360fdd9
1,025
hh
C++
plugins/gui/abstract-gui.hh
Schroedingers-Cat/clap-examples
9cbf04216316ca5bccb75b884906caa15766440b
[ "MIT" ]
null
null
null
plugins/gui/abstract-gui.hh
Schroedingers-Cat/clap-examples
9cbf04216316ca5bccb75b884906caa15766440b
[ "MIT" ]
null
null
null
plugins/gui/abstract-gui.hh
Schroedingers-Cat/clap-examples
9cbf04216316ca5bccb75b884906caa15766440b
[ "MIT" ]
null
null
null
#pragma once #include <clap/clap.h> namespace clap { class CorePlugin; class AbstractGuiListener; class AbstractGui { public: AbstractGui(AbstractGuiListener &listener); virtual ~AbstractGui(); virtual void defineParameter(const clap_param_info &paramInfo) = 0; virtual void updateParameter(clap_id paramId, double value, double modAmount) = 0; virtual void clearTransport() = 0; virtual void updateTransport(const clap_event_transport &transport) = 0; virtual bool attachCocoa(void *nsView) = 0; virtual bool attachWin32(clap_hwnd window) = 0; virtual bool attachX11(const char *displayName, unsigned long window) = 0; virtual bool size(uint32_t *width, uint32_t *height) = 0; virtual bool setScale(double scale) = 0; virtual bool show() = 0; virtual bool hide() = 0; virtual void destroy() = 0; protected: AbstractGuiListener &_listener; bool _isTransportSubscribed = false; }; } // namespace clap
26.973684
88
0.684878
Schroedingers-Cat
2d4c3ec94e49c50d982126d1b2384bbd8c865ebf
255
cpp
C++
code3.cpp
gaosiqiang/CSCode
cce6f63d74cca5fd843ac6a734809cc481b6d618
[ "MIT" ]
null
null
null
code3.cpp
gaosiqiang/CSCode
cce6f63d74cca5fd843ac6a734809cc481b6d618
[ "MIT" ]
null
null
null
code3.cpp
gaosiqiang/CSCode
cce6f63d74cca5fd843ac6a734809cc481b6d618
[ "MIT" ]
null
null
null
#include <iostream> //循环结构 int main(int argc, char const *argv[]) { //输出小于a的自然数 int a; std::cout << "请输入一个整数"; std::cin >> a; if (a > 0) { for (int i = 0; i < a; ++i) { std::cout << i << std::endl; } } else { std::cout << "不得小于1"; } }
12.75
38
0.494118
gaosiqiang
2d5242fd89a6e0731ca54baf77eceafc0698fa95
8,388
cpp
C++
modules/boost/simd/operator/unit/scalar/access.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
modules/boost/simd/operator/unit/scalar/access.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/operator/unit/scalar/access.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
/******************************************************************************* * Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II * Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 0x01.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #define NT2_UNIT_MODULE "boost::simd::memory::load and store" #include <boost/mpl/int.hpp> #include <boost/simd/sdk/simd/native.hpp> #include <boost/simd/include/functions/load.hpp> #include <boost/simd/include/functions/store.hpp> #include <boost/simd/include/functions/unaligned_load.hpp> #include <boost/simd/include/functions/unaligned_store.hpp> #include <boost/simd/sdk/config/types.hpp> #include <boost/simd/sdk/config/type_lists.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/relation.hpp> //////////////////////////////////////////////////////////////////////////////// // Test load behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(load, BOOST_SIMD_TYPES) { using boost::simd::load; T data[5] = {0,1,2,3,4}; NT2_TEST_EQUAL( (load<T,-4>(&data[0],4)), T(0) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],5)), T(1) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],6)), T(2) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],7)), T(3) ); NT2_TEST_EQUAL( (load<T,-4>(&data[0],8)), T(4) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],3)), T(0) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],4)), T(1) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],5)), T(2) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],6)), T(3) ); NT2_TEST_EQUAL( (load<T,-3>(&data[0],7)), T(4) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],2)), T(0) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],3)), T(1) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],4)), T(2) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],5)), T(3) ); NT2_TEST_EQUAL( (load<T,-2>(&data[0],6)), T(4) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],1)), T(0) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],2)), T(1) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],3)), T(2) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],4)), T(3) ); NT2_TEST_EQUAL( (load<T,-1>(&data[0],5)), T(4) ); NT2_TEST_EQUAL( load<T>(&data[0],0), T(0) ); NT2_TEST_EQUAL( load<T>(&data[0],1), T(1) ); NT2_TEST_EQUAL( load<T>(&data[0],2), T(2) ); NT2_TEST_EQUAL( load<T>(&data[0],3), T(3) ); NT2_TEST_EQUAL( load<T>(&data[0],4), T(4) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],0)), T(0) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],1)), T(1) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],2)), T(2) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],3)), T(3) ); NT2_TEST_EQUAL( (load<T,0>(&data[0],4)), T(4) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],-1)), T(0) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],0)) , T(1) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],1)) , T(2) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],2)) , T(3) ); NT2_TEST_EQUAL( (load<T,1>(&data[0],3)) , T(4) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],-2)), T(0) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],-1)), T(1) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],0)) , T(2) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],1)) , T(3) ); NT2_TEST_EQUAL( (load<T,2>(&data[0],2)) , T(4) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-3)), T(0) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-2)), T(1) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],-1)), T(2) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],0)) , T(3) ); NT2_TEST_EQUAL( (load<T,3>(&data[0],1)) , T(4) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-4)), T(0) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-3)), T(1) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-2)), T(2) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],-1)), T(3) ); NT2_TEST_EQUAL( (load<T,4>(&data[0],0)) , T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test store behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(store, BOOST_SIMD_TYPES) { using boost::simd::store; T data[5]; for(boost::simd::int32_t i=0;i<5;++i) store(static_cast<T>(i),&data[0],i); NT2_TEST_EQUAL( data[0], T(0) ); NT2_TEST_EQUAL( data[1], T(1) ); NT2_TEST_EQUAL( data[2], T(2) ); NT2_TEST_EQUAL( data[3], T(3) ); NT2_TEST_EQUAL( data[4], T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test unaligned_load behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(unaligned_load, BOOST_SIMD_TYPES) { using boost::simd::unaligned_load; T data[5] = {0,1,2,3,4}; NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],4)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],5)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],6)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],7)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-4>(&data[0],8)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],3)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],4)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],5)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],6)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-3>(&data[0],7)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],2)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],3)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],4)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],5)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-2>(&data[0],6)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],1)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],2)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],3)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],4)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,-1>(&data[0],5)), T(4) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],0), T(0) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],1), T(1) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],2), T(2) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],3), T(3) ); NT2_TEST_EQUAL( unaligned_load<T>(&data[0],4), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],0)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],1)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],2)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],3)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,0>(&data[0],4)), T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],-1)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],0)) , T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],1)) , T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],2)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,1>(&data[0],3)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],-2)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],-1)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],0)) , T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],1)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,2>(&data[0],2)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-3)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-2)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],-1)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],0)) , T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,3>(&data[0],1)) , T(4) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-4)), T(0) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-3)), T(1) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-2)), T(2) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],-1)), T(3) ); NT2_TEST_EQUAL( (unaligned_load<T,4>(&data[0],0)) , T(4) ); } //////////////////////////////////////////////////////////////////////////////// // Test unaligned_store behavior //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE_TPL(unaligned_store, BOOST_SIMD_TYPES) { using boost::simd::unaligned_store; T data[5]; for(boost::simd::int32_t i=0;i<5;++i) unaligned_store(static_cast<T>(i),&data[0],i); NT2_TEST_EQUAL( data[0], T(0) ); NT2_TEST_EQUAL( data[1], T(1) ); NT2_TEST_EQUAL( data[2], T(2) ); NT2_TEST_EQUAL( data[3], T(3) ); NT2_TEST_EQUAL( data[4], T(4) ); }
43.46114
86
0.549952
pbrunet
2d53604aceb64d056aea6d2e56e93cbe9e0be93c
26,331
cpp
C++
Code/Tools/SerializeContextTools/Dumper.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Tools/SerializeContextTools/Dumper.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Tools/SerializeContextTools/Dumper.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Dumper.h> // Moved to the top because AssetSerializer requires include for the SerializeContext #include <AzCore/Asset/AssetSerializer.h> #include <AzCore/Casting/lossy_cast.h> #include <AzCore/Debug/Trace.h> #include <AzCore/IO/Path/Path.h> #include <AzCore/IO/SystemFile.h> #include <AzCore/JSON/stringbuffer.h> #include <AzCore/JSON/prettywriter.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Settings/SettingsRegistryMergeUtils.h> #include <AzCore/std/algorithm.h> #include <AzCore/std/sort.h> #include <AzCore/StringFunc/StringFunc.h> #include <Application.h> #include <Utilities.h> namespace AZ::SerializeContextTools { bool Dumper::DumpFiles(Application& application) { SerializeContext* sc = application.GetSerializeContext(); if (!sc) { AZ_Error("SerializeContextTools", false, "No serialize context found."); return false; } AZStd::string outputFolder = Utilities::ReadOutputTargetFromCommandLine(application); AZ::IO::Path sourceGameFolder; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Get(sourceGameFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectPath); } bool result = true; AZStd::vector<AZStd::string> fileList = Utilities::ReadFileListFromCommandLine(application, "files"); for (const AZStd::string& filePath : fileList) { AZ_Printf("DumpFiles", "Dumping file '%.*s'\n", aznumeric_cast<int>(filePath.size()), filePath.data()); AZ::IO::FixedMaxPath outputPath{ AZStd::string_view{ outputFolder }}; outputPath /= AZ::IO::FixedMaxPath(filePath).LexicallyRelative(sourceGameFolder); outputPath.Native() += ".dump.txt"; IO::SystemFile outputFile; if (!outputFile.Open(outputPath.c_str(), IO::SystemFile::OpenMode::SF_OPEN_CREATE | IO::SystemFile::OpenMode::SF_OPEN_CREATE_PATH | IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY)) { AZ_Error("SerializeContextTools", false, "Unable to open file '%s' for writing.", outputPath.c_str()); result = false; continue; } AZStd::string content; content.reserve(1 * 1024 * 1024); // Reserve 1mb to avoid frequently resizing the string. auto callback = [&content, &result](void* classPtr, const Uuid& classId, SerializeContext* context) { result = DumpClassContent(content, classPtr, classId, context) && result; const SerializeContext::ClassData* classData = context->FindClassData(classId); if (classData && classData->m_factory) { classData->m_factory->Destroy(classPtr); } else { AZ_Error("SerializeContextTools", false, "Missing class factory, so data will leak."); result = false; } }; if (!Utilities::InspectSerializedFile(filePath.c_str(), sc, callback)) { result = false; continue; } outputFile.Write(content.data(), content.length()); } return result; } bool Dumper::DumpSerializeContext(Application& application) { AZStd::string outputPath = Utilities::ReadOutputTargetFromCommandLine(application, "SerializeContext.json"); AZ_Printf("dumpsc", "Writing Serialize Context at '%s'.\n", outputPath.c_str()); IO::SystemFile outputFile; if (!outputFile.Open(outputPath.c_str(), IO::SystemFile::OpenMode::SF_OPEN_CREATE | IO::SystemFile::OpenMode::SF_OPEN_CREATE_PATH | IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY)) { AZ_Error("SerializeContextTools", false, "Unable to open output file '%s'.", outputPath.c_str()); return false; } SerializeContext* context = application.GetSerializeContext(); AZStd::vector<Uuid> systemComponents = Utilities::GetSystemComponents(application); AZStd::sort(systemComponents.begin(), systemComponents.end()); rapidjson::Document doc; rapidjson::Value& root = doc.SetObject(); rapidjson::Value scObject; scObject.SetObject(); AZStd::string temp; temp.reserve(256 * 1024); // Reserve 256kb of memory to avoid the string constantly resizing. bool result = true; auto callback = [context, &doc, &scObject, &temp, &systemComponents, &result](const SerializeContext::ClassData* classData, const Uuid& /*typeId*/) -> bool { if (!DumpClassContent(classData, scObject, doc, systemComponents, context, temp)) { result = false; } return true; }; context->EnumerateAll(callback, true); root.AddMember("SerializeContext", AZStd::move(scObject), doc.GetAllocator()); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); outputFile.Write(buffer.GetString(), buffer.GetSize()); outputFile.Close(); return result; } AZStd::vector<Uuid> Dumper::CreateFilterListByNames(SerializeContext* context, AZStd::string_view name) { AZStd::vector<AZStd::string_view> names; auto AppendNames = [&names](AZStd::string_view filename) { names.emplace_back(filename); }; AZ::StringFunc::TokenizeVisitor(name, AppendNames, ';'); AZStd::vector<Uuid> filterIds; filterIds.reserve(names.size()); for (const AZStd::string_view& singleName : names) { AZStd::vector<Uuid> foundFilters = context->FindClassId(Crc32(singleName.data(), singleName.length(), true)); filterIds.insert(filterIds.end(), foundFilters.begin(), foundFilters.end()); } return filterIds; } AZStd::string_view Dumper::ExtractNamespace(const AZStd::string& name) { size_t offset = 0; const char* startChar = name.data(); const char* currentChar = name.data(); while (*currentChar != 0 && *currentChar != '<') { if (*currentChar != ':') { ++currentChar; } else { ++currentChar; if (*currentChar == ':') { AZ_Assert(currentChar - startChar >= 1, "Offset out of bounds while trying to extract namespace from name '%s'.", name.c_str()); offset = currentChar - startChar - 1; // -1 to exclude the last "::" } } } return AZStd::string_view(startChar, offset); } rapidjson::Value Dumper::WriteToJsonValue(const Uuid& uuid, rapidjson::Document& document) { char buffer[Uuid::MaxStringBuffer]; int writtenCount = uuid.ToString(buffer, AZ_ARRAY_SIZE(buffer)); if (writtenCount > 0) { return rapidjson::Value(buffer, writtenCount - 1, document.GetAllocator()); //-1 as the null character shouldn't be written. } else { return rapidjson::Value(rapidjson::StringRef("{uuid conversion failed}")); } } bool Dumper::DumpClassContent(const SerializeContext::ClassData* classData, rapidjson::Value& parent, rapidjson::Document& document, const AZStd::vector<Uuid>& systemComponents, SerializeContext* context, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer wasn't empty."); rapidjson::Value classNode(rapidjson::kObjectType); DumpClassName(classNode, context, classData, document, scratchStringBuffer); Edit::ClassData* editData = classData->m_editData; GenericClassInfo* genericClassInfo = context->FindGenericClassInfo(classData->m_typeId); if (editData && editData->m_description) { AZStd::string_view description = editData->m_description; // Skipping if there's only one character as there are several cases where a blank description is given. if (description.size() > 1) { classNode.AddMember("Description", rapidjson::Value(description.data(), document.GetAllocator()), document.GetAllocator()); } } classNode.AddMember("Id", rapidjson::StringRef(classData->m_name), document.GetAllocator()); classNode.AddMember("Version", classData->IsDeprecated() ? rapidjson::Value(rapidjson::StringRef("Deprecated")) : rapidjson::Value(classData->m_version), document.GetAllocator()); auto systemComponentIt = AZStd::lower_bound(systemComponents.begin(), systemComponents.end(), classData->m_typeId); bool isSystemComponent = systemComponentIt != systemComponents.end() && *systemComponentIt == classData->m_typeId; classNode.AddMember("IsSystemComponent", isSystemComponent, document.GetAllocator()); classNode.AddMember("IsPrimitive", Utilities::IsSerializationPrimitive(genericClassInfo ? genericClassInfo->GetGenericTypeId() : classData->m_typeId), document.GetAllocator()); classNode.AddMember("IsContainer", classData->m_container != nullptr, document.GetAllocator()); if (genericClassInfo) { classNode.AddMember("GenericUuid", WriteToJsonValue(genericClassInfo->GetGenericTypeId(), document), document.GetAllocator()); classNode.AddMember("Generics", DumpGenericStructure(genericClassInfo, context, document, scratchStringBuffer), document.GetAllocator()); } if (!classData->m_elements.empty()) { rapidjson::Value fields(rapidjson::kArrayType); rapidjson::Value bases(rapidjson::kArrayType); for (const SerializeContext::ClassElement& element : classData->m_elements) { DumpElementInfo(element, classData, context, fields, bases, document, scratchStringBuffer); } if (!bases.Empty()) { classNode.AddMember("Bases", AZStd::move(bases), document.GetAllocator()); } if (!fields.Empty()) { classNode.AddMember("Fields", AZStd::move(fields), document.GetAllocator()); } } parent.AddMember(WriteToJsonValue(classData->m_typeId, document), AZStd::move(classNode), document.GetAllocator()); return true; } bool Dumper::DumpClassContent(AZStd::string& output, void* classPtr, const Uuid& classId, SerializeContext* context) { const SerializeContext::ClassData* classData = context->FindClassData(classId); if (!classData) { AZ_Printf("", " Class data for '%s' is missing.\n", classId.ToString<AZStd::string>().c_str()); return false; } size_t indention = 0; auto begin = [context, &output, &indention](void* /*instance*/, const SerializeContext::ClassData* classData, const SerializeContext::ClassElement* classElement) -> bool { for (size_t i = 0; i < indention; ++i) { output += ' '; } if (classData) { output += classData->m_name; } DumpElementInfo(output, classElement, context); DumpPrimitiveTag(output, classData, classElement); output += '\n'; indention += 2; return true; }; auto end = [&indention]() -> bool { indention = indention > 0 ? indention - 2 : 0; return true; }; SerializeContext::EnumerateInstanceCallContext callContext(begin, end, context, SerializeContext::ENUM_ACCESS_FOR_WRITE, nullptr); context->EnumerateInstance(&callContext, classPtr, classId, classData, nullptr); return true; } void Dumper::DumpElementInfo(const SerializeContext::ClassElement& element, const SerializeContext::ClassData* classData, SerializeContext* context, rapidjson::Value& fields, rapidjson::Value& bases, rapidjson::Document& document, AZStd::string& scratchStringBuffer) { AZ_Assert(fields.IsArray(), "Expected 'fields' to be an array."); AZ_Assert(bases.IsArray(), "Expected 'bases' to be an array."); AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer wasn't empty."); const SerializeContext::ClassData* elementClass = context->FindClassData(element.m_typeId, classData); AppendTypeName(scratchStringBuffer, elementClass, element.m_typeId); Uuid elementTypeId = element.m_typeId; if (element.m_genericClassInfo) { DumpGenericStructure(scratchStringBuffer, element.m_genericClassInfo, context); elementTypeId = element.m_genericClassInfo->GetSpecializedTypeId(); } if ((element.m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { scratchStringBuffer += '*'; } rapidjson::Value elementTypeString(scratchStringBuffer.c_str(), document.GetAllocator()); scratchStringBuffer.clear(); if ((element.m_flags & SerializeContext::ClassElement::FLG_BASE_CLASS) != 0) { rapidjson::Value baseNode(rapidjson::kObjectType); baseNode.AddMember("Type", AZStd::move(elementTypeString), document.GetAllocator()); baseNode.AddMember("Uuid", WriteToJsonValue(elementTypeId, document), document.GetAllocator()); bases.PushBack(AZStd::move(baseNode), document.GetAllocator()); } else { rapidjson::Value elementNode(rapidjson::kObjectType); elementNode.AddMember("Name", rapidjson::StringRef(element.m_name), document.GetAllocator()); elementNode.AddMember("Type", AZStd::move(elementTypeString), document.GetAllocator()); elementNode.AddMember("Uuid", WriteToJsonValue(elementTypeId, document), document.GetAllocator()); elementNode.AddMember("HasDefault", (element.m_flags & SerializeContext::ClassElement::FLG_NO_DEFAULT_VALUE) == 0, document.GetAllocator()); elementNode.AddMember("IsDynamic", (element.m_flags & SerializeContext::ClassElement::FLG_DYNAMIC_FIELD) != 0, document.GetAllocator()); elementNode.AddMember("IsPointer", (element.m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0, document.GetAllocator()); elementNode.AddMember("IsUiElement", (element.m_flags & SerializeContext::ClassElement::FLG_UI_ELEMENT) != 0, document.GetAllocator()); elementNode.AddMember("DataSize", static_cast<uint64_t>(element.m_dataSize), document.GetAllocator()); elementNode.AddMember("Offset", static_cast<uint64_t>(element.m_offset), document.GetAllocator()); Edit::ElementData* elementEditData = element.m_editData; if (elementEditData) { elementNode.AddMember("Description", rapidjson::StringRef(elementEditData->m_description), document.GetAllocator()); } if (element.m_genericClassInfo) { rapidjson::Value genericArray(rapidjson::kArrayType); rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* genericClassData = element.m_genericClassInfo->GetClassData(); classObject.AddMember("Type", rapidjson::StringRef(genericClassData->m_name), document.GetAllocator()); classObject.AddMember("GenericUuid", WriteToJsonValue(element.m_genericClassInfo->GetGenericTypeId(), document), document.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(element.m_genericClassInfo->GetSpecializedTypeId(), document), document.GetAllocator()); classObject.AddMember("Generics", DumpGenericStructure(element.m_genericClassInfo, context, document, scratchStringBuffer), document.GetAllocator()); genericArray.PushBack(AZStd::move(classObject), document.GetAllocator()); elementNode.AddMember("Generics", AZStd::move(genericArray), document.GetAllocator()); } fields.PushBack(AZStd::move(elementNode), document.GetAllocator()); } } void Dumper::DumpElementInfo(AZStd::string& output, const SerializeContext::ClassElement* classElement, SerializeContext* context) { if (classElement) { if (classElement->m_genericClassInfo) { DumpGenericStructure(output, classElement->m_genericClassInfo, context); } if ((classElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { output += '*'; } output += ' '; output += classElement->m_name; if ((classElement->m_flags & SerializeContext::ClassElement::FLG_BASE_CLASS) != 0) { output += " [Base]"; } } } void Dumper::DumpGenericStructure(AZStd::string& output, GenericClassInfo* genericClassInfo, SerializeContext* context) { output += '<'; const SerializeContext::ClassData* classData = genericClassInfo->GetClassData(); if (classData && classData->m_container) { bool firstArgument = true; auto callback = [&output, context, &firstArgument](const Uuid& elementClassId, const SerializeContext::ClassElement* genericClassElement) -> bool { if (!firstArgument) { output += ','; } else { firstArgument = false; } const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(output, argClassData, elementClassId); if (genericClassElement->m_genericClassInfo) { DumpGenericStructure(output, genericClassElement->m_genericClassInfo, context); } if ((genericClassElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0) { output += '*'; } return true; }; classData->m_container->EnumTypes(callback); } else { // No container information available, so as much as possible through other means, although // this might not be complete information. size_t numArgs = genericClassInfo->GetNumTemplatedArguments(); for (size_t i = 0; i < numArgs; ++i) { if (i != 0) { output += ','; } const Uuid& argClassId = genericClassInfo->GetTemplatedTypeId(i); const SerializeContext::ClassData* argClass = context->FindClassData(argClassId); AppendTypeName(output, argClass, argClassId); } } output += '>'; } rapidjson::Value Dumper::DumpGenericStructure(GenericClassInfo* genericClassInfo, SerializeContext* context, rapidjson::Document& parentDoc, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Provided scratch string buffer still contains data."); rapidjson::Value result(rapidjson::kArrayType); const SerializeContext::ClassData* classData = genericClassInfo->GetClassData(); if (classData && classData->m_container) { auto callback = [&result, context, &parentDoc, &scratchStringBuffer](const Uuid& elementClassId, const SerializeContext::ClassElement* genericClassElement) -> bool { rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(scratchStringBuffer, argClassData, elementClassId); classObject.AddMember("Type", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); scratchStringBuffer.clear(); classObject.AddMember("IsPointer", (genericClassElement->m_flags & SerializeContext::ClassElement::FLG_POINTER) != 0, parentDoc.GetAllocator()); if (genericClassElement->m_genericClassInfo) { GenericClassInfo* genericClassInfo = genericClassElement->m_genericClassInfo; classObject.AddMember("GenericUuid", WriteToJsonValue(genericClassInfo->GetGenericTypeId(), parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(genericClassInfo->GetSpecializedTypeId(), parentDoc), parentDoc.GetAllocator()); classObject.AddMember("Generics", DumpGenericStructure(genericClassInfo, context, parentDoc, scratchStringBuffer), parentDoc.GetAllocator()); } else { classObject.AddMember("GenericUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); } result.PushBack(AZStd::move(classObject), parentDoc.GetAllocator()); return true; }; classData->m_container->EnumTypes(callback); } else { // No container information available, so as much as possible through other means, although // this might not be complete information. size_t numArgs = genericClassInfo->GetNumTemplatedArguments(); for (size_t i = 0; i < numArgs; ++i) { const Uuid& elementClassId = genericClassInfo->GetTemplatedTypeId(i); rapidjson::Value classObject(rapidjson::kObjectType); const SerializeContext::ClassData* argClassData = context->FindClassData(elementClassId); AppendTypeName(scratchStringBuffer, argClassData, elementClassId); classObject.AddMember("Type", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); scratchStringBuffer.clear(); classObject.AddMember("GenericUuid", WriteToJsonValue(argClassData ? argClassData->m_typeId : elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("SpecializedUuid", WriteToJsonValue(elementClassId, parentDoc), parentDoc.GetAllocator()); classObject.AddMember("IsPointer", false, parentDoc.GetAllocator()); result.PushBack(AZStd::move(classObject), parentDoc.GetAllocator()); } } return result; } void Dumper::DumpPrimitiveTag(AZStd::string& output, const SerializeContext::ClassData* classData, const SerializeContext::ClassElement* classElement) { if (classData) { Uuid classId = classData->m_typeId; if (classElement && classElement->m_genericClassInfo) { classId = classElement->m_genericClassInfo->GetGenericTypeId(); } if (Utilities::IsSerializationPrimitive(classId)) { output += " [Primitive]"; } } } void Dumper::DumpClassName(rapidjson::Value& parent, SerializeContext* context, const SerializeContext::ClassData* classData, rapidjson::Document& parentDoc, AZStd::string& scratchStringBuffer) { AZ_Assert(scratchStringBuffer.empty(), "Scratch string buffer is not empty."); Edit::ClassData* editData = classData->m_editData; GenericClassInfo* genericClassInfo = context->FindGenericClassInfo(classData->m_typeId); if (genericClassInfo) { // If the type itself is a generic, dump it's information. scratchStringBuffer = classData->m_name; DumpGenericStructure(scratchStringBuffer, genericClassInfo, context); } else { bool hasEditName = editData && editData->m_name && strlen(editData->m_name) > 0; scratchStringBuffer = hasEditName ? editData->m_name : classData->m_name; } AZStd::string_view namespacePortion = ExtractNamespace(scratchStringBuffer); if (!namespacePortion.empty()) { parent.AddMember("Namespace", rapidjson::Value(namespacePortion.data(), azlossy_caster(namespacePortion.length()), parentDoc.GetAllocator()), parentDoc.GetAllocator()); parent.AddMember("Name", rapidjson::Value(scratchStringBuffer.c_str() + namespacePortion.length() + 2, parentDoc.GetAllocator()), parentDoc.GetAllocator()); } else { parent.AddMember("Name", rapidjson::Value(scratchStringBuffer.c_str(), parentDoc.GetAllocator()), parentDoc.GetAllocator()); } scratchStringBuffer.clear(); } void Dumper::AppendTypeName(AZStd::string& output, const SerializeContext::ClassData* classData, const Uuid& classId) { if (classData) { output += classData->m_name; } else if (classId == GetAssetClassId()) { output += "Asset"; } else { output += classId.ToString<AZStd::string>(); } } // namespace AZ::SerializeContextTools }
45.242268
184
0.624967
cypherdotXd
2d54821c3a21a2235f96c05a611dc5675b8d4133
8,859
cpp
C++
sources/enduro2d/utils/strings.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
92
2018-08-07T14:45:33.000Z
2021-11-14T20:37:23.000Z
sources/enduro2d/utils/strings.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
43
2018-09-30T20:48:03.000Z
2020-04-20T20:05:26.000Z
sources/enduro2d/utils/strings.cpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
13
2018-08-08T13:45:28.000Z
2020-10-02T11:55:58.000Z
/******************************************************************************* * This file is part of the "Enduro2D" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #include <enduro2d/utils/strings.hpp> #include <3rdparty/utfcpp/utf8.h> namespace { using namespace e2d; // // utf8_to_X // str16 utf8_to_16(str_view src) { str16 dst; dst.reserve(src.size()); utf8::utf8to16(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } str32 utf8_to_32(str_view src) { str32 dst; dst.reserve(src.size()); utf8::utf8to32(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename WChar = wchar_t > std::enable_if_t<sizeof(WChar) == 2, wstr> utf8_to_wide(str_view src) { wstr dst; dst.reserve(src.size()); utf8::utf8to16(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename WChar = wchar_t > std::enable_if_t<sizeof(WChar) == 4, wstr> utf8_to_wide(str_view src) { wstr dst; dst.reserve(src.size()); utf8::utf8to32(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } // // utf16_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 2, str> utf16_to_8(basic_string_view<Char> src) { str dst; dst.reserve(src.size() * 2); utf8::utf16to8(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str32> utf16_to_32(basic_string_view<Char> src) { return utf8_to_32(utf16_to_8(src)); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, wstr> utf16_to_wide(basic_string_view<Char> src) { return utf8_to_wide(utf16_to_8(src)); } // // utf32_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 4, str> utf32_to_8(basic_string_view<Char> src) { str dst; dst.reserve(src.size() * 4); utf8::utf32to8(src.cbegin(), src.cend(), std::back_inserter(dst)); dst.shrink_to_fit(); return dst; } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str16> utf32_to_16(basic_string_view<Char> src) { return utf8_to_16(utf32_to_8(src)); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, wstr> utf32_to_wide(basic_string_view<Char> src) { return utf8_to_wide(utf32_to_8(src)); } // // wide_to_X // template < typename Char > std::enable_if_t<sizeof(Char) == 2, str> wide_to_utf8(basic_string_view<Char> src) { return utf16_to_8(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str> wide_to_utf8(basic_string_view<Char> src) { return utf32_to_8(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str16> wide_to_utf16(basic_string_view<Char> src) { return src.empty() ? str16() : str16(src.cbegin(), src.cend()); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str16> wide_to_utf16(basic_string_view<Char> src) { return utf32_to_16(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 2, str32> wide_to_utf32(basic_string_view<Char> src) { return utf16_to_32(src); } template < typename Char > std::enable_if_t<sizeof(Char) == 4, str32> wide_to_utf32(basic_string_view<Char> src) { return src.empty() ? str32() : str32(src.cbegin(), src.cend()); } } namespace e2d { // // make_utf8 // str make_utf8(str_view src) { return src.empty() ? str() : str(src.cbegin(), src.cend()); } str make_utf8(wstr_view src) { return wide_to_utf8(src); } str make_utf8(str16_view src) { return utf16_to_8(src); } str make_utf8(str32_view src) { return utf32_to_8(src); } // // make_wide // wstr make_wide(str_view src) { return utf8_to_wide(src); } wstr make_wide(wstr_view src) { return src.empty() ? wstr() : wstr(src.cbegin(), src.cend()); } wstr make_wide(str16_view src) { return utf16_to_wide(src); } wstr make_wide(str32_view src) { return utf32_to_wide(src); } // // make_utf16 // str16 make_utf16(str_view src) { return utf8_to_16(src); } str16 make_utf16(wstr_view src) { return wide_to_utf16(src); } str16 make_utf16(str16_view src) { return src.empty() ? str16() : str16(src.cbegin(), src.cend()); } str16 make_utf16(str32_view src) { return utf32_to_16(src); } // // make_utf32 // str32 make_utf32(str_view src) { return utf8_to_32(src); } str32 make_utf32(wstr_view src) { return wide_to_utf32(src); } str32 make_utf32(str16_view src) { return utf16_to_32(src); } str32 make_utf32(str32_view src) { return src.empty() ? str32() : str32(src.cbegin(), src.cend()); } // // make_hash // str_hash make_hash(str_view src) noexcept { return str_hash(src); } wstr_hash make_hash(wstr_view src) noexcept { return wstr_hash(src); } str16_hash make_hash(str16_view src) noexcept { return str16_hash(src); } str32_hash make_hash(str32_view src) noexcept { return str32_hash(src); } } namespace e2d::strings { namespace impl { // Inspired by: // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing using utf8_iter = utf8::iterator<str_view::const_iterator>; static bool wildcard_match_impl( utf8_iter string_i, utf8_iter string_e, utf8_iter pattern_i, utf8_iter pattern_e) { while ( pattern_i != pattern_e && *pattern_i != '*' ) { if ( string_i == string_e ) { break; } if ( *pattern_i != *string_i && *pattern_i != '?' ) { return false; } ++string_i; ++pattern_i; } if ( pattern_i == pattern_e ) { return string_i == string_e; } utf8_iter s_mark = string_e; utf8_iter p_mark = pattern_e; while ( string_i != string_e ) { if ( pattern_i != pattern_e ) { if ( *pattern_i == '*' ) { if ( ++pattern_i == pattern_e ) { return true; } s_mark = string_i; p_mark = pattern_i; ++s_mark; continue; } else if ( *pattern_i == *string_i || *pattern_i == '?' ) { ++string_i; ++pattern_i; continue; } } string_i = s_mark; pattern_i = p_mark; if ( s_mark != string_e ) { ++s_mark; } } while ( pattern_i != pattern_e && *pattern_i == '*' ) { ++pattern_i; } return pattern_i == pattern_e; } } bool wildcard_match(str_view string, str_view pattern) { using namespace impl; str_view::const_iterator si = string.cbegin(); str_view::const_iterator se = string.cend(); str_view::const_iterator pi = pattern.cbegin(); str_view::const_iterator pe = pattern.cend(); return wildcard_match_impl( utf8_iter(si, si, se), utf8_iter(se, si, se), utf8_iter(pi, pi, pe), utf8_iter(pe, pi, pe)); } bool starts_with(str_view input, str_view test) noexcept { return input.size() >= test.size() && 0 == input.compare(0, test.size(), test); } bool ends_with(str_view input, str_view test) noexcept { return input.size() >= test.size() && 0 == input.compare(input.size() - test.size(), test.size(), test); } }
25.979472
85
0.531098
NechukhrinN
2d58fdfda68d9263cfd696c601afefbff3d1f671
15,221
cpp
C++
Libs/Db/src/LegacyDataset.cpp
n8vm/OpenVisus
dab633f6ecf13ffcf9ac2ad47d51e48902d4aaef
[ "Unlicense" ]
1
2019-04-30T12:11:24.000Z
2019-04-30T12:11:24.000Z
Libs/Db/src/LegacyDataset.cpp
tjhei/OpenVisus
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
[ "Unlicense" ]
null
null
null
Libs/Db/src/LegacyDataset.cpp
tjhei/OpenVisus
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
[ "Unlicense" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright(c) 2010 - 2018 ViSUS L.L.C., Scientific Computing and Imaging Institute of the University of Utah ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. For additional information about this project contact : pascucci@acm.org For support : support@visus.net -----------------------------------------------------------------------------*/ #include <Visus/LegacyDataset.h> #include <Visus/Access.h> #include <Visus/NetService.h> namespace Visus { ////////////////////////////////////////////////////////////// class LegacyAccess : public Access { public: LegacyDataset* dataset; StringTree config; Url url; SharedPtr<NetService> netservice; //constructor LegacyAccess(LegacyDataset* dataset_,StringTree config_=StringTree()) : dataset(dataset_),config(config_) { this->name = "LegacyAccess"; this->can_read = StringUtils::find(config.readString("chmod", "rw"), "r") >= 0; this->can_write = StringUtils::find(config.readString("chmod", "rw"), "w") >= 0; this->bitsperblock = cint(config.readString("bitsperblock", cstring(dataset->getDefaultBitsPerBlock()))); VisusAssert(this->bitsperblock>0); this->url = config.readString("url",dataset->getUrl().toString()); VisusAssert(url.valid()); this->config.writeString("url", url.toString()); bool disable_async = config.readBool("disable_async", dataset->bServerMode); if (int nconnections = disable_async ? 0 : config.readInt("nconnections", 8)) this->netservice = std::make_shared<NetService>(nconnections); } //destructor virtual ~LegacyAccess(){ } //readBlock virtual void readBlock(SharedPtr<BlockQuery> query) override { auto coord=dataset->getTileCoordinate(query->start_address,query->end_address); int X=coord.x; int Y=coord.y; int Z=coord.z; //mirror along Y Y=(int)((1<<Z)-Y-1); Url url=dataset->getUrl(); url.params.clear(); url.setParam("x",cstring(X)); url.setParam("y",cstring(Y)); url.setParam("z",cstring(Z)); auto request=NetRequest(url); if (!request.valid()) return readFailed(query); request.aborted=query->aborted; //note [...,query] keep the query in memory NetService::push(netservice, request).when_ready([this, query](NetResponse response) { NdPoint nsamples = NdPoint::one(2); nsamples[0] = dataset->tile_nsamples.x; nsamples[1] = dataset->tile_nsamples.y; response.setHeader("visus-compression", dataset->tile_compression); response.setHeader("visus-nsamples", nsamples.toString()); response.setHeader("visus-dtype", query->field.dtype.toString()); response.setHeader("visus-layout", ""); if (query->aborted() || !response.isSuccessful()) return readFailed(query); auto decoded = response.getArrayBody(); if (!decoded) return readFailed(query); VisusAssert(decoded.dims == query->nsamples); VisusAssert(decoded.dtype == query->field.dtype); query->buffer = decoded; return readOk(query); }); } //writeBlock virtual void writeBlock(SharedPtr<BlockQuery> query) override { VisusAssert(false);//not supported writeFailed(query); } //printStatistics virtual void printStatistics() override { VisusInfo() << name << " hostname(" << url.getHostname() << ") port(" << url.getPort() << ") url(" << url.toString() << ")"; Access::printStatistics(); } }; ////////////////////////////////////////////////////////////// bool LegacyDataset::beginQuery(SharedPtr<Query> query) { if (!Dataset::beginQuery(query)) return false; VisusAssert(query->start_resolution==0); VisusAssert(query->max_resolution==this->getBitmask().getMaxResolution()); //i don't have odd resolutions { std::vector<int> end_resolutions=query->end_resolutions; std::vector<int> even_end_resolutions; for (int I=0;I<(int)end_resolutions.size();I++) { int even_end_resolution=(end_resolutions[I]>>1)<<1; if (even_end_resolutions.empty() || even_end_resolutions.back()!=even_end_resolution) even_end_resolutions.push_back(even_end_resolution); } query->end_resolutions=even_end_resolutions; } //writing is not supported if (query->mode=='w') { query->setFailed("Writing mode not suppoted"); return false; } Position position=query->position; //not supported if (!position.getTransformation().isIdentity()) { query->setFailed("Position has non-identity transformation"); return false; } auto user_box= query->position.getNdBox().getIntersection(this->getBox()); if (!user_box.isFullDim()) { query->setFailed("user_box not valid"); return false; } query->setRunning(); std::vector<int> end_resolutions=query->end_resolutions; for (query->query_cursor=0;query->query_cursor<(int)end_resolutions.size();query->query_cursor++) { if (setCurrentEndResolution(query)) return true; } query->setFailed("Cannot find a good initial resolution"); return false; } ////////////////////////////////////////////////////////////// void LegacyDataset::kdTraverse(std::vector< SharedPtr<BlockQuery> >& block_queries,SharedPtr<Query> query,NdBox box,BigInt id,int H,int end_resolution) { if (query->aborted()) return; if (!box.getIntersection(query->position.getNdBox()).isFullDim()) return; int samplesperblock=1<<this->getDefaultBitsPerBlock(); if (H==end_resolution) { VisusAssert(H % 2==0); BigInt start_address=(id-1)*samplesperblock; BigInt end_address =start_address+samplesperblock; auto block_query=std::make_shared<BlockQuery>(query->field,query->time,start_address,end_address,query->aborted); block_queries.push_back(block_query); return; } DatasetBitmask bitmask=this->getBitmask(); int split_bit=bitmask[1+H - this->getDefaultBitsPerBlock()]; NdPoint::coord_t middle=(box.p1[split_bit]+box.p2[split_bit])>>1; auto left_box =box; left_box .p2[split_bit]=middle; auto right_box =box; right_box.p1[split_bit]=middle; kdTraverse(block_queries,query,left_box ,id*2+0,H+1,end_resolution); kdTraverse(block_queries,query,right_box,id*2+1,H+1,end_resolution); } ////////////////////////////////////////////////////////////// bool LegacyDataset::executeQuery(SharedPtr<Access> access,SharedPtr<Query> query) { if (!Dataset::executeQuery(access,query)) return false; if (!query->allocateBufferIfNeeded()) { query->setFailed("cannot allocate buffer"); return false; } //always need an access.. the google server cannot handle pure remote queries (i.e. compose the tiles on server side) if (!access) access=std::make_shared<LegacyAccess>(this); int end_resolution=query->getEndResolution(); VisusAssert(end_resolution % 2==0); WaitAsync< Future<Void> > wait_async; NdBox box=this->getBox(); std::vector< SharedPtr<BlockQuery> > block_queries; kdTraverse(block_queries,query,box,/*id*/1,/*H*/this->getDefaultBitsPerBlock(),end_resolution); access->beginRead(); { for (auto block_query : block_queries) { wait_async.pushRunning(readBlock(access,block_query)).when_ready([this,query, block_query](Void) { if (!query->aborted() && block_query->ok()) mergeQueryWithBlock(query, block_query); }); } } access->endRead(); wait_async.waitAllDone(); query->currentLevelReady(); return true; } ////////////////////////////////////////////////////////////// bool LegacyDataset::nextQuery(SharedPtr<Query> query) { if (!Dataset::nextQuery(query)) return false; //merging is not supported query->buffer=Array(); if (!setCurrentEndResolution(query)) { query->setFailed("cannot set end resolution"); return false; } else { return true; } } ////////////////////////////////////////////////////////////// bool LegacyDataset::mergeQueryWithBlock(SharedPtr<Query> query,SharedPtr<BlockQuery> blockquery) { return Query::mergeSamples(query->logic_box, query->buffer, blockquery->logic_box, blockquery->buffer, Query::InsertSamples, query->aborted); } ////////////////////////////////////////////////////////////// SharedPtr<Access> LegacyDataset::createAccess(StringTree config, bool bForBlockQuery) { VisusAssert(this->valid()); if (config.empty()) config = getDefaultAccessConfig(); String type = StringUtils::toLower(config.readString("type")); //I always need an access if (type.empty()) return std::make_shared<LegacyAccess>(this, config); //LegacyAccess if (type=="legacyaccess") return std::make_shared<LegacyAccess>(this, config); return Dataset::createAccess(config, bForBlockQuery); } ////////////////////////////////////////////////////////////// std::vector<int> LegacyDataset::guessEndResolutions(const Frustum& viewdep,Position position,Query::Quality quality,Query::Progression progression) { std::vector<int> ret=Dataset::guessEndResolutions(viewdep,position,quality,progression); for (int I=0;I<(int)ret.size();I++) ret[I]=(ret[I]>>1)<<1; //i don't have even resolution return ret; } ////////////////////////////////////////////////////////////// Point3i LegacyDataset::getTileCoordinate(BigInt start_address,BigInt end_address) { int bitsperblock=this->getDefaultBitsPerBlock(); int samplesperblock=((BigInt)1)<<bitsperblock; VisusAssert(end_address==start_address+samplesperblock); Int64 blocknum=cint64(start_address>>bitsperblock); int H=bitsperblock+Utils::getLog2(1+blocknum); VisusAssert((H % 2)==0); Int64 first_block_in_level=(((Int64)1)<<(H-bitsperblock))-1; NdPoint tile_coord=bitmask.deinterleave(blocknum-first_block_in_level,H-bitsperblock); return Point3i( (int)(tile_coord[0]), (int)(tile_coord[1]), (H-bitsperblock)>>1); } ////////////////////////////////////////////////////////////// LogicBox LegacyDataset::getAddressRangeBox(BigInt start_address,BigInt end_address) { auto coord=getTileCoordinate(start_address,end_address); int X=coord.x; int Y=coord.y; int Z=coord.z; int tile_width =(int)(this->getBox().p2[0])>>Z; int tile_height=(int)(this->getBox().p2[1])>>Z; NdPoint delta=NdPoint::one(2); delta[0]=tile_width /this->tile_nsamples.x; delta[1]=tile_height/this->tile_nsamples.y; NdBox box(NdPoint(2), NdPoint::one(2)); box.p1[0] = tile_width * (X + 0); box.p2[0] = tile_width * (X + 1); box.p1[1] = tile_height * (Y + 0); box.p2[1] = tile_height * (Y + 1); return LogicBox(box,delta); } ////////////////////////////////////////////////////////////// bool LegacyDataset::openFromUrl(Url url) { this->tile_nsamples.x = cint(url.getParam("tile_width" ,"0")); this->tile_nsamples.y = cint(url.getParam("tile_height","0")); int nlevels = cint(url.getParam("nlevels","0")) ; this->tile_compression = url.getParam("compression") ; this->dtype = DType::fromString(url.getParam("dtype")); if (tile_nsamples.x<=0 || tile_nsamples.y<=0 || !nlevels || !dtype.valid() || tile_compression.empty()) { VisusAssert(false); this->invalidate(); return false; } //any google level double the dimensions in x and y (i.e. i don't have even resolutions) NdPoint overall_dims=NdPoint::one(2); overall_dims[0]=tile_nsamples.x * (((NdPoint::coord_t)1)<<nlevels); overall_dims[1]=tile_nsamples.y * (((NdPoint::coord_t)1)<<nlevels); this->url=url.toString(); this->bitmask=DatasetBitmask::guess(overall_dims); this->default_bitsperblock=Utils::getLog2(tile_nsamples.x*tile_nsamples.y); this->box=NdBox(NdPoint(0,0),overall_dims); this->timesteps=DatasetTimesteps(); this->timesteps.addTimestep(0); addField(Field("DATA",dtype)); //UseQuery not supported? actually yes, but it's a nonsense since a query it's really a block query if (this->kdquery_mode==KdQueryMode::UseQuery) this->kdquery_mode=KdQueryMode::UseBlockQuery; return true; } ////////////////////////////////////////////////////////////// LogicBox LegacyDataset::getLevelBox(int H) { int bitsperblock=this->getDefaultBitsPerBlock(); VisusAssert((H%2)==0 && H>=bitsperblock); int Z=(H-bitsperblock)>>1; int tile_width =(int)(this->getBox().p2[0])>>Z; int tile_height=(int)(this->getBox().p2[1])>>Z; int ntiles_x=(int)(1<<Z); int ntiles_y=(int)(1<<Z); NdPoint delta=NdPoint::one(2); delta[0]=tile_width /this->tile_nsamples.x; delta[1]=tile_height/this->tile_nsamples.y; NdBox box(NdPoint(0,0), NdPoint::one(1,1)); box.p2[0] = ntiles_x*tile_width; box.p2[1] = ntiles_y*tile_height; auto ret=LogicBox(box,delta); VisusAssert(ret.valid()); return ret; } ////////////////////////////////////////////////////////////// bool LegacyDataset::setCurrentEndResolution(SharedPtr<Query> query) { int end_resolution=query->getEndResolution(); if (end_resolution<0) return false; VisusAssert(end_resolution % 2==0); int max_resolution=query->max_resolution; //necessary condition VisusAssert(query->start_resolution<=end_resolution); VisusAssert(end_resolution<=max_resolution); auto user_box= query->position.getNdBox().getIntersection(this->getBox()); VisusAssert(user_box.isFullDim()); int H=end_resolution; LogicBox Lbox=getLevelBox(end_resolution); NdBox box=Lbox.alignBox(user_box); if (!box.isFullDim()) return false; LogicBox logic_box(box,Lbox.delta); query->nsamples=logic_box.nsamples; query->logic_box=logic_box; query->buffer=Array(); return true; } } //namespace Visus
31.448347
151
0.663228
n8vm
2d5aadae4d03a88a1372ef72d0e2d1dbe87b0a79
1,793
hpp
C++
hld/usb/hld_usb_driver.hpp
brandonbraun653/Thor_STM32
2aaba95728936b2d5784e99b96c208a94e3cb8df
[ "MIT" ]
null
null
null
hld/usb/hld_usb_driver.hpp
brandonbraun653/Thor_STM32
2aaba95728936b2d5784e99b96c208a94e3cb8df
[ "MIT" ]
36
2019-03-24T14:43:25.000Z
2021-01-11T00:05:30.000Z
hld/usb/hld_usb_driver.hpp
brandonbraun653/Thor
46e022f1791c8644955135c630fdd12a4296e44d
[ "MIT" ]
null
null
null
/******************************************************************************** * File Name: * hld_usb_driver.hpp * * Description: * Thor USB high level driver * * 2020 | Brandon Braun | brandonbraun653@gmail.com ********************************************************************************/ #pragma once #ifndef THOR_HLD_USB_HPP #define THOR_HLD_USB_HPP /* C++ Includes */ #include <cstdint> #include <cstdlib> /* Chimera Includes */ #include <Chimera/common> #include <Chimera/usb> #include <Chimera/thread> /* Thor Includes */ #include <Thor/hld/usb/hld_usb_types.hpp> namespace Thor::USB { /*------------------------------------------------------------------------------- Public Functions -------------------------------------------------------------------------------*/ Chimera::Status_t initialize(); Chimera::Status_t reset(); Driver_rPtr getDriver( const Chimera::USB::Channel ch ); /*------------------------------------------------------------------------------- Classes -------------------------------------------------------------------------------*/ /** * USB Peripheral Driver * Methods here at a minimum implement the interface specified in Chimera. * Inheritance is avoided to minimize cost of virtual function lookup table. */ class Driver : public Chimera::Thread::Lockable<Driver> { public: Driver(); ~Driver(); /*------------------------------------------------- Interface: Hardware -------------------------------------------------*/ Chimera::Status_t open( const Chimera::USB::PeriphConfig &cfg ); void close(); private: friend Chimera::Thread::Lockable<Driver>; Chimera::USB::Channel mChannel; }; } // namespace Thor::USB #endif /* THOR_HLD_USB_HPP */
27.166667
83
0.452872
brandonbraun653
2d5b922bd699638d8abf206102207bccd7b5f96b
614
cpp
C++
solutions/729.my-calendar-i.254107150.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/729.my-calendar-i.254107150.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/729.my-calendar-i.254107150.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class MyCalendar { map<int, int> mp; public: MyCalendar() {} bool book(int start, int end) { auto it1 = mp.lower_bound(start); if (it1 != mp.end() && it1->first == start) return false; if (it1 != mp.end() && it1->first < end) return false; if (mp.size() && it1 != mp.begin()) { --it1; if (it1->second > start) return false; } // return false; mp[start] = end; return true; } }; /** * Your MyCalendar object will be instantiated and called as such: * MyCalendar* obj = new MyCalendar(); * bool param_1 = obj->book(start,end); */
17.055556
66
0.552117
satu0king
2d5c8a2966ce7dade5b76f6074cf52aed4df5f72
31,088
cpp
C++
base/fs/rdr2/rdpdr/drkdx/rdpdrkd.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/rdr2/rdpdr/drkdx/rdpdrkd.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/rdr2/rdpdr/drkdx/rdpdrkd.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1990 Microsoft Corporation Module Name: rdpdrkd.c Abstract: Redirector Kernel Debugger extension Author: Balan Sethu Raman (SethuR) 11-May-1994 Revision History: 11-Nov-1994 SethuR Created --*/ #define KDEXT_32BIT #include "rx.h" // NT network file system driver include file #include "ntddnfs2.h" // new stuff device driver definitions #include <pchannel.h> #include <tschannl.h> #include <rdpdr.h> #include "rdpdrp.h" #include "namespc.h" #include "strcnv.h" #include "dbg.h" #include "topobj.h" #include "smartptr.h" #include "kernutil.h" #include "isession.h" #include "iexchnge.h" #include "channel.h" #include "device.h" #include "prnport.h" #include "serport.h" #include "parport.h" #include "devmgr.h" #include "exchnge.h" #include "session.h" #include "sessmgr.h" #include "rdpdyn.h" #include "rdpevlst.h" #include "rdpdrpnp.h" #include "rdpdrprt.h" #include "trc.h" #include <string.h> #include <stdio.h> #include <kdextlib.h> #include <rdpdrkd.h> /* * RDPDR global variables. * */ LPSTR GlobalBool[] = { 0}; LPSTR GlobalShort[] = {0}; LPSTR GlobalLong[] = { 0}; LPSTR GlobalPtrs[] = { "rdpdr!RxExpCXR", "rdpdr!RxExpEXR", "rdpdr!RxExpAddr", "rdpdr!RxExpCode", "rdpdr!RxActiveContexts", "rdpdr!RxNetNameTable", "rdpdr!RxProcessorArchitecture", "rdpdr!RxBuildNumber", "rdpdr!RxPrivateBuild", "rdpdr!ClientList", 0}; /* * IRP_CONTEXT debugging. * */ FIELD_DESCRIPTOR RxContextFields[] = { FIELD3(FieldTypeUShort,RX_CONTEXT,NodeTypeCode), FIELD3(FieldTypeShort,RX_CONTEXT,NodeByteSize), FIELD3(FieldTypeULong,RX_CONTEXT,ReferenceCount), FIELD3(FieldTypeULong,RX_CONTEXT,SerialNumber), FIELD3(FieldTypeStruct,RX_CONTEXT,WorkQueueItem), FIELD3(FieldTypePointer,RX_CONTEXT,CurrentIrp), FIELD3(FieldTypePointer,RX_CONTEXT,CurrentIrpSp), FIELD3(FieldTypePointer,RX_CONTEXT,pFcb), FIELD3(FieldTypePointer,RX_CONTEXT,pFobx), //FIELD3(FieldTypePointer,RX_CONTEXT,pRelevantSrvOpen), FIELD3(FieldTypePointer,RX_CONTEXT,LastExecutionThread), #ifdef RDBSS_TRACKER FIELD3(FieldTypePointer,RX_CONTEXT,AcquireReleaseFcbTrackerX), #endif FIELD3(FieldTypePointer,RX_CONTEXT,MRxContext[2]), FIELD3(FieldTypeSymbol,RX_CONTEXT,ResumeRoutine), FIELD3(FieldTypePointer,RX_CONTEXT,RealDevice), FIELD3(FieldTypeULongFlags,RX_CONTEXT,Flags), FIELD3(FieldTypeChar,RX_CONTEXT,MajorFunction), FIELD3(FieldTypeChar,RX_CONTEXT,MinorFunction), FIELD3(FieldTypeULong,RX_CONTEXT,StoredStatus), FIELD3(FieldTypeStruct,RX_CONTEXT,SyncEvent), FIELD3(FieldTypeStruct,RX_CONTEXT,RxContextSerializationQLinks), FIELD3(FieldTypeStruct,RX_CONTEXT,Create), FIELD3(FieldTypeStruct,RX_CONTEXT,LowIoContext), FIELD3(FieldTypePointer,RX_CONTEXT,Create.NetNamePrefixEntry), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pSrvCall), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pNetRoot), FIELD3(FieldTypePointer,RX_CONTEXT,Create.pVNetRoot), //FIELD3(FieldTypePointer,RX_CONTEXT,Create.pSrvOpen), FIELDLAST }; /* * SRV_CALL debugging. * */ //CODE.IMPROVEMENT we should have a fieldtype for prefixentry that // will print out the names FIELD_DESCRIPTOR SrvCallFields[] = { FIELD3(FieldTypeUShort,SRV_CALL,NodeTypeCode), FIELD3(FieldTypeShort,SRV_CALL,NodeByteSize), FIELD3(FieldTypeStruct,SRV_CALL,PrefixEntry), FIELD3(FieldTypeUnicodeString,SRV_CALL,PrefixEntry.Prefix), FIELD3(FieldTypePointer,SRV_CALL,Context), FIELD3(FieldTypePointer,SRV_CALL,Context2), FIELD3(FieldTypeULong,SRV_CALL,Flags), FIELDLAST }; /* * NET_ROOT debugging. * */ FIELD_DESCRIPTOR NetRootFields[] = { FIELD3(FieldTypeUShort,NET_ROOT,NodeTypeCode), FIELD3(FieldTypeShort,NET_ROOT,NodeByteSize), FIELD3(FieldTypeULong,NET_ROOT,NodeReferenceCount), FIELD3(FieldTypeStruct,NET_ROOT,PrefixEntry), FIELD3(FieldTypeUnicodeString,NET_ROOT,PrefixEntry.Prefix), FIELD3(FieldTypeStruct,NET_ROOT,FcbTable), //FIELD3(FieldTypePointer,NET_ROOT,Dispatch), FIELD3(FieldTypePointer,NET_ROOT,Context), FIELD3(FieldTypePointer,NET_ROOT,Context2), FIELD3(FieldTypePointer,NET_ROOT,pSrvCall), FIELD3(FieldTypeULong,NET_ROOT,Flags), FIELDLAST }; /* * V_NET_ROOT debugging. * */ FIELD_DESCRIPTOR VNetRootFields[] = { FIELD3(FieldTypeUShort,V_NET_ROOT,NodeTypeCode), FIELD3(FieldTypeShort,V_NET_ROOT,NodeByteSize), FIELD3(FieldTypeULong,V_NET_ROOT,NodeReferenceCount), FIELD3(FieldTypeStruct,V_NET_ROOT,PrefixEntry), FIELD3(FieldTypeUnicodeString,V_NET_ROOT,PrefixEntry.Prefix), FIELD3(FieldTypeUnicodeString,V_NET_ROOT,NamePrefix), FIELD3(FieldTypePointer,V_NET_ROOT,Context), FIELD3(FieldTypePointer,V_NET_ROOT,Context2), FIELD3(FieldTypePointer,V_NET_ROOT,pNetRoot), FIELDLAST }; /* * FCB debugging. * */ FIELD_DESCRIPTOR FcbFields[] = { FIELD3(FieldTypeUShort,FCB,Header.NodeTypeCode), FIELD3(FieldTypeShort,FCB,Header.NodeByteSize), FIELD3(FieldTypeULong,FCB,NodeReferenceCount), FIELD3(FieldTypeULong,FCB,FcbState), FIELD3(FieldTypeULong,FCB,OpenCount), FIELD3(FieldTypeULong,FCB,UncleanCount), FIELD3(FieldTypePointer,FCB,Header.Resource), FIELD3(FieldTypePointer,FCB,Header.PagingIoResource), FIELD3(FieldTypeStruct,FCB,FcbTableEntry), FIELD3(FieldTypeUnicodeString,FCB,PrivateAlreadyPrefixedName), FIELD3(FieldTypePointer,FCB,VNetRoot), FIELD3(FieldTypePointer,FCB,pNetRoot), FIELD3(FieldTypePointer,FCB,Context), FIELD3(FieldTypePointer,FCB,Context2), FIELDLAST }; /* * SRV_OPEN debugging. * */ FIELD_DESCRIPTOR SrvOpenFields[] = { FIELD3(FieldTypeShort,SRV_OPEN,NodeTypeCode), FIELD3(FieldTypeShort,SRV_OPEN,NodeByteSize), FIELD3(FieldTypeULong,SRV_OPEN,NodeReferenceCount), FIELD3(FieldTypePointer,SRV_OPEN,pFcb), FIELD3(FieldTypeULong,SRV_OPEN,Flags), FIELDLAST }; /* * FOBX debugging. * */ FIELD_DESCRIPTOR FobxFields[] = { FIELD3(FieldTypeShort,FOBX,NodeTypeCode), FIELD3(FieldTypeShort,FOBX,NodeByteSize), FIELD3(FieldTypeULong,FOBX,NodeReferenceCount), FIELD3(FieldTypePointer,FOBX,pSrvOpen), FIELDLAST }; //this enum is used in the definition of the structures that can be dumped....the order here //is not important, only that there is a definition for each dumpee structure..... typedef enum _STRUCTURE_IDS { StrEnum_RX_CONTEXT = 1, StrEnum_FCB, StrEnum_SRV_OPEN, StrEnum_FOBX, StrEnum_SRV_CALL, StrEnum_NET_ROOT, StrEnum_V_NET_ROOT, StrEnum_CHANNELAPCCONTEXT, StrEnum_TopObj, StrEnum_DrExchangeManager, StrEnum_DrExchange, StrEnum_DrIoContext, StrEnum_DrDeviceManager, StrEnum_DoubleList, StrEnum_KernelResource, StrEnum_VirtualChannel, StrEnum_DrDevice, StrEnum_DrPrinterPort, StrEnum_DrParallelPort, StrEnum_DrSerialPort, StrEnum_DrSessionManager, StrEnum_DrSession, StrEnum_ReferenceTraceRecord, StrEnum_SESSIONLISTNODE, StrEnum_EVENTLISTNODE, StrEnum_RDPDR_IOCOMPLETION_PACKET, StrEnum_RDPDR_IOREQUEST_PACKET, StrEnum_RDPDR_UPDATE_DEVICEINFO_PACKET, StrEnum_RDPDR_DEVICE_REPLY_PACKET, StrEnum_RDPDR_DEVICELIST_ANNOUNCE_PACKET, StrEnum_RDPDR_DEVICE_ANNOUNCE, StrEnum_RDPDR_CLIENT_NAME_PACKET, StrEnum_RDPDR_CLIENT_CONFIRM_PACKET, StrEnum_RDPDR_SERVER_ANNOUNCE_PACKET, StrEnum_RDPDR_HEADER, StrEnum_TRC_CONFIG, StrEnum_TRC_PREFIX_DATA, StrEnum_last }; // 1) All ENUM_VALUE_DESCRIPTOR definitions are named EnumValueDescrsOf_ENUMTYPENAME, where // ENUMTYPENAME defines the corresponding enumerated type. // ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_STATUS [] = { {0, "dsAvailable"}, {1, "dsDisabled"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_TYPE [] = { {1, "RDPDR_DTYP_SERIAL"}, {2, "RDPDR_DTYP_PARALLEL"}, {3, "RDPDR_DTYP_FILE"}, {4, "RDPDR_DTYP_PRINT"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_CLIENT_STATUS [] = { {0, "csDisconnected"}, {1, "csPendingClientConfirm"}, {2, "csPendingClientReconfirm"}, {3, "csConnected"}, {4, "csExpired"}, {0, NULL} }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_ExchangeManagerState [] = { {0, "demsStopped"}, {1, "demsStarted"}, {0, NULL} }; #if DBG #define TOPOBJFIELDS(ObjTyp) \ FIELD3(FieldTypeBoolean, ObjTyp, _IsValid), \ FIELD3(FieldTypeULong, ObjTyp, _ObjectType), \ FIELD3(FieldTypeBoolean, ObjTyp, _ForceTrace), \ FIELD3(FieldTypePointer, ObjTyp, _ClassName), \ FIELD3(FieldTypeULong, ObjTyp, _magicNo) #else // DBG #define TOPOBJFIELDS(ObjTyp) \ FIELD3(FieldTypeBoolean, ObjTyp, _IsValid), \ FIELD3(FieldTypeULong, ObjTyp, _ObjectType) #endif // DBG FIELD_DESCRIPTOR TopObjFields[] = { TOPOBJFIELDS(TopObj), FIELDLAST }; FIELD_DESCRIPTOR DrExchangeManagerFields[] = { TOPOBJFIELDS(DrExchangeManager), FIELD3(FieldTypePointer, DrExchangeManager, _RxMidAtlas), FIELD4(FieldTypeEnum, DrExchangeManager, _demsState, EnumValueDescrsOf_ExchangeManagerState), FIELD3(FieldTypePointer, DrExchangeManager, _Session), FIELDLAST }; FIELD_DESCRIPTOR DrExchangeFields[] = { TOPOBJFIELDS(DrExchange), FIELD3(FieldTypeULong, DrExchange, _crefs), FIELD3(FieldTypePointer, DrExchange, _ExchangeManager), FIELD3(FieldTypePointer, DrExchange, _Context), FIELD3(FieldTypePointer, DrExchange, _ExchangeUser), FIELD3(FieldTypeUShort, DrExchange, _Mid), FIELDLAST }; FIELD_DESCRIPTOR DrIoContextFields[] = { TOPOBJFIELDS(DrIoContext), FIELD3(FieldTypePointer, DrIoContext, _Device), FIELD3(FieldTypeBool, DrIoContext, _Busy), FIELD3(FieldTypeBool, DrIoContext, _Cancelled), FIELD3(FieldTypeBool, DrIoContext, _Disconnected), FIELD3(FieldTypePointer, DrIoContext, _RxContext), FIELD3(FieldTypeChar, DrIoContext, _MajorFunction), FIELD3(FieldTypeChar, DrIoContext, _MinorFunction), FIELDLAST }; FIELD_DESCRIPTOR DrDeviceManagerFields[] = { TOPOBJFIELDS(DrDeviceManager), FIELD3(FieldTypeStruct, DrDeviceManager, _DeviceList), FIELD3(FieldTypePointer, DrDeviceManager, _Session), FIELDLAST }; FIELD_DESCRIPTOR DoubleListFields[] = { TOPOBJFIELDS(DoubleList), FIELD3(FieldTypeStruct, DoubleList, _List), FIELDLAST }; FIELD_DESCRIPTOR KernelResourceFields[] = { TOPOBJFIELDS(KernelResource), FIELD3(FieldTypeStruct, KernelResource, _Resource), FIELDLAST }; FIELD_DESCRIPTOR VirtualChannelFields[] = { TOPOBJFIELDS(VirtualChannel), FIELD3(FieldTypeULong, VirtualChannel, _crefs), FIELD3(FieldTypePointer, VirtualChannel, _Channel), FIELD3(FieldTypeStruct, VirtualChannel, _HandleLock), FIELD3(FieldTypePointer, VirtualChannel, _DeletionEvent), FIELDLAST }; #define DRDEVICEFIELDS(ObjType) \ TOPOBJFIELDS(ObjType), \ FIELD3(FieldTypeULong, ObjType, _crefs), \ FIELD3(FieldTypeStruct, ObjType, _Session), \ FIELD3(FieldTypeULong, ObjType, _DeviceId), \ FIELD4(FieldTypeEnum, ObjType, _DeviceType, EnumValueDescrsOf_DEVICE_TYPE), \ FIELD3(FieldTypeStruct, ObjType, _PreferredDosName), \ FIELD4(FieldTypeEnum, ObjType, _DeviceStatus, EnumValueDescrsOf_DEVICE_STATUS) FIELD_DESCRIPTOR DrDeviceFields[] = { DRDEVICEFIELDS(DrDevice), FIELDLAST }; #define DRPRINTERPORTFIELDS(ObjType) \ DRDEVICEFIELDS(ObjType), \ FIELD3(FieldTypeULong, ObjType, _PortNumber), \ FIELD3(FieldTypeStruct, ObjType, _SymbolicLinkName), \ FIELD3(FieldTypeBool, ObjType, _IsOpen) FIELD_DESCRIPTOR DrPrinterPortFields[] = { DRPRINTERPORTFIELDS(DrPrinterPort), FIELDLAST }; FIELD_DESCRIPTOR DrParallelPortFields[] = { DRPRINTERPORTFIELDS(DrParallelPort), FIELDLAST }; FIELD_DESCRIPTOR DrSerialPortFields[] = { DRPRINTERPORTFIELDS(DrSerialPort), FIELDLAST }; FIELD_DESCRIPTOR DrSessionManagerFields[] = { TOPOBJFIELDS(DrSessionManager), FIELD3(FieldTypeStruct, DrSessionManager, _SessionList), FIELDLAST }; FIELD_DESCRIPTOR DrSessionFields[] = { TOPOBJFIELDS(DrSession), FIELD3(FieldTypeULong, DrSession, _crefs), FIELD3(FieldTypeStruct, DrSession, _Channel), FIELD3(FieldTypeStruct, DrSession, _PacketReceivers), FIELD3(FieldTypeStruct, DrSession, _ConnectNotificatingLock), FIELD3(FieldTypeStruct, DrSession, _ChannelLock), FIELD4(FieldTypeEnum, DrSession, _SessionState, EnumValueDescrsOf_CLIENT_STATUS), FIELD3(FieldTypePointer, DrSession, _ChannelBuffer), FIELD3(FieldTypeULong, DrSession, _ChannelBufferSize), FIELD3(FieldTypeStruct, DrSession, _ChannelDeletionEvent), FIELD3(FieldTypeULong, DrSession, _ReadStatus.Status), FIELD3(FieldTypeULong, DrSession, _ReadStatus.Information), FIELD3(FieldTypeULong, DrSession, _ClientId), FIELD3(FieldTypeStruct, DrSession, _ExchangeManager), FIELD3(FieldTypeULong, DrSession, _PartialPacketData), FIELD3(FieldTypeStruct, DrSession, _ClientName), FIELD3(FieldTypeStruct, DrSession, _DeviceManager), FIELD3(FieldTypeULong, DrSession, _SessionId), FIELD3(FieldTypeUShort, DrSession, _ClientVersion.Major), FIELD3(FieldTypeUShort, DrSession, _ClientVersion.Major), FIELD3(FieldTypeLong, DrSession, _Initialized), FIELDLAST }; typedef struct tagCHANNELAPCCONTEXT { SmartPtr<VirtualChannel> Channel; PIO_APC_ROUTINE ApcRoutine; PVOID ApcContext; } CHANNELAPCCONTEXT, *PCHANNELAPCCONTEXT; FIELD_DESCRIPTOR ChannelApcContextFields[] = { FIELD3(FieldTypeStruct, CHANNELAPCCONTEXT, Channel), FIELD3(FieldTypePointer, CHANNELAPCCONTEXT, ApcRoutine), FIELD3(FieldTypePointer, CHANNELAPCCONTEXT, ApcContext), FIELDLAST }; #if DBG FIELD_DESCRIPTOR ReferenceTraceRecordFields[] = { FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[0]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[1]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[2]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[3]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[4]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[5]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[6]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[7]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[8]), FIELD3(FieldTypeSymbol, ReferenceTraceRecord, Stack[9]), FIELD3(FieldTypePointer, ReferenceTraceRecord, pRefCount), FIELD3(FieldTypePointer, ReferenceTraceRecord, ClassName), FIELD3(FieldTypeLong, ReferenceTraceRecord, refs), FIELDLAST }; #endif FIELD_DESCRIPTOR SESSIONLISTNODEFields[] = { #if DBG FIELD3(FieldTypeULong, SESSIONLISTNODE, magicNo), #endif FIELD3(FieldTypeULong, SESSIONLISTNODE, sessionID), FIELD3(FieldTypeStruct, SESSIONLISTNODE, requestListHead), FIELD3(FieldTypeStruct, SESSIONLISTNODE, eventListHead), FIELD3(FieldTypeStruct, SESSIONLISTNODE, listEntry), FIELDLAST }; FIELD_DESCRIPTOR EVENTLISTNODEFields[] = { #if DBG FIELD3(FieldTypeULong, EVENTLISTNODE, magicNo), #endif FIELD3(FieldTypePointer, EVENTLISTNODE, event), FIELD3(FieldTypeULong, EVENTLISTNODE, type), FIELD3(FieldTypeStruct, EVENTLISTNODE, listEntry), FIELDLAST }; #define RDPDRPACKETCODE(Component, PacketId) \ MAKELONG(Component, PacketId) ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_PACKET_CODE [] = { {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_SERVER_ANNOUNCE), "RDPDR_SERVER_ANNOUNCE_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_CLIENTID_CONFIRM), "DR_CORE_CLIENTID_CONFIRM_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_CLIENT_NAME), "DR_CORE_CLIENT_NAME_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_ANNOUNCE), "DR_CORE_DEVICE_ANNOUNCE@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICELIST_ANNOUNCE), "DR_CORE_DEVICELIST_ANNOUNCE_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICELIST_REPLY), "DR_CORE_DEVICELIST_REPLY_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_REPLY), "DR_CORE_DEVICE_REPLY_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_IOREQUEST), "DR_CORE_DEVICE_IOREQUEST_PACKET@"}, {RDPDRPACKETCODE(RDPDR_CTYP_CORE, DR_CORE_DEVICE_IOCOMPLETION), "DR_CORE_DEVICE_IOCOMPLETION_PACKET@"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrHeaderFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELDLAST }; FIELD_DESCRIPTOR RdpdrServerAnnounceFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeUShort, RDPDR_SERVER_ANNOUNCE_PACKET, VersionInfo.Major), FIELD3(FieldTypeUShort, RDPDR_SERVER_ANNOUNCE_PACKET, VersionInfo.Minor), FIELD3(FieldTypeULong, RDPDR_SERVER_ANNOUNCE_PACKET, ServerAnnounce.ClientId), FIELDLAST }; FIELD_DESCRIPTOR RdpdrClientConfirmFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeUShort, RDPDR_CLIENT_CONFIRM_PACKET, VersionInfo.Major), FIELD3(FieldTypeUShort, RDPDR_CLIENT_CONFIRM_PACKET, VersionInfo.Minor), FIELD3(FieldTypeULong, RDPDR_CLIENT_CONFIRM_PACKET, ClientConfirm.ClientId), FIELDLAST }; FIELD_DESCRIPTOR RdpdrClientNameFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), // FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, (ULONG)Name.Unicode), FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, Name.CodePage), FIELD3(FieldTypeULong, RDPDR_CLIENT_NAME_PACKET, Name.ComputerNameLen), FIELDLAST }; FIELD_DESCRIPTOR RdpdrDeviceAnnounceFields[] = { FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceType), FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceId), FIELD3(FieldTypeStruct, RDPDR_DEVICE_ANNOUNCE, PreferredDosName), FIELD3(FieldTypeULong, RDPDR_DEVICE_ANNOUNCE, DeviceDataLength), FIELDLAST }; FIELD_DESCRIPTOR RdpdrDeviceListAnnounceFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_DEVICELIST_ANNOUNCE_PACKET, DeviceListAnnounce.DeviceCount), FIELD3(FieldTypeStruct, RDPDR_DEVICELIST_ANNOUNCE_PACKET, DeviceAnnounce), FIELDLAST }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_DEVICE_REPLY_RESULT [] = { {0, "RDPDR_DEVICE_REPLY_SUCCESS"}, {1, "RDPDR_DEVICE_REPLY_REJECTED"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrDeviceReplyFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_DEVICE_REPLY_PACKET, DeviceReply.DeviceId), FIELD4(FieldTypeEnum, RDPDR_DEVICE_REPLY_PACKET, DeviceReply.ResultCode, EnumValueDescrsOf_DEVICE_REPLY_RESULT ), FIELDLAST }; FIELD_DESCRIPTOR RdpdrUpdateDeviceInfoFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_UPDATE_DEVICEINFO_PACKET, DeviceUpdate.DeviceId), FIELD3(FieldTypeULong, RDPDR_UPDATE_DEVICEINFO_PACKET, DeviceUpdate.DeviceDataLength), FIELDLAST }; ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_MAJOR_FUNCTION [] = { {0x00, "IRP_MJ_CREATE"}, {0x01, "IRP_MJ_CREATE_NAMED_PIPE"}, {0x02, "IRP_MJ_CLOSE"}, {0x03, "IRP_MJ_READ"}, {0x04, "IRP_MJ_WRITE"}, {0x05, "IRP_MJ_QUERY_INFORMATION"}, {0x06, "IRP_MJ_SET_INFORMATION"}, {0x07, "IRP_MJ_QUERY_EA"}, {0x08, "IRP_MJ_SET_EA"}, {0x09, "IRP_MJ_FLUSH_BUFFERS"}, {0x0a, "IRP_MJ_QUERY_VOLUME_INFORMATION"}, {0x0b, "IRP_MJ_SET_VOLUME_INFORMATION"}, {0x0c, "IRP_MJ_DIRECTORY_CONTROL"}, {0x0d, "IRP_MJ_FILE_SYSTEM_CONTROL"}, {0x0e, "IRP_MJ_DEVICE_CONTROL"}, {0x0f, "IRP_MJ_INTERNAL_DEVICE_CONTROL"}, {0x10, "IRP_MJ_SHUTDOWN"}, {0x11, "IRP_MJ_LOCK_CONTROL"}, {0x12, "IRP_MJ_CLEANUP"}, {0x13, "IRP_MJ_CREATE_MAILSLOT"}, {0x14, "IRP_MJ_QUERY_SECURITY"}, {0x15, "IRP_MJ_SET_SECURITY"}, {0x16, "IRP_MJ_POWER"}, {0x17, "IRP_MJ_SYSTEM_CONTROL"}, {0x18, "IRP_MJ_DEVICE_CHANGE"}, {0x19, "IRP_MJ_QUERY_QUOTA"}, {0x1a, "IRP_MJ_SET_QUOTA"}, {0x1b, "IRP_MJ_PNP"}, {0x1b, "IRP_MJ_MAXIMUM_FUNCTION"}, {0, NULL} }; FIELD_DESCRIPTOR RdpdrIoRequestFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.DeviceId), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.FileId), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.CompletionId), FIELD4(FieldTypeEnum, RDPDR_IOREQUEST_PACKET, IoRequest.MajorFunction, EnumValueDescrsOf_MAJOR_FUNCTION), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.MinorFunction), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.DesiredAccess), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.AllocationSize.u.HighPart), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.AllocationSize.u.LowPart), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.FileAttributes), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.ShareAccess), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.Disposition), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.CreateOptions), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Create.PathLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Read.Length), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.Write.Length), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.OutputBufferLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.InputBufferLength), FIELD3(FieldTypeULong, RDPDR_IOREQUEST_PACKET, IoRequest.Parameters.DeviceIoControl.IoControlCode), FIELDLAST }; FIELD_DESCRIPTOR RdpdrIoCompletionFields[] = { FIELD3(FieldTypeUShort, RDPDR_HEADER, Component), FIELD3(FieldTypeUShort, RDPDR_HEADER, PacketId), FIELD4(FieldTypeEnum, RDPDR_HEADER, Component, EnumValueDescrsOf_PACKET_CODE), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.DeviceId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.CompletionId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.IoStatus), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Create.FileId), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Read.Length), FIELD3(FieldTypeStruct, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Read.Buffer), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.Write.Length), FIELD3(FieldTypeULong, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.DeviceIoControl.OutputBufferLength), FIELD3(FieldTypeStruct, RDPDR_IOCOMPLETION_PACKET, IoCompletion.Parameters.DeviceIoControl.OutputBuffer), FIELDLAST }; #if DBG ENUM_VALUE_DESCRIPTOR EnumValueDescrsOf_TRACE_LEVEL [] = { {0, "TRC_LEVEL_DBG"}, {1, "TRC_LEVEL_NRM"}, {2, "TRC_LEVEL_ALT"}, {3, "TRC_LEVEL_ERR"}, {4, "TRC_LEVEL_ASSERT"}, {5, "TRC_LEVEL_DIS"}, {0, NULL} }; FIELD_DESCRIPTOR TRC_CONFIGFields[] = { FIELD4(FieldTypeULong, TRC_CONFIG, TraceLevel, EnumValueDescrsOf_TRACE_LEVEL), FIELD3(FieldTypeULong, TRC_CONFIG, FunctionLength), FIELD3(FieldTypeULong, TRC_CONFIG, TraceDebugger), FIELD3(FieldTypeULong, TRC_CONFIG, TraceProfile), FIELD3(FieldTypeStruct, TRC_CONFIG, Prefix[0]), FIELD3(FieldTypeStruct, TRC_CONFIG, Prefix[1]), FIELDLAST }; FIELD_DESCRIPTOR TRC_PREFIX_DATAFields[] = { FIELD3(FieldTypeStruct, TRC_PREFIX_DATA, name), FIELD3(FieldTypeULong, TRC_PREFIX_DATA, start), FIELD3(FieldTypeULong, TRC_PREFIX_DATA, end), FIELDLAST }; #endif // DBG // // List of structs currently handled by the debugger extensions // STRUCT_DESCRIPTOR Structs[] = { STRUCT(RX_CONTEXT,RxContextFields,0xffff,RDBSS_NTC_RX_CONTEXT), STRUCT(FCB,FcbFields,0xeff0,RDBSS_STORAGE_NTC(0)), STRUCT(FCB,FcbFields,0xeff0,RDBSS_STORAGE_NTC(0xf0)), STRUCT(SRV_OPEN,SrvOpenFields,0xffff,RDBSS_NTC_SRVOPEN), STRUCT(FOBX,FobxFields,0xffff,RDBSS_NTC_FOBX), STRUCT(SRV_CALL,SrvCallFields,0xffff,RDBSS_NTC_SRVCALL), STRUCT(NET_ROOT,NetRootFields,0xffff,RDBSS_NTC_NETROOT), STRUCT(V_NET_ROOT,VNetRootFields,0xffff,RDBSS_NTC_V_NETROOT), STRUCT(CHANNELAPCCONTEXT,ChannelApcContextFields,0xffff,0), STRUCT(TopObj,TopObjFields,0xffff,0), STRUCT(DrExchangeManager,DrExchangeManagerFields,0xffff,0), STRUCT(DrExchange,DrExchangeFields,0xffff,0), STRUCT(DrIoContext,DrIoContextFields,0xffff,0), STRUCT(DrDeviceManager,DrDeviceManagerFields,0xffff,0), STRUCT(DoubleList,DoubleListFields,0xffff,0), STRUCT(KernelResource,KernelResourceFields,0xffff,0), STRUCT(VirtualChannel,VirtualChannelFields,0xffff,0), STRUCT(DrDevice,DrDeviceFields,0xffff,0), STRUCT(DrPrinterPort,DrPrinterPortFields,0xffff,0), STRUCT(DrParallelPort,DrParallelPortFields,0xffff,0), STRUCT(DrSerialPort,DrSerialPortFields,0xffff,0), STRUCT(DrSessionManager,DrSessionManagerFields,0xffff,0), STRUCT(DrSession,DrSessionFields,0xffff,0), #if DBG STRUCT(ReferenceTraceRecord,ReferenceTraceRecordFields,0xffff,0), #endif STRUCT(SESSIONLISTNODE,SESSIONLISTNODEFields,0xffff,0), STRUCT(EVENTLISTNODE,EVENTLISTNODEFields,0xffff,0), STRUCT(RDPDR_IOCOMPLETION_PACKET,RdpdrIoCompletionFields,0xffff,0), STRUCT(RDPDR_IOREQUEST_PACKET,RdpdrIoRequestFields,0xffff,0), STRUCT(RDPDR_UPDATE_DEVICEINFO_PACKET,RdpdrUpdateDeviceInfoFields,0xffff,0), STRUCT(RDPDR_DEVICE_REPLY_PACKET,RdpdrDeviceReplyFields,0xffff,0), STRUCT(RDPDR_DEVICELIST_ANNOUNCE_PACKET,RdpdrDeviceListAnnounceFields,0xffff,0), STRUCT(RDPDR_DEVICE_ANNOUNCE,RdpdrDeviceAnnounceFields,0xffff,0), STRUCT(RDPDR_CLIENT_NAME_PACKET,RdpdrClientNameFields,0xffff,0), STRUCT(RDPDR_CLIENT_CONFIRM_PACKET,RdpdrClientConfirmFields,0xffff,0), STRUCT(RDPDR_SERVER_ANNOUNCE_PACKET,RdpdrServerAnnounceFields,0xffff,0), STRUCT(RDPDR_HEADER,RdpdrHeaderFields,0xffff,0), #if DBG STRUCT(TRC_CONFIG,TRC_CONFIGFields,0xffff,0), STRUCT(TRC_PREFIX_DATA,TRC_PREFIX_DATAFields,0xffff,0), #endif // DBG STRUCTLAST }; ULONG_PTR FieldOffsetOfContextListEntryInRxC(){ return FIELD_OFFSET(RX_CONTEXT,ContextListEntry);} PCWSTR GetExtensionLibPerDebugeeArchitecture(ULONG DebugeeArchitecture){ switch (DebugeeArchitecture) { case RX_PROCESSOR_ARCHITECTURE_INTEL: return L"kdextx86.dll"; case RX_PROCESSOR_ARCHITECTURE_MIPS: return L"kdextmip.dll"; case RX_PROCESSOR_ARCHITECTURE_ALPHA: return L"kdextalp.dll"; case RX_PROCESSOR_ARCHITECTURE_PPC: return L"kdextppc.dll"; default: return(NULL); } } //CODE.IMPROVEMENT it is not good to try to structure along the lines of "this routine knows // rxstructures" versus "this routine knows debugger extensions". also we // need a precomp.h BOOLEAN wGetData( ULONG_PTR dwAddress, PVOID ptr, ULONG size, IN PSZ type); VOID ReadRxContextFields(ULONG_PTR RxContext,PULONG_PTR pFcb,PULONG_PTR pThread, PULONG_PTR pMiniCtx2) { RX_CONTEXT RxContextBuffer; if (!wGetData(RxContext,&RxContextBuffer,sizeof(RxContextBuffer),"RxContextFieldss")) return; *pFcb = (ULONG_PTR)(RxContextBuffer.pFcb); *pThread = (ULONG_PTR)(RxContextBuffer.LastExecutionThread); *pMiniCtx2 = (ULONG_PTR)(RxContextBuffer.MRxContext[2]); } FOLLOWON_HELPER_RETURNS __FollowOnError ( OUT PBYTE Buffer2, IN PBYTE followontext, ULONG LastId, ULONG Index) { if (LastId==0) { sprintf((char *)Buffer2,"Cant dump a %s. no previous dump.\n", followontext,Index); } else { sprintf((char *)Buffer2,"Cant dump a %s from a %s\n", followontext,Structs[Index].StructName); } return(FOLLOWONHELPER_ERROR); } #define FollowOnError(A) (__FollowOnError(Buffer2,A,p->IdOfLastDump,p->IndexOfLastDump)) VOID dprintfsprintfbuffer(BYTE *Buffer); DECLARE_FOLLOWON_HELPER_CALLEE(FcbFollowOn) { //BYTE DbgBuf[200]; //sprintf(DbgBuf,"top p,id=%08lx,%d",p,p->IdOfLastDump); //dprintfsprintfbuffer(DbgBuf); switch (p->IdOfLastDump) { case StrEnum_RX_CONTEXT:{ PRX_CONTEXT RxContext = (PRX_CONTEXT)(&p->StructDumpBuffer[0]); sprintf((char *)Buffer2," %08p\n",RxContext->pFcb); return(FOLLOWONHELPER_DUMP); } break; default: return FollowOnError((PUCHAR)"irp"); } }
35.529143
118
0.73144
npocmaka
2d5dfac9f670a063d8e316b690b0d3ed9b9cfdfc
2,248
cpp
C++
class-exercises/acc-07/wbpriarbiter.cpp
cambridgehackers/atomicc-examples
d0280629b94185d806637486b8413dd1a806d82a
[ "MIT" ]
null
null
null
class-exercises/acc-07/wbpriarbiter.cpp
cambridgehackers/atomicc-examples
d0280629b94185d806637486b8413dd1a806d82a
[ "MIT" ]
null
null
null
class-exercises/acc-07/wbpriarbiter.cpp
cambridgehackers/atomicc-examples
d0280629b94185d806637486b8413dd1a806d82a
[ "MIT" ]
null
null
null
/* Copyright (c) 2020 The Connectal Project * * 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 "fwbslave.h" template<int OPT_ZERO_ON_IDLE, int F_OPT_CLK2FFLOGIC> class WbPriArbiterIfc { WishboneType a; WishboneType b; WishboneType *o; }; template<int OPT_ZERO_ON_IDLE, int F_OPT_CLK2FFLOGIC> class WbPriArbiter __implements __verilog WbPriArbiterIfc<OPT_ZERO_ON_IDLE, F_OPT_CLK2FFLOGIC> { bool r_a_owner; void a.stb(bool we, __uint(AW) addr, __uint(DW) data, __uint(DW/8) sel) if (this->a.cyc) { r_a_owner = true; this->o->stb(we, addr, data, sel); } bool a.ack() { return this->o->ack() & r_a_owner; } bool a.stall() { return this->o->stall() | !r_a_owner; } bool a.err() { return this->o->err() & r_a_owner; } void b.stb(bool we, __uint(AW) addr, __uint(DW) data, __uint(DW/8) sel) if (!this->a.cyc) { r_a_owner = false; this->o->stb(we, addr, data, sel); } bool b.ack() { return this->o->ack() & !r_a_owner; } bool b.stall() { return this->o->stall() | r_a_owner; } bool b.err() { return this->o->err() & !r_a_owner; } }; WbPriArbiter<0, 1> dummy;
35.68254
96
0.68016
cambridgehackers
2d5e5bdcda379693aa3abbafe188f9511eb1d3a7
2,434
cpp
C++
boost/boost_1_56_0/libs/spirit/test/x3/difference.cpp
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
3
2018-11-02T07:15:32.000Z
2018-12-15T19:56:59.000Z
boost/boost_1_56_0/libs/spirit/test/x3/difference.cpp
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
2
2017-11-18T21:24:03.000Z
2020-03-11T12:39:57.000Z
boost/boost_1_56_0/libs/spirit/test/x3/difference.cpp
cooparation/caffe-android
cd91078d1f298c74fca4c242531989d64a32ba03
[ "BSD-2-Clause-FreeBSD" ]
3
2017-01-02T14:11:37.000Z
2019-12-20T13:42:13.000Z
/*============================================================================= Copyright (c) 2001-2013 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/home/x3.hpp> //~ #include <boost/phoenix/core.hpp> //~ #include <boost/phoenix/operator.hpp> #include <string> #include <iostream> #include "test.hpp" int main() { using boost::spirit::x3::ascii::char_; using boost::spirit::x3::lit; using spirit_test::test; using spirit_test::test_attr; // Basic tests { BOOST_TEST(test("b", char_ - 'a')); BOOST_TEST(!test("a", char_ - 'a')); BOOST_TEST(test("/* abcdefghijk */", "/*" >> *(char_ - "*/") >> "*/")); BOOST_TEST(!test("switch", lit("switch") - "switch")); } // Test attributes { char attr; BOOST_TEST(test_attr("xg", (char_ - 'g') >> 'g', attr)); BOOST_TEST(attr == 'x'); } // Test handling of container attributes { std::string attr; BOOST_TEST(test_attr("abcdefg", *(char_ - 'g') >> 'g', attr)); BOOST_TEST(attr == "abcdef"); } // $$$ Not yet implemented //~ { //~ BOOST_TEST(test("b", char_ - no_case['a'])); //~ BOOST_TEST(!test("a", char_ - no_case['a'])); //~ BOOST_TEST(!test("A", char_ - no_case['a'])); //~ BOOST_TEST(test("b", no_case[lower - 'a'])); //~ BOOST_TEST(test("B", no_case[lower - 'a'])); //~ BOOST_TEST(!test("a", no_case[lower - 'a'])); //~ BOOST_TEST(!test("A", no_case[lower - 'a'])); //~ } // $$$ Not yet implemented //~ { //~ using boost::spirit::x3::_1; //~ namespace phx = boost::phoenix; //~ std::string s; //~ BOOST_TEST(test( //~ "/*abcdefghijk*/" //~ , "/*" >> *(char_ - "*/")[phx::ref(s) += _1] >> "*/" //~ )); //~ BOOST_TEST(s == "abcdefghijk"); //~ s.clear(); //~ BOOST_TEST(test( //~ " /*abcdefghijk*/" //~ , "/*" >> *(char_ - "*/")[phx::ref(s) += _1] >> "*/" //~ , space //~ )); //~ BOOST_TEST(s == "abcdefghijk"); //~ } return boost::report_errors(); }
29.325301
80
0.468776
cooparation
2d5e8ad945853de51aaf8f6bfebe8e45ba7bc36d
23,811
cpp
C++
tst_reamber_base_test.cpp
Eve-ning/reamber_base_test
19d856516073a157f2a2f918491955121fe490b4
[ "MIT" ]
null
null
null
tst_reamber_base_test.cpp
Eve-ning/reamber_base_test
19d856516073a157f2a2f918491955121fe490b4
[ "MIT" ]
null
null
null
tst_reamber_base_test.cpp
Eve-ning/reamber_base_test
19d856516073a157f2a2f918491955121fe490b4
[ "MIT" ]
null
null
null
#include <QtTest> // add necessary includes here #include <iostream> #include <vector> #include <algorithm/algorithm.h> #include <object/singular/hitobject.h> #include <object/singular/timingpoint.h> #include <QDebug> #include <QSharedPointer> class TestObjs { public: TestObjs() { hoNote.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hitsound.wav", 4); hoLongNote.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::LN, OsuObject::SAMPLE_SET::AUTO, 1500, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hitsound.wav", 4); tpSv.loadParameters( 1000, 2, 4, OsuObject::SAMPLE_SET::AUTO, 0, 50, false, false ); tpBpm.loadParameters( 1000, 300, 4, OsuObject::SAMPLE_SET::AUTO, 0, 50, true, false ); eHOSingular.loadParameters(1, 1000, 0, 4); eHOMutliple[0].loadParameters(1, 1000, 0, 4); eHOMutliple[1].loadParameters(2, 2000, 0, 4); hoMultiple[0].loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 40, "hit1.wav", 4); hoMultiple[1].loadParameters( 2, 192, 2000, HitObject::NOTE_TYPE::LN, OsuObject::SAMPLE_SET::AUTO, 2500, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "hit2.wav", 4); hoMultiple[2].loadParameters( 3, 192, 3000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 60, "hit3.wav", 4); tpMultiple[0].loadParameters( 0, 400, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, true, false ); tpMultiple[1].loadParameters( 1000, 2, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, false, true ); tpMultiple[2].loadParameters( 2000, 0.5, 4, OsuObject::SAMPLE_SET::NORMAL, 1, 50, false, false ); pEHOMutliple = QSPtr<HitObjectV>::create(eHOMutliple); pHOMultiple = QSPtr<HitObjectV>::create(hoMultiple); pTPMultiple = QSPtr<TimingPointV>::create(tpMultiple); } QString rawHOStrNote = "64,192,1000,1,0,0:0:0:50:hitsound.wav"; QString rawHOStrLongNote = "64,192,1000,128,0,1500:0:0:0:50:hitsound.wav"; QString rawTPSv = "1000,-50,4,0,0,50,0,0"; QString rawTPBpm = "1000,200,4,0,0,50,1,0"; QString eHOStrSingular = "00:01:000 (1000|1) -"; QString eHOStrMultiple = "00:01:000 (1000|1,2000|2) -"; QString rawHOStrMultiple = "64,192,1000,1,0,0:0:0:40:hit1.wav\n" // N "320,192,2000,128,0,2500:0:0:0:70:hit2.wav\n" // LN "448,192,3000,1,0,0:0:0:60:hit3.wav"; // N QString rawTPStrMultiple = "0,150,4,1,1,50,1,0\n" // BPM 400 "1000,-50,4,1,1,50,0,1\n" // SV 2.0 Kiai "2000,-200,4,1,1,50,0,0"; // SV 0.50 HitObject hoNote; HitObject hoLongNote; TimingPoint tpSv; TimingPoint tpBpm; HitObject eHOSingular; HitObjectV eHOMutliple = HitObjectV(2); HitObjectV hoMultiple = HitObjectV(3); TimingPointV tpMultiple = TimingPointV(3); QSPtr<HitObjectV> pEHOMutliple; QSPtr<HitObjectV> pHOMultiple ; QSPtr<TimingPointV> pTPMultiple ; }; class reamber_base_test : public QObject { Q_OBJECT private slots: void trimEHO(); void hoRawLoading(); void tpRawLoad(); void hoEditorLoading(); void hoVRawLoading(); void tpVRawLoading(); void hoVEditorLoading(); void foboHO(); void foboTP(); void loboHO(); void loboTP(); void getColumnV(); void getOffsetMinHO(); void getOffsetMaxHO(); void getOffsetMinTP(); void getOffsetMaxTP(); void sortByOffsetHO(); void sortByOffsetTP(); void tpVMultiply(); void tpVGetAve(); void tpVArithmetic(); void libOffsetDiff(); void libCopySingularHO(); void libCopyMultipleHO(); void libCopySingularTP(); void libCopyMultipleTP(); void libCopySubByHO(); void libCopySubByHODelay(); void libCopySubToHO(); void libCopySubToHODelay(); void libCopyReldiff(); void libCopyReldiffDelay(); void libCopyAbsdiff(); void libCopyAbsdiffDelay(); void libNormalize(); void libCreateStutterRelative(); void libCreateStutterAbsolute(); void libCreateStutterFromOffset(); void libExtractNth(); void libDeleteNth(); private: TestObjs tests = TestObjs(); }; void reamber_base_test::trimEHO() { QString str = tests.eHOStrMultiple; HitObject::trimEditor(str); QVERIFY(QString("1000|1,2000|2") == str); } void reamber_base_test::hoRawLoading() { HitObject ho; ho.loadRaw(tests.rawHOStrNote, 4); QVERIFY(ho == tests.hoNote); } void reamber_base_test::tpRawLoad() { TimingPoint tp; tp.loadRaw(tests.rawTPBpm); QVERIFY(tp == tests.tpBpm); } void reamber_base_test::hoEditorLoading() { HitObject ho("00:01:000 (1000|0) - ", HitObject::TYPE::EDITOR, 4); HitObject ho_expected; ho_expected.loadParameters( 0, 192, 1000, HitObject::NOTE_TYPE::NORMAL, OsuObject::SAMPLE_SET::AUTO, 0, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, OsuObject::SAMPLE_SET::AUTO, 50, "", 4); QVERIFY(ho_expected == ho); } void reamber_base_test::hoVRawLoading() { HitObjectV ho_v(tests.rawHOStrMultiple, HitObject::TYPE::RAW, 4); QVERIFY(ho_v == tests.hoMultiple); } void reamber_base_test::tpVRawLoading() { TimingPointV tpV(tests.rawTPStrMultiple); QVERIFY(tpV == tests.tpMultiple); } void reamber_base_test::hoVEditorLoading() { HitObjectV ho_v(tests.eHOStrMultiple, HitObject::TYPE::EDITOR, 4); QVERIFY(ho_v == tests.eHOMutliple); } // FOBO: First Object By Offset // LOBO: Last Object By Offset void reamber_base_test::foboHO(){ QVERIFY(tests.hoMultiple[0] == // Expect the first object tests.hoMultiple.getFirstObjectByOffset()); } void reamber_base_test::foboTP(){ QVERIFY(tests.tpMultiple[0] == // Expect the first object tests.tpMultiple.getFirstObjectByOffset()); } void reamber_base_test::loboHO(){ QVERIFY(tests.hoMultiple[2] == // Expect the first object tests.hoMultiple.getLastObjectByOffset()); } void reamber_base_test::loboTP(){ QVERIFY(tests.tpMultiple[2] == // Expect the first object tests.tpMultiple.getLastObjectByOffset()); } void reamber_base_test::getColumnV() { QVERIFY((tests.hoMultiple.getColumnV() == QVector<unsigned int>{0, 2, 3})); } void reamber_base_test::getOffsetMinHO() { QVERIFY(tests.hoMultiple.getOffsetMin() == 1000.0); } void reamber_base_test::getOffsetMaxHO() { QVERIFY(tests.hoMultiple.getOffsetMax() == 3000.0); } void reamber_base_test::getOffsetMinTP() { QVERIFY(tests.tpMultiple.getOffsetMin() == 0.0); } void reamber_base_test::getOffsetMaxTP() { QVERIFY(tests.tpMultiple.getOffsetMax() == 2000.0); } void reamber_base_test::sortByOffsetHO() { HitObjectV ho_v = tests.hoMultiple; // Manually sort by descending HitObjectV ho_v_sort_desc = HitObjectV(3); ho_v_sort_desc[0] = ho_v[2]; ho_v_sort_desc[1] = ho_v[1]; ho_v_sort_desc[2] = ho_v[0]; // Sort by Descending ho_v.sortByOffset(false); QVERIFY(ho_v == ho_v_sort_desc); } void reamber_base_test::sortByOffsetTP() { TimingPointV tpV = tests.tpMultiple; // Manually sort by descending TimingPointV tpVSortDesc = TimingPointV(3); tpVSortDesc[0] = tpV[2]; tpVSortDesc[1] = tpV[1]; tpVSortDesc[2] = tpV[0]; // Sort by Descending tpV.sortByOffset(false); QVERIFY(tpV == tpVSortDesc); } void reamber_base_test::tpVMultiply() { // [0] [1] [2] [3] [4] // SELF : 1 1 1 // EFF : 1 1 1 TimingPointV tpV(4); tpV[0].loadParameters(0, 1, false); tpV[1].loadParameters(1, 2, false); tpV[2].loadParameters(4, 4, false); tpV[3].loadParameters(5, 8, false); TimingPointV tpV_eff(3); tpV_eff[0].loadParameters(0, 1, false); tpV_eff[1].loadParameters(2, 0.5, false); tpV_eff[2].loadParameters(3, 0.25, false); tpV.crossEffectMultiply(tpV_eff); QVector<QString> expected = { "0,-100,4,0,0,25,0,0", "1,-50,4,0,0,25,0,0", "4,-100,4,0,0,25,0,0", "5,-50,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::tpVGetAve() { // SV TimingPointV tpV = TimingPointV(3); tpV[0].loadParameters(0, 1.5, false); tpV[1].loadParameters(100, 0.5, false); tpV[2].loadParameters(400, 1.75, false); QVERIFY(0.75 == tpV.getAverageSvValue()); // BPM tpV = TimingPointV(3); tpV[0].loadParameters(0, 200, true); tpV[1].loadParameters(100, 100, true); tpV[2].loadParameters(400, 150, true); QVERIFY(125.0 == tpV.getAverageBpmValue()); // MIXED tpV = TimingPointV(4); tpV[0].loadParameters(0, 200, true); tpV[1].loadParameters(50, 0.5, false); // JUNK SV tpV[2].loadParameters(100, 100, true); tpV[3].loadParameters(400, 150, true); QVERIFY(125.0 == tpV.getAverageBpmValue()); } void reamber_base_test::tpVArithmetic() { // + TimingPointV tpV = TimingPointV(3); tpV[0].loadParameters(0, 1.5, false); tpV[1].loadParameters(100, 0.5, false); tpV[2].loadParameters(400, 1.75, false); tpV += 2; // for (auto tp : tpV) { // qDebug() << tp.getStringRaw().toStdString().c_str(); // } QVERIFY(true); } void reamber_base_test::libOffsetDiff() { auto offsetDifference = algorithm::offsetDiff<HitObject>(tests.pHOMultiple); QVERIFY(offsetDifference == QVector<double>({1000, 1000})); } void reamber_base_test::libCopySingularHO() { auto copies = algorithm::copy<HitObject>(tests.hoNote, QVector<double>{1000, 2000}); QVERIFY(QVector<double>({ 1000,2000 }) == copies.getOffsetV(false)); } void reamber_base_test::libCopyMultipleHO() { auto copies = algorithm::copy<HitObject>(tests.pHOMultiple, QVector<double>{1000, 2000}); // Get unique offset for copies QVERIFY(QVector<double>({ 1000,2000,3000,4000 }) == copies.getOffsetV(true)); } void reamber_base_test::libCopySingularTP() { auto copies = algorithm::copy<TimingPoint>(tests.tpSv, QVector<double>{1000, 2000}); QVERIFY(QVector<double>({ 1000,2000 }) == copies.getOffsetV(false)); } void reamber_base_test::libCopyMultipleTP() { auto copies = algorithm::copy<TimingPoint>(tests.pTPMultiple, QVector<double>{1000, 2000}); // Get unique offset for copies QVERIFY(QVector<double>({ 1000,2000,3000,4000 }) == copies.getOffsetV(true)); } void reamber_base_test::libCopySubByHO() { // EXCLUDE auto copies = algorithm::copySubdBy<HitObject> (QVector<double>({ 100,400,700 }), tests.hoNote, 2, false); // for (auto s : copies.getStringRawV()) // qDebug() << s; QVector<QString> expected = { "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,500,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,600,1,0,0:0:0:50:hitsound.wav" // Subd 2 }; QVERIFY(copies.getStringRawV() == expected); // INCLUDE copies = algorithm::copySubdBy<HitObject> (QVector<double>({ 100,400,700 }), tests.hoNote, 2, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,500,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,600,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,700,1,0,0:0:0:50:hitsound.wav" // Subd 0 }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubByHODelay() { auto copies = algorithm::copySubdBy<HitObject>(tests.pHOMultiple, 4, false); QVector<QString> expected = { "64,192,1200,1,0,0:0:0:40:hit1.wav", "64,192,1400,1,0,0:0:0:40:hit1.wav", "64,192,1600,1,0,0:0:0:40:hit1.wav", "64,192,1800,1,0,0:0:0:40:hit1.wav", "320,192,2200,128,0,2500:0:0:0:50:hit2.wav", "320,192,2400,128,0,2500:0:0:0:50:hit2.wav", "320,192,2600,128,0,2500:0:0:0:50:hit2.wav", "320,192,2800,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copySubdBy<HitObject>(tests.pHOMultiple, 4, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1200,1,0,0:0:0:40:hit1.wav", "64,192,1400,1,0,0:0:0:40:hit1.wav", "64,192,1600,1,0,0:0:0:40:hit1.wav", "64,192,1800,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2200,128,0,2500:0:0:0:50:hit2.wav", "320,192,2400,128,0,2500:0:0:0:50:hit2.wav", "320,192,2600,128,0,2500:0:0:0:50:hit2.wav", "320,192,2800,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubToHO() { // EXCLUDE auto copies = algorithm::copySubdTo<HitObject> (QVector<double>({ 100,300,500 }), tests.hoNote, 50, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,250,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,350,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,450,1,0,0:0:0:50:hitsound.wav" // Subd 3 }; // for (auto ho : copies) { // qDebug() << ho.getStringRaw().toStdString().c_str(); // } QVERIFY(copies.getStringRawV() == expected); // INCLUDE copies = algorithm::copySubdTo<HitObject> (QVector<double>({ 100,300,500 }), tests.hoNote, 50, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,150,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,200,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,250,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,300,1,0,0:0:0:50:hitsound.wav", // Subd 0 "64,192,350,1,0,0:0:0:50:hitsound.wav", // Subd 1 "64,192,400,1,0,0:0:0:50:hitsound.wav", // Subd 2 "64,192,450,1,0,0:0:0:50:hitsound.wav", // Subd 3 "64,192,500,1,0,0:0:0:50:hitsound.wav" // Subd 0 }; // for (auto ho : copies) { // qDebug() << ho.getStringRaw().toStdString().c_str(); // } QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopySubToHODelay() { auto copies = algorithm::copySubdTo<HitObject>(tests.pHOMultiple, 250, false); QVector<QString> expected = { "64,192,1250,1,0,0:0:0:40:hit1.wav", "64,192,1500,1,0,0:0:0:40:hit1.wav", "64,192,1750,1,0,0:0:0:40:hit1.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "320,192,2500,128,0,2500:0:0:0:50:hit2.wav", "320,192,2750,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copySubdTo<HitObject>(tests.pHOMultiple, 250, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1250,1,0,0:0:0:40:hit1.wav", "64,192,1500,1,0,0:0:0:40:hit1.wav", "64,192,1750,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "320,192,2500,128,0,2500:0:0:0:50:hit2.wav", "320,192,2750,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyReldiff() { auto copies = algorithm::copyRel( QVector<double>({ 100, 300 }), tests.hoNote, 0.25, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyRel( QVector<double>({ 100, 300 }), tests.hoNote, 0.25, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,150,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyReldiffDelay() { auto copies = algorithm::copyRel<HitObject> (tests.pHOMultiple, 0.25, false); QVector<QString> expected = { "64,192,1250,1,0,0:0:0:40:hit1.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyRel<HitObject> (tests.pHOMultiple, 0.25, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1250,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2250,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyAbsdiff() { // EXCLUDE auto copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, false, true, false); QVector<QString> expected = { "64,192,150,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, true, true, false); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,150,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 250, true, true, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav", }; QVERIFY(copies.getStringRawV() == expected); // FROM THE BACK copies = algorithm::copyAbs( QVector<double>({ 100, 300 }), tests.hoNote, 50, true, false, true); expected = { "64,192,100,1,0,0:0:0:50:hitsound.wav", "64,192,250,1,0,0:0:0:50:hitsound.wav", "64,192,300,1,0,0:0:0:50:hitsound.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libCopyAbsdiffDelay() { // EXCLUDE auto copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 15, false, true, true); QVector<QString> expected = { "64,192,1015,1,0,0:0:0:40:hit1.wav", "320,192,2015,128,0,2500:0:0:0:50:hit2.wav", }; // INCLUDE QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 15, true, true, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1015,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2015,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 2000, true, true, true); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); // EXCLUDE OVERLAP QVERIFY(copies.getStringRawV() == expected); copies = algorithm::copyAbs<HitObject> (tests.pHOMultiple, 100, true, false, false); expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "64,192,1900,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", "320,192,2900,128,0,2500:0:0:0:50:hit2.wav", "448,192,3000,1,0,0:0:0:60:hit3.wav" }; QVERIFY(copies.getStringRawV() == expected); } void reamber_base_test::libNormalize() { auto normalized = algorithm::normalize(tests.tpMultiple, 200, false); QVector<QString> expected = { "0,-200,4,1,1,50,0,0" }; QVERIFY(normalized.getStringRawV() == expected); } void reamber_base_test::libCreateStutterRelative() { // SV auto tpV = algorithm::stutterRel(QVector<double>({ 100,350,600 }), 4, 0.2); QVector<QString> expected = { "100,-25,4,0,0,25,0,0", "150,-400,4,0,0,25,0,0", "350,-25,4,0,0,25,0,0", "400,-400,4,0,0,25,0,0", "600,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); // BPM tpV = algorithm::stutterRel(QVector<double>({ 100,300,700 }), 400, 0.25, 200, true, false); expected = { "100,150,4,0,0,25,1,0", "150,450,4,0,0,25,1,0", "300,150,4,0,0,25,1,0", "400,450,4,0,0,25,1,0", "700,300,4,0,0,25,1,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libCreateStutterAbsolute() { // SV auto tpV = algorithm::stutterAbs(QVector<double>({ 100,300,700 }), 1.5, 100, 1.0); //for (auto s : tpV.getStringRawV()) qDebug () << s; QVector<QString> expected = { "100,-66.66666667,4,0,0,25,0,0", "200,-200,4,0,0,25,0,0", "300,-66.66666667,4,0,0,25,0,0", "400,-120,4,0,0,25,0,0", "700,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); // BPM tpV = algorithm::stutterAbs(QVector<double>({ 100,300,700 }), 150, 100, 100, true, true, true); expected = { "100,400,4,0,0,25,1,0", "200,1200,4,0,0,25,1,0", "300,400,4,0,0,25,1,0", "400,720,4,0,0,25,1,0", "700,600,4,0,0,25,1,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libCreateStutterFromOffset() { auto tpV = algorithm::stutter(QVector<double>({ 100,400,700 }), 1.5, 1.0, false, true); QVector<QString> expected = { "100,-66.66666667,4,0,0,25,0,0", "400,-200,4,0,0,25,0,0", "700,-100,4,0,0,25,0,0" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libDeleteNth() { // HO auto ho_v = algorithm::deleteNth<HitObject>(tests.pHOMultiple, 2, 1); QVector<QString> expected = { "64,192,1000,1,0,0:0:0:40:hit1.wav", "320,192,2000,128,0,2500:0:0:0:50:hit2.wav", }; QVERIFY(ho_v.getStringRawV() == expected); // TP auto tpV = algorithm::deleteNth<TimingPoint>(tests.pTPMultiple, 2, 1); expected = { "0,150,4,1,1,50,1,0", "1000,-50,4,1,1,50,0,1" }; QVERIFY(tpV.getStringRawV() == expected); } void reamber_base_test::libExtractNth() { // HO auto ho_v = algorithm::extractNth<HitObject>(tests.pHOMultiple, 2, 1); QVector<QString> expected = { "320,192,2000,128,0,2500:0:0:0:50:hit2.wav" }; QVERIFY(ho_v.getStringRawV() == expected); // TP auto tpV = algorithm::extractNth<TimingPoint>(tests.pTPMultiple, 2, 1); expected = { "1000,-50,4,1,1,50,0,1" }; QVERIFY(tpV.getStringRawV() == expected); } QTEST_APPLESS_MAIN(reamber_base_test) #include "tst_reamber_base_test.moc"
31.003906
99
0.60808
Eve-ning
2d5fea0264fcda9067e8fe8718213c0ec2b3b9c4
564
cpp
C++
Kuma Engine/PanelFile.cpp
GerardClotet/Kuma-Engine
16759a8c5e18b69eb6ce50b6feeaf50d5312e957
[ "MIT" ]
2
2019-10-07T07:11:16.000Z
2019-10-31T16:45:56.000Z
Kuma Engine/PanelFile.cpp
GerardClotet/Kuma-Engine
16759a8c5e18b69eb6ce50b6feeaf50d5312e957
[ "MIT" ]
null
null
null
Kuma Engine/PanelFile.cpp
GerardClotet/Kuma-Engine
16759a8c5e18b69eb6ce50b6feeaf50d5312e957
[ "MIT" ]
null
null
null
#include "PanelConfig.h" #include "Globals.h" #include "ModuleRenderer3D.h" #include "ModuleUI.h" #include "PanelFile.h" PanelFile::~PanelFile() { } update_status PanelFile::Draw() { if (App->ui->file_load_model)LoadModel(); if (App->ui->file_save_scene)DisplaySaveScene(); if (App->ui->file_load_scene)DisplayLoadScene(); return UPDATE_CONTINUE; } void PanelFile::LoadModel() { App->ui->LoadFile("fbx"); } void PanelFile::DisplaySaveScene() { App->ui->SaveFile("kumaScene"); } void PanelFile::DisplayLoadScene() { App->ui->LoadFile("kumaScene"); }
15.666667
49
0.714539
GerardClotet
062450d280164d63958326b5826ab5b370311a05
9,832
cpp
C++
src/frameworks/native/libs/nativewindow/ANativeWindow.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/libs/nativewindow/ANativeWindow.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/libs/nativewindow/ANativeWindow.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 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. */ #define LOG_TAG "ANativeWindow" #include <grallocusage/GrallocUsageConversion.h> // from nativewindow/includes/system/window.h // (not to be confused with the compatibility-only window.h from system/core/includes) #include <system/window.h> #include <private/android/AHardwareBufferHelpers.h> #include <ui/GraphicBuffer.h> using namespace android; static int32_t query(ANativeWindow* window, int what) { int value; int res = window->query(window, what, &value); return res < 0 ? res : value; } static bool isDataSpaceValid(ANativeWindow* window, int32_t dataSpace) { bool supported = false; switch (dataSpace) { case HAL_DATASPACE_UNKNOWN: case HAL_DATASPACE_V0_SRGB: return true; // These data space need wide gamut support. case HAL_DATASPACE_V0_SCRGB_LINEAR: case HAL_DATASPACE_V0_SCRGB: case HAL_DATASPACE_DISPLAY_P3: native_window_get_wide_color_support(window, &supported); return supported; // These data space need HDR support. case HAL_DATASPACE_BT2020_PQ: native_window_get_hdr_support(window, &supported); return supported; default: return false; } } /************************************************************************************************** * NDK **************************************************************************************************/ void ANativeWindow_acquire(ANativeWindow* window) { // incStrong/decStrong token must be the same, doesn't matter what it is window->incStrong((void*)ANativeWindow_acquire); } void ANativeWindow_release(ANativeWindow* window) { // incStrong/decStrong token must be the same, doesn't matter what it is window->decStrong((void*)ANativeWindow_acquire); } int32_t ANativeWindow_getWidth(ANativeWindow* window) { return query(window, NATIVE_WINDOW_WIDTH); } int32_t ANativeWindow_getHeight(ANativeWindow* window) { return query(window, NATIVE_WINDOW_HEIGHT); } int32_t ANativeWindow_getFormat(ANativeWindow* window) { return query(window, NATIVE_WINDOW_FORMAT); } int32_t ANativeWindow_setBuffersGeometry(ANativeWindow* window, int32_t width, int32_t height, int32_t format) { int32_t err = native_window_set_buffers_format(window, format); if (!err) { err = native_window_set_buffers_user_dimensions(window, width, height); if (!err) { int mode = NATIVE_WINDOW_SCALING_MODE_FREEZE; if (width && height) { mode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW; } err = native_window_set_scaling_mode(window, mode); } } return err; } int32_t ANativeWindow_lock(ANativeWindow* window, ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds) { return window->perform(window, NATIVE_WINDOW_LOCK, outBuffer, inOutDirtyBounds); } int32_t ANativeWindow_unlockAndPost(ANativeWindow* window) { return window->perform(window, NATIVE_WINDOW_UNLOCK_AND_POST); } int32_t ANativeWindow_setBuffersTransform(ANativeWindow* window, int32_t transform) { static_assert(ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL == NATIVE_WINDOW_TRANSFORM_FLIP_H); static_assert(ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL == NATIVE_WINDOW_TRANSFORM_FLIP_V); static_assert(ANATIVEWINDOW_TRANSFORM_ROTATE_90 == NATIVE_WINDOW_TRANSFORM_ROT_90); constexpr int32_t kAllTransformBits = ANATIVEWINDOW_TRANSFORM_MIRROR_HORIZONTAL | ANATIVEWINDOW_TRANSFORM_MIRROR_VERTICAL | ANATIVEWINDOW_TRANSFORM_ROTATE_90 | // We don't expose INVERSE_DISPLAY as an NDK constant, but someone could have read it // from a buffer already set by Camera framework, so we allow it to be forwarded. NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY; if (!window || !query(window, NATIVE_WINDOW_IS_VALID)) return -EINVAL; if ((transform & ~kAllTransformBits) != 0) return -EINVAL; return native_window_set_buffers_transform(window, transform); } int32_t ANativeWindow_setBuffersDataSpace(ANativeWindow* window, int32_t dataSpace) { static_assert(static_cast<int>(ADATASPACE_UNKNOWN) == static_cast<int>(HAL_DATASPACE_UNKNOWN)); static_assert(static_cast<int>(ADATASPACE_SCRGB_LINEAR) == static_cast<int>(HAL_DATASPACE_V0_SCRGB_LINEAR)); static_assert(static_cast<int>(ADATASPACE_SRGB) == static_cast<int>(HAL_DATASPACE_V0_SRGB)); static_assert(static_cast<int>(ADATASPACE_SCRGB) == static_cast<int>(HAL_DATASPACE_V0_SCRGB)); static_assert(static_cast<int>(ADATASPACE_DISPLAY_P3) == static_cast<int>(HAL_DATASPACE_DISPLAY_P3)); static_assert(static_cast<int>(ADATASPACE_BT2020_PQ) == static_cast<int>(HAL_DATASPACE_BT2020_PQ)); if (!window || !query(window, NATIVE_WINDOW_IS_VALID) || !isDataSpaceValid(window, dataSpace)) { return -EINVAL; } return native_window_set_buffers_data_space(window, static_cast<android_dataspace_t>(dataSpace)); } int32_t ANativeWindow_getBuffersDataSpace(ANativeWindow* window) { if (!window || !query(window, NATIVE_WINDOW_IS_VALID)) return -EINVAL; return query(window, NATIVE_WINDOW_DATASPACE); } /************************************************************************************************** * vndk-stable **************************************************************************************************/ #if 0 // M3E AHardwareBuffer* ANativeWindowBuffer_getHardwareBuffer(ANativeWindowBuffer* anwb) { return AHardwareBuffer_from_GraphicBuffer(static_cast<GraphicBuffer*>(anwb)); } #endif // M3E int ANativeWindow_OemStorageSet(ANativeWindow* window, uint32_t slot, intptr_t value) { if (slot < 4) { window->oem[slot] = value; return 0; } return -EINVAL; } int ANativeWindow_OemStorageGet(ANativeWindow* window, uint32_t slot, intptr_t* value) { if (slot >= 4) { *value = window->oem[slot]; return 0; } return -EINVAL; } int ANativeWindow_setSwapInterval(ANativeWindow* window, int interval) { return window->setSwapInterval(window, interval); } int ANativeWindow_query(const ANativeWindow* window, ANativeWindowQuery what, int* value) { switch (what) { case ANATIVEWINDOW_QUERY_MIN_UNDEQUEUED_BUFFERS: case ANATIVEWINDOW_QUERY_DEFAULT_WIDTH: case ANATIVEWINDOW_QUERY_DEFAULT_HEIGHT: case ANATIVEWINDOW_QUERY_TRANSFORM_HINT: // these are part of the VNDK API break; case ANATIVEWINDOW_QUERY_MIN_SWAP_INTERVAL: *value = window->minSwapInterval; return 0; case ANATIVEWINDOW_QUERY_MAX_SWAP_INTERVAL: *value = window->maxSwapInterval; return 0; case ANATIVEWINDOW_QUERY_XDPI: *value = (int)window->xdpi; return 0; case ANATIVEWINDOW_QUERY_YDPI: *value = (int)window->ydpi; return 0; default: // asked for an invalid query(), one that isn't part of the VNDK return -EINVAL; } return window->query(window, int(what), value); } int ANativeWindow_queryf(const ANativeWindow* window, ANativeWindowQuery what, float* value) { switch (what) { case ANATIVEWINDOW_QUERY_XDPI: *value = window->xdpi; return 0; case ANATIVEWINDOW_QUERY_YDPI: *value = window->ydpi; return 0; default: break; } int i; int e = ANativeWindow_query(window, what, &i); if (e == 0) { *value = (float)i; } return e; } int ANativeWindow_dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer, int* fenceFd) { return window->dequeueBuffer(window, buffer, fenceFd); } int ANativeWindow_queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) { return window->queueBuffer(window, buffer, fenceFd); } int ANativeWindow_cancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) { return window->cancelBuffer(window, buffer, fenceFd); } int ANativeWindow_setUsage(ANativeWindow* window, uint64_t usage) { return native_window_set_usage(window, usage); } int ANativeWindow_setBufferCount(ANativeWindow* window, size_t bufferCount) { return native_window_set_buffer_count(window, bufferCount); } int ANativeWindow_setBuffersDimensions(ANativeWindow* window, uint32_t w, uint32_t h) { return native_window_set_buffers_dimensions(window, (int)w, (int)h); } int ANativeWindow_setBuffersFormat(ANativeWindow* window, int format) { return native_window_set_buffers_format(window, format); } int ANativeWindow_setBuffersTimestamp(ANativeWindow* window, int64_t timestamp) { return native_window_set_buffers_timestamp(window, timestamp); } int ANativeWindow_setSharedBufferMode(ANativeWindow* window, bool sharedBufferMode) { return native_window_set_shared_buffer_mode(window, sharedBufferMode); } int ANativeWindow_setAutoRefresh(ANativeWindow* window, bool autoRefresh) { return native_window_set_auto_refresh(window, autoRefresh); }
36.686567
112
0.690195
dAck2cC2
0625c8920947fb021877fb14bcd6bf917ea7ec6b
785
cpp
C++
symengine/polys/uintpoly_piranha.cpp
shifan3/symengine
d9539af520c4b121aff780d27ba22cced9983ece
[ "MIT" ]
2
2020-11-06T12:45:03.000Z
2022-03-18T18:00:15.000Z
symengine/polys/uintpoly_piranha.cpp
HQSquantumsimulations/symengine
95d6af92dc6a759d9320d6bdadfa51d038c81218
[ "MIT" ]
null
null
null
symengine/polys/uintpoly_piranha.cpp
HQSquantumsimulations/symengine
95d6af92dc6a759d9320d6bdadfa51d038c81218
[ "MIT" ]
null
null
null
#include <symengine/symbol.h> #include <symengine/expression.h> #include <symengine/polys/uintpoly_piranha.h> namespace SymEngine { UIntPolyPiranha::UIntPolyPiranha(const RCP<const Basic> &var, pintpoly &&dict) : UPiranhaPoly(var, std::move(dict)) { SYMENGINE_ASSIGN_TYPEID() } hash_t UIntPolyPiranha::__hash__() const { hash_t seed = SYMENGINE_UINTPOLYPIRANHA; seed += get_poly().hash(); seed += get_var()->hash(); return seed; } URatPolyPiranha::URatPolyPiranha(const RCP<const Basic> &var, pratpoly &&dict) : UPiranhaPoly(var, std::move(dict)) { SYMENGINE_ASSIGN_TYPEID() } hash_t URatPolyPiranha::__hash__() const { hash_t seed = SYMENGINE_URATPOLYPIRANHA; seed += get_poly().hash(); seed += get_var()->hash(); return seed; } }
21.805556
78
0.700637
shifan3
0626fcd489b980fda2a16cecca3851c9755f0972
2,291
cpp
C++
Seagull-Core/src/Platform/DirectX/DirectX12SwapChain.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12SwapChain.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12SwapChain.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
#include "sgpch.h" #include "DirectX12SwapChain.h" #include "DirectXHelper.h" #include "Core/Application.h" #include "DirectX12Context.h" #include "DirectXHelper.h" namespace SG { DirectX12SwapChain::DirectX12SwapChain(IDXGIFactory7* factory, const Ref<DirectX12RenderQueue>& renderQueue) { // Create swap chain m_SwapChain.Reset(); m_SwapChainDesc = { }; m_SwapChainDesc.BufferDesc.Width = (UINT)Application::Get().GetWindow()->GetWidth(); m_SwapChainDesc.BufferDesc.Height = (UINT)Application::Get().GetWindow()->GetHeight(); m_SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; m_SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; m_SwapChainDesc.BufferDesc.Format = DirectX12Context::GetBackBufferFormat(); m_SwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; m_SwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; m_SwapChainDesc.SampleDesc.Count = DirectX12Context::Get4xMSAAState() ? 4 : 1; m_SwapChainDesc.SampleDesc.Quality = DirectX12Context::Get4xMSAAState() ? (DirectX12Context::Get4xMSAAQualityCount() - 1) : 0; m_SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; m_SwapChainDesc.BufferCount = 2; m_SwapChainDesc.OutputWindow = static_cast<HWND>(Application::Get().GetWindow()->GetNativeWindow()); m_SwapChainDesc.Windowed = true; m_SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; m_SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; ThrowIfFailed(factory->CreateSwapChain(renderQueue->GetCommandQueueNative(), &m_SwapChainDesc, m_SwapChain.GetAddressOf())); } void DirectX12SwapChain::GetBuffer(UINT index, ComPtr<ID3D12Resource>& resource) { ThrowIfFailed(m_SwapChain->GetBuffer(index, IID_PPV_ARGS(&resource))); } void DirectX12SwapChain::ResizeBuffer(UINT bufferCount, UINT swapChainFormat) { ThrowIfFailed(m_SwapChain->ResizeBuffers(bufferCount, Application::Get().GetWindow()->GetWidth(), Application::Get().GetWindow()->GetHeight(), DirectX12Context::GetBackBufferFormat(), swapChainFormat)); m_CurrBackBufferIndex = 0; } void DirectX12SwapChain::Present(UINT syncInterval, UINT flags) { ThrowIfFailed(m_SwapChain->Present(syncInterval, flags)); m_CurrBackBufferIndex = (m_CurrBackBufferIndex + 1) % 2; } }
38.830508
128
0.787866
ILLmew
06279bcf01a36b0127a46534bbd5fa8bb05d7642
593
cpp
C++
include/hydro/parser/__ast/BinaryOp.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/BinaryOp.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/parser/__ast/BinaryOp.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "BinaryOp.hpp" namespace hydro { BinaryOp::BinaryOp(ast_expr lhs, lex_token token, ast_expr rhs) : Expr{token}, _lhs{lhs}, _rhs{rhs} { addChild(_lhs); addChild(_rhs); } BinaryOp::~BinaryOp() {} } // namespace hydro
22.807692
99
0.404722
hydraate
062924c8157b83437d009a40fa20e9846bf91aa4
936
cc
C++
chrome/test/data/nacl/simple.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/test/data/nacl/simple.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/test/data/nacl/simple.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "ppapi/cpp/instance.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/var.h" class SimpleInstance : public pp::Instance { public: explicit SimpleInstance(PP_Instance instance) : pp::Instance(instance) { } virtual void HandleMessage(const pp::Var& var_message) { if (var_message.is_string() && var_message.AsString() == "ping") { PostMessage(pp::Var("pong")); return; } PostMessage(pp::Var("failed")); } }; class SimpleModule : public pp::Module { public: virtual pp::Instance* CreateInstance(PP_Instance instance) { return new SimpleInstance(instance); } }; namespace pp { __attribute__((visibility("default"))) Module* CreateModule() { return new SimpleModule(); } } // namespace pp
23.4
74
0.695513
zealoussnow
062b9be2fb2ee8a36e9e25d52e2241ccba49f9a4
1,692
cpp
C++
src/ShaderProgramLinker.cpp
Killavus/Phelsuma
734e89efa2c1b3b9c52ca3feb555e4b2acc69c80
[ "MIT" ]
null
null
null
src/ShaderProgramLinker.cpp
Killavus/Phelsuma
734e89efa2c1b3b9c52ca3feb555e4b2acc69c80
[ "MIT" ]
null
null
null
src/ShaderProgramLinker.cpp
Killavus/Phelsuma
734e89efa2c1b3b9c52ca3feb555e4b2acc69c80
[ "MIT" ]
null
null
null
#include <string> #include "ShaderProgramLinker.h" #include "Shader.h" #include "ShaderProgram.h" bool ShaderProgramLinker::attachShader(const Shader& shader) { if (shader.invalid()) { return false; } auto sameTypeElement = findShaderByType(shader.type()); if (sameTypeElement != attachedShaders.end()) { return false; } attachedShaders.push_back(shader); return true; } bool ShaderProgramLinker::detachShader(GLenum type) { auto element = findShaderByType(type); if (element == attachedShaders.end()) { return false; } else { attachedShaders.erase(element); return true; } } ShaderProgram ShaderProgramLinker::link() { GLuint programId = glCreateProgram(); GLint linkStatus = GL_TRUE, infoLogLength; for (auto const& shader : attachedShaders) { glAttachShader(programId, shader.id()); } glLinkProgram(programId); glGetProgramiv(programId, GL_LINK_STATUS, &linkStatus); if (linkStatus == GL_FALSE) { glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &infoLogLength); infoLogLength = infoLogLength == 0 ? 512 : infoLogLength; char *infoLog = new char[infoLogLength + 1]; glGetProgramInfoLog(programId, infoLogLength, NULL, infoLog); std::string errorMessage(infoLog); return ShaderProgram(errorMessage); } for (auto const& shader : attachedShaders) { glDetachShader(programId, shader.id()); } return ShaderProgram(programId); } std::vector<Shader>::iterator ShaderProgramLinker::findShaderByType(GLenum type) { return std::find_if( attachedShaders.begin(), attachedShaders.end(), [type](const Shader& attachedShader) -> bool { return type == attachedShader.type(); } ); }
24.171429
82
0.713948
Killavus
062eab6bb833a1105fd1c36fa73dc3f7f6757399
4,956
cpp
C++
projects/2_OOP/oop_lab_3_2/test.cpp
GodBastardNeil/somethings
56a25ab2a3150658356924b00fed7d97ad76a9cb
[ "BSD-3-Clause" ]
null
null
null
projects/2_OOP/oop_lab_3_2/test.cpp
GodBastardNeil/somethings
56a25ab2a3150658356924b00fed7d97ad76a9cb
[ "BSD-3-Clause" ]
null
null
null
projects/2_OOP/oop_lab_3_2/test.cpp
GodBastardNeil/somethings
56a25ab2a3150658356924b00fed7d97ad76a9cb
[ "BSD-3-Clause" ]
null
null
null
#include "catch.hpp" #include "money.h" TEST_CASE("Проверка работы методов класса money", "[money]") { money m; // -- нулевой объект нужен всем -- // - определение чистой виртуальной функции run() класса Test -- // -- тестовые методы -- SECTION("Инициализация переменных класса money") // -- создание и присваивание { money two; CHECK(m == two); CHECK(two.toString() == "0,00 руб."); money d0(12, 34); CHECK(d0.toString() == "12,34 руб."); money dd0(56); CHECK(dd0.toString() == "56,00 руб."); CHECK_THROWS ( [&]() { money d1(12, 134); } () ); CHECK_THROWS // 1 -- ошибка -- будет просто 0,16 - не должно выводить исключение, по этому выведется ошибка ( [&]() { money dd1(1, 16); } () ); } SECTION("Метод Сложения") // -- тестирование сложения { money one; one += money{1, 1}; CHECK(one.toString() == "1,01 руб."); money two = one + one; CHECK(two.toString() == "2,02 руб."); two = one + money{3, 3}; CHECK(two.toString() == "4,04 руб."); two += money{0, 66}; CHECK(two.toString() == "5,10 руб."); // 2 -- ошибка - должно быть 4,70 two += money{5}; CHECK(two.toString() == "9,70 руб."); } SECTION("Метод Вычитания") // -- тестирование вычитания { money one {5, 5}; one -= money{1, 1}; CHECK(one.toString() == "4,04 руб."); money two = one - one; CHECK(two.toString() == "0,00 руб."); two = one - money{1, 1}; CHECK(two.toString() == "3,03 руб."); two -= money{1, 3}; CHECK(two.toString() == "2,01 руб."); // 3 -- ошибка - должно быть 2,00 CHECK_THROWS // 4 -- ошибка - не должно выводить исключение, по этому выведется ошибка ( [&]() { money one{4, 4}; two = one - money{1}; } () ); CHECK_THROWS ( [&]() { two -= money{3, 5}; } () ); CHECK_THROWS ( [&]() { two = one - money{5, 4}; } () ); } SECTION("Метод Деления money / money") // -- тестирование деления money / money { money one {5, 5}; double d = one / money{1, 1}; CHECK(d == 5.00); d = one / money{5, 5}; CHECK(fabs(d - 1.1) < 0.001); // 5 -- ошибка - должно быть 1.00 d = money{1, 1} / one; CHECK(fabs(d - 0.2) < 0.001); d = one / money{0, 20}; CHECK(d == 25.25); d = money{0, 20} / money(0, 20); CHECK(d == 1.00); } SECTION("Метод Деления money / double") // -- тестирование деления money / double { money one {5, 5}; double d = one / 1.01; CHECK(d == 500.0); d = one / 5.05; CHECK(d == 101.0); // 6 -- ошибка - должно быть 1.00 d = money{1, 1} / 5.05; CHECK(d == 20.0); d = one / 0.20; CHECK(d == 2525.0); d = money{0, 20} / 0.20; CHECK(d == 100.0); } SECTION("Метод Деления money * double") // -- тестирование деления money * double { money one {5, 5}; one *= 4; CHECK(one.toString() == "20,20 руб."); one = money(1, 1); one *= 1.5; CHECK(one.toString() == "1,51 руб."); one *= 10; CHECK(one.toString() == "15,01 руб."); // 7 -- ошибка - должно быть 15,10 one *= 0.56; CHECK(one.toString() == "8,45 руб."); one *= 1.56; CHECK(one.toString() == "13,18 руб."); } SECTION("Методы Сравнения") // -- проверка сравнения { money a{1, 1}; money b{1, 11}; money c{1, 11}; money d{11, 1}; CHECK(a < b); CHECK(a < c); CHECK(a < d); CHECK(a > b); // 8 -- ошибка -- CHECK(a > c); // 9 -- ошибка -- CHECK(a > d); // 10 -- ошибка -- CHECK(a == b); // 11 -- ошибка -- CHECK(a == c); // 12 -- ошибка -- CHECK(a == d); // 13 -- ошибка -- CHECK(a <= b); CHECK(a <= c); CHECK(a <= d); CHECK(a >= b); // 14 -- ошибка -- CHECK(a >= c); // 15 -- ошибка -- CHECK(a >= d); // 16 -- ошибка -- CHECK(b < c); // 17 -- ошибка -- CHECK(b < d); CHECK(b > c); // 18 -- ошибка -- CHECK(b > d); // 19 -- ошибка -- CHECK(b == c); CHECK(b == d); // 20 -- ошибка -- CHECK(b <= c); CHECK(b <= d); CHECK(b >= c); CHECK(b >= d); // 21 -- ошибка -- CHECK(c < d); CHECK(c > d); // 22 -- ошибка -- CHECK(c == d); // 23 -- ошибка -- CHECK(c <= d); CHECK(c >= d); // 24 -- ошибка -- } }
38.418605
115
0.421509
GodBastardNeil
06319cbc06a99182d6b1d3bf32168b266f778fde
3,374
cpp
C++
src/csapex_qt/src/view/param/color_param_adapter.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_qt/src/view/param/color_param_adapter.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_qt/src/view/param/color_param_adapter.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
/// HEADER #include <csapex/view/param/color_param_adapter.h> /// PROJECT #include <csapex/view/utility/qwrapper.h> #include <csapex/view/node/parameter_context_menu.h> #include <csapex/view/utility/qt_helper.hpp> #include <csapex/utility/assert.h> #include <csapex/utility/type.h> #include <csapex/command/update_parameter.h> /// SYSTEM #include <QPointer> #include <QPushButton> #include <QColorDialog> #include <QApplication> #include <iostream> #include <sstream> #include <iomanip> using namespace csapex; namespace { QString toColorSS(const std::vector<int>& v) { std::stringstream ss; ss << "QPushButton {"; ss << "background-color: #" << std::hex << std::setfill('0'); ss << std::setw(2) << v[0]; ss << std::setw(2) << v[1]; ss << std::setw(2) << v[2]; ss << std::dec << ";"; ss << "}"; return QString::fromStdString(ss.str()); } } // namespace ColorParameterAdapter::ColorParameterAdapter(param::ColorParameter::Ptr p) : ParameterAdapter(std::dynamic_pointer_cast<param::Parameter>(p)), color_p_(p) { } QWidget* ColorParameterAdapter::setup(QBoxLayout* layout, const std::string& display_name) { QPointer<QPushButton> btn = new QPushButton; btn->setStyleSheet(toColorSS(color_p_->value())); btn->setContextMenuPolicy(Qt::CustomContextMenu); QObject::connect(btn.data(), &QPushButton::customContextMenuRequested, [=](const QPoint& point) { customContextMenuRequested(btn, point); }); QHBoxLayout* sub = new QHBoxLayout; sub->addWidget(btn); layout->addLayout(QtHelper::wrap(display_name, sub, context_handler)); // ui callback QObject::connect(btn.data(), &QPushButton::pressed, [this, btn]() { if (!color_p_ || !btn) { return; } std::vector<int> c = color_p_->value(); QColor init(c[0], c[1], c[2]); QColorDialog diag(QApplication::activeWindow()); diag.setCurrentColor(init); diag.setModal(true); // diag.setOptions(QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel); // diag.setVisible(true); // diag.setOptions(QColorDialog::DontUseNativeDialog); // diag.setAttribute(Qt::WA_WState_Visible, true); // diag.setAttribute(Qt::WA_WState_Hidden, false); // diag.setAttribute(Qt::WA_WState_ExplicitShowHide); if (!diag.exec()) { return; } QColor color = diag.selectedColor(); if (color.isValid()) { std::vector<int> v(3); v[0] = color.red(); v[1] = color.green(); v[2] = color.blue(); btn->setStyleSheet(toColorSS(v)); command::UpdateParameter::Ptr update_parameter = std::make_shared<command::UpdateParameter>(p_->getUUID().getAbsoluteUUID(), v); executeCommand(update_parameter); } }); // model change -> ui connectInGuiThread(p_->parameter_changed, [this, btn](param::Parameter*) { if (!color_p_ || !btn) { return; } btn->setStyleSheet(toColorSS(color_p_->value())); }); return btn; } void ColorParameterAdapter::setupContextMenu(ParameterContextMenu* context_handler) { context_handler->addAction(new QAction("reset to default", context_handler), [this]() { color_p_->set(color_p_->def()); }); }
29.858407
154
0.633076
ICRA-2018
06326a4e7a60fa3cb80ab43c324903882ceac0ab
2,323
cpp
C++
src/tests/system/libroot/posix/seek_and_write_test.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/tests/system/libroot/posix/seek_and_write_test.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/tests/system/libroot/posix/seek_and_write_test.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2010, Axel Dörfler, axeld@pinc-software.de. * This file may be used under the terms of the MIT License. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <algorithm> void test_for_content(int fd, off_t start, const char* contents, size_t length) { char buffer[4096]; while (length > 0) { size_t toRead = std::min(length, sizeof(buffer)); if (pread(fd, buffer, toRead, start) != (ssize_t)toRead) { perror("reading failed"); exit(1); } if (memcmp(contents, buffer, toRead)) { fprintf(stderr, "Contents at %lld differ!\n", start); exit(1); } contents += toRead; start += toRead; length -= toRead; } } void test_for_zero(int fd, off_t start, off_t end) { while (start < end) { char buffer[4096]; size_t length = std::min((size_t)(end - start), sizeof(buffer)); if (pread(fd, buffer, length, start) != (ssize_t)length) { perror("reading failed"); exit(1); } for (size_t i = 0; i < length; i++) { if (buffer[i] != 0) { fprintf(stderr, "Buffer at %lld is not empty (%#x)!\n", start + i, buffer[i]); exit(1); } } start += length; } } int main(int argc, char** argv) { const char* name = "/tmp/seek_and_write"; bool prefill = true; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == 'n') prefill = false; else { fprintf(stderr, "Unknown option\n"); return 1; } continue; } name = argv[i]; } int fd = open(name, O_RDWR | O_TRUNC | O_CREAT, 0644); if (fd < 0) { perror("failed to open file"); return 1; } char buffer[256]; for (size_t i = 0; i < 256; i++) buffer[i] = i; if (prefill) { // Write test data to file to make sure it's not empty for (size_t i = 0; i < 100; i++) { if (write(fd, buffer, sizeof(buffer)) != (ssize_t)sizeof(buffer)) { perror("writing failed"); return 1; } } } // Truncate it again in order to remove its contents ftruncate(fd, 0); // Seek past its end, and write something pwrite(fd, "---", 3, 100 * 1024); pwrite(fd, "+++", 3, 200 * 1024); // Test contents test_for_zero(fd, 0, 100 * 1024); test_for_content(fd, 100 * 1024, "---", 3); test_for_zero(fd, 100 * 1024 + 256, 200 * 1024); test_for_content(fd, 200 * 1024, "+++", 3); return 0; }
18.733871
74
0.591907
Kirishikesan
0635ef71a5fc5fb78b52757a942077da79a68813
4,412
cpp
C++
src/gui/widgets/algoStarterWidgets/mathwidget.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
5
2016-03-17T07:02:11.000Z
2021-12-12T14:43:58.000Z
src/gui/widgets/algoStarterWidgets/mathwidget.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
null
null
null
src/gui/widgets/algoStarterWidgets/mathwidget.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
3
2015-10-29T15:21:01.000Z
2020-11-25T09:41:21.000Z
/* * mathwidget.cpp * * Created on: Mar 24, 2014 * Author: schurade */ #include "mathwidget.h" #include "../../../data/datasets/datasetscalar.h" #include "../../../data/models.h" #include "../../../data/vptr.h" #include "../../../io/writer.h" #include "../controls/sliderwithedit.h" #include "../controls/sliderwitheditint.h" #include "../controls/selectwithlabel.h" MathWidget::MathWidget( DatasetScalar* ds, QWidget* parent ) : m_dataset( ds ) { m_layout = new QVBoxLayout(); m_modeSelect = new SelectWithLabel( QString( "mode" ), 1 ); m_modeSelect->insertItem( 0, QString("make binary") ); m_modeSelect->insertItem( 1, QString("add") ); m_modeSelect->insertItem( 2, QString("mult") ); m_modeSelect->insertItem( 3, QString("between thresholds") ); m_layout->addWidget( m_modeSelect ); connect( m_modeSelect, SIGNAL( currentIndexChanged( int, int ) ), this, SLOT( modeChanged( int ) ) ); m_sourceSelect = new SelectWithLabel( QString( "source dataset" ), 1 ); QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList(); for ( int k = 0; k < dsl.size(); ++k ) { if ( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_TYPE ).toInt() == (int)Fn::DatasetType::NIFTI_SCALAR ) { m_sourceSelect->addItem( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_NAME ).toString(), dsl[k] ); } } m_layout->addWidget( m_sourceSelect ); m_sourceSelect->hide(); m_arg = new SliderWithEdit( QString("arg") ); m_arg->setMin( -1000 ); m_arg->setMax( 1000 ); m_arg->setValue( 0 ); m_layout->addWidget( m_arg ); m_arg->hide(); QHBoxLayout* hLayout = new QHBoxLayout(); m_executeButton = new QPushButton( tr("execute") ); connect( m_executeButton, SIGNAL( clicked() ), this, SLOT( execute() ) ); hLayout->addStretch(); hLayout->addWidget( m_executeButton ); m_layout->addLayout( hLayout ); m_layout->addStretch(); setLayout( m_layout ); } MathWidget::~MathWidget() { } void MathWidget::modeChanged( int mode ) { switch ( mode ) { case 0: m_sourceSelect->hide(); m_arg->hide(); break; case 1: m_sourceSelect->hide(); m_arg->show(); break; case 2: m_sourceSelect->hide(); m_arg->show(); break; case 3: m_sourceSelect->hide(); m_arg->hide(); break; } } void MathWidget::execute() { std::vector<float> data = *( m_dataset->getData() ); int mode = m_modeSelect->getCurrentIndex(); float arg = m_arg->getValue(); float lowerThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat(); float upperThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat(); switch ( mode ) { case 0: { for ( unsigned int i = 0; i < data.size(); ++i ) { if ( data[i] > lowerThreshold && data[i] < upperThreshold ) { data[i] = 1.0; } else { data[i] = 0.0; } } break; } case 1: { for ( unsigned int i = 0; i < data.size(); ++i ) { data[i] += arg; } break; } case 2: { for ( unsigned int i = 0; i < data.size(); ++i ) { data[i] *= arg; } break; } case 3: { for ( unsigned int i = 0; i < data.size(); ++i ) { if ( data[i] < lowerThreshold || data[i] > upperThreshold ) { data[i] = 0.0; } } break; } } Writer writer( m_dataset, QFileInfo() ); DatasetScalar* out = new DatasetScalar( QDir( "new dataset" ), data, writer.createHeader( 1 ) ); QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET ); Models::d()->setData( index, VPtr<Dataset>::asQVariant( out ), Qt::DisplayRole ); this->hide(); }
27.924051
133
0.524025
mhough
063b63c9a32c8067804690277d86af68fd109d2a
78,422
cpp
C++
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/vsite.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
1
2020-04-20T04:33:11.000Z
2020-04-20T04:33:11.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/vsite.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
8
2019-07-10T15:18:21.000Z
2019-07-31T13:38:09.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/mdlib/vsite.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
3
2019-07-10T10:50:25.000Z
2020-12-08T13:42:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "vsite.h" #include <cstdio> #include <algorithm> #include <memory> #include <vector> #include "gromacs/domdec/domdec.h" #include "gromacs/domdec/domdec_struct.h" #include "gromacs/gmxlib/network.h" #include "gromacs/gmxlib/nrnb.h" #include "gromacs/math/functions.h" #include "gromacs/math/vec.h" #include "gromacs/mdlib/gmx_omp_nthreads.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/pbcutil/ishift.h" #include "gromacs/pbcutil/mshift.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/topology/ifunc.h" #include "gromacs/topology/mtop_util.h" #include "gromacs/topology/topology.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/gmxomp.h" /* The strategy used here for assigning virtual sites to (thread-)tasks * is as follows: * * We divide the atom range that vsites operate on (natoms_local with DD, * 0 - last atom involved in vsites without DD) equally over all threads. * * Vsites in the local range constructed from atoms in the local range * and/or other vsites that are fully local are assigned to a simple, * independent task. * * Vsites that are not assigned after using the above criterion get assigned * to a so called "interdependent" thread task when none of the constructing * atoms is a vsite. These tasks are called interdependent, because one task * accesses atoms assigned to a different task/thread. * Note that this option is turned off with large (local) atom counts * to avoid high memory usage. * * Any remaining vsites are assigned to a separate master thread task. */ using gmx::RVec; static void init_ilist(t_ilist *ilist) { for (int i = 0; i < F_NRE; i++) { ilist[i].nr = 0; ilist[i].nalloc = 0; ilist[i].iatoms = nullptr; } } /*! \brief List of atom indices belonging to a task */ struct AtomIndex { //! List of atom indices std::vector<int> atom; }; /*! \brief Data structure for thread tasks that use constructing atoms outside their own atom range */ struct InterdependentTask { //! The interaction lists, only vsite entries are used t_ilist ilist[F_NRE]; //! Thread/task-local force buffer std::vector<RVec> force; //! The atom indices of the vsites of our task std::vector<int> vsite; //! Flags if elements in force are spread to or not std::vector<bool> use; //! The number of entries set to true in use int nuse; //! Array of atoms indices, size nthreads, covering all nuse set elements in use std::vector<AtomIndex> atomIndex; //! List of tasks (force blocks) this task spread forces to std::vector<int> spreadTask; //! List of tasks that write to this tasks force block range std::vector<int> reduceTask; InterdependentTask() { init_ilist(ilist); nuse = 0; } }; /*! \brief Vsite thread task data structure */ struct VsiteThread { //! Start of atom range of this task int rangeStart; //! End of atom range of this task int rangeEnd; //! The interaction lists, only vsite entries are used t_ilist ilist[F_NRE]; //! Local fshift accumulation buffer rvec fshift[SHIFTS]; //! Local virial dx*df accumulation buffer matrix dxdf; //! Tells if interdependent task idTask should be used (in addition to the rest of this task), this bool has the same value on all threads bool useInterdependentTask; //! Data for vsites that involve constructing atoms in the atom range of other threads/tasks InterdependentTask idTask; /*! \brief Constructor */ VsiteThread() { rangeStart = -1; rangeEnd = -1; init_ilist(ilist); clear_rvecs(SHIFTS, fshift); clear_mat(dxdf); useInterdependentTask = false; } }; /*! \brief Returns the sum of the vsite ilist sizes over all vsite types * * \param[in] ilist The interaction list */ template <typename T> static int vsiteIlistNrCount(const T *ilist) { int nr = 0; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { nr += ilist[ftype].size(); } return nr; } static int pbc_rvec_sub(const t_pbc *pbc, const rvec xi, const rvec xj, rvec dx) { if (pbc) { return pbc_dx_aiuc(pbc, xi, xj, dx); } else { rvec_sub(xi, xj, dx); return CENTRAL; } } /* Vsite construction routines */ static void constr_vsite2(const rvec xi, const rvec xj, rvec x, real a, const t_pbc *pbc) { real b = 1 - a; /* 1 flop */ if (pbc) { rvec dx; pbc_dx_aiuc(pbc, xj, xi, dx); x[XX] = xi[XX] + a*dx[XX]; x[YY] = xi[YY] + a*dx[YY]; x[ZZ] = xi[ZZ] + a*dx[ZZ]; } else { x[XX] = b*xi[XX] + a*xj[XX]; x[YY] = b*xi[YY] + a*xj[YY]; x[ZZ] = b*xi[ZZ] + a*xj[ZZ]; /* 9 Flops */ } /* TOTAL: 10 flops */ } static void constr_vsite3(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { real c = 1 - a - b; /* 2 flops */ if (pbc) { rvec dxj, dxk; pbc_dx_aiuc(pbc, xj, xi, dxj); pbc_dx_aiuc(pbc, xk, xi, dxk); x[XX] = xi[XX] + a*dxj[XX] + b*dxk[XX]; x[YY] = xi[YY] + a*dxj[YY] + b*dxk[YY]; x[ZZ] = xi[ZZ] + a*dxj[ZZ] + b*dxk[ZZ]; } else { x[XX] = c*xi[XX] + a*xj[XX] + b*xk[XX]; x[YY] = c*xi[YY] + a*xj[YY] + b*xk[YY]; x[ZZ] = c*xi[ZZ] + a*xj[ZZ] + b*xk[ZZ]; /* 15 Flops */ } /* TOTAL: 17 flops */ } static void constr_vsite3FD(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { rvec xij, xjk, temp; real c; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ /* temp goes from i to a point on the line jk */ temp[XX] = xij[XX] + a*xjk[XX]; temp[YY] = xij[YY] + a*xjk[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ]; /* 6 flops */ c = b*gmx::invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + c*temp[XX]; x[YY] = xi[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + c*temp[ZZ]; /* 6 Flops */ /* TOTAL: 34 flops */ } static void constr_vsite3FAD(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, const t_pbc *pbc) { rvec xij, xjk, xp; real a1, b1, c1, invdij; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ invdij = gmx::invsqrt(iprod(xij, xij)); c1 = invdij * invdij * iprod(xij, xjk); xp[XX] = xjk[XX] - c1*xij[XX]; xp[YY] = xjk[YY] - c1*xij[YY]; xp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; a1 = a*invdij; b1 = b*gmx::invsqrt(iprod(xp, xp)); /* 45 */ x[XX] = xi[XX] + a1*xij[XX] + b1*xp[XX]; x[YY] = xi[YY] + a1*xij[YY] + b1*xp[YY]; x[ZZ] = xi[ZZ] + a1*xij[ZZ] + b1*xp[ZZ]; /* 12 Flops */ /* TOTAL: 63 flops */ } static void constr_vsite3OUT(const rvec xi, const rvec xj, const rvec xk, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xik, temp; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); cprod(xij, xik, temp); /* 15 Flops */ x[XX] = xi[XX] + a*xij[XX] + b*xik[XX] + c*temp[XX]; x[YY] = xi[YY] + a*xij[YY] + b*xik[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + a*xij[ZZ] + b*xik[ZZ] + c*temp[ZZ]; /* 18 Flops */ /* TOTAL: 33 flops */ } static void constr_vsite4FD(const rvec xi, const rvec xj, const rvec xk, const rvec xl, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xjk, xjl, temp; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); pbc_rvec_sub(pbc, xl, xj, xjl); /* 9 flops */ /* temp goes from i to a point on the plane jkl */ temp[XX] = xij[XX] + a*xjk[XX] + b*xjl[XX]; temp[YY] = xij[YY] + a*xjk[YY] + b*xjl[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ] + b*xjl[ZZ]; /* 12 flops */ d = c*gmx::invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + d*temp[XX]; x[YY] = xi[YY] + d*temp[YY]; x[ZZ] = xi[ZZ] + d*temp[ZZ]; /* 6 Flops */ /* TOTAL: 43 flops */ } static void constr_vsite4FDN(const rvec xi, const rvec xj, const rvec xk, const rvec xl, rvec x, real a, real b, real c, const t_pbc *pbc) { rvec xij, xik, xil, ra, rb, rja, rjb, rm; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); pbc_rvec_sub(pbc, xl, xi, xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); /* 6 flops */ cprod(rja, rjb, rm); /* 9 flops */ d = c*gmx::invsqrt(norm2(rm)); /* 5+5+1 flops */ x[XX] = xi[XX] + d*rm[XX]; x[YY] = xi[YY] + d*rm[YY]; x[ZZ] = xi[ZZ] + d*rm[ZZ]; /* 6 Flops */ /* TOTAL: 47 flops */ } static int constr_vsiten(const t_iatom *ia, const t_iparams ip[], rvec *x, const t_pbc *pbc) { rvec x1, dx; dvec dsum; int n3, av, ai; real a; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; ai = ia[2]; copy_rvec(x[ai], x1); clear_dvec(dsum); for (int i = 3; i < n3; i += 3) { ai = ia[i+2]; a = ip[ia[i]].vsiten.a; if (pbc) { pbc_dx_aiuc(pbc, x[ai], x1, dx); } else { rvec_sub(x[ai], x1, dx); } dsum[XX] += a*dx[XX]; dsum[YY] += a*dx[YY]; dsum[ZZ] += a*dx[ZZ]; /* 9 Flops */ } x[av][XX] = x1[XX] + dsum[XX]; x[av][YY] = x1[YY] + dsum[YY]; x[av][ZZ] = x1[ZZ] + dsum[ZZ]; return n3; } /*! \brief PBC modes for vsite construction and spreading */ enum class PbcMode { all, // Apply normal, simple PBC for all vsites none // No PBC treatment needed }; /*! \brief Returns the PBC mode based on the system PBC and vsite properties * * \param[in] pbcPtr A pointer to a PBC struct or nullptr when no PBC treatment is required */ static PbcMode getPbcMode(const t_pbc *pbcPtr) { if (pbcPtr == nullptr) { return PbcMode::none; } else { return PbcMode::all; } } static void construct_vsites_thread(rvec x[], real dt, rvec *v, const t_iparams ip[], const t_ilist ilist[], const t_pbc *pbc_null) { real inv_dt; if (v != nullptr) { inv_dt = 1.0/dt; } else { inv_dt = 1.0; } const PbcMode pbcMode = getPbcMode(pbc_null); /* We need another pbc pointer, as with charge groups we switch per vsite */ const t_pbc *pbc_null2 = pbc_null; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { if (ilist[ftype].nr == 0) { continue; } { // TODO remove me int nra = interaction_function[ftype].nratoms; int inc = 1 + nra; int nr = ilist[ftype].nr; const t_iatom *ia = ilist[ftype].iatoms; for (int i = 0; i < nr; ) { int tp = ia[0]; /* The vsite and constructing atoms */ int avsite = ia[1]; int ai = ia[2]; /* Constants for constructing vsites */ real a1 = ip[tp].vsite.a; /* Copy the old position */ rvec xv; copy_rvec(x[avsite], xv); /* Construct the vsite depending on type */ int aj, ak, al; real b1, c1; switch (ftype) { case F_VSITE2: aj = ia[3]; constr_vsite2(x[ai], x[aj], x[avsite], a1, pbc_null2); break; case F_VSITE3: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FAD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FAD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3OUT: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite3OUT(x[ai], x[aj], x[ak], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FD: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FD(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FDN: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FDN(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITEN: inc = constr_vsiten(ia, ip, x, pbc_null2); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } if (pbcMode == PbcMode::all) { /* Keep the vsite in the same periodic image as before */ rvec dx; int ishift = pbc_dx_aiuc(pbc_null, x[avsite], xv, dx); if (ishift != CENTRAL) { rvec_add(xv, dx, x[avsite]); } } if (v != nullptr) { /* Calculate velocity of vsite... */ rvec vv; rvec_sub(x[avsite], xv, vv); svmul(inv_dt, vv, v[avsite]); } /* Increment loop variables */ i += inc; ia += inc; } } } } void construct_vsites(const gmx_vsite_t *vsite, rvec x[], real dt, rvec *v, const t_iparams ip[], const t_ilist ilist[], int ePBC, gmx_bool bMolPBC, const t_commrec *cr, const matrix box) { const bool useDomdec = (vsite != nullptr && vsite->useDomdec); GMX_ASSERT(!useDomdec || (cr != nullptr && DOMAINDECOMP(cr)), "When vsites are set up with domain decomposition, we need a valid commrec"); // TODO: Remove this assertion when we remove charge groups GMX_ASSERT(vsite != nullptr || ePBC == epbcNONE, "Without a vsite struct we can not do PBC (in case we have charge groups)"); t_pbc pbc, *pbc_null; /* We only need to do pbc when we have inter-cg vsites. * Note that with domain decomposition we do not need to apply PBC here * when we have at least 3 domains along each dimension. Currently we * do not optimize this case. */ if (ePBC != epbcNONE && (useDomdec || bMolPBC) && !(vsite != nullptr && vsite->numInterUpdategroupVsites == 0)) { /* This is wasting some CPU time as we now do this multiple times * per MD step. */ ivec null_ivec; clear_ivec(null_ivec); pbc_null = set_pbc_dd(&pbc, ePBC, useDomdec ? cr->dd->nc : null_ivec, FALSE, box); } else { pbc_null = nullptr; } if (useDomdec) { dd_move_x_vsites(cr->dd, box, x); } if (vsite == nullptr || vsite->nthreads == 1) { construct_vsites_thread(x, dt, v, ip, ilist, pbc_null); } else { #pragma omp parallel num_threads(vsite->nthreads) { try { const int th = gmx_omp_get_thread_num(); const VsiteThread &tData = *vsite->tData[th]; GMX_ASSERT(tData.rangeStart >= 0, "The thread data should be initialized before calling construct_vsites"); construct_vsites_thread(x, dt, v, ip, tData.ilist, pbc_null); if (tData.useInterdependentTask) { /* Here we don't need a barrier (unlike the spreading), * since both tasks only construct vsites from particles, * or local vsites, not from non-local vsites. */ construct_vsites_thread(x, dt, v, ip, tData.idTask.ilist, pbc_null); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } /* Now we can construct the vsites that might depend on other vsites */ construct_vsites_thread(x, dt, v, ip, vsite->tData[vsite->nthreads]->ilist, pbc_null); } } static void spread_vsite2(const t_iatom ia[], real a, const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec fi, fj, dx; t_iatom av, ai, aj; ivec di; int siv, sij; av = ia[1]; ai = ia[2]; aj = ia[3]; svmul(1 - a, f[av], fi); svmul( a, f[av], fj); /* 7 flop */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); /* 6 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); } else { siv = CENTRAL; sij = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); } /* TOTAL: 13 flops */ } void constructVsitesGlobal(const gmx_mtop_t &mtop, gmx::ArrayRef<gmx::RVec> x) { GMX_ASSERT(x.ssize() >= mtop.natoms, "x should contain the whole system"); GMX_ASSERT(!mtop.moleculeBlockIndices.empty(), "molblock indices are needed in constructVsitesGlobal"); for (size_t mb = 0; mb < mtop.molblock.size(); mb++) { const gmx_molblock_t &molb = mtop.molblock[mb]; const gmx_moltype_t &molt = mtop.moltype[molb.type]; if (vsiteIlistNrCount(molt.ilist.data()) > 0) { int atomOffset = mtop.moleculeBlockIndices[mb].globalAtomStart; for (int mol = 0; mol < molb.nmol; mol++) { t_ilist ilist[F_NRE]; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { ilist[ftype].nr = molt.ilist[ftype].size(); ilist[ftype].iatoms = const_cast<t_iatom *>(molt.ilist[ftype].iatoms.data()); } construct_vsites(nullptr, as_rvec_array(x.data()) + atomOffset, 0.0, nullptr, mtop.ffparams.iparams.data(), ilist, epbcNONE, TRUE, nullptr, nullptr); atomOffset += molt.atoms.nr; } } } } static void spread_vsite3(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec fi, fj, fk, dx; int av, ai, aj, ak; ivec di; int siv, sij, sik; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; svmul(1 - a - b, f[av], fi); svmul( a, f[av], fj); svmul( b, f[av], fk); /* 11 flops */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 9 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ia[1]), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ak), di); sik = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); sik = pbc_dx_aiuc(pbc, x[ai], x[ak], dx); } else { siv = CENTRAL; sij = CENTRAL; sik = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL || sik != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); rvec_dec(fshift[sik], fk); } /* TOTAL: 20 flops */ } static void spread_vsite3FD(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { real c, invl, fproj, a1; rvec xvi, xij, xjk, xix, fv, temp; t_iatom av, ai, aj, ak; int svi, sji, skj; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[av], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ /* xix goes from i to point x on the line jk */ xix[XX] = xij[XX]+a*xjk[XX]; xix[YY] = xij[YY]+a*xjk[YY]; xix[ZZ] = xij[ZZ]+a*xjk[ZZ]; /* 6 flops */ invl = gmx::invsqrt(iprod(xix, xix)); c = b*invl; /* 4 + ?10? flops */ fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ temp[XX] = c*(fv[XX]-fproj*xix[XX]); temp[YY] = c*(fv[YY]-fproj*xix[YY]); temp[ZZ] = c*(fv[ZZ]-fproj*xix[ZZ]); /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 26 flops! */ a1 = 1 - a; f[ai][XX] += fv[XX] - temp[XX]; f[ai][YY] += fv[YY] - temp[YY]; f[ai][ZZ] += fv[ZZ] - temp[ZZ]; f[aj][XX] += a1*temp[XX]; f[aj][YY] += a1*temp[YY]; f[aj][ZZ] += a1*temp[ZZ]; f[ak][XX] += a*temp[XX]; f[ak][YY] += a*temp[YY]; f[ak][ZZ] += a*temp[ZZ]; /* 19 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - (1 + a)*temp[XX]; fshift[CENTRAL][YY] += fv[YY] - (1 + a)*temp[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - (1 + a)*temp[ZZ]; fshift[ sji][XX] += temp[XX]; fshift[ sji][YY] += temp[YY]; fshift[ sji][ZZ] += temp[ZZ]; fshift[ skj][XX] += a*temp[XX]; fshift[ skj][YY] += a*temp[YY]; fshift[ skj][ZZ] += a*temp[ZZ]; } if (VirCorr) { /* When VirCorr=TRUE, the virial for the current forces is not * calculated from the redistributed forces. This means that * the effect of non-linear virtual site constructions on the virial * needs to be added separately. This contribution can be calculated * in many ways, but the simplest and cheapest way is to use * the first constructing atom ai as a reference position in space: * subtract (xv-xi)*fv and add (xj-xi)*fj + (xk-xi)*fk. */ rvec xiv; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { /* As xix is a linear combination of j and k, use that here */ dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 61 flops */ } static void spread_vsite3FAD(const t_iatom ia[], real a, real b, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xjk, xperp, Fpij, Fppp, fv, f1, f2, f3; real a1, b1, c1, c2, invdij, invdij2, invdp, fproj; t_iatom av, ai, aj, ak; int svi, sji, skj, d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[ia[1]], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ invdij = gmx::invsqrt(iprod(xij, xij)); invdij2 = invdij * invdij; c1 = iprod(xij, xjk) * invdij2; xperp[XX] = xjk[XX] - c1*xij[XX]; xperp[YY] = xjk[YY] - c1*xij[YY]; xperp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; /* xperp in plane ijk, perp. to ij */ invdp = gmx::invsqrt(iprod(xperp, xperp)); a1 = a*invdij; b1 = b*invdp; /* 45 flops */ /* a1, b1 and c1 are already calculated in constr_vsite3FAD storing them somewhere will save 45 flops! */ fproj = iprod(xij, fv)*invdij2; svmul(fproj, xij, Fpij); /* proj. f on xij */ svmul(iprod(xperp, fv)*invdp*invdp, xperp, Fppp); /* proj. f on xperp */ svmul(b1*fproj, xperp, f3); /* 23 flops */ rvec_sub(fv, Fpij, f1); /* f1 = f - Fpij */ rvec_sub(f1, Fppp, f2); /* f2 = f - Fpij - Fppp */ for (d = 0; (d < DIM); d++) { f1[d] *= a1; f2[d] *= b1; } /* 12 flops */ c2 = 1 + c1; f[ai][XX] += fv[XX] - f1[XX] + c1*f2[XX] + f3[XX]; f[ai][YY] += fv[YY] - f1[YY] + c1*f2[YY] + f3[YY]; f[ai][ZZ] += fv[ZZ] - f1[ZZ] + c1*f2[ZZ] + f3[ZZ]; f[aj][XX] += f1[XX] - c2*f2[XX] - f3[XX]; f[aj][YY] += f1[YY] - c2*f2[YY] - f3[YY]; f[aj][ZZ] += f1[ZZ] - c2*f2[ZZ] - f3[ZZ]; f[ak][XX] += f2[XX]; f[ak][YY] += f2[YY]; f[ak][ZZ] += f2[ZZ]; /* 30 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - f1[XX] - (1-c1)*f2[XX] + f3[XX]; fshift[CENTRAL][YY] += fv[YY] - f1[YY] - (1-c1)*f2[YY] + f3[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - f1[ZZ] - (1-c1)*f2[ZZ] + f3[ZZ]; fshift[ sji][XX] += f1[XX] - c1 *f2[XX] - f3[XX]; fshift[ sji][YY] += f1[YY] - c1 *f2[YY] - f3[YY]; fshift[ sji][ZZ] += f1[ZZ] - c1 *f2[ZZ] - f3[ZZ]; fshift[ skj][XX] += f2[XX]; fshift[ skj][YY] += f2[YY]; fshift[ skj][ZZ] += f2[ZZ]; } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { /* Note that xik=xij+xjk, so we have to add xij*f2 */ dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*(f1[j] + (1 - c2)*f2[j] - f3[j]) + xjk[i]*f2[j]; } } } /* TOTAL: 113 flops */ } static void spread_vsite3OUT(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xik, fv, fj, fk; real cfx, cfy, cfz; int av, ai, aj, ak; ivec di; int svi, sji, ski; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); ski = pbc_rvec_sub(pbc, x[ak], x[ai], xik); /* 6 Flops */ copy_rvec(f[av], fv); cfx = c*fv[XX]; cfy = c*fv[YY]; cfz = c*fv[ZZ]; /* 3 Flops */ fj[XX] = a*fv[XX] - xik[ZZ]*cfy + xik[YY]*cfz; fj[YY] = xik[ZZ]*cfx + a*fv[YY] - xik[XX]*cfz; fj[ZZ] = -xik[YY]*cfx + xik[XX]*cfy + a*fv[ZZ]; fk[XX] = b*fv[XX] + xij[ZZ]*cfy - xij[YY]*cfz; fk[YY] = -xij[ZZ]*cfx + b*fv[YY] + xij[XX]*cfz; fk[ZZ] = xij[YY]*cfx - xij[XX]*cfy + b*fv[ZZ]; /* 30 Flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 15 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); ski = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || ski != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(fshift[sji], fj); rvec_inc(fshift[ski], fk); } if (VirCorr) { rvec xiv; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j]; } } } /* TOTAL: 54 flops */ } static void spread_vsite4FD(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { real d, invl, fproj, a1; rvec xvi, xij, xjk, xjl, xix, fv, temp; int av, ai, aj, ak, al; ivec di; int svi, sji, skj, slj, m; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); slj = pbc_rvec_sub(pbc, x[al], x[aj], xjl); /* 9 flops */ /* xix goes from i to point x on the plane jkl */ for (m = 0; m < DIM; m++) { xix[m] = xij[m] + a*xjk[m] + b*xjl[m]; } /* 12 flops */ invl = gmx::invsqrt(iprod(xix, xix)); d = c*invl; /* 4 + ?10? flops */ copy_rvec(f[av], fv); fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ for (m = 0; m < DIM; m++) { temp[m] = d*(fv[m] - fproj*xix[m]); } /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 35 flops! */ a1 = 1 - a - b; for (m = 0; m < DIM; m++) { f[ai][m] += fv[m] - temp[m]; f[aj][m] += a1*temp[m]; f[ak][m] += a*temp[m]; f[al][m] += b*temp[m]; } /* 26 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, aj), di); slj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL || slj != CENTRAL)) { rvec_dec(fshift[svi], fv); for (m = 0; m < DIM; m++) { fshift[CENTRAL][m] += fv[m] - (1 + a + b)*temp[m]; fshift[ sji][m] += temp[m]; fshift[ skj][m] += a*temp[m]; fshift[ slj][m] += b*temp[m]; } } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 77 flops */ } static void spread_vsite4FDN(const t_iatom ia[], real a, real b, real c, const rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, const t_pbc *pbc, const t_graph *g) { rvec xvi, xij, xik, xil, ra, rb, rja, rjb, rab, rm, rt; rvec fv, fj, fk, fl; real invrm, denom; real cfx, cfy, cfz; ivec di; int av, ai, aj, ak, al; int svi, sij, sik, sil; /* DEBUG: check atom indices */ av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; copy_rvec(f[av], fv); sij = pbc_rvec_sub(pbc, x[aj], x[ai], xij); sik = pbc_rvec_sub(pbc, x[ak], x[ai], xik); sil = pbc_rvec_sub(pbc, x[al], x[ai], xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); rvec_sub(rb, ra, rab); /* 9 flops */ cprod(rja, rjb, rm); /* 9 flops */ invrm = gmx::invsqrt(norm2(rm)); denom = invrm*invrm; /* 5+5+2 flops */ cfx = c*invrm*fv[XX]; cfy = c*invrm*fv[YY]; cfz = c*invrm*fv[ZZ]; /* 6 Flops */ cprod(rm, rab, rt); /* 9 flops */ rt[XX] *= denom; rt[YY] *= denom; rt[ZZ] *= denom; /* 3flops */ fj[XX] = ( -rm[XX]*rt[XX]) * cfx + ( rab[ZZ]-rm[YY]*rt[XX]) * cfy + (-rab[YY]-rm[ZZ]*rt[XX]) * cfz; fj[YY] = (-rab[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( rab[XX]-rm[ZZ]*rt[YY]) * cfz; fj[ZZ] = ( rab[YY]-rm[XX]*rt[ZZ]) * cfx + (-rab[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 30 flops */ cprod(rjb, rm, rt); /* 9 flops */ rt[XX] *= denom*a; rt[YY] *= denom*a; rt[ZZ] *= denom*a; /* 3flops */ fk[XX] = ( -rm[XX]*rt[XX]) * cfx + (-a*rjb[ZZ]-rm[YY]*rt[XX]) * cfy + ( a*rjb[YY]-rm[ZZ]*rt[XX]) * cfz; fk[YY] = ( a*rjb[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + (-a*rjb[XX]-rm[ZZ]*rt[YY]) * cfz; fk[ZZ] = (-a*rjb[YY]-rm[XX]*rt[ZZ]) * cfx + ( a*rjb[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ cprod(rm, rja, rt); /* 9 flops */ rt[XX] *= denom*b; rt[YY] *= denom*b; rt[ZZ] *= denom*b; /* 3flops */ fl[XX] = ( -rm[XX]*rt[XX]) * cfx + ( b*rja[ZZ]-rm[YY]*rt[XX]) * cfy + (-b*rja[YY]-rm[ZZ]*rt[XX]) * cfz; fl[YY] = (-b*rja[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( b*rja[XX]-rm[ZZ]*rt[YY]) * cfz; fl[ZZ] = ( b*rja[YY]-rm[XX]*rt[ZZ]) * cfx + (-b*rja[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); rvec_inc(f[al], fl); /* 21 flops */ if (g) { ivec_sub(SHIFT_IVEC(g, av), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); sik = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, ai), di); sil = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sij != CENTRAL || sik != CENTRAL || sil != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(fshift[sij], fj); rvec_inc(fshift[sik], fk); rvec_inc(fshift[sil], fl); } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j] + xil[i]*fl[j]; } } } /* Total: 207 flops (Yuck!) */ } static int spread_vsiten(const t_iatom ia[], const t_iparams ip[], const rvec x[], rvec f[], rvec fshift[], const t_pbc *pbc, const t_graph *g) { rvec xv, dx, fi; int n3, av, i, ai; real a; ivec di; int siv; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; copy_rvec(x[av], xv); for (i = 0; i < n3; i += 3) { ai = ia[i+2]; if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], xv, dx); } else { siv = CENTRAL; } a = ip[ia[i]].vsiten.a; svmul(a, f[av], fi); rvec_inc(f[ai], fi); if (fshift && siv != CENTRAL) { rvec_inc(fshift[siv], fi); rvec_dec(fshift[CENTRAL], fi); } /* 6 Flops */ } return n3; } static int vsite_count(const t_ilist *ilist, int ftype) { if (ftype == F_VSITEN) { return ilist[ftype].nr/3; } else { return ilist[ftype].nr/(1 + interaction_function[ftype].nratoms); } } static void spread_vsite_f_thread(const rvec x[], rvec f[], rvec *fshift, gmx_bool VirCorr, matrix dxdf, t_iparams ip[], const t_ilist ilist[], const t_graph *g, const t_pbc *pbc_null) { const PbcMode pbcMode = getPbcMode(pbc_null); /* We need another pbc pointer, as with charge groups we switch per vsite */ const t_pbc *pbc_null2 = pbc_null; gmx::ArrayRef<const int> vsite_pbc; /* this loop goes backwards to be able to build * * higher type vsites from lower types */ for (int ftype = c_ftypeVsiteEnd - 1; ftype >= c_ftypeVsiteStart; ftype--) { if (ilist[ftype].nr == 0) { continue; } { // TODO remove me int nra = interaction_function[ftype].nratoms; int inc = 1 + nra; int nr = ilist[ftype].nr; const t_iatom *ia = ilist[ftype].iatoms; if (pbcMode == PbcMode::all) { pbc_null2 = pbc_null; } for (int i = 0; i < nr; ) { int tp = ia[0]; /* Constants for constructing */ real a1, b1, c1; a1 = ip[tp].vsite.a; /* Construct the vsite depending on type */ switch (ftype) { case F_VSITE2: spread_vsite2(ia, a1, x, f, fshift, pbc_null2, g); break; case F_VSITE3: b1 = ip[tp].vsite.b; spread_vsite3(ia, a1, b1, x, f, fshift, pbc_null2, g); break; case F_VSITE3FD: b1 = ip[tp].vsite.b; spread_vsite3FD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3FAD: b1 = ip[tp].vsite.b; spread_vsite3FAD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3OUT: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite3OUT(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FD: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FD(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FDN: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FDN(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITEN: inc = spread_vsiten(ia, ip, x, f, fshift, pbc_null2, g); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } clear_rvec(f[ia[1]]); /* Increment loop variables */ i += inc; ia += inc; } } } } /*! \brief Clears the task force buffer elements that are written by task idTask */ static void clearTaskForceBufferUsedElements(InterdependentTask *idTask) { int ntask = idTask->spreadTask.size(); for (int ti = 0; ti < ntask; ti++) { const AtomIndex *atomList = &idTask->atomIndex[idTask->spreadTask[ti]]; int natom = atomList->atom.size(); RVec *force = idTask->force.data(); for (int i = 0; i < natom; i++) { clear_rvec(force[atomList->atom[i]]); } } } void spread_vsite_f(const gmx_vsite_t *vsite, const rvec * gmx_restrict x, rvec * gmx_restrict f, rvec * gmx_restrict fshift, gmx_bool VirCorr, matrix vir, t_nrnb *nrnb, const t_idef *idef, int ePBC, gmx_bool bMolPBC, const t_graph *g, const matrix box, const t_commrec *cr, gmx_wallcycle *wcycle) { wallcycle_start(wcycle, ewcVSITESPREAD); const bool useDomdec = vsite->useDomdec; GMX_ASSERT(!useDomdec || (cr != nullptr && DOMAINDECOMP(cr)), "When vsites are set up with domain decomposition, we need a valid commrec"); t_pbc pbc, *pbc_null; /* We only need to do pbc when we have inter-cg vsites */ if ((useDomdec || bMolPBC) && vsite->numInterUpdategroupVsites) { /* This is wasting some CPU time as we now do this multiple times * per MD step. */ pbc_null = set_pbc_dd(&pbc, ePBC, useDomdec ? cr->dd->nc : nullptr, FALSE, box); } else { pbc_null = nullptr; } if (useDomdec) { dd_clear_f_vsites(cr->dd, f); } if (vsite->nthreads == 1) { matrix dxdf; if (VirCorr) { clear_mat(dxdf); } spread_vsite_f_thread(x, f, fshift, VirCorr, dxdf, idef->iparams, idef->il, g, pbc_null); if (VirCorr) { for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { vir[i][j] += -0.5*dxdf[i][j]; } } } } else { /* First spread the vsites that might depend on non-local vsites */ if (VirCorr) { clear_mat(vsite->tData[vsite->nthreads]->dxdf); } spread_vsite_f_thread(x, f, fshift, VirCorr, vsite->tData[vsite->nthreads]->dxdf, idef->iparams, vsite->tData[vsite->nthreads]->ilist, g, pbc_null); #pragma omp parallel num_threads(vsite->nthreads) { try { int thread = gmx_omp_get_thread_num(); VsiteThread &tData = *vsite->tData[thread]; rvec *fshift_t; if (thread == 0 || fshift == nullptr) { fshift_t = fshift; } else { fshift_t = tData.fshift; for (int i = 0; i < SHIFTS; i++) { clear_rvec(fshift_t[i]); } } if (VirCorr) { clear_mat(tData.dxdf); } if (tData.useInterdependentTask) { /* Spread the vsites that spread outside our local range. * This is done using a thread-local force buffer force. * First we need to copy the input vsite forces to force. */ InterdependentTask *idTask = &tData.idTask; /* Clear the buffer elements set by our task during * the last call to spread_vsite_f. */ clearTaskForceBufferUsedElements(idTask); int nvsite = idTask->vsite.size(); for (int i = 0; i < nvsite; i++) { copy_rvec(f[idTask->vsite[i]], idTask->force[idTask->vsite[i]]); } spread_vsite_f_thread(x, as_rvec_array(idTask->force.data()), fshift_t, VirCorr, tData.dxdf, idef->iparams, tData.idTask.ilist, g, pbc_null); /* We need a barrier before reducing forces below * that have been produced by a different thread above. */ #pragma omp barrier /* Loop over all thread task and reduce forces they * produced on atoms that fall in our range. * Note that atomic reduction would be a simpler solution, * but that might not have good support on all platforms. */ int ntask = idTask->reduceTask.size(); for (int ti = 0; ti < ntask; ti++) { const InterdependentTask *idt_foreign = &vsite->tData[idTask->reduceTask[ti]]->idTask; const AtomIndex *atomList = &idt_foreign->atomIndex[thread]; const RVec *f_foreign = idt_foreign->force.data(); int natom = atomList->atom.size(); for (int i = 0; i < natom; i++) { int ind = atomList->atom[i]; rvec_inc(f[ind], f_foreign[ind]); /* Clearing of f_foreign is done at the next step */ } } /* Clear the vsite forces, both in f and force */ for (int i = 0; i < nvsite; i++) { int ind = tData.idTask.vsite[i]; clear_rvec(f[ind]); clear_rvec(tData.idTask.force[ind]); } } /* Spread the vsites that spread locally only */ spread_vsite_f_thread(x, f, fshift_t, VirCorr, tData.dxdf, idef->iparams, tData.ilist, g, pbc_null); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } if (fshift != nullptr) { for (int th = 1; th < vsite->nthreads; th++) { for (int i = 0; i < SHIFTS; i++) { rvec_inc(fshift[i], vsite->tData[th]->fshift[i]); } } } if (VirCorr) { for (int th = 0; th < vsite->nthreads + 1; th++) { /* MSVC doesn't like matrix references, so we use a pointer */ const matrix *dxdf = &vsite->tData[th]->dxdf; for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { vir[i][j] += -0.5*(*dxdf)[i][j]; } } } } } if (useDomdec) { dd_move_f_vsites(cr->dd, f, fshift); } inc_nrnb(nrnb, eNR_VSITE2, vsite_count(idef->il, F_VSITE2)); inc_nrnb(nrnb, eNR_VSITE3, vsite_count(idef->il, F_VSITE3)); inc_nrnb(nrnb, eNR_VSITE3FD, vsite_count(idef->il, F_VSITE3FD)); inc_nrnb(nrnb, eNR_VSITE3FAD, vsite_count(idef->il, F_VSITE3FAD)); inc_nrnb(nrnb, eNR_VSITE3OUT, vsite_count(idef->il, F_VSITE3OUT)); inc_nrnb(nrnb, eNR_VSITE4FD, vsite_count(idef->il, F_VSITE4FD)); inc_nrnb(nrnb, eNR_VSITE4FDN, vsite_count(idef->il, F_VSITE4FDN)); inc_nrnb(nrnb, eNR_VSITEN, vsite_count(idef->il, F_VSITEN)); wallcycle_stop(wcycle, ewcVSITESPREAD); } /*! \brief Returns the an array with group indices for each atom * * \param[in] grouping The paritioning of the atom range into atom groups */ static std::vector<int> makeAtomToGroupMapping(const gmx::RangePartitioning &grouping) { std::vector<int> atomToGroup(grouping.fullRange().end(), 0); for (int group = 0; group < grouping.numBlocks(); group++) { auto block = grouping.block(group); std::fill(atomToGroup.begin() + block.begin(), atomToGroup.begin() + block.end(), group); } return atomToGroup; } int countNonlinearVsites(const gmx_mtop_t &mtop) { int numNonlinearVsites = 0; for (const gmx_molblock_t &molb : mtop.molblock) { const gmx_moltype_t &molt = mtop.moltype[molb.type]; for (const auto &ilist : extractILists(molt.ilist, IF_VSITE)) { if (ilist.functionType != F_VSITE2 && ilist.functionType != F_VSITE3 && ilist.functionType != F_VSITEN) { numNonlinearVsites += molb.nmol*ilist.iatoms.size()/(1 + NRAL(ilist.functionType)); } } } return numNonlinearVsites; } int countInterUpdategroupVsites(const gmx_mtop_t &mtop, gmx::ArrayRef<const gmx::RangePartitioning> updateGroupingPerMoleculetype) { int n_intercg_vsite = 0; for (const gmx_molblock_t &molb : mtop.molblock) { const gmx_moltype_t &molt = mtop.moltype[molb.type]; std::vector<int> atomToGroup; if (!updateGroupingPerMoleculetype.empty()) { atomToGroup = makeAtomToGroupMapping(updateGroupingPerMoleculetype[molb.type]); } for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { const int nral = NRAL(ftype); const InteractionList &il = molt.ilist[ftype]; for (int i = 0; i < il.size(); i += 1 + nral) { bool isInterGroup = atomToGroup.empty(); if (!isInterGroup) { const int group = atomToGroup[il.iatoms[1 + i]]; for (int a = 1; a < nral; a++) { if (atomToGroup[il.iatoms[1 + a]] != group) { isInterGroup = true; break; } } } if (isInterGroup) { n_intercg_vsite += molb.nmol; } } } } return n_intercg_vsite; } std::unique_ptr<gmx_vsite_t> initVsite(const gmx_mtop_t &mtop, const t_commrec *cr) { GMX_RELEASE_ASSERT(cr != nullptr, "We need a valid commrec"); std::unique_ptr<gmx_vsite_t> vsite; /* check if there are vsites */ int nvsite = 0; for (int ftype = 0; ftype < F_NRE; ftype++) { if (interaction_function[ftype].flags & IF_VSITE) { GMX_ASSERT(ftype >= c_ftypeVsiteStart && ftype < c_ftypeVsiteEnd, "c_ftypeVsiteStart and/or c_ftypeVsiteEnd do not have correct values"); nvsite += gmx_mtop_ftype_count(&mtop, ftype); } else { GMX_ASSERT(ftype < c_ftypeVsiteStart || ftype >= c_ftypeVsiteEnd, "c_ftypeVsiteStart and/or c_ftypeVsiteEnd do not have correct values"); } } if (nvsite == 0) { return vsite; } vsite = std::make_unique<gmx_vsite_t>(); gmx::ArrayRef<const gmx::RangePartitioning> updateGroupingPerMoleculetype; if (DOMAINDECOMP(cr)) { updateGroupingPerMoleculetype = getUpdateGroupingPerMoleculetype(*cr->dd); } vsite->numInterUpdategroupVsites = countInterUpdategroupVsites(mtop, updateGroupingPerMoleculetype); vsite->useDomdec = (DOMAINDECOMP(cr) && cr->dd->nnodes > 1); vsite->nthreads = gmx_omp_nthreads_get(emntVSITE); if (vsite->nthreads > 1) { /* We need one extra thread data structure for the overlap vsites */ vsite->tData.resize(vsite->nthreads + 1); #pragma omp parallel for num_threads(vsite->nthreads) schedule(static) for (int thread = 0; thread < vsite->nthreads; thread++) { try { vsite->tData[thread] = std::make_unique<VsiteThread>(); InterdependentTask &idTask = vsite->tData[thread]->idTask; idTask.nuse = 0; idTask.atomIndex.resize(vsite->nthreads); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } if (vsite->nthreads > 1) { vsite->tData[vsite->nthreads] = std::make_unique<VsiteThread>(); } } return vsite; } gmx_vsite_t::gmx_vsite_t() { } gmx_vsite_t::~gmx_vsite_t() { } static inline void flagAtom(InterdependentTask *idTask, int atom, int thread, int nthread, int natperthread) { if (!idTask->use[atom]) { idTask->use[atom] = true; thread = atom/natperthread; /* Assign all non-local atom force writes to thread 0 */ if (thread >= nthread) { thread = 0; } idTask->atomIndex[thread].atom.push_back(atom); } } /*\brief Here we try to assign all vsites that are in our local range. * * Our task local atom range is tData->rangeStart - tData->rangeEnd. * Vsites that depend only on local atoms, as indicated by taskIndex[]==thread, * are assigned to task tData->ilist. Vsites that depend on non-local atoms * but not on other vsites are assigned to task tData->id_task.ilist. * taskIndex[] is set for all vsites in our range, either to our local tasks * or to the single last task as taskIndex[]=2*nthreads. */ static void assignVsitesToThread(VsiteThread *tData, int thread, int nthread, int natperthread, gmx::ArrayRef<int> taskIndex, const t_ilist *ilist, const t_iparams *ip, const unsigned short *ptype) { for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { tData->ilist[ftype].nr = 0; tData->idTask.ilist[ftype].nr = 0; int nral1 = 1 + NRAL(ftype); int inc = nral1; t_iatom *iat = ilist[ftype].iatoms; for (int i = 0; i < ilist[ftype].nr; ) { if (ftype == F_VSITEN) { /* The 3 below is from 1+NRAL(ftype)=3 */ inc = ip[iat[i]].vsiten.n*3; } if (iat[1 + i] < tData->rangeStart || iat[1 + i] >= tData->rangeEnd) { /* This vsite belongs to a different thread */ i += inc; continue; } /* We would like to assign this vsite to task thread, * but it might depend on atoms outside the atom range of thread * or on another vsite not assigned to task thread. */ int task = thread; if (ftype != F_VSITEN) { for (int j = i + 2; j < i + nral1; j++) { /* Do a range check to avoid a harmless race on taskIndex */ if (iat[j] < tData->rangeStart || iat[j] >= tData->rangeEnd || taskIndex[iat[j]] != thread) { if (!tData->useInterdependentTask || ptype[iat[j]] == eptVSite) { /* At least one constructing atom is a vsite * that is not assigned to the same thread. * Put this vsite into a separate task. */ task = 2*nthread; break; } /* There are constructing atoms outside our range, * put this vsite into a second task to be executed * on the same thread. During construction no barrier * is needed between the two tasks on the same thread. * During spreading we need to run this task with * an additional thread-local intermediate force buffer * (or atomic reduction) and a barrier between the two * tasks. */ task = nthread + thread; } } } else { for (int j = i + 2; j < i + inc; j += 3) { /* Do a range check to avoid a harmless race on taskIndex */ if (iat[j] < tData->rangeStart || iat[j] >= tData->rangeEnd || taskIndex[iat[j]] != thread) { GMX_ASSERT(ptype[iat[j]] != eptVSite, "A vsite to be assigned in assignVsitesToThread has a vsite as a constructing atom that does not belong to our task, such vsites should be assigned to the single 'master' task"); task = nthread + thread; } } } /* Update this vsite's thread index entry */ taskIndex[iat[1+i]] = task; if (task == thread || task == nthread + thread) { /* Copy this vsite to the thread data struct of thread */ t_ilist *il_task; if (task == thread) { il_task = &tData->ilist[ftype]; } else { il_task = &tData->idTask.ilist[ftype]; } /* Ensure we have sufficient memory allocated */ if (il_task->nr + inc > il_task->nalloc) { il_task->nalloc = over_alloc_large(il_task->nr + inc); srenew(il_task->iatoms, il_task->nalloc); } /* Copy the vsite data to the thread-task local array */ for (int j = i; j < i + inc; j++) { il_task->iatoms[il_task->nr++] = iat[j]; } if (task == nthread + thread) { /* This vsite write outside our own task force block. * Put it into the interdependent task list and flag * the atoms involved for reduction. */ tData->idTask.vsite.push_back(iat[i + 1]); if (ftype != F_VSITEN) { for (int j = i + 2; j < i + nral1; j++) { flagAtom(&tData->idTask, iat[j], thread, nthread, natperthread); } } else { for (int j = i + 2; j < i + inc; j += 3) { flagAtom(&tData->idTask, iat[j], thread, nthread, natperthread); } } } } i += inc; } } } /*! \brief Assign all vsites with taskIndex[]==task to task tData */ static void assignVsitesToSingleTask(VsiteThread *tData, int task, gmx::ArrayRef<const int> taskIndex, const t_ilist *ilist, const t_iparams *ip) { for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { tData->ilist[ftype].nr = 0; tData->idTask.ilist[ftype].nr = 0; int nral1 = 1 + NRAL(ftype); int inc = nral1; t_iatom *iat = ilist[ftype].iatoms; t_ilist *il_task = &tData->ilist[ftype]; for (int i = 0; i < ilist[ftype].nr; ) { if (ftype == F_VSITEN) { /* The 3 below is from 1+NRAL(ftype)=3 */ inc = ip[iat[i]].vsiten.n*3; } /* Check if the vsite is assigned to our task */ if (taskIndex[iat[1 + i]] == task) { /* Ensure we have sufficient memory allocated */ if (il_task->nr + inc > il_task->nalloc) { il_task->nalloc = over_alloc_large(il_task->nr + inc); srenew(il_task->iatoms, il_task->nalloc); } /* Copy the vsite data to the thread-task local array */ for (int j = i; j < i + inc; j++) { il_task->iatoms[il_task->nr++] = iat[j]; } } i += inc; } } } void split_vsites_over_threads(const t_ilist *ilist, const t_iparams *ip, const t_mdatoms *mdatoms, gmx_vsite_t *vsite) { int vsite_atom_range, natperthread; if (vsite->nthreads == 1) { /* Nothing to do */ return; } /* The current way of distributing the vsites over threads in primitive. * We divide the atom range 0 - natoms_in_vsite uniformly over threads, * without taking into account how the vsites are distributed. * Without domain decomposition we at least tighten the upper bound * of the range (useful for common systems such as a vsite-protein * in 3-site water). * With domain decomposition, as long as the vsites are distributed * uniformly in each domain along the major dimension, usually x, * it will also perform well. */ if (!vsite->useDomdec) { vsite_atom_range = -1; for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { { // TODO remove me if (ftype != F_VSITEN) { int nral1 = 1 + NRAL(ftype); const t_iatom *iat = ilist[ftype].iatoms; for (int i = 0; i < ilist[ftype].nr; i += nral1) { for (int j = i + 1; j < i + nral1; j++) { vsite_atom_range = std::max(vsite_atom_range, iat[j]); } } } else { int vs_ind_end; const t_iatom *iat = ilist[ftype].iatoms; int i = 0; while (i < ilist[ftype].nr) { /* The 3 below is from 1+NRAL(ftype)=3 */ vs_ind_end = i + ip[iat[i]].vsiten.n*3; vsite_atom_range = std::max(vsite_atom_range, iat[i+1]); while (i < vs_ind_end) { vsite_atom_range = std::max(vsite_atom_range, iat[i+2]); i += 3; } } } } } vsite_atom_range++; natperthread = (vsite_atom_range + vsite->nthreads - 1)/vsite->nthreads; } else { /* Any local or not local atom could be involved in virtual sites. * But since we usually have very few non-local virtual sites * (only non-local vsites that depend on local vsites), * we distribute the local atom range equally over the threads. * When assigning vsites to threads, we should take care that the last * threads also covers the non-local range. */ vsite_atom_range = mdatoms->nr; natperthread = (mdatoms->homenr + vsite->nthreads - 1)/vsite->nthreads; } if (debug) { fprintf(debug, "virtual site thread dist: natoms %d, range %d, natperthread %d\n", mdatoms->nr, vsite_atom_range, natperthread); } /* To simplify the vsite assignment, we make an index which tells us * to which task particles, both non-vsites and vsites, are assigned. */ vsite->taskIndex.resize(mdatoms->nr); /* Initialize the task index array. Here we assign the non-vsite * particles to task=thread, so we easily figure out if vsites * depend on local and/or non-local particles in assignVsitesToThread. */ gmx::ArrayRef<int> taskIndex = vsite->taskIndex; { int thread = 0; for (int i = 0; i < mdatoms->nr; i++) { if (mdatoms->ptype[i] == eptVSite) { /* vsites are not assigned to a task yet */ taskIndex[i] = -1; } else { /* assign non-vsite particles to task thread */ taskIndex[i] = thread; } if (i == (thread + 1)*natperthread && thread < vsite->nthreads) { thread++; } } } #pragma omp parallel num_threads(vsite->nthreads) { try { int thread = gmx_omp_get_thread_num(); VsiteThread &tData = *vsite->tData[thread]; /* Clear the buffer use flags that were set before */ if (tData.useInterdependentTask) { InterdependentTask &idTask = tData.idTask; /* To avoid an extra OpenMP barrier in spread_vsite_f, * we clear the force buffer at the next step, * so we need to do it here as well. */ clearTaskForceBufferUsedElements(&idTask); idTask.vsite.resize(0); for (int t = 0; t < vsite->nthreads; t++) { AtomIndex &atomIndex = idTask.atomIndex[t]; int natom = atomIndex.atom.size(); for (int i = 0; i < natom; i++) { idTask.use[atomIndex.atom[i]] = false; } atomIndex.atom.resize(0); } idTask.nuse = 0; } /* To avoid large f_buf allocations of #threads*vsite_atom_range * we don't use task2 with more than 200000 atoms. This doesn't * affect performance, since with such a large range relatively few * vsites will end up in the separate task. * Note that useTask2 should be the same for all threads. */ tData.useInterdependentTask = (vsite_atom_range <= 200000); if (tData.useInterdependentTask) { size_t natoms_use_in_vsites = vsite_atom_range; InterdependentTask &idTask = tData.idTask; /* To avoid resizing and re-clearing every nstlist steps, * we never down size the force buffer. */ if (natoms_use_in_vsites > idTask.force.size() || natoms_use_in_vsites > idTask.use.size()) { idTask.force.resize(natoms_use_in_vsites, { 0, 0, 0 }); idTask.use.resize(natoms_use_in_vsites, false); } } /* Assign all vsites that can execute independently on threads */ tData.rangeStart = thread *natperthread; if (thread < vsite->nthreads - 1) { tData.rangeEnd = (thread + 1)*natperthread; } else { /* The last thread should cover up to the end of the range */ tData.rangeEnd = mdatoms->nr; } assignVsitesToThread(&tData, thread, vsite->nthreads, natperthread, taskIndex, ilist, ip, mdatoms->ptype); if (tData.useInterdependentTask) { /* In the worst case, all tasks write to force ranges of * all other tasks, leading to #tasks^2 scaling (this is only * the overhead, the actual flops remain constant). * But in most cases there is far less coupling. To improve * scaling at high thread counts we therefore construct * an index to only loop over the actually affected tasks. */ InterdependentTask &idTask = tData.idTask; /* Ensure assignVsitesToThread finished on other threads */ #pragma omp barrier idTask.spreadTask.resize(0); idTask.reduceTask.resize(0); for (int t = 0; t < vsite->nthreads; t++) { /* Do we write to the force buffer of task t? */ if (!idTask.atomIndex[t].atom.empty()) { idTask.spreadTask.push_back(t); } /* Does task t write to our force buffer? */ if (!vsite->tData[t]->idTask.atomIndex[thread].atom.empty()) { idTask.reduceTask.push_back(t); } } } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; } /* Assign all remaining vsites, that will have taskIndex[]=2*vsite->nthreads, * to a single task that will not run in parallel with other tasks. */ assignVsitesToSingleTask(vsite->tData[vsite->nthreads].get(), 2*vsite->nthreads, taskIndex, ilist, ip); if (debug && vsite->nthreads > 1) { fprintf(debug, "virtual site useInterdependentTask %d, nuse:\n", static_cast<int>(vsite->tData[0]->useInterdependentTask)); for (int th = 0; th < vsite->nthreads + 1; th++) { fprintf(debug, " %4d", vsite->tData[th]->idTask.nuse); } fprintf(debug, "\n"); for (int ftype = c_ftypeVsiteStart; ftype < c_ftypeVsiteEnd; ftype++) { if (ilist[ftype].nr > 0) { fprintf(debug, "%-20s thread dist:", interaction_function[ftype].longname); for (int th = 0; th < vsite->nthreads + 1; th++) { fprintf(debug, " %4d %4d ", vsite->tData[th]->ilist[ftype].nr, vsite->tData[th]->idTask.ilist[ftype].nr); } fprintf(debug, "\n"); } } } #ifndef NDEBUG int nrOrig = vsiteIlistNrCount(ilist); int nrThreaded = 0; for (int th = 0; th < vsite->nthreads + 1; th++) { nrThreaded += vsiteIlistNrCount(vsite->tData[th]->ilist) + vsiteIlistNrCount(vsite->tData[th]->idTask.ilist); } GMX_ASSERT(nrThreaded == nrOrig, "The number of virtual sites assigned to all thread task has to match the total number of virtual sites"); #endif } void set_vsite_top(gmx_vsite_t *vsite, const gmx_localtop_t *top, const t_mdatoms *md) { if (vsite->nthreads > 1) { split_vsites_over_threads(top->idef.il, top->idef.iparams, md, vsite); } }
32.621464
240
0.471908
berkhess
063df958db48db62653a3fce4d9098ce1493cc54
1,274
cpp
C++
test/test.cpp
nuclearczy/Terp-tag-test
f1b8db368cbc74c0d9ce4cc96233b5d5ce2465af
[ "BSD-3-Clause" ]
null
null
null
test/test.cpp
nuclearczy/Terp-tag-test
f1b8db368cbc74c0d9ce4cc96233b5d5ce2465af
[ "BSD-3-Clause" ]
null
null
null
test/test.cpp
nuclearczy/Terp-tag-test
f1b8db368cbc74c0d9ce4cc96233b5d5ce2465af
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2019 Hao Da (Kevin) Dong * @file test.cpp * @date 2019/11/10 * @brief Unit tests for talker.cpp * @license This project is released under the BSD-3-Clause License. See full details in LICENSE. */ #include <gtest/gtest.h> #include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/printString.h" // I have no idea why this is required for rostest/gtest to work... std::shared_ptr<ros::NodeHandle> nh; /** * @brief Tests the output of the printString service */ TEST(TalkerTestSuite, transformTest) { // Create client to test printString service ros::ServiceClient testClient = nh->serviceClient<beginner_tutorials::printString>("printString"); // Create printString service object beginner_tutorials::printString srv; // Call printString service srv.request.name = "Kevin"; testClient.call(srv); EXPECT_EQ(srv.response.returnMsg, "This ROS service exists to serve the master: Kevin"); } // Initialize ROS and run all the tests that were declared with TEST() int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "serviceTest"); nh.reset(new ros::NodeHandle); // Once again: WHY?? return RUN_ALL_TESTS(); }
31.073171
102
0.696232
nuclearczy