hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
d77009683cc72fd70801fe2ce8c1481f14d22fd4
3,331
cc
C++
experiments/conductivity_inverse/conductivity_inverse.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
experiments/conductivity_inverse/conductivity_inverse.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
experiments/conductivity_inverse/conductivity_inverse.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
#include <MeshIO.hh> #include <MSHFieldWriter.hh> #include "Conductivity.hh" using namespace std; template<size_t N, size_t Deg> void execute(const vector<MeshIO::IOVertex> &inVertices, const vector<MeshIO::IOElement> &inElements) { FEMMesh<N, Deg, VectorND<N>> omega(inElements, inVertices); std::vector<Real> f(omega.numNodes()), a(omega.numNodes()); for (auto n : omega.nodes()) { Real x = n->p[0], y = n->p[1]; f[n.index()] = sin(2 * M_PI * x * y); a[n.index()] = 1.5 + cos(0.5 * M_PI * x * y); } MSHFieldWriter writer("out.msh", omega, false); // Compute forward solution and residual auto u = Conductivity::solveForwardProblem(omega, a, f); auto b = Conductivity::load(omega, f); auto L = Conductivity::forwardProblemMatrix(omega, a); auto r = ScalarField<Real>(L.apply(u)) - ScalarField<Real>(b); // Dirichlet load auto a_inferred = Conductivity::solveDirectInverseProblem(omega, u, a, f, r, writer); auto L_ainf = Conductivity::forwardProblemMatrix(omega, a_inferred); auto r_ainf = ScalarField<Real>(L_ainf.apply(u)) - ScalarField<Real>(b); auto L_1 = Conductivity::forwardProblemMatrix(omega, std::vector<Real>(omega.numNodes(), 1.0)); auto r_1 = ScalarField<Real>(L_1.apply(u)) - ScalarField<Real>(b); // Compute inverse system residual auto M = Conductivity::directInverseProblemMatrix(omega, u); ScalarField<Real> ma = ScalarField<Real>(M.apply(a)); ScalarField<Real> m_ainf = ScalarField<Real>(M.apply(a_inferred)); ScalarField<Real> mr = ma - ScalarField<Real>(b); ScalarField<Real> mr_ainf = m_ainf - ScalarField<Real>(b); ScalarField<Real> mr_a1 = ScalarField<Real>(M.apply(std::vector<Real>(omega.numNodes(), 1.0))) - ScalarField<Real>(b); ScalarField<Real> bsurf = ScalarField<Real>(Conductivity::surfaceLoad(omega, u, a)); writer.addField("f", ScalarField<Real>(f)); writer.addField("a", ScalarField<Real>(a)); writer.addField("u", ScalarField<Real>(u)); writer.addField("a_inferred", ScalarField<Real>(a_inferred)); writer.addField("a_infered residual", ScalarField<Real>(r_ainf)); writer.addField("a residual", ScalarField<Real>(r)); writer.addField("a=1 residual", ScalarField<Real>(r_1)); writer.addField("M * a", ma); writer.addField("M * a_inf", m_ainf); writer.addField("Mr", mr); writer.addField("Mr_ainf", mr_ainf); // writer.addField("Mr a = 1", mr_a1); writer.addField("bsurf", bsurf); writer.addField("load", ScalarField<Real>(b)); } int main(int argc, char *argv[]) { vector<MeshIO::IOVertex> inVertices; vector<MeshIO::IOElement> inElements; // usage: mesh_path fem_degree string meshPath = argv[1]; size_t deg = stoi(argv[2]); auto type = load(meshPath, inVertices, inElements, MeshIO::FMT_GUESS, MeshIO::MESH_GUESS); // Infer dimension from mesh type. size_t dim; if (type == MeshIO::MESH_TET) dim = 3; else if (type == MeshIO::MESH_TRI) dim = 2; else throw std::runtime_error("Mesh must be pure triangle or tet."); auto exec = (dim == 3) ? ((deg == 2) ? execute<3, 2> : execute<3, 1>) : ((deg == 2) ? execute<2, 2> : execute<2, 1>); exec(inVertices, inElements); return 0; }
37.852273
122
0.646052
[ "mesh", "vector" ]
d772b099c51c3496042853cbfe64061cb9a720c4
565
hpp
C++
Samples/Flags/Flagpole.hpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
4
2021-03-05T05:49:34.000Z
2022-03-30T15:30:46.000Z
Samples/Flags/Flagpole.hpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
null
null
null
Samples/Flags/Flagpole.hpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
null
null
null
#pragma once #include <RavEngine/Entity.hpp> #include <RavEngine/BuiltinMaterials.hpp> #include <vector> struct FlagMat : public RavEngine::PBRMaterial{ FlagMat() : PBRMaterial("flag"){} }; struct FlagMatInst : public RavEngine::PBRMaterialInstance{ FlagMatInst(Ref<FlagMat> f) : PBRMaterialInstance(f){} }; struct Flagpole : public RavEngine::Entity{ Flagpole(); struct entry{ std::string name; Ref<RavEngine::PBRMaterialInstance> matInst; }; RavEngine::Vector<entry> flags; void SwitchToFlag(uint16_t idx); };
22.6
59
0.697345
[ "vector" ]
d7738676a69f9a9b9fc42799f978ad3406439dd7
6,405
cc
C++
python_bindings/metric_fit.cc
jpanetta/Inflatables
6941fb1bf4a2f61a847605aea37adef97bf05d76
[ "MIT" ]
10
2021-10-05T18:52:48.000Z
2022-03-16T06:35:04.000Z
python_bindings/metric_fit.cc
jpanetta/Inflatables
6941fb1bf4a2f61a847605aea37adef97bf05d76
[ "MIT" ]
null
null
null
python_bindings/metric_fit.cc
jpanetta/Inflatables
6941fb1bf4a2f61a847605aea37adef97bf05d76
[ "MIT" ]
2
2021-09-24T22:26:45.000Z
2021-10-14T21:51:18.000Z
#include <iostream> #include <iomanip> #include <sstream> #include <utility> #include <memory> #include <MeshFEM/GlobalBenchmark.hh> #include <MeshFEM/MeshIO.hh> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/eigen.h> #include <pybind11/iostream.h> #include <pybind11/functional.h> namespace py = pybind11; #include "../BendingEnergy.hh" #include "../MetricFitter.hh" #include "../CollapsePreventionEnergy.hh" #include "../fit_metric_newton.hh" PYBIND11_MODULE(metric_fit, m) { m.doc() = "Metric-fitting surface immersion optimization"; py::module::import("py_newton_optimizer"); //////////////////////////////////////////////////////////////////////////////// // Free-standing functions //////////////////////////////////////////////////////////////////////////////// m.def("fit_metric_newton", &fit_metric_newton, py::arg("mfit"), py::arg("fixedVars"), py::arg("options") = NewtonOptimizerOptions(), py::arg("callback") = nullptr); //////////////////////////////////////////////////////////////////////////////// // Mesh construction (for mesh type used by metric fitting routines) //////////////////////////////////////////////////////////////////////////////// using Mesh = MetricFitter::Mesh; // WARNING: Mesh's holder type is a shared_ptr; returning a unique_ptr will lead to a dangling pointer in the current version of Pybind11 m.def("Mesh", [](const std::string &path) { return std::shared_ptr<Mesh>(Mesh::load(path)); }, py::arg("path")); m.def("Mesh", [](const Eigen::MatrixX2d &V, const Eigen::MatrixX3i &F) { return std::make_shared<Mesh>(F, V); }, py::arg("V"), py::arg("F")); m.def("Mesh", [](const Eigen::MatrixX3d &V, const Eigen::MatrixX3i &F) { return std::make_shared<Mesh>(F, V); }, py::arg("V"), py::arg("F")); using HE = HingeEnergy<double>; py::class_<HE>(m, "HingeEnergy") .def(py::init<const Point3D &, const Point3D &, const Point3D &, const Point3D &>(), py::arg("p0"), py::arg("p1"), py::arg("p2"), py::arg("p3")) .def("setDeformedConfiguration", &HE::setDeformedConfiguration, py::arg("p0"), py::arg("p1"), py::arg("p2"), py::arg("p3")) .def("gradTheta", &HE::gradTheta) .def("hessTheta", &HE::hessTheta) .def_readonly("e_bar_len", &HE::e_bar_len) .def_readonly("h_bar" , &HE::h_bar) .def_readonly("theta_bar", &HE::theta_bar) .def_readonly("e_len" , &HE::e_len) .def_readonly("theta" , &HE::theta) .def_readonly("deformed_pts", &HE::deformed_pts) .def("energy" , &HE::energy) .def("gradient", &HE::gradient) .def("hessian" , &HE::hessian) ; using CPE = CollapsePreventionEnergyDet; py::class_<CPE>(m, "CollapsePreventionEnergyDet") .def(py::init<>()) .def_property("activationThreshold", &CPE::activationThreshold, &CPE::setActivationThreshold) .def("setMatrix", [](CPE &cpe, const Eigen::Matrix2d &C) { cpe.setMatrix(C); }) .def("energy", &CPE::energy) .def("denergy", &CPE::denergy) .def("delta_denergy", [](const CPE &cpe, const Eigen::Matrix2d &dC) { return cpe.delta_denergy(dC).cast<double>(); }) // det-specific functions for debugging. .def("setDet", &CPE::setDet) .def("det", &CPE::det ) .def("normalizedDet", &CPE::normalizedDet) .def("denergy_ddet", &CPE::denergy_ddet) .def("d2energy_d2det", &CPE::d2energy_d2det) ; py::class_<MetricFitter> pyMetricFitter(m, "MetricFitter"); using EnergyType = MetricFitter::EnergyType; py::enum_<EnergyType>(pyMetricFitter, "EnergyType") .value("Full" , EnergyType::Full) .value("MetricFitting", EnergyType::MetricFitting) .value("Bending" , EnergyType::Bending) .value("Gravitational", EnergyType::Gravitational) .value("CollapsePrevention", EnergyType::CollapsePrevention) ; pyMetricFitter .def(py::init<const std::shared_ptr<Mesh> &>(), py::arg("mesh")) .def("mesh", &MetricFitter::meshPtr) .def_property_readonly("rigidMotionPinVars", [](const MetricFitter &mf) { return mf.rigidMotionPinVars(); }) .def("numVars", &MetricFitter::numVars) .def("getVars", &MetricFitter::getVars) .def("setVars", &MetricFitter::setVars) .def("setIdentityImmersion", &MetricFitter::setIdentityImmersion) .def("getIdentityImmersion", &MetricFitter::getIdentityImmersion) .def( "setImmersion", &MetricFitter:: setImmersion) .def( "getImmersion", &MetricFitter:: getImmersion) .def_property_readonly("rigidMotionPinVars", [](const MetricFitter &mf) { return mf.rigidMotionPinVars(); }) .def("setTargetMetric", &MetricFitter::setTargetMetric, py::arg("targetMetric"), py::arg("relativeCollapsePreventionThreshold") = 0.25) .def("setCurrentMetricAsTarget", &MetricFitter::setCurrentMetricAsTarget, py::arg("relativeCollapsePreventionThreshold") = 0.25) .def_readwrite("bendingStiffness", &MetricFitter::bendingStiffness) .def_readwrite("collapsePreventionWeight", &MetricFitter::collapsePreventionWeight) .def_readwrite("gravityVector", &MetricFitter::gravityVector) .def("energy", &MetricFitter::energy , py::arg("energyType") = EnergyType::Full) .def("gradient", &MetricFitter::gradient, py::arg("energyType") = EnergyType::Full) .def("hessian", py::overload_cast<EnergyType>(&MetricFitter::hessian, py::const_), py::arg("energyType") = EnergyType::Full) .def("hinge", &MetricFitter::hinge, py::arg("hingeIdx")) .def("numHinges", &MetricFitter::numHinges) .def("getIncidentHinges", &MetricFitter::getIncidentHinges, py::arg("vtxIdx")) .def("metricDistSq", &MetricFitter::metricDistSq) .def("collapsePreventer", &MetricFitter::collapsePreventer, py::arg("edgeIdx")) ; //////////////////////////////////////////////////////////////////////////////// // Enable output redirection from Python side //////////////////////////////////////////////////////////////////////////////// py::add_ostream_redirect(m, "ostream_redirect"); }
48.522727
169
0.584699
[ "mesh" ]
d775faa046952beb2d822da1fc47d2ed18df7b0a
12,478
cc
C++
geom/is_valid.cc
tintor/sima
7bc21cf1383ee81b7082158ce690befe025f0a4e
[ "Apache-2.0" ]
1
2019-07-06T15:01:00.000Z
2019-07-06T15:01:00.000Z
geom/is_valid.cc
tintor/sima
7bc21cf1383ee81b7082158ce690befe025f0a4e
[ "Apache-2.0" ]
null
null
null
geom/is_valid.cc
tintor/sima
7bc21cf1383ee81b7082158ce690befe025f0a4e
[ "Apache-2.0" ]
null
null
null
#include <core/exception.h> #include <core/union_find.h> #include <core/util.h> #include <geom/aabb.h> #include <geom/classify.h> #include <geom/is_valid.h> #include <geom/primitives.h> #include <geom/project.h> #include <geom/properties.h> bool IsValidPolygon(cspan<double2> poly) { auto n = poly.size(); if (n < 3) return false; // all vertices must be unique for (auto i : range(n)) for (auto j : range(i)) if (equal(poly[i], poly[j])) return false; // no self intersection for (auto i : range(n)) { double2 a = poly[i], b = poly[(i + 1) % n]; double inv_ab_len = 1 / length(a - b); for (auto j : range(i)) { double2 p = poly[j], q = poly[(j + 1) % n]; if (relate_abxo(segment2(a, b), segment2(p, q), inv_ab_len)) return false; } } return true; } bool IsValid(const polygon2& poly) { return IsValidPolygon(poly); } bool IsValid(const xpolygon2& poly) { THROW(not_implemented); } // is triangle Q intersecting with plane defined by plane of triangle P /*inline bool intersects_plane(const itriangle3& q, const itriangle3& plane) { // TODO is this overflow safe? auto n = cross(plane.b - plane.a, plane.c - plane.a); auto e = dot(n, plane.a); auto a = dot(n, q.a) - e; auto b = dot(n, q.b) - e; auto c = dot(n, q.a) - e; return (a <= 0 || b <= 0 || c <= 0) && (a >= 0 || b >= 0 || c >= 0); }*/ // if vertex/edge touch only return false bool edge_overlap(triangle3 p, triangle3 q) { if (!Intersects(aabb3(p), aabb3(q))) return false; for (segment3 pe : Edges(p)) for (segment3 qe : Edges(q)) if (colinear(pe.a, qe.a, qe.b) && colinear(pe.b, qe.a, qe.b)) return Intersects(aabb3(pe), aabb3(qe)); return false; } // =============== bool contains_multiple_components(const mesh3& mesh) { vector<UnionFind> component(mesh.size()); for (auto i : range(mesh.size())) for (auto j : range(i)) if (edge_overlap(mesh[i], mesh[j])) component[i].merge(component[j]); for (auto& c : component) if (c.find() != component[0].find()) return true; return false; } bool face_cuts_into_other_face(const mesh3& mesh) { for (const triangle3& m : mesh) { auto box = aabb3(m.a); double3 cross_cb = cross(m.c, m.b); double3 cross_ba = cross(m.b, m.a); double3 cross_ac = cross(m.a, m.c); double3 sub_cb = m.c - m.b; double3 sub_ac = m.a - m.c; for (triangle3 n : mesh) if (Intersects(aabb3(n), box)) for (segment3 e : Edges(n)) { if (equal(e.a, m.a) || equal(e.a, m.b) || equal(e.a, m.c) || equal(e.b, m.a) || equal(e.b, m.b) || equal(e.b, m.c)) continue; double3 d = e.b - e.a; double3 norm = cross(d, e.b); double s = dot(norm, sub_cb); double t = dot(norm, sub_ac); if (dot(d, cross_cb) > -s && dot(d, cross_ac) > -t && dot(d, cross_ba) > s + t) { print("face %s intersects face %s with edge %s\n", m, n, e); return true; } } } return false; } bool contains_open_edge(const mesh3& mesh) { unordered_set<segment3, hash_t<segment3>> open_edges; for (auto i : range(mesh.size())) for (auto e : mesh[i].edges()) if (open_edges.erase(e.reversed()) == 0) open_edges.insert(e); for (segment3 e : open_edges) print("open edge: %s\n", e); return !open_edges.empty(); } // assume all three points are colinear // assume A and B are on the same side of P static bool closer_to(double3 p, double3 a, double3 b) { assert(colinear(a, b, p)); assert(aabb3(p, a).intersects(aabb3(p, b))); return (p.x <= a.x && a.x < b.x) || (p.y <= a.y && a.y < b.y) || (p.z <= a.z && a.z < b.z) || (p.x >= a.x && a.x > b.x) || (p.y >= a.y && a.y > b.y) || (p.z >= a.z && a.z > b.z); } struct Point { double3 pos; double3 angle_pos; double3 angle_off; bool begin; bool ccw; // when looking in the direction of line, is positive side of triangle pointing CCW? }; void format_e(string& s, string_view spec, const Point& p) { format_s(s, "{pos: %s, angle_pos: %s, angle_off: %s, begin: %s, ccw: %s}", p.pos, p.angle_pos, p.angle_off, p.begin, p.ccw); } // angle between planes [line,A] and [line,REF] // returns angle in range [-PI, PI] // TODO [line] is not used? double compute_angle(line3 line, double3 pos, double3 off, double3 dir, double3 ref, double3 cross_dir_ref) { double3 da = off - pos; double3 e = normalize(da - dir * dot(da, dir)); double alpha = angle(e, ref); return dot(e, cross_dir_ref) < 0 ? -alpha : alpha; } struct LineData { vector<Point> points; double3 dir; }; bool IsSealed(const mesh3& mesh) { // Extract all intervals on all lines of all edges unordered_map<line3, LineData, hash_t<line3>> lines; for (const triangle3& f : mesh) for (int i : range(3)) { double3 a = f[i], b = f[(i + 1) % 3], c = f[(i + 2) % 3]; double3 d = normalize(b - a); bool flip = d.x < 0 || (d.x == 0 && d.y < 0) || (d.x == 0 && d.y == 0 && d.z < 0); if (flip) d = -d; line3 e{a, b}; auto& data = lines[e]; data.points.push_back({a, flip ? a : b, c, !flip, !flip}); data.points.push_back({b, flip ? a : b, c, flip, !flip}); data.dir = d; } for (auto& [line, data] : lines) { double3 line_a = line.origin; std::sort(data.points.begin(), data.points.end(), [&line_a](const Point& a, const Point& b) { // TODO verify ordering logic! return closer_to(line_a, a.pos, b.pos) || (equal(a.pos, b.pos) && !a.begin && b.begin); }); } // Verify all edges are sealed and no seal is penetrating any other seal for (const auto& [line, data] : lines) { // coordinate system to compute angles in! double3 d = data.dir; double3 r = normalize(any_normal(d.xyz)); double3 dr = normalize(cross(d, r)); auto less = [](pair<double, bool> a, pair<double, bool> b) { return a.first < b.first; }; multiset<pair<double, bool>, decltype(less)> angles(less); for (auto a = data.points.begin(); a != data.points.end(); a++) { double angle = compute_angle(line, a->angle_pos, a->angle_off, d, r, dr); if (a->begin) angles.insert({angle, a->ccw}); else angles.erase({angle, a->ccw}); auto b = a + 1; if (a->begin && b != data.points.end() && !b->begin) for (auto p = angles.begin(); p != angles.end(); p++) { auto q = p; ++q; if (q == angles.end()) q = angles.begin(); if (p->first == q->first || p->second == q->second) return false; } } assert(angles.empty()); } return true; } bool are_coplanar_faces_overlapping(triangle3 p, triangle3 q, double3 normal) { for (auto i : range(3)) { double3 ma = p[i]; double3 mb = p[(i + 1) % 3]; double3 mc = ma + normal; double3 c = p[(i + 2) % 3]; double3 normal = compute_normal(ma, mb, mc); double pc = dot(p.c - ma, normal); // TODO possible typo bug bool outside = true; for (double3 v : q) { double qa = dot(v - ma, normal); if ((pc > 0 && qa > 0) || (pc < 0 && qa < 0)) { outside = false; break; } } if (outside) return false; } return true; } bool contains_overlapping_faces(const mesh3& mesh) { // are there two faces whose intersection is 2d? for (auto i : range(mesh.size())) { auto p = mesh[i]; double3 n = compute_normal(p.a, p.b, p.c); for (auto j : range(i)) { auto q = mesh[j]; if (dot(q.a - p.a, n) != 0) continue; if (dot(q.b - p.a, n) != 0) continue; if (dot(q.c - p.a, n) != 0) continue; if (are_coplanar_faces_overlapping(p, q, n)) return false; } } return false; } bool AreAllEdgesConnected(const mesh3& mesh) { unordered_set<segment3, hash_t<segment3>> edges; for (const auto& f : mesh) for (segment3 e : Edges(f)) { if (edges.count(e) > 0) return false; edges.insert(e); } for (segment3 e : edges) print("edge %s\n", e); for (const auto& f : mesh) for (segment3 e : Edges(f)) if (edges.count(segment3{e.b, e.a}) == 0) { print("edge %s is not connected\n", e); return false; } return true; } Validity IsValid(const mesh3& mesh) { if (mesh.size() < 4) return Validity::TooFewFaces; // All faces must be valid for (auto f : mesh) if (colinear(f[0], f[1], f[2])) return Validity::InvalidFace; if (contains_multiple_components(mesh)) return Validity::SeparateComponents; if (face_cuts_into_other_face(mesh)) return Validity::SelfIntersection; if (contains_overlapping_faces(mesh)) return Validity::OverlappingFaces; if (!AreAllEdgesConnected(mesh)) // if (!IsSealed(mesh)) return Validity::NotSealed; // check if all faces are oriented outside if (SignedVolume(mesh) < 0) return Validity::Inverted; // Strict stronger condition than is_sealed // if (contains_open_edge(mesh)) // return Validity::OpenEdge; return Validity::OK; } bool AreCoplanarFacesOverlapping(face p, face q) { int axis = ProjectionAxis(p); xpolygon2 p2 = Project(p, axis); xpolygon2 q2 = Project(q, axis); // TODO issue this projection will stretch some axis more than others and skew tolerances! return Classify(p2, q2) == -1; } // +2 - disjoint positive // +1 - touching from positive // 0 - coplanar // -1 - touching from negative // -2 - disjoint negative // -100 - crossing int Classify(plane p, face f) { int count[3] = {0, 0, 0}; for (double3 v : f.vertices()) count[Sign(p, v) + 1] += 1; int neg = count[0]; int zero = count[1]; int pos = count[2]; if (neg == 0 && pos > 0) return (zero > 0) ? +1 : +2; if (neg > 0 && pos == 0) return (zero > 0) ? -1 : -2; if (neg == 0 && zero == 0 && pos == 0) return 0; return -100; } bool AreCoplanar(plane p, face f) { for (double3 v : f.vertices()) if (Sign(p, v) != 0) return false; return true; } bool ContainsOverlappingFaces(const xmesh3& mesh) { // are there two faces whose intersection is 2d? for (auto i : range(mesh.size())) { face p = mesh[i]; plane pp = best_fit_plane(p.vertices()); for (auto j : range(i)) { face q = mesh[j]; if (AreCoplanar(pp, q) && AreCoplanarFacesOverlapping(p, q)) return true; } } return false; } // each edge must have its reversed edge bool IsSealed(const xmesh3& mesh) { unordered_multiset<segment3, hash_t<segment3>> edges; for (face f : mesh) for (auto ring : f) for (auto edge : Edges(ring)) edges.insert(edge); for (const segment3& e : edges) if (edges.count(e) != edges.count(e.reversed())) return false; return true; } Validity IsValid(const xmesh3& mesh) { if (mesh.size() < 4) return Validity::TooFewFaces; // All faces must be valid for (face f : mesh) { if (!AreCoplanar(best_fit_plane(f.vertices()), f)) return Validity::NonPlanarFace; xpolygon2 poly = Project(f, ProjectionAxis(f)); if (!IsValid(poly)) return Validity::InvalidFace; } /*if (contains_multiple_components(mesh)) return Validity::SeparateComponents; if (face_cuts_into_other_face(mesh)) return Validity::SelfIntersection;*/ if (ContainsOverlappingFaces(mesh)) return Validity::OverlappingFaces; if (!IsSealed(mesh)) return Validity::NotSealed; // check if all faces are oriented outside if (SignedVolume(mesh) < 0) return Validity::Inverted; return Validity::OK; } void MakeValid(mesh3& mesh) { THROW(not_implemented); } void MakeValid(xmesh3& mesh) { THROW(not_implemented); }
34.186301
120
0.555217
[ "mesh", "vector" ]
d7761285f4969ab0875cd7f3b1e510aaccb7be56
5,503
hpp
C++
Source/Pd/PdInstance.hpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
Source/Pd/PdInstance.hpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
Source/Pd/PdInstance.hpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
/* // Copyright (c) 2015-2018 Pierre Guillot. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #pragma once #include <map> #include <utility> #include "PdPatch.hpp" #include "PdAtom.hpp" #include "../Queues/readerwriterqueue.h" #include "../Queues/concurrentqueue.h" namespace pd { class Patch; // ==================================================================================== // // INSTANCE // // ==================================================================================== // class Instance { public: Instance(std::string const& symbol); Instance(Instance const& other) = delete; virtual ~Instance(); void prepareDSP(const int nins, const int nouts, const double samplerate); void startDSP(); void releaseDSP(); void performDSP(float const* inputs, float* outputs); int getBlockSize() const noexcept; void sendNoteOn(const int channel, const int pitch, const int velocity) const; void sendControlChange(const int channel, const int controller, const int value) const; void sendProgramChange(const int channel, const int value) const; void sendPitchBend(const int channel, const int value) const; void sendAfterTouch(const int channel, const int value) const; void sendPolyAfterTouch(const int channel, const int pitch, const int value) const; void sendSysEx(const int port, const int byte) const; void sendSysRealTime(const int port, const int byte) const; void sendMidiByte(const int port, const int byte) const; virtual void receiveNoteOn(const int channel, const int pitch, const int velocity) {} virtual void receiveControlChange(const int channel, const int controller, const int value) {} virtual void receiveProgramChange(const int channel, const int value) {} virtual void receivePitchBend(const int channel, const int value) {} virtual void receiveAftertouch(const int channel, const int value) {} virtual void receivePolyAftertouch(const int channel, const int pitch, const int value) {} virtual void receiveMidiByte(const int port, const int byte) {} void sendBang(std::string const& receiver) const; void sendFloat(std::string const& receiver, float const value) const; void sendSymbol(std::string const& receiver, std::string const& symbol) const; void sendList(std::string const& receiver, const std::vector<Atom>& list) const; void sendMessage(std::string const& receiver, const std::string& msg, const std::vector<Atom>& list) const; virtual void receivePrint(const std::string& message) {}; virtual void receiveBang() {} virtual void receiveFloat(float num) {} virtual void receiveSymbol(const std::string& symbol) {} virtual void receiveList(const std::vector<Atom>& list) {} virtual void receiveMessage(const std::string& msg, const std::vector<Atom>& list) {} void enqueueMessages(const std::string& dest, const std::string& msg, std::vector<Atom>&& list); void enqueueDirectMessages(void* object, const std::string& msg); void enqueueDirectMessages(void* object, const float msg); virtual void messageEnqueued() {}; void dequeueMessages(); void processMessages(); void processPrints(); void processMidi(); void openPatch(std::string const& path, std::string const& name); void closePatch(); Patch getPatch(); void setThis(); Array getArray(std::string const& name); private: void* m_instance = nullptr; void* m_patch = nullptr; void* m_atoms = nullptr; void* m_message_receiver = nullptr; void* m_midi_receiver = nullptr; void* m_print_receiver = nullptr; struct Message { std::string selector; std::vector<Atom> list; }; struct dmessage { void* object; std::string destination; std::string selector; std::vector<Atom> list; }; typedef struct midievent { enum { NOTEON, CONTROLCHANGE, PROGRAMCHANGE, PITCHBEND, AFTERTOUCH, POLYAFTERTOUCH, MIDIBYTE } type; int midi1; int midi2; int midi3; } midievent; typedef moodycamel::ConcurrentQueue<dmessage> message_queue; message_queue m_send_queue = message_queue(4096); moodycamel::ConcurrentQueue<Message> m_message_queue = moodycamel::ConcurrentQueue<Message>(4096); moodycamel::ConcurrentQueue<midievent> m_midi_queue = moodycamel::ConcurrentQueue<midievent>(4096); moodycamel::ConcurrentQueue<std::string> m_print_queue = moodycamel::ConcurrentQueue<std::string>(4096); struct internal; }; }
39.876812
116
0.576958
[ "object", "vector" ]
d77aa5a14eafd3db5939d3d3c4241833eab2aff9
3,546
cpp
C++
c++/protocol/NativeProtocol/NativeProtocol/com_minecade_deepend_nativeprot_DeependProtocol.cpp
Sauilitired/Deepend
6cfcb6b18e3997c1cf7ed9b944ce5bfb97ce8aaf
[ "Apache-2.0" ]
1
2016-02-26T21:08:00.000Z
2016-02-26T21:08:00.000Z
c++/protocol/NativeProtocol/NativeProtocol/com_minecade_deepend_nativeprot_DeependProtocol.cpp
Minecade/Deepend
6cfcb6b18e3997c1cf7ed9b944ce5bfb97ce8aaf
[ "Apache-2.0" ]
null
null
null
c++/protocol/NativeProtocol/NativeProtocol/com_minecade_deepend_nativeprot_DeependProtocol.cpp
Minecade/Deepend
6cfcb6b18e3997c1cf7ed9b944ce5bfb97ce8aaf
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "com_minecade_deepend_nativeprot_DeependProtocol.h" using std::cout; using std::endl; static jclass c_nativeClass; static jmethodID c_constructorB; static jmethodID c_constructorI; static jmethodID c_constructorS; static jstring emptyString; jchar* bytesToChars(const jbyte *bytes, const jint len, _int32* offset) { std::vector<jchar> vector(len); for (int i = 0; i < len; i++) { jbyte b = bytes[*offset + i]; vector[i] = jchar(b); } *offset += len; return vector.data(); } jbyte bytesToByte(const jbyte *bytes, _int32* offset) { jbyte result; result = bytes[*offset]; *offset += sizeof(jbyte); return result; } jint bytesToInt(jbyte *bytes, _int32* offset) { jint result = 0; for (int i = 0; i < sizeof(jint); i++) { int total(i + *offset); result = (result << CHAR_BIT) + bytes[total]; } *offset += sizeof(jint); return result; } JNIEXPORT void JNICALL Java_com_minecade_deepend_nativeprot_DeependProtocol_initialize(JNIEnv *env, jclass) { cout << "[NativeProtocol] Loading com.minecade.deepend.nativeprot.NativeObj" << endl; jclass tmpClass = env->FindClass("com/minecade/deepend/nativeprot/NativeObj"); c_nativeClass = (jclass)env->NewGlobalRef(tmpClass); cout << "[NativeProtocol] Loading byte constructor" << endl; c_constructorB = env->GetMethodID(c_nativeClass, "<init>", "(B)V"); cout << "[NativeProtocol] Loading int constructor" << endl; c_constructorI = env->GetMethodID(c_nativeClass, "<init>", "(I)V"); cout << "[NativeProtocol] Loading String constructor" << endl; c_constructorS = env->GetMethodID(c_nativeClass, "<init>", "(Ljava/lang/String;)V"); env->DeleteLocalRef(tmpClass); cout << "[NativeProtocol] Loading empty string" << endl; emptyString = env->NewString(new jchar, 0); } JNIEXPORT void JNICALL Java_com_minecade_deepend_nativeprot_DeependProtocol_destroy(JNIEnv *env, jclass) { env->DeleteGlobalRef(c_nativeClass); } JNIEXPORT jobjectArray JNICALL Java_com_minecade_deepend_nativeprot_DeependProtocol_loadNativeBuf (JNIEnv * env, jclass, jint jArraySize, jbyteArray jBytes) { jbyte* bytes = env->GetByteArrayElements(jBytes, JNI_FALSE); int offset = 0; jint objSize = bytesToInt(bytes, &offset); jobjectArray arr = env->NewObjectArray(objSize, c_nativeClass, nullptr); for (int object = 0; object < objSize; object++) { int requiredBytes = offset + (sizeof(jint) * 2); if (jArraySize < requiredBytes) { std::cout << "Size was less than expected" << std::endl; break; } jint type = bytesToInt(bytes, &offset); jint osize = bytesToInt(bytes, &offset); if (type == NativeType::NTYPE_BYTE) { jbyte byte = bytesToByte(bytes, &offset); jvalue values[1]; values[0].b = byte; jobject cObject = env->NewObjectA(c_nativeClass, c_constructorB, values); env->SetObjectArrayElement(arr, jsize(object), cObject); } else if (type == NativeType::NTYPE_INT) { jint readInt = bytesToInt(bytes, &offset); jvalue values[1]; values[0].i = readInt; jobject cObject = env->NewObjectA(c_nativeClass, c_constructorI, values); env->SetObjectArrayElement(arr, jsize(object), cObject); } else if (type == NativeType::NTYPE_STRING) { jchar* chars = bytesToChars(bytes, osize, &offset); jstring str = env->NewString(chars, osize); jvalue values[1]; values[0].l = str; jobject cObject = env->NewObjectA(c_nativeClass, c_constructorS, values); env->SetObjectArrayElement(arr, jsize(object), cObject); } } env->ReleaseByteArrayElements(jBytes, bytes, 0); return (jobjectArray) arr; }
31.380531
107
0.718556
[ "object", "vector" ]
d77abdc3ec1ebeef7b1f81846d58c2521cc06dee
18,518
cpp
C++
src/tcp.cpp
swishcloud/tcp-cpp
03c65e980b283532f9032835ce75cc7c427a2bd2
[ "MIT" ]
null
null
null
src/tcp.cpp
swishcloud/tcp-cpp
03c65e980b283532f9032835ce75cc7c427a2bd2
[ "MIT" ]
null
null
null
src/tcp.cpp
swishcloud/tcp-cpp
03c65e980b283532f9032835ce75cc7c427a2bd2
[ "MIT" ]
null
null
null
#include <tcp.h> namespace GLOBAL_NAMESPACE_NAME { tcp_server::tcp_server(short port) : port(port), accecption_times{0}, session_count_peak{0}, end{false} { } tcp_server::~tcp_server() { //common::print_debug(common::string_format("waiting heartbeat thread to exit...")); //this->heartbeat_thread.join(); } void tcp_server::accecpt(tcp::acceptor &acceptor) { acceptor.async_accept( [&acceptor, this](boost::system::error_code ec, tcp::socket socket) { if (!ec) { tcp_session *session = new tcp_session{this->io_context, std::move(socket)}; this->add_session(session); if (this->on_accepted) { this->on_accepted(session, this); } } else { common::print_debug(common::string_format("async_accept failed:%s", ec.message().c_str())); } accecption_times++; common::print_debug(common::string_format("async_accept %s on the %dth attempt, sustained session count:%d", (ec ? "failed" : "ok"), this->accecption_times, this->sessions.size())); this->accecpt(acceptor); }); } void tcp_server::listen() { tcp::acceptor acceptor(io_context, tcp::endpoint(boost::asio::ip::address::from_string("0.0.0.0"), port)); this->accecpt(acceptor); auto work = boost::asio::require(io_context.get_executor(), boost::asio::execution::outstanding_work.tracked); heartbeat_thread = std::thread([this]() { while (!end || this->sessions.size() > 0) { std::this_thread::sleep_for(std::chrono::seconds{1}); auto n = this->sessions.size(); for (int i = 0; i < n; i++) { auto session = this->sessions[i]; if (session->closed && session->_running_tasks == 0) { //remove this session this->remove_session(session); i--; n--; } } } }); std::vector<std::thread> threads; for (int i = 0; i <= 50; i++) { threads.push_back(std::move(std::thread([this]() { io_context.run(); }))); } for (auto &t : threads) { t.join(); } } void tcp_server::add_session(tcp_session *session) { std::lock_guard<std::mutex> guard(sessions_mtx); this->sessions.push_back(session); if (this->session_count_peak < this->sessions.size()) { this->session_count_peak = this->sessions.size(); } common::print_debug(common::string_format("sustained session count:%d", this->sessions.size())); } void tcp_server::remove_session(tcp_session *s) { std::lock_guard<std::mutex> guard(sessions_mtx); for (int i = 0; i < this->sessions.size(); i++) { auto session = this->sessions[i]; if (session == s) { if (!session->closed) { common::print_info("closing the un-closed session before releasing"); session->close(); } this->sessions.erase(this->sessions.begin() + i); delete session; common::print_info("server released a session"); break; } } common::print_debug(common::string_format("sustained session count:%d", this->sessions.size())); } void tcp_server::shutdown() { this->end = true; this->io_context.stop(); this->heartbeat_thread.join(); } //begin tcp_client void tcp_client::start(std::string server_ip, std::string server_port) { try { tcp::resolver r(io_context); this->endpoints = r.resolve(server_ip, server_port); this->connect(endpoints.begin()); auto work = boost::asio::require(io_context.get_executor(), boost::asio::execution::outstanding_work.tracked); this->client_thread = std::thread([this, work]() { io_context.run(); common::print_debug("A tcp_client thread terminated."); }); } catch (const std::exception &e) { common::print_debug(e.what()); if (this->on_connect_fail) { on_connect_fail(this); } } } void tcp_client::connect(tcp::resolver::results_type::iterator endpoint_iter) { if (endpoint_iter == this->endpoints.end()) { common::print_debug("no more endpoint for connection"); if (this->on_connect_fail) { on_connect_fail(this); } return; } session.socket.async_connect(endpoint_iter->endpoint(), std::bind(&tcp_client::handle_connect, this, std::placeholders::_1, endpoint_iter)); } void tcp_client::handle_connect(const boost::system::error_code &error, tcp::resolver::results_type::iterator endpoint_iter) { if (error) { common::print_debug(common::string_format("connection failed:%s", error.message().c_str())); connect(++endpoint_iter); return; } //connection suceess connected = true; if (this->on_connect_success) on_connect_success(this); } tcp_client::tcp_client() : connected{false}, session{io_context} { } tcp_client::~tcp_client() { this->session.close(); this->io_context.stop(); this->client_thread.join(); } bool tcp_session::set_expiration() { if (this->timer.expires_from_now(boost::posix_time::seconds(timeout)) > 0) { this->timer.async_wait(boost::bind(&XTCP::tcp_session::on_timeout, this, boost::placeholders::_1)); return true; } common::print_debug("failed to change expiration time."); //this session is already time out, can no longer be used. return false; } void tcp_session::on_timeout(const boost::system::error_code &e) { if (e != boost::asio::error::operation_aborted) { common::print_debug("this session is time out, closing..."); this->is_expired = true; this->close(); } } tcp_session::tcp_session(boost::asio::io_context &io_context) : tcp_session{io_context, tcp::socket{io_context}} { memset(this->buffer.get(), 0, buffer_size); } tcp_session::tcp_session(boost::asio::io_context &io_context, tcp::socket socket) : io_context{io_context}, timer{io_context}, socket{std::move(socket)}, buffer{new char[buffer_size]}, read_size{0}, closed{false}, is_expired{false}, timeout{20}, _running_tasks{0} { this->timer.expires_from_now(boost::posix_time::seconds(timeout)); this->timer.async_wait(boost::bind(&XTCP::tcp_session::on_timeout, this, boost::placeholders::_1)); } void tcp_session::read(size_t size, read_handler on_read, void *p) { this->increase_task_num(); this->socket.async_read_some(boost::asio::buffer(buffer.get(), size > buffer_size ? buffer_size : size), [this, size, on_read, p](const boost::system::error_code &error, std::size_t bytes_transferred) { on_read(bytes_transferred, this, size == bytes_transferred, this->is_expired && error ? "session timeout" : error ? error.message().c_str() : NULL, p); if (!error) { if (!closed) //the timer is canceled if the session has closed, not set expiration again. this->set_expiration(); time(&this->last_read_timer); this->read_size += bytes_transferred; if (size != bytes_transferred) { this->read(size - bytes_transferred, on_read, p); } } this->decrease_task_num(); }); } void tcp_session::write(const char *data, size_t size, written_handler on_written, void *p) { this->increase_task_num(); this->socket.async_write_some(boost::asio::buffer(data, size), [this, data, size, on_written, p](const boost::system::error_code &error, std::size_t bytes_transferred) { on_written(bytes_transferred, this, size == bytes_transferred, this->is_expired && error ? "session timeout" : error ? error.message().c_str() : NULL, p); if (!error) { if (!closed) //the timer is canceled if the session has closed, not set expiration again. this->set_expiration(); time(&this->last_write_timer); this->written_size += bytes_transferred; if (size != bytes_transferred) { this->write(data + bytes_transferred, size - bytes_transferred, on_written, p); } } this->decrease_task_num(); }); } void tcp_session::send_stream(std::shared_ptr<std::istream> fs, sent_stream_handler on_sent_stream, void *p) { static const int BUFFER_SIZE = 1 * 1024 * 1024; std::shared_ptr<char[]> buf{new char[BUFFER_SIZE]}; fs->read(buf.get(), BUFFER_SIZE); if (fs->rdstate() & (std::ios_base::badbit)) { throw common::exception("failed to read bytes"); } int read_count = fs->gcount(); this->write( buf.get(), read_count, [this, fs, on_sent_stream, buf](size_t written_size, XTCP::tcp_session *session, bool completed, common::error error, void *p) { bool eof = fs->rdstate() & (std::ios_base::eofbit); on_sent_stream(written_size, session, completed && eof, error, p); if (completed) { if (!eof) send_stream(fs, on_sent_stream, p); } }, NULL); } void tcp_session::receive_stream(std::shared_ptr<std::ostream> fs, size_t size, received_stream_handler on_received_stream, void *p) { this->read( size, [size, fs, on_received_stream](size_t read_size, XTCP::tcp_session *session, bool completed, common::error error, void *p) { if (!error) { fs->write(session->buffer.get(), read_size); if (!*fs) { completed = false; error = "Writing failed."; } } on_received_stream(read_size, session, completed, error, p); }, NULL); } void tcp_session::close() { if (this->closed) { common::print_info("WARNING:the session already been closed before!"); return; } if (on_closed) { on_closed(this); } this->timer.cancel(); this->closed = true; this->socket.close(); } void tcp_session::increase_task_num() { std::lock_guard<std::mutex> guard(running_tasks_counter_mutex); _running_tasks++; } void tcp_session::decrease_task_num() { std::lock_guard<std::mutex> guard(running_tasks_counter_mutex); _running_tasks--; } void _receive_size(XTCP::tcp_session *tcp_session, std::shared_ptr<std::stringstream> size_ss, std::function<void(common::error error, message &msg)> on_read); void _receive_message(XTCP::tcp_session *tcp_session, std::shared_ptr<std::stringstream> msg_ss, size_t size, std::function<void(common::error error, message &msg)> on_read); char *message::to_json() const { nlohmann::json j; for (auto header : this->headers) { header.fill_json(j["Header"]); } j["MsgType"] = this->msg_type; j["BodySize"] = this->body_size; std::string json_str = j.dump(); return common::strcpy(json_str.c_str()); } message::operator bool() const { return this->msg_type > 0; } message message::parse(std::string json) { nlohmann::json j = nlohmann::json::parse(json); message msg; msg.msg_type = j["MsgType"].get<int>(); msg.body_size = j["BodySize"].get<long>(); for (auto &header : j["Header"].items()) { nlohmann::json val = header.value(); if (val.is_number()) { msg.addHeader({header.key(), static_cast<size_t>(val)}); } else { msg.addHeader({header.key(), static_cast<std::string>(val)}); } } return msg; } void message::addHeader(message_header value) { headers.push_back(value); } message_header::message_header(std::string name, std::string v) { this->name = name; t = 0; this->str_v = v; } message_header::message_header(std::string name, size_t v) { this->name = name; t = 1; this->int_v = v; } void message_header::fill_json(json &j) { if (this->t == 0) j[this->name] = this->str_v; else if (this->t == 1) j[this->name] = this->int_v; } void send_message(XTCP::tcp_session *session, message &msg, std::function<void(common::error error)> on_sent) { auto json = std::unique_ptr<char[]>{msg.to_json()}; int json_len = strlen(json.get()); std::string json_len_str = common::string_format("%x", json_len); int buf_len = json_len_str.size() + 1 + json_len; std::shared_ptr<char[]> buf{new char[buf_len]}; char *dest = buf.get(); memcpy(dest, json_len_str.c_str(), json_len_str.size()); dest += json_len_str.size(); memcpy(dest++, "\0", 1); memcpy(dest, json.get(), json_len); session->write( buf.get(), buf_len, [buf, on_sent](size_t read_size, XTCP::tcp_session *session, bool completed, common::error error, void *p) { if ((completed || error)) { on_sent(error); } }, NULL); } void send_message(XTCP::tcp_session *session, message &msg, common::error &error) { std::promise<common::error> promise; send_message(session, msg, [&promise](common::error error) { promise.set_value(error); }); error = promise.get_future().get(); } void read_message(XTCP::tcp_session *session, std::function<void(common::error error, message &msg)> on_read) { std::shared_ptr<std::stringstream> size_ss{new std::stringstream{}}; *size_ss << std::hex; _receive_size(session, size_ss, [on_read, session](common::error error, message &msg) { on_read(error, msg); }); } void read_message(XTCP::tcp_session *session, message &msg, common::error &error) { std::promise<common::error> promise; read_message(session, [&msg, &promise](common::error error, message &_msg) { msg = _msg; promise.set_value(error); }); error = promise.get_future().get(); } void _receive_size(XTCP::tcp_session *tcp_session, std::shared_ptr<std::stringstream> size_ss, std::function<void(common::error error, message &msg)> on_read) { tcp_session->read( 1, [on_read, size_ss](size_t read_size, XTCP::tcp_session *session, bool completed, common::error error, void *p) { if (error) { message msg; on_read(error, msg); return; } *size_ss << session->buffer.get()[0]; if (session->buffer.get()[0] == '\0') { int size; *size_ss >> size; common::print_debug(common::string_format("read message SIZE:%d", size)); std::shared_ptr<std::stringstream> msg_ss{new std::stringstream{}}; _receive_message(session, msg_ss, size, on_read); return; } else { assert(completed); //just one byte. _receive_size(session, size_ss, on_read); } }, NULL); } void _receive_message(XTCP::tcp_session *tcp_session, std::shared_ptr<std::stringstream> msg_ss, size_t size, std::function<void(common::error error, message &msg)> on_read) { tcp_session->read( size, [msg_ss, on_read](size_t read_size, XTCP::tcp_session *session, bool completed, common::error error, void *p) { message msg; msg_ss->write(session->buffer.get(), read_size); if (!msg_ss) { session->close(); on_read("!!!FAILED TO WRITE TO STRINGSTREAM", msg); return; } if (completed) { common::print_debug(common::string_format("read message:%s", msg_ss->str().c_str())); try { msg = message::parse(msg_ss->str()); } catch (const std::exception &e) { on_read(common::string_format("error reading message:%s", e.what()), msg); return; } } if (error || completed) { on_read(error, msg); } }, NULL); } };
39.4
267
0.523275
[ "vector" ]
d780add27304c38f418973c94918c48d8f8aa680
3,415
hpp
C++
CSGOSimple/valve_sdk/interfaces/IPrediction.hpp
kmgb/Gazoozle
564247f55d310c00af4370296778b1f3b700ee49
[ "MIT" ]
18
2018-08-15T13:25:45.000Z
2021-06-10T09:03:29.000Z
CSGOSimple/valve_sdk/interfaces/IPrediction.hpp
kmgb/Gazoozle
564247f55d310c00af4370296778b1f3b700ee49
[ "MIT" ]
2
2018-08-21T14:43:04.000Z
2021-07-30T06:09:02.000Z
CSGOSimple/valve_sdk/interfaces/IPrediction.hpp
kmgb/Gazoozle
564247f55d310c00af4370296778b1f3b700ee49
[ "MIT" ]
9
2018-08-16T10:41:13.000Z
2021-08-23T23:05:16.000Z
#pragma once #include "../math/QAngle.hpp" #include "../misc/CUserCmd.hpp" #include "IMoveHelper.hpp" class CMoveData { public: bool m_bFirstRunOfFunctions : 1; bool m_bGameCodeMovedPlayer : 1; int m_nPlayerHandle; // edict index on server, client entity handle on client= int m_nImpulseCommand; // Impulse command issued. Vector m_vecViewAngles; // Command view angles (local space) Vector m_vecAbsViewAngles; // Command view angles (world space) int m_nButtons; // Attack buttons. int m_nOldButtons; // From host_client->oldbuttons; float m_flForwardMove; float m_flSideMove; float m_flUpMove; float m_flMaxSpeed; float m_flClientMaxSpeed; Vector m_vecVelocity; // edict::velocity // Current movement direction. Vector m_vecAngles; // edict::angles Vector m_vecOldAngles; float m_outStepHeight; // how much you climbed this move Vector m_outWishVel; // This is where you tried Vector m_outJumpVel; // This is your jump velocity Vector m_vecConstraintCenter; float m_flConstraintRadius; float m_flConstraintWidth; float m_flConstraintSpeedFactor; float m_flUnknown[5]; Vector m_vecAbsOrigin; }; class C_BasePlayer; class IGameMovement { public: virtual ~IGameMovement(void) {} virtual void ProcessMovement(C_BasePlayer *pPlayer, CMoveData *pMove) = 0; virtual void Reset(void) = 0; virtual void StartTrackPredictionErrors(C_BasePlayer *pPlayer) = 0; virtual void FinishTrackPredictionErrors(C_BasePlayer *pPlayer) = 0; virtual void DiffPrint(char const *fmt, ...) = 0; virtual Vector const& GetPlayerMins(bool ducked) const = 0; virtual Vector const& GetPlayerMaxs(bool ducked) const = 0; virtual Vector const& GetPlayerViewOffset(bool ducked) const = 0; virtual bool IsMovingPlayerStuck(void) const = 0; virtual C_BasePlayer* GetMovingPlayer(void) const = 0; virtual void UnblockPusher(C_BasePlayer *pPlayer, C_BasePlayer *pPusher) = 0; virtual void SetupMovementBounds(CMoveData *pMove) = 0; }; class CGameMovement : public IGameMovement { public: virtual ~CGameMovement(void) {} }; class IPrediction { public: bool InPrediction() { typedef bool(__thiscall* oInPrediction)(void*); return CallVFunction<oInPrediction>(this, 14)(this); } void RunCommand(C_BasePlayer *player, CUserCmd *ucmd, IMoveHelper *moveHelper) { typedef void(__thiscall* oRunCommand)(void*, C_BasePlayer*, CUserCmd*, IMoveHelper*); return CallVFunction<oRunCommand>(this, 19)(this, player, ucmd, moveHelper); } void SetupMove(C_BasePlayer *player, CUserCmd *ucmd, IMoveHelper *moveHelper, void* pMoveData) { typedef void(__thiscall* oSetupMove)(void*, C_BasePlayer*, CUserCmd*, IMoveHelper*, void*); return CallVFunction<oSetupMove>(this, 20)(this, player, ucmd, moveHelper, pMoveData); } void FinishMove(C_BasePlayer *player, CUserCmd *ucmd, void*pMoveData) { typedef void(__thiscall* oFinishMove)(void*, C_BasePlayer*, CUserCmd*, void*); return CallVFunction<oFinishMove>(this, 21)(this, player, ucmd, pMoveData); } };
37.527473
99
0.666764
[ "vector" ]
d78c27aeb4165c6f6ddd5555ea9c8ae73f8d063a
21,142
cc
C++
src/Molecule_Lib/marvin.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
6
2020-08-17T15:02:14.000Z
2022-01-21T19:27:56.000Z
src/Molecule_Lib/marvin.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
null
null
null
src/Molecule_Lib/marvin.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <limits> #include <memory> #include "Foundational/data_source/iwstring_data_source.h" #include "Foundational/iwmisc/misc.h" #include "Foundational/xmlParser/xmlParser.h" #define COMPILING_MARVIN_CC #include "molecule.h" #include "marvin.h" static const Marvin_Structure_Information * msi = NULL; void set_marvin_structure_information_for_writing (const Marvin_Structure_Information * s) { msi = s; } void Marvin_Structure_Information::reset () { _atom_colour.resize_keep_storage(0); _bond_colour.resize_keep_storage(0); reset_atoms_and_bonds(); return; } void Marvin_Structure_Information::reset_atoms_and_bonds () { _atom_number_colour_index.clear(); _bond_number_colour_index.clear(); return; } static int do_add_looking_for_N_and_hash (const IWString & s, resizable_array_p<IWString> & z) { if ('N' == s) { z.add(new IWString('N')); return 1; } if (s.starts_with('#')) { IWString * t = new IWString (s); z.add(t); } IWString * t = new IWString; t->add('#'); (*t) << s; z.add(t); return 1; } int Marvin_Structure_Information::add_atom_colour (const const_IWSubstring & s) { return do_add_looking_for_N_and_hash(s, _atom_colour); } int Marvin_Structure_Information::add_bond_colour (const const_IWSubstring & s) { return do_add_looking_for_N_and_hash(s, _bond_colour); } int Marvin_Structure_Information::colour_index_for_atom (atom_number_t a) const { IW_Hash_Map<atom_number_t, unsigned int>::const_iterator f = _atom_number_colour_index.find(a); if (f == _atom_number_colour_index.end()) return 0; return (*f).second; } int Marvin_Structure_Information::colour_index_for_bond (int bond_number) const { IW_Hash_Map<atom_number_t, unsigned int>::const_iterator f = _bond_number_colour_index.find(bond_number); if (f == _atom_number_colour_index.end()) return 0; return (*f).second; } int Marvin_Structure_Information::write_atom_and_bond_colours (std::ostream & os) const { if (_atom_colour.number_elements()) { os << " atomSetRGB=\""; for (int i = 0; i < _atom_colour.number_elements(); i++) { if (i > 0) os << ','; os << i << ":" << *(_atom_colour[i]); } os << "\"\n"; } if (_bond_colour.number_elements()) { os << " bondSetRGB=\""; for (int i = 0; i < _bond_colour.number_elements(); i++) { if (i > 0) os << ','; os << i << ":" << *(_bond_colour[i]); } os << "\"\n"; } return 1; } int Molecule::write_molecule_mrv (std::ostream & os) { os << "<MDocument"; if (NULL != msi) msi->write_atom_and_bond_colours (os); os << ">\n"; int rc = _write_molecule_mrv(os); os << "</MDocument>\n"; msi = NULL; return rc; } int Molecule::_write_molecule_mrv (std::ostream & os) const { os << " <MChemicalStruct>\n"; os << " <molecule title=\"" << _molecule_name << "\">\n"; os << " <atomArray\n"; _write_atoms_mrv(os); os << " />\n"; os << " <bondArray>\n"; _write_bonds_mrv(os); os << " </bondArray>\n"; os << " </molecule>\n"; os << " </MChemicalStruct>\n"; return os.good(); } int Molecule::_write_atoms_mrv (std::ostream & os) const { os << " atomID=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << 'a' << (i + 1); } os << "\"\n"; os << " elementType=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << _things[i]->atomic_symbol(); } os << "\"\n"; if (maximum_isotope() > 0) { os << " isotope=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << _things[i]->isotope(); } os << "\"\n"; } if (has_formal_charges()) { os << " formalCharge=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << _things[i]->formal_charge(); } os << "\"\n"; } if (NULL == msi) // no atom colours present ; else if (msi->atom_colour_specifications_present()) { os << " mrvSetSeq=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; if (NULL == msi) os << '0'; else os << msi->colour_index_for_atom(i); } os << "\"\n"; } os << " x2=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << _things[i]->x(); } os << "\"\n"; os << " y2=\""; for (int i = 0; i < _number_elements; i++) { if (i > 0) os << ' '; os << _things[i]->y(); } os << "\"\n"; return 1; } int Molecule::_write_bonds_mrv (std::ostream & os) const { int n = _bond_list.number_elements(); for (int i = 0; i < n; i++) { const Bond * b = _bond_list[i]; os << " <bond atomRefs2=\"a" << (b->a1() + 1) << " a" << (b->a2()+1) << "\" order=\""; if (b->is_single_bond()) os << '1'; else if (b->is_double_bond()) os << '2'; else if (b->is_triple_bond()) os << '3'; else if (b->is_aromatic()) os << 'A'; else os << '5'; // HUH!! os << "\" "; if (NULL != msi) { int c = msi->colour_index_for_bond (i); if (c > 0) os << "mrvSetSeq=\"" << c << "\" "; } if (! b->is_wedge_definitive()) { os << " />\n"; continue; } os << ">\n"; if (b->is_wedge_up()) os << " <bondStereo>H</bondStereo>\n"; else if (b->is_wedge_down()) os << " <bondStereo>W</bondStereo>\n"; os << " </bond>\n"; } return 1; } int Molecule::read_molecule_mrv_ds (iwstring_data_source & input) { const_IWSubstring buffer; int found_mdocument = 0; int lines_read = 0; while (input.next_record(buffer)) { lines_read++; if ("</cml>" == buffer) { input.next_record(buffer); // force eof return 0; } if (! buffer.starts_with("<MDocument")) continue; found_mdocument = 1; break; } if (found_mdocument) // great ; else if (0 == lines_read) // normal eof return 0; else // bad { cerr << "Molecule::read_molecule_mrv_ds:no MDocument record found\n"; return 0; } IWString xml; xml << buffer; found_mdocument = 0; // the end this time while (input.next_record(buffer)) { xml << buffer; // cerr << "Check '" << buffer << "'\n"; if (! buffer.starts_with("</MDocument")) continue; found_mdocument = 1; break; } if (! found_mdocument) { cerr << "Molecule::read_molecule_mrv_ds:no termination MDocument\n"; return 0; } XMLResults xe; XMLNode xMainNode = XMLNode::parseString(xml.null_terminated_chars(), "MDocument", &xe); if (0 != xe.error) { cerr << "Molecule::read_molecule_mrv_ds:error in xml data, line " << xe.nLine << endl; return 0; } #ifdef DEBUG_MARVIN_READ_MOLECULE cerr << "Successfully initialised xml, name '" << xMainNode.getName() << "'\n"; #endif XMLNode xNode=xMainNode.getChildNode("MChemicalStruct"); if (NULL == xNode.getName()) { cerr << "molecule::read_molecule_mrv_ds:could not get 'MChemicalStruct' attribute\n"; return 0; } #ifdef DEBUG_MARVIN_READ_MOLECULE cerr << "Got '" << xNode.getName() << "'\n"; #endif return read_molecule_mrv_mchemical(xNode); } int Molecule::read_molecule_mrv_mchemical (XMLNode & mchemicalstruct) { XMLNode molecule = mchemicalstruct.getChildNode("molecule"); if (NULL == molecule.getName()) { cerr << "molecule::read_molecule_mrv:no 'molecule' tag in xml\n"; return 0; } return read_molecule_mrv_molecule(molecule); } int Molecule::read_molecule_mrv_molecule (XMLNode & xml) { XMLCSTR mname = xml.getAttribute("title", 0); if (NULL != mname) _molecule_name = mname; //cerr << "Molecule name set to '" << _molecule_name << "'\n"; XMLNode atomArray = xml.getChildNode("atomArray"); if (NULL == atomArray.getName()) { cerr << "Molecule::_read_molecule_mrv:no atomArray in xml\n"; return 0; } if (! _read_atom_array_mrv(atomArray)) { cerr << "Molecule::_read_molecule_mrv:cannot read atom array\n"; return 0; } if (0 == _number_elements) // cannot be anything else, strange... { cerr << "Molecule::_read_bond_array_mrv:no atoms\n"; return 1; } // There must be at least natoms bonds present, safe upper estimate int * aromatic_bonds = new_int(_number_elements + _number_elements); std::unique_ptr<int[]> free_aromatic_bonds(aromatic_bonds); XMLNode bondarray = xml.getChildNode("bondArray"); if (NULL == bondarray.getName()) ; else if (! _read_bond_array_mrv(bondarray, aromatic_bonds)) { cerr << "Molecule::_read_molecule_mrv:cannot read bond array\n"; return 0; } if (locate_item_in_array(1, _bond_list.number_elements(), aromatic_bonds) < 0) // no aromatic bonds ; else if (! _final_processing_of_aromatic_mdl_input(NULL, aromatic_bonds)) { cerr << "Molecule::_read_molecule_mrv:cannot resolve aromatic bonds\n"; return 0; } return 1; } static int zero_length_or_this_many_tokens (const IWString & s, int nw) { if (0 == s.length()) return 1; if (nw == s.nwords()) return 1; cerr << "Molecule::_read_atom_array_mrv:inconsistent atom list lengths\n"; cerr << "'" << s << "'\n"; return 0; } /* Could not get a template for this to work, so we have two versions... */ template <typename T> int convert_to_numeric (const IWString & s, resizable_array<T> & v, T minval) { if (0 == s.length()) return 1; int i = 0; const_IWSubstring token; while (s.nextword(token, i)) { if ('0' == token) // a common case { v.add(0); continue; } T t; if (! token.numeric_value(t)) { cerr << "Invalid numeric '" << t << "'\n"; return 0; } if (t < minval) { cerr << "Value out of range " << t << " compare " << minval << endl; return 0; } v.add(t); } return v.number_elements(); } /* Atoms can appear as individual items or as an array */ int Molecule::_read_atom_array_mrv (XMLNode & xml) { XMLCSTR xml_atomID = xml.getAttribute("atomID", 0); if (NULL == xml_atomID) return _read_atom_array_mrv_individual_attributes (xml); XMLCSTR xml_elementType = xml.getAttribute("elementType"); if (NULL == xml_elementType) { cerr << "Molecule::_read_atom_array_mrv:no elementType\n"; return 0; } IWString elementType = xml_elementType; IWString x2 = xml.getAttribute("x2", 0); IWString y2 = xml.getAttribute("y2", 0); IWString x3 = xml.getAttribute("x3", 0); IWString y3 = xml.getAttribute("y3", 0); IWString z3 = xml.getAttribute("z3", 0); IWString isotope = xml.getAttribute("isotope"); IWString formalCharge = xml.getAttribute("formalCharge"); int dimensionality = 0; if (x2.length() > 0 && y2.length() > 0 && 0 == x3.length() && 0 == y3.length() && 0 == z3.length()) dimensionality = 2; else if (0 == x2.length() && 0 == y2.length() && x3.length() && y3.length() && z3.length()) dimensionality = 3; else if (0 == x2.length() && 0 == y2.length() && 0 == x3.length() && 0 == y3.length() && 0 == z3.length()) ; // zero dimensionality else { cerr << "Molecule::_read_atom_array_mrv:inconsistent geometry specifications\n"; return 0; } int natoms = elementType.nwords(); //cerr << "Molecule contains " << natoms << " atoms\n"; if (! zero_length_or_this_many_tokens(x2, natoms)) return 0; if (! zero_length_or_this_many_tokens(y2, natoms)) return 0; if (! zero_length_or_this_many_tokens(x3, natoms)) return 0; if (! zero_length_or_this_many_tokens(y3, natoms)) return 0; if (! zero_length_or_this_many_tokens(z3, natoms)) return 0; if (! zero_length_or_this_many_tokens(isotope, natoms)) return 0; if (! zero_length_or_this_many_tokens(formalCharge, natoms)) return 0; int elementType_i = 0; //int x2_i = 0; //int x3_i = 0; //int y2_i = 0; //int y3_i = 0; //int z3_i = 0; resizable_array<int> isotopes; if (! convert_to_numeric(isotope, isotopes, static_cast<int>(0))) { cerr << "Molecule::_read_atom_array_mrv:invalid isotopic specification\n"; return 0; } resizable_array<formal_charge_t> formal_charges; if (! convert_to_numeric(formalCharge, formal_charges, -9999)) { cerr << "Molecule::_read_atom_array_mrv:invalid formal charge\n"; return 0; } resizable_array<coord_t> x, y, z; if (2 == dimensionality) { if (! convert_to_numeric(x2, x, - std::numeric_limits<coord_t>::max())) { cerr << "Molecule::_read_atom_array_mrv:invalid x coordinate\n"; return 0; } if (! convert_to_numeric(y2, y, - std::numeric_limits<coord_t>::max())) { cerr << "Molecule::_read_atom_array_mrv:invalid y coordinate\n"; return 0; } } else if (3 == dimensionality) { if (! convert_to_numeric(x3, x, -std::numeric_limits<coord_t>::max())) { cerr << "Molecule::_read_atom_array_mrv:invalid x coordinate\n"; return 0; } if (! convert_to_numeric(y3, y, -std::numeric_limits<coord_t>::max())) { cerr << "Molecule::_read_atom_array_mrv:invalid y coordinate\n"; return 0; } if (! convert_to_numeric(z3, z, -std::numeric_limits<coord_t>::max())) { cerr << "Molecule::_read_atom_array_mrv:invalid z coordinate\n"; return 0; } } const_IWSubstring elementType_token, x2_token, y2_token, x3_token, y3_token, z3_token, isotope_token, formalCharge_token; const_IWSubstring token; int ndx = 0; while (elementType.nextword(elementType_token, elementType_i)) { const Element * e = get_element_from_symbol_no_case_conversion(elementType_token); if (NULL == e) { cerr << "Molecule::_read_atom_array_mrv:cannot create element from '" << elementType_token << "'\n"; return 0; } Atom * a = new Atom(e); if (formal_charges.empty()) ; else if (0 != formal_charges[ndx]) a->set_formal_charge(formal_charges[ndx]); if (isotopes.empty()) ; else if (0 != isotopes[ndx]) a->set_isotope(isotopes[ndx]); if (2 == dimensionality) { a->setxyz(x[ndx], y[ndx], static_cast<coord_t>(0.0)); } else if (3 == dimensionality) { a->setxyz(x[ndx], y[ndx], z[ndx]); } add(a); ndx++; } return 1; } template <typename T> int convert_to_numeric (XMLCSTR & s, T & v) { IWString tmp(s); return tmp.numeric_value(v); } int Molecule::_read_atom_array_mrv_individual_attributes (const XMLNode & xml) { for (int i = 0; ; i++) { XMLNode xml_a = xml.getChildNode(i); if (NULL == xml_a.getName()) break; // cerr << "Processing atom node '" << xml_a.getName() << "'\n"; if (0 != strncmp("atom", xml_a.getName(), 4)) continue; XMLCSTR elementType = xml_a.getAttribute("elementType"); // cerr << "Element is '" << elementType << "'\n"; if (NULL == elementType) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:no elementType attribute\n"; return 0; } XMLCSTR x2 = xml_a.getAttribute("x2"); XMLCSTR y2 = xml_a.getAttribute("y2"); XMLCSTR x3 = xml_a.getAttribute("x3"); XMLCSTR y3 = xml_a.getAttribute("y3"); XMLCSTR z3 = xml_a.getAttribute("z3"); XMLCSTR isotope = xml_a.getAttribute("isotope"); XMLCSTR formalCharge = xml_a.getAttribute("formalCharge"); const Element * e = get_element_from_symbol_no_case_conversion(elementType); if (NULL != e) ; else if (! auto_create_new_elements()) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:cannot create element from '" << elementType << "'\n"; return 0; } else { e = create_element_with_symbol(elementType); if (NULL == e) { cerr << "Molecule::read_molecule_mrv_molecule:cannot create element '" << elementType << "'\n"; return 0; } } Atom * a = new Atom(e); if (NULL != formalCharge) { formal_charge_t q; if (! convert_to_numeric(formalCharge, q) || ! reasonable_formal_charge_value(q)) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:invalid charge '" << formalCharge << "'\n"; return 0; } a->set_formal_charge(q); } if (NULL != isotope) { int iso; if (! convert_to_numeric(isotope, iso) || iso < 0) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:invalid isotopic specification '" << isotope << "'\n"; return 0; } a->set_isotope(iso); } if (NULL != x2) // 2D coordinates specified { coord_t x; if (! convert_to_numeric(x2, x)) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:invalid x2 '" << x2 << "'\n"; return 0; } coord_t y; if (NULL == y2) // silently ignore this!!? y = static_cast<coord_t>(0.0); else if (! convert_to_numeric(y2, y)) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:invalid y2 '" << y2 << "'\n"; return 0; } a->setxyz(x, y, static_cast<coord_t>(0.0)); } else if (NULL != x3) { if (NULL == y3 || NULL == z3) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:incomplete 3d specification\n"; return 0; } coord_t x, y, z; if (! convert_to_numeric(x3, x) || ! convert_to_numeric(y3, y) || ! convert_to_numeric(z3, z)) { cerr << "Molecule::_read_atom_array_mrv_individual_attributes:invalid 3d specification '" << x3 << "', '" << y3 << "', '" << z3 << "'\n"; return 0; } a->setxyz(x, y, z); } add(a); } return 1; } int Molecule::_read_bond_array_mrv (XMLNode & xml, int * aromatic_bonds) { int wedge_bonds_encountered = 0; for (int i = 0; ; i++) { XMLNode xml_b = xml.getChildNode(i); if (NULL == xml_b.getName()) break; #ifdef DEBUG_MARVIN_BOND_LIST cerr << "Examining child '" << xml_b.getName() << "'\n"; #endif if (0 != strncmp("bond", xml_b.getName(), 4)) continue; IWString atomRefs2 = xml_b.getAttribute("atomRefs2", 0); IWString order = xml_b.getAttribute("order", 0); if (0 == atomRefs2.length() || 0 == order.length()) { cerr << "Molecule::_read_bond_array_mrv:invalid bond\n"; return 0; } #ifdef DEBUG_MARVIN_BOND_LIST cerr << "atomRefs2 '" << atomRefs2 << "', order " << order << "'\n"; #endif if (2 != atomRefs2.nwords()) { cerr << "Molecule::_read_bond_array_mrv:bond must have two atoms\n"; return 0; } const_IWSubstring sa1, sa2; atomRefs2.split(sa1, ' ', sa2); if (! sa1.starts_with('a') || ! sa2.starts_with('a')) { cerr << "Molecule::_read_bond_array_mrv:bond specifications must start with 'a' '" << atomRefs2 << "'\n"; return 0; } sa1++; sa2++; atom_number_t a1, a2; if (! sa1.numeric_value(a1) || a1 < 1 || a1 > _number_elements) { cerr << "Molecule::_read_bond_array_mrv:invalid atom in bond '" << atomRefs2 << "'\n"; return 0; } if (! sa2.numeric_value(a2) || a2 < 1 || a2 > _number_elements || a1 == a2) { cerr << "Molecule::_read_bond_array_mrv:invalid atom in bond '" << atomRefs2 << "'\n"; return 0; } a1--; a2--; bond_type_t bt; if ('1' == order) bt = SINGLE_BOND; else if ('2' == order) bt = DOUBLE_BOND; else if ('3' == order) bt = TRIPLE_BOND; else if ('A' == order) { int nb = _bond_list.number_elements(); aromatic_bonds[nb] = 1; bt = SINGLE_BOND; } else { cerr << "Molecule::_read_bond_array_mrv:what kind of bond is '" << order << "', set to single\n"; bt = SINGLE_BOND; } add_bond(a1, a2, bt, 1); for (int j = 0; ; j++) { XMLNode xml_bs = xml_b.getChildNode(j); if (NULL == xml_bs.getName()) break; // cerr << "Processing '" << xml_bs.getName() << "'\n"; if (0 != strncmp("bondStereo", xml_bs.getName(), 10)) continue; Bond * b = _bond_list.last_item(); XMLCSTR att = xml_bs.getText(); if (0 == strncmp(att, "H", 1)) { b->set_wedge_up(); wedge_bonds_encountered++; } else if (0 == strncmp(att, "W", 1)) { b->set_wedge_down(); wedge_bonds_encountered++; } else { cerr << "Molecule::_read_bond_array_mrv:unrecognised wedge bond attribute '" << att << "', ignored\n"; } } } if (wedge_bonds_encountered) discern_chirality_from_wedge_bonds(); return 1; }
22.684549
145
0.585753
[ "geometry", "3d" ]
d78e8fad5744184acee52dd993e8768a8d23fe83
1,924
cpp
C++
modules/segmentation/src/segmenter_euclidean.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
modules/segmentation/src/segmenter_euclidean.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
modules/segmentation/src/segmenter_euclidean.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
#include <v4r/segmentation/segmenter_euclidean.h> #include <pcl/impl/instantiate.hpp> #include <pcl/segmentation/extract_clusters.h> #include <pcl/kdtree/kdtree.h> namespace v4r { template <typename PointT> void EuclideanSegmenter<PointT>::segment() { // NaN points cause segmentation fault in kdtree search typename pcl::PointCloud<PointT>::Ptr scene_wo_nans (new pcl::PointCloud<PointT> ); scene_wo_nans->points.resize( scene_->points.size() ); std::vector<int> indices_converter ( scene_->points.size() ); size_t kept=0; for(size_t i=0; i<scene_->points.size(); i++) { const PointT &p = scene_->points[i]; if( pcl::isFinite(p) ) { scene_wo_nans->points[kept] = p; indices_converter[kept] = i; kept++; } } indices_converter.resize(kept); scene_wo_nans->points.resize(kept); scene_wo_nans->width = kept; scene_wo_nans->height = 1; typename pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT>); tree->setInputCloud ( scene_wo_nans ); pcl::EuclideanClusterExtraction<PointT> ec; ec.setClusterTolerance (param_.cluster_tolerance_); ec.setMinClusterSize (param_.min_cluster_size_); ec.setMaxClusterSize (param_.max_cluster_size_); ec.setSearchMethod (tree); ec.setInputCloud ( scene_wo_nans ); std::vector<pcl::PointIndices> clusters_pcl; ec.extract (clusters_pcl); clusters_.clear(); clusters_.resize( clusters_pcl.size() ); for(size_t i=0; i<clusters_pcl.size(); i++) { clusters_[i].reserve( clusters_pcl[i].indices.size() ); for( int idx_wo_nan : clusters_pcl[i].indices ) clusters_[i].push_back( indices_converter[ idx_wo_nan ] ); } } #define PCL_INSTANTIATE_EuclideanSegmenter(T) template class V4R_EXPORTS EuclideanSegmenter<T>; PCL_INSTANTIATE(EuclideanSegmenter, PCL_XYZ_POINT_TYPES ) }
32.066667
95
0.685551
[ "vector" ]
d7900c94fe11345af40108e84bde170acb844066
14,727
cc
C++
src/bin/d2/d2_cfg_mgr.cc
gumingpo/kea-latest
ca64954cd71dd544e7c92a0aa366dfc0f79d4ce1
[ "Apache-2.0" ]
null
null
null
src/bin/d2/d2_cfg_mgr.cc
gumingpo/kea-latest
ca64954cd71dd544e7c92a0aa366dfc0f79d4ce1
[ "Apache-2.0" ]
null
null
null
src/bin/d2/d2_cfg_mgr.cc
gumingpo/kea-latest
ca64954cd71dd544e7c92a0aa366dfc0f79d4ce1
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2014-2017 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <d2/d2_log.h> #include <d2/d2_cfg_mgr.h> #include <d2/d2_simple_parser.h> #include <util/encode/hex.h> #include <boost/foreach.hpp> using namespace isc::asiolink; using namespace isc::data; using namespace isc::process; namespace isc { namespace d2 { namespace { typedef std::vector<uint8_t> ByteAddress; } // end of unnamed namespace // *********************** D2CfgContext ************************* D2CfgContext::D2CfgContext() : d2_params_(new D2Params()), forward_mgr_(new DdnsDomainListMgr("forward-ddns")), reverse_mgr_(new DdnsDomainListMgr("reverse-ddns")), keys_(new TSIGKeyInfoMap()) { } D2CfgContext::D2CfgContext(const D2CfgContext& rhs) : DCfgContextBase(rhs) { d2_params_ = rhs.d2_params_; if (rhs.forward_mgr_) { forward_mgr_.reset(new DdnsDomainListMgr(rhs.forward_mgr_->getName())); forward_mgr_->setDomains(rhs.forward_mgr_->getDomains()); } if (rhs.reverse_mgr_) { reverse_mgr_.reset(new DdnsDomainListMgr(rhs.reverse_mgr_->getName())); reverse_mgr_->setDomains(rhs.reverse_mgr_->getDomains()); } keys_ = rhs.keys_; } D2CfgContext::~D2CfgContext() { } ElementPtr D2CfgContext::toElement() const { ElementPtr d2 = Element::createMap(); // Set ip-address const IOAddress& ip_address = d2_params_->getIpAddress(); d2->set("ip-address", Element::create(ip_address.toText())); // Set port size_t port = d2_params_->getPort(); d2->set("port", Element::create(static_cast<int64_t>(port))); // Set dns-server-timeout size_t dns_server_timeout = d2_params_->getDnsServerTimeout(); d2->set("dns-server-timeout", Element::create(static_cast<int64_t>(dns_server_timeout))); // Set ncr-protocol const dhcp_ddns::NameChangeProtocol& ncr_protocol = d2_params_->getNcrProtocol(); d2->set("ncr-protocol", Element::create(dhcp_ddns::ncrProtocolToString(ncr_protocol))); // Set ncr-format const dhcp_ddns::NameChangeFormat& ncr_format = d2_params_->getNcrFormat(); d2->set("ncr-format", Element::create(dhcp_ddns::ncrFormatToString(ncr_format))); // Set forward-ddns ElementPtr forward_ddns = Element::createMap(); forward_ddns->set("ddns-domains", forward_mgr_->toElement()); d2->set("forward-ddns", forward_ddns); // Set reverse-ddns ElementPtr reverse_ddns = Element::createMap(); reverse_ddns->set("ddns-domains", reverse_mgr_->toElement()); d2->set("reverse-ddns", reverse_ddns); // Set tsig-keys ElementPtr tsig_keys = Element::createList(); for (TSIGKeyInfoMap::const_iterator key = keys_->begin(); key != keys_->end(); ++key) { tsig_keys->add(key->second->toElement()); } d2->set("tsig-keys", tsig_keys); // Set DhcpDdns ElementPtr result = Element::createMap(); result->set("DhcpDdns", d2); return (result); } // *********************** D2CfgMgr ************************* const char* D2CfgMgr::IPV4_REV_ZONE_SUFFIX = "in-addr.arpa."; const char* D2CfgMgr::IPV6_REV_ZONE_SUFFIX = "ip6.arpa."; D2CfgMgr::D2CfgMgr() : DCfgMgrBase(DCfgContextBasePtr(new D2CfgContext())) { // TSIG keys need to parse before the Domains, so we can catch Domains // that specify undefined keys. Create the necessary parsing order now. addToParseOrder("tsig-keys"); addToParseOrder("forward-ddns"); addToParseOrder("reverse-ddns"); } D2CfgMgr::~D2CfgMgr() { } DCfgContextBasePtr D2CfgMgr::createNewContext() { return (DCfgContextBasePtr(new D2CfgContext())); } bool D2CfgMgr::forwardUpdatesEnabled() { // Forward updates are not enabled if no forward servers are defined. return (getD2CfgContext()->getForwardMgr()->size() > 0); } bool D2CfgMgr::reverseUpdatesEnabled() { // Reverse updates are not enabled if no reverse servers are defined. return (getD2CfgContext()->getReverseMgr()->size() > 0); } bool D2CfgMgr::matchForward(const std::string& fqdn, DdnsDomainPtr& domain) { if (fqdn.empty()) { // This is a programmatic error and should not happen. isc_throw(D2CfgError, "matchForward passed an empty fqdn"); } // Fetch the forward manager from the D2 context. DdnsDomainListMgrPtr mgr = getD2CfgContext()->getForwardMgr(); // Call the manager's match method and return the result. return (mgr->matchDomain(fqdn, domain)); } bool D2CfgMgr::matchReverse(const std::string& ip_address, DdnsDomainPtr& domain) { // Note, reverseIpAddress will throw if the ip_address is invalid. std::string reverse_address = reverseIpAddress(ip_address); // Fetch the reverse manager from the D2 context. DdnsDomainListMgrPtr mgr = getD2CfgContext()->getReverseMgr(); return (mgr->matchDomain(reverse_address, domain)); } std::string D2CfgMgr::reverseIpAddress(const std::string& address) { try { // Convert string address into an IOAddress and invoke the // appropriate reverse method. isc::asiolink::IOAddress ioaddr(address); if (ioaddr.isV4()) { return (reverseV4Address(ioaddr)); } return (reverseV6Address(ioaddr)); } catch (const isc::Exception& ex) { isc_throw(D2CfgError, "D2CfgMgr cannot reverse address: " << address << " : " << ex.what()); } } std::string D2CfgMgr::reverseV4Address(const isc::asiolink::IOAddress& ioaddr) { if (!ioaddr.isV4()) { isc_throw(D2CfgError, "D2CfgMgr address is not IPv4 address :" << ioaddr); } // Get the address in byte vector form. const ByteAddress bytes = ioaddr.toBytes(); // Walk backwards through vector outputting each octet and a dot. std::ostringstream stream; // We have to set the following variable to get // const_reverse_iterator type of rend(), otherwise Solaris GCC // complains on operator!= by trying to use the non-const variant. const ByteAddress::const_reverse_iterator end = bytes.rend(); for (ByteAddress::const_reverse_iterator rit = bytes.rbegin(); rit != end; ++rit) { stream << static_cast<unsigned int>(*rit) << "."; } // Tack on the suffix and we're done. stream << IPV4_REV_ZONE_SUFFIX; return(stream.str()); } std::string D2CfgMgr::reverseV6Address(const isc::asiolink::IOAddress& ioaddr) { if (!ioaddr.isV6()) { isc_throw(D2CfgError, "D2Cfg address is not IPv6 address: " << ioaddr); } // Turn the address into a string of digits. const ByteAddress bytes = ioaddr.toBytes(); const std::string digits = isc::util::encode::encodeHex(bytes); // Walk backwards through string outputting each digits and a dot. std::ostringstream stream; // We have to set the following variable to get // const_reverse_iterator type of rend(), otherwise Solaris GCC // complains on operator!= by trying to use the non-const variant. const std::string::const_reverse_iterator end = digits.rend(); for (std::string::const_reverse_iterator rit = digits.rbegin(); rit != end; ++rit) { stream << static_cast<char>(*rit) << "."; } // Tack on the suffix and we're done. stream << IPV6_REV_ZONE_SUFFIX; return(stream.str()); } const D2ParamsPtr& D2CfgMgr::getD2Params() { return (getD2CfgContext()->getD2Params()); } std::string D2CfgMgr::getConfigSummary(const uint32_t) { return (getD2Params()->getConfigSummary()); } namespace { template <typename int_type> int_type getInt(const std::string& name, isc::data::ConstElementPtr value) { int64_t val_int = value->intValue(); if ((val_int < std::numeric_limits<int_type>::min()) || (val_int > std::numeric_limits<int_type>::max())) { isc_throw(D2CfgError, "out of range value (" << val_int << ") specified for parameter '" << name << "' (" << value->getPosition() << ")"); } return (static_cast<int_type>(val_int)); } isc::asiolink::IOAddress getIOAddress(const std::string& name, isc::data::ConstElementPtr value) { std::string str = value->stringValue(); try { return (isc::asiolink::IOAddress(str)); } catch (const std::exception& ex) { isc_throw(D2CfgError, "invalid address (" << str << ") specified for parameter '" << name << "' (" << value->getPosition() << ")"); } } dhcp_ddns::NameChangeProtocol getProtocol(const std::string& name, isc::data::ConstElementPtr value) { std::string str = value->stringValue(); try { return (dhcp_ddns::stringToNcrProtocol(str)); } catch (const std::exception& ex) { isc_throw(D2CfgError, "invalid NameChangeRequest protocol (" << str << ") specified for parameter '" << name << "' (" << value->getPosition() << ")"); } } dhcp_ddns::NameChangeFormat getFormat(const std::string& name, isc::data::ConstElementPtr value) { std::string str = value->stringValue(); try { return (dhcp_ddns::stringToNcrFormat(str)); } catch (const std::exception& ex) { isc_throw(D2CfgError, "invalid NameChangeRequest format (" << str << ") specified for parameter '" << name << "' (" << value->getPosition() << ")"); } } } // anon void D2CfgMgr::parseElement(const std::string& element_id, isc::data::ConstElementPtr element) { try { // Get D2 specific context. D2CfgContextPtr context = getD2CfgContext(); if ((element_id == "ip-address") || (element_id == "ncr-protocol") || (element_id == "ncr-format") || (element_id == "port") || (element_id == "dns-server-timeout")) { // global scalar params require nothing extra be done } else if (element_id == "tsig-keys") { TSIGKeyInfoListParser parser; context->setKeys(parser.parse(element)); } else if (element_id == "forward-ddns") { DdnsDomainListMgrParser parser; DdnsDomainListMgrPtr mgr = parser.parse(element, element_id, context->getKeys()); context->setForwardMgr(mgr); } else if (element_id == "reverse-ddns") { DdnsDomainListMgrParser parser; DdnsDomainListMgrPtr mgr = parser.parse(element, element_id, context->getKeys()); context->setReverseMgr(mgr); } else { // Shouldn't occur if the JSON parser is doing its job. isc_throw(D2CfgError, "Unsupported element: " << element_id << element->getPosition()); } } catch (const D2CfgError& ex) { // Should already have a specific error and position info throw ex; } catch (const std::exception& ex) { isc_throw(D2CfgError, "element: " << element_id << " : " << ex.what() << element->getPosition()); } }; void D2CfgMgr::setCfgDefaults(isc::data::ElementPtr mutable_config) { D2SimpleParser::setAllDefaults(mutable_config); } void D2CfgMgr::buildParams(isc::data::ConstElementPtr params_config) { // Base class build creates parses and invokes build on each parser. // This populate the context scalar stores with all of the parameters. DCfgMgrBase::buildParams(params_config); // Fetch the parameters in the config, performing any logcial // validation required. asiolink::IOAddress ip_address(0); uint32_t port = 0; uint32_t dns_server_timeout = 0; dhcp_ddns::NameChangeProtocol ncr_protocol = dhcp_ddns::NCR_UDP; dhcp_ddns::NameChangeFormat ncr_format = dhcp_ddns::FMT_JSON; // Assumes that params_config has had defaults added BOOST_FOREACH(isc::dhcp::ConfigPair param, params_config->mapValue()) { std::string entry(param.first); isc::data::ConstElementPtr value(param.second); try { if (entry == "ip-address") { ip_address = getIOAddress(entry, value); if ((ip_address.toText() == "0.0.0.0") || (ip_address.toText() == "::")) { isc_throw(D2CfgError, "IP address cannot be \"" << ip_address << "\"" << " (" << value->getPosition() << ")"); } } else if (entry == "port") { port = getInt<uint32_t>(entry, value); } else if (entry == "dns-server-timeout") { dns_server_timeout = getInt<uint32_t>(entry, value); } else if (entry == "ncr-protocol") { ncr_protocol = getProtocol(entry, value); if (ncr_protocol != dhcp_ddns::NCR_UDP) { isc_throw(D2CfgError, "ncr-protocol : " << dhcp_ddns::ncrProtocolToString(ncr_protocol) << " is not yet supported " << " (" << value->getPosition() << ")"); } } else if (entry == "ncr-format") { ncr_format = getFormat(entry, value); if (ncr_format != dhcp_ddns::FMT_JSON) { isc_throw(D2CfgError, "NCR Format:" << dhcp_ddns::ncrFormatToString(ncr_format) << " is not yet supported" << " (" << value->getPosition() << ")"); } } else { isc_throw(D2CfgError, "unsupported parameter '" << entry << " (" << value->getPosition() << ")"); } } catch (const isc::data::TypeError&) { isc_throw(D2CfgError, "invalid value type specified for parameter '" << entry << " (" << value->getPosition() << ")"); } } // Attempt to create the new client config. This ought to fly as // we already validated everything. D2ParamsPtr params(new D2Params(ip_address, port, dns_server_timeout, ncr_protocol, ncr_format)); getD2CfgContext()->getD2Params() = params; } }; // end of isc::dhcp namespace }; // end of isc namespace
35.316547
79
0.606641
[ "vector" ]
d7945c9f6a9ee62855c4813d75363ac9cf92c6f4
5,248
hpp
C++
src/editor/editor.hpp
shacklettbp/csknowviz
8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7
[ "MIT" ]
null
null
null
src/editor/editor.hpp
shacklettbp/csknowviz
8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7
[ "MIT" ]
null
null
null
src/editor/editor.hpp
shacklettbp/csknowviz
8c4e1b9f8bc15818ab47e0a6252c168bd9fc25c7
[ "MIT" ]
null
null
null
#pragma once #include <unordered_set> #include <unordered_map> #include <utility> #include <string> #include "renderer.hpp" #include "utils.hpp" #include "json.hpp" namespace RLpbr { namespace editor { struct AreaLight { std::array<glm::vec3, 4> vertices; glm::vec3 translate; }; struct NavmeshData { std::vector<AABB> aabbs; std::vector<OverlayVertex> overlayVerts; std::vector<uint32_t> overlayIdxs; std::unordered_map<uint64_t, uint64_t> navmeshIndexToAABBIndex; std::unordered_map<uint64_t, uint64_t> aabbIndexToNavmeshIndex; std::unordered_map<uint64_t, std::vector<uint64_t>> aabbNeighbors; }; struct compareVec { bool operator() (const glm::vec3& lhs, const glm::vec3& rhs) const { return (lhs.x < rhs.x) || (lhs.x == rhs.x && lhs.y < rhs.y) || (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z < rhs.z); } }; struct compareAABB { compareVec c; bool operator() (const AABB& lhs, const AABB& rhs) const { if (glm::all(glm::equal(lhs.pMin, rhs.pMin))) { return c(lhs.pMax, rhs.pMax); } else { return c(lhs.pMin, rhs.pMin); } } }; struct pairHash { template <class T1, class T2> std::size_t operator () (std::pair<T1, T2> const &pair) const { std::size_t h1 = std::hash<T1>()(pair.first); std::size_t h2 = std::hash<T2>()(pair.second); return h1 ^ h2; } }; // https://gist.github.com/etcwilde/0eb1870fbce202184499 class Points { public: Points() : m_verts() { } Points(const std::vector<glm::vec3>& verts) : m_verts(verts) { } inline void addVertex(const glm::vec3& v) { m_verts.push_back(v); } const glm::vec3& operator[](unsigned int i) const { return m_verts[i]; } unsigned int size() const { return m_verts.size(); } private: std::vector<glm::vec3> m_verts; }; class PointsAdaptor { public: PointsAdaptor(const Points& pts) : m_pts(pts) { } inline unsigned int kdtree_get_point_count() const { return m_pts.size(); } inline float kdtree_distance(const float* p1, const unsigned int index_2, unsigned int) const { return glm::length(glm::vec3(p1[0], p1[1], p1[2]) - m_pts[index_2]); } inline float kdtree_get_pt(const unsigned int i, int dim) const { if (dim == 0) return m_pts[i].x; else if (dim == 1) return m_pts[i].y; else return m_pts[i].z; } template <class BBOX> bool kdtree_get_bbox(BBOX&) const { return false; } private: const Points& m_pts; }; struct ArrayLookup { size_t start; size_t length; }; class Vec3IndexLessThan { public: Vec3IndexLessThan(const std::vector<glm::vec3>& points) : m_points(points) { } inline glm::ivec3 getGridCoordinates(const int idx) { glm::vec3 point = m_points[idx]; return {std::floor(point.x) / gridSize + halfArrayDim, std::floor(point.y) / gridSize + halfArrayDim, std::floor(point.z) / gridSize + halfArrayDim}; } inline bool operator() (const int& idx0, const int& idx1) { glm::ivec3 c0 = getGridCoordinates(idx0); glm::ivec3 c1 = getGridCoordinates(idx1); return (c0.x < c1.x) || (c0.x == c1.x && c0.y < c1.y) || (c0.x == c1.x && c0.y == c1.y && c0.z < c1.z); } const int gridSize = 10; const int halfArrayDim = 400; private: const std::vector<glm::vec3>& m_points; }; struct CoverResults { std::vector<AABB> aabbs; std::vector<AABB> allEdges; std::vector<OverlayVertex> overlayVerts; std::vector<uint32_t> overlayIdxs; std::vector<uint32_t> edgeClusterIndices; uint32_t num_clusters; }; struct CoverData { std::optional<NavmeshData> navmesh {}; std::optional<vk::LocalBuffer> navmeshAABBGPU {}; std::optional<ExpandedTLAS> tlasWithAABBs {}; bool showNavmesh = false; std::unordered_map<glm::vec3, CoverResults> results {}; std::vector<bool> origin_to_navmesh_pvs; bool showCover = false; float sampleSpacing = 20.f; float voxelSizeXZ = 32.f * 0.8; float voxelStrideXZ = 2.f; float voxelSizeY = 72.f; float agentHeight = 72.f; float eyeHeight = 64.f; float torsoHeight = 35.f; int sqrtOffsetSamples = 3; float offsetRadius = 10.f; int numVoxelTests = 20; int numAABBs = 20; glm::vec3 nearestCamPoint = glm::vec3(0.f); AABB launchRegion; bool triedLoadingLaunchRegion = false; bool definingLaunchRegion = false; bool definedLaunchRegion = false; bool showAllCoverEdges = false; bool fixOrigin = false; }; struct EditorScene { std::string scenePath; std::filesystem::path outputPath; EditorVkScene hdl; std::vector<char> cpuData; PackedVertex *verts; uint32_t *indices; AABB bbox; uint32_t totalTriangles; EditorCam cam; Renderer::OverlayConfig overlayCfg; CoverData cover; }; class Editor { public: Editor(uint32_t gpu_id, uint32_t img_width, uint32_t img_height); void loadScene(const char *scene_name, std::filesystem::path output_path); void loop(); private: void startFrame(); void render(EditorScene &scene, float frame_duration); Renderer renderer_; uint32_t cur_scene_idx_; std::vector<EditorScene> scenes_; }; } }
24.638498
82
0.648056
[ "render", "vector" ]
d79574282d715a93273d7d07d9c7c2d5245b1e6b
13,555
cpp
C++
gnc/matlab/code_generation/sharedutils/ekfccjmgknopmoph_svd.cpp
sahibdhanjal/astrobee
5bc4e6e58adcf1bc7e1c3719ced736063bba276c
[ "Apache-2.0" ]
3
2018-01-04T02:00:49.000Z
2020-09-29T20:32:07.000Z
gnc/matlab/code_generation/sharedutils/ekfccjmgknopmoph_svd.cpp
sahibdhanjal/astrobee
5bc4e6e58adcf1bc7e1c3719ced736063bba276c
[ "Apache-2.0" ]
null
null
null
gnc/matlab/code_generation/sharedutils/ekfccjmgknopmoph_svd.cpp
sahibdhanjal/astrobee
5bc4e6e58adcf1bc7e1c3719ced736063bba276c
[ "Apache-2.0" ]
2
2020-02-20T06:02:33.000Z
2020-07-21T11:45:47.000Z
// // File: ekfccjmgknopmoph_svd.cpp // // Code generated for Simulink model 'fam_force_allocation_module'. // // Model version : 1.1142 // Simulink Coder version : 8.11 (R2016b) 25-Aug-2016 // C/C++ source code generated on : Mon Dec 4 08:34:01 2017 // #include "rtwtypes.h" #include <math.h> #include <string.h> #include "bimohlfkbaaidbai_xscal.h" #include "cbimpphlphlnekfc_xswap.h" #include "ekfkdjmomglnngln_xdotc.h" #include "fkngjekfaimgmohd_xaxpy.h" #include "hdbinophmgdjjmoh_xrotg.h" #include "imopmohdaaaimgln_xrot.h" #include "knohlnohphdbkfcj_xnrm2.h" #include "knoplnopecjmpphd_xaxpy.h" #include "lfcjdbieaimomoph_xdotc.h" #include "mgdjglnoimohglno_xaxpy.h" #include "nglndjmgaimophdj_xswap.h" #include "nohlkfkngdjmkfcb_xrot.h" #include "ohlfeknojmopaimg_xscal.h" #include "opphjmohhlnodjmo_xaxpy.h" #include "ppppfkfkiekfimop_xnrm2.h" #include "rt_nonfinite.h" #include "ekfccjmgknopmoph_svd.h" // Function for MATLAB Function: '<S12>/MATLAB Function' void ekfccjmgknopmoph_svd(const real32_T A[72], real32_T U[72], real32_T S[36], real32_T V[36]) { real32_T b_A[72]; real32_T s[6]; real32_T e[6]; real32_T work[12]; real32_T Vf[36]; int32_T q; boolean_T apply_transform; int32_T iter; real32_T snorm; real32_T ztest0; int32_T kase; int32_T qs; real32_T ztest; real32_T smm1; real32_T emm1; real32_T sqds; real32_T shift; int32_T j_ii; real32_T varargin_1[5]; int32_T i; boolean_T exitg1; boolean_T exitg2; int32_T exitg3; memcpy(&b_A[0], &A[0], (uint32_T)(72U * sizeof(real32_T))); for (i = 0; i < 6; i++) { s[i] = 0.0F; e[i] = 0.0F; } for (i = 0; i < 12; i++) { work[i] = 0.0F; } memset(&U[0], 0, (uint32_T)(72U * sizeof(real32_T))); memset(&Vf[0], 0, (uint32_T)(36U * sizeof(real32_T))); for (i = 0; i < 6; i++) { iter = (int32_T)((int32_T)(12 * i) + i); apply_transform = false; snorm = ppppfkfkiekfimop_xnrm2((int32_T)(12 - i), b_A, (int32_T)(iter + 1)); if (snorm > 0.0F) { apply_transform = true; if (b_A[iter] < 0.0F) { s[i] = -snorm; } else { s[i] = snorm; } if ((real32_T)fabs((real_T)s[i]) >= 9.86076132E-32F) { snorm = 1.0F / s[i]; q = (int32_T)((int32_T)(iter - i) + 12); for (qs = iter; (int32_T)(qs + 1) <= q; qs++) { b_A[qs] *= snorm; } } else { q = (int32_T)((int32_T)(iter - i) + 12); for (qs = iter; (int32_T)(qs + 1) <= q; qs++) { b_A[qs] /= s[i]; } } b_A[iter]++; s[i] = -s[i]; } else { s[i] = 0.0F; } for (q = (int32_T)(i + 1); (int32_T)(q + 1) < 7; q++) { qs = (int32_T)((int32_T)(12 * q) + i); if (apply_transform) { fkngjekfaimgmohd_xaxpy((int32_T)(12 - i), -(ekfkdjmomglnngln_xdotc ((int32_T)(12 - i), b_A, (int32_T)(iter + 1), b_A, (int32_T)(qs + 1)) / b_A[(int32_T)(i + (int32_T)(12 * i))]), (int32_T)(iter + 1), b_A, (int32_T)(qs + 1)); } e[q] = b_A[qs]; } for (iter = i; (int32_T)(iter + 1) < 13; iter++) { U[(int32_T)(iter + (int32_T)(12 * i))] = b_A[(int32_T)((int32_T)(12 * i) + iter)]; } if ((int32_T)(i + 1) <= 4) { snorm = knohlnohphdbkfcj_xnrm2((int32_T)(5 - i), e, (int32_T)(i + 2)); if (snorm == 0.0F) { e[i] = 0.0F; } else { if (e[(int32_T)(i + 1)] < 0.0F) { e[i] = -snorm; } else { e[i] = snorm; } snorm = e[i]; if ((real32_T)fabs((real_T)e[i]) >= 9.86076132E-32F) { snorm = 1.0F / e[i]; for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 7; iter++) { e[iter] *= snorm; } } else { for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 7; iter++) { e[iter] /= snorm; } } e[(int32_T)(i + 1)]++; e[i] = -e[i]; for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 13; iter++) { work[iter] = 0.0F; } for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 7; iter++) { mgdjglnoimohglno_xaxpy((int32_T)(11 - i), e[iter], b_A, (int32_T) ((int32_T)(i + (int32_T)(12 * iter)) + 2), work, (int32_T)(i + 2)); } for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 7; iter++) { opphjmohhlnodjmo_xaxpy((int32_T)(11 - i), -e[iter] / e[(int32_T)(i + 1)], work, (int32_T)(i + 2), b_A, (int32_T)((int32_T)(i + (int32_T)(12 * iter)) + 2)); } } for (iter = (int32_T)(i + 1); (int32_T)(iter + 1) < 7; iter++) { Vf[(int32_T)(iter + (int32_T)(6 * i))] = e[iter]; } } } i = 4; e[4] = b_A[64]; e[5] = 0.0F; for (q = 5; q >= 0; q += -1) { iter = (int32_T)((int32_T)(12 * q) + q); if (s[q] != 0.0F) { for (kase = (int32_T)(q + 1); (int32_T)(kase + 1) < 7; kase++) { qs = (int32_T)((int32_T)((int32_T)(12 * kase) + q) + 1); fkngjekfaimgmohd_xaxpy((int32_T)(12 - q), -(ekfkdjmomglnngln_xdotc ((int32_T)(12 - q), U, (int32_T)(iter + 1), U, qs) / U[iter]), (int32_T)(iter + 1), U, qs); } for (qs = q; (int32_T)(qs + 1) < 13; qs++) { U[(int32_T)(qs + (int32_T)(12 * q))] = -U[(int32_T)((int32_T)(12 * q) + qs)]; } U[iter]++; for (iter = 1; iter <= q; iter++) { U[(int32_T)((int32_T)(iter + (int32_T)(12 * q)) - 1)] = 0.0F; } } else { for (qs = 0; qs < 12; qs++) { U[(int32_T)(qs + (int32_T)(12 * q))] = 0.0F; } U[iter] = 1.0F; } } for (iter = 5; iter >= 0; iter += -1) { if (((int32_T)(iter + 1) <= 4) && (e[iter] != 0.0F)) { q = (int32_T)((int32_T)((int32_T)(6 * iter) + iter) + 2); for (qs = (int32_T)(iter + 1); (int32_T)(qs + 1) < 7; qs++) { kase = (int32_T)((int32_T)((int32_T)(6 * qs) + iter) + 2); knoplnopecjmpphd_xaxpy((int32_T)(5 - iter), -(lfcjdbieaimomoph_xdotc ((int32_T)(5 - iter), Vf, q, Vf, kase) / Vf[(int32_T)(q - 1)]), q, Vf, kase); } } for (q = 0; q < 6; q++) { Vf[(int32_T)(q + (int32_T)(6 * iter))] = 0.0F; } Vf[(int32_T)(iter + (int32_T)(6 * iter))] = 1.0F; } for (iter = 0; iter < 6; iter++) { ztest = e[iter]; if (s[iter] != 0.0F) { ztest0 = (real32_T)fabs((real_T)s[iter]); snorm = s[iter] / ztest0; s[iter] = ztest0; if ((int32_T)(iter + 1) < 6) { ztest = e[iter] / snorm; } bimohlfkbaaidbai_xscal(snorm, U, (int32_T)(1 + (int32_T)(12 * iter))); } if (((int32_T)(iter + 1) < 6) && (ztest != 0.0F)) { ztest0 = (real32_T)fabs((real_T)ztest); snorm = ztest0 / ztest; ztest = ztest0; s[(int32_T)(iter + 1)] *= snorm; ohlfeknojmopaimg_xscal(snorm, Vf, (int32_T)(1 + (int32_T)(6 * (int32_T) (iter + 1)))); } e[iter] = ztest; } iter = 0; snorm = 0.0F; for (q = 0; q < 6; q++) { ztest0 = (real32_T)fabs((real_T)s[q]); ztest = (real32_T)fabs((real_T)e[q]); if ((ztest0 >= ztest) || rtIsNaNF(ztest)) { ztest = ztest0; } if (!((snorm >= ztest) || rtIsNaNF(ztest))) { snorm = ztest; } } while (((int32_T)(i + 2) > 0) && (!(iter >= 75))) { kase = (int32_T)(i + 1); do { exitg3 = 0; q = kase; if (kase == 0) { exitg3 = 1; } else { ztest0 = (real32_T)fabs((real_T)e[(int32_T)(kase - 1)]); if ((ztest0 <= ((real32_T)fabs((real_T)s[(int32_T)(kase - 1)]) + (real32_T)fabs((real_T)s[kase])) * 1.1920929E-7F) || ((ztest0 <= 9.86076132E-32F) || ((iter > 20) && (ztest0 <= 1.1920929E-7F * snorm)))) { e[(int32_T)(kase - 1)] = 0.0F; exitg3 = 1; } else { kase--; } } } while (exitg3 == 0); if ((int32_T)(i + 1) == kase) { kase = 4; } else { qs = (int32_T)(i + 2); j_ii = (int32_T)(i + 2); exitg2 = false; while ((!exitg2) && (j_ii >= kase)) { qs = j_ii; if (j_ii == kase) { exitg2 = true; } else { ztest0 = 0.0F; if (j_ii < (int32_T)(i + 2)) { ztest0 = (real32_T)fabs((real_T)e[(int32_T)(j_ii - 1)]); } if (j_ii > (int32_T)(kase + 1)) { ztest0 += (real32_T)fabs((real_T)e[(int32_T)(j_ii - 2)]); } ztest = (real32_T)fabs((real_T)s[(int32_T)(j_ii - 1)]); if ((ztest <= 1.1920929E-7F * ztest0) || (ztest <= 9.86076132E-32F)) { s[(int32_T)(j_ii - 1)] = 0.0F; exitg2 = true; } else { j_ii--; } } } if (qs == kase) { kase = 3; } else if ((int32_T)(i + 2) == qs) { kase = 1; } else { kase = 2; q = qs; } } switch (kase) { case 1: ztest0 = e[i]; e[i] = 0.0F; for (qs = i; (int32_T)(qs + 1) >= (int32_T)(q + 1); qs--) { ztest = s[qs]; hdbinophmgdjjmoh_xrotg(&ztest, &ztest0, &sqds, &smm1); s[qs] = ztest; if ((int32_T)(qs + 1) > (int32_T)(q + 1)) { ztest0 = e[(int32_T)(qs - 1)] * -smm1; e[(int32_T)(qs - 1)] *= sqds; } imopmohdaaaimgln_xrot(Vf, (int32_T)(1 + (int32_T)(6 * qs)), (int32_T)(1 + (int32_T)(6 * (int32_T)(i + 1))), sqds, smm1); } break; case 2: ztest0 = e[(int32_T)(q - 1)]; e[(int32_T)(q - 1)] = 0.0F; for (qs = q; (int32_T)(qs + 1) <= (int32_T)(i + 2); qs++) { ztest = s[qs]; hdbinophmgdjjmoh_xrotg(&ztest, &ztest0, &sqds, &smm1); s[qs] = ztest; ztest0 = -smm1 * e[qs]; e[qs] *= sqds; nohlkfkngdjmkfcb_xrot(U, (int32_T)(1 + (int32_T)(12 * qs)), (int32_T)(1 + (int32_T)(12 * (int32_T)(q - 1))), sqds, smm1); } break; case 3: varargin_1[0] = (real32_T)fabs((real_T)s[(int32_T)(i + 1)]); varargin_1[1] = (real32_T)fabs((real_T)s[i]); varargin_1[2] = (real32_T)fabs((real_T)e[i]); varargin_1[3] = (real32_T)fabs((real_T)s[q]); varargin_1[4] = (real32_T)fabs((real_T)e[q]); qs = 1; ztest = varargin_1[0]; if (rtIsNaNF(varargin_1[0])) { kase = 2; exitg1 = false; while ((!exitg1) && (kase < 6)) { qs = kase; if (!rtIsNaNF(varargin_1[(int32_T)(kase - 1)])) { ztest = varargin_1[(int32_T)(kase - 1)]; exitg1 = true; } else { kase++; } } } if (qs < 5) { while ((int32_T)(qs + 1) < 6) { if (varargin_1[qs] > ztest) { ztest = varargin_1[qs]; } qs++; } } ztest0 = s[(int32_T)(i + 1)] / ztest; smm1 = s[i] / ztest; emm1 = e[i] / ztest; sqds = s[q] / ztest; smm1 = ((smm1 + ztest0) * (smm1 - ztest0) + emm1 * emm1) / 2.0F; emm1 *= ztest0; emm1 *= emm1; if ((smm1 != 0.0F) || (emm1 != 0.0F)) { shift = (real32_T)sqrt((real_T)(smm1 * smm1 + emm1)); if (smm1 < 0.0F) { shift = -shift; } shift = emm1 / (smm1 + shift); } else { shift = 0.0F; } ztest0 = (sqds + ztest0) * (sqds - ztest0) + shift; ztest = e[q] / ztest * sqds; for (qs = (int32_T)(q + 1); qs <= (int32_T)(i + 1); qs++) { hdbinophmgdjjmoh_xrotg(&ztest0, &ztest, &sqds, &smm1); if (qs > (int32_T)(q + 1)) { e[(int32_T)(qs - 2)] = ztest0; } ztest0 = s[(int32_T)(qs - 1)] * sqds + e[(int32_T)(qs - 1)] * smm1; e[(int32_T)(qs - 1)] = e[(int32_T)(qs - 1)] * sqds - s[(int32_T)(qs - 1)] * smm1; ztest = smm1 * s[qs]; s[qs] *= sqds; imopmohdaaaimgln_xrot(Vf, (int32_T)(1 + (int32_T)(6 * (int32_T)(qs - 1))), (int32_T)(1 + (int32_T)(6 * qs)), sqds, smm1); hdbinophmgdjjmoh_xrotg(&ztest0, &ztest, &sqds, &smm1); s[(int32_T)(qs - 1)] = ztest0; ztest0 = e[(int32_T)(qs - 1)] * sqds + smm1 * s[qs]; s[qs] = e[(int32_T)(qs - 1)] * -smm1 + sqds * s[qs]; ztest = smm1 * e[qs]; e[qs] *= sqds; nohlkfkngdjmkfcb_xrot(U, (int32_T)(1 + (int32_T)(12 * (int32_T)(qs - 1))), (int32_T)(1 + (int32_T)(12 * qs)), sqds, smm1); } e[i] = ztest0; iter++; break; default: if (s[q] < 0.0F) { s[q] = -s[q]; ohlfeknojmopaimg_xscal(-1.0F, Vf, (int32_T)(1 + (int32_T)(6 * q))); } iter = (int32_T)(q + 1); while (((int32_T)(q + 1) < 6) && (s[q] < s[iter])) { ztest0 = s[q]; s[q] = s[iter]; s[iter] = ztest0; cbimpphlphlnekfc_xswap(Vf, (int32_T)(1 + (int32_T)(6 * q)), (int32_T)(1 + (int32_T)(6 * (int32_T)(q + 1)))); nglndjmgaimophdj_xswap(U, (int32_T)(1 + (int32_T)(12 * q)), (int32_T)(1 + (int32_T)(12 * (int32_T)(q + 1)))); q = iter; iter++; } iter = 0; i--; break; } } for (i = 0; i < 6; i++) { e[i] = s[i]; for (iter = 0; iter < 6; iter++) { V[(int32_T)(iter + (int32_T)(6 * i))] = Vf[(int32_T)((int32_T)(6 * i) + iter)]; } } memset(&S[0], 0, (uint32_T)(36U * sizeof(real32_T))); for (i = 0; i < 6; i++) { S[(int32_T)(i + (int32_T)(6 * i))] = e[i]; } } // // File trailer for generated code. // // [EOF] //
28.901919
83
0.466322
[ "model" ]
d7958cbc439f94bc72330717b8f4f4e70030f8aa
1,359
cpp
C++
1011_shipWithinDays.cpp
yzhhome/leetcode_cpp
69404b039848e9e43ace80c43243f04b037a1fa1
[ "MIT" ]
null
null
null
1011_shipWithinDays.cpp
yzhhome/leetcode_cpp
69404b039848e9e43ace80c43243f04b037a1fa1
[ "MIT" ]
null
null
null
1011_shipWithinDays.cpp
yzhhome/leetcode_cpp
69404b039848e9e43ace80c43243f04b037a1fa1
[ "MIT" ]
null
null
null
/* 1011. 在D天内送达包裹的能力 https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/ */ #include <iostream> #include <vector> using namespace std; // weights重量的货物,以cap的运载能力,D天内能否完成运输 bool canFinish(vector<int> weights, int D, int caps){ int i = 0; for (int day = 0; day < D; day++){ int maxCap = caps; while ((maxCap -= weights[i]) >= 0){ i++; // 能装下货物 if (i == weights.size()) return true; } } return false; } // 货物重量的最大值 int getMax(vector<int> weights){ int maxValue = 0; for (int n : weights){ maxValue = max(maxValue, n); } return maxValue; } // 货物重量的和 int getSum(vector<int> weights){ int sumValue = 0; for (int n : weights){ sumValue += n; } return sumValue; } int shipWithinDays(vector<int> weights, int days){ // 套用二分搜索左侧边界的算法框架 int left = getMax(weights), right = getSum(weights) + 1; while (left < right){ int mid = left + (right - left) / 2; if (canFinish(weights, days, mid)){ right = mid; } else{ left = mid + 1; } } return left; } int main(){ int D = 5; vector<int> weights = {1,2,3,4,5,6,7,8,9,10}; cout<<shipWithinDays(weights, D)<<endl; system("pause"); return 0; }
20.590909
77
0.535688
[ "vector" ]
d79685629c1079cfa805d19d0f934a5423d6aad9
20,174
cc
C++
L1Trigger/Phase2L1Taus/test/L1TausAnalyzer.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
L1Trigger/Phase2L1Taus/test/L1TausAnalyzer.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
L1Trigger/Phase2L1Taus/test/L1TausAnalyzer.cc
thesps/cmssw
ad5315934948ce96699b29cc1d5b03a59f99634f
[ "Apache-2.0" ]
null
null
null
// -*- C++ -*- // // Package: L1TausAnalyzer // Class: L1TausAnalyzer // /**\class L1TausAnalyzer L1TausAnalyzer.cc Description: Study the performace of the L1 hadronic tau algorithms (Rates, Efficiencies, Turn-on curves) Implementation: [Notes on implementation] */ // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Utilities/interface/InputTag.h" // Gen-level stuff: #include "DataFormats/L1Trigger/interface/L1Candidate.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/HepMCCandidate/interface/GenParticleFwd.h" #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h" // L1Tau Objects: #include "DataFormats/L1TrackTrigger/interface/L1TrkTauParticle.h" #include "L1Trigger/Phase2L1Taus/interface/L1TrkTauEtComparator.h" #include "DataFormats/L1TrackTrigger/interface/L1TkEGTauParticle.h" #include "L1Trigger/Phase2L1Taus/interface/L1TkEGTauEtComparator.h" #include "DataFormats/L1TrackTrigger/interface/L1CaloTkTauParticle.h" #include "SimDataFormats/Track/interface/SimTrackContainer.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "DataFormats/Math/interface/deltaR.h" #include "DataFormats/Math/interface/deltaPhi.h" #include "TH1F.h" #include "TH2F.h" using namespace l1t; // // class declaration // class L1TausAnalyzer : public edm::EDAnalyzer { public: explicit L1TausAnalyzer(const edm::ParameterSet&); ~L1TausAnalyzer(); private: virtual void beginJob() ; virtual void analyze(const edm::Event&, const edm::EventSetup&); virtual void endJob() ; void fillIntegralHistos(TH1F* th, float var); void finaliseEfficiencyHisto(TH1F* th, const int nEvtsTotal); template <class T1> void checkEfficiency(const T1 & tkObjCollection); template<class T1> void checkRate(const T1 & tkObjCollection); std::vector<unsigned int> findGenParticles(const edm::Handle<reco::GenParticleCollection>& genH, std::vector<float>& etVis, std::vector<float>& et, std::vector<float>& eta, std::vector<float>& phi ); math::XYZTLorentzVector GetVisP4(reco::GenParticle p); bool isLepton(unsigned int pdgId); ///////////////////////////////////////////////////// // Histograms Definitions ///////////////////////////////////////////////////// // Number of events TH1F* nEvents; // Gen Particles TH1F* etVisGenL1Obj; TH1F* etGenL1Obj; TH1F* etaGenL1Obj; TH1F* phiGenL1Obj; // L1-Track Objects TH1F* nL1TrkObj; TH1F* etL1TrkObj; TH1F* etaL1TrkObj; TH1F* phiL1TrkObj; TH1F* massL1TrkObj; TH1F* etL1TrkObjMatched; TH1F* etaL1TrkObjMatched; TH1F* phiL1TrkObjMatched; TH1F* massL1TrkObjMatched; // Performance TH1F* etL1TrkObjTurnOn; TH1F* etGenObjTurnOn; TH1F* etThrL1TrkObj; TH1F* effL1TrkObj; // TH2 TH2F* etL1TrkObjVsGen; ///////////////////////////////////////////////////// // Variables Definitions ///////////////////////////////////////////////////// // Counters int ievent; int selectedL1TkObjTot; int selectedL1TkObjEtTot; unsigned int nEvtsWithMaxHadTaus; // Booleans bool bFoundAllTaus; // Configuration parameters std::string cfg_analysisOption; std::string cfg_objectType; float cfg_genEtVisThreshold; float cfg_genEtaVisCutoff; float cfg_l1EtThreshold; float cfg_l1EtaCutoff; float cfg_genEtVisThreshold_Trigger; float cfg_l1TurnOnThreshold; float cfg_dRMatching; // Gen Particles Properties std::vector<unsigned int> genIndices; std::vector<float > genEtsVis; std::vector<float > genEts; std::vector<float > genEtas; std::vector<float > genPhis; // Tokens const edm::EDGetTokenT< L1TrkTauParticleCollection > trktauToken; const edm::EDGetTokenT< L1TkEGTauParticleCollection > tkegtauToken; const edm::EDGetTokenT< L1CaloTkTauParticleCollection > calotktauToken; const edm::EDGetTokenT< reco::GenParticleCollection > genToken; }; L1TausAnalyzer::L1TausAnalyzer(const edm::ParameterSet& iConfig) : trktauToken(consumes< L1TrkTauParticleCollection > (iConfig.getParameter<edm::InputTag>("L1TrkTauInputTag"))), tkegtauToken(consumes< L1TkEGTauParticleCollection > (iConfig.getParameter<edm::InputTag>("L1TkEGTauInputTag"))), calotktauToken(consumes< L1CaloTkTauParticleCollection > (iConfig.getParameter<edm::InputTag>("L1CaloTkTauInputTag"))), genToken(consumes < reco::GenParticleCollection > (iConfig.getParameter<edm::InputTag>("GenParticleInputTag"))) { edm::Service<TFileService> fs; cfg_analysisOption = iConfig.getParameter<std::string>("AnalysisOption"); cfg_objectType = iConfig.getParameter<std::string>("ObjectType"); cfg_genEtVisThreshold = iConfig.getParameter<double>("GenEtVisThreshold"); cfg_genEtaVisCutoff = iConfig.getParameter<double>("GenEtaVisCutOff"); cfg_l1EtThreshold = iConfig.getParameter<double>("L1EtThreshold"); cfg_l1EtaCutoff = iConfig.getParameter<double>("L1EtaCutOff"); cfg_genEtVisThreshold_Trigger = iConfig.getParameter<double>("GenEtVisThreshold_Trigger"); cfg_l1TurnOnThreshold = iConfig.getParameter<double>("L1TurnOnThreshold"); cfg_dRMatching = iConfig.getParameter<double>("DRMatching"); } void L1TausAnalyzer::beginJob() { edm::Service<TFileService> fs; std::ostringstream HistoName; // Number of events nEvents = fs->make<TH1F>("nEvents", "nEvents", 1 , 0.0, 1.0); // L1 Objects nL1TrkObj = fs->make<TH1F>("Multiplicity","Multiplicity", 50, -0.5, 49.5); etL1TrkObj = fs->make<TH1F>("Et" ,"Et" , 200, 0.5, 200.5); etaL1TrkObj = fs->make<TH1F>("Eta" ,"Eta" , 90, -4.5, 4.5); phiL1TrkObj = fs->make<TH1F>("Phi" ,"Phi" , 64, -3.2, 3.2); massL1TrkObj = fs->make<TH1F>("Mass" ,"Mass" , 20, 0.0, 2.0); if (cfg_analysisOption == "Efficiency") { // Gen Particles etVisGenL1Obj = fs->make<TH1F>("GenEtVis", "GenEtVis", 40, 0.5, 200.5); etGenL1Obj = fs->make<TH1F>("GenEt" , "GenEt" , 40, 0.5, 200.5); etaGenL1Obj = fs->make<TH1F>("GenEta" , "GenEta" , 90, -4.5, 4.5); phiGenL1Obj = fs->make<TH1F>("GenPhi" , "GenPhi" , 64, -3.2, 3.2); // L1 Matched object etL1TrkObjMatched = fs->make<TH1F>("EtMatched" ,"EtMatched" , 40, 0.5, 200.5); etaL1TrkObjMatched = fs->make<TH1F>("EtaMatched" ,"EtaMatched" , 90, -4.5, 4.5); phiL1TrkObjMatched = fs->make<TH1F>("PhiMatched" ,"PhiMatched" , 64, -3.2, 3.2); massL1TrkObjMatched = fs->make<TH1F>("MassMatched" ,"MassMatched" , 20, 0.0, 2.0); // 2D Plots etL1TrkObjVsGen = fs->make<TH2F>("EtVsGenEt", "EtVsGenEt", 200, 0.5, 200.5, 200, 0.5, 200.5); // Turn-on numerator plots etL1TrkObjTurnOn = fs->make<TH1F>("EtTurnOn" , "EtTurnOn" , 40, 0.5, 200.5); etGenObjTurnOn = fs->make<TH1F>("GenEtTurnOn", "GenEtTurnOn", 40, 0.5, 200.5); // Efficiency plot effL1TrkObj = fs->make<TH1F>("EtEfficiency", "EtEfficiency", 200, 0.5, 200.5); } else { // Rate plot etThrL1TrkObj = fs->make<TH1F>("EtThreshold", "EtThreshold", 200, 0.5, 200.5); } selectedL1TkObjTot = 0; selectedL1TkObjEtTot = 0; nEvtsWithMaxHadTaus = 0; ievent = 0; } L1TausAnalyzer::~L1TausAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called for each event ------------ void L1TausAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; ievent++; // Clear global vectors genIndices.clear(); genEtsVis.clear(); genEts.clear(); genEtas.clear(); genPhis.clear(); bFoundAllTaus = false; // Gen Particles if (cfg_analysisOption == "Efficiency") { edm::Handle<reco::GenParticleCollection> genParticleHandle; iEvent.getByToken(genToken, genParticleHandle); genIndices = findGenParticles(genParticleHandle, genEtsVis, genEts, genEtas, genPhis); // Check unsigned int nTrigTaus=0; for (unsigned int i=0; i < genIndices.size(); i++) { if (genEtsVis.at(i) > cfg_genEtVisThreshold_Trigger) nTrigTaus++; } if (nTrigTaus >= 2) bFoundAllTaus = true; // fixme: use the number of taus for each sample if (bFoundAllTaus) nEvtsWithMaxHadTaus++; } // TrkTau: start if (cfg_objectType == "TrkTau"){ edm::Handle< L1TrkTauParticleCollection > l1TrkTauHandle; iEvent.getByToken(trktauToken, l1TrkTauHandle); L1TrkTauParticleCollection l1TrkTauCollection = (*l1TrkTauHandle.product()); sort( l1TrkTauCollection.begin(), l1TrkTauCollection.end(), L1TrkTau::EtComparator() ); // Plot the Properties nL1TrkObj->Fill(l1TrkTauCollection.size()); for (auto tkObjIter = l1TrkTauCollection.begin(); tkObjIter != l1TrkTauCollection.end(); ++tkObjIter) { if (fabs(tkObjIter->eta()) > cfg_l1EtaCutoff && tkObjIter->et() < cfg_l1EtThreshold) continue; etL1TrkObj -> Fill(tkObjIter->et()); etaL1TrkObj -> Fill(tkObjIter->eta()); phiL1TrkObj -> Fill(tkObjIter->phi()); massL1TrkObj -> Fill(tkObjIter->mass()); } if (cfg_analysisOption == "Efficiency" && genIndices.size() > 0) checkEfficiency(l1TrkTauCollection); else if (cfg_analysisOption == "Rate") checkRate(l1TrkTauCollection); }// TrkTau: end // TkEGTau: start if (cfg_objectType == "TkEG"){ edm::Handle< L1TkEGTauParticleCollection > l1TkEGTauHandle; iEvent.getByToken(tkegtauToken, l1TkEGTauHandle); L1TkEGTauParticleCollection l1TkEGTauCollection = (*l1TkEGTauHandle.product()); sort( l1TkEGTauCollection.begin(), l1TkEGTauCollection.end(), L1TkEGTau::EtComparator() ); // Plot the Properties nL1TrkObj->Fill(l1TkEGTauCollection.size()); for (auto tkObjIter = l1TkEGTauCollection.begin(); tkObjIter != l1TkEGTauCollection.end(); ++tkObjIter) { if (fabs(tkObjIter->eta()) > cfg_l1EtaCutoff && tkObjIter->et() < cfg_l1EtThreshold) continue; etL1TrkObj -> Fill(tkObjIter->et()); etaL1TrkObj -> Fill(tkObjIter->eta()); phiL1TrkObj -> Fill(tkObjIter->phi()); massL1TrkObj -> Fill(tkObjIter->mass()); } if (cfg_analysisOption == "Efficiency" && genIndices.size() > 0) checkEfficiency(l1TkEGTauCollection); else if (cfg_analysisOption == "Rate") checkRate(l1TkEGTauCollection); }// TkEGTau: end // CaloTkTau: start if (cfg_objectType == "CaloTk"){ edm::Handle< L1CaloTkTauParticleCollection > l1CaloTkTauHandle; iEvent.getByToken(calotktauToken, l1CaloTkTauHandle); L1CaloTkTauParticleCollection l1CaloTkTauCollection = (*l1CaloTkTauHandle.product()); //sort( l1CaloTkTauCollection.begin(), l1CaloTkTauCollection.end(), L1CaloTkTau::EtComparator() ); // fixme: use L1CaloTkTauEtComparator once implemented // Plot the Properties nL1TrkObj->Fill(l1CaloTkTauCollection.size()); for (auto tkObjIter = l1CaloTkTauCollection.begin(); tkObjIter != l1CaloTkTauCollection.end(); ++tkObjIter) { if (fabs(tkObjIter->eta()) > cfg_l1EtaCutoff && tkObjIter->et() < cfg_l1EtThreshold) continue; etL1TrkObj -> Fill(tkObjIter->et()); etaL1TrkObj -> Fill(tkObjIter->eta()); phiL1TrkObj -> Fill(tkObjIter->phi()); massL1TrkObj -> Fill(tkObjIter->mass()); } if (cfg_analysisOption == "Efficiency" && genIndices.size() > 0) checkEfficiency(l1CaloTkTauCollection); else if (cfg_analysisOption == "Rate") checkRate(l1CaloTkTauCollection); }// CaloTkTau: end } void L1TausAnalyzer::endJob() { if (cfg_analysisOption == "Efficiency") { // Finalise efficiency histogram finaliseEfficiencyHisto(effL1TrkObj, nEvtsWithMaxHadTaus); // Print Efficiency Information std::cout << " Number of Selected " << cfg_objectType << " : "<< selectedL1TkObjTot << std::endl; std::cout << " Number of Events with Maxium No of Gen Hadronic Taus: "<< nEvtsWithMaxHadTaus << std::endl; std::cout << " Number of Events Proccessed " << ievent << std::endl; } // Fill histogram with number of events nEvents -> SetBinContent(1, ievent ); } template<class T1> void L1TausAnalyzer::checkEfficiency(const T1 & tkObjCollection) { std::vector<unsigned int> matchedL1TkObjIndices; // For-loop: All the gen objects in the event for (size_t i = 0; i < genIndices.size(); i++) { // Initializations float dRminTkObj = 999.9; unsigned int indxTkObj = -1 ; float etTkObj, etaTkObj, phiTkObj, massTkObj; // Find the closest track object to the gen particle unsigned int iTkObj = -1; // For-loop: All the track objects in the event for (auto tkObjIter = tkObjCollection.begin(); tkObjIter != tkObjCollection.end(); ++tkObjIter) { iTkObj++; // Get seed track properties L1TTTrackRefPtr seedTk = tkObjIter->getSeedTrk(); float seedEta = seedTk->getMomentum().eta(); float seedPhi = seedTk->getMomentum().phi(); if (fabs(tkObjIter->eta()) > cfg_l1EtaCutoff && tkObjIter->et() < cfg_l1EtThreshold) continue; float dPhi = reco::deltaPhi(seedPhi, genPhis.at(i)); float dEta = (seedEta - genEtas.at(i)); float dR = sqrt(dPhi*dPhi + dEta*dEta); //float dR = reco::deltaR(seedEta, seedPhi, genEtas.at(i),genPhis.at(i)); if (dR < dRminTkObj ) { dRminTkObj = dR; indxTkObj = iTkObj; etTkObj = tkObjIter->et(); etaTkObj = tkObjIter->eta(); phiTkObj = tkObjIter->phi(); massTkObj = tkObjIter->mass(); } }// End-loop: All the track objects in the event // Apply the matching dR criteria if (dRminTkObj < cfg_dRMatching) { selectedL1TkObjTot++; matchedL1TkObjIndices.push_back(indxTkObj); // Fill histos with properties of the matched track objects etL1TrkObjMatched -> Fill(etTkObj); etaL1TrkObjMatched -> Fill(etaTkObj); phiL1TrkObjMatched -> Fill(phiTkObj); massL1TrkObjMatched -> Fill(massTkObj); etL1TrkObjVsGen->Fill(etTkObj, genEtsVis.at(i)); // Fill turn-on numerator for a given Et threshold if (etTkObj > cfg_l1TurnOnThreshold) { selectedL1TkObjEtTot++; etL1TrkObjTurnOn->Fill(etTkObj); etGenObjTurnOn->Fill(genEtsVis.at(i)); } } // Debug if (0) { std::cout << " Gen Info : eta, phi, Et " << genEtas.at(i) << " " << genPhis.at(i) << " " << genEts.at(i) << std::endl; std::cout << " L1TkObject Info : dR Gen , et " << dRminTkObj << " " << etTkObj << std::endl; std::cout << " Selected Candidate : L1TkObject, L1TkObjectEtThr " << selectedL1TkObjTot << " " << selectedL1TkObjEtTot << std::endl; } } // End-loop: All gen objects in the event // Calculate efficiency if (matchedL1TkObjIndices.size() <= 0) return; if (!bFoundAllTaus) return; // Find the ET of the leading matched L1TrkObj float maxEt = 0; for (unsigned int i=0; i < matchedL1TkObjIndices.size(); i++) { unsigned int indx = matchedL1TkObjIndices.at(i); if (tkObjCollection.at(indx).et() > maxEt) maxEt = tkObjCollection.at(indx).et(); } // Fill efficiency histo fillIntegralHistos(effL1TrkObj, maxEt); return; } template<class T1> void L1TausAnalyzer::checkRate(const T1 & tkObjCollection) { int nObj=0; float et; // For-loop: All the track objects in the event for (auto tkObjIter = tkObjCollection.begin(); tkObjIter != tkObjCollection.end(); ++tkObjIter) { // not needed (could just use the first object - leading) if (fabs(tkObjIter->eta()) > cfg_l1EtaCutoff && tkObjIter->et() < cfg_l1EtThreshold) continue; nObj++; et = tkObjIter->et(); // Fill rate histo for with the et of the leading track object if (nObj == 1) { fillIntegralHistos(etThrL1TrkObj, et); } }// End-loop: All the track objects in the event return; } void L1TausAnalyzer::fillIntegralHistos(TH1F* th, float var){ int nbin = th->FindBin(var); for (int ibin = 1; ibin < nbin+1; ibin++) th->Fill(th->GetBinCenter(ibin)); } void L1TausAnalyzer::finaliseEfficiencyHisto(TH1F* th, const int nEvtsTotal){ const int nBinsX = th->GetNbinsX()+1; double eff, err; // For-loop: x-axis bins for (int i=0; i <= nBinsX; i++){ const int nPass = th->GetBinContent(i); // Calculate the Efficiency if (nEvtsTotal == 0) { eff = 0.0; err = 0.0; } else { eff = double(nPass)/double(nEvtsTotal); err = (1.0/nEvtsTotal) * sqrt(nPass * (1.0 - nPass/nEvtsTotal) ); //Louise } // Update current histo bin to true eff value and error th->SetBinContent(i, eff); th->SetBinError (i, err); }// For-loop: x-axis bins return; } std::vector<unsigned int> L1TausAnalyzer::findGenParticles(const edm::Handle<reco::GenParticleCollection>& genH, std::vector<float>& etVis, std::vector<float>& et, std::vector<float>& eta, std::vector<float>& phi ) { std::vector<unsigned int> indices; int pId = 0; if ((cfg_objectType == "TkEG") || (cfg_objectType == "TrkTau") || (cfg_objectType == "CaloTk")) { pId = 15; } // Get GenParticles collection const reco::GenParticleCollection& genParticles = *genH; unsigned int i=0; for(const auto& p : genParticles) { i++; // Get visible P4 of genParticle math::XYZTLorentzVector p4vis = GetVisP4(p); if (abs(p.pdgId()) != pId) continue; if (fabs(p4vis.Eta()) > cfg_genEtaVisCutoff) continue; if (p4vis.Et() < cfg_genEtVisThreshold) continue; // Get the daughters of the genParticle const reco::GenParticleRefVector& daughters = p.daughterRefVector(); // Determine if it's a last copy bool bDecaysToSelf = false; for (const auto& d : daughters) { if (abs(d->pdgId()) == pId) { bDecaysToSelf = true; break; } } if (bDecaysToSelf) continue; // Determine if it's a hadronic decay bool bLeptonicDecay = false; for (const auto& d : daughters) { if (isLepton(d->pdgId())) { bLeptonicDecay = true; break; } } if (bLeptonicDecay) continue; // If it is a last copy and it is a hadronic decay keep it indices.push_back(i); etVis.push_back(p4vis.Et()); et.push_back(p.et()); eta.push_back(p.eta()); phi.push_back(p.phi()); // Fill histos etVisGenL1Obj->Fill(p4vis.Et()); etGenL1Obj->Fill(p.et()); etaGenL1Obj->Fill(p.eta()); phiGenL1Obj->Fill(p.phi()); } return indices; } math::XYZTLorentzVector L1TausAnalyzer::GetVisP4(reco::GenParticle p) { math::XYZTLorentzVector p4vis; std::vector<unsigned int> nuIds; nuIds.push_back(12); // nu_e nuIds.push_back(14); // nu_mu nuIds.push_back(16); // nu_tau // Get the daughters of the genParticle const reco::GenParticleRefVector& daughters = p.daughterRefVector(); for (const auto& d : daughters) { // Skip if it's a neutrino if ( std::find(nuIds.begin(), nuIds.end(), abs(d->pdgId()) ) != nuIds.end() ) continue; p4vis += d->p4(); } return p4vis; } bool L1TausAnalyzer::isLepton(unsigned int pdgId) { bool islepton = false; // Check if the genParticle is e,mu or their neutrinos if ((fabs(pdgId) == 11) || (fabs(pdgId) == 12) || (fabs(pdgId) == 13) || (fabs(pdgId) == 14)) { islepton = true; } return islepton; } //define this as a plug-in DEFINE_FWK_MODULE(L1TausAnalyzer);
32.644013
216
0.660801
[ "object", "vector" ]
d79aacc578e029676d271c71e05cf10924bbca95
2,429
hpp
C++
test/test_utils/scheduling.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/test_utils/scheduling.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/test_utils/scheduling.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) // // 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) //======================================================================= /** * @file scheduling.hpp * @brief * @author Robert Rosolek * @version 1.0 * @date 2013-11-19 */ #ifndef PAAL_SCHEDULING_HPP #define PAAL_SCHEDULING_HPP #include "test_utils/logger.hpp" #include "paal/utils/type_functions.hpp" #include "paal/utils/assign_updates.hpp" #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm/max_element.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/test/unit_test.hpp> #include <boost/functional/hash.hpp> #include <unordered_map> #include <utility> #include <vector> template <class Machines, class Time, class GetSpeed> std::vector<long long> generate_job_loads(Machines machines, double minJobsOnMachine, Time time, GetSpeed getSpeed) { std::vector<long long> loads; for (auto const machine : machines) { for (Time left = time; left > 0;) { Time jobTime = rand() % ((long long)(time / minJobsOnMachine)); paal::assign_min(jobTime, left); loads.push_back(jobTime * getSpeed(machine)); left -= jobTime; } } return loads; } template <class Result, class Job> void check_jobs(Result result, std::vector<Job> jobs) { std::vector<Job> gotJobs; for (auto const &it : result) { gotJobs.push_back(*it.second); } boost::sort(gotJobs); boost::sort(jobs); BOOST_CHECK(jobs == gotJobs); } template <class Result, class GetSpeed> double get_max_time(const Result &result, GetSpeed getSpeed) { typedef typename paal::range_to_elem_t<Result>::first_type MachineIter; typedef typename std::iterator_traits<MachineIter>::value_type Machine; std::unordered_map<Machine, double, boost::hash<Machine>> machineTime; for (auto const &machineJobPair : result) { Machine machine = *machineJobPair.first; auto load = *machineJobPair.second; machineTime[machine] += double(load) / getSpeed(machine); } return *boost::max_element(machineTime | boost::adaptors::map_values); } #endif // PAAL_SCHEDULING_HPP
32.824324
77
0.631536
[ "vector" ]
d79baa582c1019d75e4195dbc74a6613f1e7b5f9
1,596
hpp
C++
modules/arm_plugin/src/arm_plugin.hpp
embedded-dev-research/openvino_contrib
fe1f48588812677719d81bf0f778a9d01f811f93
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/arm_plugin.hpp
embedded-dev-research/openvino_contrib
fe1f48588812677719d81bf0f778a9d01f811f93
[ "Apache-2.0" ]
null
null
null
modules/arm_plugin/src/arm_plugin.hpp
embedded-dev-research/openvino_contrib
fe1f48588812677719d81bf0f778a9d01f811f93
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <string> #include <map> #include <unordered_map> #include <vector> #include <cpp/ie_cnn_network.h> #include <cpp_interfaces/interface/ie_iplugin_internal.hpp> #include "arm_executable_network.hpp" #include "arm_config.hpp" namespace ArmPlugin { struct Plugin : public InferenceEngine::IInferencePlugin { using Ptr = std::shared_ptr<Plugin>; Plugin(); ~Plugin(); void SetConfig(const std::map<std::string, std::string>& config) override; InferenceEngine::QueryNetworkResult QueryNetwork(const InferenceEngine::CNNNetwork& network, const std::map<std::string, std::string>& config) const override; InferenceEngine::IExecutableNetworkInternal::Ptr LoadExeNetworkImpl(const InferenceEngine::CNNNetwork& network, const std::map<std::string, std::string>& config) override; InferenceEngine::Parameter GetConfig(const std::string& name, const std::map<std::string, InferenceEngine::Parameter>& options) const override; InferenceEngine::Parameter GetMetric(const std::string& name, const std::map<std::string, InferenceEngine::Parameter> & options) const override; std::shared_ptr<ngraph::Function> Transform(const std::shared_ptr<const ngraph::Function>& function, const Configuration& config) const; Configuration _cfg; }; } // namespace ArmPlugin
37.116279
123
0.676692
[ "vector", "transform" ]
d79c916ce01ee2afd0af2abac248b6c2ac7624ce
3,109
hpp
C++
old/error_states.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
old/error_states.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
old/error_states.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
namespace actan { namespace error_states { const size_t LE_NL = 0; const size_t LE_NA = 1; const size_t LE_CS = 2; struct ErrorCodeACTAN { int error_type; std::string description; std::string getErrorString(int64_t timestamp, std::string extra_args="", size_t nl=LE_NL) { std::string error_string = std::to_string(timestamp) + "," + std::to_string(this->error_type) + "," + this->description + extra_args; if (nl == LE_NL) { error_string += "\n"; } if (nl == LE_CS) { error_string += ","; } return error_string; } }; ErrorCodeACTAN FUBAR = {-1,"Mr. Stark I don't feel so good."}; ErrorCodeACTAN NOMINAL = {0,"All systems nominal"}; ErrorCodeACTAN SUSPECTED_MID_MISSION_RESTART = {1,"Possible mid mission restart detected. Will evaluate more closely when first gps string is obtained."}; ErrorCodeACTAN CONFIRMED_MID_MISSION_RESTART = {2,"Mid mission restart confirmed. Will load polynomial physics model coefficients from latest log."}; ErrorCodeACTAN DATA_IO_STARTUP = {3,"Starting up data input and output threads."}; ErrorCodeACTAN DATA_INPUT_STARTING_UP = {2345,"Starting all data input threads."}; ErrorCodeACTAN DATA_INPUT_STARTUP = {4,"Started all data input threads."}; ErrorCodeACTAN DATA_OUTPUT_STARTING_UP = {3456,"Starting all data output threads."}; ErrorCodeACTAN DATA_OUTPUT_STARTUP = {5,"Started all data output threads."}; ErrorCodeACTAN OPERATING_LOOP_STARTUP = {6,"Started main operating loop."}; ErrorCodeACTAN INPUT_DATA_DUMP = {7,"Creating log for input data."}; ErrorCodeACTAN OUTPUT_DATA_DUMP = {8,"Creating log for output data."}; ErrorCodeACTAN OPERATING_LOOP_DATA_DUMP = {9,"Creating log for operating loop data."}; ErrorCodeACTAN ACTAN_STARTUP_SUCCESSFUL = {10,"Successfully opened all threads required to run ACTAN."}; ErrorCodeACTAN DATA_INPUT_TERMINATED = {11,"Terminated data input."}; ErrorCodeACTAN DATA_INPUT_THREADS_TERMINATED = {111,"Terminated data input threads."}; ErrorCodeACTAN DATA_OUTPUT_TERMINATED = {12,"Terminated data output."}; ErrorCodeACTAN OPERATING_LOOP_TERMINATED = {13,"Terminated operating loop."}; ErrorCodeACTAN TERMINATING_DATA_OUTPUT_LOOP = {14,"Terminating data output loop."}; ErrorCodeACTAN TERMINATING_DATA_INPUT_LOOP = {15,"Terminating data input loop."}; ErrorCodeACTAN TERMINATING_DATA_INPUT_THREADS = {151, "Terminating data input threads."}; ErrorCodeACTAN TERMINATING_OPERATING_LOOP = {16,"Terminating operating loop."}; ErrorCodeACTAN ACTAN_TERMINATED = {23061912,"I have done what I can. Terminating ACTAN."}; ErrorCodeACTAN NO_SAFE_OPS_LOG = {17,"No safe operations logging file was found. I will make one."}; } }
53.603448
162
0.649405
[ "model" ]
d79d69ea6da8960c71c1b12ce89b5cbd9fcde299
931
cpp
C++
Sources/Material.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
Sources/Material.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
Sources/Material.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Material.h" Material Material::createMirror(Vector specular_color) { Material m = Material(); m._mirror = true; m._specular_color = specular_color; return m; } Material Material::createTransparent(Vector specular_color, double n_object) { Material m = Material(); m._transparent = true; m._specular_color = specular_color; m._n_object = n_object; return m; } Material Material::createEmissive(Vector color, double emissivity) { Material m = Material(); m._color = color; m._emissive = true; m._emissivity = emissivity; return m; } Material Material::createDiffuse(Vector color) { Material m = Material(); m._color = color; return m; } Material Material::createPhong(Vector color, Vector specular_color, double phong_exponent) { Material m = Material(); m._color = color; m._specular_color = specular_color; m._phong = true; m._phong_exponent = phong_exponent; return m; }
19.808511
90
0.741139
[ "vector" ]
d79df492b5c89241cf5bd6c5e796b61aa6ce5d77
13,454
cpp
C++
Visual Mercutio/zModel/PSS_ProcessModelTreeView.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModel/PSS_ProcessModelTreeView.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModel/PSS_ProcessModelTreeView.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_ProcessModelTreeView --------------------------------------------* **************************************************************************** * Description : Provides a process model tree view * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_ProcessModelTreeView.h" // processsoft #include "zBaseLib\PSS_DropView.h" #include "zBaseLib\PSS_TreeCtrl.h" #include "PSS_Symbol.h" #include "PSS_LinkSymbol.h" #include "PSS_ProcessGraphPage.h" #include "PSS_ModelObserverMsg.h" // resources #ifdef _DEBUG #include "zFormsRes\zFormsRes.h" #endif #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Dynamic creation //--------------------------------------------------------------------------- IMPLEMENT_DYNCREATE(PSS_ProcessModelTreeView, PSS_TreeView) //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_ProcessModelTreeView, PSS_TreeView) //{{AFX_MSG_MAP(PSS_ProcessModelTreeView) ON_WM_LBUTTONDBLCLK() ON_WM_RBUTTONDBLCLK() ON_WM_RBUTTONUP() ON_WM_CONTEXTMENU() ON_COMMAND(ID_MBRS_EDIT_NAME, OnModelBrowserEditName) ON_COMMAND(ID_MBRS_GOIN_SYMBOL, OnModelBrowserGoInSymbol) ON_COMMAND(ID_MBRS_EDIT_CUT, OnModelBrowserEditCut) ON_COMMAND(ID_MBRS_EDIT_COPY, OnModelBrowserEditCopy) ON_COMMAND(ID_MBRS_EDIT_CLEAR, OnModelBrowserEditClear) ON_COMMAND(ID_MBRS_OD_PROPERTIES, OnModelBrowserProperties) ON_COMMAND(ID_MBRS_SELECT_SYMBOL, OnModelBrowserSelectSymbol) ON_COMMAND(ID_MBRS_BROWSE_SOURCESYMBOL, OnModelBrowserBrowseSourceSymbol) ON_COMMAND(ID_MBRS_INSERT_MODELPAGE, OnInsertModelPage) ON_COMMAND(ID_MBRS_RENAME_MODELPAGE, OnRenameModelPage) ON_COMMAND(ID_MBRS_DELETE_MODELPAGE, OnDeleteModelPage) ON_COMMAND(ID_REFRESH, OnRefresh) ON_COMMAND(ID_COLLAPSE_BRANCH, OnCollapseBranch) ON_COMMAND(ID_EXPAND_BRANCH, OnExpandBranch) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_ProcessModelTreeView //--------------------------------------------------------------------------- PSS_ProcessModelTreeView::PSS_ProcessModelTreeView() : PSS_TreeView(), m_pModelSet(NULL), m_pPopupSubMenu(NULL), m_EnableMenuItems(false) {} //--------------------------------------------------------------------------- PSS_ProcessModelTreeView::~PSS_ProcessModelTreeView() {} //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::Initialize(const CString& modelName, PSS_ModelSet* pModelSet, UINT imageResID, PSS_RuntimeClassSet* pSet, bool enableMenuItems) { m_pModelSet = pModelSet; m_EnableMenuItems = enableMenuItems; // enable drag and drop ((PSS_TreeCtrl*)&GetTreeCtrl())->DisableDragDrop(false); // initialize the worker class m_ModelTree.Initialize((PSS_TreeCtrl*)&GetTreeCtrl(), modelName, m_pModelSet, imageResID, pSet); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::Refresh() { m_ModelTree.Refresh(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::Empty() { m_ModelTree.Empty(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::AddModel(PSS_ProcessGraphModelMdl* pModel) { m_ModelTree.AddModel(pModel); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::RemoveModel(PSS_ProcessGraphModelMdl* pModel) { m_ModelTree.RemoveModel(pModel); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::AddModelSet(PSS_ModelSet* pModelSet) { m_ModelTree.AddModelSet(pModelSet); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::RemoveModelSet(PSS_ModelSet* pModelSet) { m_ModelTree.RemoveModelSet(pModelSet); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::AddSymbol(CODSymbolComponent* pSymbol, PSS_ProcessGraphModelMdl* pModel, bool checkUnique) { m_ModelTree.AddSymbol(pSymbol, pModel, checkUnique); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::RemoveSymbol(CODSymbolComponent* pSymbol, PSS_ProcessGraphModelMdl* pModel) { m_ModelTree.RemoveSymbol(pSymbol, pModel); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::ModifySymbol(CODSymbolComponent* pSymbol, PSS_ProcessGraphModelMdl* pModel) { m_ModelTree.ModifySymbol(pSymbol, pModel); } //--------------------------------------------------------------------------- int PSS_ProcessModelTreeView::HasContextMenu(CWnd* pWnd, const CPoint& point) { CPoint pt(point); ScreenToClient(&pt); UINT flags; HTREEITEM hItem = ((PSS_TreeCtrl*)&GetTreeCtrl())->HitTest(pt, &flags); int idMenu = -1; // show the right sub-menu if (hItem && (TVHT_ONITEM & flags)) { CODSymbolComponent* pComp = m_ModelTree.GetSymbol(hItem); PSS_Symbol* pSymbol = dynamic_cast<PSS_Symbol*>(pComp); PSS_LinkSymbol* pLinkSymbol = pSymbol ? NULL : dynamic_cast<PSS_LinkSymbol*>(pComp); if (pSymbol || pLinkSymbol) { if (pSymbol) idMenu = pSymbol->GetRightSubMenu(); else idMenu = pLinkSymbol->GetRightSubMenu(); } else if (m_ModelTree.GetPage(hItem)) idMenu = 0; } return idMenu; } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::ShowContextMenu(CWnd* pWnd, const CPoint& point) { const int idMenu = HasContextMenu(pWnd, point); if (idMenu == -1) return; CPoint pt(point); ScreenToClient(&pt); // test the hit UINT flags; HTREEITEM hItem = ((PSS_TreeCtrl*)&GetTreeCtrl())->HitTest(pt, &flags); if (hItem && (TVHT_ONITEM & flags)) { ((PSS_TreeCtrl*)&GetTreeCtrl())->Select(hItem, TVGN_CARET); // check if local or referenced symbol bool local = true; CODSymbolComponent* pComp = m_ModelTree.GetSymbol(hItem); PSS_Symbol* pSymbol = dynamic_cast<PSS_Symbol*>(pComp); PSS_LinkSymbol* pLinkSymbol = pSymbol ? NULL : dynamic_cast<PSS_LinkSymbol*>(pComp); if (pSymbol) local = pSymbol->IsLocal(); else if (pLinkSymbol) local = pLinkSymbol->IsLocal(); CMenu* pPopup = NULL; if (local) pPopup = m_SymbolPopupMainMenu.GetSubMenu(idMenu); else pPopup = m_SymbolRefPopupMainMenu.GetSubMenu(idMenu); PSS_Assert(pPopup); CWnd* pWndPopupOwner = this; while (pWndPopupOwner->GetStyle() & WS_CHILD) pWndPopupOwner = pWndPopupOwner->GetParent(); // if needed to enable all menu items if (m_EnableMenuItems) { UINT count = pPopup->GetMenuItemCount(); for (UINT i = 0; i < count; ++i) pPopup->EnableMenuItem(i, MF_BYPOSITION | MF_ENABLED); } pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, m_EnableMenuItems ? this : pWndPopupOwner); } } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnDraw(CDC* pDC) {} //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnLButtonDblClk(UINT nFlags, CPoint point) { // browse the symbol OnDoubleClick(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnRButtonDblClk(UINT nFlags, CPoint point) { PSS_TreeView::OnRButtonDblClk(nFlags, point); // browse the symbol OnDoubleClick(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnRButtonUp(UINT nFlags, CPoint point) { PSS_TreeView::OnRButtonUp(nFlags, point); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnContextMenu(CWnd* pWnd, CPoint point) { ShowContextMenu(pWnd, point); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserEditName() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_EDIT_NAME); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserGoInSymbol() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_GOIN_SYMBOL); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserEditCut() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_EDIT_CUT); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserEditCopy() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_EDIT_COPY); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserEditClear() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_EDIT_CLEAR); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserProperties() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_OD_PROPERTIES); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserBrowseSourceSymbol() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_BROWSE_SOURCESYMBOL); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnModelBrowserSelectSymbol() { m_ModelTree.DoSelectSymbol(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnInsertModelPage() { CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_INSERT_MODELPAGE); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnRenameModelPage() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_RENAME_CURRENTMODELPAGE); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnDeleteModelPage() { m_ModelTree.DoSelectSymbol(); CWnd* pWnd = ::AfxGetMainWnd(); if (pWnd) pWnd->SendMessage(WM_COMMAND, ID_DELETE_CURRENTMODELPAGE); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnRefresh() { m_ModelTree.Refresh(); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnCollapseBranch() { CollapseBranch(((PSS_TreeCtrl*)&GetTreeCtrl())->GetSelectedItem(), TRUE); } //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnExpandBranch() { ExpandBranch(((PSS_TreeCtrl*)&GetTreeCtrl())->GetSelectedItem(), TRUE); } //--------------------------------------------------------------------------- #ifdef _DEBUG void PSS_ProcessModelTreeView::AssertValid() const { PSS_TreeView::AssertValid(); } #endif //--------------------------------------------------------------------------- #ifdef _DEBUG void PSS_ProcessModelTreeView::Dump(CDumpContext& dc) const { PSS_TreeView::Dump(dc); } #endif //--------------------------------------------------------------------------- void PSS_ProcessModelTreeView::OnDoubleClick() { m_ModelTree.OnDoubleClick(); } //---------------------------------------------------------------------------
34.675258
121
0.501338
[ "model" ]
d7a4a2abfa603f434710804543f606c5e04952c6
1,059
cpp
C++
articulation point.cpp
amitXsarkar/ProgrammingHub
2c860effb55da1ec303a96224751692a52d3dbfd
[ "MIT" ]
null
null
null
articulation point.cpp
amitXsarkar/ProgrammingHub
2c860effb55da1ec303a96224751692a52d3dbfd
[ "MIT" ]
null
null
null
articulation point.cpp
amitXsarkar/ProgrammingHub
2c860effb55da1ec303a96224751692a52d3dbfd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; vector<ll> adj[10001]; ll low[10001],disc[10001],child[10001],cnt; bool vis[10001]; void dfs(ll node,ll tim,ll par) { ll i,j,k,flag=0; //cout<<node<<" "; vis[node]=true; disc[node]=tim; low[node]=tim; for(i=0;i<adj[node].size();i++) { ll x=adj[node][i]; if(!vis[x]) { vis[x]=true; child[node]++; dfs(x,tim+1,node); low[node]=min(low[node],low[x]); if(node==par&&child[node]>1) flag=1; if(node!=par&&low[x]>=disc[node]) { flag=1; } } else if(x!=par){ low[node]=min(low[node],disc[x]); } } //cout<<node<<"-"<<flag<<endl; cnt=cnt+flag; } int main() { // your code goes here ll n,m; cin>>n>>m; while(n) { ll u,v,i,j,k; for(i=0;i<m;i++) { cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } cnt=0; dfs(1,0,1); cout<<cnt<<endl; for(i=0;i<=n;i++) { vis[i]=false; adj[i].clear(); child[i]=0; } cin>>n>>m; } return 0; }
16.292308
44
0.501416
[ "vector" ]
d7a4a90ea6e60b76fb5e12e968aaf356452ac7b9
949
hpp
C++
lib/world/city.hpp
julienlopez/QCityBuilder
fe61a56bcdeda301211d49a9e358258eefafa14c
[ "MIT" ]
1
2019-03-19T03:14:22.000Z
2019-03-19T03:14:22.000Z
lib/world/city.hpp
julienlopez/QCityBuilder
fe61a56bcdeda301211d49a9e358258eefafa14c
[ "MIT" ]
11
2015-01-27T17:35:12.000Z
2018-08-13T07:48:35.000Z
lib/world/city.hpp
julienlopez/QCityBuilder
fe61a56bcdeda301211d49a9e358258eefafa14c
[ "MIT" ]
null
null
null
#ifndef CITY_HPP #define CITY_HPP #include "building.hpp" #include "map.hpp" #include "villager.hpp" #include <string> class InventorySummary; BEGIN_NAMESPACE_WORLD class City { public: using container_building = std::vector<Building>; using VillagerContainer_t = std::vector<Villager>; City(std::string name_, utils::SizeU size_); ~City() = default; void add(Building b); const Map& map() const; const std::string& name() const; const container_building& buildings() const; const VillagerContainer_t& villagers() const; void addRoad(Map::square_container_t squares); bool isAreaFreeToBuild(const utils::RectU& area) const; InventorySummary totalInventory() const; bool isOutOfBound(const utils::RectU& area) const; private: std::string m_name; Map m_map; container_building m_buildings; VillagerContainer_t m_villagers; }; END_NAMESPACE_WORLD #endif // CITY_HPP
18.607843
59
0.718651
[ "vector" ]
d7a64e662119c8b0e6e33994ee68d40b49960023
22,918
cc
C++
tools/click-mkmindriver/click-mkmindriver.cc
kkovacs/fastclick
59a9a26cc0026305d44d9bb50a5e8ea4b12f79b6
[ "BSD-3-Clause-Clear" ]
null
null
null
tools/click-mkmindriver/click-mkmindriver.cc
kkovacs/fastclick
59a9a26cc0026305d44d9bb50a5e8ea4b12f79b6
[ "BSD-3-Clause-Clear" ]
null
null
null
tools/click-mkmindriver/click-mkmindriver.cc
kkovacs/fastclick
59a9a26cc0026305d44d9bb50a5e8ea4b12f79b6
[ "BSD-3-Clause-Clear" ]
null
null
null
// -*- c-basic-offset: 4 -*- /* * click-mkmindriver.cc -- produce a minimum Click driver Makefile setup * Eddie Kohler * * Copyright (c) 2001 Massachusetts Institute of Technology * Copyright (c) 2001 International Computer Science Institute * Copyright (c) 2004-2011 Regents of the University of California * Copyright (c) 2013 President and Fellows of Harvard College * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/pathvars.h> #include <click/error.hh> #include <click/confparse.hh> #include <click/straccum.hh> #include <click/archive.hh> #include <click/driver.hh> #include "lexert.hh" #include "routert.hh" #include "toolutils.hh" #include "elementmap.hh" #include <click/clp.h> #include <stdio.h> #include <ctype.h> #include <time.h> #define HELP_OPT 300 #define VERSION_OPT 301 #define CLICKPATH_OPT 302 #define ROUTER_OPT 303 #define EXPRESSION_OPT 304 #define PACKAGE_OPT 306 #define DIRECTORY_OPT 307 #define KERNEL_OPT 308 #define USERLEVEL_OPT 309 #define ELEMENT_OPT 310 #define ALIGN_OPT 311 #define ALL_OPT 312 #define CHECK_OPT 313 #define VERBOSE_OPT 314 #define EXTRAS_OPT 315 #define EMBED_OPT 316 static const Clp_Option options[] = { { "align", 'A', ALIGN_OPT, 0, 0 }, { "all", 'a', ALL_OPT, 0, Clp_Negate }, { "check", 0, CHECK_OPT, 0, Clp_Negate }, { "clickpath", 'C', CLICKPATH_OPT, Clp_ValString, 0 }, { "directory", 'd', DIRECTORY_OPT, Clp_ValString, 0 }, { "elements", 'E', ELEMENT_OPT, Clp_ValString, 0 }, { "expression", 'e', EXPRESSION_OPT, Clp_ValString, 0 }, { "extras", 0, EXTRAS_OPT, 0, Clp_Negate }, { "file", 'f', ROUTER_OPT, Clp_ValString, 0 }, { "help", 0, HELP_OPT, 0, 0 }, { "ship", 0, EMBED_OPT, 0, 0 }, { "kernel", 'k', KERNEL_OPT, 0, 0 }, // DEPRECATED { "linuxmodule", 'l', KERNEL_OPT, 0, 0 }, { "package", 'p', PACKAGE_OPT, Clp_ValString, 0 }, { "userlevel", 'u', USERLEVEL_OPT, 0, 0 }, { "verbose", 'V', VERBOSE_OPT, 0, Clp_Negate } }; static const char *program_name; static int driver = -1; static String subpackage; static HashTable<String, int> initial_requirements(-1); static bool verbose = false; static bool embed_package = false; static String* click_compile_prog = 0; void short_usage() { fprintf(stderr, "Usage: %s -p PKGNAME [OPTION]... [ROUTERFILE]...\n\ Try '%s --help' for more information.\n", program_name, program_name); } void usage() { printf("\ 'Click-mkmindriver' generates a build environment for a minimal Click driver,\n\ which contains just the elements required to support one or more\n\ configurations. Run 'click-mkmindriver' in the relevant driver's build\n\ directory and supply a package name with the '-p PKG' option. Running\n\ 'make MINDRIVER=PKG' will build a 'PKGclick' user-level driver or 'PKGclick.ko'\n\ kernel module.\n\ \n\ Usage: %s -p PKG [-lu] [OPTION]... [ROUTERFILE]...\n\ \n\ Options:\n\ -p, --package PKG Name of package is PKG.\n\ -f, --file FILE Read a router configuration from FILE.\n\ -e, --expression EXPR Use EXPR as a router configuration.\n\ -a, --all Add all element classes from following configs,\n\ even those in unused compound elements.\n\ -l, --linuxmodule Build Makefile for Linux kernel module driver.\n\ -u, --userlevel Build Makefile for user-level driver (default).\n\ -d, --directory DIR Put files in DIR. DIR must contain a 'Makefile'\n\ for the relevant driver. Default is '.'.\n\ -E, --elements ELTS Include element classes ELTS.\n\ --no-extras Don't include surplus often-useful elements.\n\ -s, --ship Ship source given in package archives in the binary.\n\ -V, --verbose Print progress information.\n\ -C, --clickpath PATH Use PATH for CLICKPATH.\n\ --help Print this message and exit.\n\ -v, --version Print version number and exit.\n\ \n\ Report bugs to <click@librelist.com>.\n", program_name); } class Mindriver { public: Mindriver(); void provide(const String&, ErrorHandler*); void require(const String&, ErrorHandler*); void add_source_file(const String&, ErrorHandler*); void add_router_requirements(RouterT*, ElementMap&, ErrorHandler*); bool add_traits(const Traits&, const ElementMap&, ErrorHandler*); bool resolve_requirement(const String& requirement, const ElementMap& emap, ErrorHandler* errh, bool complain = true); int click_compile_file(String source, String obj, String package, ErrorHandler* errh); void print_elements_conf(FILE*, String package, const ElementMap&, const String &top_srcdir, ErrorHandler* errh); HashTable<String, int> _provisions; HashTable<String, int> _requirements; HashTable<String, int> _source_files; int _nrequirements; }; Mindriver::Mindriver() : _provisions(-1), _requirements(-1), _source_files(-1), _nrequirements(0) { } void Mindriver::provide(const String& req, ErrorHandler* errh) { if (verbose && _provisions[req] < 0) errh->message("providing %<%s%>", req.c_str()); _provisions[req] = 1; } void Mindriver::require(const String& req, ErrorHandler* errh) { if (_provisions.get(req) < 0) { if (verbose && _requirements[req] < 0) errh->message("requiring %<%s%>", req.c_str()); _requirements[req] = 1; _nrequirements++; } } void Mindriver::add_source_file(const String& fn, ErrorHandler* errh) { if (verbose && _source_files[fn] < 0) errh->message("adding source file %<%s%>", fn.c_str()); _source_files[fn] = 1; } void Mindriver::add_router_requirements(RouterT* router, ElementMap& emap, ErrorHandler* errh) { // find and parse elementmap emap.parse_requirement_files(router, CLICK_DATADIR, errh, verbose); // check whether suitable for driver if (!emap.driver_compatible(router, driver)) { errh->error("not compatible with %s driver; ignored", Driver::name(driver)); return; } emap.set_driver(driver); StringAccum missing_sa; int nmissing = 0; HashTable<ElementClassT*, int> primitives(-1); router->collect_types(primitives); for (HashTable<ElementClassT*, int>::iterator i = primitives.begin(); i.live(); i++) { if (!i.key()->primitive()) continue; String tname = i.key()->name(); if (!emap.has_traits(tname)) missing_sa << (nmissing++ ? ", " : "") << tname; else require(tname, errh); } if (nmissing == 1) errh->fatal("cannot locate required element class %<%s%>\n(This may be due to a missing or out-of-date %<elementmap.xml%>.)", missing_sa.c_str()); else if (nmissing > 1) errh->fatal("cannot locate these required element classes:\n %s\n(This may be due to a missing or out-of-date %<elementmap.xml%>.)", missing_sa.c_str()); } static void handle_router(Mindriver& md, String filename_in, ElementMap &emap, ErrorHandler *errh) { // decide if 'filename' should be flattened bool flattenable = (filename_in[0] != 'a'); bool file_is_expr = (filename_in[1] == 'e'); const char *filename = filename_in.c_str() + 2; // read file int before = errh->nerrors(); RouterT *router = read_router(filename, file_is_expr, errh); if (file_is_expr) filename = "config"; else if (!filename || strcmp(filename, "-") == 0) filename = "<stdin>"; LandmarkErrorHandler lerrh(errh, filename); if (router && flattenable) router->flatten(&lerrh); if (router && errh->nerrors() == before) md.add_router_requirements(router, emap, &lerrh); delete router; } bool Mindriver::add_traits(const Traits& t, const ElementMap&, ErrorHandler* errh) { if (t.source_file) add_source_file(t.source_file, errh); if (t.name) provide(t.name, errh); if (t.provisions) { Vector<String> args; cp_spacevec(t.provisions, args); for (String* s = args.begin(); s < args.end(); s++) if (Driver::driver(*s) < 0) provide(*s, errh); } if (t.requirements) { Vector<String> args; cp_spacevec(t.requirements, args); for (String* s = args.begin(); s < args.end(); s++) require(*s, errh); } return true; } bool Mindriver::resolve_requirement(const String& requirement, const ElementMap& emap, ErrorHandler* errh, bool complain) { LandmarkErrorHandler lerrh(errh, "resolving " + requirement); if (_provisions.get(requirement) > 0) return true; int try_name_emapi = emap.traits_index(requirement); if (try_name_emapi > 0) { add_traits(emap.traits_at(try_name_emapi), emap, &lerrh); return true; } if (requirement.starts_with("!")) { String nr = requirement.substring(1); for (int i = 1; i < emap.size(); i++) { if (emap.traits_at(i).provides(nr)) { if (complain) errh->error("cannot requirement %<%s%> as it is providen", requirement.c_str()); return false; } } return true; } for (int i = 1; i < emap.size(); i++) { if (emap.traits_at(i).provides(requirement)) { add_traits(emap.traits_at(i), emap, &lerrh); return true; } } // check for '|' requirements const char *begin = requirement.begin(), *bar; while ((bar = find(begin, requirement.end(), '|')) < requirement.end()) { if (resolve_requirement(requirement.substring(begin, bar), emap, errh, false)) return true; begin = bar + 1; } do_complain: if (complain) errh->error("cannot satisfy requirement %<%s%>", requirement.c_str()); return false; } int Mindriver::click_compile_file(String source, String obj, String package, ErrorHandler* errh) { // find compile program if (!click_compile_prog) click_compile_prog = new String(clickpath_find_file("click-compile", "bin", CLICK_BINDIR, errh)); if (!*click_compile_prog) return -1; ContextErrorHandler cerrh (errh, "While compiling dependency %<%s%>:", obj.c_str()); // prepare click-compile StringAccum compile_command; compile_command << *click_compile_prog << " -t " << Driver::name(driver) << " -p " << package << " --objs -c " << source << " -o " << obj; // finish compile_command if (verbose) errh->message("%s", compile_command.c_str()); int compile_retval = system(compile_command.c_str()); if (compile_retval == 127) return cerrh.error("could not run %<%s%>", compile_command.c_str()); else if (compile_retval < 0) return cerrh.error("could not run %<%s%>: %s", compile_command.c_str(), strerror(errno)); else if (compile_retval != 0) return cerrh.error("%<%s%> failed", compile_command.c_str()); else return 0; } void Mindriver::print_elements_conf(FILE *f, String package, const ElementMap &emap, const String &top_srcdir,ErrorHandler* errh) { Vector<String> sourcevec; for (HashTable<String, int>::iterator iter = _source_files.begin(); iter.live(); iter++) { iter.value() = sourcevec.size(); sourcevec.push_back(iter.key()); } Vector<String> headervec(sourcevec.size(), String()); Vector<String> compilevec(sourcevec.size(), String()); Vector<String> classvec(sourcevec.size(), String()); HashTable<String, int> statichash(0); // collect header file and C++ element class definitions from emap for (int i = 1; i < emap.size(); i++) { const Traits &elt = emap.traits_at(i); int sourcei = _source_files.get(elt.source_file); if (sourcei >= 0) { if (emap.package(elt) != subpackage) { if (embed_package) { compilevec[sourcei] = emap.archive(elt); } else continue; } // track ELEMENT_LIBS // ah, if only I had regular expressions if (!headervec[sourcei] && elt.libs) { StringAccum sa; sa << " -!lib"; for (const char *x = elt.libs.begin(); x != elt.libs.end(); x++) if (isspace((unsigned char) *x)) { sa << ';'; skipspace: while (x + 1 != elt.libs.end() && isspace((unsigned char) x[1])) x++; } else if (x + 1 != elt.libs.end() && *x == '-' && x[1] == 'L') { sa << '-' << 'L'; x++; goto skipspace; } else sa << *x; classvec[sourcei] += sa.take_string(); } // remember header file headervec[sourcei] = elt.header_file; // remember name if (elt.name && !elt.noexport) { // Avoid adding duplicate elements String tmp_elem = " " + elt.cxx + "-" + elt.name; int found = classvec[sourcei].find_left(tmp_elem,0); if(found >= 0) { printf("Found duplicate element! %s at %d\n", tmp_elem.c_str(), found); continue; } classvec[sourcei] += tmp_elem; } // remember static methods if (elt.methods && !statichash[elt.cxx]) { statichash[elt.cxx] = 1; Vector<String> ms; cp_spacevec(elt.methods, ms); for (String *m = ms.begin(); m != ms.end(); m++) if (*m == "static_initialize") classvec[sourcei] += " " + elt.cxx + "-!si"; else if (*m == "static_cleanup") classvec[sourcei] += " " + elt.cxx + "-!sc"; } } } // output data time_t now = time(0); char date_str[256]; strftime(date_str, sizeof(date_str), "%c\n" , localtime(&now)); fprintf(f, "# Generated by 'click-mkmindriver -p %s' on %s", package.c_str(), date_str); for (int i = 0; i < sourcevec.size(); i++) { if (headervec[i]) { String classstr(classvec[i].begin() + 1, classvec[i].end()); if (compilevec[i]) { String source = sourcevec[i]; String obj = source.substring(0,source.find_right('.')) + ".o"; String s = file_string(compilevec[i], errh); Vector<ArchiveElement> ar; ArchiveElement::parse(s, ar); ArchiveElement::extract(ar, source, source, errh); String header = headervec[i]; ArchiveElement::extract(ar, header, header, errh); click_compile_file(source,obj,package,errh); fprintf(f, "%s\t\"%s\"\t%s\n", obj.c_str(), header.c_str(), classstr.c_str()); } else { if (headervec[i][0] != '\"' && headervec[i][0] != '<') fprintf(f, "%s%s\t\"%s%s\"\t%s\n", top_srcdir.c_str(), sourcevec[i].c_str(), top_srcdir.c_str(), headervec[i].c_str(), classstr.c_str()); else fprintf(f, "%s%s\t%s\t%s\n", top_srcdir.c_str(), sourcevec[i].c_str(), headervec[i].c_str(), classstr.c_str()); } } } } static String analyze_makefile(const String &directory, ErrorHandler *errh) { int before = errh->nerrors(); String fn = directory + "Makefile"; String text = file_string(fn, errh); if (before != errh->nerrors()) return String(); // What kind of driver is this? int allowed_drivers = 0; int pos; if ((pos = text.find_left("\npackage := ")) >= 0) { int endpos = text.find_left('\n', pos + 1); subpackage = text.substring(pos + 12, endpos - (pos + 12)); if (text.find_left("\nMAKE_UPACKAGE = 1\n") >= 0) allowed_drivers |= 1 << Driver::USERLEVEL; if (text.find_left("\nMAKE_KPACKAGE = 1\n") >= 0) allowed_drivers |= 1 << Driver::LINUXMODULE; } else { subpackage = String(); if (text.find_left("\n## Click userlevel driver Makefile ##\n") >= 0) allowed_drivers |= 1 << Driver::USERLEVEL; if (text.find_left("\n## Click linuxmodule driver Makefile ##\n") >= 0) allowed_drivers |= 1 << Driver::LINUXMODULE; } if (allowed_drivers == 0) { errh->error("%s unrecognized as Click Makefile", fn.c_str()); return String(); } if (driver < 0) driver = (allowed_drivers & (1 << Driver::USERLEVEL) ? Driver::USERLEVEL : Driver::LINUXMODULE); if (!(allowed_drivers & (1 << driver))) { errh->error("%s does not support %s driver", fn.c_str(), Driver::name(driver)); return String(); } if ((pos = text.find_left("\ntop_srcdir := ")) < 0) { errh->error("%s lacks top_srcdir variable", fn.c_str()); return String(); } int endpos = text.find_left('\n', pos + 1); String top_srcdir = text.substring(pos + 15, endpos - (pos + 15)); if (top_srcdir.back() != '/') top_srcdir += '/'; return top_srcdir; } int main(int argc, char **argv) { click_static_initialize(); CLICK_DEFAULT_PROVIDES; ErrorHandler *errh = ErrorHandler::default_handler(); LandmarkErrorHandler arg_lerrh(errh, "argument requirements"); // read command line arguments Clp_Parser *clp = Clp_NewParser(argc, argv, sizeof(options) / sizeof(options[0]), options); Clp_SetOptionChar(clp, '+', Clp_ShortNegated); program_name = Clp_ProgramName(clp); Vector<String> router_filenames; String specifier = "x"; const char *package_name = 0; String directory; bool check = true; bool extras = true; Mindriver md; while (1) { int opt = Clp_Next(clp); switch (opt) { case HELP_OPT: usage(); exit(0); break; case VERSION_OPT: printf("click-mkmindriver (Click) %s\n", CLICK_VERSION); printf("Copyright (c) 2001 Massachusetts Institute of Technology\n\ Copyright (c) 2001 International Computer Science Institute\n\ Copyright (c) 2004-2011 Regents of the University of California\n\ This is free software; see the source for copying conditions.\n\ There is NO warranty, not even for merchantability or fitness for a\n\ particular purpose.\n"); exit(0); break; case CLICKPATH_OPT: set_clickpath(clp->vstr); break; case KERNEL_OPT: driver = Driver::LINUXMODULE; break; case USERLEVEL_OPT: driver = Driver::USERLEVEL; break; case PACKAGE_OPT: package_name = clp->vstr; break; case DIRECTORY_OPT: directory = clp->vstr; if (directory.length() && directory.back() != '/') directory += "/"; break; case ALL_OPT: specifier = (clp->negated ? "x" : "a"); break; case CHECK_OPT: check = !clp->negated; break; case ELEMENT_OPT: { Vector<String> elements; cp_spacevec(clp->vstr, elements); for (String *e = elements.begin(); e < elements.end(); e++) md.require(*e, &arg_lerrh); break; } case ALIGN_OPT: break; case EMBED_OPT: embed_package = !clp->negated; break; case EXTRAS_OPT: extras = !clp->negated; break; case VERBOSE_OPT: verbose = !clp->negated; break; case ROUTER_OPT: router_file: router_filenames.push_back(specifier + String("f") + clp->vstr); break; case Clp_NotOption: if (!click_maybe_define(clp->vstr, &arg_lerrh)) goto router_file; break; case EXPRESSION_OPT: router_filenames.push_back(specifier + String("e") + clp->vstr); break; case Clp_BadOption: short_usage(); exit(1); break; case Clp_Done: goto done; } } done: if (!package_name) errh->fatal("fatal error: no package name specified\nPlease supply the %<-p PKG%> option."); String top_srcdir = analyze_makefile(directory, (check ? errh : ErrorHandler::silent_handler())); if (extras && !subpackage) { md.require("Align", errh); md.require("IPNameInfo", errh); } ElementMap default_emap; if (!default_emap.parse_default_file(CLICK_DATADIR, errh, verbose)) default_emap.report_file_not_found(CLICK_DATADIR, false, errh); if (subpackage) default_emap.parse_package_file(subpackage, 0, CLICK_DATADIR, errh, verbose); for (int i = 0; i < router_filenames.size(); i++) handle_router(md, router_filenames[i], default_emap, errh); if (md._nrequirements == 0) errh->fatal("no elements required"); // add types that are always required if (!subpackage) { LandmarkErrorHandler lerrh(errh, "default requirements"); md.require("AddressInfo", &lerrh); md.require("AlignmentInfo", &lerrh); md.require("Error", &lerrh); md.require("PortInfo", &lerrh); md.require("ScheduleInfo", &lerrh); if (driver == Driver::USERLEVEL) md.require("ControlSocket", &lerrh); } // add initial provisions default_emap.set_driver(driver); md.provide(Driver::requirement(driver), errh); // all default provisions are stored in elementmap index 0 md.add_traits(default_emap.traits_at(0), default_emap, errh); // now, loop over requirements until closure while (1) { HashTable<String, int> old_reqs(-1); old_reqs.swap(md._requirements); for (HashTable<String, int>::iterator iter = old_reqs.begin(); iter.live(); iter++) md.resolve_requirement(iter.key(), default_emap, errh); if (!md._requirements.size()) break; } if (errh->nerrors() > 0) exit(1); // Print elements_PKG.conf if (errh->nerrors() == 0) { String fn = directory; if (subpackage && driver == Driver::USERLEVEL) fn += String(package_name) + "-uelem.conf"; else if (subpackage && driver == Driver::LINUXMODULE) fn += String(package_name) + "-kelem.conf"; else fn += String("elements_") + package_name + ".conf"; errh->message("Creating %s...", fn.c_str()); FILE *f = fopen(fn.c_str(), "w"); if (!f) errh->fatal("%s: %s", fn.c_str(), strerror(errno)); md.print_elements_conf(f, package_name, default_emap, top_srcdir, errh); fclose(f); } // Final message if (errh->nerrors() == 0) { if (subpackage && driver == Driver::USERLEVEL) errh->message("Build %<%s.uo%> with %<make MINDRIVER=%s%>.", package_name, package_name); else if (subpackage && driver == Driver::LINUXMODULE) errh->message("Build %<%s.ko%> with %<make MINDRIVER=%s%>.", package_name, package_name); else if (driver == Driver::USERLEVEL) errh->message("Build %<%sclick%> with %<make %sclick MINDRIVER=%s%>.\nYou should also add STATIC=1 if you use --static pass from click-devirtualize.", package_name, package_name, package_name); else errh->message("Build %<%sclick.ko%> with %<make MINDRIVER=%s%>.", package_name, package_name); return 0; } else exit(1); }
32.278873
155
0.630247
[ "vector" ]
d7a76d2b54cd6380769ecaba659ef319647bf378
2,598
cpp
C++
2016 Multi-University Training Contest 3/D.cpp
PrayStarJirachi/Reshiram
6475fe37f105cdd5382e4f621050128250603acb
[ "MIT" ]
null
null
null
2016 Multi-University Training Contest 3/D.cpp
PrayStarJirachi/Reshiram
6475fe37f105cdd5382e4f621050128250603acb
[ "MIT" ]
null
null
null
2016 Multi-University Training Contest 3/D.cpp
PrayStarJirachi/Reshiram
6475fe37f105cdd5382e4f621050128250603acb
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> const int MAXE = 911; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, 1, -1}; int T, n, m, a[MAXE][MAXE], id[MAXE][MAXE], x[MAXE], map[MAXE][MAXE]; int main() { freopen("D.in", "r", stdin); scanf("%d", &T); for (int cs = 1; cs <= T; cs++) { int n, m, tot = 0; scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) id[i][j] = ++tot; for (int i = 1; i <= tot; i++) for (int j = 1; j <= tot + 1; j++) a[i][j] = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[id[i][j]][tot + 1]); map[i][j] = a[id[i][j]][tot + 1]; a[id[i][j]][tot + 1] = (3 - a[id[i][j]][tot + 1]) % 3; a[id[i][j]][id[i][j]] = (a[id[i][j]][id[i][j]] + 2) % 3; for (int d = 0; d < 4; d++) { int nx = i + dx[d], ny = j + dy[d]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m) { a[id[i][j]][id[nx][ny]]++; } } } for (int h = 1; h <= tot; h++) { if (a[h][h] == 0) { for (int i = h + 1; i <= tot; i++) if (a[i][h] != 0) { for (int j = h; j <= tot + 1; j++) { std::swap(a[i][j], a[h][j]); } break; } } if (a[h][h] == 0) continue; for (int i = h + 1; i <= tot; i++) { if (a[i][h] == 0) continue; int t = a[i][h] * a[h][h] % 3; for (int j = h; j <= tot + 1; j++) { a[i][j] = (a[i][j] - a[h][j] * t) % 3; if (a[i][j] < 0) a[i][j] += 3; } } } /*for (int i = 1; i <= tot; i++) { for (int j = 1; j <= tot; j++) printf("%d ", a[i][j]); printf(" | %d\n", a[i][tot + 1]); }*/ for (int h = tot; h >= 1; h--) { x[h] = a[h][tot + 1]; for (int i = h + 1; i <= tot; i++) { x[h] = (x[h] - a[h][i] * x[i]) % 3; } x[h] = (x[h] * a[h][h]) % 3; x[h] = (x[h] % 3 + 3) % 3; } std::vector<std::pair<int, int> > answer; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) for (int k = 1; k <= x[id[i][j]]; k++) { answer.push_back(std::make_pair(i, j)); } printf("%d\n", (int)answer.size()); for (int i = 0; i < (int)answer.size(); i++) { printf("%d %d\n", answer[i].first, answer[i].second); /*map[answer[i].first][answer[i].second] = (map[answer[i].first][answer[i].second] + 2) % 3; for (int d = 0; d < 4; d++) { int nx = answer[i].first + dx[d]; int ny = answer[i].second + dy[d]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m) { map[nx][ny] = (map[nx][ny] + 1) % 3; } }*/ } /*for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) printf("%d%c", map[i][j], " \n"[j == m]);*/ } }
28.549451
95
0.383372
[ "vector" ]
92e2811e191aa2c13ad5fdf735276f7d2d6f2deb
2,400
cpp
C++
test/local_search/facility_location/facility_location_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/local_search/facility_location/facility_location_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/local_search/facility_location/facility_location_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) // // 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 "test_utils/sample_graph.hpp" #include "test_utils/logger.hpp" #include "paal/local_search/facility_location/facility_location.hpp" #include "paal/local_search/custom_components.hpp" #include "paal/utils/functors.hpp" #include <boost/test/unit_test.hpp> using namespace paal::local_search; BOOST_AUTO_TEST_CASE(FacilityLocationTest) { typedef sample_graphs_metrics SGM; auto gm = SGM::get_graph_metric_small(); std::vector<int> fcosts{ 7, 8 }; auto cost = paal::utils::make_array_to_functor(fcosts); typedef paal::data_structures::voronoi<decltype(gm)> VorType; typedef paal::data_structures::facility_location_solution<decltype(cost), VorType> Sol; typedef typename VorType::GeneratorsSet FSet; VorType voronoi(FSet{}, FSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm); Sol sol(std::move(voronoi), FSet{ SGM::A, SGM::B }, cost); default_remove_fl_components rem; default_add_fl_components add; default_swap_fl_components swap; paal::utils::always_true nop; // this search can and in one or 2 rounds depending on // implementation of unordered_set in facility_location_solution // if the first facility to add is A, then the search will be finished // in one round. The 2 round are needed otherwise stop_condition_count_limit oneRoundSearch(2); ON_LOG(auto const &ch = sol.get_chosen_facilities()); LOGLN("Solution before the first search"); LOG_COPY_RANGE_DEL(ch, ","); LOGLN(""); BOOST_CHECK(facility_location_local_search( sol, first_improving_strategy{}, nop, oneRoundSearch, rem, add, swap)); LOGLN("Solution after the first search"); LOG_COPY_RANGE_DEL(ch, ","); LOGLN(""); BOOST_CHECK(!facility_location_first_improving(sol, rem, add, swap)); //best improving strategy BOOST_CHECK(!facility_location_local_search(sol, best_improving_strategy{}, paal::utils::always_true{}, paal::utils::always_false{}, rem, add, swap)); }
40
80
0.654583
[ "vector" ]
92e8db239d01916c648f2f6d0a51e8fc89e38195
5,280
cpp
C++
examples/ml/Configuration.cpp
jcarreira/cirrus-kv
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
8
2018-07-18T22:13:36.000Z
2021-08-24T12:28:42.000Z
examples/ml/Configuration.cpp
jcarreira/ddc
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
7
2016-11-22T11:07:14.000Z
2016-12-17T22:49:23.000Z
examples/ml/Configuration.cpp
jcarreira/ddc
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
null
null
null
#include <examples/ml/Configuration.h> #include <fstream> #include <iostream> #include <sstream> #include <utils/Log.h> Configuration::Configuration() : learning_rate(-1), epsilon(-1) {} /** * Read configuration from a specific config file * @param path Path to the configuration file */ void Configuration::read(const std::string& path) { std::ifstream fin(path.c_str(), std::ifstream::in); if (!fin) { throw std::runtime_error("Error opening config file: " + path); } std::string line; while (getline(fin, line)) { parse_line(line); } print(); } void Configuration::print() const { std::cout << "Printing configuration: " << std::endl; std::cout << "input_path: " << get_input_path() << std::endl; std::cout << "Minibatch size: " << get_minibatch_size() << std::endl; std::cout << "learning rate: " << get_learning_rate() << std::endl; std::cout << "num_samples: " << get_num_samples() << std::endl; } /** * Parse a specific line in the config file * @param line A line from the input file */ void Configuration::parse_line(const std::string& line) { std::istringstream iss(line); std::string s; iss >> s; std::cout << "Parsing line: " << line << std::endl; if (s == "minibatch_size:") { iss >> minibatch_size; } else if (s == "input_path:") { iss >> input_path; } else if (s == "samples_path:") { iss >> samples_path; } else if (s == "labels_path:") { iss >> labels_path; } else if (s == "n_workers:") { iss >> n_workers; } else if (s == "prefetching:") { iss >> prefetching; } else if (s == "epsilon:") { iss >> epsilon; } else if (s == "input_type:") { iss >> input_type; } else if (s == "learning_rate:") { iss >> learning_rate; } else if (s == "num_classes:") { iss >> num_classes; } else if (s == "limit_cols:") { iss >> limit_cols; } else if (s == "num_samples:") { iss >> num_samples; } else if (s == "normalize:") { int n; iss >> n; normalize = (n == 1); } else if (s == "model_type:") { std::string model; iss >> model; if (model == "LogisticRegression") { model_type = LOGISTICREGRESSION; } else if (model == "Softmax") { model_type = SOFTMAX; } else { throw std::runtime_error(std::string("Unknown model : ") + model); } } else { throw std::runtime_error("Unrecognized option: " + line); } if (iss.fail()) { throw std::runtime_error("Error parsing configuration file"); } } std::string Configuration::get_input_path() const { if (input_path == "") throw std::runtime_error("input path not loaded"); return input_path; } std::string Configuration::get_samples_path() const { if (samples_path == "") throw std::runtime_error("samples path not loaded"); if (input_type != "double_binary") throw std::runtime_error("mismatch between paths and input type"); return samples_path; } std::string Configuration::get_labels_path() const { if (labels_path == "") throw std::runtime_error("labels path not loaded"); if (input_type != "double_binary") throw std::runtime_error("mismatch between paths and input type"); return labels_path; } double Configuration::get_learning_rate() const { if (learning_rate == -1) throw std::runtime_error("learning rate not loaded"); return learning_rate; } double Configuration::get_epsilon() const { if (epsilon == -1) throw std::runtime_error("epsilon not loaded"); return epsilon; } uint64_t Configuration::get_minibatch_size() const { if (minibatch_size == 0) throw std::runtime_error("Minibatch size not loaded"); return minibatch_size; } int Configuration::get_prefetching() const { if (prefetching == -1) throw std::runtime_error("prefetching not loaded"); return prefetching; } std::string Configuration::get_input_type() const { if (input_type == "") throw std::runtime_error("input_type not loaded"); return input_type; } /** * Get the format of the input dataset from the config file */ Configuration::ModelType Configuration::get_model_type() const { if (model_type == UNKNOWN) { throw std::runtime_error("model_type not loaded"); } return model_type; } /** * Get the number of classes we use in this workload/dataset/algorithm */ uint64_t Configuration::get_num_classes() const { if (num_classes == 0) { throw std::runtime_error("num_classes not loaded"); } return num_classes; } /** * Get the maximum number of features/columns to read from each sample */ uint64_t Configuration::get_limit_cols() const { if (limit_cols == 0) { cirrus::LOG<cirrus::INFO>("limit_cols not loaded"); } return limit_cols; } /** * Get the flag saying whether the dataset should be normalized or not */ bool Configuration::get_normalize() const { return normalize; } /** * Get number of training input samples */ uint64_t Configuration::get_num_samples() const { return num_samples; }
27.076923
78
0.6125
[ "model" ]
92ed4d34499916f40c1b889e3854cf4c8bf39e79
3,717
cpp
C++
workspace/VariantUsage/src/Test.cpp
PeterSommerlad/workshopworkspace
5e5eb9c42280a4aba27ee196d3003fd54a5e3607
[ "MIT" ]
2
2021-08-28T11:43:58.000Z
2021-09-07T08:10:05.000Z
workspace/VariantUsage/src/Test.cpp
PeterSommerlad/workshopworkspace
5e5eb9c42280a4aba27ee196d3003fd54a5e3607
[ "MIT" ]
null
null
null
workspace/VariantUsage/src/Test.cpp
PeterSommerlad/workshopworkspace
5e5eb9c42280a4aba27ee196d3003fd54a5e3607
[ "MIT" ]
null
null
null
#include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include "pssst.h" #include <sstream> #include <string> #include <variant> enum class errorcode { ok, failed_input }; std::variant<std::string, errorcode> inputName(std::istream & in) { std::string name{}; if (in >> name) return name; return errorcode::failed_input; } void failing_input() { std::istringstream input{}; auto const res = inputName(input); ASSERT_EQUAL(1,res.index()); ASSERT_EQUAL(errorcode::failed_input, std::get<errorcode>(res)); ASSERT_THROWS(std::get<0>(res),std::bad_variant_access); } void successful_input() { std::istringstream input{"Peter"}; auto const res = inputName(input); ASSERT_EQUAL(0,res.index()); ASSERT_EQUAL("Peter", std::get<std::string>(res)); ASSERT_THROWS(std::get<errorcode>(res),std::bad_variant_access); } // now for polymorphism variant namespace polyvariant { using namespace pssst; struct Width: strong<int,Width>, Out<Width>{}; struct Height: strong<int,Height>, Out<Height>{}; struct Radius: strong<int,Radius>, Out<Radius>{}; using screen=std::ostream; struct rect{ rect(Width w, Height h): width{w},height{h}{} Width width; Height height; }; void draw(rect const &r, screen& on){ on << "rectangle:" << r.width << "," << r.height; } struct circle{ circle(Radius r): radius{r}{} Radius radius; }; void draw(circle const &c, screen& on){ on << "circle:" << c.radius; } void draw(char const *const &s,screen&os){ os << "string:"<< s; } void draw(int i,screen &os){ // make ints a special case os << "an_int:"<<i; } struct composite; using widget = std::variant<rect,circle,composite,int,char const *>; using widgets=std::vector<widget>; // helper for visitor, did not make it into C++17 template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; void draw(widget const &w,screen & on); struct composite{ void add(widget w){ content.emplace_back(std::move(w)); } friend void draw(composite const &c, screen &on){ on << "{ "; for(widget const &drawable : c.content){ draw(drawable,on); on << ','; } on << " }"; } private: widgets content{}; }; void draw(widget const &w,screen & on){ visit(overloaded{ [&on](int const &i){ draw(i,on);}, [&on](char const *s){ draw(s,on);}, [&on](rect const &r){ draw(r,on);}, [&on](circle const &c){ draw(c,on);}, [&on](composite const &co){ draw(co,on);} },w); } void testRect(){ std::ostringstream out{}; widget r{rect{Width{2},Height{4}}}; draw(r,out); ASSERT_EQUAL("rectangle:2,4",out.str()); } void testCircle(){ std::ostringstream out{}; widget c{circle{Radius{4}}}; draw(c,out); ASSERT_EQUAL("circle:4",out.str()); } void testComposite(){ std::ostringstream out{}; composite c{}; c.add(circle(Radius{42})); c.add(rect(Width{4},Height{2})); c.add(circle(Radius{4})); c.add(42); c.add("a c string"); widget w{c}; draw(w,out); ASSERT_EQUAL("{ circle:42,rectangle:4,2,circle:4,an_int:42,string:a c string, }",out.str()); } } bool runAllTests(int argc, char const *argv[]) { cute::suite s { }; //TODO add your test here s.push_back(CUTE(failing_input)); s.push_back(CUTE(successful_input)); s.push_back(CUTE(polyvariant::testRect)); s.push_back(CUTE(polyvariant::testCircle)); s.push_back(CUTE(polyvariant::testComposite)); cute::xml_file_opener xmlfile(argc, argv); cute::xml_listener<cute::ide_listener<>> lis(xmlfile.out); auto runner = cute::makeRunner(lis, argc, argv); bool success = runner(s, "AllTests"); return success; } int main(int argc, char const *argv[]) { return runAllTests(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE; }
23.826923
93
0.670702
[ "vector" ]
92ee20554ffdf7f782ef0a376e6263f3e19afd72
3,466
hpp
C++
CSGOSimple/valve_sdk/misc/datamap.hpp
Tyler-Admin/CSGOSimple
99a659a1368ed9445b9ccf8ec4514d25d9bf81d6
[ "MIT" ]
400
2018-10-30T14:52:13.000Z
2022-03-29T11:46:24.000Z
CSGOSimple/valve_sdk/misc/datamap.hpp
Tyler-Admin/CSGOSimple
99a659a1368ed9445b9ccf8ec4514d25d9bf81d6
[ "MIT" ]
126
2018-12-03T15:54:57.000Z
2022-03-23T17:11:53.000Z
CSGOSimple/valve_sdk/misc/datamap.hpp
alerion921/krilu92-csgo
aa18bff83ff48b2c9c52655424db39a9b9655e86
[ "MIT" ]
316
2018-11-09T22:38:38.000Z
2022-03-25T13:35:09.000Z
#pragma once #include <iostream> struct inputdata_t; typedef enum _fieldtypes { FIELD_VOID = 0, // No type or value FIELD_FLOAT, // Any floating point value FIELD_STRING, // A string ID (return from ALLOC_STRING) FIELD_VECTOR, // Any vector, QAngle, or AngularImpulse FIELD_QUATERNION, // A quaternion FIELD_INTEGER, // Any integer or enum FIELD_BOOLEAN, // boolean, implemented as an int, I may use this as a hint for compression FIELD_SHORT, // 2 byte integer FIELD_CHARACTER, // a byte FIELD_COLOR32, // 8-bit per channel r,g,b,a (32bit color) FIELD_EMBEDDED, // an embedded object with a datadesc, recursively traverse and embedded class/structure based on an additional typedescription FIELD_CUSTOM, // special type that contains function pointers to it's read/write/parse functions FIELD_CLASSPTR, // CBaseEntity * FIELD_EHANDLE, // Entity handle FIELD_EDICT, // edict_t * FIELD_POSITION_VECTOR, // A world coordinate (these are fixed up across level transitions automagically) FIELD_TIME, // a floating point time (these are fixed up automatically too!) FIELD_TICK, // an integer tick count( fixed up similarly to time) FIELD_MODELNAME, // Engine string that is a model name (needs precache) FIELD_SOUNDNAME, // Engine string that is a sound name (needs precache) FIELD_INPUT, // a list of inputed data fields (all derived from CMultiInputVar) FIELD_FUNCTION, // A class function pointer (Think, Use, etc) FIELD_VMATRIX, // a vmatrix (output coords are NOT worldspace) // NOTE: Use float arrays for local transformations that don't need to be fixed up. FIELD_VMATRIX_WORLDSPACE,// A VMatrix that maps some local space to world space (translation is fixed up on level transitions) FIELD_MATRIX3X4_WORLDSPACE, // matrix3x4_t that maps some local space to world space (translation is fixed up on level transitions) FIELD_INTERVAL, // a start and range floating point interval ( e.g., 3.2->3.6 == 3.2 and 0.4 ) FIELD_MODELINDEX, // a model index FIELD_MATERIALINDEX, // a material index (using the material precache string table) FIELD_VECTOR2D, // 2 floats FIELD_TYPECOUNT, // MUST BE LAST } fieldtype_t; class ISaveRestoreOps; class C_BaseEntity; // // Function prototype for all input handlers. // typedef void (C_BaseEntity::*inputfunc_t)(inputdata_t &data); struct datamap_t; struct typedescription_t; enum { TD_OFFSET_NORMAL = 0, TD_OFFSET_PACKED = 1, // Must be last TD_OFFSET_COUNT, }; struct typedescription_t { int32_t fieldType; //0x0000 char* fieldName; //0x0004 int fieldOffset[TD_OFFSET_COUNT]; //0x0008 int16_t fieldSize_UNKNWN; //0x0010 int16_t flags_UNKWN; //0x0012 char pad_0014[12]; //0x0014 datamap_t* td; //0x0020 char pad_0024[24]; //0x0024 }; //Size: 0x003C //----------------------------------------------------------------------------- // Purpose: stores the list of objects in the hierarchy // used to iterate through an object's data descriptions //----------------------------------------------------------------------------- struct datamap_t { typedescription_t *dataDesc; int dataNumFields; char const *dataClassName; datamap_t *baseMap; bool chains_validated; // Have the "packed" offsets been computed bool packed_offsets_computed; int packed_size; };
36.484211
146
0.680323
[ "object", "vector", "model" ]
92f0733f640e937ec157f7e009494ad8a3f5c39e
16,817
cc
C++
google/cloud/servicemanagement/internal/service_manager_connection_impl.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/servicemanagement/internal/service_manager_connection_impl.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/servicemanagement/internal/service_manager_connection_impl.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/api/servicemanagement/v1/servicemanager.proto #include "google/cloud/servicemanagement/internal/service_manager_connection_impl.h" #include "google/cloud/servicemanagement/internal/service_manager_option_defaults.h" #include "google/cloud/background_threads.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/async_long_running_operation.h" #include "google/cloud/internal/pagination_range.h" #include "google/cloud/internal/retry_loop.h" #include <memory> namespace google { namespace cloud { namespace servicemanagement_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( std::unique_ptr<google::cloud::BackgroundThreads> background, std::shared_ptr<servicemanagement_internal::ServiceManagerStub> stub, Options options) : background_(std::move(background)), stub_(std::move(stub)), options_(internal::MergeOptions( std::move(options), servicemanagement_internal::ServiceManagerDefaultOptions( ServiceManagerConnection::options()))) {} StreamRange<google::api::servicemanagement::v1::ManagedService> ServiceManagerConnectionImpl::ListServices( google::api::servicemanagement::v1::ListServicesRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<servicemanagement::ServiceManagerRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListServices(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::api::servicemanagement::v1::ManagedService>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::api::servicemanagement::v1::ListServicesRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub]( grpc::ClientContext& context, google::api::servicemanagement::v1::ListServicesRequest const& request) { return stub->ListServices(context, request); }, r, function_name); }, [](google::api::servicemanagement::v1::ListServicesResponse r) { std::vector<google::api::servicemanagement::v1::ManagedService> result( r.services().size()); auto& messages = *r.mutable_services(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StatusOr<google::api::servicemanagement::v1::ManagedService> ServiceManagerConnectionImpl::GetService( google::api::servicemanagement::v1::GetServiceRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetService(request), [this](grpc::ClientContext& context, google::api::servicemanagement::v1::GetServiceRequest const& request) { return stub_->GetService(context, request); }, request, __func__); } future<StatusOr<google::api::servicemanagement::v1::ManagedService>> ServiceManagerConnectionImpl::CreateService( google::api::servicemanagement::v1::CreateServiceRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::api::servicemanagement::v1::ManagedService>( background_->cq(), request, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::api::servicemanagement::v1::CreateServiceRequest const& request) { return stub->AsyncCreateService(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::api::servicemanagement::v1::ManagedService>, retry_policy(), backoff_policy(), idempotency_policy()->CreateService(request), polling_policy(), __func__); } future<StatusOr<google::api::servicemanagement::v1::OperationMetadata>> ServiceManagerConnectionImpl::DeleteService( google::api::servicemanagement::v1::DeleteServiceRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::api::servicemanagement::v1::OperationMetadata>( background_->cq(), request, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::api::servicemanagement::v1::DeleteServiceRequest const& request) { return stub->AsyncDeleteService(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultMetadata< google::api::servicemanagement::v1::OperationMetadata>, retry_policy(), backoff_policy(), idempotency_policy()->DeleteService(request), polling_policy(), __func__); } future<StatusOr<google::api::servicemanagement::v1::UndeleteServiceResponse>> ServiceManagerConnectionImpl::UndeleteService( google::api::servicemanagement::v1::UndeleteServiceRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::api::servicemanagement::v1::UndeleteServiceResponse>( background_->cq(), request, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::api::servicemanagement::v1::UndeleteServiceRequest const& request) { return stub->AsyncUndeleteService(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::api::servicemanagement::v1::UndeleteServiceResponse>, retry_policy(), backoff_policy(), idempotency_policy()->UndeleteService(request), polling_policy(), __func__); } StreamRange<google::api::Service> ServiceManagerConnectionImpl::ListServiceConfigs( google::api::servicemanagement::v1::ListServiceConfigsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<servicemanagement::ServiceManagerRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListServiceConfigs(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::api::Service>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::api::servicemanagement::v1::ListServiceConfigsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::api::servicemanagement::v1:: ListServiceConfigsRequest const& request) { return stub->ListServiceConfigs(context, request); }, r, function_name); }, [](google::api::servicemanagement::v1::ListServiceConfigsResponse r) { std::vector<google::api::Service> result(r.service_configs().size()); auto& messages = *r.mutable_service_configs(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StatusOr<google::api::Service> ServiceManagerConnectionImpl::GetServiceConfig( google::api::servicemanagement::v1::GetServiceConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetServiceConfig(request), [this](grpc::ClientContext& context, google::api::servicemanagement::v1::GetServiceConfigRequest const& request) { return stub_->GetServiceConfig(context, request); }, request, __func__); } StatusOr<google::api::Service> ServiceManagerConnectionImpl::CreateServiceConfig( google::api::servicemanagement::v1::CreateServiceConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->CreateServiceConfig(request), [this]( grpc::ClientContext& context, google::api::servicemanagement::v1::CreateServiceConfigRequest const& request) { return stub_->CreateServiceConfig(context, request); }, request, __func__); } future<StatusOr<google::api::servicemanagement::v1::SubmitConfigSourceResponse>> ServiceManagerConnectionImpl::SubmitConfigSource( google::api::servicemanagement::v1::SubmitConfigSourceRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::api::servicemanagement::v1::SubmitConfigSourceResponse>( background_->cq(), request, [stub]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::api::servicemanagement::v1::SubmitConfigSourceRequest const& request) { return stub->AsyncSubmitConfigSource(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::api::servicemanagement::v1::SubmitConfigSourceResponse>, retry_policy(), backoff_policy(), idempotency_policy()->SubmitConfigSource(request), polling_policy(), __func__); } StreamRange<google::api::servicemanagement::v1::Rollout> ServiceManagerConnectionImpl::ListServiceRollouts( google::api::servicemanagement::v1::ListServiceRolloutsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<servicemanagement::ServiceManagerRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListServiceRollouts(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::api::servicemanagement::v1::Rollout>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::api::servicemanagement::v1::ListServiceRolloutsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::api::servicemanagement::v1:: ListServiceRolloutsRequest const& request) { return stub->ListServiceRollouts(context, request); }, r, function_name); }, [](google::api::servicemanagement::v1::ListServiceRolloutsResponse r) { std::vector<google::api::servicemanagement::v1::Rollout> result( r.rollouts().size()); auto& messages = *r.mutable_rollouts(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StatusOr<google::api::servicemanagement::v1::Rollout> ServiceManagerConnectionImpl::GetServiceRollout( google::api::servicemanagement::v1::GetServiceRolloutRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetServiceRollout(request), [this](grpc::ClientContext& context, google::api::servicemanagement::v1::GetServiceRolloutRequest const& request) { return stub_->GetServiceRollout(context, request); }, request, __func__); } future<StatusOr<google::api::servicemanagement::v1::Rollout>> ServiceManagerConnectionImpl::CreateServiceRollout( google::api::servicemanagement::v1::CreateServiceRolloutRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::api::servicemanagement::v1::Rollout>( background_->cq(), request, [stub]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::api::servicemanagement::v1::CreateServiceRolloutRequest const& request) { return stub->AsyncCreateServiceRollout(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::api::servicemanagement::v1::Rollout>, retry_policy(), backoff_policy(), idempotency_policy()->CreateServiceRollout(request), polling_policy(), __func__); } StatusOr<google::api::servicemanagement::v1::GenerateConfigReportResponse> ServiceManagerConnectionImpl::GenerateConfigReport( google::api::servicemanagement::v1::GenerateConfigReportRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GenerateConfigReport(request), [this]( grpc::ClientContext& context, google::api::servicemanagement::v1::GenerateConfigReportRequest const& request) { return stub_->GenerateConfigReport(context, request); }, request, __func__); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace servicemanagement_internal } // namespace cloud } // namespace google
45.206989
84
0.688113
[ "vector" ]
1303ff300e5b55ef73a3fd1d2d7be95ebb7b2481
27,821
cpp
C++
tools/onnx2bnn/OnnxConverter.cpp
qaz734913414/dabnn
27b88a48a1d8da3b15e5296356418ebb0b515f1f
[ "Apache-2.0" ]
null
null
null
tools/onnx2bnn/OnnxConverter.cpp
qaz734913414/dabnn
27b88a48a1d8da3b15e5296356418ebb0b515f1f
[ "Apache-2.0" ]
null
null
null
tools/onnx2bnn/OnnxConverter.cpp
qaz734913414/dabnn
27b88a48a1d8da3b15e5296356418ebb0b515f1f
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 JD.com Inc. JD AI #include "OnnxConverter.h" #include <bitset> #include <fstream> #include <map> #include <memory> #include <numeric> #include <string> #include <vector> #include <common/Shaper.h> #include <common/StrKeyMap.h> #include <common/common_bitpack.h> #include <common/flatbuffers_helper.h> #include <common/helper.h> #include <common/macros.h> #include <glog/logging.h> #include <onnx/onnx_pb.h> #include <onnx/optimizer/optimize.h> #include "NodeAttrHelper.h" namespace bnn { using std::string; using std::unique_ptr; using std::vector; using Shape = Shaper::Shape; std::string OnnxConverter::m(const std::string &str) { if (name_map_.find(str) != name_map_.end()) { return name_map_[str]; } return str; } void OnnxConverter::AddBinConv(const std::string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const std::string &weight_name, const std::string &output_name, BTensor bin_weight) { BNN_ASSERT(group == 1, "Group != 1 is not supported"); const auto param = flatbnn::CreateBinConv2DDirect( builder_, input_name.c_str(), weight_name.c_str(), nullptr, &pads, &strides, &dilations, output_name.c_str()); const auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::BinConv2D, 0, param); const auto flat_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Bit, &bin_weight.data, nullptr, &bin_weight.shape, weight_name.c_str(), bin_weight.align_hwc_to_128); tensors_.push_back(flat_tensor); layers_.push_back(layer); } void OnnxConverter::AddFloatConv( const string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const string &weight_name, const nonstd::optional<std::string> &bias_name, const string &output_name, FTensor float_weight) { flatbuffers::Offset<flatbnn::Layer> layer; flatbuffers::Offset<flatbnn::Tensor> flat_tensor; if (group != 1) { // TODO: Support it throw std::invalid_argument("group != 1 is not supported"); } bnn_tensors_[weight_name] = float_weight; auto param = flatbnn::CreateFpConv2DDirect( builder_, input_name.c_str(), weight_name.c_str(), bias_name ? bias_name.value().c_str() : nullptr, &pads, &strides, &dilations, output_name.c_str()); layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::FpConv2D, param); flat_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &float_weight.data, &float_weight.shape, weight_name.c_str()); tensors_.push_back(flat_tensor); layers_.push_back(layer); } void OnnxConverter::AddConv(const string &input_name, const std::vector<int> &strides, const std::vector<int> &pads, const std::vector<int> &dilations, int group, const string &ori_weight_name, const nonstd::optional<std::string> &bias_name, const string &output_name, const bool binary) { flatbuffers::Offset<flatbnn::Layer> layer; flatbuffers::Offset<flatbnn::Tensor> flat_tensor; const auto &onnx_weight = onnx_float_tensors_.at(ori_weight_name); FTensor bnn_float_tensor = OnnxToBnn(onnx_weight); string weight_name = ori_weight_name + "_conv_w"; shaper_.AddShape(weight_name, bnn_float_tensor.shape); shaper_.Conv(input_name, strides[1], strides[0], 1, 1, pads[2], pads[3], pads[0], pads[1], weight_name, output_name); if (binary) { VLOG(5) << "Binary conv" + weight_name; BTensor weight_tensor = bitpack(bnn_float_tensor); AddBinConv(input_name, strides, pads, dilations, group, weight_name, output_name, weight_tensor); } else { AddFloatConv(input_name, strides, pads, dilations, group, weight_name, bias_name, output_name, bnn_float_tensor); } } /* * Bitpack a bnn tensor, input_channels should be the last dimension * The data size of the packed tensor may be different from * Shaper::total(tensor.shape) / 64, since every HWC will be padded * so that they are aligned to 128. */ OnnxConverter::BTensor OnnxConverter::bitpack(OnnxConverter::FTensor ftensor) { static_assert(std::is_same<bin_t, uint64_t>::value, "bitpack requires bin_t is 64 bit"); const auto N = Shaper::kn(ftensor.shape); const auto C = Shaper::kc(ftensor.shape); const auto HWC = Shaper::total(ftensor.shape) / N; vector<bin_t> packed_data; bin_t tmp; Shape shape = {ftensor.shape[0], ftensor.shape[1], ftensor.shape[2], ftensor.shape[3]}; bool align_hwc_to_128 = (C != 64); if (align_hwc_to_128) { FORZ(n, N) { FORZS(i, HWC, 128) { const size_t eff_bits = std::min<size_t>(HWC - i, 128); pack_64_bitset(&ftensor.data[n * HWC + i], &tmp, std::min<size_t>(eff_bits, 64)); packed_data.push_back(tmp); pack_64_bitset( &ftensor.data[n * HWC + i + 64], &tmp, std::min<size_t>(std::max<size_t>(0, eff_bits - 64), 64)); packed_data.push_back(tmp); } } } else { FORZS(i, Shaper::total(ftensor.shape), 64) { pack_64_bitset(&ftensor.data[i], &tmp); packed_data.push_back(tmp); } } return {packed_data, shape, align_hwc_to_128}; } std::vector<OnnxConverter::BTensor> OnnxConverter::split( OnnxConverter::BTensor input, int num) { std::vector<BTensor> outputs; const auto shape = input.get_shape_for_accessing_element(); BNN_ASSERT(Shaper::kn(shape) % num == 0, ""); const auto n_per_group = Shaper::kn(shape) / num; FORZ(i, num) { BTensor tensor; FORZ(n, n_per_group) { FORZ(h, Shaper::kh(shape)) { FORZ(w, Shaper::kw(shape)) { FORZ(c, Shaper::kc(shape)) { const auto &tmp = input.get({i * n_per_group + n, h, w, c}); tensor.data.push_back(tmp); } } } } tensor.shape = input.shape; tensor.shape[0] = n_per_group; outputs.push_back(tensor); } return outputs; } std::vector<std::string> OnnxConverter::Convert( const ONNX_NAMESPACE::ModelProto &model_proto, const std::string &filepath, const OnnxConverter::Level level, const std::vector<std::string> &expected_binary_conv_outputs) { GOOGLE_PROTOBUF_VERIFY_VERSION; // We recognize binary convolutions in our custom ONNX optimizers. // Please check out "dabnn_*" pases in // https://github.com/daquexian/onnx/blob/optimizer_for_bnn/onnx/optimizer/passes // for details. vector<string> optimizers{"eliminate_nop_pad", "extract_constant_to_initializer", "dabnn_bconv_strict"}; if (level == Level::kModerate || level == Level::kAggressive) { optimizers.push_back("dabnn_bconv_moderate"); } if (level == Level::kAggressive) { optimizers.push_back("dabnn_bconv_aggressive"); } // model_proto is only used here. Please use the member variable // model_proto_ in the following code model_proto_ = ONNX_NAMESPACE::optimization::Optimize(model_proto, optimizers); for (const auto &tensor : model_proto_.graph().initializer()) { if (tensor.data_type() == ONNX_NAMESPACE::TensorProto_DataType_FLOAT) { Shape shape; for (auto dim : tensor.dims()) { shape.push_back(static_cast<uint32_t>(dim)); } const float *ptr = tensor.float_data().empty() ? reinterpret_cast<const float *>(tensor.raw_data().data()) : tensor.float_data().data(); auto data_vec = vector<float>(ptr, ptr + Product(shape)); onnx_float_tensors_[tensor.name()] = {data_vec, shape, false}; } operands_.push_back(tensor.name()); } vector<flatbuffers::Offset<flatbnn::Input>> inputs; for (const auto &input : model_proto_.graph().input()) { if (std::find(operands_.begin(), operands_.end(), input.name()) != operands_.end()) { continue; } Shape shape; for (const auto &dim : input.type().tensor_type().shape().dim()) { if (dim.value_case() == ONNX_NAMESPACE::TensorShapeProto_Dimension::kDimValue) { shape.push_back(static_cast<uint32_t>(dim.dim_value())); } else { throw std::invalid_argument( "The input of graph doesn't have dim_value"); } } Shape nnapi_shape{shape[0], shape[2], shape[3], shape[1]}; shaper_.AddShape(input.name(), nnapi_shape); auto flat_input = flatbnn::CreateInputDirect(builder_, &nnapi_shape, input.name().c_str()); inputs.push_back(flat_input); } vector<string> binary_conv_outputs; vector<string> skipped_act; bool has_reshape = false; for (const auto &node : model_proto_.graph().node()) { if (has_reshape) { throw std::invalid_argument( "Reshape can only be the last layer for now"); } NodeAttrHelper helper(node); const auto &op = node.op_type(); VLOG(5) << "Node " << node.name(); if (op == "Conv") { VLOG(5) << "Start converting Conv"; auto strides = helper.get("strides", vector<int>{1, 1}); auto pads = helper.get("pads", vector<int>{0, 0, 0, 0}); auto dilations = helper.get("dilations", vector<int>{1, 1}); CHECK_EQ(pads.size(), 4ul); CHECK_EQ(strides.size(), 2ul); CHECK_EQ(dilations.size(), 2ul); auto group = helper.get("group", 1); nonstd::optional<string> bias_name; if (node.input_size() >= 3) { auto ori_bias_name = m(node.input(2)); bias_name = ori_bias_name + "_conv_b"; bnn_tensors_[bias_name.value()] = onnx_float_tensors_.at(ori_bias_name); auto flat_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &bnn_tensors_.at(bias_name.value()).data, &bnn_tensors_.at(bias_name.value()).shape, bias_name.value().c_str()); tensors_.push_back(flat_tensor); } auto ori_weight_name = m(node.input(1)); const bool binary_conv = (node.domain() == "dabnn") || (std::find(expected_binary_conv_outputs.begin(), expected_binary_conv_outputs.end(), node.output(0)) != expected_binary_conv_outputs.end()); if (binary_conv) { binary_conv_outputs.push_back(node.output(0)); bool precede_bn = false; for (const auto &node2 : model_proto_.graph().node()) { if (node2.op_type() == "BatchNormalization" && node2.input(0) == node.output(0)) { precede_bn = true; break; } } if (!precede_bn) { throw std::invalid_argument( "Binary convolutions should precede BatchNorm"); } } AddConv(m(node.input(0)), strides, pads, dilations, group, ori_weight_name, bias_name, m(node.output(0)), binary_conv); VLOG(5) << "Converting Conv completed"; } else if (op == "AveragePool" || op == "MaxPool" || op == "GlobalAveragePool" || op == "GlobalMaxPool") { VLOG(5) << "Start converting Pool"; auto input_name = m(node.input(0)); auto output_name = m(node.output(0)); vector<int> strides, pads, kernel_shape; if (op == "AveragePool" || op == "MaxPool") { strides = helper.get("strides", vector<int>{1, 1}); pads = helper.get("pads", vector<int>{0, 0, 0, 0}); kernel_shape = helper.get("kernel_shape", vector<int>{0, 0}); auto count_include_pad = helper.get("count_include_pad", 0); if (count_include_pad == 1) { throw std::invalid_argument( "count_include_pad == 1 is not supported"); } auto storage_order = helper.get("storage_order", 0); if (storage_order == 1) { throw std::invalid_argument( "storage_order == 1 is not supported"); } if (helper.has_attr("auto_pad")) { throw std::invalid_argument("auto_pad is not supported"); } } else { strides = {0, 0}; pads = {0, 0, 0, 0}; kernel_shape = {-1, -1}; // -1 for global } CHECK_EQ(pads.size(), 4ul); CHECK_EQ(kernel_shape.size(), 2ul); CHECK_EQ(strides.size(), 2ul); shaper_.Pool(input_name, strides[1], strides[0], pads[2], pads[3], pads[0], pads[1], kernel_shape[0], kernel_shape[1], output_name); flatbuffers::Offset<flatbnn::Layer> layer; if (op == "AveragePool" || op == "GlobalAveragePool") { auto param = flatbnn::CreateAvePoolDirect( builder_, input_name.c_str(), &kernel_shape, &pads, &strides, output_name.c_str()); layer = flatbnn::CreateLayer( builder_, flatbnn::LayerType::AvePool, 0, 0, param); } else { auto param = flatbnn::CreateMaxPoolDirect( builder_, input_name.c_str(), &kernel_shape, &pads, &strides, output_name.c_str()); layer = flatbnn::CreateLayer( builder_, flatbnn::LayerType::MaxPool, 0, 0, 0, param); } layers_.push_back(layer); VLOG(5) << "Converting Pool completed"; } else if (op == "PRelu") { VLOG(5) << "Start converting PRelu"; auto input_name = m(node.input(0)); auto slope_name = m(node.input(1)); const auto onnx_slope_tensor = onnx_float_tensors_.at(slope_name); BNN_ASSERT(shaper_[input_name].size() == 4, "PRelu only support 4-d tensor input for now"); const auto slope_shape = onnx_slope_tensor.shape; BNN_ASSERT( (slope_shape.size() == 3 && slope_shape[1] == 1 && slope_shape[2] == 1) || onnx_slope_tensor.data == std::vector<float>{1}, "PRelu only support scalr slope or per-channel slope for now"); const Shape flat_slope_shape{slope_shape[0]}; auto flat_slope_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &onnx_slope_tensor.data, &flat_slope_shape, slope_name.c_str()); tensors_.push_back(flat_slope_tensor); auto output_name = m(node.output(0)); shaper_.Relu(input_name, output_name); auto param = flatbnn::CreatePReluDirect( builder_, input_name.c_str(), slope_name.c_str(), output_name.c_str()); auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::PRelu, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, param); layers_.push_back(layer); VLOG(5) << "Converting PRelu completed"; } else if (op == "Relu") { VLOG(5) << "Start converting Relu"; auto input_name = m(node.input(0)); auto output_name = m(node.output(0)); shaper_.Relu(input_name, output_name); auto param = flatbnn::CreateReluDirect(builder_, input_name.c_str(), output_name.c_str()); auto layer = flatbnn::CreateLayer( builder_, flatbnn::LayerType::Relu, 0, 0, 0, 0, param); layers_.push_back(layer); VLOG(5) << "Converting Relu completed"; } else if (op == "Add") { VLOG(5) << "Start converting Add"; auto input1_name = m(node.input(0)); auto input2_name = m(node.input(1)); auto output_name = m(node.output(0)); shaper_.Eltwise(input1_name, input2_name, output_name); auto param = flatbnn::CreateAddDirect(builder_, input1_name.c_str(), input2_name.c_str(), output_name.c_str()); auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::Add, 0, 0, 0, 0, 0, 0, 0, param); layers_.push_back(layer); VLOG(5) << "Converting Add completed"; } else if (op == "Gemm") { VLOG(5) << "Start converting Gemm"; auto transA = helper.get("transA", 0); auto transB = helper.get("transB", 0); auto alpha = helper.get("alpha", 1.0f); auto beta = helper.get("beta", 1.0f); if (transA == 0 && transB == 1 && alpha == 1.f && beta == 1.f) { auto input_name = m(node.input(0)); auto weight_name = m(node.input(1)); { bnn_tensors_[weight_name] = onnx_float_tensors_.at(weight_name); const auto &weight_tensor = bnn_tensors_[weight_name]; shaper_.AddShape(weight_name, weight_tensor.shape); auto flat_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &weight_tensor.data, &weight_tensor.shape, weight_name.c_str()); tensors_.push_back(flat_tensor); } string bias_name; if (node.input_size() >= 3) { bias_name = m(node.input(2)); bnn_tensors_[bias_name] = onnx_float_tensors_.at(bias_name); const auto &bias_tensor = bnn_tensors_[bias_name]; auto flat_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &bias_tensor.data, &bias_tensor.shape, bias_name.c_str()); tensors_.push_back(flat_tensor); } auto output_name = m(node.output(0)); shaper_.FC(input_name, weight_name, output_name); auto param = flatbnn::CreateFCDirect( builder_, input_name.c_str(), weight_name.c_str(), node.input_size() >= 3 ? bias_name.c_str() : nullptr, output_name.c_str()); auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::FC, 0, 0, 0, 0, 0, 0, param, 0); layers_.push_back(layer); } else { throw std::invalid_argument( "Only transA == 0, transB == 1, alpha == 1.0 and beta == " "1.0 is supported."); } VLOG(5) << "Converting Gemm completed"; } else if (op == "Softmax") { VLOG(5) << "Start converting Softmax"; auto input_name = m(node.input(0)); auto output_name = m(node.output(0)); shaper_.Softmax(input_name, output_name); // simply ignore attribute "axis", because nnapi softmax didn't has // this attr, and we will check the equality of the two ops in // DaqReader.cpp auto param = flatbnn::CreateSoftmaxDirect( builder_, input_name.c_str(), output_name.c_str()); auto layer = flatbnn::CreateLayer( builder_, flatbnn::LayerType::Softmax, 0, 0, 0, 0, 0, param); layers_.push_back(layer); VLOG(5) << "Converting Softmax completed"; } else if (op == "Concat") { VLOG(5) << "Start converting Concat"; vector<std::string> concat_inputs_str; for (const auto &onnx_input : node.input()) { concat_inputs_str.push_back(m(onnx_input)); } vector<flatbuffers::Offset<flatbuffers::String>> concat_inputs = pack_str_vec(concat_inputs_str, builder_); auto axis = helper.get("axis", 1); uint32_t axis_nchw_to_nhwc[4]{0, 3, 1, 2}; auto output_name = m(node.output(0)); shaper_.Concat(concat_inputs_str, axis, output_name); auto param = flatbnn::CreateConcatDirect(builder_, &concat_inputs, axis_nchw_to_nhwc[axis], output_name.c_str()); auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::Concat, 0, 0, 0, 0, 0, 0, 0, 0, param); layers_.push_back(layer); VLOG(5) << "Converting Concat completed"; } else if (op == "Dropout") { VLOG(5) << "Start converting Dropout"; // Dropout does nothing, so the output is the same as the input name_map_[node.output(0)] = m(node.input(0)); VLOG(5) << "Converting Dropout completed"; } else if (op == "Reshape") { VLOG(5) << "Start converting Reshape"; has_reshape = true; VLOG(5) << "Converting Reshape completed"; } else if (op == "BatchNormalization") { VLOG(5) << "Start converting BatchNormalization"; const auto &input_name = node.input(0); const auto &output_name = node.output(0); const auto coeff_a_name = output_name + "_a"; const auto coeff_b_name = output_name + "_b"; CalculateCoeff(node, coeff_a_name, coeff_b_name); shaper_.Affine(input_name, output_name); auto param = flatbnn::CreateAffineDirect( builder_, input_name.c_str(), coeff_a_name.c_str(), coeff_b_name.c_str(), output_name.c_str()); auto layer = flatbnn::CreateLayer(builder_, flatbnn::LayerType::Affine, 0, 0, 0, 0, 0, 0, 0, 0, 0, param); layers_.push_back(layer); auto a_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &onnx_float_tensors_[coeff_a_name].data, &onnx_float_tensors_[coeff_a_name].shape, coeff_a_name.c_str()); auto b_tensor = flatbnn::CreateTensorDirect( builder_, flatbnn::DataType::Float32, nullptr, &onnx_float_tensors_[coeff_b_name].data, &onnx_float_tensors_[coeff_b_name].shape, coeff_b_name.c_str()); tensors_.push_back(a_tensor); tensors_.push_back(b_tensor); VLOG(5) << "Converting BatchNormalization completed"; } else { throw std::invalid_argument("Unsupported operator " + op); } } for (const auto &expected : expected_binary_conv_outputs) { if (std::find(binary_conv_outputs.begin(), binary_conv_outputs.end(), expected) == binary_conv_outputs.end()) { throw std::invalid_argument( expected + " is in the list file but not in the ONNX model, please check " "your list file"); } } auto flat_layers = builder_.CreateVector(layers_); auto flat_inputs = builder_.CreateVector(inputs); auto flat_tensors = builder_.CreateVector(tensors_); auto flat_model = flatbnn::CreateModel(builder_, flat_layers, flat_tensors, flat_inputs, BNN_LATEST_MODEL_VERSION); builder_.Finish(flat_model); VLOG(3) << "Shapes: "; VLOG(3) << shaper_; std::ofstream ofs(filepath); ofs.write(reinterpret_cast<char *>(builder_.GetBufferPointer()), builder_.GetSize()); ofs.close(); return binary_conv_outputs; } void OnnxConverter::CalculateCoeff(const ONNX_NAMESPACE::NodeProto &node, const std::string &coeff_a_name, const std::string &coeff_b_name) { const auto &scale_name = node.input(1); const auto &b_name = node.input(2); const auto &mean_name = node.input(3); const auto &var_name = node.input(4); const auto &eps = NodeAttrHelper(node).get("eps", 1e-5f); const auto &scale = onnx_float_tensors_.at(scale_name); const auto &b = onnx_float_tensors_.at(b_name); const auto &mean = onnx_float_tensors_.at(mean_name); const auto &var = onnx_float_tensors_.at(var_name); std::vector<float> coeff_a_data, coeff_b_data; FORZ(i, scale.data.size()) { const float tmp = std::sqrt(var.data[i] + eps); coeff_a_data.push_back(scale.data[i] / tmp); coeff_b_data.push_back(b.data[i] - scale.data[i] * mean.data[i] / tmp); } for (const auto &node2 : model_proto_.graph().node()) { if (node2.domain() == "dabnn" && node2.op_type() == "Conv" && node2.output(0) == node.input(0)) { const auto &weight = onnx_float_tensors_[node2.input(1)]; { int channels = Shaper::onnx_kc(weight.shape); int width = Shaper::onnx_kw(weight.shape); int height = Shaper::onnx_kh(weight.shape); FORZ(i, coeff_b_data.size()) { coeff_b_data[i] = coeff_b_data[i] + channels * width * height * coeff_a_data[i]; } if (node2.input_size() == 3) { const auto &bias = onnx_float_tensors_[node2.input(2)]; FORZ(i, coeff_b_data.size()) { coeff_b_data[i] += coeff_a_data[i] * bias.data[i]; } } } { FORZ(i, coeff_a_data.size()) { coeff_a_data[i] *= -2; } } } } FTensor coeff_a; coeff_a.data = coeff_a_data; coeff_a.shape = Shape{static_cast<Shaper::len_t>(coeff_a_data.size())}; FTensor coeff_b; coeff_b.data = coeff_b_data; coeff_b.shape = Shape{static_cast<Shaper::len_t>(coeff_b_data.size())}; onnx_float_tensors_[coeff_a_name] = coeff_a; onnx_float_tensors_[coeff_b_name] = coeff_b; } } // namespace bnn
44.584936
85
0.54865
[ "shape", "vector", "model" ]
130a643b031f6069a362be2888c16a820dffe53d
26,912
cc
C++
modules/tracking/plugin/PiiMultiPointTracker.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-19T22:14:18.000Z
2020-04-13T23:27:20.000Z
modules/tracking/plugin/PiiMultiPointTracker.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
null
null
null
modules/tracking/plugin/PiiMultiPointTracker.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-16T05:43:15.000Z
2019-01-29T07:57:11.000Z
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiMultiPointTracker.h" #include <PiiYdinTypes.h> #include <QPainter> #include <QList> #include <PiiQImage.h> #include <PiiMatrix.h> #include <QPolygon> #include <QPoint> #include <QLineF> PiiMultiPointTracker::Data::Data(PiiMultiPointTracker *parent) : tracker(parent), uiPreviousEmissionTime(0), iMinimumTrajectoryLength(5), iFrameCount(0), matMeasurementCounts(1,10), bCumulativeStatistics(false), iEmissionInterval(570), bAllowMerging(false) { } PiiMultiPointTracker::Data::~Data() { } PiiMultiPointTracker::PiiMultiPointTracker() : PiiDefaultOperation(new Data(this)) { PII_D; //init previousEmissionTime to the currentTime d->uiPreviousEmissionTime = QDateTime::currentDateTime().toTime_t(); //add inputs addSocket(d->pCoordinatesInput = new PiiInputSocket("coordinates")); addSocket(d->pLabelsInput = new PiiInputSocket("labels")); d->pLabelsInput->setOptional(true); addSocket(d->pImageInput = new PiiInputSocket("image")); d->pImageInput->setOptional(true); //add outputs addSocket(d->pAreaIdOutput = new PiiOutputSocket("area id")); addSocket(d->pDwellHistogramOutput = new PiiOutputSocket("dwell histogram")); addSocket(d->pAverageDwellOutput = new PiiOutputSocket("average dwell")); addSocket(d->pObjectsOutput = new PiiOutputSocket("objects")); addSocket(d->pVisitorsOutput = new PiiOutputSocket("visitors")); addSocket(d->pAreaStartTimeOutput = new PiiOutputSocket("area start time")); addSocket(d->pAreaEndTimeOutput = new PiiOutputSocket("area end time")); addSocket(d->pLineIdOutput = new PiiOutputSocket("line id")); addSocket(d->pObjectsInOutput = new PiiOutputSocket("objects in")); addSocket(d->pObjectsOutOutput = new PiiOutputSocket("objects out")); addSocket(d->pLineStartTimeOutput = new PiiOutputSocket("line start time")); addSocket(d->pLineEndTimeOutput = new PiiOutputSocket("line end time")); addSocket(d->pImageOutput = new PiiOutputSocket("image")); d->colorList.append(QColor(Qt::black)); d->colorList.append(QColor(Qt::cyan)); d->colorList.append(QColor(Qt::green)); d->colorList.append(QColor(Qt::blue)); d->colorList.append(QColor(Qt::yellow)); d->colorList.append(QColor(Qt::darkRed)); d->colorList.append(QColor(Qt::darkGreen)); d->colorList.append(QColor(Qt::darkBlue)); d->colorList.append(QColor(Qt::darkCyan)); d->colorList.append(QColor(Qt::darkMagenta)); } void PiiMultiPointTracker::check(bool reset) { PII_D; PiiDefaultOperation::check(reset); d->trackerTime.start(); setFrameCount(0); } void PiiMultiPointTracker::setFrameCount(int frameCount) { PII_D; d->iFrameCount = frameCount; if (frameCount == 0) { // Reset statistics QList<int> lineKeys = d->hashLines.keys(); for ( int i=0; i<lineKeys.size(); i++ ) { int key = lineKeys[i]; d->hashLines[key].objectsIn = 0; d->hashLines[key].objectsOut = 0; } QList<int> areaKeys = d->hashAreas.keys(); for ( int i=0; i<areaKeys.size(); i++ ) { int key = areaKeys[i]; d->hashAreas[key].totalStayTime = 0; d->hashAreas[key].totalObjectCount = 0; d->hashAreas[key].dwellHistogram = 0; d->hashAreas[key].visitors = 0; } d->matMeasurementCounts = 0; // Reset tracker d->tracker.resetTracker(); d->trackerTime.start(); } } void PiiMultiPointTracker::process() { PII_D; QDateTime time = QDateTime::currentDateTime(); unsigned int currentTime = time.toTime_t(); PiiVariant coordObj = d->pCoordinatesInput->firstObject(); if (coordObj.type() == PiiYdin::IntMatrixType) { if (d->pLabelsInput->isConnected()) { PiiVariant labelsObj = d->pLabelsInput->firstObject(); if (labelsObj.type() == PiiYdin::IntMatrixType) operate(coordObj.valueAs<PiiMatrix<int> >(), labelsObj.valueAs<PiiMatrix<int> >()); else PII_THROW_UNKNOWN_TYPE(d->pLabelsInput); } else operate(coordObj.valueAs<PiiMatrix<int> >()); } else PII_THROW_UNKNOWN_TYPE(d->pCoordinatesInput); if (d->pImageInput->isConnected() && d->pImageOutput->isConnected()) { //if image-input is connected, draw all routes to the image PiiVariant imageObj = d->pImageInput->firstObject(); switch (imageObj.type()) { case PiiYdin::UnsignedCharColorMatrixType: operateImage<PiiColor<unsigned char> >(imageObj); break; case PiiYdin::UnsignedCharColor4MatrixType: operateImage<PiiColor4<unsigned char> >(imageObj); break; PII_NUMERIC_MATRIX_CASES(operateImage, imageObj); default: PII_THROW_UNKNOWN_TYPE(d->pImageInput); } } d->iFrameCount++; // We need to emit the analysis results if ( (currentTime - d->uiPreviousEmissionTime) >= (unsigned int)d->iEmissionInterval ) { // Area statistics QList<int> areaKeys = d->hashAreas.keys(); for ( int i=0; i<areaKeys.size(); i++ ) { int key = areaKeys[i]; AreaStatistics areaStruct = d->hashAreas[key]; int visitorCount = areaStruct.visitors; d->pAreaIdOutput->emitObject(key); d->pDwellHistogramOutput->emitObject(areaStruct.dwellHistogram); d->pAverageDwellOutput->emitObject(visitorCount ? double(areaStruct.totalStayTime) / visitorCount : 0); d->pObjectsOutput->emitObject(double(areaStruct.totalObjectCount) / (double)d->iFrameCount); d->pVisitorsOutput->emitObject(visitorCount); d->pAreaStartTimeOutput->emitObject(static_cast<int>(d->uiPreviousEmissionTime)); d->pAreaEndTimeOutput->emitObject(static_cast<int>(currentTime)); } // Line statistics QList<int> lineKeys = d->hashLines.keys(); for ( int i=0; i<lineKeys.size(); i++ ) { int key = lineKeys[i]; d->pLineIdOutput->emitObject(key); d->pObjectsInOutput->emitObject(d->hashLines[key].objectsIn); d->pObjectsOutOutput->emitObject(d->hashLines[key].objectsOut); d->pLineStartTimeOutput->emitObject(static_cast<int>(d->uiPreviousEmissionTime)); d->pLineEndTimeOutput->emitObject(static_cast<int>(currentTime)); } if (!d->bCumulativeStatistics) { // Reset all statistics for ( int i=0; i<lineKeys.size(); i++ ) { int key = lineKeys[i]; d->hashLines[key].objectsIn = 0; d->hashLines[key].objectsOut = 0; } for ( int i=0; i<areaKeys.size(); i++ ) { int key = areaKeys[i]; d->hashAreas[key].totalStayTime = 0; d->hashAreas[key].totalObjectCount = 0; d->hashAreas[key].dwellHistogram = 0; d->hashAreas[key].visitors = 0; } d->iFrameCount = 0; } d->uiPreviousEmissionTime = currentTime; } } int PiiMultiPointTracker::mapTime(int time) { static const int limits[8] = { 10, 20, 30, 60, 120, 180, 240, 300 }; for (int i=0; i<8; i++) if (time < limits[i]) return i; return 8; } bool PiiMultiPointTracker::collectLineStatistics(PiiCoordinateTrackerNode<double,2>* trajectory) { PII_D; bool bAmountChanged = false; // First calculate count of the in/out QPoint previousPoint = QPoint(int(trajectory->measurement()[0]), int(trajectory->measurement()[1])); trajectory = trajectory->next(); PiiMatrix<int> directionSums(1,d->lstLines.size()); while (trajectory) { QPoint currentPoint = QPoint(int(trajectory->measurement()[0]), int(trajectory->measurement()[1])); for (int i=0; i<d->lstLines.size(); i++ ) { QPoint lineStartPoint = d->lstLines[i].value<QPolygon>().point(0); QPoint lineEndPoint = d->lstLines[i].value<QPolygon>().point(1); directionSums(0,i) += checkCalculationLine(lineStartPoint, lineEndPoint, currentPoint, previousPoint); } trajectory = trajectory->next(); previousPoint = currentPoint; } // Then store values for ( int i=0; i<d->lstLineIdentifications.size(); i++) { int key = d->lstLineIdentifications[i].toInt(); if (d->hashLines.contains(key)) { if (directionSums(0,i) > 0) { bAmountChanged = true; d->hashLines[key].objectsIn++; } else if (directionSums(0,i) < 0) { bAmountChanged = true; d->hashLines[key].objectsOut++; } } } return bAmountChanged; } bool PiiMultiPointTracker::collectAreaStatistics(PiiCoordinateTrackerNode<double,2>* trajectory) { PII_D; bool bAmountChanged = false; PiiVector<double,2> previousPoint = trajectory->measurement(); int size = d->lstAreas.size(); bool *previousIn = new bool[size]; bool *currentIn = new bool[size]; bool *someIn = new bool[size]; int *exitTime = new int[size]; for ( int i=0; i<size; i++ ) { previousIn[i] = false; currentIn[i] = false; someIn[i] = false; exitTime[i] = 0; } int previousTime = trajectory->time(); while (trajectory) { PiiVector<double,2> currentPoint = trajectory->measurement(); QPoint point((int)currentPoint[0],(int)currentPoint[1]); for ( int i=0; i<size; i++ ) { int key = d->lstAreaIdentifications[i].toInt(); if ( d->hashAreas.contains(key) ) { QPolygon polygon = d->lstAreas[i].value<QPolygon>(); currentIn[i] = polygon.contains(point); //Pii::contains(polygon,point); someIn[i] = someIn[i] || currentIn[i]; // If the point is within the area, we increase total object // count. if (currentIn[i]) { d->hashAreas[key].totalObjectCount++; // Object exited area if (!previousIn[i]) exitTime[i] = previousTime; } // Object entered area else if (previousIn[i]) { int stayTime = int(double(exitTime[i] - previousTime)/1000.0 + 0.5); int k=mapTime(stayTime); d->hashAreas[key].dwellHistogram(k)++; d->hashAreas[key].totalStayTime += stayTime; } previousIn[i] = currentIn[i]; } } previousPoint = currentPoint; previousTime = trajectory->time(); trajectory = trajectory->next(); } // If the start point of the trajectory is still within the area, // and the object has exited it later, we need to count for ( int i=0; i<size; i++ ) { int key = d->lstAreaIdentifications[i].toInt(); if (previousIn[i] && exitTime[i]) { if ( d->hashAreas.contains(key) ) { int stayTime = int(double(exitTime[i] - previousTime)/1000.0 + 0.5); int k=mapTime(stayTime); d->hashAreas[key].dwellHistogram(k)++; d->hashAreas[key].totalStayTime += stayTime; bAmountChanged = true; } } // Increase visitor counting if necessary if (someIn[i]) d->hashAreas[key].visitors++; } delete[] previousIn; delete[] currentIn; delete[] someIn; delete[] exitTime; return bAmountChanged; } void PiiMultiPointTracker::operate(const PiiMatrix<int>& coordinates) { PII_D; d->tracker.addMeasurements(coordinates, d->trackerTime.elapsed()); } void PiiMultiPointTracker::operate(const PiiMatrix<int>& coordinates, const PiiMatrix<int>& labels) { PII_D; d->tracker.addMeasurements(coordinates, labels, d->trackerTime.elapsed()); } template <class T> void PiiMultiPointTracker::operateImage(const PiiVariant& obj) { PII_D; QList<PiiCoordinateTrackerNode<double,2>* > trajectories = d->tracker; QList<QPolygonF> trajects; for ( int i=0; i<trajectories.count(); i++ ) { PiiCoordinateTrackerNode<double,2> *node = trajectories[i]; QPolygonF polygon; while ( node ) { QPointF point(node->measurement()[0],node->measurement()[1]); polygon.append(point); node = node->next(); } trajects.append(polygon); } const PiiMatrix<T>& matrix = obj.valueAs<PiiMatrix<T> >(); PiiColorQImage* qmatrix = PiiColorQImage::create(matrix); QPainter painter(qmatrix); QPen pen(Qt::DashLine); pen.setWidth(2); pen.setCosmetic(true); pen.setColor(QColor(Qt::magenta)); painter.setPen(pen); painter.setBrush(QBrush(Qt::NoBrush)); // Draw calculating lines for ( int i=0; i < d->lstLines.size(); i++ ) painter.drawPolygon(d->lstLines[i].value<QPolygon>()); // Draw calculating areas painter.setPen(pen); for ( int i=0; i < d->lstAreas.size(); i++ ) painter.drawPolygon(d->lstAreas[i].value<QPolygon>()); // Draw tracking area pen.setColor(QColor(Qt::gray)); painter.setPen(pen); painter.drawRect(d->trackingArea); // Draw trajectories pen.setStyle(Qt::SolidLine); for ( int i=0; i<trajects.count(); i++ ) { pen.setColor(d->colorList[i%d->colorList.size()]); painter.setPen(pen); painter.drawPolyline(trajects[i]); } painter.end(); d->pImageOutput->emitObject(qmatrix->toMatrix()); } /* * This function checks, if the path from the point `prev` to the * point `curr` intersects the calculation line from the point * `calcLineStart` to `calcLineEnd.` If there is now intersection, 0 is * returned. If the intersection occurs from right to left relative to * the calculation line (vector) direction, +1 is returned. In the * opposite case (from left to right), -1 is returned. */ int PiiMultiPointTracker::checkCalculationLine(const QPoint& calcLineStart, const QPoint& calcLineEnd, const QPoint& prev, const QPoint& curr ) { if (hasIntersection(calcLineStart, calcLineEnd, prev, curr)) { return pathDirection(calcLineStart, calcLineEnd, prev, curr); } else { return 0; } } /* * Returns true, if the line from `prev` to `curr` intersects the line * from `calcLineStart` and `calcLineEnd` */ bool PiiMultiPointTracker::hasIntersection(const QPoint& calcLineStart, const QPoint& calcLineEnd, const QPoint& prev, const QPoint& curr ) { QLineF calculationLine = QLineF(QPointF(calcLineStart), QPointF(calcLineEnd)); QLineF trajectoryLine = QLineF(QPointF(prev), QPointF(curr)); QPointF intersectionPoint; return calculationLine.intersect(trajectoryLine, &intersectionPoint) == QLineF::BoundedIntersection; } /* * Calculates the path direction relative to the calculation line. If the * path goes to leftwards compared to the calculation line (vector), +1 is * returned. In the opposite case -1 is returned. If the path goes parallel * compared to the calculation line, 0 is returned. */ int PiiMultiPointTracker::pathDirection(const QPoint& calcLineStart, const QPoint& calcLineEnd, const QPoint& prev, const QPoint& curr) { // Calculate the dot product of the calculation line vector and the // vector perpendicular (90 degrees rotated clockwise) to the path // vector. If the result is positive, the path goes leftwards // compared to the calculte line, and the path goes in rightwards in // the opposite case. QPoint calcLineVector = calcLineEnd-calcLineStart; QPoint pathVector = curr-prev; int dotProduct = calcLineVector.x()*(-pathVector.y()) + calcLineVector.y()*pathVector.x(); return dotProduct/abs(dotProduct); } void PiiMultiPointTracker::setAreas(const QVariantList& areas) { PII_D; d->lstAreas.clear(); d->lstAreas = areas; if ( d->lstAreaIdentifications.empty() ) for ( int i=0; i<d->lstAreas.size(); i++ ) d->lstAreaIdentifications << i; //update area hashtable //add new calculation areas for ( int i=0; i<d->lstAreaIdentifications.size(); i++ ) { int id = d->lstAreaIdentifications[i].toInt(); if ( !d->hashAreas.contains(id) ) { AreaStatistics newStruct; newStruct.dwellHistogram = PiiMatrix<int>(1,9); newStruct.totalStayTime = 0; newStruct.totalObjectCount = 0; newStruct.visitors = 0; d->hashAreas.insert(id, newStruct); } } //remove unnecessary areas QHashIterator<int, AreaStatistics> k(d->hashAreas); while (k.hasNext()) { k.next(); if ( !d->lstAreaIdentifications.contains(k.key()) ) d->hashAreas.remove(k.key()); } } void PiiMultiPointTracker::setLines(const QVariantList& lines) { PII_D; d->lstLines.clear(); d->lstLines = lines; if ( d->lstLineIdentifications.empty() ) for ( int i=0; i<d->lstLines.size(); i++ ) d->lstLineIdentifications << i; //update line hashtable //add new calculation lines for ( int i=0; i<d->lstLineIdentifications.size(); i++ ) { int id = d->lstLineIdentifications[i].toInt(); if ( !d->hashLines.contains(id) ) { LineStatistics newStruct; newStruct.objectsIn = 0; newStruct.objectsOut = 0; d->hashLines.insert(id, newStruct); } } //remove unnecessary lines QHashIterator<int, LineStatistics> k(d->hashLines); while (k.hasNext()) { k.next(); if ( !d->lstLineIdentifications.contains(k.key()) ) d->hashLines.remove(k.key()); } } void PiiMultiPointTracker::setMinimumTrajectoryLength(int minimumTrajectoryLength) { _d()->iMinimumTrajectoryLength = minimumTrajectoryLength; } int PiiMultiPointTracker::minimumTrajectoryLength() const { return _d()->iMinimumTrajectoryLength; } void PiiMultiPointTracker::setCumulativeStatistics(bool cumulativeStatistics) { _d()->bCumulativeStatistics = cumulativeStatistics; } bool PiiMultiPointTracker::cumulativeStatistics() const { return _d()->bCumulativeStatistics; } int PiiMultiPointTracker::frameCount() const { return _d()->iFrameCount; } void PiiMultiPointTracker::setTrackingArea(const QRect& trackingArea) { _d()->trackingArea = trackingArea; } QRect PiiMultiPointTracker::trackingArea() const { return _d()->trackingArea; } void PiiMultiPointTracker::setAreaIdentifications(const QVariantList& areaIdentifications) { _d()->lstAreaIdentifications = areaIdentifications; } QVariantList PiiMultiPointTracker::areaIdentifications() const { return _d()->lstAreaIdentifications; } void PiiMultiPointTracker::setLineIdentifications(const QVariantList& lineIdentifications) { _d()->lstLineIdentifications = lineIdentifications; } QVariantList PiiMultiPointTracker::lineIdentifications() const { return _d()->lstLineIdentifications; } QVariantList PiiMultiPointTracker::areas() const { return _d()->lstAreas; } QVariantList PiiMultiPointTracker::lines() const { return _d()->lstLines; } void PiiMultiPointTracker::setEmissionInterval(int emissionInterval) { _d()->iEmissionInterval = emissionInterval; } int PiiMultiPointTracker::emissionInterval() const { return _d()->iEmissionInterval; } void PiiMultiPointTracker::setAllowMerging(bool allowMerging) { _d()->bAllowMerging = allowMerging; } bool PiiMultiPointTracker::allowMerging() const { return _d()->bAllowMerging; } void PiiMultiPointTracker::setInitialThreshold(int initialThreshold) { _d()->tracker.setInitialThreshold(initialThreshold); } int PiiMultiPointTracker::initialThreshold() const { return _d()->tracker.initialThreshold(); } void PiiMultiPointTracker::setPredictionThreshold(int predictionThreshold) { _d()->tracker.setPredictionThreshold(predictionThreshold); } int PiiMultiPointTracker::predictionThreshold() const { return _d()->tracker.predictionThreshold(); } void PiiMultiPointTracker::setMaximumStopTime(int maximumStopTime) { _d()->tracker.setMaximumStopTime(maximumStopTime); } int PiiMultiPointTracker::maximumStopTime() const { return _d()->tracker.maximumStopTime(); } void PiiMultiPointTracker::setMaximumPredictionLength(int maximumPredictionLength) { _d()->tracker.setMaximumPredictionLength(maximumPredictionLength); } int PiiMultiPointTracker::maximumPredictionLength() const { return _d()->tracker.maximumPredictionLength(); } // PiiMultiPointTracker::Tracker functions PiiMultiPointTracker::Tracker::Tracker(PiiMultiPointTracker *parent) : _pParent(parent) { } PiiMultiPointTracker::Tracker::~Tracker() { } void PiiMultiPointTracker::Tracker::resetTracker() { qDeleteAll(*this); clear(); } double PiiMultiPointTracker::Tracker::evaluateTrajectory(PiiCoordinateTrackerNode<double,2>* trajectory) { return trajectory->length(); } void PiiMultiPointTracker::Tracker::predict(int /*t*/) { // Do nothing because we manually invoke the superclass' prediction // function at the start of addMeasurements(). } void PiiMultiPointTracker::Tracker::addMeasurements(const PiiMatrix<int>& coordinates, int t) { PiiCoordinateTracker<double,2>::addMeasurements(PiiMatrix<double>(coordinates), t); } void PiiMultiPointTracker::Tracker::addMeasurements(const PiiMatrix<int>& coordinates, const PiiMatrix<int>& labels, int t) { PiiCoordinateTracker<double,2>::addMeasurements(PiiMatrix<double>(coordinates), PiiMatrix<double>(labels), t); } void PiiMultiPointTracker::Tracker::addMeasurements(const QList<PiiVector<double,2> >& measurements, int t) { PiiMultiPointTracker::Data* const d = _pParent->_d(); // First predict a new position for all measurements PiiCoordinateTracker<double,2>::predict(t); // Then get rid of all trajectories whose predictions are outside // of the tracking area. if (d->trackingArea.isValid()) { QList<PiiCoordinateTrackerNode<double,2>*> deletedTrajectories; for (int i=count(); i--;) { PiiVector<double,2>* prediction = at(i)->prediction(); if (prediction) { // The prediction is outside of image boundaries -> // finalize it if (prediction->values[0] < d->trackingArea.left() || prediction->values[0] > d->trackingArea.right() || prediction->values[1] < d->trackingArea.top() || prediction->values[1] > d->trackingArea.bottom()) deletedTrajectories << takeAt(i); } } endTrajectories(deletedTrajectories, t); } // Now run the tracker once PiiExtendedCoordinateTracker<double,2>::addMeasurements(measurements, t); // Evaluate and sort trajectories for (int i=count(); i--;) { PiiCoordinateTrackerNode<double,2> *node = (*this)[i]; node->setTrajectoryFitness(evaluateTrajectory(node)); } // Puts the trajectories in descending order sortTrajectories(); // Store the number of measurements d->matMeasurementCounts(d->iFrameCount % d->matMeasurementCounts.columns()) = measurements.size(); // The number of routes considered depens on the local maximum in // measurement counts. int maxRetainedTrajectories = Pii::max(d->matMeasurementCounts) * 2; QList<PiiCoordinateTrackerNode<double,2>*> retainedTrajectories; // Retain at least one route (the best one) for each measurement // independent of its fitness. for (int m = measurements.size(); m--; ) { for (int t = count(); t--; ) { // This trajectory ends at this point if (at(t)->measurement() == measurements[m]) { retainedTrajectories << takeAt(t); break; } } } // If we still have room for candidates and something left, let's // add them in fitness order while (count() > 0 && retainedTrajectories.size() < maxRetainedTrajectories) retainedTrajectories << takeLast(); // Retain all remaining short routes anyway for (int i=count(); i--; ) if (at(i)->length() <= 2) retainedTrajectories << takeAt(i); // Get rid of any remaining ones resetTracker(); // We are done append(retainedTrajectories); } void PiiMultiPointTracker::Tracker::endTrajectories(QList<PiiCoordinateTrackerNode<double,2>*> trajectories, int t) { PiiMultiPointTracker::Data* const d = _pParent->_d(); bool bLineStatChanged = false; bool bAreaStatChanged = false; for (int i=0; i<trajectories.size(); i++) { PiiCoordinateTrackerNode<double,2>* trajectory = trajectories[i]; // Is the trajectory long enough? This should remove spurious // branches. if (trajectory->lengthToBranch() > d->iMinimumTrajectoryLength) { qDebug("Trajectory %i was finished at time step %i. Length: %i", i, t, trajectory->lengthToBranch()); // Collect statistics if (_pParent->collectAreaStatistics(trajectory)) bAreaStatChanged = true; if (_pParent->collectLineStatistics(trajectory)) bLineStatChanged = true; if (!d->bAllowMerging) { // Since this route is stored, get rid of all other alternatives // ending at this point. for (int j=trajectories.size()-1; j>i; j--) if (*trajectories[j] == *trajectories[i]) { qDebug(" Also deleted trajectory %i because there is the same end point.", j); delete trajectories.takeAt(j); } } } delete trajectories[i]; } if (bLineStatChanged) { //debug in and outs QList<int> keys = d->hashLines.keys(); for ( int i=0; i<keys.size(); i++) { qDebug("Line %i:", keys[i]); qDebug(" in \t%i", d->hashLines[keys[i]].objectsIn); qDebug(" out\t%i", d->hashLines[keys[i]].objectsOut); } } if (bAreaStatChanged) { //debug area visitors QList<int> areaKeys = d->hashAreas.keys(); for ( int i=0; i<areaKeys.size(); i++ ) { int key = areaKeys[i]; qDebug("Area %i:", key); qDebug(" visitors %i", d->hashAreas[key].visitors); } } }
33.102091
146
0.649227
[ "object", "vector" ]
130c66622630f6305632ee4d3d65506d1a2f4f8b
2,625
cpp
C++
DevTools/HackStudio/WidgetTreeModel.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
3
2020-05-01T02:39:03.000Z
2021-11-26T08:34:54.000Z
DevTools/HackStudio/WidgetTreeModel.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
null
null
null
DevTools/HackStudio/WidgetTreeModel.cpp
JamiKettunen/serenity
232da5cc188496f570ef55276a897f1095509c87
[ "BSD-2-Clause" ]
1
2021-06-02T18:02:51.000Z
2021-06-02T18:02:51.000Z
#include "WidgetTreeModel.h" #include <AK/StringBuilder.h> #include <LibGUI/GWidget.h> #include <stdio.h> WidgetTreeModel::WidgetTreeModel(GWidget& root) : m_root(root) { m_widget_icon.set_bitmap_for_size(16, GraphicsBitmap::load_from_file("/res/icons/16x16/inspector-object.png")); } WidgetTreeModel::~WidgetTreeModel() { } GModelIndex WidgetTreeModel::index(int row, int column, const GModelIndex& parent) const { if (!parent.is_valid()) { return create_index(row, column, m_root.ptr()); } auto& parent_node = *static_cast<GWidget*>(parent.internal_data()); return create_index(row, column, parent_node.child_widgets().at(row)); } GModelIndex WidgetTreeModel::parent_index(const GModelIndex& index) const { if (!index.is_valid()) return {}; auto& widget = *static_cast<GWidget*>(index.internal_data()); if (&widget == m_root.ptr()) return {}; if (widget.parent_widget() == m_root.ptr()) return create_index(0, 0, m_root.ptr()); // Walk the grandparent's children to find the index of widget's parent in its parent. // (This is needed to produce the row number of the GModelIndex corresponding to widget's parent.) int grandparent_child_index = 0; for (auto& grandparent_child : widget.parent_widget()->parent_widget()->child_widgets()) { if (grandparent_child == widget.parent_widget()) return create_index(grandparent_child_index, 0, widget.parent_widget()); ++grandparent_child_index; } ASSERT_NOT_REACHED(); return {}; } int WidgetTreeModel::row_count(const GModelIndex& index) const { if (!index.is_valid()) return 1; auto& widget = *static_cast<GWidget*>(index.internal_data()); return widget.child_widgets().size(); } int WidgetTreeModel::column_count(const GModelIndex&) const { return 1; } GVariant WidgetTreeModel::data(const GModelIndex& index, Role role) const { auto* widget = static_cast<GWidget*>(index.internal_data()); if (role == Role::Icon) { return m_widget_icon; } if (role == Role::Display) { return String::format("%s (%s)", widget->class_name(), widget->relative_rect().to_string().characters()); } return {}; } void WidgetTreeModel::update() { did_update(); } GModelIndex WidgetTreeModel::index_for_widget(GWidget& widget) const { int parent_child_index = 0; for (auto& parent_child : widget.parent_widget()->child_widgets()) { if (parent_child == &widget) return create_index(parent_child_index, 0, &widget); ++parent_child_index; } return {}; }
29.494382
115
0.680381
[ "object" ]
130d1f17d6269776f44e7dd7cae3543ddf3b52e3
10,790
cpp
C++
src/tests/ip.cpp
Erroneous1/brewpipp
73b65f0c7f78920fa1f65b787ed19f5b3681ffcd
[ "MIT" ]
1
2019-04-30T08:53:47.000Z
2019-04-30T08:53:47.000Z
src/tests/ip.cpp
Erroneous1/brewpipp
73b65f0c7f78920fa1f65b787ed19f5b3681ffcd
[ "MIT" ]
null
null
null
src/tests/ip.cpp
Erroneous1/brewpipp
73b65f0c7f78920fa1f65b787ed19f5b3681ffcd
[ "MIT" ]
null
null
null
/* * Distrubuted under The MIT License (MIT) * * Copyright (c) 2016 Aaron Bishop * * 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 "util/ip.hpp" #include <iostream> #include <vector> #include <utility> bool ipv6test(const char* text, const std::string& correct) { brewpipp::util::ip ip(text); if(ip.to_string().compare(correct)!=0) { std::cout << "Bad IPv6 conversion!" << std::endl << "Input: " << text << std::endl << "Output: " << ip.to_string() << std::endl << "Expect: " << correct << std::endl; std::string data = ip.value(); std::cout << "Data: "; for(const auto& c : data) { std::printf("%02x ",static_cast<uint8_t>(c)); } std::cout << std::endl; std::cout << "IPv" << (brewpipp::util::netmask::ipv4_map() == ip ? '4' : '6') << std::endl; return false; }else{ return true; } } int main() { std::vector<std::pair<std::string,std::string> > test_cases({ {"::1","::1"},// loopback, compressed, non-routable {"::","::"},// unspecified, compressed, non-routable {"0:0:0:0:0:0:0:1","::1"},// loopback, full {"0:0:0:0:0:0:0:0","::"},// unspecified, full {"2001:DB8:0:0:8:800:200C:417A","2001:db8::8:800:200c:417a"},// unicast, full {"FF01:0:0:0:0:0:0:101","ff01::101"},// multicast, full {"2001:DB8::8:800:200C:417A","2001:db8::8:800:200c:417a"},// unicast, compressed {"FF01::101","ff01::101"},// multicast, compressed {"fe80::217:f2ff:fe07:ed62","fe80::217:f2ff:fe07:ed62"}, {"2001:0000:1234:0000:0000:C1C0:ABCD:0876","2001:0:1234::c1c0:abcd:876"}, {"3ffe:0b00:0000:0000:0001:0000:0000:000a","3ffe:b00::1:0:0:a"}, {"FF02:0000:0000:0000:0000:0000:0000:0001","ff02::1"}, {"0000:0000:0000:0000:0000:0000:0000:0001","::1"}, {"0000:0000:0000:0000:0000:0000:0000:0000","::"}, {"2::10","2::10"}, {"ff02::1","ff02::1"}, {"fe80::","fe80::"}, {"2002::","2002::"}, {"2001:db8::","2001:db8::"}, {"2001:0db8:1234::","2001:db8:1234::"}, {"::ffff:0:0","0.0.0.0"}, {"1:2:3:4:5:6:7:8","1:2:3:4:5:6:7:8"}, {"1:2:3:4:5:6::8","1:2:3:4:5:6::8"}, {"1:2:3:4:5::8","1:2:3:4:5::8"}, {"1:2:3:4::8","1:2:3:4::8"}, {"1:2:3::8","1:2:3::8"}, {"1:2::8","1:2::8"}, {"1::8","1::8"}, {"1::2:3:4:5:6:7","1::2:3:4:5:6:7"}, {"1::2:3:4:5:6","1::2:3:4:5:6"}, {"1::2:3:4:5","1::2:3:4:5"}, {"1::2:3:4","1::2:3:4"}, {"1::2:3","1::2:3"}, {"1::8","1::8"}, {"::2:3:4:5:6:7:8","::2:3:4:5:6:7:8"}, {"::2:3:4:5:6:7","::2:3:4:5:6:7"}, {"::2:3:4:5:6","::2:3:4:5:6"}, {"::2:3:4:5","::2:3:4:5"}, {"::2:3:4","::2:3:4"}, {"::2:3","::2:3"}, {"::8","::8"}, {"1:2:3:4:5:6::","1:2:3:4:5:6::"}, {"1:2:3:4:5::","1:2:3:4:5::"}, {"1:2:3:4::","1:2:3:4::"}, {"1:2:3::","1:2:3::"}, {"1:2::","1:2::"}, {"1::","1::"}, {"1:2:3:4:5::7:8","1:2:3:4:5::7:8"}, {"1:2:3:4::7:8","1:2:3:4::7:8"}, {"1:2:3::7:8","1:2:3::7:8"}, {"1:2::7:8","1:2::7:8"}, {"1::7:8","1::7:8"}, // IPv4 addresses as dotted-quads {"1:2:3:4:5:6:1.2.3.4","1.2.3.4"}, {"1:2:3:4:5::1.2.3.4","1.2.3.4"}, {"1:2:3:4::1.2.3.4","1.2.3.4"}, {"1:2:3::1.2.3.4","1.2.3.4"}, {"1:2::1.2.3.4","1.2.3.4"}, {"1::1.2.3.4","1.2.3.4"}, {"1:2:3:4::5:1.2.3.4","1.2.3.4"}, {"1:2:3::5:1.2.3.4","1.2.3.4"}, {"1:2::5:1.2.3.4","1.2.3.4"}, {"1::5:1.2.3.4","1.2.3.4"}, {"1::5:11.22.33.44","11.22.33.44"}, {"fe80::217:f2ff:254.7.237.98","254.7.237.98"}, {"::ffff:192.168.1.26","192.168.1.26"}, {"::ffff:192.168.1.1","192.168.1.1"}, {"0:0:0:0:0:0:13.1.68.3","13.1.68.3"},// IPv4-compatible IPv6 address, full, deprecated {"0:0:0:0:0:FFFF:129.144.52.38","129.144.52.38"},// IPv4-mapped IPv6 address, full {"::13.1.68.3","13.1.68.3"},// IPv4-compatible IPv6 address, compressed, deprecated {"::FFFF:129.144.52.38","129.144.52.38"},// IPv4-mapped IPv6 address, compressed {"fe80:0:0:0:204:61ff:254.157.241.86","254.157.241.86"}, {"fe80::204:61ff:254.157.241.86","254.157.241.86"}, {"::ffff:12.34.56.78","12.34.56.78"}, {"::ffff:192.0.2.128","192.0.2.128"}, // but this is OK, since there's a single digit {"fe80:0000:0000:0000:0204:61ff:fe9d:f156","fe80::204:61ff:fe9d:f156"}, {"fe80:0:0:0:204:61ff:fe9d:f156","fe80::204:61ff:fe9d:f156"}, {"fe80::204:61ff:fe9d:f156","fe80::204:61ff:fe9d:f156"}, {"fe80::","fe80::"}, {"fe80::1","fe80::1"}, {"::ffff:c000:280","192.0.2.128"}, // Additional test cases // from http://rt.cpan.org/Public/Bug/Display.html?id=50693 {"2001:0db8:85a3:0000:0000:8a2e:0370:7334","2001:db8:85a3::8a2e:370:7334"}, {"2001:db8:85a3:0:0:8a2e:370:7334","2001:db8:85a3::8a2e:370:7334"}, {"2001:db8:85a3::8a2e:370:7334","2001:db8:85a3::8a2e:370:7334"}, {"2001:0db8:0000:0000:0000:0000:1428:57ab","2001:db8::1428:57ab"}, {"2001:0db8:0000:0000:0000::1428:57ab","2001:db8::1428:57ab"}, {"2001:0db8:0:0:0:0:1428:57ab","2001:db8::1428:57ab"}, {"2001:0db8:0:0::1428:57ab","2001:db8::1428:57ab"}, {"2001:0db8::1428:57ab","2001:db8::1428:57ab"}, {"2001:db8::1428:57ab","2001:db8::1428:57ab"}, {"0000:0000:0000:0000:0000:0000:0000:0001","::1"}, {"::ffff:0c22:384e","12.34.56.78"}, {"2001:0db8:1234:0000:0000:0000:0000:0000","2001:db8:1234::"}, {"2001:0db8:1234:ffff:ffff:ffff:ffff:ffff","2001:db8:1234:ffff:ffff:ffff:ffff:ffff"}, {"2001:db8:a::123","2001:db8:a::123"}, {"fe80::","fe80::"}, // New from Aeron {"1111:2222:3333:4444:5555:6666:7777:8888","1111:2222:3333:4444:5555:6666:7777:8888"}, {"1111:2222:3333:4444:5555:6666:7777::","1111:2222:3333:4444:5555:6666:7777::"}, {"1111:2222:3333:4444:5555:6666::","1111:2222:3333:4444:5555:6666::"}, {"1111:2222:3333:4444:5555::","1111:2222:3333:4444:5555::"}, {"1111:2222:3333:4444::","1111:2222:3333:4444::"}, {"1111:2222:3333::","1111:2222:3333::"}, {"1111:2222::","1111:2222::"}, {"1111::","1111::"}, {"1111:2222:3333:4444:5555:6666::8888","1111:2222:3333:4444:5555:6666::8888"}, {"1111:2222:3333:4444:5555::8888","1111:2222:3333:4444:5555::8888"}, {"1111:2222:3333:4444::8888","1111:2222:3333:4444::8888"}, {"1111:2222:3333::8888","1111:2222:3333::8888"}, {"1111:2222::8888","1111:2222::8888"}, {"1111::8888","1111::8888"}, {"::8888","::8888"}, {"1111:2222:3333:4444:5555::7777:8888","1111:2222:3333:4444:5555::7777:8888"}, {"1111:2222:3333:4444::7777:8888","1111:2222:3333:4444::7777:8888"}, {"1111:2222:3333::7777:8888","1111:2222:3333::7777:8888"}, {"1111:2222::7777:8888","1111:2222::7777:8888"}, {"1111::7777:8888","1111::7777:8888"}, {"::7777:8888","::7777:8888"}, {"1111:2222:3333:4444::6666:7777:8888","1111:2222:3333:4444::6666:7777:8888"}, {"1111:2222:3333::6666:7777:8888","1111:2222:3333::6666:7777:8888"}, {"1111:2222::6666:7777:8888","1111:2222::6666:7777:8888"}, {"1111::6666:7777:8888","1111::6666:7777:8888"}, {"::6666:7777:8888","::6666:7777:8888"}, {"1111:2222:3333::5555:6666:7777:8888","1111:2222:3333::5555:6666:7777:8888"}, {"1111:2222::5555:6666:7777:8888","1111:2222::5555:6666:7777:8888"}, {"1111::5555:6666:7777:8888","1111::5555:6666:7777:8888"}, {"::5555:6666:7777:8888","::5555:6666:7777:8888"}, {"1111:2222::4444:5555:6666:7777:8888","1111:2222::4444:5555:6666:7777:8888"}, {"1111::4444:5555:6666:7777:8888","1111::4444:5555:6666:7777:8888"}, {"::4444:5555:6666:7777:8888","::4444:5555:6666:7777:8888"}, {"1111::3333:4444:5555:6666:7777:8888","1111::3333:4444:5555:6666:7777:8888"}, {"::3333:4444:5555:6666:7777:8888","::3333:4444:5555:6666:7777:8888"}, {"::2222:3333:4444:5555:6666:7777:8888","::2222:3333:4444:5555:6666:7777:8888"}, {"1111:2222:3333:4444:5555:6666:123.123.123.123","123.123.123.123"}, {"1111:2222:3333:4444:5555::123.123.123.123","123.123.123.123"}, {"1111:2222:3333:4444::123.123.123.123","123.123.123.123"}, {"1111:2222:3333::123.123.123.123","123.123.123.123"}, {"1111:2222::123.123.123.123","123.123.123.123"}, {"1111::123.123.123.123","123.123.123.123"}, {"::123.123.123.123","123.123.123.123"}, {"1111:2222:3333:4444::6666:123.123.123.123","123.123.123.123"}, {"1111:2222:3333::6666:123.123.123.123","123.123.123.123"}, {"1111:2222::6666:123.123.123.123","123.123.123.123"}, {"1111::6666:123.123.123.123","123.123.123.123"}, {"::6666:123.123.123.123","123.123.123.123"}, {"1111:2222:3333::5555:6666:123.123.123.123","123.123.123.123"}, {"1111:2222::5555:6666:123.123.123.123","123.123.123.123"}, {"1111::5555:6666:123.123.123.123","123.123.123.123"}, {"::5555:6666:123.123.123.123","123.123.123.123"}, {"1111:2222::4444:5555:6666:123.123.123.123","123.123.123.123"}, {"1111::4444:5555:6666:123.123.123.123","123.123.123.123"}, {"::4444:5555:6666:123.123.123.123","123.123.123.123"}, {"1111::3333:4444:5555:6666:123.123.123.123","123.123.123.123"}, {"::2222:3333:4444:5555:6666:123.123.123.123","123.123.123.123"}, // Playing with combinations of "0" and "::" // NB: these are all sytactically correct, but are bad form // because "0" adjacent to "::" should be combined into "::" {"::0:0:0:0:0:0:0","::"}, {"::0:0:0:0:0:0","::"}, {"::0:0:0:0:0","::"}, {"::0:0:0:0","::"}, {"::0:0:0","::"}, {"::0:0","::"}, {"::0","::"}, {"0:0:0:0:0:0:0::","::"}, {"0:0:0:0:0:0::","::"}, {"0:0:0:0:0::","::"}, {"0:0:0:0::","::"}, {"0:0:0::","::"}, {"0:0::","::"}, {"0::","::"}, // Additional cases: http://crisp.tweakblogs.net/blog/2031/ipv6-validation-%28and-caveats%29.html {"0:a:b:c:d:e:f::","0:a:b:c:d:e:f::"}, {"::0:a:b:c:d:e:f","::a:b:c:d:e:f"}, // syntactically correct, but bad form (::0:... could be combined) {"a:b:c:d:e:f:0::","a:b:c:d:e:f::"} }); for(size_t i = 0; i < test_cases.size(); i++) { if(!ipv6test(test_cases[i].first.c_str(),test_cases[i].second)) { std::cout << "failed test case " << i << std::endl; return 1; } } std::cout << "Successfully passed " << test_cases.size() << " tests" << std::endl; return 0; }
44.040816
105
0.583689
[ "vector" ]
1317bb2dbb34678d5c8e1535ea6052ee8e80ad65
7,315
hpp
C++
include/algorithms/cpop.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
include/algorithms/cpop.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
include/algorithms/cpop.hpp
Felix-Droop/static_task_scheduling
084b7d53caeff9ac3593aa7e3d2c5206afd234d0
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <queue> #include <ranges> #include <sstream> #include <unordered_map> #include <unordered_set> #include <vector> #include <cluster/cluster.hpp> #include <io/command_line_arguments.hpp> #include <io/handle_output.hpp> #include <schedule/schedule.hpp> #include <util/epsilon_compare.hpp> #include <workflow/workflow.hpp> namespace algorithms { std::unordered_map<workflow::task_id, double> compute_task_priorities( std::unordered_map<workflow::task_id, double> downward_ranks, std::unordered_map<workflow::task_id, double> upward_ranks ) { std::unordered_map<workflow::task_id, double> task_priorities{}; for (auto const & [t_id, downward_rank] : downward_ranks) { task_priorities.insert({ t_id, downward_rank + upward_ranks.at(t_id) }); } return task_priorities; } std::unordered_set<workflow::task_id> compute_critical_path( workflow::workflow const & w, std::unordered_map<workflow::task_id, double> task_priorities ) { // we don't enforce a single entry task and choose the independent task with the highest priority auto const & independent_task_ids = w.get_independent_task_ids(); auto const max_it = std::ranges::max_element(independent_task_ids, [&task_priorities] (workflow::task_id const & t0_id, workflow::task_id const & t1_id) { // this should be analogous to the std::less operator regarding priority (t0 < t1?) // if the priorities are equal, then t0 has a smaller priority, if its id is larger double const t0_priority = task_priorities.at(t0_id); double const t1_priority = task_priorities.at(t1_id); if (t0_priority == t1_priority) { return t0_id > t1_id; } else { return t0_priority < t1_priority; } }); // safe dereference because it is enforced that independent tasks exist double const critical_path_priority = task_priorities.at(*max_it); workflow::task_id curr_task_id = *max_it; std::unordered_set<workflow::task_id> critical_path{}; auto const has_critical_priority = [&task_priorities, critical_path_priority] (workflow::task_id const & t_id) { return util::epsilon_eq(task_priorities.at(t_id), critical_path_priority); }; while (true) { critical_path.insert(curr_task_id); auto critical_successor_task_ids = w.get_task_outgoing_edges(curr_task_id) | std::views::transform([] (auto const & edge) { auto const & [neighbor_id, weight] = edge; return neighbor_id; }) | std::views::filter(has_critical_priority); // tie break using lowest id auto const next_it = std::ranges::min_element(critical_successor_task_ids); if (next_it == critical_successor_task_ids.end()) { break; } curr_task_id = *next_it; } return critical_path; } cluster::node_id best_fitting_node( std::unordered_set<workflow::task_id> const & critical_path, workflow::workflow const & w, cluster::cluster const & c, bool const use_memory_requirements ) { if (!use_memory_requirements) { return c.best_performance_node(); } // in our input model, the critical path is simply scheduled on // the best node with sufficient memory if we want to use the memory requirements auto critical_path_memories = critical_path | std::views::transform([&w] (workflow::task_id const & t_id) { return w.get_task(t_id).memory_requirement; }); double const critical_path_memory_requirement = *std::ranges::min_element(critical_path_memories); return c.best_performance_node(critical_path_memory_requirement); } std::string critical_path_to_string( std::unordered_set<workflow::task_id> const & critical_path ) { std::vector<workflow::task_id> critical_path_seq( critical_path.begin(), critical_path.end() ); std::ranges::sort(critical_path_seq); std::stringstream out; out << "CPOP -- Critical path: [ "; for (auto const task_id : critical_path_seq) { out << task_id << ' '; } out << "]\n\n"; return out.str(); } // Critical path on processor // Running time analysis: // TODO // tie-breaking for critical path and priority queue: lower id task -> higher priority schedule::schedule cpop( cluster::cluster const & c, workflow::workflow const & w, io::command_line_arguments const & args ) { auto const downward_ranks = w.all_downward_ranks( c.mean_performance(), c.mean_bandwidth() ); auto const upward_ranks = w.all_upward_ranks( c.mean_performance(), c.mean_bandwidth() ); auto const task_priorities = compute_task_priorities(downward_ranks, upward_ranks); auto const critical_path = compute_critical_path(w, task_priorities); io::handle_output_str(args, critical_path_to_string(critical_path)); cluster::node_id const best_node = best_fitting_node(critical_path, w, c, args.use_memory_requirements); schedule::schedule s(c, args.use_memory_requirements); struct prioritized_task { // members can't be const because the priority queue needs this to be moveable workflow::task_id id; double priority; bool on_critical_path; }; struct task_priority_compare { bool operator() (prioritized_task const & t0, prioritized_task const & t1) const { // this should be analogous to the std::less operator regarding priority (t0 < t1?) // if the priorities are equal, then t0 has a smaller priority, if its id is larger if (t0.priority == t1.priority) { return t0.id > t1.id; } else { return t0.priority < t1.priority; } } }; std::priority_queue<prioritized_task, std::vector<prioritized_task>, task_priority_compare> prio_q; for (workflow::task_id const & t_id : w.get_independent_task_ids()) { prio_q.push({ t_id, task_priorities.at(t_id), critical_path.contains(t_id) }); } // copy incoming edges locally to modify to identify new independent tasks auto temp_incoming_edges = w.get_all_incoming_edges(); while (!prio_q.empty()) { auto [curr_t_id, priority, on_critical_path] = prio_q.top(); prio_q.pop(); if (on_critical_path) { s.insert_into_node_schedule(curr_t_id, best_node, w); } else { s.insert_into_best_eft_node_schedule(curr_t_id, w); } for (auto const & [neighbor_id, weight] : w.get_task_outgoing_edges(curr_t_id)) { size_t const num_erased = temp_incoming_edges.at(neighbor_id).erase(curr_t_id); if (num_erased != 1) { throw std::runtime_error("Internal bug: incoming/outgoing edges are out of sync"); } if (temp_incoming_edges.at(neighbor_id).empty()) { prio_q.push({ neighbor_id, task_priorities.at(neighbor_id), critical_path.contains(neighbor_id) }); } } } return s; } } // namespace algorithms
33.25
116
0.660014
[ "vector", "model", "transform" ]
13254f3ba52dc7b5758a8b534b6fbec5b884742e
807
cpp
C++
leetcode.com/0802 Find Eventual Safe States/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0802 Find Eventual Safe States/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0802 Find Eventual Safe States/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; // ref: Detect Cycle in a directed graph using colors // https://www.geeksforgeeks.org/detect-cycle-direct-graph-using-colors/ class Solution { enum Color { UNCHKED, SAFE, UNSAFE }; int n; bool is_safe(int i, vector<Color>& colors, vector<vector<int>>& graph) { if (colors[i]) return colors[i] == SAFE; colors[i] = UNSAFE; for (int j : graph[i]) { if (!is_safe(j, colors, graph)) return false; } colors[i] = SAFE; return true; } public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { n = graph.size(); vector<int> res; vector<Color> colors(n); // all unchked for (int i = 0; i < n; ++i) { if (is_safe(i, colors, graph)) res.push_back(i); } return res; } };
24.454545
74
0.61834
[ "vector" ]
1325acc7b5913890a15a5903f760072b3e368c02
13,104
cpp
C++
src/obj/NiNode.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
1
2021-12-24T00:42:42.000Z
2021-12-24T00:42:42.000Z
src/obj/NiNode.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
null
null
null
src/obj/NiNode.cpp
BlazesRus/niflib
7e8efb6b2c73a3410135dbd6d73694e29f1e9ce8
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// //--BEGIN FILE HEAD CUSTOM CODE--// #include "../../include/obj/NiSkinInstance.h" #include "../../include/obj/NiTriBasedGeom.h" #include "../../include/obj/NiSkinData.h" //--END CUSTOM CODE--// #include "../../include/FixLink.h" #include "../../include/ObjectRegistry.h" #include "../../include/NIF_IO.h" #include "../../include/obj/NiNode.h" #include "../../include/obj/NiAVObject.h" #include "../../include/obj/NiDynamicEffect.h" using namespace Niflib; //Definition of TYPE constant const Type NiNode::TYPE("NiNode", &NiAVObject::TYPE ); NiNode::NiNode() : numChildren((unsigned int)0), numEffects((unsigned int)0) { //--BEGIN CONSTRUCTOR CUSTOM CODE--// //Set flag to default of 8: not a skin influence flags = 8; //--END CUSTOM CODE--// } NiNode::~NiNode() { //--BEGIN DESTRUCTOR CUSTOM CODE--// //Unbind any attached skins - must happen before children are cleared for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { (*it)->SkeletonLost(); } //Clear Children ClearChildren(); //--END CUSTOM CODE--// } const Type & NiNode::GetType() const { return TYPE; } NiObject * NiNode::Create() { return new NiNode; } void NiNode::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) { //--BEGIN PRE-READ CUSTOM CODE--// //--END CUSTOM CODE--// unsigned int block_num; NiAVObject::Read( in, link_stack, info ); NifStream( numChildren, in, info ); children.resize(numChildren); for (unsigned int i1 = 0; i1 < children.size(); i1++) { NifStream( block_num, in, info ); link_stack.push_back( block_num ); }; NifStream( numEffects, in, info ); effects.resize(numEffects); for (unsigned int i1 = 0; i1 < effects.size(); i1++) { NifStream( block_num, in, info ); link_stack.push_back( block_num ); }; //--BEGIN POST-READ CUSTOM CODE--// //--END CUSTOM CODE--// } void NiNode::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const { //--BEGIN PRE-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// NiAVObject::Write( out, link_map, missing_link_stack, info ); numEffects = (unsigned int)(effects.size()); numChildren = (unsigned int)(children.size()); NifStream( numChildren, out, info ); for (unsigned int i1 = 0; i1 < children.size(); i1++) { if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*children[i1]), out ); } else { if ( children[i1] != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(children[i1]) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( children[i1] ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } }; NifStream( numEffects, out, info ); for (unsigned int i1 = 0; i1 < effects.size(); i1++) { if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*effects[i1]), out ); } else { if ( effects[i1] != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(effects[i1]) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( effects[i1] ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } }; //--BEGIN POST-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// } std::string NiNode::asString( bool verbose ) const { //--BEGIN PRE-STRING CUSTOM CODE--// //--END CUSTOM CODE--// stringstream out; unsigned int array_output_count = 0; out << NiAVObject::asString(); numEffects = (unsigned int)(effects.size()); numChildren = (unsigned int)(children.size()); out << " Num Children: " << numChildren << endl; array_output_count = 0; for (unsigned int i1 = 0; i1 < children.size(); i1++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl; break; }; if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { break; }; out << " Children[" << i1 << "]: " << children[i1] << endl; array_output_count++; }; out << " Num Effects: " << numEffects << endl; array_output_count = 0; for (unsigned int i1 = 0; i1 < effects.size(); i1++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "<Data Truncated. Use verbose mode to see complete listing.>" << endl; break; }; if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { break; }; out << " Effects[" << i1 << "]: " << effects[i1] << endl; array_output_count++; }; return out.str(); //--BEGIN POST-STRING CUSTOM CODE--// //--END CUSTOM CODE--// } void NiNode::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) { //--BEGIN PRE-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// NiAVObject::FixLinks( objects, link_stack, missing_link_stack, info ); for (unsigned int i1 = 0; i1 < children.size(); i1++) { children[i1] = FixLink<NiAVObject>( objects, link_stack, missing_link_stack, info ); }; for (unsigned int i1 = 0; i1 < effects.size(); i1++) { effects[i1] = FixLink<NiDynamicEffect>( objects, link_stack, missing_link_stack, info ); }; //--BEGIN POST-FIXLINKS CUSTOM CODE--// //Connect children to their parents and remove any NULL ones for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == NULL) { it = children.erase( it ); } else { (*it)->SetParent(this); ++it; } } //--END CUSTOM CODE--// } std::list<NiObjectRef> NiNode::GetRefs() const { list<Ref<NiObject> > refs; refs = NiAVObject::GetRefs(); for (unsigned int i1 = 0; i1 < children.size(); i1++) { if ( children[i1] != NULL ) refs.push_back(StaticCast<NiObject>(children[i1])); }; for (unsigned int i1 = 0; i1 < effects.size(); i1++) { if ( effects[i1] != NULL ) refs.push_back(StaticCast<NiObject>(effects[i1])); }; return refs; } std::list<NiObject *> NiNode::GetPtrs() const { list<NiObject *> ptrs; ptrs = NiAVObject::GetPtrs(); for (unsigned int i1 = 0; i1 < children.size(); i1++) { }; for (unsigned int i1 = 0; i1 < effects.size(); i1++) { }; return ptrs; } //--BEGIN MISC CUSTOM CODE--// void NiNode::AddChild( Ref<NiAVObject> obj ) { if ( obj->GetParent() != NULL ) { throw runtime_error( "You have attempted to add a child to a NiNode which already is the child of another NiNode." ); } obj->SetParent( this ); //Sometimes NiTriBasedGeom with skins can be siblings of NiNodes that //represent joints for that same skin. When this is the case, NiTriBasedGeom //must com first, so we enforce that by always adding NiTriBasedGeom to the //begining of the child list. NiTriBasedGeomRef niGeom = DynamicCast<NiTriBasedGeom>(obj); if ( niGeom != NULL ) { //This is a NiTriBasedGeom, so shift all children to the right size_t old_size = children.size(); children.resize( children.size() + 1 ); for ( size_t i = children.size() - 1; i >= 1; --i ) { children[i] = children[i-1]; } //Now add the new child to the begining of the list children[0] = obj; } else { //This is some other type of object. Just add it to the end of the list. children.push_back( obj ); } } void NiNode::RemoveChild( Ref<NiAVObject> obj ) { //Search child list for the one to remove for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == obj ) { (*it)->SetParent(NULL); it = children.erase( it ); } else { ++it; } } } void NiNode::ClearChildren() { for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ++it) { if ( *it != NULL ) { (*it)->SetParent(NULL); } } children.clear(); } vector< Ref<NiAVObject> > NiNode::GetChildren() const { return children; } void NiNode::AddEffect( NiDynamicEffect * obj ) { obj->SetParent( this ); effects.push_back( obj ); } void NiNode::RemoveEffect( NiDynamicEffect * obj ) { //Search Effect list for the one to remove for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ) { if ( *it == obj ) { (*it)->SetParent(NULL); it = effects.erase( it ); } else { ++it; } } } void NiNode::ClearEffects() { for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ++it) { if (*it) (*it)->SetParent(NULL); } effects.clear(); } vector< Ref<NiDynamicEffect> > NiNode::GetEffects() const { return effects; } bool NiNode::IsSkeletonRoot() const { return ( skins.size() > 0 ); } bool NiNode::IsSkinInfluence() const { return ((flags & 8) == 0); } void NiNode::AddSkin( NiSkinInstance * skin_inst ) { skins.push_back( skin_inst ); } void NiNode::RemoveSkin( NiSkinInstance * skin_inst ) { //Remove the reference skins.remove( skin_inst); //Ensure that any multiply referenced bone nodes still //have their skin flag set vector<NiNodeRef> bones; for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { bones = (*it)->GetBones(); for ( unsigned int i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } } } void NiNode::SetSkinFlag( bool n ) { if ( IsSkinInfluence() == n ) { //Already set to the requested value return; } else { //Requested value is different, flip bit flags ^= 8; } } void NiNode::GoToSkeletonBindPosition() { //map<NiNodeRef, Matrix44> world_positions; //Loop through all attached skins, straightening the skeleton on each for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { //Get Bone list and Skin Data vector<NiNodeRef> bone_nodes = (*it)->GetBones(); NiSkinDataRef skin_data = (*it)->GetSkinData(); if ( skin_data == NULL ) { //There's no skin data for this skin instance; skip it. continue; } //Make sure the counts match if ( bone_nodes.size() != skin_data->GetBoneCount() ) { throw runtime_error( "Bone counts in NiSkinInstance and attached NiSkinData must match" ); } //Loop through all bones influencing this skin for ( unsigned int i = 0; i < bone_nodes.size(); ++i ) { //Get current offset Matrix for this bone Matrix44 parent_offset = skin_data->GetBoneTransform(i); //Loop through all bones again, checking for any that have this bone as a parent for ( unsigned int j = 0; j < bone_nodes.size(); ++j ) { if ( bone_nodes[j]->GetParent() == bone_nodes[i] ) { //Node 2 has node 1 as a parent //Get child offset Matrix33 Matrix44 child_offset = skin_data->GetBoneTransform(j); //Do calculation to get correct bone postion in relation to parent Matrix44 child_pos = child_offset.Inverse() * parent_offset; //bones[j]->SetWorldBindPos( child_pos ); bone_nodes[j]->SetLocalRotation( child_pos.GetRotation() ); bone_nodes[j]->SetLocalScale( 1.0f ); bone_nodes[j]->SetLocalTranslation( child_pos.GetTranslation() ); } } } } } void NiNode::PropagateTransform() { Matrix44 par_trans = this->GetLocalTransform(); //Loop through each child and apply this node's transform to it for ( unsigned i = 0; i < children.size(); ++i ) { children[i]->SetLocalTransform( children[i]->GetLocalTransform() * par_trans ); } //Nowthat the transforms have been propogated, clear them out this->SetLocalTransform( Matrix44::IDENTITY ); } bool NiNode::IsSplitMeshProxy() const { //Let us guess that a node is a split mesh proxy if: // 1) It is not a skin influence // 2) All its children are NiTriBasedGeom derived objects. // 3) All its children have identity transforms. // 4) It has more than one child // 5) All meshes are visible // 6) ???? May need more criteria as time goes on. if ( this->IsSkinInfluence() ) { return false; } if ( children.size() < 2 ) { return false; } for ( unsigned i = 0; i < children.size(); ++i ) { if ( children[i]->IsDerivedType( NiTriBasedGeom::TYPE ) == false ) { return false; } if ( children[i]->GetLocalTransform() != Matrix44::IDENTITY ) { return false; } if ( children[i]->GetVisibility() == false ) { return false; } } //Made it all the way through the loop without returning false return true; } //--END CUSTOM CODE--//
29.917808
167
0.638584
[ "mesh", "object", "vector", "transform" ]
133200c49fc3cf52379285ab8000cccc962ad122
3,978
cpp
C++
bl/util/dynamic_lib.cpp
potato3d/baselib
2744c4dc752b50c9171c43cf0f1db4c6716a634d
[ "MIT" ]
null
null
null
bl/util/dynamic_lib.cpp
potato3d/baselib
2744c4dc752b50c9171c43cf0f1db4c6716a634d
[ "MIT" ]
null
null
null
bl/util/dynamic_lib.cpp
potato3d/baselib
2744c4dc752b50c9171c43cf0f1db4c6716a634d
[ "MIT" ]
null
null
null
#include <bl/util/dynamic_lib.h> #include <bl/util/algorithm.h> #include <bl/util/path.h> #if defined BL_OS_WIN #define WIN32_LEAN_AND_MEAN #include <windows.h> #elif defined BL_OS_LINUX #include <dlfcn.h> #else #error "Unsupported operating system." #endif namespace bl { static string get_last_error() { string err = "unknown error"; #ifdef BL_OS_WIN LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&lpMsgBuf), 0, NULL ); if(lpMsgBuf != nullptr) { err = lpMsgBuf; LocalFree(lpMsgBuf); } #elif defined BL_OS_LINUX err = dlerror(); #else #error "unsupported operating system" #endif return err; } bool dynamic_lib::has_valid_extension(const string& pathstr) { #if defined BL_OS_WIN #define WIN32_LEAN_AND_MEAN const string ext = "dll"; #elif defined BL_OS_LINUX const string ext = "so"; #else #error "Unsupported operating system." #endif return contains(path::get_extension(pathstr), ext); } dynamic_lib::dynamic_lib(const string& pathstr) : _filepath(pathstr), _loaded(false), _handleptr(nullptr) { } dynamic_lib::~dynamic_lib() { unload(); } bool dynamic_lib::load() { if(_loaded) { unload(); } _lasterror = "no error"; if(!path::exists(_filepath)) { _lasterror = str("Cannot load '%0' (error = No such file or directory)", _filepath); return false; } if(!has_valid_extension(_filepath)) { _lasterror = str("Cannot load '%0' (error = Wrong extension)", _filepath); return false; } #if defined(BL_OS_WIN) // Avoid 'Bad Image' message box. UINT oldmode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); _handleptr = LoadLibraryA(_filepath.ptr()); SetErrorMode(oldmode); #elif defined BL_OS_LINUX // Relocations are performed when the object is loaded. _handleptr = dlopen(_filepath.data(), RTLD_NOW); #else #error "Unsupported operating system." #endif if(!_handleptr) { _loaded = false; _lasterror = str("Cannot load '%0' (error = %1)", _filepath, get_last_error()); } else { _loaded = true; _lasterror = "no error"; } return _loaded; } bool dynamic_lib::unload() { if(_loaded) { #ifdef BL_OS_WIN _loaded = !FreeLibrary(reinterpret_cast<HINSTANCE>(_handleptr)); #elif defined BL_OS_LINUX _loaded = dlclose(_handleptr); #else #error "Unsupported operating system." #endif } if(_loaded) { _lasterror = get_last_error(); } else { _handleptr = nullptr; _lasterror = "no error"; } return !_loaded; } const string& dynamic_lib::filepath() { return _filepath; } const string& dynamic_lib::last_error() { return _lasterror; } dynamic_lib::func_type dynamic_lib::_resolve_function(const string& name) { func_type address = nullptr; #if defined(BL_OS_WIN32) typedef __stdcall int (*Ptr)(); *reinterpret_cast<Ptr*>(&address) = GetProcAddress(static_cast<HINSTANCE>(_handleptr), name.ptr()); if(!address) { _lasterror = string("dynamic_lib::_resolve_symbol: Symbol '%0' undefined in '%1'", name, _filepath); return nullptr; } #elif defined(BL_OS_WIN64) typedef __stdcall long long int (*Ptr)(); *reinterpret_cast<Ptr*>(&address) = GetProcAddress(static_cast<HINSTANCE>(_handleptr), name.ptr()); if(!address) { _lasterror = string("dynamic_lib::_resolve_symbol: Symbol '%0' undefined in '%1'", name, _filepath); return nullptr; } #elif defined BL_OS_LINUX *reinterpret_cast<void**>(&address) = dlsym(_handleptr, name.data()); const char* err = dlerror(); if(err) { _lasterror = str("Symbol '%0' undefined in '%1' (%2)", name, _filepath, err); return nullptr; } #else #error "Unsupported operating system." #endif _lasterror = ""; return address; } } // namespace bl
20.827225
103
0.686023
[ "object" ]
133817d199f5adc4da9a36517aa39ccdc67d98a2
3,052
cc
C++
countingBound/cliqueCounter/CliqueCoverageCounter.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
countingBound/cliqueCounter/CliqueCoverageCounter.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
countingBound/cliqueCounter/CliqueCoverageCounter.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
#include "CliqueCoverageCounter.h" #include <stdint.h> #include <cstdlib> #include <iostream> #include <vector> using namespace std; /** Constructor. */ CliqueCoverageCounter::CliqueCoverageCounter(int n, int r, int maxCliqueSize) : cliques(n, r, maxCliqueSize), cliqueCount(maxCliqueSize+1), coveredEdgeCount(maxCliqueSize+1) { } /** Samples a random graph, and prints counts of cliques of various sizes (and how many edges they cover). */ void CliqueCoverageCounter::printCoverageCounts() { // sample a graph, and print counts bits g = randomBitset(cliques.getNumEdges()); printCoverageCounts1(g); // then print counts for the complement g.flip(); printCoverageCounts1(g); } /** Prints counts for one graph. */ void CliqueCoverageCounter::printCoverageCounts1(bits & g) { bits coveredEdges(g); for(int k = 0; k <= cliques.max_clique_size_; ++k) { cliqueCount[k] = cliques.getCoveredEdges(g, k, coveredEdges); coveredEdgeCount[k] = coveredEdges.count(); } // print the counts for(int k = 0; k <= cliques.max_clique_size_; ++k) cout << cliqueCount[k] << " "; cout << " "; // add a tiny bit of formatting for(int k = 0; k <= cliques.max_clique_size_; ++k) cout << coveredEdgeCount[k] << " "; cout << endl; } /** Creates a random bitset of some size. */ bits CliqueCoverageCounter::randomBitset(int numBits) { bits b; // first, get enough 64-bit blocks for(int i = 0; i < (numBits/64)+1; i++) { // get a 64-bit random number uint64_t r = random() ^ (random() << 32); b.append(r); } // then truncate to the required size b.resize(numBits); return b; } /** Prints total coverage counts, for all possible graphs. Note that this may be slow. XXX Note that this uses the cliqueCount and coveredEdgeCount vectors in a different way -- as a total across many different hypergraphs, rather than in only one hypergraph. */ bool CliqueCoverageCounter::printCoverageAllHypergraphs() { // if the number of edges is more than 62, just punt if (cliques.getNumEdges() >= 62) return false; // this will track which hyperedges in g are covered bits coveredEdges(cliques.getNumEdges()); // loop through the possible hypergraphs for(unsigned int i=0; i < (1ul << cliques.getNumEdges()); i++) { // convert counter to a hypergraph bits g(cliques.getNumEdges(), i); // check for cliques of each size for(int k = 0; k <= cliques.max_clique_size_; ++k) { // add to totals of each size cliqueCount[k] += cliques.getCoveredEdges(g, k, coveredEdges); coveredEdgeCount[k] += coveredEdges.count(); } } // print the (total!) counts for(int k = 0; k <= cliques.max_clique_size_; ++k) cout << cliqueCount[k] << " "; cout << " "; // add a tiny bit of formatting for(int k = 0; k <= cliques.max_clique_size_; ++k) cout << coveredEdgeCount[k] << " "; cout << endl; return true; }
32.817204
79
0.642857
[ "vector" ]
133aedbd43a636c48b0fb9d30690d7beafb81c6b
9,810
cc
C++
src/NodeHMM.cc
KanoComputing/node-gr
849262582801601f2fe9e09f894f91a796264355
[ "MIT" ]
4
2018-06-22T13:01:14.000Z
2021-02-12T15:07:07.000Z
src/NodeHMM.cc
KanoComputing/node-gr
849262582801601f2fe9e09f894f91a796264355
[ "MIT" ]
1
2018-06-01T13:56:05.000Z
2018-12-11T00:52:34.000Z
src/NodeHMM.cc
KanoComputing/node-gr
849262582801601f2fe9e09f894f91a796264355
[ "MIT" ]
4
2018-02-02T15:31:04.000Z
2021-07-25T07:32:41.000Z
#include "NodeHMM.h" #include "NodeTimeSeriesClassificationData.h" #include <GRT/GRT.h> Nan::Persistent<v8::Function> NodeHMM::constructor; NAN_MODULE_INIT(NodeHMM::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("HMM").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "setHMMType", SetHMMType); Nan::SetPrototypeMethod(tpl, "setNumStates", SetNumStates); Nan::SetPrototypeMethod(tpl, "setNumSymbols", SetNumSymbols); Nan::SetPrototypeMethod(tpl, "setModelType", SetModelType); Nan::SetPrototypeMethod(tpl, "setMinChange", SetMinChange); Nan::SetPrototypeMethod(tpl, "setMaxNumEpochs", SetMaxNumEpochs); Nan::SetPrototypeMethod(tpl, "setNumRandomTrainingIterations", SetNumRandomTrainingIterations); Nan::SetPrototypeMethod(tpl, "train", Train); Nan::SetPrototypeMethod(tpl, "predict", Predict); Nan::SetPrototypeMethod(tpl, "getPredictedClassLabel", GetPredictedClassLabel); Nan::SetPrototypeMethod(tpl, "getClassLikelihoods", GetClassLikelihoods); constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("HMM").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NodeHMM::NodeHMM() { hmm = new GRT::HMM(); } NodeHMM::~NodeHMM() { } NAN_METHOD(NodeHMM::Train) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); NodeTimeSeriesClassificationData* data = Nan::ObjectWrap::Unwrap<NodeTimeSeriesClassificationData>(info[0]->ToObject()); bool returnValue = obj->hmm->train(*data->getTimeSeriesClassificationData()); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetHMMType) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsInt32()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int hmmType = ( int )( info[0]->Int32Value() ); bool returnValue = obj->hmm->setHMMType(hmmType); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetNumStates) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsInt32()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int numStates = ( int )( info[0]->Int32Value() ); bool returnValue = obj->hmm->setNumStates(numStates); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetNumSymbols) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsInt32()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int numSymbols = ( int )( info[0]->Int32Value() ); bool returnValue = obj->hmm->setNumSymbols(numSymbols); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetModelType) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsInt32()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int modelType = ( int )( info[0]->Int32Value() ); bool returnValue = obj->hmm->setModelType(modelType); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetMinChange) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsNumber()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int minChange = ( int )( info[0]->NumberValue() ); bool returnValue = obj->hmm->setMinChange(minChange); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetMaxNumEpochs) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsNumber()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int maxNumEpochs = ( int )( info[0]->NumberValue() ); bool returnValue = obj->hmm->setMaxNumEpochs(maxNumEpochs); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::SetNumRandomTrainingIterations) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { std::string argsLength = std::to_string(info.Length()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, ("Wrong number of arguments: expected 1, got " + argsLength).c_str()))); return; } if (!info[0]->IsNumber()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int numRandomTrainingIterations = ( int )( info[0]->NumberValue() ); bool returnValue = obj->hmm->setNumRandomTrainingIterations(numRandomTrainingIterations); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::Predict) { v8::Isolate* isolate = info.GetIsolate(); if (info.Length() < 1) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong number of arguments"))); return; } NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); if (!info[0]->IsArray()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); return; } GRT::MatrixFloat sample; v8::Handle<v8::Value> val; v8::Handle<v8::Value> itemVal; v8::Handle<v8::Array> item; v8::Handle<v8::Array> jsArray = v8::Handle<v8::Array>::Cast(info[0]); double number; GRT::VectorFloat vector; for (unsigned int i = 0; i < jsArray->Length(); i++) { val = jsArray->Get(i); if (!val->IsArray()) { isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, "Wrong argument"))); } item = v8::Handle<v8::Array>::Cast(val); for (unsigned int j = 0; j < item->Length(); j++) { itemVal = item->Get(j); number = itemVal->NumberValue(); vector.push_back(number); } sample.push_back(vector); vector.clear(); } bool returnValue = obj->hmm->predict(sample); info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::GetPredictedClassLabel) { NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); int returnValue = obj->hmm->getPredictedClassLabel(); std::cout << "Predicted class label: " << returnValue << std::endl; info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::GetClassLikelihoods) { v8::Isolate* isolate = info.GetIsolate(); NodeHMM* obj = Nan::ObjectWrap::Unwrap<NodeHMM>(info.This()); GRT::VectorFloat vectorReturn = obj->hmm->getClassLikelihoods(); v8::Handle<v8::Array> returnValue = v8::Array::New(isolate, vectorReturn.getSize()); for (unsigned int i = 0; i < vectorReturn.getSize(); i++) { v8::Handle<v8::Number> returnNum = v8::Number::New(isolate, vectorReturn[i]); returnValue->Set(i, returnNum); } info.GetReturnValue().Set(returnValue); } NAN_METHOD(NodeHMM::New) { if (info.IsConstructCall()) { NodeHMM *obj = new NodeHMM(); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { v8::Local<v8::Function> cons = Nan::New(constructor); info.GetReturnValue().Set(cons->NewInstance()); } }
37.159091
158
0.64842
[ "vector" ]
133b40f46ae568831787623799635928b013bbcd
1,041
cc
C++
basic/template/variadic/10.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/template/variadic/10.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/template/variadic/10.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; template <std::size_t... Indices> struct indices { using next = indices<Indices..., sizeof...(Indices)>; }; template <std::size_t N> struct build_indices { using type = typename build_indices<N-1>::type::next; }; template <> struct build_indices<0> { using type = indices<>; }; template <std::size_t N> using BuildIndices = typename build_indices<N>::type; template <size_t num_args> struct unpack_caller { private: template <typename FuncType, size_t... I> void call(FuncType &f, std::vector<int> &args, indices<I...>){ f(args[I]...); } public: template <typename FuncType> void operator () (FuncType &f, std::vector<int> &args){ assert(args.size() == num_args); // just to be sure call(f, args, BuildIndices<num_args>{}); } }; int main() { std::vector<int> a = {12,4,3,2}; auto func = [](int i) { std::cout << i << std::endl; }; const size_t a_size = a.size(); unpack_caller<4>(func, a); }
20.82
66
0.623439
[ "vector" ]
1343555b330919d62a10f5de604cc72749dd1289
2,671
cc
C++
base/posix/unix_domain_socket_linux_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
base/posix/unix_domain_socket_linux_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
base/posix/unix_domain_socket_linux_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2013 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 <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/file_util.h" #include "base/pickle.h" #include "base/posix/unix_domain_socket_linux.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { TEST(UnixDomainSocketTest, SendRecvMsgAbortOnReplyFDClose) { Thread message_thread("UnixDomainSocketTest"); ASSERT_TRUE(message_thread.Start()); int fds[2]; ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds)); file_util::ScopedFD scoped_fd0(&fds[0]); file_util::ScopedFD scoped_fd1(&fds[1]); // Have the thread send a synchronous message via the socket. Pickle request; message_thread.message_loop()->PostTask( FROM_HERE, Bind(IgnoreResult(&UnixDomainSocket::SendRecvMsg), fds[1], static_cast<uint8_t*>(NULL), 0U, static_cast<int*>(NULL), request)); // Receive the message. std::vector<int> message_fds; uint8_t buffer[16]; ASSERT_EQ(static_cast<int>(request.size()), UnixDomainSocket::RecvMsg(fds[0], buffer, sizeof(buffer), &message_fds)); ASSERT_EQ(1U, message_fds.size()); // Close the reply FD. ASSERT_EQ(0, HANDLE_EINTR(close(message_fds.front()))); // Check that the thread didn't get blocked. WaitableEvent event(false, false); message_thread.message_loop()->PostTask( FROM_HERE, Bind(&WaitableEvent::Signal, Unretained(&event))); ASSERT_TRUE(event.TimedWait(TimeDelta::FromMilliseconds(5000))); } TEST(UnixDomainSocketTest, SendRecvMsgAvoidsSIGPIPE) { // Make sure SIGPIPE isn't being ignored. struct sigaction act = {}, oldact; act.sa_handler = SIG_DFL; ASSERT_EQ(0, sigaction(SIGPIPE, &act, &oldact)); int fds[2]; ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds)); file_util::ScopedFD scoped_fd1(&fds[1]); ASSERT_EQ(0, HANDLE_EINTR(close(fds[0]))); // Have the thread send a synchronous message via the socket. Unless the // message is sent with MSG_NOSIGNAL, this shall result in SIGPIPE. Pickle request; ASSERT_EQ(-1, UnixDomainSocket::SendRecvMsg(fds[1], static_cast<uint8_t*>(NULL), 0U, static_cast<int*>(NULL), request)); ASSERT_EQ(EPIPE, errno); // Restore the SIGPIPE handler. ASSERT_EQ(0, sigaction(SIGPIPE, &oldact, NULL)); } } // namespace } // namespace base
32.573171
76
0.699738
[ "vector" ]
134982c49c5fb8d20eb612f1b04e8b2610ad4880
318
cpp
C++
Source/Core/RectangleGeometry.cpp
thavlik/iridium
8051e7ed6aefd42552e5737aff3d20fd0b844eda
[ "MIT" ]
1
2017-09-08T04:26:19.000Z
2017-09-08T04:26:19.000Z
Source/Core/RectangleGeometry.cpp
thavlik/iridium
8051e7ed6aefd42552e5737aff3d20fd0b844eda
[ "MIT" ]
null
null
null
Source/Core/RectangleGeometry.cpp
thavlik/iridium
8051e7ed6aefd42552e5737aff3d20fd0b844eda
[ "MIT" ]
null
null
null
#include "RectangleGeometry.h" namespace Ir { RectangleGeometry::RectangleGeometry(Object* parent) : Geometry(parent) { OBJECT_PROPERTY( Top ); OBJECT_PROPERTY( Right ); OBJECT_PROPERTY( Bottom ); OBJECT_PROPERTY( Left ); } bool RectangleGeometry::ContainsPoint(vec2f point) const { return false; } }
21.2
59
0.735849
[ "geometry", "object" ]
134a6fccc8abcffa81be3f085c5fd1d0355bbe27
6,196
cpp
C++
Projects/kirikiri2-master/kirikiri2/src/core/utils/win32/DebugImpl.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
2
2020-02-25T15:18:53.000Z
2020-08-24T13:30:34.000Z
Projects/kirikiri2-master/kirikiri2/src/core/utils/win32/DebugImpl.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
null
null
null
Projects/kirikiri2-master/kirikiri2/src/core/utils/win32/DebugImpl.cpp
CATION-M/X-moe
2bac3bb45ff21e50921aac8422f2e00839f546e5
[ "MIT" ]
1
2019-11-25T05:29:30.000Z
2019-11-25T05:29:30.000Z
//--------------------------------------------------------------------------- /* TVP2 ( T Visual Presenter 2 ) A script authoring tool Copyright (C) 2000 W.Dee <dee@kikyou.info> and contributors See details of license at "license.txt" */ //--------------------------------------------------------------------------- // Utilities for Debugging //--------------------------------------------------------------------------- #include "tjsCommHead.h" #include "DebugImpl.h" #include "MainFormUnit.h" //--------------------------------------------------------------------------- // on-error hook //--------------------------------------------------------------------------- void TVPOnErrorHook() { if(TVPMainForm) TVPMainForm->NotifySystemError(); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // tTJSNC_Controller : TJS Controller Class //--------------------------------------------------------------------------- class tTJSNC_Controller : public tTJSNativeClass { public: tTJSNC_Controller(); static tjs_uint32 ClassID; }; //--------------------------------------------------------------------------- tjs_uint32 tTJSNC_Controller::ClassID = (tjs_uint32)-1; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- tTJSNC_Controller::tTJSNC_Controller() : tTJSNativeClass(TJS_W("Controller")) { TJS_BEGIN_NATIVE_MEMBERS(Debug) TJS_DECL_EMPTY_FINALIZE_METHOD //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_CONSTRUCTOR_DECL_NO_INSTANCE(/*TJS class name*/Controller) { return TJS_S_OK; } TJS_END_NATIVE_CONSTRUCTOR_DECL(/*TJS class name*/Controller) //---------------------------------------------------------------------- // properties //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_PROP_DECL(visible) { TJS_BEGIN_NATIVE_PROP_GETTER { *result = TVPMainForm->Visible; return TJS_S_OK; } TJS_END_NATIVE_PROP_GETTER TJS_BEGIN_NATIVE_PROP_SETTER { TVPMainForm->Visible = param->operator bool(); return TJS_S_OK; } TJS_END_NATIVE_PROP_SETTER } TJS_END_NATIVE_STATIC_PROP_DECL(visible) //---------------------------------------------------------------------- TJS_END_NATIVE_MEMBERS } //--------------------------------------------------------------------------- static iTJSDispatch2 * TVPGetControllerClass() { struct tClassHolder { iTJSDispatch2 *Object; tClassHolder() { Object = new tTJSNC_Controller(); } ~tClassHolder() { Object->Release(); } } static Holder; Holder.Object->AddRef(); return Holder.Object; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // tTJSNC_Console : TJS Console Class //--------------------------------------------------------------------------- class tTJSNC_Console : public tTJSNativeClass { public: tTJSNC_Console(); static tjs_uint32 ClassID; }; //--------------------------------------------------------------------------- tjs_uint32 tTJSNC_Console::ClassID = (tjs_uint32)-1; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- tTJSNC_Console::tTJSNC_Console() : tTJSNativeClass(TJS_W("Console")) { TJS_BEGIN_NATIVE_MEMBERS(Debug) TJS_DECL_EMPTY_FINALIZE_METHOD //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_CONSTRUCTOR_DECL_NO_INSTANCE(/*TJS class name*/Console) { return TJS_S_OK; } TJS_END_NATIVE_CONSTRUCTOR_DECL(/*TJS class name*/Console) //---------------------------------------------------------------------- // properties //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_PROP_DECL(visible) { TJS_BEGIN_NATIVE_PROP_GETTER { *result = TVPMainForm->GetConsoleVisible(); return TJS_S_OK; } TJS_END_NATIVE_PROP_GETTER TJS_BEGIN_NATIVE_PROP_SETTER { bool visible = param->operator bool(); TVPMainForm->SetConsoleVisible(visible); return TJS_S_OK; } TJS_END_NATIVE_PROP_SETTER } TJS_END_NATIVE_STATIC_PROP_DECL(visible) //---------------------------------------------------------------------- TJS_END_NATIVE_MEMBERS } //--------------------------------------------------------------------------- static iTJSDispatch2 * TVPGetConsoleClass() { struct tClassHolder { iTJSDispatch2 *Object; tClassHolder() { Object = new tTJSNC_Console(); } ~tClassHolder() { Object->Release(); } } static Holder; Holder.Object->AddRef(); return Holder.Object; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // tTJSNC_Debug //--------------------------------------------------------------------------- tTJSNativeInstance *tTJSNC_Debug::CreateNativeInstance() { return NULL; } //--------------------------------------------------------------------------- tTJSNativeClass * TVPCreateNativeClass_Debug() { tTJSNativeClass *cls = new tTJSNC_Debug(); //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_PROP_DECL(controller) { TJS_BEGIN_NATIVE_PROP_GETTER { iTJSDispatch2 *dsp = TVPGetControllerClass(); *result = tTJSVariant(dsp, dsp); dsp->Release(); return TJS_S_OK; } TJS_END_NATIVE_PROP_GETTER TJS_DENY_NATIVE_PROP_SETTER } TJS_END_NATIVE_STATIC_PROP_DECL_OUTER(cls, controller) //---------------------------------------------------------------------- TJS_BEGIN_NATIVE_PROP_DECL(console) { TJS_BEGIN_NATIVE_PROP_GETTER { iTJSDispatch2 *dsp = TVPGetConsoleClass(); *result = tTJSVariant(dsp, dsp); dsp->Release(); return TJS_S_OK; } TJS_END_NATIVE_PROP_GETTER TJS_DENY_NATIVE_PROP_SETTER } TJS_END_NATIVE_STATIC_PROP_DECL_OUTER(cls, console) //---------------------------------------------------------------------- return cls; } //---------------------------------------------------------------------------
28.163636
77
0.442059
[ "object" ]
134af1540a7e708eb234727f3a46856d1a70b489
16,112
cc
C++
contrib/cryptomb/private_key_providers/test/ops_test.cc
giantcroc/envoy
c535d5abf8d106925070fe6fd018a716e6bf2bf1
[ "Apache-2.0" ]
1
2022-02-15T23:04:31.000Z
2022-02-15T23:04:31.000Z
contrib/cryptomb/private_key_providers/test/ops_test.cc
giantcroc/envoy
c535d5abf8d106925070fe6fd018a716e6bf2bf1
[ "Apache-2.0" ]
299
2021-04-26T10:25:02.000Z
2022-03-31T22:39:46.000Z
contrib/cryptomb/private_key_providers/test/ops_test.cc
giantcroc/envoy
c535d5abf8d106925070fe6fd018a716e6bf2bf1
[ "Apache-2.0" ]
1
2021-04-30T08:07:12.000Z
2021-04-30T08:07:12.000Z
#include <memory> #include <string> #include <vector> #include "source/extensions/transport_sockets/tls/private_key/private_key_manager_impl.h" #include "test/common/stats/stat_test_utility.h" #include "test/test_common/environment.h" #include "test/test_common/simulated_time_system.h" #include "test/test_common/utility.h" #include "contrib/cryptomb/private_key_providers/source/cryptomb_private_key_provider.h" #include "fake_factory.h" #include "gtest/gtest.h" namespace Envoy { namespace Extensions { namespace PrivateKeyMethodProvider { namespace CryptoMb { // Testing interface ssl_private_key_result_t privateKeyCompleteForTest(CryptoMbPrivateKeyConnection* ops, uint8_t* out, size_t* out_len, size_t max_out); ssl_private_key_result_t ecdsaPrivateKeySignForTest(CryptoMbPrivateKeyConnection* ops, uint8_t* out, size_t* out_len, size_t max_out, uint16_t signature_algorithm, const uint8_t* in, size_t in_len); ssl_private_key_result_t rsaPrivateKeySignForTest(CryptoMbPrivateKeyConnection* ops, uint8_t* out, size_t* out_len, size_t max_out, uint16_t signature_algorithm, const uint8_t* in, size_t in_len); ssl_private_key_result_t rsaPrivateKeyDecryptForTest(CryptoMbPrivateKeyConnection* ops, uint8_t* out, size_t* out_len, size_t max_out, const uint8_t* in, size_t in_len); namespace { class TestCallbacks : public Envoy::Ssl::PrivateKeyConnectionCallbacks { public: void onPrivateKeyMethodComplete() override{ }; }; class CryptoMbProviderTest : public testing::Test { protected: CryptoMbProviderTest() : api_(Api::createApiForTest(store_, time_system_)), dispatcher_(api_->allocateDispatcher("test_thread")), fakeIpp_(std::make_shared<FakeIppCryptoImpl>(true)), stats_(generateCryptoMbStats("cryptomb", store_)) {} bssl::UniquePtr<EVP_PKEY> makeRsaKey() { std::string file = TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/contrib/cryptomb/private_key_providers/test/test_data/rsa-1024.pem")); bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(file.data(), file.size())); bssl::UniquePtr<EVP_PKEY> key(EVP_PKEY_new()); RSA* rsa = PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, nullptr, nullptr); RELEASE_ASSERT(rsa != nullptr, "PEM_read_bio_RSAPrivateKey failed."); RELEASE_ASSERT(1 == EVP_PKEY_assign_RSA(key.get(), rsa), "EVP_PKEY_assign_RSA failed."); return key; } bssl::UniquePtr<EVP_PKEY> makeEcdsaKey() { std::string file = TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir " "}}/contrib/cryptomb/private_key_providers/test/test_data/ecdsa-p256.pem")); bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(file.data(), file.size())); bssl::UniquePtr<EVP_PKEY> key(EVP_PKEY_new()); EC_KEY* ec = PEM_read_bio_ECPrivateKey(bio.get(), nullptr, nullptr, nullptr); RELEASE_ASSERT(ec != nullptr, "PEM_read_bio_ECPrivateKey failed."); RELEASE_ASSERT(1 == EVP_PKEY_assign_EC_KEY(key.get(), ec), "EVP_PKEY_assign_EC_KEY failed."); return key; } Stats::TestUtil::TestStore store_; Api::ApiPtr api_; Event::SimulatedTimeSystem time_system_; Event::DispatcherPtr dispatcher_; std::shared_ptr<FakeIppCryptoImpl> fakeIpp_; CryptoMbStats stats_; // Result of an operation. ssl_private_key_result_t res_; // A size for signing and decryption operation input chosen for tests. static constexpr size_t in_len_ = 32; // Test input bytes for signing and decryption chosen for tests. static constexpr uint8_t in_[in_len_] = {0x7f}; // Maximum size of out_ in all tests cases. static constexpr size_t max_out_len_ = 128; uint8_t out_[max_out_len_] = {0}; // Size of output in out_ from an operation. size_t out_len_ = 0; const std::string queue_size_histogram_name_ = "cryptomb.rsa_queue_sizes"; }; class CryptoMbProviderRsaTest : public CryptoMbProviderTest { protected: CryptoMbProviderRsaTest() : queue_(std::chrono::milliseconds(200), KeyType::Rsa, 1024, fakeIpp_, *dispatcher_, stats_), pkey_(makeRsaKey()) { RSA* rsa = EVP_PKEY_get0_RSA(pkey_.get()); fakeIpp_->setRsaKey(rsa); } CryptoMbQueue queue_; bssl::UniquePtr<EVP_PKEY> pkey_; }; class CryptoMbProviderEcdsaTest : public CryptoMbProviderTest { protected: CryptoMbProviderEcdsaTest() : queue_(std::chrono::milliseconds(200), KeyType::Ec, 256, fakeIpp_, *dispatcher_, stats_), pkey_(makeEcdsaKey()) {} CryptoMbQueue queue_; bssl::UniquePtr<EVP_PKEY> pkey_; }; TEST_F(CryptoMbProviderEcdsaTest, TestEcdsaSigning) { TestCallbacks cb; CryptoMbPrivateKeyConnection op(cb, *dispatcher_, bssl::UpRef(pkey_), queue_); res_ = ecdsaPrivateKeySignForTest(&op, out_, &out_len_, max_out_len_, SSL_SIGN_ECDSA_SECP256R1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_success); } TEST_F(CryptoMbProviderRsaTest, TestRsaPkcs1Signing) { // Initialize connections. TestCallbacks cbs[CryptoMbQueue::MULTIBUFF_BATCH]; std::vector<std::unique_ptr<CryptoMbPrivateKeyConnection>> connections; for (auto& cb : cbs) { connections.push_back(std::make_unique<CryptoMbPrivateKeyConnection>( cb, *dispatcher_, bssl::UpRef(pkey_), queue_)); } // Create MULTIBUFF_BATCH amount of signing operations. for (uint32_t i = 0; i < CryptoMbQueue::MULTIBUFF_BATCH; i++) { // Create request. res_ = rsaPrivateKeySignForTest(connections[i].get(), nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PKCS1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); // No processing done after first requests. // After the last request, the status is set only from the event loop which is not run. This // should still be "retry", the cryptographic result is present anyway. res_ = privateKeyCompleteForTest(connections[i].get(), nullptr, nullptr, max_out_len_); EXPECT_EQ(res_, ssl_private_key_retry); } // Timeout does not have to be triggered when queue is at maximum size. dispatcher_->run(Event::Dispatcher::RunType::NonBlock); res_ = privateKeyCompleteForTest(connections[0].get(), out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); } TEST_F(CryptoMbProviderRsaTest, TestRsaPssSigning) { // Initialize connections. TestCallbacks cbs[CryptoMbQueue::MULTIBUFF_BATCH]; std::vector<std::unique_ptr<CryptoMbPrivateKeyConnection>> connections; for (auto& cb : cbs) { connections.push_back(std::make_unique<CryptoMbPrivateKeyConnection>( cb, *dispatcher_, bssl::UpRef(pkey_), queue_)); } // Create MULTIBUFF_BATCH amount of signing operations. for (uint32_t i = 0; i < CryptoMbQueue::MULTIBUFF_BATCH; i++) { // Create request. res_ = rsaPrivateKeySignForTest(connections[i].get(), nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PSS_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); // No processing done after first requests. // After the last request, the status is set only from the event loop which is not run. This // should still be "retry", the cryptographic result is present anyway. res_ = privateKeyCompleteForTest(connections[i].get(), nullptr, nullptr, max_out_len_); EXPECT_EQ(res_, ssl_private_key_retry); } // Timeout does not have to be triggered when queue is at maximum size. dispatcher_->run(Event::Dispatcher::RunType::NonBlock); res_ = privateKeyCompleteForTest(connections[0].get(), out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); } TEST_F(CryptoMbProviderRsaTest, TestRsaDecrypt) { // Initialize connections. TestCallbacks cbs[CryptoMbQueue::MULTIBUFF_BATCH]; std::vector<std::unique_ptr<CryptoMbPrivateKeyConnection>> connections; for (auto& cb : cbs) { connections.push_back(std::make_unique<CryptoMbPrivateKeyConnection>( cb, *dispatcher_, bssl::UpRef(pkey_), queue_)); } // Create MULTIBUFF_BATCH amount of decryption operations. for (uint32_t i = 0; i < CryptoMbQueue::MULTIBUFF_BATCH; i++) { // Create request. res_ = rsaPrivateKeyDecryptForTest(connections[i].get(), nullptr, nullptr, max_out_len_, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); // No processing done after first requests. // After the last request, the status is set only from the event loop which is not run. This // should still be "retry", the cryptographic result is present anyway. res_ = privateKeyCompleteForTest(connections[i].get(), nullptr, nullptr, max_out_len_); EXPECT_EQ(res_, ssl_private_key_retry); } // Timeout does not have to be triggered when queue is at maximum size. dispatcher_->run(Event::Dispatcher::RunType::NonBlock); res_ = privateKeyCompleteForTest(connections[0].get(), out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); } TEST_F(CryptoMbProviderTest, TestErrors) { bssl::UniquePtr<EVP_PKEY> pkey = makeEcdsaKey(); bssl::UniquePtr<EVP_PKEY> rsa_pkey = makeRsaKey(); CryptoMbQueue ec_queue(std::chrono::milliseconds(200), KeyType::Ec, 256, fakeIpp_, *dispatcher_, stats_); CryptoMbQueue rsa_queue(std::chrono::milliseconds(200), KeyType::Rsa, 1024, fakeIpp_, *dispatcher_, stats_); TestCallbacks cb; CryptoMbPrivateKeyConnection op_ec(cb, *dispatcher_, bssl::UpRef(pkey), ec_queue); CryptoMbPrivateKeyConnection op_rsa(cb, *dispatcher_, bssl::UpRef(rsa_pkey), rsa_queue); // no operation defined res_ = ecdsaPrivateKeySignForTest(nullptr, nullptr, nullptr, max_out_len_, SSL_SIGN_ECDSA_SECP256R1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeySignForTest(nullptr, nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PSS_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeyDecryptForTest(nullptr, nullptr, nullptr, max_out_len_, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); // Unknown signature algorithm res_ = ecdsaPrivateKeySignForTest(&op_ec, nullptr, nullptr, max_out_len_, 1234, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeySignForTest(&op_rsa, nullptr, nullptr, max_out_len_, 1234, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); // Wrong signature algorithm res_ = ecdsaPrivateKeySignForTest(&op_ec, nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PSS_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeySignForTest(&op_rsa, nullptr, nullptr, max_out_len_, SSL_SIGN_ECDSA_SECP256R1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); // Wrong operation type res_ = ecdsaPrivateKeySignForTest(&op_rsa, nullptr, nullptr, max_out_len_, SSL_SIGN_ECDSA_SECP256R1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeySignForTest(&op_ec, nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PSS_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); res_ = rsaPrivateKeyDecryptForTest(&op_ec, nullptr, nullptr, max_out_len_, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_failure); } TEST_F(CryptoMbProviderRsaTest, TestRSATimer) { TestCallbacks cbs[2]; // Successful operation with timer. CryptoMbPrivateKeyConnection op0(cbs[0], *dispatcher_, bssl::UpRef(pkey_), queue_); res_ = rsaPrivateKeySignForTest(&op0, nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PKCS1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); res_ = privateKeyCompleteForTest(&op0, nullptr, nullptr, max_out_len_); // No processing done yet after first request EXPECT_EQ(res_, ssl_private_key_retry); time_system_.advanceTimeAndRun(std::chrono::seconds(1), *dispatcher_, Event::Dispatcher::RunType::NonBlock); res_ = privateKeyCompleteForTest(&op0, out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); // Unsuccessful operation with timer. // Add crypto library errors fakeIpp_->injectErrors(true); CryptoMbPrivateKeyConnection op1(cbs[1], *dispatcher_, bssl::UpRef(pkey_), queue_); res_ = rsaPrivateKeySignForTest(&op1, nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PKCS1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); res_ = privateKeyCompleteForTest(&op1, nullptr, nullptr, max_out_len_); // No processing done yet after first request EXPECT_EQ(res_, ssl_private_key_retry); time_system_.advanceTimeAndRun(std::chrono::seconds(1), *dispatcher_, Event::Dispatcher::RunType::NonBlock); res_ = privateKeyCompleteForTest(&op1, out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_failure); } TEST_F(CryptoMbProviderRsaTest, TestRSAQueueSizeStatistics) { // Initialize connections. TestCallbacks cbs[CryptoMbQueue::MULTIBUFF_BATCH]; std::vector<std::unique_ptr<CryptoMbPrivateKeyConnection>> connections; for (auto& cb : cbs) { connections.push_back(std::make_unique<CryptoMbPrivateKeyConnection>( cb, *dispatcher_, bssl::UpRef(pkey_), queue_)); } // Increment all but the last queue size once inside the loop. for (uint32_t i = 1; i < CryptoMbQueue::MULTIBUFF_BATCH; i++) { // Create correct amount of signing operations for current index. for (uint32_t j = 0; j < i; j++) { res_ = rsaPrivateKeySignForTest(connections[j].get(), nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PKCS1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); } time_system_.advanceTimeAndRun(std::chrono::seconds(1), *dispatcher_, Event::Dispatcher::RunType::NonBlock); out_len_ = 0; res_ = privateKeyCompleteForTest(connections[0].get(), out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); // Check that current queue size is recorded. std::vector<uint64_t> histogram_values( store_.histogramValues(queue_size_histogram_name_, true)); EXPECT_EQ(histogram_values.size(), 1); EXPECT_EQ(histogram_values[0], i); } // Increment last queue size once. // Create an amount of signing operations equal to maximum queue size. for (uint32_t j = 0; j < CryptoMbQueue::MULTIBUFF_BATCH; j++) { res_ = rsaPrivateKeySignForTest(connections[j].get(), nullptr, nullptr, max_out_len_, SSL_SIGN_RSA_PKCS1_SHA256, in_, in_len_); EXPECT_EQ(res_, ssl_private_key_retry); } // Timeout does not have to be triggered when queue is at maximum size. dispatcher_->run(Event::Dispatcher::RunType::NonBlock); out_len_ = 0; res_ = privateKeyCompleteForTest(connections[0].get(), out_, &out_len_, max_out_len_); EXPECT_EQ(res_, ssl_private_key_success); EXPECT_NE(out_len_, 0); // Check that last queue size is recorded. std::vector<uint64_t> histogram_values(store_.histogramValues(queue_size_histogram_name_, true)); EXPECT_EQ(histogram_values.size(), 1); EXPECT_EQ(histogram_values[0], CryptoMbQueue::MULTIBUFF_BATCH); } } // namespace } // namespace CryptoMb } // namespace PrivateKeyMethodProvider } // namespace Extensions } // namespace Envoy
42.624339
100
0.705809
[ "vector" ]
1357b43cc845d9e01862df5bfbd6bb458e7827ab
15,465
cpp
C++
test/parser.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
test/parser.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
test/parser.cpp
WillCoates/QuickCalc
49a4946c5c9b3781d1d5820815bda8395a8ed0dd
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <vector> #include "parser.hpp" using namespace quickcalc; namespace { class MockLexer: public ILexer { std::vector<Token> _tokens; int _offset; public: MockLexer(std::vector<Token> &&tokens): _tokens(std::move(tokens)), _offset(0) { } Token read() override { if (_offset == _tokens.size()) { return {}; } return _tokens[_offset++]; } Token peek() override { if (_offset == _tokens.size()) { return {}; } return _tokens[_offset]; } }; void testParser(MockLexer &lexer, std::unique_ptr<StmtNode> &expected) { Parser parser(lexer); std::unique_ptr<StmtNode> actual = parser.parse(); EXPECT_EQ(*actual, *expected); } void testParserThrows(MockLexer &lexer) { Parser parser(lexer); EXPECT_THROW(parser.parse(), std::runtime_error); } } TEST(parser, ParseNumber) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 } }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<ConstNode>(1.0) ); testParser(lexer, expected); } TEST(parser, ParseAddition) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::ADD }, { 2, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ) ); testParser(lexer, expected); } TEST(parser, ParseSubtraction) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::SUBTRACT }, { 2, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::SUBTRACT, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ) ); testParser(lexer, expected); } TEST(parser, ParseMultiplication) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::MULTIPLY }, { 2, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::MULTIPLY, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ) ); testParser(lexer, expected); } TEST(parser, ParseDivision) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::DIVIDE }, { 2, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::DIVIDE, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ) ); testParser(lexer, expected); } TEST(parser, ParseMultipleAddition) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::ADD }, { 2, 0, TokenType::NUMBER, 2.0 }, { 3, 0, TokenType::SYMBOL, Symbol::ADD }, { 4, 0, TokenType::NUMBER, 3.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(2.0), std::make_unique<ConstNode>(3.0) ) ) ); testParser(lexer, expected); } TEST(parser, ParseAddMul) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::ADD }, { 2, 0, TokenType::NUMBER, 2.0 }, { 3, 0, TokenType::SYMBOL, Symbol::MULTIPLY }, { 4, 0, TokenType::NUMBER, 3.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<BinaryOperationNode>( BinaryOperation::MULTIPLY, std::make_unique<ConstNode>(2.0), std::make_unique<ConstNode>(3.0) ) ) ); testParser(lexer, expected); } TEST(parser, ParseMulAdd) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::MULTIPLY }, { 2, 0, TokenType::NUMBER, 2.0 }, { 3, 0, TokenType::SYMBOL, Symbol::ADD }, { 4, 0, TokenType::NUMBER, 3.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<BinaryOperationNode>( BinaryOperation::MULTIPLY, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ), std::make_unique<ConstNode>(3.0) ) ); testParser(lexer, expected); } TEST(parser, ParseBrackets) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::MULTIPLY }, { 2, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 3, 0, TokenType::NUMBER, 2.0 }, { 4, 0, TokenType::SYMBOL, Symbol::ADD }, { 5, 0, TokenType::NUMBER, 3.0 }, { 6, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::MULTIPLY, std::make_unique<ConstNode>(1.0), std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(2.0), std::make_unique<ConstNode>(3.0) ) ) ); testParser(lexer, expected); } TEST(parser, ParseNegation) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::SYMBOL, Symbol::SUBTRACT }, { 1, 0, TokenType::NUMBER, 1.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<UnaryOperationNode>( UnaryOperation::NEGATE, std::make_unique<ConstNode>(1.0) ) ); testParser(lexer, expected); } TEST(parser, ParseNegationWithBrackets) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::SYMBOL, Symbol::SUBTRACT }, { 1, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 2, 0, TokenType::NUMBER, 1.0 }, { 3, 0, TokenType::SYMBOL, Symbol::ADD }, { 4, 0, TokenType::NUMBER, 2.0 }, { 5, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<UnaryOperationNode>( UnaryOperation::NEGATE, std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ) ) ); testParser(lexer, expected); } TEST(parser, SequentalNumberFail) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::NUMBER, 2.0 }, }); testParserThrows(lexer); } TEST(parser, RogueClosedBracketFail) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, }); testParserThrows(lexer); } TEST(parser, ForgotCloseBracketFail) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 1, 0, TokenType::NUMBER, 1.0 }, }); testParserThrows(lexer); } TEST(parse, ParseMultiple) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NUMBER, 1.0 }, { 1, 0, TokenType::END_OF_STMT }, { 2, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expectedA = std::make_unique<ExprStmtNode>( std::make_unique<ConstNode>(1.0) ); std::unique_ptr<StmtNode> expectedB = std::make_unique<ExprStmtNode>( std::make_unique<ConstNode>(2.0) ); testParser(lexer, expectedA); testParser(lexer, expectedB); } TEST(parser, ParseFunctionDefinitionNoArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::KEYWORD, Keyword::LET }, { 1, 0, TokenType::NAME, "foo" }, { 2, 0, TokenType::SYMBOL, Symbol::EQUALS }, { 3, 0, TokenType::NUMBER, 1.0 }, { 4, 0, TokenType::SYMBOL, Symbol::ADD }, { 5, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<FuncDefNode>( "foo", std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ), std::vector<std::string>() ); testParser(lexer, expected); } TEST(parser, ParseFunctionDefinitionWithSingleArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::KEYWORD, Keyword::LET }, { 1, 0, TokenType::NAME, "foo" }, { 2, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 3, 0, TokenType::NAME, "a" }, { 4, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, { 5, 0, TokenType::SYMBOL, Symbol::EQUALS }, { 6, 0, TokenType::NUMBER, 1.0 }, { 7, 0, TokenType::SYMBOL, Symbol::ADD }, { 8, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<FuncDefNode>( "foo", std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ), std::vector<std::string>({"a"}) ); testParser(lexer, expected); } TEST(parser, ParseFunctionDefinitionWithMultiArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::KEYWORD, Keyword::LET }, { 1, 0, TokenType::NAME, "foo" }, { 2, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 3, 0, TokenType::NAME, "a" }, { 4, 0, TokenType::SYMBOL, Symbol::COMMA }, { 5, 0, TokenType::NAME, "b" }, { 6, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, { 7, 0, TokenType::SYMBOL, Symbol::EQUALS }, { 8, 0, TokenType::NUMBER, 1.0 }, { 9, 0, TokenType::SYMBOL, Symbol::ADD }, { 10, 0, TokenType::NUMBER, 2.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<FuncDefNode>( "foo", std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) ), std::vector<std::string>({"a", "b"}) ); testParser(lexer, expected); } TEST(parser, ParseInvokeNoArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NAME, "foo" }, { 1, 0, TokenType::SYMBOL, Symbol::ADD }, { 2, 0, TokenType::NUMBER, 1.0 }, }); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<FunctionInvocationNode>("foo", std::vector<std::unique_ptr<ExprNode>>()), std::make_unique<ConstNode>(1.0) ) ); testParser(lexer, expected); } TEST(parser, ParseInvokeSingleArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NAME, "foo" }, { 1, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 2, 0, TokenType::NUMBER, 1.0 }, { 3, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, { 4, 0, TokenType::SYMBOL, Symbol::ADD }, { 5, 0, TokenType::NUMBER, 2.0 }, }); std::vector<std::unique_ptr<ExprNode>> params; params.push_back(std::make_unique<ConstNode>(1.0)); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<FunctionInvocationNode>("foo", std::move(params)), std::make_unique<ConstNode>(2.0) ) ); testParser(lexer, expected); } TEST(parser, ParseInvokeMultiArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NAME, "foo" }, { 1, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 2, 0, TokenType::NUMBER, 1.0 }, { 3, 0, TokenType::SYMBOL, Symbol::COMMA }, { 4, 0, TokenType::NUMBER, 2.0 }, { 5, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, { 6, 0, TokenType::SYMBOL, Symbol::ADD }, { 7, 0, TokenType::NUMBER, 3.0 }, }); std::vector<std::unique_ptr<ExprNode>> params; params.push_back(std::make_unique<ConstNode>(1.0)); params.push_back(std::make_unique<ConstNode>(2.0)); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<FunctionInvocationNode>("foo", std::move(params)), std::make_unique<ConstNode>(3.0) ) ); testParser(lexer, expected); } TEST(parser, ParseInvokeComplexArg) { MockLexer lexer = MockLexer({ { 0, 0, TokenType::NAME, "foo" }, { 1, 0, TokenType::SYMBOL, Symbol::BRACKET_OPEN }, { 2, 0, TokenType::NUMBER, 1.0 }, { 3, 0, TokenType::SYMBOL, Symbol::ADD }, { 4, 0, TokenType::NUMBER, 2.0 }, { 5, 0, TokenType::SYMBOL, Symbol::BRACKET_CLOSE }, { 6, 0, TokenType::SYMBOL, Symbol::ADD }, { 7, 0, TokenType::NUMBER, 3.0 }, }); std::vector<std::unique_ptr<ExprNode>> params; params.push_back(std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<ConstNode>(1.0), std::make_unique<ConstNode>(2.0) )); std::unique_ptr<StmtNode> expected = std::make_unique<ExprStmtNode>( std::make_unique<BinaryOperationNode>( BinaryOperation::ADD, std::make_unique<FunctionInvocationNode>("foo", std::move(params)), std::make_unique<ConstNode>(3.0) ) ); testParser(lexer, expected); }
33.766376
106
0.548723
[ "vector" ]
135fbfbf0717f174ea39ebe5285bd17d0ac40c6d
15,278
cpp
C++
BonDriver_mirakc.cpp
epgdatacapbon/BonDriver_mirakc
e158a9a6e9460c1b7d816fba96137077201692d9
[ "MIT" ]
6
2020-03-08T20:14:47.000Z
2021-09-20T16:49:06.000Z
BonDriver_mirakc.cpp
epgdatacapbon/BonDriver_Mirakurun
e158a9a6e9460c1b7d816fba96137077201692d9
[ "MIT" ]
2
2021-06-01T01:10:17.000Z
2022-01-19T14:51:03.000Z
BonDriver_mirakc.cpp
epgdatacapbon/BonDriver_Mirakurun
e158a9a6e9460c1b7d816fba96137077201692d9
[ "MIT" ]
2
2020-05-23T02:17:45.000Z
2021-02-03T07:55:38.000Z
#include "BonDriver_mirakc.h" ////////////////////////////////////////////////////////////////////// // DLLMain ////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: if (Init(hModule) != 0) { return FALSE; } // モジュールハンドル保存 CBonTuner::m_hModule = hModule; break; case DLL_PROCESS_DETACH: // 未開放の場合はインスタンス開放 if (CBonTuner::m_pThis) { CBonTuner::m_pThis->Release(); } break; } return TRUE; } static int Init(HMODULE hModule) { GetModuleFileName(hModule, g_IniFilePath, MAX_PATH); wchar_t drive[_MAX_DRIVE]; wchar_t dir[_MAX_DIR]; wchar_t fname[_MAX_FNAME]; _wsplitpath_s(g_IniFilePath, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, NULL, NULL); wsprintf(g_IniFilePath, L"%s%s%s.ini\0", drive, dir, fname); HANDLE hFile = CreateFile(g_IniFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { return -2; } CloseHandle(hFile); GetPrivateProfileStringW(L"GLOBAL", L"SERVER_HOST", L"localhost" , g_ServerHost, MAX_HOST_LEN, g_IniFilePath); g_ServerPort = GetPrivateProfileInt( L"GLOBAL", L"SERVER_PORT", 40772, g_IniFilePath); g_DecodeB25 = GetPrivateProfileInt( L"GLOBAL", L"DECODE_B25", 0, g_IniFilePath); g_Priority = GetPrivateProfileInt( L"GLOBAL", L"PRIORITY", 0, g_IniFilePath); g_Service_Split = GetPrivateProfileInt( L"GLOBAL", L"SERVICE_SPLIT", 0, g_IniFilePath); return 0; } ////////////////////////////////////////////////////////////////////// // インスタンス生成メソッド ////////////////////////////////////////////////////////////////////// extern "C" __declspec(dllexport) IBonDriver * CreateBonDriver() { // スタンス生成(既存の場合はインスタンスのポインタを返す) return (CBonTuner::m_pThis)? CBonTuner::m_pThis : ((IBonDriver *) new CBonTuner); } ////////////////////////////////////////////////////////////////////// // 構築/消滅 ////////////////////////////////////////////////////////////////////// // 静的メンバ初期化 CBonTuner * CBonTuner::m_pThis = NULL; HINSTANCE CBonTuner::m_hModule = NULL; CBonTuner::CBonTuner() : m_hMutex(NULL) , m_hOnStreamEvent(NULL) , m_hStopEvent(NULL) , m_hRecvThread(NULL) , m_pGrabTsData(NULL) , hSession(NULL) , hConnect(NULL) , hRequest(NULL) , m_dwCurSpace(0xffffffff) , m_dwCurChannel(0xffffffff) { m_pThis = this; ::InitializeCriticalSection(&m_CriticalSection); // GrabTsDataインスタンス作成 m_pGrabTsData = new GrabTsData(&m_hOnStreamEvent); } CBonTuner::~CBonTuner() { // 開かれてる場合は閉じる CloseTuner(); // GrabTsDataインスタンス開放 if (m_pGrabTsData) { delete m_pGrabTsData; } ::DeleteCriticalSection(&m_CriticalSection); m_pThis = NULL; } const BOOL CBonTuner::OpenTuner() { while (1) { // ミューテックス作成 m_hMutex = ::CreateMutexA(NULL, TRUE, g_TunerName); if (!m_hMutex) { break; } // イベントオブジェクト作成 g_hCloseEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); m_hOnStreamEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); m_hStopEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); if (!g_hCloseEvent || !m_hOnStreamEvent || !m_hStopEvent) { break; } // WinHTTP初期化 hSession = WinHttpOpen( TEXT(TUNER_NAME "/1.0"), WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) { char szDebugOut[64]; sprintf_s(szDebugOut, "%s: WinHTTP not supported\n", g_TunerName); ::OutputDebugStringA(szDebugOut); break; } // サーバー接続 hConnect = WinHttpConnect(hSession, g_ServerHost, g_ServerPort, 0); if (!hConnect) { char szDebugOut[64]; sprintf_s(szDebugOut, "%s: Connection failed\n", g_TunerName); ::OutputDebugStringA(szDebugOut); break; } //Initialize channel if (!InitChannel()) { break; } // スレッド起動 m_hRecvThread = (HANDLE)_beginthreadex(NULL, 0, CBonTuner::RecvThread, (LPVOID)this, 0, NULL); if (!m_hRecvThread) { break; } //return SetChannel(0UL,0UL); return TRUE; } CloseTuner(); return FALSE; } void CBonTuner::CloseTuner() { // チャンネル初期化 m_dwCurSpace = 0xffffffff; m_dwCurChannel = 0xffffffff; // スレッド終了 if (m_hRecvThread) { ::SetEvent(m_hStopEvent); if (::WaitForSingleObject(m_hRecvThread, 10000) == WAIT_TIMEOUT) { // スレッド強制終了 ::TerminateThread(m_hRecvThread, 0xffffffff); char szDebugOut[64]; sprintf_s(szDebugOut, "%s: CloseTuner() ::TerminateThread\n", g_TunerName); ::OutputDebugStringA(szDebugOut); } ::CloseHandle(m_hRecvThread); m_hRecvThread = NULL; } // チューニング空間解放 for (int i = 0; i <= g_Max_Type; i++) { if (g_pType[i]) { free(g_pType[i]); } } g_Max_Type = -1; // WinHTTP開放 if (hRequest) { WinHttpCloseHandle(hRequest); ::WaitForSingleObject(g_hCloseEvent, 5000); hRequest = NULL; } if (hConnect) { WinHttpCloseHandle(hConnect); hConnect = NULL; } if (hSession) { WinHttpCloseHandle(hSession); hSession = NULL; } // イベントオブジェクト開放 if (m_hStopEvent) { ::CloseHandle(m_hStopEvent); m_hStopEvent = NULL; } if (m_hOnStreamEvent) { ::CloseHandle(m_hOnStreamEvent); m_hOnStreamEvent = NULL; } if (g_hCloseEvent) { ::CloseHandle(g_hCloseEvent); g_hCloseEvent = NULL; } // ミューテックス開放 if (m_hMutex) { ::ReleaseMutex(m_hMutex); ::CloseHandle(m_hMutex); m_hMutex = NULL; } } const DWORD CBonTuner::WaitTsStream(const DWORD dwTimeOut) { // 終了チェック if (!m_hOnStreamEvent) { return WAIT_ABANDONED; } // イベントがシグナル状態になるのを待つ const DWORD dwRet = ::WaitForSingleObject(m_hOnStreamEvent, (dwTimeOut) ? dwTimeOut : INFINITE); switch (dwRet) { case WAIT_ABANDONED : // チューナが閉じられた return WAIT_ABANDONED; case WAIT_OBJECT_0 : case WAIT_TIMEOUT : // ストリーム取得可能 return dwRet; case WAIT_FAILED : default: // 例外 return WAIT_FAILED; } } const DWORD CBonTuner::GetReadyCount() { DWORD dwCount = 0; if (m_pGrabTsData) { m_pGrabTsData->get_ReadyCount(&dwCount); } return dwCount; } const BOOL CBonTuner::GetTsStream(BYTE *pDst, DWORD *pdwSize, DWORD *pdwRemain) { BYTE *pSrc = NULL; // TSデータをバッファから取り出す if (GetTsStream(&pSrc, pdwSize, pdwRemain)) { if (*pdwSize) { ::CopyMemory(pDst, pSrc, *pdwSize); } return TRUE; } return FALSE; } const BOOL CBonTuner::GetTsStream(BYTE **ppDst, DWORD *pdwSize, DWORD *pdwRemain) { if (!m_pGrabTsData || m_dwCurChannel == 0xffffffff) { return FALSE; } return m_pGrabTsData->get_TsStream(ppDst, pdwSize, pdwRemain); } void CBonTuner::PurgeTsStream() { if (m_pGrabTsData) { m_pGrabTsData->purge_TsStream(); } } void CBonTuner::Release() { // インスタンス開放 delete this; } LPCTSTR CBonTuner::GetTunerName(void) { // チューナ名を返す return TEXT(TUNER_NAME); } const BOOL CBonTuner::IsTunerOpening(void) { // チューナの使用中の有無を返す(全プロセスを通して) HANDLE hMutex = ::OpenMutexA(MUTEX_ALL_ACCESS, FALSE, g_TunerName); if (hMutex) { // 既にチューナは開かれている ::CloseHandle(hMutex); return TRUE; } // チューナは開かれていない return FALSE; } LPCTSTR CBonTuner::EnumTuningSpace(const DWORD dwSpace) { if ((int32_t)dwSpace > g_Max_Type) { return NULL; } // 使用可能なチューニング空間を返す const int len = 8; static TCHAR buf[len]; ::MultiByteToWideChar(CP_UTF8, 0, g_pType[dwSpace], -1, buf, len); return buf; } LPCTSTR CBonTuner::EnumChannelName(const DWORD dwSpace, const DWORD dwChannel) { if ((int32_t)dwSpace > g_Max_Type) { return NULL; } if ((int32_t)dwSpace < g_Max_Type) { if (dwChannel >= g_Channel_Base[dwSpace + 1] - g_Channel_Base[dwSpace]) { return NULL; } } DWORD Bon_Channel = dwChannel + g_Channel_Base[dwSpace]; if (!g_Channel_JSON.contains(Bon_Channel)) { return NULL; } picojson::object& channel_obj = g_Channel_JSON.get(Bon_Channel).get<picojson::object>(); // 使用可能なチャンネル名を返す const int len = 128; static TCHAR buf[len]; ::MultiByteToWideChar(CP_UTF8, 0, channel_obj["name"].get<std::string>().c_str(), -1, buf, len); return buf; } const DWORD CBonTuner::GetCurSpace(void) { // 現在のチューニング空間を返す return m_dwCurSpace; } const DWORD CBonTuner::GetCurChannel(void) { // 現在のチャンネルを返す return m_dwCurChannel; } // チャンネル設定 const BOOL CBonTuner::SetChannel(const BYTE bCh) { return SetChannel((DWORD)0,(DWORD)bCh - 13); } // チャンネル設定 const BOOL CBonTuner::SetChannel(const DWORD dwSpace, const DWORD dwChannel) { if ((int32_t)dwSpace > g_Max_Type) { return FALSE; } DWORD Bon_Channel = dwChannel + g_Channel_Base[dwSpace]; if (!g_Channel_JSON.contains(Bon_Channel)) { return FALSE; } picojson::object& channel_obj = g_Channel_JSON.get(Bon_Channel).get<picojson::object>(); // Server request const int len = 64; wchar_t url[len]; if (g_Service_Split == 1) { const int64_t id = (int64_t)channel_obj["id"].get<double>(); swprintf_s(url, len, L"/api/services/%lld/stream?decode=%d", id, g_DecodeB25); } else { const char *type = channel_obj["type"].get<std::string>().c_str(); const char *channel = channel_obj["channel"].get<std::string>().c_str(); swprintf_s(url, len, L"/api/channels/%S/%S/stream?decode=%d", type, channel, g_DecodeB25); } if (!SendRequest(url)) { return TRUE; // to complete channel setting } // チャンネル情報更新 m_dwCurSpace = dwSpace; m_dwCurChannel = dwChannel; // TSデータパージ PurgeTsStream(); return TRUE; } // 信号レベル(ビットレート)取得 const float CBonTuner::GetSignalLevel(void) { // チャンネル番号不明時は0を返す float fSignalLevel = 0; if (m_dwCurChannel != 0xffffffff && m_pGrabTsData) m_pGrabTsData->get_Bitrate(&fSignalLevel); return fSignalLevel; } BOOL CBonTuner::InitChannel() { // mirakc APIよりchannel取得 if (!GetApiChannels(&g_Channel_JSON, g_Service_Split)) { return FALSE; } if (g_Channel_JSON.is<picojson::null>()) { return FALSE; } if (!g_Channel_JSON.contains(0)) { return FALSE; } // チューニング空間取得 int i = 0; int j = -1; while (j < SPACE_NUM - 1) { if (!g_Channel_JSON.contains(i)) { break; } picojson::object& channel_obj = g_Channel_JSON.get(i).get<picojson::object>(); const char *type; if (g_Service_Split == 1) { picojson::object& channel_detail = channel_obj["channel"].get<picojson::object>(); type = channel_detail["type"].get<std::string>().c_str(); } else { type = channel_obj["type"].get<std::string>().c_str(); } if (j < 0 || strcmp(g_pType[j], type)) { j++; int len = (int)strlen(type) + 1; g_pType[j] = (char *)malloc(len); if (!g_pType[j]) { j--; break; } strcpy_s(g_pType[j], len, type); g_Channel_Base[j] = i; } i++; } if (j < 0) { return FALSE; } g_Max_Type = j; return TRUE; } BOOL CBonTuner::GetApiChannels(picojson::value *channel_json, int service_split) { const int len = 14; wchar_t url[len]; wcscpy_s(url, len, L"/api/"); if (service_split == 1) { wcscat_s(url, len, L"services"); } else { wcscat_s(url, len, L"channels"); } if (!SendRequest(url)) { return FALSE; } char *data = NULL; char *prev = NULL; DWORD dwSize; DWORD dwTotalSize = 0; BOOL ret; while(1) { ret = WinHttpQueryDataAvailable(hRequest, &dwSize); if (ret && dwSize > 0) { data = (char *)malloc((size_t)dwTotalSize + dwSize + 1); if (!data) { if (prev) { free(prev); } return FALSE; } if (prev) { ::CopyMemory(data, prev, dwTotalSize); free(prev); } WinHttpReadData(hRequest, data + dwTotalSize, dwSize, NULL); prev = data; dwTotalSize += dwSize; } else { break; } } if (!data) { return FALSE; } *(data + dwTotalSize) = '\0'; picojson::value v; std::string err = picojson::parse(v, data); if (!err.empty()) { return FALSE; } *channel_json = v; free(data); return TRUE; } BOOL CBonTuner::SendRequest(wchar_t *url) { BOOL ret = FALSE; char szDebugOut[64]; ::EnterCriticalSection(&m_CriticalSection); while (1) { if (hRequest) { WinHttpCloseHandle(hRequest); ::Sleep(100); ::WaitForSingleObject(g_hCloseEvent, 5000); } hRequest = WinHttpOpenRequest( hConnect, L"GET", url, NULL, WINHTTP_NO_REFERER, NULL, 0); if (!hRequest) { sprintf_s(szDebugOut, "%s: OpenRequest failed\n", g_TunerName); ::OutputDebugStringA(szDebugOut); break; } if (WINHTTP_INVALID_STATUS_CALLBACK == WinHttpSetStatusCallback(hRequest, InternetCallback, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, NULL)) { char szDebugOut[64]; sprintf_s(szDebugOut, "%s: Callback function not set\n", g_TunerName); ::OutputDebugStringA(szDebugOut); break; } const int len = 64; wchar_t szHeader[len]; swprintf_s(szHeader, len, L"Connection: close\r\nX-Mirakurun-Priority: %d", g_Priority); int i = 0; while (1) { if (!WinHttpSendRequest( hRequest, szHeader, -1L, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { sprintf_s(szDebugOut, "%s: SendRequest failed\n", g_TunerName); ::OutputDebugStringA(szDebugOut); break; } WinHttpReceiveResponse(hRequest, NULL); DWORD dwStatusCode = 0; DWORD dwSize = sizeof(dwStatusCode); WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &dwStatusCode, &dwSize, WINHTTP_NO_HEADER_INDEX); if (dwStatusCode == HTTP_STATUS_OK) { ret = TRUE; break; } else{ sprintf_s(szDebugOut, "%s: Tuner unavailable\n", g_TunerName); ::OutputDebugStringA(szDebugOut); } if (++i < 2) { ::Sleep(500); } else { break; } } break; } ::LeaveCriticalSection(&m_CriticalSection); return ret; } void CALLBACK CBonTuner::InternetCallback( HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: SetEvent(g_hCloseEvent); break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: char szDebugOut[64]; sprintf_s(szDebugOut, "%s: Request error\n", g_TunerName); ::OutputDebugStringA(szDebugOut); } } UINT WINAPI CBonTuner::RecvThread(LPVOID pParam) { CBonTuner *pThis = (CBonTuner *)pParam; BYTE *data; DWORD dwSize; BOOL ret; while (1) { if (::WaitForSingleObject(pThis->m_hStopEvent, 0) != WAIT_TIMEOUT) { //中止 break; } ::EnterCriticalSection(&pThis->m_CriticalSection); if (pThis->hRequest) { ret = WinHttpQueryDataAvailable(pThis->hRequest, &dwSize); if (ret && dwSize > 0) { data = (BYTE *)malloc(dwSize); if (data) { WinHttpReadData(pThis->hRequest, data, dwSize, NULL); pThis->m_pGrabTsData->put_TsStream(data, dwSize); free(data); } } } ::LeaveCriticalSection(&pThis->m_CriticalSection); } return 0; }
21.919656
82
0.636667
[ "object" ]
136d6a6b5edade1fd91a1e071700c045bc2de482
1,678
hpp
C++
apps/ImageProcessing.hpp
markvilar/openvslam
a8cc7cd0c063ec0549fdf1d6a8f764a28037a123
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
apps/ImageProcessing.hpp
markvilar/openvslam
a8cc7cd0c063ec0549fdf1d6a8f764a28037a123
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
apps/ImageProcessing.hpp
markvilar/openvslam
a8cc7cd0c063ec0549fdf1d6a8f764a28037a123
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/core/cuda.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui.hpp> #include "openvslam/util/image_converter.h" #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wignored-qualifiers" #pragma GCC diagnostic ignored "-Wdeprecated-copy" #include "sl/Camera.hpp" #include "Image.hpp" enum class ImagePreprocessingType { None = 0, HistogramEqualization = 1, CLAHE = 2, UIENet = 3, }; ImagePreprocessingType IntToImagePreprocessingType(const int x); int ImagePreprocessingTypeToInt(const ImagePreprocessingType x); std::string ToString(const ImagePreprocessingType x); std::ostream& operator<<(std::ostream& os, const ImagePreprocessingType x); class StereoImageProcessor { public: static std::pair<cv::Mat, cv::Mat> ProcessImagePairRaw( const std::shared_ptr<sl::Camera>& camera); static std::pair<cv::Mat, cv::Mat> ProcessImagePairHE( const std::shared_ptr<sl::Camera>& camera); static std::pair<cv::Mat, cv::Mat> ProcessImagePairCLAHE( const std::shared_ptr<sl::Camera>& camera, const double clipLimit, const int size); static std::pair<cv::Mat, cv::Mat> ProcessImagePairUIENet( const std::shared_ptr<sl::Camera>& camera, const std::shared_ptr<torch::jit::script::Module>& model); static void FilterImageBilateral(const cv::Mat& src, cv::Mat& dst, const uint32_t diameter, const uint32_t sigmaColor, const uint32_t sigmaSpace); };
31.074074
75
0.702622
[ "model" ]
1379da2b84254c6c051829752b63aac056d264ff
1,682
cpp
C++
benchmarks/halide/heat3d_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
benchmarks/halide/heat3d_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
benchmarks/halide/heat3d_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
5
2017-02-16T14:26:40.000Z
2018-05-30T16:49:27.000Z
#include <tiramisu/tiramisu.h> #include "wrapper_heat3d.h" using namespace tiramisu; int main(int argc, char **argv) { init("heat3d_tiramisu"); constant ROWS("ROWS", _X); constant COLS("COLS", _Y); constant HEIGHT("HEIGHT", _Z); constant TIME("TIME",_TIME); constant ALPHA("ALPHA",_ALPHA); constant BETA("BETA",_BETA); //for heat3d_init var x_in=var("x_in",0,ROWS); var y_in=var("y_in",0,COLS); var z_in=var("z_in",0,HEIGHT); var t_in=var("t_in",0,TIME+1); //for heat3d_c var x=var("x",1,ROWS-1); var y=var("y",1,COLS-1); var z=var("z",1,HEIGHT-1); var t=var("t",1,TIME+1); //input -- 3D input data("data",{z_in,y_in,x_in},p_float32); //init computation computation heat3d_init("heat3d_init",{t_in,z_in,y_in,x_in},data(z_in,y_in,x_in)); //kernel computation heat3dc("heat3dc",{t,z,y,x},p_float32); heat3dc.set_expression( heat3dc(t-1,z,y,x) + expr(o_mul, ALPHA, heat3dc(t-1,z-1,y,x) - expr(o_mul,BETA,heat3dc(t-1,z,y,x)) + heat3dc(t-1,z+1,y,x) + heat3dc(t-1,z,y-1,x) - expr(o_mul,BETA,heat3dc(t-1,z,y,x)) + heat3dc(t-1,z,y+1,x) + heat3dc(t-1,z,y,x-1) - expr(o_mul,BETA,heat3dc(t-1,z,y,x)) + heat3dc(t-1,z,y,x+1))); heat3dc.after(heat3d_init,computation::root); //we need to initialize all data before computing //buffers buffer b_in("b_in",{HEIGHT,COLS,ROWS},p_float32,a_input); buffer b_out("b_out",{TIME+1,HEIGHT,COLS,ROWS},p_float32,a_output); data.store_in(&b_in); heat3d_init.store_in(&b_out,{t_in,z_in,y_in,x_in}); heat3dc.store_in(&b_out,{t,z,y,x}); codegen({&b_in,&b_out}, "build/generated_fct_heat3d.o"); return 0; }
35.041667
99
0.636147
[ "3d" ]
137db91e44d7ca0c6e3c4868259704099fc71e1e
7,104
cpp
C++
Modules/CppMicroServices/core/test/usAnyTest.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/CppMicroServices/core/test/usAnyTest.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/CppMicroServices/core/test/usAnyTest.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ Library: CppMicroServices Copyright (c) German Cancer Research Center (DKFZ) 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 <usAny.h> #include "usTestingMacros.h" #include <limits> US_USE_NAMESPACE int usAnyTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("AnyTest"); Any anyBool = true; US_TEST_CONDITION(anyBool.Type() == typeid(bool), "Any[bool].Type()") US_TEST_CONDITION(any_cast<bool>(anyBool) == true, "any_cast<bool>()") US_TEST_CONDITION(anyBool.ToString() == "1", "Any[bool].ToString()") US_TEST_CONDITION(anyBool.ToJSON() == "true", "Any[bool].ToJSON()") anyBool = false; US_TEST_CONDITION(anyBool.ToString() == "0", "Any[bool].ToString()") US_TEST_CONDITION(anyBool.ToJSON() == "false", "Any[bool].ToJSON()") Any anyInt = 13; US_TEST_CONDITION(anyInt.Type() == typeid(int), "Any[int].Type()") US_TEST_CONDITION(any_cast<int>(anyInt) == 13, "any_cast<int>()") US_TEST_CONDITION(anyInt.ToString() == "13", "Any[int].ToString()") US_TEST_CONDITION(anyInt.ToJSON() == "13", "Any[int].ToJSON()") Any anyChar = 'a'; US_TEST_CONDITION(anyChar.Type() == typeid(char), "Any[char].Type()") US_TEST_CONDITION(any_cast<char>(anyChar) == 'a', "any_cast<char>()") US_TEST_CONDITION(anyChar.ToString() == "a", "Any[char].ToString()") US_TEST_CONDITION(anyChar.ToJSON() == "a", "Any[char].ToJSON()") Any anyFloat = 0.2f; US_TEST_CONDITION(anyFloat.Type() == typeid(float), "Any[float].Type()") US_TEST_CONDITION(any_cast<float>(anyFloat) - 0.2f < std::numeric_limits<float>::epsilon(), "any_cast<float>()") US_TEST_CONDITION(anyFloat.ToString() == "0.2", "Any[float].ToString()") US_TEST_CONDITION(anyFloat.ToString() == "0.2", "Any[float].ToJSON()") Any anyDouble = 0.5; US_TEST_CONDITION(anyDouble.Type() == typeid(double), "Any[double].Type()") US_TEST_CONDITION(any_cast<double>(anyDouble) - 0.5 < std::numeric_limits<double>::epsilon(), "any_cast<double>()") US_TEST_CONDITION(anyDouble.ToString() == "0.5", "Any[double].ToString()") US_TEST_CONDITION(anyDouble.ToString() == "0.5", "Any[double].ToJSON()") Any anyString = std::string("hello"); US_TEST_CONDITION(anyString.Type() == typeid(std::string), "Any[std::string].Type()") US_TEST_CONDITION(any_cast<std::string>(anyString) == "hello", "any_cast<std::string>()") US_TEST_CONDITION(anyString.ToString() == "hello", "Any[std::string].ToString()") US_TEST_CONDITION(anyString.ToJSON() == "\"hello\"", "Any[std::string].ToJSON()") std::vector<int> vecInts; vecInts.push_back(1); vecInts.push_back(2); Any anyVectorOfInts = vecInts; US_TEST_CONDITION(anyVectorOfInts.Type() == typeid(std::vector<int>), "Any[std::vector<int>].Type()") US_TEST_CONDITION(any_cast<std::vector<int> >(anyVectorOfInts) == vecInts, "any_cast<std::vector<int>>()") US_TEST_CONDITION(anyVectorOfInts.ToString() == "[1,2]", "Any[std::vector<int>].ToString()") US_TEST_CONDITION(anyVectorOfInts.ToJSON() == "[1,2]", "Any[std::vector<int>].ToJSON()") std::list<int> listInts; listInts.push_back(1); listInts.push_back(2); Any anyListOfInts = listInts; US_TEST_CONDITION(anyListOfInts.Type() == typeid(std::list<int>), "Any[std::list<int>].Type()") US_TEST_CONDITION(any_cast<std::list<int> >(anyListOfInts) == listInts, "any_cast<std::list<int>>()") US_TEST_CONDITION(anyListOfInts.ToString() == "[1,2]", "Any[std::list<int>].ToString()") US_TEST_CONDITION(anyListOfInts.ToJSON() == "[1,2]", "Any[std::list<int>].ToJSON()") std::set<int> setInts; setInts.insert(1); setInts.insert(2); Any anySetOfInts = setInts; US_TEST_CONDITION(anySetOfInts.Type() == typeid(std::set<int>), "Any[std::set<int>].Type()") US_TEST_CONDITION(any_cast<std::set<int> >(anySetOfInts) == setInts, "any_cast<std::set<int>>()") US_TEST_CONDITION(anySetOfInts.ToString() == "[1,2]", "Any[std::set<int>].ToString()") US_TEST_CONDITION(anySetOfInts.ToJSON() == "[1,2]", "Any[std::set<int>].ToJSON()") std::vector<Any> vecAny; vecAny.push_back(1); vecAny.push_back(std::string("hello")); Any anyVectorOfAnys = vecAny; US_TEST_CONDITION(anyVectorOfAnys.Type() == typeid(std::vector<Any>), "Any[std::vector<Any>].Type()") US_TEST_CONDITION(anyVectorOfAnys.ToString() == "[1,hello]", "Any[std::vector<Any>].ToString()") US_TEST_CONDITION(anyVectorOfAnys.ToJSON() == "[1,\"hello\"]", "Any[std::vector<Any>].ToJSON()") std::list<Any> listAny; listAny.push_back(1); listAny.push_back(std::string("hello")); Any anyListOfAnys = listAny; US_TEST_CONDITION(anyListOfAnys.Type() == typeid(std::list<Any>), "Any[std::list<Any>].Type()") US_TEST_CONDITION(anyListOfAnys.ToString() == "[1,hello]", "Any[std::list<Any>].ToString()") US_TEST_CONDITION(anyListOfAnys.ToJSON() == "[1,\"hello\"]", "Any[std::list<Any>].ToJSON()") std::map<std::string, int> map1; map1["one"] = 1; map1["two"] = 2; Any anyMap1 = map1; US_TEST_CONDITION(anyMap1.Type() == typeid(std::map<std::string, int>), "Any[std::map<std::string,int>].Type()") US_TEST_CONDITION((any_cast<std::map<std::string, int> >(anyMap1) == map1), "any_cast<std::map<std::string,int>>()") US_TEST_CONDITION(anyMap1.ToString() == "{one : 1, two : 2}", "Any[std::map<std::string,int>].ToString()") US_TEST_CONDITION(anyMap1.ToJSON() == "{\"one\" : 1, \"two\" : 2}", "Any[std::map<std::string,int>].ToJSON()") std::map<int, Any> map2; map2[1] = 0.3; map2[3] = std::string("bye"); Any anyMap2 = map2; US_TEST_CONDITION(anyMap2.Type() == typeid(std::map<int, Any>), "Any[std::map<int,Any>].Type()") US_TEST_CONDITION(anyMap2.ToString() == "{1 : 0.3, 3 : bye}", "Any[std::map<int,Any>].ToString()") US_TEST_CONDITION(anyMap2.ToJSON() == "{\"1\" : 0.3, \"3\" : \"bye\"}", "Any[std::map<int,Any>].ToJSON()") std::map<std::string, Any> map3; map3["number"] = 5; std::vector<int> numbers; numbers.push_back(9); numbers.push_back(8); numbers.push_back(7); map3["vector"] = numbers; map3["map"] = map2; Any anyMap3 = map3; US_TEST_CONDITION(anyMap3.Type() == typeid(std::map<std::string, Any>), "Any[std::map<std::string,Any>].Type()") US_TEST_CONDITION(anyMap3.ToString() == "{map : {1 : 0.3, 3 : bye}, number : 5, vector : [9,8,7]}", "Any[std::map<std::string,Any>].ToString()") US_TEST_CONDITION(anyMap3.ToJSON() == "{\"map\" : {\"1\" : 0.3, \"3\" : \"bye\"}, \"number\" : 5, \"vector\" : [9,8,7]}", "Any[std::map<std::string,Any>].ToJSON()") US_TEST_END() }
48
166
0.656109
[ "vector" ]
137fd13d030e0e8419efe1b66b749e53218e9928
35,431
cpp
C++
language-extensions/R/test/src/RExtensionInitParamTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
82
2019-05-24T00:36:57.000Z
2022-02-21T23:51:46.000Z
language-extensions/R/test/src/RExtensionInitParamTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
20
2019-07-05T06:12:28.000Z
2022-03-31T20:48:30.000Z
language-extensions/R/test/src/RExtensionInitParamTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
35
2019-05-24T01:44:07.000Z
2022-02-28T13:29:44.000Z
//************************************************************************************************** // RExtension-test : Executable testing language extension that implements the SQL Server // external language communication protocol. // Copyright (C) 2020 Microsoft Corporation. // // This file is part of RExtension-test. // // RExtension-test is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // RExtension-test is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with RExtension-test. If not, see <https://www.gnu.org/licenses/>. // // @File: RExtensionApiInitParamTests.cpp // // Purpose: // Tests the RExtension's implementation of the external language InitParam API. // //************************************************************************************************** #include "Common.h" using namespace std; namespace ExtensionApiTest { //---------------------------------------------------------------------------------------------- // Name: InitIntegerParamTest // // Description: // Tests multiple SQLINTEGER values. // TEST_F(RExtensionApiTests, InitIntegerParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 5); // parametersNumber // Test max INT value, min INT value with respect to R, // a normal value, NA value and // a NULL INT value. // vector<shared_ptr<SQLINTEGER>> expectedParamValues = { make_shared<SQLINTEGER>(m_MaxInt), make_shared<SQLINTEGER>(m_MinInt), make_shared<SQLINTEGER>(5), make_shared<SQLINTEGER>(R_NaInt), nullptr }; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA}; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLINTEGER, Rcpp::IntegerVector, SQL_C_SLONG>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitLogicalParamTest // // Description: // Tests multiple logical (bit) values. // TEST_F(RExtensionApiTests, InitLogicalParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 8); // parametersNumber // Test '1', '0', NA, 0, 1, NULL and > 1 BIT values. // When testing out of range NA value with respect to R, // returned paramValue is '\0' even though parameter is NA in R // since type casting NA (which is -2'147'483'648) to SQLCHAR returns \0. // vector<shared_ptr<SQLCHAR>> expectedParamValues = { make_shared<SQLCHAR>('1'), make_shared<SQLCHAR>('0'), make_shared<SQLCHAR>(NA_LOGICAL), make_shared<SQLCHAR>(0), make_shared<SQLCHAR>(1), nullptr, make_shared<SQLCHAR>('2'), make_shared<SQLCHAR>(3) }; vector<SQLINTEGER> strLenOrInd = { 0, 0, SQL_NULL_DATA, 0, 0, SQL_NULL_DATA, 0, 0 }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLCHAR, Rcpp::LogicalVector, SQL_C_BIT>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitRealParamTest // // Description: // Tests multiple real values. // TEST_F(RExtensionApiTests, InitRealParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 5); // parametersNumber // Test max FLOAT(24), min FLOAT(24), a normal, NA_REAL and nullptr REAL values // vector<shared_ptr<SQLREAL>> expectedParamValues = { make_shared<SQLREAL>(m_MaxReal), make_shared<SQLREAL>(m_MinReal), make_shared<SQLREAL>(2.3e4), make_shared<SQLREAL>(NA_REAL), nullptr }; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLREAL, Rcpp::NumericVector, SQL_C_FLOAT>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitDoubleParamTest // // Description: // Tests multiple double values. // TEST_F(RExtensionApiTests, InitDoubleParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 5); // parametersNumber // Test max FLOAT(53), min FLOAT(53), a normal, NA_REAL and nullptr // i.e. DOUBLE PRECISION values // vector<shared_ptr<SQLDOUBLE>> expectedParamValues = { make_shared<SQLDOUBLE>(m_MaxDouble), make_shared<SQLDOUBLE>(m_MinDouble), make_shared<SQLDOUBLE>(1.45e38), make_shared<SQLDOUBLE>(NA_REAL), nullptr }; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA}; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLDOUBLE, Rcpp::NumericVector, SQL_C_DOUBLE>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitBigIntParamTest // // Description: // Tests multiple big int values. // TEST_F(RExtensionApiTests, InitBigIntParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 5); // parametersNumber // Test max, min, normal, NA and NULL BIGINT values // vector<shared_ptr<SQLBIGINT>> expectedParamValues = { make_shared<SQLBIGINT>(m_MaxBigInt), make_shared<SQLBIGINT>(m_MinBigInt), make_shared<SQLBIGINT>(9'372'036'854'775), make_shared<SQLBIGINT>(NA_REAL), nullptr }; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLBIGINT, Rcpp::NumericVector, SQL_C_SBIGINT>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitSmallIntParamTest // // Description: // Tests multiple small int values. // TEST_F(RExtensionApiTests, InitSmallIntParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 5); // parametersNumber // Test max, min, normal, NA_INTEGER and NULL SMALLINT values // vector<shared_ptr<SQLSMALLINT>> expectedParamValues = { make_shared<SQLSMALLINT>(m_MaxSmallInt), make_shared<SQLSMALLINT>(m_MinSmallInt), make_shared<SQLSMALLINT>(0), // Since NA_INTEGER in R is a bigger value than the type SQLSMALLINT can hold, // static type casting leads to a 0 value. But this is differentiated by SQL_NULL_DATA. // make_shared<SQLSMALLINT>(0), nullptr }; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA}; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLSMALLINT, Rcpp::IntegerVector, SQL_C_SSHORT>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitTinyIntParamTest // // Description: // Tests multiple tiny int values. // TEST_F(RExtensionApiTests, InitTinyIntParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 6); // parametersNumber // Test max, min, normal, NA, NULL, (-1) underflows to max TINYINT values // vector<shared_ptr<SQLCHAR>> expectedParamValues = { make_shared<SQLCHAR>(m_MaxTinyInt), make_shared<SQLCHAR>(m_MinTinyInt), make_shared<SQLCHAR>(123), // When value is NA, expectedParamValue is type casted to '\0'. // even though in R it is NA_INTEGER which is larger than what SQLCHAR can hold. // make_shared<SQLCHAR>('\0'), nullptr, make_shared<SQLCHAR>(-1)}; vector<SQLINTEGER> strLenOrInd = { 0, 0, 0, SQL_NULL_DATA, SQL_NULL_DATA, 0 }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitParam<SQLCHAR, Rcpp::IntegerVector, SQL_C_UTINYINT>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitCharParamTest // // Description: // Tests multiple character values // TEST_F(RExtensionApiTests, InitCharParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 12); // parametersNumber // Test VARCHAR(8) value with UTF-8 encoded string (with cyrillic) // while actual utfstring length is 4. // string utfstring = u8"абвг"; // Test CHAR(4) value with paramSize same as length. // A UTF-8 self-constructed encoded character (Euro sign) // https://en.wikipedia.org/wiki/UTF-8#Examples // string goodUTF8 = string("a") + "\xE2" + "\x82" + "\xAC"; vector<const char*> expectedParamValues = { // Test simple CHAR(5) value with exact string length as the type allows i.e. here 5. // "HELLO", // Test CHAR(6) value with parameter length less than size - should be padded. // "WORLD", // Test CHAR(6) value with parameter length more than size - should be truncated. // "REXTENSION", // Test null CHAR(5) value // nullptr, // Test a 0 length CHAR(5) value // "", // Test simple VARCHAR(6) value // "WORLD!", // Test simple VARCHAR(8) value with parameter length less than size - no padding. // "WORLD", // Test VARCHAR(6) value with parameter length more than size - should be truncated. // "REXTENSION", // Test null VARCHAR(5) value // nullptr, // Test 0 length VARCHAR(6) value // "", // Test VARCHAR(8) value with UTF-8 encoded string (with cyrillic) // while actual utfstring length is 4. // utfstring.c_str(), // Test CHAR(4) value with paramSize same as length. // A UTF-8 self-constructed encoded character (Euro sign) // https://en.wikipedia.org/wiki/UTF-8#Examples // goodUTF8.c_str() }; vector<SQLULEN> paramSizes = { 5, 6, 6, 5, 5, 6, 8, 6, 5, 6, 8, 4 }; vector<bool> isFixedType = { true, true, true, true, true, false, false, false, false, false, false, true }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitCharParam<char, SQL_C_CHAR>( expectedParamValues, paramSizes, isFixedType, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitNCharParamTest // // Description: // Tests multiple NCHAR and NVARCHAR values. // TEST_F(RExtensionApiTests, InitNCharParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 14); // parametersNumber // Test NCHAR with self-constructed UTF-16 char (𐐷) // https://en.wikipedia.org/wiki/UTF-16#Examples // We need to use u16string here because wstring doesn't // handle multibyte characters well in Linux with the -fshort-wchar option. // u16string goodUTF16 = u16string(u"a") + u"\xd801\xdc37" + u"b"; vector<const wchar_t*> expectedParamValues = { // Test simple NCHAR(5) value with exact string length as the type allows i.e. here 5. // L"HELLO", // Test NCHAR(6) value with parameter length less than size - should be padded. // L"WORLD", // Test NCHAR(6) value with parameter length more than size - should be truncated. // L"REXTENSION", // Test null NCHAR(5) value // nullptr, // Test a 0 length NCHAR(5) value // L"", // Test UNICODE NCHAR(2) // L"你好", // Test simple NVARCHAR(6) value // L"WORLD!", // Test simple NVARCHAR(8) value with parameter length less than size - no padding. // L"WORLD", // Test NVARCHAR(6) value with parameter length more than size - should be truncated. // L"REXTENSION", // Test null NVARCHAR(5) value // nullptr, // Test 0 length NVARCHAR(6) value // L"", // Test Unicode NVARCHAR(6) value // L"你好", // Test Unicode NVARCHAR value (with cyrillic) // L"абвг", // Test NCHAR with self-constructed UTF-16 char (𐐷) // https://en.wikipedia.org/wiki/UTF-16#Examples // We need to use u16string here because wstring doesn't // handle multibyte characters well in Linux with the -fshort-wchar option. // reinterpret_cast<const wchar_t*>(goodUTF16.c_str()) }; vector<SQLULEN> paramSizes = { 5, 6, 6, 5, 5, 2, 6, 8, 6, 5, 6, 6, 10, 4 }; vector<bool> isFixedType = { true, true, true, true, true, true, false, false, false, false, false, false, false, true }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitCharParam<wchar_t, SQL_C_WCHAR>( expectedParamValues, paramSizes, isFixedType, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitRawParamTest // // Description: // Tests multiple binary values. // TEST_F(RExtensionApiTests, InitRawParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 6); // parametersNumber // Test binary(4) value - binary length matching with type. // const vector<SQLCHAR> BinaryValue1 = { 0x00, 0x01, 0xe2, 0x40 }; // Test binary(6) - actual value less than size but padded with 0x00. // const vector<SQLCHAR> BinaryValue2 = { 0x61, 0x62, 0x63, 0x64, 0x00, 0x00 }; // Test simple varbinary(4) value // const vector<SQLCHAR> BinaryValue3 = { 0x00, 0x01, 0xe2, 0x40 }; // Test varbinary(5) value with length less than size - no padding // const vector<SQLCHAR> BinaryValue4 = { 0x61, 0x62, 0x63, 0x64 }; vector<SQLCHAR*> expectedParamValues = { const_cast<SQLCHAR*>(BinaryValue1.data()), // Test null binary(4) value // nullptr, const_cast<SQLCHAR*>(BinaryValue2.data()), const_cast<SQLCHAR*>(BinaryValue3.data()), // Test null varbinary(5) value // nullptr, const_cast<SQLCHAR*>(BinaryValue4.data()) }; vector<SQLINTEGER> strLenOrInd = { static_cast<SQLINTEGER>(BinaryValue1.size())/m_BinarySize, SQL_NULL_DATA, static_cast<SQLINTEGER>(BinaryValue2.size())/m_BinarySize, static_cast<SQLINTEGER>(BinaryValue3.size())/m_BinarySize, SQL_NULL_DATA, static_cast<SQLINTEGER>(BinaryValue4.size())/m_BinarySize }; vector<SQLULEN> paramSizes = { 4, 4, 6, 4, 4, 6 }; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitRawParam( expectedParamValues, strLenOrInd, paramSizes, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitDateParamTest // // Description: // Tests multiple DATE values. // TEST_F(RExtensionApiTests, InitDateParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 6); // parametersNumber vector<SQL_DATE_STRUCT> expectedParamValues = { // Test max SQL_DATE_STRUCT value // { 9999,12,31 }, // Test min SQL_DATE_STRUCT value // { 1,1,1 }, // Test normal SQL_DATE_STRUCT value // { 1470,7,27 }, // Test today's Local date // Utilities::GetTodaysDate<LOCAL_DATE>(), // Test today's UTC date // Utilities::GetTodaysDate<UTC_DATE>(), // Test null SQL_DATE_STRUCT value // {}}; vector<SQLINTEGER> strLenOrInd(expectedParamValues.size(), sizeof(SQL_DATE_STRUCT)); strLenOrInd[expectedParamValues.size() - 1] = SQL_NULL_DATA; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitDateTimeParam<SQL_DATE_STRUCT, Rcpp::DateVector, Rcpp::Date, SQL_C_TYPE_DATE>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitDateTimeParamTest // // Description: // Tests multiple DATETIME values. // TEST_F(RExtensionApiTests, InitDateTimeParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 6); // parametersNumber vector<SQL_TIMESTAMP_STRUCT> expectedParamValues = { // Test max SQL_TIMESTAMP_STRUCT value // { 9999,12,31,23,59,59,999 }, // Test min SQL_TIMESTAMP_STRUCT value // { 1,1,1,0,0,0,0 }, // Test normal SQL_TIMESTAMP_STRUCT value // { 1470,7,27,17,47,52,123456 }, // Test a value of nanoseconds divisible by 100'000'000 // { 2020,9,01,18,23,58,100'000'000 }, // Test a 9 digit value of nanoseconds // { 1970,10,31,8,30,2,123654489 }, // Test null SQL_TIMESTAMP_STRUCT value // {}}; vector<SQLINTEGER> strLenOrInd(expectedParamValues.size(), sizeof(SQL_TIMESTAMP_STRUCT)); strLenOrInd[expectedParamValues.size() - 1] = SQL_NULL_DATA; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitDateTimeParam<SQL_TIMESTAMP_STRUCT, Rcpp::DatetimeVector, Rcpp::Datetime, SQL_C_TYPE_TIMESTAMP>( expectedParamValues, strLenOrInd, inputOutputTypes); } //---------------------------------------------------------------------------------------------- // Name: InitNumericParamTest // // Description: // Tests multiple numeric values with varying precision and scale for all // the following storage classes: // Precision Storage bytes // 1 - 9 5 // 10-19 9 // 20-28 13 // 29-38 17 // TEST_F(RExtensionApiTests, InitNumericParamTest) { SQLUSMALLINT parametersNumber = 16; InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString parametersNumber); // parametersNumber vector<SQL_NUMERIC_STRUCT> inputNumericValues = { { 38, 0, 1, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 196, 134, 90, 168, 76, 59, 75 } }, { 38, 38, 1, { 4, 100, 27, 105, 247, 121, 172, 24, 247, 70, 218, 213, 16, 238, 133, 7 } }, { 38, 38, 1, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 38, 19, 0, { 186, 36, 94, 229, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 28, 0, 1, { 0, 0, 0, 0, 0, 2, 37, 62, 94, 206, 79, 32, 0, 0, 0, 0 } }, { 28, 27, 1, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 28, 14, 0, { 186, 36, 94, 229, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 19, 0, 1, { 0, 0, 100, 167, 179, 182, 224, 13, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 19, 19, 1, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 19, 9, 0, { 186, 36, 94, 229, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 9, 0, 1, { 0, 225, 245, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 9, 9, 1, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 9, 5, 0, { 218, 220, 63, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 20, 0, 1, { 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0 } }, { 20, 0, 1, { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, {} }; vector<SQLULEN> precisionAsParamSize(parametersNumber, 0); vector<SQLSMALLINT> decimalDigits(parametersNumber, 0); for (int paramNumber = 0; paramNumber < parametersNumber; ++paramNumber) { precisionAsParamSize[paramNumber] = inputNumericValues[paramNumber].precision; decimalDigits[paramNumber] = inputNumericValues[paramNumber].scale; } vector<double> expectedParamValues = { // Test numeric(38, 0) // 1e38, // Test max value for numeric (38, 38) // 9999999999999999999999999999999999999e-38, // Test min numeric(38, 38) // 1e-38, // Test numeric(38, 19) // -5578989.33434e-14, // Test numeric(28, 0) // 1e28, // Test numeric(28, 27) // 1e-27, // Test numeric(28, 14) // -5578989.33434e-9, // Test numeric(19, 0) // 1e18, // Test numeric(19, 19) // 1e-19, // Test numeric(19, 9) // -5578989.33434e-4, // Test numeric(9, 0) // 1e8, // Test numeric(9, 9) // 1e-9, // Test numeric(9, 5) // -5578.33434, // Test ULLONG_MAX // 18446744073709551615.0, // Test ULLONG_MAX + 1 // 18446744073709551616.0 }; vector<SQLINTEGER> strLenOrInd(inputNumericValues.size(), sizeof(SQL_NUMERIC_STRUCT)); strLenOrInd[inputNumericValues.size() - 1] = SQL_NULL_DATA; vector<SQLSMALLINT> inputOutputTypes(expectedParamValues.size(), SQL_PARAM_INPUT); InitNumericParam( inputNumericValues, strLenOrInd, inputOutputTypes, precisionAsParamSize, decimalDigits, expectedParamValues); } // // Negative tests // //---------------------------------------------------------------------------------------------- // Name: InitNullNameParamTest // // Description: // Tests InitParam() API with null parameter name. A negative test. // TEST_F(RExtensionApiTests, InitNullNameParamTest) { InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 1); // parametersNumber SQLCHAR *paramName = nullptr; SQLSMALLINT paramNameLength = 0; SQLINTEGER paramValue = 123; SQLRETURN result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, 0, // paramNumber paramName, paramNameLength, SQL_C_SLONG, m_IntSize, // paramSize 0, // decimalDigits &paramValue, // paramValue SQL_NULL_DATA, // strLenOrInd SQL_PARAM_INPUT); // inputOutputType EXPECT_EQ(result, SQL_ERROR); } //---------------------------------------------------------------------------------------------- // Name: InitInvalidParamNumberTest // // Description: // Tests InitParam() API with bad param numbers (too big). A negative test. // TEST_F(RExtensionApiTests, InitInvalidParamNumberTest) { SQLUSMALLINT parametersNumber = 1; InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString parametersNumber); // parametersNumber string paramNameString = "@param"; SQLCHAR *paramName = static_cast<SQLCHAR *>( static_cast<void *>(const_cast<char *>(paramNameString.c_str()))); SQLINTEGER paramValue = 123; SQLRETURN result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, parametersNumber + 1, // paramNumber outside of range paramName, paramNameString.length(), SQL_C_SLONG, m_IntSize, // paramSize 0, // decimalDigits &paramValue, // argValue 0, // strLenOrInd SQL_PARAM_INPUT); // inputOutputType EXPECT_EQ(result, SQL_ERROR); } //---------------------------------------------------------------------------------------------- // Name: InitBadEncodingParamTest // // Description: // Test InitParam() API with bad strings (out of encoding range) // TEST_F(RExtensionApiTests, InitBadEncodingParamTest) { // Testing a bad UTF-8 string // InitializeSession( 0, // inputSchemaColumnsNumber "", // scriptString 1); // parametersNumber // Construct a bad UTF-8 string: // https://en.wikipedia.org/wiki/UTF-8#Encoding // 0xF7 defines a 4-byte character and expects three more chars of range 0x80-0xBF // string badUTF8 = string("a") + "\xF7" + "\xFF" + "b"; vector<const char*> expectedParamValues = { badUTF8.c_str() }; vector<SQLULEN> paramSizes = { badUTF8.length() }; vector<bool> isFixedType = { true }; vector<SQLSMALLINT> inputOutputTypes = { SQL_PARAM_INPUT_OUTPUT }; InitCharParam<char, SQL_C_CHAR>( expectedParamValues, paramSizes, isFixedType, inputOutputTypes, false, false); // Testing a bad UTF-16 string // // Construct a bad UTF-16 string: // https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF // 0xd800 (high surrogate) expects a low surrogate afterwards (0xdc00-0xdfff) // We need to use u16string here because wstring doesn't // handle multibyte characters well in Linux with the -fshort-wchar option. // u16string badUTF16 = u16string(u"a") + u"\xd800\xd800" + u"b"; vector<const wchar_t*> expectedWideParamValues = { reinterpret_cast<const wchar_t*>(badUTF16.c_str()) }; paramSizes = { badUTF16.size() }; isFixedType = { true }; inputOutputTypes = { SQL_PARAM_INPUT_OUTPUT }; InitCharParam<wchar_t, SQL_C_WCHAR>( expectedWideParamValues, paramSizes, isFixedType, inputOutputTypes, false, false); } //---------------------------------------------------------------------------------------------- // Name: RExtensionApiTest::InitParam // // Description: // Templatized function to call InitParam for the given paramValues and dataType. // Testing if InitParam is implemented correctly for integer/numeric/logical dataTypes. // When inRange is false and paramValue is 0, it tests a nullptr paramValue given to InitParam. // template<class SQLType, class RVectorType, SQLSMALLINT DataType> void RExtensionApiTests::InitParam( vector<shared_ptr<SQLType>> expectedParamValues, vector<SQLINTEGER> strLenOrInd, vector<SQLSMALLINT> inputOutputTypes, bool validate) { for (SQLUSMALLINT paramNumber = 0; paramNumber < expectedParamValues.size(); ++paramNumber) { string paramNameString = string("@param" + to_string(paramNumber + 1)); SQLCHAR *paramName = static_cast<SQLCHAR*>( static_cast<void*>(const_cast<char *>(paramNameString.c_str()))); SQLRETURN result = SQL_ERROR; result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, paramNumber, paramName, paramNameString.length(), DataType, sizeof(SQLType), // paramSize 0, // decimalDigits expectedParamValues[paramNumber] != nullptr ? expectedParamValues[paramNumber].get() : nullptr, // paramValue strLenOrInd[paramNumber], inputOutputTypes[paramNumber]); ASSERT_EQ(result, SQL_SUCCESS); if (validate) { // Do + 1 to skip the @ from the paramName // RVectorType param = m_globalEnvironment[paramNameString.c_str() + 1]; if (strLenOrInd[paramNumber] != SQL_NULL_DATA) { SQLType expectedParamValue = *expectedParamValues[paramNumber]; if constexpr (DataType == SQL_C_BIT) { EXPECT_EQ(param[0], expectedParamValue != '0' && expectedParamValue != 0); } else { EXPECT_EQ(param[0], expectedParamValue); } } else { EXPECT_TRUE(RVectorType::is_na(param[0])); } } } } //---------------------------------------------------------------------------------------------- // Name: InitCharParam // // Description: // Templatized function testing if InitParam is implemented correctly for the // (n)char/(n)varchar dataTypes // template<class CharType, SQLSMALLINT DataType> void RExtensionApiTests::InitCharParam( vector<const CharType*> expectedParamValues, vector<SQLULEN> paramSizes, vector<bool> isFixedType, vector<SQLSMALLINT> inputOutputTypes, bool validate, bool expectSuccess) { for (SQLUSMALLINT paramNumber = 0; paramNumber < expectedParamValues.size(); ++paramNumber) { string paramNameString = string("@param" + to_string(paramNumber + 1)); SQLCHAR *paramName = static_cast<SQLCHAR*>( static_cast<void*>(const_cast<char *>(paramNameString.c_str()))); vector<CharType> fixedParamValue(paramSizes[paramNumber] + 1, 0); SQLULEN strLenOrInd = 0; CharType *expectedParamValue = nullptr; SQLULEN paramLengthAfterTruncationIfAny = 0; if (expectedParamValues[paramNumber] != nullptr) { SQLULEN paramLength = 0; if constexpr (is_same_v<CharType, wchar_t>) { paramLength = Utilities::GetWStringLength(expectedParamValues[paramNumber]); } else { paramLength = strlen(expectedParamValues[paramNumber]); } const CharType *paramValue = expectedParamValues[paramNumber]; copy(paramValue, paramValue + min(paramLength, paramSizes[paramNumber]), fixedParamValue.begin()); if (isFixedType[paramNumber]) { strLenOrInd = paramSizes[paramNumber]; // pad the rest of the vector // for (SQLULEN index = paramLength; index < strLenOrInd; ++index) { fixedParamValue[index] = ' '; } } else { strLenOrInd = min(paramLength, paramSizes[paramNumber]); } paramLengthAfterTruncationIfAny = strLenOrInd; strLenOrInd *= sizeof(CharType); expectedParamValue = fixedParamValue.data(); } else { strLenOrInd = SQL_NULL_DATA; } SQLRETURN result = SQL_ERROR; // Even though paramSize doesn't include the null terminator, // we create a CharacterVector parameter with a null terminator string // result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, paramNumber, paramName, paramNameString.length(), DataType, paramSizes[paramNumber], 0, // decimalDigits expectedParamValue, strLenOrInd, inputOutputTypes[paramNumber]); if(!expectSuccess) { ASSERT_EQ(result, SQL_ERROR); } else { ASSERT_EQ(result, SQL_SUCCESS); if (validate) { // Do + 1 to skip the @ from the paramName // Rcpp::CharacterVector param = m_globalEnvironment[paramNameString.c_str() + 1]; if (expectedParamValues[paramNumber] != nullptr) { const char *actualParam = param[0]; string expectedParamUtf8; if constexpr (is_same_v<CharType, wchar_t>) { estd::ToUtf8( reinterpret_cast<char16_t*>(expectedParamValue), paramLengthAfterTruncationIfAny, expectedParamUtf8); } else { expectedParamUtf8 = string(expectedParamValue, paramLengthAfterTruncationIfAny); } for (SQLULEN index = 0; index < paramLengthAfterTruncationIfAny; ++index) { EXPECT_EQ(actualParam[index], expectedParamUtf8[index]); } } else { EXPECT_EQ(param[0], NA_STRING); } } } } } //---------------------------------------------------------------------------------------------- // Name: RExtensionApiTest::InitRawParam // // Description: // Testing if InitParam is implemented correctly for the binary/varbinary dataType. // void RExtensionApiTests::InitRawParam( vector<SQLCHAR*> expectedParamValues, vector<SQLINTEGER> strLenOrInd, vector<SQLULEN> paramSizes, vector<SQLSMALLINT> inputOutputTypes, bool validate) { for (SQLUSMALLINT paramNumber = 0; paramNumber < expectedParamValues.size(); ++paramNumber) { string paramNameString = string("@param" + to_string(paramNumber + 1)); SQLCHAR *paramName = static_cast<SQLCHAR*>( static_cast<void*>(const_cast<char *>(paramNameString.c_str()))); SQLCHAR *expectedParamValue = expectedParamValues[paramNumber]; SQLRETURN result = SQL_ERROR; result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, paramNumber, paramName, paramNameString.length(), SQL_C_BINARY, paramSizes[paramNumber], 0, // decimalDigits expectedParamValue, strLenOrInd[paramNumber], inputOutputTypes[paramNumber]); ASSERT_EQ(result, SQL_SUCCESS); if (validate) { // Do + 1 to skip the @ from the paramName // Rcpp::RawVector param = m_globalEnvironment[paramNameString.c_str() + 1]; if (expectedParamValue != nullptr) { // Always compare using strLenOrInd because // we copy only those many bytes into the raw parameter // for (SQLINTEGER i = 0; i < strLenOrInd[paramNumber]; ++i) { EXPECT_EQ(param[i], expectedParamValue[i]); } } else { // If expectedParamValue is NULL, the size of param // should be 0. // EXPECT_EQ(param.size(), 0); } } } } //---------------------------------------------------------------------------------------------- // Name: RExtensionApiTest::InitDateTimeParam // // Description: // Testing if InitParam is implemented correctly for the date/datetime dataTypes. // template<class SQLType, class RVectorType, class DateTimeTypeInR, SQLSMALLINT DataType> void RExtensionApiTests::InitDateTimeParam( vector<SQLType> expectedParamValues, vector<SQLINTEGER> strLenOrInd, vector<SQLSMALLINT> inputOutputTypes, bool validate) { for (SQLUSMALLINT paramNumber = 0; paramNumber < expectedParamValues.size(); ++paramNumber) { string paramNameString = string("@param" + to_string(paramNumber + 1)); SQLCHAR *paramName = static_cast<SQLCHAR*>( static_cast<void*>(const_cast<char *>(paramNameString.c_str()))); SQLType expectedParamValue = expectedParamValues[paramNumber]; SQLRETURN result = SQL_ERROR; result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, paramNumber, paramName, paramNameString.length(), DataType, sizeof(SQLType), // paramSize 0, // decimalDigits &expectedParamValue, strLenOrInd[paramNumber], inputOutputTypes[paramNumber]); ASSERT_EQ(result, SQL_SUCCESS); if (validate) { // Do + 1 to skip the @ from the paramName // RVectorType param = m_globalEnvironment[paramNameString.c_str() + 1]; CheckRDateTimeVectorColumnDataEquality<SQLType, RVectorType, DateTimeTypeInR>( 1, param, &expectedParamValue, &strLenOrInd[paramNumber]); } } } //---------------------------------------------------------------------------------------------- // Name: RExtensionApiTest::InitNumericParam // // Description: // Testing if InitParam is implemented correctly for the decimal/numeric dataTypes. // void RExtensionApiTests::InitNumericParam( vector<SQL_NUMERIC_STRUCT> initParamValues, vector<SQLINTEGER> strLenOrInd, vector<SQLSMALLINT> inputOutputTypes, vector<SQLULEN> precisionAsParamSize, vector<SQLSMALLINT> decimalDigits, vector<double> expectedParamValues) { for (SQLUSMALLINT paramNumber = 0; paramNumber < initParamValues.size(); ++paramNumber) { string paramNameString = string("@param" + to_string(paramNumber + 1)); SQLCHAR *paramName = static_cast<SQLCHAR*>( static_cast<void*>(const_cast<char *>(paramNameString.c_str()))); SQLRETURN result = SQL_ERROR; result = (*sm_initParamFuncPtr)( *m_sessionId, m_taskId, paramNumber, paramName, paramNameString.length(), SQL_C_NUMERIC, precisionAsParamSize[paramNumber], decimalDigits[paramNumber], &initParamValues[paramNumber], strLenOrInd[paramNumber], inputOutputTypes[paramNumber]); ASSERT_EQ(result, SQL_SUCCESS); if (expectedParamValues.size() > 0) { // Do + 1 to skip the @ from the paramName // Rcpp::NumericVector param = m_globalEnvironment[paramNameString.c_str() + 1]; if (strLenOrInd[paramNumber] != SQL_NULL_DATA) { double expectedParamValue = expectedParamValues[paramNumber]; EXPECT_EQ(param[0], expectedParamValue); } else { EXPECT_TRUE(Rcpp::NumericVector::is_na(param[0])); } } } } }
30.179727
102
0.627755
[ "vector" ]
1389402e9a63980fda213cd474178ba3b9be948e
41,179
hpp
C++
stapl_release/stapl/views/multiarray_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/multiarray_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/views/multiarray_view.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_VIEWS_MULTIARRAY_VIEW_HPP #define STAPL_VIEWS_MULTIARRAY_VIEW_HPP #include <stapl/utility/tuple.hpp> #include <stapl/views/array_view.hpp> #include <stapl/containers/type_traits/dimension_traits.hpp> #include <stapl/views/mapping_functions/mapping_functions.hpp> #include <stapl/views/mapping_functions/linearization.hpp> #include <stapl/containers/type_traits/default_traversal.hpp> #include <stapl/utility/use_default.hpp> #include <stapl/views/operations/multi_dimensional_subscript.hpp> #include <stapl/domains/indexed.hpp> #include <stapl/views/type_traits/underlying_container.hpp> #include <stapl/views/type_traits/is_segmented_view.hpp> #include <stapl/views/metadata/coarsening_traits.hpp> #include <stapl/views/metadata/projection/multiarray_view_over_array_view.hpp> #include <stapl/containers/array/array_fwd.hpp> #include <iostream> namespace stapl { #ifdef STAPL_DOCUMENTATION_ONLY ////////////////////////////////////////////////////////////////////// /// @brief Provide a one dimensional, random access view over a /// multi-dimensional view. /// @tparam View The underlying multi-dimensional view to linearize. /// @tparam Traversal The traversal method to use for linearization /// @todo Remove linear_view freestanding function idiom and rename /// this class to linear_view. ////////////////////////////////////////////////////////////////////// template<typename View, typename Traversal = typename default_traversal< tuple_size<typename view_traits<View>::index_type>::value >::type> class linear_view_impl; #else template<typename View, typename ...OptionalParams> class linear_view_impl; #endif ////////////////////////////////////////////////////////////////////// /// @brief Type metafunction to select a default traversal if a /// @ref linear_view has not been passed an optional traversal /// type parameter. Otherwise, return the passed type. ////////////////////////////////////////////////////////////////////// template<int N, typename ...OptionalTraversal> struct compute_traversal_type; template<int N> struct compute_traversal_type<N> { typedef typename default_traversal<N>::type type; }; template<int N, typename Traversal> struct compute_traversal_type<N, Traversal> { typedef Traversal type; }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for when all four type parameters are specified. ////////////////////////////////////////////////////////////////////// template<typename View, typename ...OptionalParams> struct view_traits<linear_view_impl<View, OptionalParams...>> : default_view_traits< typename view_traits<View>::container, indexed_domain<size_t>, typename compose_func< typename view_traits<View>::map_function, nd_reverse_linearize< typename view_traits<View>::index_type, typename compute_traversal_type< tuple_size<typename view_traits<View>::index_type>::value, OptionalParams...>::type>>::type, linear_view_impl<View, OptionalParams...> > { }; template <typename View> struct is_SLICED_view; ////////////////////////////////////////////////////////////////////// /// @brief Meta-function providing a public member @p value which is /// true if given view composition starting with @ref linear_view_impl /// should be preserved. /// /// This specialization is needed because the default implementation of /// @p preserve_composition uses @p view_container_type to recurse down /// the composition, but @p linear_view_impl::view_container_type doesn't /// refer to the view being linearized, but rather to its underlying /// container. /// /// @todo We should be able to flatten linear_view_impl<SLICED_view<...>>, /// but there is currently a mapping function type mis-match when /// constructing the corresponding localized_view. ////////////////////////////////////////////////////////////////////// template<typename View, typename... OptionalParams> struct preserve_composition<linear_view_impl<View, OptionalParams...>> { static constexpr bool value = should_preserve<View>::value; }; ////////////////////////////////////////////////////////////////////// /// @brief Transform a linear view to one over a base container. /// /// For linear views over views other than @ref segmented_view (and views /// derived from it) or @ref SLICED_view, the variadic /// @ref new_cast_container_view metafunction is used (returning a linear view /// over the base container with a mapping function composed of all the /// underlying views). For linear views over a @p segmented_view or /// @p SLICED_view, a linear view over the casted @p segmented_view or /// @p SLICED_view is returned (with its original mapping function). ////////////////////////////////////////////////////////////////////// template<typename OldC, typename ...OptionalParams, typename NewC> struct cast_container_view<linear_view_impl<OldC, OptionalParams...>, NewC> : std::conditional< is_segmented_view<OldC>::value || is_SLICED_view<OldC>::value, cast_container_view_preserve_mapfunc< linear_view_impl<OldC, OptionalParams...>, typename cast_container_view<OldC, NewC>::type >, new_cast_container_view< linear_view_impl<OldC, OptionalParams...>, NewC > >::type { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization ensures container, domain and mapping function /// transform for variadic based optionals is used. ////////////////////////////////////////////////////////////////////// template<typename C, typename ...OptionalParams, typename Dom, typename MF> struct upcast_view<linear_view_impl<C, OptionalParams...>, Dom, MF> : new_upcast_view<linear_view_impl<C, OptionalParams...>, Dom, MF> { }; ////////////////////////////////////////////////////////////////////// /// @brief Implementation of the linear view concept (a 1D view providing /// access to all elements of given multidimensional view by using /// linearized indices). /// /// @tparam View original multidimensional view to be linearized /// @tparam OptionalParams optional parameter specifying the traversal /// order used for linearization ////////////////////////////////////////////////////////////////////// template<typename View, typename ...OptionalParams> class linear_view_impl : public array_view< typename view_traits<View>::container, indexed_domain<size_t>, typename compose_func< typename view_traits<View>::map_function, nd_reverse_linearize< typename view_traits<View>::index_type, typename compute_traversal_type< tuple_size<typename view_traits<View>::index_type>::value, OptionalParams...>::type>>::type, linear_view_impl<View, OptionalParams...> > { public: STAPL_VIEW_REFLECT_TRAITS(linear_view_impl) private: typedef typename view_traits<linear_view_impl>::derived_type derived_type; typedef array_view<view_container_type, domain_type, map_function, linear_view_impl> base_type; typedef view_operations::sequence<derived_type> sequence_op_type; public: typedef typename sequence_op_type::iterator iterator; typedef typename sequence_op_type::const_iterator const_iterator; linear_view_impl(void) = default; linear_view_impl(linear_view_impl const&) = default; linear_view_impl(linear_view_impl&&) = default; ////////////////////////////////////////////////////////////////////// /// @brief Constructor used to pass ownership of the container to the view. /// /// @param vcont Pointer to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type* vcont, domain_type const& dom, map_func_type const& mfunc = map_function()) : base_type(vcont, dom, mfunc) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor used to pass ownership of the container to the view. /// /// @param vcont Pointer to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. /// @param other View to copy from. ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type* vcont, domain_type const& dom, map_func_type const& mfunc, linear_view_impl const&) : base_type(vcont, dom, mfunc) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor that does not takes ownership over the passed /// container. /// /// @param vcont Reference to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type const& vcont, domain_type const& dom, map_func_type const& mfunc = map_function()) : base_type(vcont, dom, mfunc) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructor that does not takes ownership over the passed /// container. /// /// @param vcont Reference to the container used to forward the operations. /// @param dom Domain to be used by the view. /// @param mfunc Mapping function to transform view indices to container /// gids. /// @param other View to copy from (ignored for linear_view_impl) ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type const& vcont, domain_type const& dom, map_func_type const& mfunc, linear_view_impl const&) : base_type(vcont, dom, mfunc) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructs a view that can reference all the elements of /// the passed container. The view takes ownership of the container. /// /// @param vcont Pointer to the container used to forward the operations. ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type* vcont) : base_type(vcont, stapl::get_domain(*vcont)) { } ////////////////////////////////////////////////////////////////////// /// @brief Constructs a view that can reference all the elements of /// the passed container. /// /// @param vcont Reference to the container used to forward the operations. ////////////////////////////////////////////////////////////////////// linear_view_impl(view_container_type& vcont) : base_type(vcont, stapl::get_domain(vcont)) { } }; // class linear_view_impl namespace result_of { ////////////////////////////////////////////////////////////////////// /// @brief Helper struct to determine the one dimensional view type /// over the given multidimensional @p View based on the /// specified @p Traversal. ////////////////////////////////////////////////////////////////////// template<typename View, typename... OptionalParams> struct linear_view { typedef linear_view_impl<View, OptionalParams...> type; }; } // namespace result_of namespace detail { ////////////////////////////////////////////////////////////////////// /// @brief Get the container for the linear view over given multidimensional /// view. /// /// A linear view is implemented as an @ref array_view with special /// mapping function and container type obtained from @ref view_traits /// for the original view (@see linear_view_impl). /// /// If the container type of the linear view is the same as the container /// type of the original view, then we may use it directly to construct /// the linear array view. If not (like when the original view does not /// conform to the <tt>V<C,D,F,Derived></tt> convention and view_traits /// reflect the view type itself as the container), we need to construct /// the container for the linear view anew from the original view, in /// order to prevent temporary implicit conversion when the container is /// passed to the linear view constructor. /// /// This primary template is used in the first case, where we just return /// a reference to the container of the provided view. /// /// @tparam OriginalView original multidimensional view to be linearized /// @tparam LinearView result of the linearization ////////////////////////////////////////////////////////////////////// template<typename OriginalView, typename LinearView, bool = std::is_same< typename OriginalView::view_container_type, typename LinearView::view_container_type >::value > struct linear_view_container { using container_type = typename LinearView::view_container_type; static container_type const& get(OriginalView const& view) { return view.container(); } }; ////////////////////////////////////////////////////////////////////// /// @brief Get the container for the linear view over given multidimensional /// view. /// /// Specialization for the case when the container type of the linear view /// doesn't match the container type of the original view. In this case, /// we need to heap-allocate the container and return a pointer to it, so /// that it is not lost when the linear view is constructed and the linear /// view takes responsibility for its deallocation. /// /// @tparam OriginalView original multidimensional view to be linearized /// @tparam LinearView result of the linearization ////////////////////////////////////////////////////////////////////// template<typename OriginalView, typename LinearView> struct linear_view_container<OriginalView, LinearView, false> { using container_type = typename LinearView::view_container_type; static container_type* get(OriginalView const& view) { static_assert(is_view<OriginalView>::value, "View type expected."); return get_impl(view, typename std::is_same<container_type, OriginalView>::type{}); } private: static container_type* get_impl(OriginalView const& view, std::true_type) { return new container_type(view.container(), view.domain(), view.mapfunc()); } static container_type* get_impl(OriginalView const& view, std::false_type) { return new container_type(view.container()); } }; } ////////////////////////////////////////////////////////////////////// /// @brief Helper function to return a one dimensional view /// over the given multidimensional @p view based on the /// specified @p Traversal type. ////////////////////////////////////////////////////////////////////// template<typename View, typename ...OptionalTraversal> typename std::enable_if<dimension_traits<View>::type::value != 1, typename result_of::linear_view<View, OptionalTraversal...>::type >::type linear_view(View const& view, OptionalTraversal const&...) { typedef typename compute_traversal_type< tuple_size<typename view_traits<View>::index_type>::value, OptionalTraversal... >::type traversal_type; typedef typename View::domain_type::size_type size_type; typedef typename view_traits<View>::index_type index_type; typedef typename view_traits<View>::map_function map_func_type; typedef typename result_of::linear_view< View, OptionalTraversal...>::type result_t; typedef nd_reverse_linearize<index_type, traversal_type> reverse_lin_t; typedef compose_func<map_func_type, reverse_lin_t> comp_mapfunc_t; const size_type size = view.domain().dimensions(); nd_linearize<index_type, traversal_type> mf(size); const size_t first = mf(view.domain().first()); const size_t last = mf(view.domain().last()); return result_t( detail::linear_view_container<View, result_t>::get(view), indexed_domain<size_t>(first, last), comp_mapfunc_t::apply(view.mapfunc(), reverse_lin_t(size))); } ////////////////////////////////////////////////////////////////////// /// @brief Definition of @p linear_view helper function for the case /// when the view being linearized is already one-dimensional. /// /// Just returns the input view unchanged. ////////////////////////////////////////////////////////////////////// template<typename View, typename ...OptionalTraversal> typename std::enable_if<dimension_traits<View>::type::value == 1, View >::type linear_view(View const& view, OptionalTraversal const&...) { return view; } #ifdef STAPL_DOCUMENTATION_ONLY ////////////////////////////////////////////////////////////////////// /// @brief Defines a multi-dimensional array view. /// /// Provides the operations that are commonly present in an array /// (random access, iteration). /// @tparam C Container type. /// @tparam Dom Domain type. By default uses the same domain type /// provided for the container. /// @tparam Mapping function type /// (default: identity mapping function) /// @tparam Derived Type of the most derived class (default: itself) /// @ingroup multi_array_view ////////////////////////////////////////////////////////////////////// template<typename C, typename Dom = typename container_traits<C>::domain_type, typename MapFunc = f_ident<typename Dom::index_type>, typename Derived = use_default> class multiarray_view; #else template<typename C, typename ...OptionalParams> class multiarray_view; #endif namespace view_operations { template <typename View> struct compute_local_domain; ////////////////////////////////////////////////////////////////////// /// @brief Helper function for computing the local domain that by default /// is partition agnostic of the underlying container distribution. /// Specializations of the class template addresses cases where we do better /// given what we know about the distribution (ideally we would like the /// local domain to be that of the elements stored on this affinity). /// /// Specialization for the case where the multiarray_view over the multiarray. /// In this case we ask the underlying base container about existing elements /// in this affinity. ////////////////////////////////////////////////////////////////////// template<int N, typename T, typename ...CArgs, typename ...Args> struct compute_local_domain< multiarray_view<multiarray<N, T, CArgs...>, Args...>> { using view_t = multiarray_view<multiarray<N, T, CArgs...>, Args...>; using domain_type = typename view_t::domain_type; static std::vector<domain_type> apply(view_t const& view, runtime::location_id loc_id, std::size_t num_locs) { std::vector<domain_type> v; if (!domain_equal<N>::apply(view.domain(), view.container().domain()) || num_locs != view.container().get_num_locations()) { v.push_back( default_local_domain(std::true_type(), view, loc_id, num_locs)); return v; } auto const& cm = view.container().distribution().container_manager(); if (cm.size() == 0) v.push_back(domain_type()); else { v.reserve(cm.size()); for (auto&& bc : cm) { v.push_back(bc.domain()); } } return v; } }; ////////////////////////////////////////////////////////////////////// /// @brief Helper function for computing the local domain that by default /// is partition agnostic of the underlying container distribution. /// Specializations of the class template addresses cases where we do better /// given what we know about the distribution (ideally we would like the /// local domain to be that of the elements stored on this affinity). /// /// Specialization for the case where the multiarray_view over the multiarray. /// In this case we ask the underlying base container about existing elements /// in this affinity. ////////////////////////////////////////////////////////////////////// template<int N, typename T, typename ...CArgs, typename ...Args, typename Accessor> struct compute_local_domain< multiarray_view<proxy<multiarray<N, T, CArgs...>, Accessor>, Args...>> { using view_t = multiarray_view<proxy<multiarray<N, T, CArgs...>, Accessor>, Args...>; using domain_type = typename view_t::domain_type; static std::vector<domain_type> apply(view_t const& view, runtime::location_id loc_id, std::size_t num_locs) { std::vector<domain_type> v; if (!domain_equal<N>::apply(view.domain(), view.container().domain()) || num_locs != view.container().get_num_locations()) { v.push_back( default_local_domain(std::true_type(), view, loc_id, num_locs)); return v; } auto const& cm = view.container().distribution().container_manager(); if (cm.size() == 0) v.push_back(domain_type()); else { v.reserve(cm.size()); for (auto&& bc : cm) { v.push_back(bc.domain()); } } return v; } }; } // namespace view_operations ////////////////////////////////////////////////////////////////////// /// @brief Specialization for when only container type parameter is specified. ////////////////////////////////////////////////////////////////////// template<typename C> struct view_traits<multiarray_view<C>> : default_view_traits<C, typename container_traits<C>::domain_type, f_ident<typename container_traits<C>::domain_type::index_type>, multiarray_view<C>> { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for when container and domain type parameters /// are specified. ////////////////////////////////////////////////////////////////////// template<typename C, typename D> struct view_traits<multiarray_view<C, D>> : default_view_traits<C, D, f_ident<typename D::index_type>, multiarray_view<C,D>> { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for when container, domain, and mapping function /// type parameters are specified. ////////////////////////////////////////////////////////////////////// template<typename C, typename D, typename F> struct view_traits<multiarray_view<C, D, F>> : default_view_traits<C, D, F, multiarray_view<C, D, F>> { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for when all four type parameters are specified. ////////////////////////////////////////////////////////////////////// template<typename C, typename D, typename F, typename Derived> struct view_traits<multiarray_view<C, D, F, Derived>> : default_view_traits<C, D, F, Derived> { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization ensures container transform for variadic /// based optionals is used. ////////////////////////////////////////////////////////////////////// template<typename OldC, typename ...OptionalParams, typename NewC> struct cast_container_view<multiarray_view<OldC, OptionalParams...>, NewC> : new_cast_container_view<multiarray_view<OldC, OptionalParams...>, NewC> { }; ////////////////////////////////////////////////////////////////////// /// @brief Specialization ensures container domain and mapping function /// transform for variadic based optionals is used. ////////////////////////////////////////////////////////////////////// template<typename C, typename ...OptionalParams, typename Dom, typename MF> struct upcast_view<multiarray_view<C, OptionalParams...>, Dom, MF> : new_upcast_view<multiarray_view<C, OptionalParams...>, Dom, MF> { }; template<typename C, typename ...OptionalParams> class multiarray_view : public core_view< C, typename view_traits<multiarray_view<C, OptionalParams...>>::domain_type, typename view_traits<multiarray_view<C, OptionalParams...>>::map_function >, public view_operations::readwrite<multiarray_view<C, OptionalParams...>>, public view_operations::multi_dimensional_subscript< typename view_traits<multiarray_view<C, OptionalParams...>>::derived_type > { public: STAPL_VIEW_REFLECT_TRAITS(multiarray_view) typedef index_type dimensions_type; typedef typename dimension_traits<index_type>::type dimension_type; private: typedef core_view<C, domain_type, map_function> base_type; public: ////////////////////////////////////////////////////////////////////// /// @copydoc stapl::array_view::array_view(view_container_type&,domain_type const&,map_func_type) ////////////////////////////////////////////////////////////////////// multiarray_view(view_container_type& vcont, domain_type const& dom, map_function mfunc = map_function()) : base_type(vcont,dom,mfunc) { } multiarray_view(view_container_type const& vcont, domain_type const& dom, map_function mfunc = map_function()) : base_type(vcont,dom,mfunc) { } ////////////////////////////////////////////////////////////////////// /// @copydoc stapl::array_view::array_view(view_container_type*) ////////////////////////////////////////////////////////////////////// multiarray_view(view_container_type* vcont) : base_type(vcont, stapl::get_domain(*vcont)) { } ////////////////////////////////////////////////////////////////////// /// @copydoc stapl::array_view::array_view(view_container_type&) ////////////////////////////////////////////////////////////////////// multiarray_view(view_container_type& vcont) : base_type(vcont, stapl::get_domain(vcont)) { } multiarray_view(view_container_type const& vcont) : base_type(vcont, stapl::get_domain(vcont)) { } ////////////////////////////////////////////////////////////////////// /// @copydoc stapl::array_view::array_view(view_container_type*,domain_type const&,map_func_type) ////////////////////////////////////////////////////////////////////// multiarray_view(view_container_type* vcont, domain_type const& dom, map_function mfunc = map_function()) : base_type(vcont,dom,mfunc) { } ///////////////////////////////////////////////////////////////// /// @brief Copy constructor when the passed view is not the most /// derived view. ////////////////////////////////////////////////////////////////////// template<typename ...OtherOptionalParams> multiarray_view(multiarray_view<C, OtherOptionalParams...> const& other) : base_type(other.container(), other.domain(), other.mapfunc()) { } multiarray_view(view_container_type& vcont, domain_type const& dom, map_function mfunc, multiarray_view const&) : base_type(vcont,dom,mfunc) { } ////////////////////////////////////////////////////////////////////// /// @brief The length of each of the dimensions of the multiarray. ////////////////////////////////////////////////////////////////////// dimensions_type dimensions(void) const { return this->domain().dimensions(); } ////////////////////////////////////////////////////////////////////// /// @brief Update the underlying container to hold the specified /// number of elements. All previous information is lost. ////////////////////////////////////////////////////////////////////// void resize(typename domain_type::size_type size) { this->incr_version(); this->container().resize(size); } ////////////////////////////////////////////////////////////////////// /// @brief Update the underlying container to have the distribution /// specified. /// /// This function is primarily called when container instances in composed /// container instances are redistributed. /// /// @param dist_view Specification of the desired container distribution, /// including the distribution of any nested containers in the case of a /// composed container instance. ////////////////////////////////////////////////////////////////////// template <typename DistSpecView> typename std::enable_if< is_distribution_view<DistSpecView>::value || detail::has_is_composed_dist_spec<DistSpecView>::value>::type redistribute(DistSpecView const& dist_view) { this->incr_version(); this->container().redistribute(dist_view); } ////////////////////////////////////////////////////////////////////// /// @internal /// @brief use to examine this class /// @param msg your message (to provide context) ////////////////////////////////////////////////////////////////////// void debug(char *msg=0) { std::cerr << "MULTI_ARRAY_VIEW " << this << " : "; if (msg) { std::cerr << msg; } std::cerr << "\n"; base_type::debug(); } ////////////////////////////////////////////////////////////////////// /// @brief Metafunction to compute the type of a deep slice on this view /// container. /// /// @tparam Slices The indices to slice on this deep slice /// @tparam Fixed The type of element that will be used to specify the /// fixed values. Typically a tuple of size |Slices|. ////////////////////////////////////////////////////////////////////// template<typename Slices, typename Fixed> struct slice_type { using type = typename view_container_type::template slice_type<Slices, Fixed>::type; }; ////////////////////////////////////////////////////////////////////// /// @brief Create a deep slice by slicing off dimensions specified /// in Slices. /// /// @tparam Slices The indices to slice on this deep slice /// @tparam Fixed The type of element that will be used to specify the /// fixed values. Typically a tuple of size |Slices|. ////////////////////////////////////////////////////////////////////// template<typename Slices, typename Fixed> typename slice_type<Slices, Fixed>::type slice(Fixed const& fixed) { return this->container().template slice<Slices>(fixed); } std::vector<domain_type> local_domain(runtime::location_id loc_id, std::size_t num_locs) const { return view_operations::compute_local_domain<multiarray_view>::apply( *this, loc_id, num_locs); } ////////////////////////////////////////////////////////////////////// /// @brief internal ////////////////////////////////////////////////////////////////////// void define_type(typer& t) { t.base<base_type>(*this); } }; // class multiarray_view ////////////////////////////////////////////////////////////////////// /// @brief Helper function to construct a multiarray_view over the passed /// container /// /// @param ct Underlying container used for the multiarray_view. /// @return A multiarray_view over the Container. ////////////////////////////////////////////////////////////////////// template<typename Container> multiarray_view<Container> make_multiarray_view(Container const& ct) { return multiarray_view<Container>(const_cast<Container&>(ct)); } ////////////////////////////////////////////////////////////////////// /// @brief A linearization mapping function which accepts an initial /// offset. This mapping function is used in the cases where a /// @c multiarray_view is defined over an existing 1D view. /// /// @tparam GID the GID type of the n-dimensional view. ////////////////////////////////////////////////////////////////////// template <typename GID> struct nd_linearize_with_offset : public nd_linearize< GID, typename default_traversal<tuple_size<GID>::value>::type> { typedef nd_linearize< GID, typename default_traversal<tuple_size<GID>::value>::type> base_t; STAPL_IMPORT_DTYPE(base_t, size_type) STAPL_IMPORT_DTYPE(base_t, index_type) STAPL_IMPORT_DTYPE(base_t, gid_type) gid_type m_offset; nd_linearize_with_offset(gid_type offset, size_type const& sizes) : base_t(sizes), m_offset(offset) { } gid_type operator()(index_type const& gid) const { return base_t::operator()(gid) + m_offset; } template<typename RefGetter, typename... Indices> typename std::result_of<RefGetter(Indices...)>::type apply_get(RefGetter const& get_reference, Indices... indices) const { return get_reference(base_t::operator()(indices...) + m_offset); } void define_type(typer& t) { t.member(m_offset); } }; ////////////////////////////////////////////////////////////////////// /// @brief Class that provides basic types used by a multidimensional /// view over a 1D view. /// /// Provides the domain type, mapping function type, type of the /// multidimensional view itself and its localized version where /// the underlying container has been swapped out for the base /// container. Also provides free-standing functions that return the /// domain and mapping function instances associated with such a /// multidimensional view. /// /// @tparam View the original 1D view /// @tparam Dims dimensions of the multidimensional view ////////////////////////////////////////////////////////////////////// template<typename View, typename... Dims> struct make_multiarray_view_traits { static size_t constexpr dim = sizeof...(Dims); using domain_type = indexed_domain<std::size_t, dim, typename default_traversal<dim>::type>; using index_type = typename domain_type::index_type; using map_function = nd_linearize_with_offset<index_type>; using type = multiarray_view<View, domain_type, map_function>; private: using view_container_type = typename underlying_container<View>::type; using base_container_type = typename view_container_type::distribution_type::base_container_type; public: using localized_type = typename cast_container_view<type, base_container_type>::type; ////////////////////////////////////////////////////////////////////// /// @brief Given n dimensions as variadic arguments, creates an /// n-dimensional domain. /// /// @param dims dimensions of the new domain /// /// @return an @ref indexed_domain ////////////////////////////////////////////////////////////////////// static domain_type domain(Dims... dims) { return { std::forward_as_tuple(dims...) }; } ////////////////////////////////////////////////////////////////////// /// @brief Given a one-dimensional view and n dimensions as variadic /// arguments, creates a mapping function that maps an /// n-dimensional index to one-dimensional GID of the view /// (starting at the first GID in the domain of the view). /// /// @param view the original one-dimensional view /// @param dims dimensions of the domain from which indices for /// the mapping function can be drawn /// /// @return an instance of @ref nd_linearize_with_offset ////////////////////////////////////////////////////////////////////// static map_function mapfunc(View const& view, Dims... dims) { return { view.domain().first(), std::forward_as_tuple(dims...) }; } }; ////////////////////////////////////////////////////////////////////// /// @brief Given a 1D view and n dimensions as variadic arguments, /// creates an n-dimensional view that can be used to access /// elements of the 1D view using nD indices /// (using default linearization). /// /// @param view original one-dimensional view /// @param dim0 first dimension of the returned view /// @param dims other dimensions of the returned view /// /// @return a @ref multiarray_view over the provided 1D view ////////////////////////////////////////////////////////////////////// template <typename View, typename D, typename... Dims> typename make_multiarray_view_traits<View, D, Dims...>::type make_multiarray_view(View const& view, D dim0, Dims... dims) { static_assert(dimension_traits<View>::type::value == 1, "make_multiarray_view(view, dim0, dim1, ...) requires 1D view."); using traits = make_multiarray_view_traits<View, D, Dims...>; return { view, traits::domain(dim0, dims...), traits::mapfunc(view, dim0, dims...) }; } ////////////////////////////////////////////////////////////////////// /// @brief Linearization of the multidimensional view over a 1D view. /// @return the original 1D view ////////////////////////////////////////////////////////////////////// template <typename View, typename D, typename... Dims> View linear_view( typename make_multiarray_view_traits<View, D, Dims...>::type const& view) { return view.container(); } namespace metadata { ////////////////////////////////////////////////////////////////////// /// @brief Traits class that specializes functionality of the coarsening /// process for multidimensional views over 1D array_views. /// /// The projection algorithm (@ref multiarray_view_over_array_view_projection) /// relies on the fact that these views are logically partitioned along the /// first dimension only. /// /// @see multiarray_view_over_array_view_projection ////////////////////////////////////////////////////////////////////// template <typename View, typename Domain> struct coarsening_traits< multiarray_view< View, Domain, nd_linearize_with_offset<typename Domain::index_type> > > { using view_type = multiarray_view< View, Domain, nd_linearize_with_offset<typename Domain::index_type> >; template<typename P> struct construct_projection { using type = multiarray_view_over_array_view_projection<const view_type, P>; }; }; ////////////////////////////////////////////////////////////////////// /// @brief Traits class that specializes functionality of the coarsening /// process for linear views over multidimensional views. /// /// The default metadata projection is used for most types of /// @p linear_view<multiarray_view<...>>, based on the underlying container /// type. If the underlying container is 1D @ref array, we assume that /// a @p multiarray_view<array_view<array>> has been created /// (using <tt>make_multiarray_view(view, dim0, dim1, ...)</tt>), possibly with /// additional multidimensional views on top of it (e.g. the slices view). /// This means that @ref multiarray_view_over_array_view_projection has been /// invoked in the metadata projection phase and a multidimensional metadata /// container partitioned along the first dimension only is being passed to the /// projection algorithm for the linear view. This allows us to use /// @ref linearized_multiarray_view_over_array_view_projection for this /// algorithm. /// /// @see linearized_multiarray_view_over_array_view_projection /// @see multiarray_view_over_array_view_projection ////////////////////////////////////////////////////////////////////// template<typename View, typename... OptionalParams> struct coarsening_traits<linear_view_impl<View, OptionalParams...>> { private: using underlying_container_type = typename underlying_container<View>::type; using view_type = linear_view_impl<View, OptionalParams...>; /// Base template - same implementation as in coarsening_traits.hpp template<typename P, typename = underlying_container_type> struct based_on_underlying_container_type { using view_container_type = typename view_type::view_container_type; using type = typename default_metadata_projection< view_type, P, is_container<view_container_type>::value, is_segmented_view<view_type>::value, is_invertible_view<view_type>::value >::type; }; /// Specialization for the case when the underlying container is a 1D array template<typename P, typename T, typename... OptParams> struct based_on_underlying_container_type<P, array<T, OptParams...>> { using type = linearized_multiarray_view_over_array_view_projection< const view_type, P>; }; public: template<typename P> struct construct_projection { using type = typename based_on_underlying_container_type<P>::type; }; }; } // namespace metadata } // namespace stapl #endif // STAPL_VIEWS_MULTIARRAY_VIEW_HPP
38.629456
99
0.593628
[ "vector", "transform" ]
138ec15124830bc51c6d5bbdb7fdb558434755da
6,633
cpp
C++
jsbridge/src/main/jni/java-types/Long.cpp
beyama/oasis-jsbridge-android
224c995c657518941bd2c0e57abf25f0312e3875
[ "Apache-2.0" ]
null
null
null
jsbridge/src/main/jni/java-types/Long.cpp
beyama/oasis-jsbridge-android
224c995c657518941bd2c0e57abf25f0312e3875
[ "Apache-2.0" ]
null
null
null
jsbridge/src/main/jni/java-types/Long.cpp
beyama/oasis-jsbridge-android
224c995c657518941bd2c0e57abf25f0312e3875
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 ProSiebenSat1.Digital GmbH. * * Originally based on Duktape Android: * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Long.h" #include "JsBridgeContext.h" #include "exceptions/JniException.h" #include "jni-helpers/JArrayLocalRef.h" #include "log.h" #ifdef DUKTAPE # include "JsBridgeContext.h" # include "StackChecker.h" #endif namespace JavaTypes { Long::Long(const JsBridgeContext *jsBridgeContext) : Primitive(jsBridgeContext, JavaTypeId::Long, JavaTypeId::BoxedLong) { } #if defined(DUKTAPE) JValue Long::pop() const { CHECK_STACK_OFFSET(m_ctx, -1); if (!duk_is_number(m_ctx, -1)) { const auto message = std::string("Cannot convert return value ") + duk_safe_to_string(m_ctx, -1) + " to long"; duk_pop(m_ctx); throw std::invalid_argument(message); } if (duk_is_null_or_undefined(m_ctx, -1)) { duk_pop(m_ctx); return JValue(); } auto l = (jlong) duk_require_number(m_ctx, -1); // no real Duktape for int64 so needing a cast from double duk_pop(m_ctx); return JValue(l); } JValue Long::popArray(uint32_t count, bool expanded) const { if (!expanded) { count = static_cast<uint32_t>(duk_get_length(m_ctx, -1)); if (!duk_is_array(m_ctx, -1)) { const auto message = std::string("Cannot convert JS value ") + duk_safe_to_string(m_ctx, -1) + " to Array<Boolean>"; duk_pop(m_ctx); // pop the array throw std::invalid_argument(message); } } JArrayLocalRef<jlong> longArray(m_jniContext, count); jlong *elements = longArray.isNull() ? nullptr : longArray.getMutableElements(); if (elements == nullptr) { duk_pop_n(m_ctx, expanded ? count : 1); // pop the expanded elements or the array throw JniException(m_jniContext); } for (int i = count - 1; i >= 0; --i) { if (!expanded) { duk_get_prop_index(m_ctx, -1, static_cast<duk_uarridx_t>(i)); } JValue value = pop(); elements[i] = value.getLong(); } if (!expanded) { duk_pop(m_ctx); // pop the array } return JValue(longArray); } duk_ret_t Long::push(const JValue &value) const { duk_push_number(m_ctx, static_cast<duk_double_t>(value.getLong())); // no real Duktape for int64 so needing a cast to double return 1; } duk_ret_t Long::pushArray(const JniLocalRef<jarray> &values, bool expand) const { JArrayLocalRef<jlong> longArray(values); const auto count = longArray.getLength(); const jlong *elements = longArray.getElements(); if (elements == nullptr) { throw JniException(m_jniContext); } CHECK_STACK_OFFSET(m_ctx, expand ? count : 1); if (!expand) { duk_push_array(m_ctx); } for (jsize i = 0; i < count; ++i) { duk_push_number(m_ctx, elements[i]); if (!expand) { duk_put_prop_index(m_ctx, -2, static_cast<duk_uarridx_t>(i)); } } return expand ? count : 1; } #elif defined(QUICKJS) namespace { inline jlong getLong(JSContext *ctx, JSValue v) { if (JS_IsInteger(v)) { int64_t i64; JS_ToInt64(ctx, &i64, v); return i64; } if (JS_IsNumber(v)) { return jlong(JS_VALUE_GET_FLOAT64(v)); } alog_warn("Cannot get long from JS: returning 0"); // TODO: proper exception handling return jlong(); } } JValue Long::toJava(JSValueConst v) const { if (!JS_IsNumber(v)) { throw std::invalid_argument("Cannot convert return value to long"); } if (JS_IsNull(v) || JS_IsUndefined(v)) { return JValue(); } return JValue(getLong(m_ctx, v)); } JValue Long::toJavaArray(JSValueConst v) const { if (JS_IsNull(v) || JS_IsUndefined(v)) { return JValue(); } if (!JS_IsArray(m_ctx, v)) { throw std::invalid_argument("Cannot convert JS value to Java array"); } JSValue lengthValue = JS_GetPropertyStr(m_ctx, v, "length"); assert(JS_IsNumber(lengthValue)); uint32_t count = JS_VALUE_GET_INT(lengthValue); JS_FreeValue(m_ctx, lengthValue); JArrayLocalRef<jlong> longArray(m_jniContext, count); if (longArray.isNull()) { throw JniException(m_jniContext); } jlong *elements = longArray.getMutableElements(); if (elements == nullptr) { throw JniException(m_jniContext); } for (uint32_t i = 0; i < count; ++i) { JSValue ev = JS_GetPropertyUint32(m_ctx, v, i); elements[i] = getLong(m_ctx, ev); } longArray.releaseArrayElements(); // copy back elements to Java return JValue(longArray); } JSValue Long::fromJava(const JValue &value) const { return JS_NewInt64(m_ctx, value.getLong()); } JSValue Long::fromJavaArray(const JniLocalRef<jarray> &values) const { JArrayLocalRef<jlong> longArray(values); const auto count = longArray.getLength(); JSValue jsArray = JS_NewArray(m_ctx); const jlong *elements = longArray.getElements(); if (elements == nullptr) { JS_FreeValue(m_ctx, jsArray); throw JniException(m_jniContext); } for (jsize i = 0; i < count; ++i) { JSValue elementValue = JS_NewInt64(m_ctx, elements[i]); JS_SetPropertyUint32(m_ctx, jsArray, static_cast<uint32_t>(i), elementValue); } return jsArray; } #endif JValue Long::callMethod(jmethodID methodId, const JniRef<jobject> &javaThis, const std::vector<JValue> &args) const { jlong l = m_jniContext->callLongMethodA(javaThis, methodId, args); // Explicitly release all values now because they won't be used afterwards JValue::releaseAll(args); if (m_jniContext->exceptionCheck()) { throw JniException(m_jniContext); } return JValue(l); } JValue Long::box(const JValue &longValue) const { // From long to Long static thread_local jmethodID boxId = m_jniContext->getStaticMethodID(getBoxedJavaClass(), "valueOf", "(J)Ljava/lang/Long;"); return JValue(m_jniContext->callStaticObjectMethod(getBoxedJavaClass(), boxId, longValue.getLong())); } JValue Long::unbox(const JValue &boxedValue) const { // From Long to long static thread_local jmethodID unboxId = m_jniContext->getMethodID(getBoxedJavaClass(), "longValue", "()J"); return JValue(m_jniContext->callLongMethod(boxedValue.getLocalRef(), unboxId)); } } // namespace JavaTypes
28.105932
127
0.691844
[ "vector" ]
138ec16db251d7d850ab566f44524f167b6ba2cc
1,987
cc
C++
targets/sqlite3/sqlite3_fuzzer.cc
alex/oss-fuzz
6d8fe671e69f3659370dd19ce3bafb933e89c5ae
[ "Apache-2.0" ]
null
null
null
targets/sqlite3/sqlite3_fuzzer.cc
alex/oss-fuzz
6d8fe671e69f3659370dd19ce3bafb933e89c5ae
[ "Apache-2.0" ]
null
null
null
targets/sqlite3/sqlite3_fuzzer.cc
alex/oss-fuzz
6d8fe671e69f3659370dd19ce3bafb933e89c5ae
[ "Apache-2.0" ]
3
2016-11-19T12:23:39.000Z
2021-06-08T08:05:43.000Z
// Copyright 2015 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 <stddef.h> #include <stdint.h> #include <algorithm> #include <array> #include <string> #include <vector> #include "sqlite3.h" static const std::array<uint8_t, 6> kBadKeyword{{'R', 'E', 'G', 'E', 'X', 'P'}}; bool checkForBadKeyword(const uint8_t* data, size_t size) { auto it = std::search( data, data + size, kBadKeyword.begin(), kBadKeyword.end(), [](char c1, char c2) { return std::toupper(c1) == std::toupper(c2); }); if (it != data + size) return true; return false; } static int Progress(void *not_used_ptr) { return 1; } // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size < 2) return 0; if (checkForBadKeyword(data, size)) return 0; sqlite3* db; int return_code = sqlite3_open_v2( "db.db", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY, 0); if (SQLITE_OK != return_code) return 0; // Use first byte as random selector for other parameters. int selector = data[0]; // To cover both cases when progress_handler is used and isn't used. if (selector & 1) sqlite3_progress_handler(db, 4, &Progress, NULL); else sqlite3_progress_handler(db, 0, NULL, NULL); // Remove least significant bit to make further usage of selector independent. selector >>= 1; sqlite3_stmt* statement = NULL; int result = sqlite3_prepare_v2(db, reinterpret_cast<const char*>(data + 1), static_cast<int>(size - 1), &statement, NULL); if (result == SQLITE_OK) { // Use selector value to randomize number of iterations. for (int i = 0; i < selector; i++) { if (sqlite3_step(statement) != SQLITE_ROW) break; } sqlite3_finalize(statement); } sqlite3_close(db); return 0; }
24.231707
80
0.656266
[ "vector" ]
ca5ee4f7ed3fa8a31a69ad872d9cfce7b9fef358
15,698
cpp
C++
Real.cpp
blambov/RealLib
b36b18ecd3d712311a12f384210735dfa319f86c
[ "Apache-2.0" ]
32
2015-02-11T13:21:24.000Z
2021-09-25T16:19:10.000Z
Real.cpp
blambov/RealLib
b36b18ecd3d712311a12f384210735dfa319f86c
[ "Apache-2.0" ]
null
null
null
Real.cpp
blambov/RealLib
b36b18ecd3d712311a12f384210735dfa319f86c
[ "Apache-2.0" ]
6
2016-06-15T22:44:03.000Z
2021-12-04T21:59:28.000Z
/* RealLib, a library for efficient exact real computation Copyright (C) 2006 Branimir Lambov This library is licensed under the Apache License, Version 2.0 (the "License"); you may not use this library 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 "defs.h" #include <string.h> #include <assert.h> #include <math.h> #include <iostream> #include <string> #include <vector> #include <valarray> #include "Real.h" #include "RealFuncs.h" #include "RealObject.h" namespace RealLib { unsigned g_precMax = 0; unsigned g_memReq = 0; void InitializeRealLib(unsigned precStart, unsigned precMax, unsigned numEst) { // set maximum precision g_precMax = precMax; g_memReq = precStart * numEst; // initialize the underlying arbitrary precision engine InitializeLongFloat(precStart, numEst); } unsigned FinalizeRealLib() { unsigned res = g_WorkingPrecision; g_precMax = 0; // release all temporary estimates while (g_pEstimatesList) { g_pEstimatesList->obj->DestroyEstimate(); } DestroyConstantEstimates(); // finalize the arbitrary precision engine FinalizeLongFloat(); return res; } unsigned ResetRealLib(unsigned precStart) { unsigned precMax = g_precMax; unsigned res = FinalizeRealLib(); InitializeRealLib(precStart, precMax, (g_memReq + precStart - 1) / precStart); return res; } Real::Real(const Real &src) : m_pObject(src.m_pObject) { assert(m_pObject); m_pObject->AddRef(); } Real::Real(RealObject *src) : m_pObject(src) { // copy the object and increase its reference count assert(m_pObject); m_pObject->AddRef(); } Real::Real(const char *src) { // create a new RealFromString object and link to it m_pObject = new RealFromString(src); assert(m_pObject); m_pObject->AddRef(); } Real::Real(const double src) { // create a new RealFromDouble object and link to it m_pObject = new RealFromDouble(src); assert(m_pObject); m_pObject->AddRef(); } Real::Real(OracleFunction oracle) { m_pObject = new RealFromOracle(oracle); assert(m_pObject); m_pObject->AddRef(); } Real::Real(Real::FuncNullary constant, UserInt user) { // create a new RealNullary object and link to it m_pObject = new RealNullary(constant, user); assert(m_pObject); m_pObject->AddRef(); } Real::Real(Real::FuncUnary unfunc, const Real &arg, UserInt user) { // create a new RealUnary object and link to it m_pObject = new RealUnary(unfunc, arg.m_pObject, user); assert(m_pObject); m_pObject->AddRef(); } Real::Real(Real::FuncBinary binfunc, const Real &lhs, const Real &rhs, UserInt user) { // create a new RealBinary object and link to it m_pObject = new RealBinary(binfunc, lhs.m_pObject, rhs.m_pObject, user); assert(m_pObject); m_pObject->AddRef(); } template <class ARRAY> void RealApplyArrayFunction(RealFuncArray arfunc, ARRAY &arr, UserInt user) { long count = (long)arr.size(); RealObject **parr = new RealObject* [count]; for (long i=0;i<count;++i) { parr[i] = arr[i].m_pObject; parr[i]->AddRef(); } RealArray *oarr = new RealArray(arfunc, parr, count, user); assert(oarr); for (long i=0;i<count;++i) arr[i] = Real(new RealArrayElement(oarr, i)); } template void RealApplyArrayFunction(RealFuncArray arfunc, ArrayInterface<Real> &arr, UserInt userdata); template void RealApplyArrayFunction(RealFuncArray arfunc, std::valarray<Real> &arr, UserInt userdata); template void RealApplyArrayFunction(RealFuncArray arfunc, std::vector<Real> &arr, UserInt userdata); // operations. they create suitable RealUnary or RealBinary // object that link to the arguments Real Real::operator - () const { return Real(UnaryMinus, (const Real &) (*this), 0); } Real operator + (const Real &lhs, const Real &rhs) { return Real(Plus, lhs, rhs, 0); } Real operator - (const Real &lhs, const Real &rhs) { return Real(Minus, lhs, rhs, 0); } Real operator * (const Real &lhs, const Real &rhs) { return Real(Multiply, lhs, rhs, 0); } Real operator / (const Real &lhs, const Real &rhs) { return Real(Divide, lhs, rhs, 0); } Real operator * (const Real &lhs, int rhs) { return Real(Multiply, lhs, UserInt(rhs)); } Real operator / (const Real &lhs, int rhs) { return Real(Divide, lhs, UserInt(rhs)); } Real recip(const Real &rhs) { return Real(recip, rhs, 0); } CreateRealConstant(Pi, pi) CreateRealConstant(Ln2, ln2) CreateUnaryRealFunction(sq) CreateUnaryRealFunction(abs) CreateUnaryRealFunction(sqrt) CreateUnaryRealFunction(rsqrt) CreateUnaryRealFunction(log) CreateUnaryRealFunction(exp) CreateBinaryRealFunction(atan2) CreateUnaryRealFunction(tan) CreateUnaryRealFunction(cos) CreateUnaryRealFunction(sin) CreateUnaryRealFunction(acos) CreateUnaryRealFunction(asin) CreateUnaryRealFunction(atan) // the tricky part struct RecursionSavedState { RealObject *ptr; int sibling; }; Encapsulation PerformEvaluation(RealObject *pObj) { assert(pObj); int maxpos = 0; if (!(pObj->HasEstimate() || pObj->m_Depth < EvaluationDepth)) { // depths range from 0 to this object's depth, inclusive RecursionSavedState* Stack = new RecursionSavedState[pObj->m_Depth+1]; int sPos = 0; RealObject *pSib; pObj->AddRef(); Stack[sPos].ptr = pObj; Stack[sPos].sibling = 0; try { // while we have not exhausted the depth-first search while (sPos >= 0) { // while there are more siblings of the currect object while (!!(pSib = Stack[sPos].ptr->GetSibling(Stack[sPos].sibling))) { ++Stack[sPos].sibling; // if we don't already have an Encapsulation if (!pSib->HasEstimate() /*&& pSib->m_Depth > EvaluationDepth*/) { // save and reference the new child and move to it ++sPos; if (sPos > maxpos) maxpos = sPos; pSib->AddRef(); Stack[sPos].ptr = pSib; Stack[sPos].sibling = 0; } } // no more children of this node: prepare an Encapsulation // note we're now sure there will be no recursion here // because we've prepared estimates in all siblings Stack[sPos].ptr->GetEstimate(); Stack[sPos].ptr->Release(0); // Release(0) does not decrease m_EstimateRefs, but GetEstimate // does. We've added an extra reference, which is now taken // care of. // move up in the stack --sPos; } } catch (...) { // clear the recursion stack in case of exception while (sPos>=0) { Stack[sPos--].ptr->Release(); } delete [] Stack; throw; } delete [] Stack; } // PerformEvaluation should not count as a use of the object // because the user working with Reals might request a value more than once pObj->AddRef(); Encapsulation res(pObj->GetEstimate()); pObj->Release(0); return res; // Release(0) does not decrease the cached value reference count } void PerformDeletion(RealObject *pObj) { assert(pObj); if (pObj->GetRefCount() == 1 && pObj->m_Depth >= EvaluationDepth) { // depths range from 0 to this object's depth, inclusive RecursionSavedState* Stack = new RecursionSavedState[pObj->m_Depth+1]; int sPos = 0; RealObject *pSib; Stack[sPos].ptr = pObj; Stack[sPos].sibling = 0; // while we have not exhausted the depth-first search while (sPos >= 0) { // while there are more siblings of the currect object while (!!(pSib = Stack[sPos].ptr->GetSibling(Stack[sPos].sibling))) { ++Stack[sPos].sibling; // if we have to delete it also if (pSib->GetRefCount() == 1 /*&& pSib->m_Depth > EvaluationDepth*/) { // save the new child and move to it // no need to reference, we're stealing the existing one ++sPos; Stack[sPos].ptr = pSib; Stack[sPos].sibling = 0; } else pSib->Release(); } // no more children of this node: delete it // do not release as this will trigger recursive // calls which we have already performed // note we will reach this point only for object that // really need to be deleted. assert(Stack[sPos].ptr->GetRefCount() == 1); Stack[sPos].ptr->NonRecursiveRelease(); // move up in the stack --sPos; } delete [] Stack; } else pObj->Release(1); } Real::~Real() { PerformDeletion(m_pObject); } Real& Real::operator = (const Real &rhs) { PerformDeletion(m_pObject); m_pObject = rhs.m_pObject; assert(m_pObject); m_pObject->AddRef(); return *this; } #define PRECMULTIPLIER 2 #define PRECDIVISOR 1 bool IsProbableZero(const Encapsulation &r, u32 prec) { // "probable zero": 0.0 is in the range of possible values, // and the current Encapsulation is smaller than the wanted precision return !r.IsNonZero() && Minus(absEncapsulation(r, 0) << prec, Encapsulation(1.0), 0).IsNegative(); // abs(r) < (Encapsulation(1) >> prec); // && (r+r.GetError()).weak_normalize() < -i32(prec) // && (r-r.GetError()).weak_normalize() < -i32(prec); } #define DELETE(x) { if (x) { delete x; x = NULL; } } // when resetting from an internal function, we must make sure // Encapsulation's begin and finish functions are called correctly // also exceptions from within MakeGoodEstimate/MakeNonZero // have to call the finish function unsigned InternalReset(unsigned precStart) { //cout << "Internal reset, prec " << g_WorkingPrecision << " new " << precStart << endl; Encapsulation::FinishComputation(); unsigned precMax = g_precMax; unsigned res = FinalizeRealLib(); InitializeRealLib(precStart, precMax, (g_memReq + precStart - 1) / precStart); Encapsulation::BeginComputation(); return res; } // evaluate object. // gradually increase the precision until the result can be considered // correct to the requirements Encapsulation MakeGoodEstimate(RealObject *pObj, i32 precision, i32 probzeroprec) { //cout << "MakeGoodEstimate " << pObj << " prec " << precision << " pzprec " << probzeroprec << endl; if (g_WorkingPrecision*32 <= precision + 32) InternalReset(precision/32 + 3); u32 prec = g_WorkingPrecision; do { try { Encapsulation r(PerformEvaluation(pObj)); if (!r.IsValueValid() || r.GetRelativeError() < precision && !IsProbableZero(r, probzeroprec)) { throw PrecisionException("MakeGoodEstimate()"); } return r; } catch (PrecisionException &e) { #ifdef REALLIB_SHOW_PRECISION_INCREASES using namespace std; cout << e; if (prec >= g_precMax) { cout << ", giving up.\n"; throw; } else { cout << ", raising precision from " << prec; InternalReset(prec = min(g_precMax, prec * PRECMULTIPLIER / PRECDIVISOR)); cout << " to " << prec << endl; } #else e; if (prec >= g_precMax) throw; else InternalReset(prec = min(g_precMax, prec * PRECMULTIPLIER / PRECDIVISOR)); #endif } } while (1); } Encapsulation MakeNonZero(RealObject *pObj) { u32 prec = g_WorkingPrecision; do { try { Encapsulation r(PerformEvaluation(pObj)); if (!r.IsValueValid() || !r.IsNonZero()) { throw PrecisionException("MakeNonZero()"); } return r; } catch (PrecisionException e) { #ifdef REALLIB_SHOW_PRECISION_INCREASES using namespace std; cout << e; if (prec >= g_precMax) { cout << ", giving up.\n"; throw; } else { cout << ", raising precision from " << prec; InternalReset(prec = min(g_precMax, prec * PRECMULTIPLIER / PRECDIVISOR)); cout << " to " << prec << endl; } #else if (prec >= g_precMax) throw; else InternalReset(prec = min(g_precMax, prec * PRECMULTIPLIER / PRECDIVISOR)); #endif } } while (1); } double Real::AsDouble() const { Encapsulation::Computation comp; Encapsulation r(MakeGoodEstimate(m_pObject, 55, 1024)); return r.weak_AsDouble(); } char *Real::AsDecimal(char *buffer, unsigned lenwanted) const { Encapsulation::Computation comp; u32 bitswanted = u32(ceil(LOG_2_10 * lenwanted)); Encapsulation r(MakeGoodEstimate(m_pObject, bitswanted, bitswanted*2)); if (IsProbableZero(r, bitswanted*2)) #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable:4996) strcpy(buffer, "probable zero"); #pragma warning (pop) #else strcpy(buffer, "probable zero"); #endif else r.weak_AsDecimal(buffer, lenwanted); return buffer; } // looks like a strange function, and it is, because it // can only return true, since equality is not decidable. // this function can also be exited via exceptions-- // which would mean that the number is zero up to the // current max precision bool Real::IsNonZero() const { Encapsulation::Computation comp; MakeNonZero(m_pObject); return true; } bool Real::IsNegative() const { Encapsulation::Computation comp; Encapsulation r(MakeNonZero(m_pObject)); return r.IsNegative(); } bool Real::IsPositive() const { Encapsulation::Computation comp; Encapsulation r(MakeNonZero(m_pObject)); return r.IsPositive(); } std::ostream& operator << (std::ostream& out, const Real &re) { Encapsulation::Computation comp; u32 pr = out.precision(); if (out.flags() & std::ios::scientific) ++pr; u32 bitswanted = u32(ceil(LOG_2_10 * (pr))); u32 pzbits = bitswanted; if (!(out.flags() & std::ios::fixed)) pzbits *= 2; // important: r should only be alive while there's no chance of // reiteration { Encapsulation r(MakeGoodEstimate(re.m_pObject, bitswanted, pzbits)); if (!(out.flags() & std::ios::fixed) || r.weak_lt(1)) { if (IsProbableZero(r, pzbits) && !(out.flags() & std::ios::fixed)) out << "probable zero"; else out << r; return out; } bitswanted += r.weak_normalize(); } // r is destroyed here before the possible reiteration // which would not occur if r was good enough (due to caching) return out << MakeGoodEstimate(re.m_pObject, bitswanted, pzbits); } std::istream& operator >> (std::istream &in, Real &r) { std::string s; in >> s; if (in) r = Real(s.c_str()); return in; } } // namespace
29.507519
108
0.621735
[ "object", "vector" ]
ca63964b684453f94f3c52e52dfd47e77cc28717
7,612
cpp
C++
example/linalgperf.cpp
onitake/glam
1b9d597e78936a7dba37c2dae1b06a58dd5e233a
[ "BSD-2-Clause" ]
4
2017-01-25T15:01:48.000Z
2017-05-15T18:01:31.000Z
example/linalgperf.cpp
onitake/glam
1b9d597e78936a7dba37c2dae1b06a58dd5e233a
[ "BSD-2-Clause" ]
null
null
null
example/linalgperf.cpp
onitake/glam
1b9d597e78936a7dba37c2dae1b06a58dd5e233a
[ "BSD-2-Clause" ]
null
null
null
/* * GLAM - GLSL Linear Algebra Math Library * * Copyright (c) 2012-2014, Gregor Riepl <onitake@gmail.com> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <cassert> #include <cmath> #include <stdint.h> #include <glam/matrix.h> using glam::determinant; using glam::inverse; using glam::transpose; typedef glam::Matrix<float, 2, 2> Matrix2f; typedef glam::Matrix<float, 5, 5> Matrix5f; typedef glam::Matrix<float, 6, 6> Matrix6f; typedef glam::Matrix<float, 10, 10> Matrix10f; typedef glam::Matrix<double, 10, 10> Matrix10d; // Transposed notation const float M1[6*6] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, }; const float M2[2*2] = { 1, 2, 3, 4, }; const float M3[5*5] = { 152, 218, 190, 27, 46, 222, 225, 181, 110, 120, 126, 230, 28, 29, 19, 248, 69, 186, 160, 224, 154, 173, 197, 49, 43, }; // The 0 allows testing if permutations work const double M4[10*10] = { 0, 94, 23, 152, 91, 248, 95, 250, 186, 165, 69, 61, 56, 182, 247, 14, 253, 146, 32, 92, 215, 247, 75, 192, 117, 117, 111, 118, 7, 38, 1, 55, 49, 162, 13, 255, 135, 142, 145, 247, 93, 15, 121, 46, 103, 138, 118, 144, 67, 214, 96, 232, 114, 87, 229, 109, 180, 155, 188, 12, 13, 146, 36, 155, 184, 69, 59, 161, 232, 224, 81, 230, 54, 207, 125, 169, 1, 236, 135, 63, 74, 46, 184, 164, 253, 254, 42, 225, 229, 183, 214, 41, 224, 111, 125, 214, 22, 2, 92, 24, }; // Fuzzy comparison // Adapted from http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/ bool compare(float a, float b) { union Float { Float(float num = 0.0f) : f(num) { } // Portable extraction of components. bool negative() const { return (i >> 31) != 0; } int32_t fraction() const { return i & ((1 << 23) - 1); } int32_t exponent() const { return (i >> 23) & 0xff; } int32_t i; float f; }; Float ua(a); Float ub(b); //std::cout << "a=" << (ua.negative() ? "-" : "") << ua.fraction() << "e" << (ua.exponent() - 127) << std::endl; //std::cout << "b=" << (ub.negative() ? "-" : "") << ub.fraction() << "e" << (ub.exponent() - 127) << std::endl; // Compare the exponents int32_t edif = std::abs(ua.exponent() - ub.exponent()); //std::cout << "edif=" << edif << std::endl; if (edif == 0) { // Exponents are equal, allow for a small error in value int32_t fdif = std::abs(ua.fraction() - ub.fraction()); //std::cout << "fdif=" << fdif << std::endl; if (fdif > 0x000100) { return false; } return true; } // Scale the relative allowable error according to the exponent of the smaller of a and b // Note that we do not subtract 127 from the exponent as per the definition of IEEE 754 single-precision // 128 and up: lowest allowable error // 1: maximum allowable error int32_t max = 128 - std::min(ua.exponent(), ub.exponent()); if (max < 0) max = 0; //std::cout << "max=" << max << std::endl; if (edif > max) { return false; } return true; } bool compare(double a, double b) { union Double { Double(float num = 0.0f) : d(num) { } // Portable extraction of components. bool negative() const { return (i >> 63) != 0; } int64_t fraction() const { return i & ((1L << 52) - 1); } int64_t exponent() const { return (i >> 52) & 0x7ffL; } int64_t i; double d; }; Double ua(a); Double ub(b); // Compare the exponents int64_t edif = std::abs(ua.exponent() - ub.exponent()); //std::cout << "edif=" << edif << std::endl; if (edif == 0) { // Exponents are equal, allow for a small error in value int64_t fdif = std::abs(ua.fraction() - ub.fraction()); //std::cout << "fdif=" << fdif << std::endl; if (fdif > 0x0000000010000L) { return false; } return true; } // Scale the relative allowable error according to the exponent of the smaller of a and b // Note that we do not subtract 1023 from the exponent as per the definition of IEEE 754 double-precision // 1024 and up: lowest allowable error // 1: maximum allowable error int64_t max = 1024L - std::min(ua.exponent(), ub.exponent()); //std::cout << "max=" << max << std::endl; if (edif > max) { return false; } return true; } // Matrix equality, allowing for error template <class T, size_t M, size_t N> bool compare(const glam::Matrix <T, M, N> &a, const glam::Matrix <T, M, N> &b) { for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { if (!compare(a[i][j], b[i][j])) { return false; } } } return true; } int main(int argc, char **argv) { Matrix6f m1(M1); Matrix2f m2(M2); Matrix5f m3(M3); Matrix10d m4(M4); Matrix2f i2(1); Matrix5f i5(1); Matrix6f i6(1); Matrix10d i10(1); std::cout << m1 << std::endl; std::cout << transpose(m1) << std::endl; assert(m1 * i6 == m1); assert(i6 * m1 == m1); std::cout << m2 << std::endl; std::cout << inverse(m2) << std::endl; assert(m2 * inverse(m2) == i2); assert(inverse(m2) * m2 == i2); assert(determinant(m1) == 0); bool e = false; try { inverse(m1); } catch (glam::NonInvertibleMatrixException &ex) { e = true; } assert(e); std::cout << m3 << std::endl; std::cout << inverse(m3) << std::endl; std::cout << (m3 * inverse(m3)) << std::endl; assert(compare(m3 * inverse(m3), i5)); assert(compare(inverse(m3) * m3, i5)); assert(!compare(inverse(m2), m2)); assert(!compare(inverse(m3), m3)); //assert(compare(m3.inv(), m3.invr())); std::cout << "det(m3)[1] = " << determinant(m3) << std::endl; //std::cout << "det(m3)[2] = " << m3.detr() << std::endl; //assert(compare(m3.det(), m3.detr())); //Matrix10d m4i = m4.inv(); //std::cout << m4i << std::endl; //std::cout << (m4 * m4i) << std::endl; //assert(compare(m4 * m4i, i10)); /*std::vector <Matrix10d> lup = m4.lup(); std::cout << lup[0] << std::endl; std::cout << lup[1] << std::endl; std::cout << lup[2] << std::endl; std::cout << m4 << std::endl; std::cout << (lup[0] * lup[1]) << std::endl; std::cout << (lup[1] * lup[0]) << std::endl; // A = P^-1LU, P^-1 = Pt assert(compare(lup[2].t() * lup[0] * lup[1], m4)); assert(!compare(lup[1] * lup[0], m4));*/ Matrix10d m4i = inverse(m4); std::cout << m4i << std::endl; assert(compare(m4 * m4i, i10)); assert(!compare(m4, m4i)); //Matrix10d m4i2 = m4.invr(); //std::cout << m4i2 << std::endl; //assert(compare(m4 * m4i2, i10)); return 0; }
33.53304
113
0.626511
[ "vector" ]
ca64873814b270a857f99c7a37a167119ecf438b
22,457
hpp
C++
Sisyphe/interpreter/plugins/libparsePlg/interpreter/src/CPPParserInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libparsePlg/interpreter/src/CPPParserInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libparsePlg/interpreter/src/CPPParserInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
/* * CPPParserInterpreter.hpp * * * @date 20-10-2018 * @author Teddy DIDE * @version 1.00 */ #ifndef _CPP_PARSER_INTERPRETER_H_ #define _CPP_PARSER_INTERPRETER_H_ #include "config.hpp" #include "Macros.hpp" #include "Base.hpp" #include "String.hpp" #include <vector> #include <functional> #include <any> #define A(str) encode<EncodingT,ansi>(str) #define C(str) encode<ansi,EncodingT>(str) using namespace boost; NAMESPACE_BEGIN(interp) using FlagSet = uint64_t; template <class EncodingT> class ParserInformation { private: std::optional<typename EncodingT::string_t> mName; std::optional<size_t> mType; public: ParserInformation(typename EncodingT::string_t& name, size_t type) : mName(name), mType(type) {} ParserInformation(typename EncodingT::string_t& name) : mName(name) {} bool hasName() const { return mName.has_value(); } bool hasType() const { return mType.has_value(); } const typename EncodingT::string_t& getName() const { return *mName; } size_t getType() const { return *mType; } }; class ParserBlock { private: size_t mStart, mEnd; std::any mData; public: ParserBlock() : mStart(-1), mEnd(-1) {} ParserBlock(size_t start, size_t end) : mStart(start), mEnd(end) {} ParserBlock(size_t val) : mStart(val), mEnd(val) {} template <class T> ParserBlock(size_t start, size_t end, T data) : mStart(start), mEnd(end), mData(data) {} static bool compareStart(const ParserBlock& me, const ParserBlock& o) { return me.mStart <= o.mStart; } static bool compareEnd(const ParserBlock& me, const ParserBlock& o) { return me.mEnd < o.mEnd; } bool inRange(size_t val) const { return (mStart <= val) && (val < mEnd); } size_t Start() const { return mStart; } size_t End() const { return mEnd; } template <class T> T data() const { return std::any_cast<T>(mData); } }; template <class EncodingT> class CPPParserInterpreter : public Base<EncodingT> { private: enum class FLAGS : std::uint8_t { IN_NO_CODE, IN_COMMENT, IN_CPP_COMMENT, IN_C_COMMENT, IN_STRING, IN_DBL_STRING, IN_SMPL_STRING, IN_ESC_STRING, IN_PREPROCESSOR, IN_PREPROCESSOR_DIRECTIVE, IN_CODE_BLOCK, IN_WORD, CLEAR_WORD, IN_CLASS, IN_CLASS_DECL, IN_CLASS_DECL_SPEC, IN_CLASS_ID, IN_CLASS_BLOCK, IN_CLASS_END, IN_CLASS_SPACE, IN_NAMESPACE, IN_NAMESPACE_ID, IN_NAMESPACE_BLOCK, IN_ENUM, IN_ENUM_ID, IN_ENUM_BLOCK, IN_ENUM_END, SET_TEMPLATE, IN_TEMPLATE, IN_TEMPLATE_DECL, IN_TYPEDEF, IN_MEMBER, IN_MEMBER_DECL, IN_MEMBER_ID, IN_ATTRIBUTE, IN_FUNCTION, IN_FUNCTION_BLOCK, IN_STATEMENT, IN_LITERAL, CODE_BREAK, IN_FUNCTION_SPACE, IN_FUNCTION_INIT, IN_FUNCTION_PARAM, }; static bool IN_CODE(const FlagSet& flags); template <typename... T> static ParserBlock InfoBlock(size_t start, size_t end, T&&... args); void parse(); boost::shared_ptr< Base<EncodingT> > mContentPtr; typename EncodingT::string_t mContent; boost::shared_ptr< Base<EncodingT> > mCodePtr; typename EncodingT::string_t mCode; std::vector<ParserBlock> mNoCode; // String + Comment std::vector<ParserBlock> mComments; // CppComment + CComment std::vector<ParserBlock> mLines; size_t mLineStart; void parseLine(size_t i, FlagSet& flags); std::vector<ParserBlock> mStrings; size_t mStringStart; void parseDblString(size_t i, FlagSet& flags); void parseSplString(size_t i, FlagSet& flags); std::vector<ParserBlock> mCppComments; size_t mCppCommentStart; void parseCppComment(size_t i, FlagSet& flags); std::vector<ParserBlock> mCComments; size_t mCCommentStart; void parseCComment(size_t i, FlagSet& flags); std::vector<ParserBlock> mPreprocessors; size_t mPreprocessorStart; typename EncodingT::string_t mPreprocessorName; void parsePreprocessor(size_t i, FlagSet& flags); std::vector<ParserBlock> mCodeBlocks; std::vector<size_t> mCodeBlockStart; void parseCodeBlock(size_t i, FlagSet& flags); void parseType(size_t i, FlagSet& flags); std::vector<ParserBlock> mComposition; std::vector<ParserBlock> mClass; std::vector<ParserBlock> mSpecifier; std::vector<ParserBlock> mStruct; std::vector<ParserBlock> mUnion; std::vector<size_t> mClassStart; std::vector<size_t> mSpecifierStart; std::vector<typename EncodingT::string_t> mClassName; std::vector<size_t> mClassBlock; std::vector<size_t> mType; std::vector<typename EncodingT::string_t> mSpecifierName; void parseClass(size_t i, FlagSet& flags); std::vector<ParserBlock> mNamespace; std::vector<size_t> mNamespaceStart; std::vector<typename EncodingT::string_t> mNamespaceName; std::vector<size_t> mNamespaceBlock; void parseNamespace(size_t i, FlagSet& flags); std::vector<ParserBlock> mEnum; size_t mEnumStart; typename EncodingT::string_t mEnumName; void parseEnum(size_t i, FlagSet& flags); std::vector<ParserBlock> mStatements; size_t mStatementStart; void parseStatement(size_t i, FlagSet& flags); size_t mWordStart; typename EncodingT::string_t mWord; typename EncodingT::string_t mPreviousWord; void parseWord(size_t i, FlagSet& flags); size_t mTemplateDelcStart; std::vector<size_t> mTemplateStart; void parseTemplate(size_t i, FlagSet& flags); std::vector<ParserBlock> mLiterals; size_t mLiteralStart; void parseLiteral(size_t i, FlagSet& flags); std::vector<ParserBlock> mFunctions; std::vector<ParserBlock> mAttributes; std::vector<size_t> mMemberStart; std::vector<bool> mIsFunction; std::vector<typename EncodingT::string_t> mMemberName; std::vector<size_t> mFunctionBlock; size_t mFctParamParenth; void parseMember(size_t i, FlagSet& flags); static constexpr size_t LINES_ID = 1U; static constexpr size_t STRINGS_ID = (1U << 2U); static constexpr size_t C_COMMENTS_ID = (1U << 3U); static constexpr size_t CPP_COMMENTS_ID = (1U << 4U); static constexpr size_t PREPROCESSORS_ID = (1U << 5U); static constexpr size_t CODE_BLOCKS_ID = (1U << 6U); static constexpr size_t CLASS_ID = (1U << 7U); static constexpr size_t CLASS_SPECIFIER_ID = (1U << 8U); static constexpr size_t NAMESPACE_ID = (1U << 9U); static constexpr size_t STRUCT_ID = (1U << 10U); static constexpr size_t ENUM_ID = (1U << 11U); static constexpr size_t FUNCTION_ID = (1U << 12U); static constexpr size_t ATTRIBUTE_ID = (1U << 13U); static constexpr size_t UNION_ID = (1U << 14U); static constexpr size_t STATEMENT_ID = (1U << 15U); static constexpr size_t LITERAL_ID = (1U << 16U); static constexpr size_t COMPOSITION_ID = CLASS_ID + STRUCT_ID + UNION_ID; static constexpr size_t COMMENTS_ID = C_COMMENTS_ID + CPP_COMMENTS_ID; static constexpr size_t NO_CODE_ID = COMMENTS_ID + STRINGS_ID; static constexpr int NO_POS = -1; bool iterators(size_t blockId, std::vector<ParserBlock>::const_iterator& first, std::vector<ParserBlock>::const_iterator& last) const; long long find(size_t val, size_t blockId, ParserBlock& block) const; static typename EncodingT::string_t getNativeContent(const typename EncodingT::string_t& path); public: CPPParserInterpreter(); virtual typename EncodingT::string_t toString() const; virtual boost::shared_ptr< Base<EncodingT> > clone() const; virtual typename EncodingT::string_t getClassName() const; virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params); FACTORY_PROTOTYPE1(getFileContent, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getFileContent(const boost::shared_ptr< Base<EncodingT> >& path) const; FACTORY_PROTOTYPE1(parseFile, In< boost::shared_ptr< Base<EncodingT> > >) void parseFile(const boost::shared_ptr< Base<EncodingT> >& path); FACTORY_PROTOTYPE1(parse, In< boost::shared_ptr< Base<EncodingT> > >) void parse(const boost::shared_ptr< Base<EncodingT> >& content); boost::shared_ptr< Base<EncodingT> > getContent() const; boost::shared_ptr< Base<EncodingT> > getSourceCode() const; boost::shared_ptr< Base<EncodingT> > literalId() const; boost::shared_ptr< Base<EncodingT> > linesId() const; boost::shared_ptr< Base<EncodingT> > stringsId() const; boost::shared_ptr< Base<EncodingT> > CCommentsId() const; boost::shared_ptr< Base<EncodingT> > CppCommentsId() const; boost::shared_ptr< Base<EncodingT> > preprocessorsId() const; boost::shared_ptr< Base<EncodingT> > commentsId() const; boost::shared_ptr< Base<EncodingT> > noCodeId() const; boost::shared_ptr< Base<EncodingT> > codeBlockId() const; boost::shared_ptr< Base<EncodingT> > classId() const; boost::shared_ptr< Base<EncodingT> > classSpecifierId() const; boost::shared_ptr< Base<EncodingT> > namespaceId() const; boost::shared_ptr< Base<EncodingT> > structId() const; boost::shared_ptr< Base<EncodingT> > unionId() const; boost::shared_ptr< Base<EncodingT> > compositionId() const; boost::shared_ptr< Base<EncodingT> > enumId() const; boost::shared_ptr< Base<EncodingT> > functionId() const; boost::shared_ptr< Base<EncodingT> > attributeId() const; boost::shared_ptr< Base<EncodingT> > statementId() const; boost::shared_ptr< Base<EncodingT> > noPos() const; FACTORY_PROTOTYPE2(indexOf, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > indexOf(const boost::shared_ptr< Base<EncodingT> >& val, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(inRange, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > inRange(const boost::shared_ptr< Base<EncodingT> >& val, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(range, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > range(const boost::shared_ptr< Base<EncodingT> >& val, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(previous, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > previous(const boost::shared_ptr< Base<EncodingT> >& val, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE1(array, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > array(const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE1(size, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > size(const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(at, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > at(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(extract, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > extract(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(extractCode, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > extractCode(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(name, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > name(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE2(type, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > type(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId) const; FACTORY_PROTOTYPE4(include, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > include(const boost::shared_ptr< Base<EncodingT> >& index, const boost::shared_ptr< Base<EncodingT> >& blockId, const boost::shared_ptr< Base<EncodingT> >& origin, const boost::shared_ptr< Base<EncodingT> >& blockOrig) const; FACTORY_BEGIN_REGISTER CLASS_KEY_REGISTER ( CPPParserInterpreter, UCS("CPPParser") ); METHOD_KEY_REGISTER1( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, getFileContent, const_t, UCS("CPPParser::FileContent") ); METHOD_KEY_REGISTER1( CPPParserInterpreter, void, parseFile, no_const_t, UCS("CPPParser::ParseFile") ); METHOD_KEY_REGISTER1( CPPParserInterpreter, void, parse, no_const_t, UCS("CPPParser::Parse") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, getContent, const_t, UCS("CPPParser::Content") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, getSourceCode, const_t, UCS("CPPParser::SourceCode") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, literalId, const_t, UCS("CPPParser::Literal") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, linesId, const_t, UCS("CPPParser::Lines") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, stringsId, const_t, UCS("CPPParser::Strings") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, CCommentsId, const_t, UCS("CPPParser::CComments") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, CppCommentsId, const_t, UCS("CPPParser::CppComments") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, preprocessorsId, const_t, UCS("CPPParser::Preprocessors") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, commentsId, const_t, UCS("CPPParser::Comments") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, noCodeId, const_t, UCS("CPPParser::NoCode") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, codeBlockId, const_t, UCS("CPPParser::CodeBlock") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, classId, const_t, UCS("CPPParser::Class") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, structId, const_t, UCS("CPPParser::Struct") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, unionId, const_t, UCS("CPPParser::Union") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, classSpecifierId, const_t, UCS("CPPParser::ClassSpecifier") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, namespaceId, const_t, UCS("CPPParser::Namespace") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, compositionId, const_t, UCS("CPPParser::Composition") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, enumId, const_t, UCS("CPPParser::Enum") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, statementId, const_t, UCS("CPPParser::Statement") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, functionId, const_t, UCS("CPPParser::Function") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, attributeId, const_t, UCS("CPPParser::Attribute") ); METHOD_KEY_REGISTER ( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, noPos, const_t, UCS("CPPParser::NoPos") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, indexOf, const_t, UCS("CPPParser::IndexOf") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, inRange, const_t, UCS("CPPParser::InRange") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, range, const_t, UCS("CPPParser::Range") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, previous, const_t, UCS("CPPParser::Previous") ); METHOD_KEY_REGISTER1( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, array, const_t, UCS("CPPParser::Array") ); METHOD_KEY_REGISTER1( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, size, const_t, UCS("CPPParser::Size") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, extract, const_t, UCS("CPPParser::Extract") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, extractCode, const_t, UCS("CPPParser::ExtractCode") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, at, const_t, UCS("CPPParser::At") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, name, const_t, UCS("CPPParser::Name") ); METHOD_KEY_REGISTER2( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, type, const_t, UCS("CPPParser::Type") ); METHOD_KEY_REGISTER4( CPPParserInterpreter, boost::shared_ptr< Base<EncodingT> >, include, const_t, UCS("CPPParser::Include") ); FACTORY_END_REGISTER FACTORY_BEGIN_UNREGISTER CLASS_KEY_UNREGISTER ( UCS("CPPParser") ); METHOD_KEY_UNREGISTER1( UCS("CPPParser::FileContent") ); METHOD_KEY_UNREGISTER1( UCS("CPPParser::ParseFile") ); METHOD_KEY_UNREGISTER1( UCS("CPPParser::Parse") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Content") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::SourceCode") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Literal") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Lines") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Strings") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::CComments") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::CppComments") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Preprocessors") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Comments") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::NoCode") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::CodeBlock") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Class") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Struct") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Union") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Composition") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Namespace") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::ClassSpecifier") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Enum") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Statement") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Function") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::Attribute") ); METHOD_KEY_UNREGISTER ( UCS("CPPParser::NoPos") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::IndexOf") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::InRange") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::Range") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::Previous") ); METHOD_KEY_UNREGISTER1( UCS("CPPParser::Array") ); METHOD_KEY_UNREGISTER1( UCS("CPPParser::Size") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::Extract") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::ExtractCode") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::At") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::Name") ); METHOD_KEY_UNREGISTER2( UCS("CPPParser::Type") ); METHOD_KEY_UNREGISTER4( UCS("CPPParser::Include") ); FACTORY_END_UNREGISTER }; NAMESPACE_END #undef A #undef C #include "CPPParserInterpreter_impl.hpp" #endif
46.207819
270
0.654406
[ "vector" ]
ca6a27f40592008b9dcc12bc7610199c010fa7c9
36,153
cc
C++
Docker/tweezer/table/block_based/block_based_table_factory.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
Docker/tweezer/table/block_based/block_based_table_factory.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
Docker/tweezer/table/block_based/block_based_table_factory.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
null
null
null
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "table/block_based/block_based_table_factory.h" #include <stdint.h> #include <cinttypes> #include <memory> #include <string> #include "options/configurable_helper.h" #include "port/port.h" #include "rocksdb/cache.h" #include "rocksdb/convenience.h" #include "rocksdb/flush_block_policy.h" #include "rocksdb/utilities/options_type.h" #include "table/block_based/block_based_table_builder.h" #include "table/block_based/block_based_table_reader.h" #include "table/format.h" #include "util/mutexlock.h" #include "util/string_util.h" namespace ROCKSDB_NAMESPACE { void TailPrefetchStats::RecordEffectiveSize(size_t len) { MutexLock l(&mutex_); if (num_records_ < kNumTracked) { num_records_++; } records_[next_++] = len; if (next_ == kNumTracked) { next_ = 0; } } size_t TailPrefetchStats::GetSuggestedPrefetchSize() { std::vector<size_t> sorted; { MutexLock l(&mutex_); if (num_records_ == 0) { return 0; } sorted.assign(records_, records_ + num_records_); } // Of the historic size, we find the maximum one that satisifis the condtiion // that if prefetching all, less than 1/8 will be wasted. std::sort(sorted.begin(), sorted.end()); // Assuming we have 5 data points, and after sorting it looks like this: // // +---+ // +---+ | | // | | | | // | | | | // | | | | // | | | | // +---+ | | | | // | | | | | | // +---+ | | | | | | // | | | | | | | | // +---+ | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // +---+ +---+ +---+ +---+ +---+ // // and we use every of the value as a candidate, and estimate how much we // wasted, compared to read. For example, when we use the 3rd record // as candiate. This area is what we read: // +---+ // +---+ | | // | | | | // | | | | // | | | | // | | | | // *** *** *** ***+ *** *** *** *** ** // * | | | | | | // +---+ | | | | | * // * | | | | | | | | // +---+ | | | | | | | * // * | | | | X | | | | | // | | | | | | | | | * // * | | | | | | | | | // | | | | | | | | | * // * | | | | | | | | | // *** *** ***-*** ***--*** ***--*** +**** // which is (size of the record) X (number of records). // // While wasted is this area: // +---+ // +---+ | | // | | | | // | | | | // | | | | // | | | | // *** *** *** ****---+ | | | | // * * | | | | | // * *-*** *** | | | | | // * * | | | | | | | // *--** *** | | | | | | | // | | | | | X | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // +---+ +---+ +---+ +---+ +---+ // // Which can be calculated iteratively. // The difference between wasted using 4st and 3rd record, will // be following area: // +---+ // +--+ +-+ ++ +-+ +-+ +---+ | | // + xxxxxxxxxxxxxxxxxxxxxxxx | | | | // xxxxxxxxxxxxxxxxxxxxxxxx | | | | // + xxxxxxxxxxxxxxxxxxxxxxxx | | | | // | xxxxxxxxxxxxxxxxxxxxxxxx | | | | // +-+ +-+ +-+ ++ +---+ +--+ | | | // | | | | | | | // +---+ ++ | | | | | | // | | | | | | X | | | // +---+ ++ | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // | | | | | | | | | | // +---+ +---+ +---+ +---+ +---+ // // which will be the size difference between 4st and 3rd record, // times 3, which is number of records before the 4st. // Here we assume that all data within the prefetch range will be useful. In // reality, it may not be the case when a partial block is inside the range, // or there are data in the middle that is not read. We ignore those cases // for simplicity. assert(!sorted.empty()); size_t prev_size = sorted[0]; size_t max_qualified_size = sorted[0]; size_t wasted = 0; for (size_t i = 1; i < sorted.size(); i++) { size_t read = sorted[i] * sorted.size(); wasted += (sorted[i] - prev_size) * i; if (wasted <= read / 8) { max_qualified_size = sorted[i]; } prev_size = sorted[i]; } const size_t kMaxPrefetchSize = 512 * 1024; // Never exceed 512KB return std::min(kMaxPrefetchSize, max_qualified_size); } #ifndef ROCKSDB_LITE const std::string kOptNameMetadataCacheOpts = "metadata_cache_options"; static std::unordered_map<std::string, PinningTier> pinning_tier_type_string_map = { {"kFallback", PinningTier::kFallback}, {"kNone", PinningTier::kNone}, {"kFlushedAndSimilar", PinningTier::kFlushedAndSimilar}, {"kAll", PinningTier::kAll}}; static std::unordered_map<std::string, BlockBasedTableOptions::IndexType> block_base_table_index_type_string_map = { {"kBinarySearch", BlockBasedTableOptions::IndexType::kBinarySearch}, {"kHashSearch", BlockBasedTableOptions::IndexType::kHashSearch}, {"kTwoLevelIndexSearch", BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch}, {"kBinarySearchWithFirstKey", BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey}}; static std::unordered_map<std::string, BlockBasedTableOptions::DataBlockIndexType> block_base_table_data_block_index_type_string_map = { {"kDataBlockBinarySearch", BlockBasedTableOptions::DataBlockIndexType::kDataBlockBinarySearch}, {"kDataBlockBinaryAndHash", BlockBasedTableOptions::DataBlockIndexType::kDataBlockBinaryAndHash}}; static std::unordered_map<std::string, BlockBasedTableOptions::IndexShorteningMode> block_base_table_index_shortening_mode_string_map = { {"kNoShortening", BlockBasedTableOptions::IndexShorteningMode::kNoShortening}, {"kShortenSeparators", BlockBasedTableOptions::IndexShorteningMode::kShortenSeparators}, {"kShortenSeparatorsAndSuccessor", BlockBasedTableOptions::IndexShorteningMode:: kShortenSeparatorsAndSuccessor}}; static std::unordered_map<std::string, OptionTypeInfo> metadata_cache_options_type_info = { {"top_level_index_pinning", OptionTypeInfo::Enum<PinningTier>( offsetof(struct MetadataCacheOptions, top_level_index_pinning), &pinning_tier_type_string_map)}, {"partition_pinning", OptionTypeInfo::Enum<PinningTier>( offsetof(struct MetadataCacheOptions, partition_pinning), &pinning_tier_type_string_map)}, {"unpartitioned_pinning", OptionTypeInfo::Enum<PinningTier>( offsetof(struct MetadataCacheOptions, unpartitioned_pinning), &pinning_tier_type_string_map)}}; #endif // ROCKSDB_LITE static std::unordered_map<std::string, OptionTypeInfo> block_based_table_type_info = { #ifndef ROCKSDB_LITE /* currently not supported std::shared_ptr<Cache> block_cache = nullptr; std::shared_ptr<Cache> block_cache_compressed = nullptr; */ {"flush_block_policy_factory", {offsetof(struct BlockBasedTableOptions, flush_block_policy_factory), OptionType::kFlushBlockPolicyFactory, OptionVerificationType::kByName, OptionTypeFlags::kCompareNever}}, {"cache_index_and_filter_blocks", {offsetof(struct BlockBasedTableOptions, cache_index_and_filter_blocks), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"cache_index_and_filter_blocks_with_high_priority", {offsetof(struct BlockBasedTableOptions, cache_index_and_filter_blocks_with_high_priority), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"pin_l0_filter_and_index_blocks_in_cache", {offsetof(struct BlockBasedTableOptions, pin_l0_filter_and_index_blocks_in_cache), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"index_type", OptionTypeInfo::Enum<BlockBasedTableOptions::IndexType>( offsetof(struct BlockBasedTableOptions, index_type), &block_base_table_index_type_string_map)}, {"hash_index_allow_collision", {offsetof(struct BlockBasedTableOptions, hash_index_allow_collision), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"data_block_index_type", OptionTypeInfo::Enum<BlockBasedTableOptions::DataBlockIndexType>( offsetof(struct BlockBasedTableOptions, data_block_index_type), &block_base_table_data_block_index_type_string_map)}, {"index_shortening", OptionTypeInfo::Enum<BlockBasedTableOptions::IndexShorteningMode>( offsetof(struct BlockBasedTableOptions, index_shortening), &block_base_table_index_shortening_mode_string_map)}, {"data_block_hash_table_util_ratio", {offsetof(struct BlockBasedTableOptions, data_block_hash_table_util_ratio), OptionType::kDouble, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"checksum", {offsetof(struct BlockBasedTableOptions, checksum), OptionType::kChecksumType, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"no_block_cache", {offsetof(struct BlockBasedTableOptions, no_block_cache), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"block_size", {offsetof(struct BlockBasedTableOptions, block_size), OptionType::kSizeT, OptionVerificationType::kNormal, OptionTypeFlags::kMutable}}, {"block_size_deviation", {offsetof(struct BlockBasedTableOptions, block_size_deviation), OptionType::kInt, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"block_restart_interval", {offsetof(struct BlockBasedTableOptions, block_restart_interval), OptionType::kInt, OptionVerificationType::kNormal, OptionTypeFlags::kMutable}}, {"index_block_restart_interval", {offsetof(struct BlockBasedTableOptions, index_block_restart_interval), OptionType::kInt, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"index_per_partition", {0, OptionType::kUInt64T, OptionVerificationType::kDeprecated, OptionTypeFlags::kNone}}, {"metadata_block_size", {offsetof(struct BlockBasedTableOptions, metadata_block_size), OptionType::kUInt64T, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"partition_filters", {offsetof(struct BlockBasedTableOptions, partition_filters), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"optimize_filters_for_memory", {offsetof(struct BlockBasedTableOptions, optimize_filters_for_memory), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"filter_policy", {offsetof(struct BlockBasedTableOptions, filter_policy), OptionType::kUnknown, OptionVerificationType::kByNameAllowFromNull, OptionTypeFlags::kNone, // Parses the Filter policy [](const ConfigOptions& opts, const std::string&, const std::string& value, char* addr) { auto* policy = reinterpret_cast<std::shared_ptr<const FilterPolicy>*>(addr); return FilterPolicy::CreateFromString(opts, value, policy); }, // Converts the FilterPolicy to its string representation [](const ConfigOptions&, const std::string&, const char* addr, std::string* value) { const auto* policy = reinterpret_cast<const std::shared_ptr<const FilterPolicy>*>( addr); if (policy->get()) { *value = (*policy)->Name(); } else { *value = kNullptrString; } return Status::OK(); }, // Compares two FilterPolicy objects for equality [](const ConfigOptions&, const std::string&, const char* addr1, const char* addr2, std::string*) { const auto* policy1 = reinterpret_cast<const std::shared_ptr<const FilterPolicy>*>( addr1) ->get(); const auto* policy2 = reinterpret_cast<const std::shared_ptr<FilterPolicy>*>(addr2) ->get(); if (policy1 == policy2) { return true; } else if (policy1 != nullptr && policy2 != nullptr) { return (strcmp(policy1->Name(), policy2->Name()) == 0); } else { return false; } }}}, {"whole_key_filtering", {offsetof(struct BlockBasedTableOptions, whole_key_filtering), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"skip_table_builder_flush", {0, OptionType::kBoolean, OptionVerificationType::kDeprecated, OptionTypeFlags::kNone}}, {"format_version", {offsetof(struct BlockBasedTableOptions, format_version), OptionType::kUInt32T, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"verify_compression", {offsetof(struct BlockBasedTableOptions, verify_compression), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"read_amp_bytes_per_bit", {offsetof(struct BlockBasedTableOptions, read_amp_bytes_per_bit), OptionType::kUInt32T, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"enable_index_compression", {offsetof(struct BlockBasedTableOptions, enable_index_compression), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"block_align", {offsetof(struct BlockBasedTableOptions, block_align), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {"pin_top_level_index_and_filter", {offsetof(struct BlockBasedTableOptions, pin_top_level_index_and_filter), OptionType::kBoolean, OptionVerificationType::kNormal, OptionTypeFlags::kNone}}, {kOptNameMetadataCacheOpts, OptionTypeInfo::Struct( kOptNameMetadataCacheOpts, &metadata_cache_options_type_info, offsetof(struct BlockBasedTableOptions, metadata_cache_options), OptionVerificationType::kNormal, OptionTypeFlags::kNone)}, {"block_cache", {offsetof(struct BlockBasedTableOptions, block_cache), OptionType::kUnknown, OptionVerificationType::kNormal, (OptionTypeFlags::kCompareNever | OptionTypeFlags::kDontSerialize), // Parses the input vsalue as a Cache [](const ConfigOptions& opts, const std::string&, const std::string& value, char* addr) { auto* cache = reinterpret_cast<std::shared_ptr<Cache>*>(addr); return Cache::CreateFromString(opts, value, cache); }}}, {"block_cache_compressed", {offsetof(struct BlockBasedTableOptions, block_cache_compressed), OptionType::kUnknown, OptionVerificationType::kNormal, (OptionTypeFlags::kCompareNever | OptionTypeFlags::kDontSerialize), // Parses the input vsalue as a Cache [](const ConfigOptions& opts, const std::string&, const std::string& value, char* addr) { auto* cache = reinterpret_cast<std::shared_ptr<Cache>*>(addr); return Cache::CreateFromString(opts, value, cache); }}}, #endif // ROCKSDB_LITE }; // TODO(myabandeh): We should return an error instead of silently changing the // options BlockBasedTableFactory::BlockBasedTableFactory( const BlockBasedTableOptions& _table_options) : table_options_(_table_options) { InitializeOptions(); ConfigurableHelper::RegisterOptions(*this, &table_options_, &block_based_table_type_info); } void BlockBasedTableFactory::InitializeOptions() { if (table_options_.flush_block_policy_factory == nullptr) { table_options_.flush_block_policy_factory.reset( new FlushBlockBySizePolicyFactory()); } if (table_options_.no_block_cache) { table_options_.block_cache.reset(); } else if (table_options_.block_cache == nullptr) { LRUCacheOptions co; co.capacity = 8 << 20; // It makes little sense to pay overhead for mid-point insertion while the // block size is only 8MB. co.high_pri_pool_ratio = 0.0; table_options_.block_cache = NewLRUCache(co); } if (table_options_.block_size_deviation < 0 || table_options_.block_size_deviation > 100) { table_options_.block_size_deviation = 0; } if (table_options_.block_restart_interval < 1) { table_options_.block_restart_interval = 1; } if (table_options_.index_block_restart_interval < 1) { table_options_.index_block_restart_interval = 1; } if (table_options_.index_type == BlockBasedTableOptions::kHashSearch && table_options_.index_block_restart_interval != 1) { // Currently kHashSearch is incompatible with index_block_restart_interval > 1 table_options_.index_block_restart_interval = 1; } if (table_options_.partition_filters && table_options_.index_type != BlockBasedTableOptions::kTwoLevelIndexSearch) { // We do not support partitioned filters without partitioning indexes table_options_.partition_filters = false; } } Status BlockBasedTableFactory::PrepareOptions(const ConfigOptions& opts) { InitializeOptions(); return TableFactory::PrepareOptions(opts); } Status BlockBasedTableFactory::NewTableReader( const ReadOptions& ro, const TableReaderOptions& table_reader_options, std::unique_ptr<RandomAccessFileReader>&& file, uint64_t file_size, std::unique_ptr<TableReader>* table_reader, bool prefetch_index_and_filter_in_cache) const { return BlockBasedTable::Open( ro, table_reader_options.ioptions, table_reader_options.env_options, table_options_, table_reader_options.internal_comparator, std::move(file), file_size, table_reader, table_reader_options.prefix_extractor, prefetch_index_and_filter_in_cache, table_reader_options.skip_filters, table_reader_options.level, table_reader_options.immortal, table_reader_options.largest_seqno, table_reader_options.force_direct_prefetch, &tail_prefetch_stats_, table_reader_options.block_cache_tracer, table_reader_options.max_file_size_for_l0_meta_pin); } TableBuilder* BlockBasedTableFactory::NewTableBuilder( const TableBuilderOptions& table_builder_options, uint32_t column_family_id, WritableFileWriter* file) const { auto table_builder = new BlockBasedTableBuilder( table_builder_options.ioptions, table_builder_options.moptions, table_options_, table_builder_options.internal_comparator, table_builder_options.int_tbl_prop_collector_factories, column_family_id, file, table_builder_options.compression_type, table_builder_options.sample_for_compression, table_builder_options.compression_opts, table_builder_options.skip_filters, table_builder_options.column_family_name, table_builder_options.level, table_builder_options.creation_time, table_builder_options.oldest_key_time, table_builder_options.target_file_size, table_builder_options.file_creation_time, table_builder_options.db_id, table_builder_options.db_session_id); return table_builder; } Status BlockBasedTableFactory::ValidateOptions( const DBOptions& db_opts, const ColumnFamilyOptions& cf_opts) const { if (table_options_.index_type == BlockBasedTableOptions::kHashSearch && cf_opts.prefix_extractor == nullptr) { return Status::InvalidArgument( "Hash index is specified for block-based " "table, but prefix_extractor is not given"); } if (table_options_.cache_index_and_filter_blocks && table_options_.no_block_cache) { return Status::InvalidArgument( "Enable cache_index_and_filter_blocks, " ", but block cache is disabled"); } if (table_options_.pin_l0_filter_and_index_blocks_in_cache && table_options_.no_block_cache) { return Status::InvalidArgument( "Enable pin_l0_filter_and_index_blocks_in_cache, " ", but block cache is disabled"); } if (!BlockBasedTableSupportedVersion(table_options_.format_version)) { return Status::InvalidArgument( "Unsupported BlockBasedTable format_version. Please check " "include/rocksdb/table.h for more info"); } if (table_options_.block_align && (cf_opts.compression != kNoCompression)) { return Status::InvalidArgument( "Enable block_align, but compression " "enabled"); } if (table_options_.block_align && (table_options_.block_size & (table_options_.block_size - 1))) { return Status::InvalidArgument( "Block alignment requested but block size is not a power of 2"); } if (table_options_.block_size > port::kMaxUint32) { return Status::InvalidArgument( "block size exceeds maximum number (4GiB) allowed"); } if (table_options_.data_block_index_type == BlockBasedTableOptions::kDataBlockBinaryAndHash && table_options_.data_block_hash_table_util_ratio <= 0) { return Status::InvalidArgument( "data_block_hash_table_util_ratio should be greater than 0 when " "data_block_index_type is set to kDataBlockBinaryAndHash"); } if (db_opts.unordered_write && cf_opts.max_successive_merges > 0) { // TODO(myabandeh): support it return Status::InvalidArgument( "max_successive_merges larger than 0 is currently inconsistent with " "unordered_write"); } return TableFactory::ValidateOptions(db_opts, cf_opts); } std::string BlockBasedTableFactory::GetPrintableOptions() const { std::string ret; ret.reserve(20000); const int kBufferSize = 200; char buffer[kBufferSize]; snprintf(buffer, kBufferSize, " flush_block_policy_factory: %s (%p)\n", table_options_.flush_block_policy_factory->Name(), static_cast<void*>(table_options_.flush_block_policy_factory.get())); ret.append(buffer); snprintf(buffer, kBufferSize, " cache_index_and_filter_blocks: %d\n", table_options_.cache_index_and_filter_blocks); ret.append(buffer); snprintf(buffer, kBufferSize, " cache_index_and_filter_blocks_with_high_priority: %d\n", table_options_.cache_index_and_filter_blocks_with_high_priority); ret.append(buffer); snprintf(buffer, kBufferSize, " pin_l0_filter_and_index_blocks_in_cache: %d\n", table_options_.pin_l0_filter_and_index_blocks_in_cache); ret.append(buffer); snprintf(buffer, kBufferSize, " pin_top_level_index_and_filter: %d\n", table_options_.pin_top_level_index_and_filter); ret.append(buffer); snprintf(buffer, kBufferSize, " index_type: %d\n", table_options_.index_type); ret.append(buffer); snprintf(buffer, kBufferSize, " data_block_index_type: %d\n", table_options_.data_block_index_type); ret.append(buffer); snprintf(buffer, kBufferSize, " index_shortening: %d\n", static_cast<int>(table_options_.index_shortening)); ret.append(buffer); snprintf(buffer, kBufferSize, " data_block_hash_table_util_ratio: %lf\n", table_options_.data_block_hash_table_util_ratio); ret.append(buffer); snprintf(buffer, kBufferSize, " hash_index_allow_collision: %d\n", table_options_.hash_index_allow_collision); ret.append(buffer); snprintf(buffer, kBufferSize, " checksum: %d\n", table_options_.checksum); ret.append(buffer); snprintf(buffer, kBufferSize, " no_block_cache: %d\n", table_options_.no_block_cache); ret.append(buffer); snprintf(buffer, kBufferSize, " block_cache: %p\n", static_cast<void*>(table_options_.block_cache.get())); ret.append(buffer); if (table_options_.block_cache) { const char* block_cache_name = table_options_.block_cache->Name(); if (block_cache_name != nullptr) { snprintf(buffer, kBufferSize, " block_cache_name: %s\n", block_cache_name); ret.append(buffer); } ret.append(" block_cache_options:\n"); ret.append(table_options_.block_cache->GetPrintableOptions()); } snprintf(buffer, kBufferSize, " block_cache_compressed: %p\n", static_cast<void*>(table_options_.block_cache_compressed.get())); ret.append(buffer); if (table_options_.block_cache_compressed) { const char* block_cache_compressed_name = table_options_.block_cache_compressed->Name(); if (block_cache_compressed_name != nullptr) { snprintf(buffer, kBufferSize, " block_cache_name: %s\n", block_cache_compressed_name); ret.append(buffer); } ret.append(" block_cache_compressed_options:\n"); ret.append(table_options_.block_cache_compressed->GetPrintableOptions()); } snprintf(buffer, kBufferSize, " persistent_cache: %p\n", static_cast<void*>(table_options_.persistent_cache.get())); ret.append(buffer); if (table_options_.persistent_cache) { snprintf(buffer, kBufferSize, " persistent_cache_options:\n"); ret.append(buffer); ret.append(table_options_.persistent_cache->GetPrintableOptions()); } snprintf(buffer, kBufferSize, " block_size: %" ROCKSDB_PRIszt "\n", table_options_.block_size); ret.append(buffer); snprintf(buffer, kBufferSize, " block_size_deviation: %d\n", table_options_.block_size_deviation); ret.append(buffer); snprintf(buffer, kBufferSize, " block_restart_interval: %d\n", table_options_.block_restart_interval); ret.append(buffer); snprintf(buffer, kBufferSize, " index_block_restart_interval: %d\n", table_options_.index_block_restart_interval); ret.append(buffer); snprintf(buffer, kBufferSize, " metadata_block_size: %" PRIu64 "\n", table_options_.metadata_block_size); ret.append(buffer); snprintf(buffer, kBufferSize, " partition_filters: %d\n", table_options_.partition_filters); ret.append(buffer); snprintf(buffer, kBufferSize, " use_delta_encoding: %d\n", table_options_.use_delta_encoding); ret.append(buffer); snprintf(buffer, kBufferSize, " filter_policy: %s\n", table_options_.filter_policy == nullptr ? "nullptr" : table_options_.filter_policy->Name()); ret.append(buffer); snprintf(buffer, kBufferSize, " whole_key_filtering: %d\n", table_options_.whole_key_filtering); ret.append(buffer); snprintf(buffer, kBufferSize, " verify_compression: %d\n", table_options_.verify_compression); ret.append(buffer); snprintf(buffer, kBufferSize, " read_amp_bytes_per_bit: %d\n", table_options_.read_amp_bytes_per_bit); ret.append(buffer); snprintf(buffer, kBufferSize, " format_version: %d\n", table_options_.format_version); ret.append(buffer); snprintf(buffer, kBufferSize, " enable_index_compression: %d\n", table_options_.enable_index_compression); ret.append(buffer); snprintf(buffer, kBufferSize, " block_align: %d\n", table_options_.block_align); ret.append(buffer); return ret; } const void* BlockBasedTableFactory::GetOptionsPtr( const std::string& name) const { if (name == kBlockCacheOpts()) { if (table_options_.no_block_cache) { return nullptr; } else { return table_options_.block_cache.get(); } } else { return TableFactory::GetOptionsPtr(name); } } #ifndef ROCKSDB_LITE // Take a default BlockBasedTableOptions "table_options" in addition to a // map "opts_map" of option name to option value to construct the new // BlockBasedTableOptions "new_table_options". // // Below are the instructions of how to config some non-primitive-typed // options in BlockBasedTableOptions: // // * filter_policy: // We currently only support the following FilterPolicy in the convenience // functions: // - BloomFilter: use "bloomfilter:[bits_per_key]:[use_block_based_builder]" // to specify BloomFilter. The above string is equivalent to calling // NewBloomFilterPolicy(bits_per_key, use_block_based_builder). // [Example]: // - Pass {"filter_policy", "bloomfilter:4:true"} in // GetBlockBasedTableOptionsFromMap to use a BloomFilter with 4-bits // per key and use_block_based_builder enabled. // // * block_cache / block_cache_compressed: // We currently only support LRU cache in the GetOptions API. The LRU // cache can be set by directly specifying its size. // [Example]: // - Passing {"block_cache", "1M"} in GetBlockBasedTableOptionsFromMap is // equivalent to setting block_cache using NewLRUCache(1024 * 1024). // // @param table_options the default options of the output "new_table_options". // @param opts_map an option name to value map for specifying how // "new_table_options" should be set. // @param new_table_options the resulting options based on "table_options" // with the change specified in "opts_map". // @param input_strings_escaped when set to true, each escaped characters // prefixed by '\' in the values of the opts_map will be further converted // back to the raw string before assigning to the associated options. // @param ignore_unknown_options when set to true, unknown options are ignored // instead of resulting in an unknown-option error. // @return Status::OK() on success. Otherwise, a non-ok status indicating // error will be returned, and "new_table_options" will be set to // "table_options". Status BlockBasedTableFactory::ParseOption(const ConfigOptions& config_options, const OptionTypeInfo& opt_info, const std::string& opt_name, const std::string& opt_value, void* opt_ptr) { Status status = TableFactory::ParseOption(config_options, opt_info, opt_name, opt_value, opt_ptr); if (config_options.input_strings_escaped && !status.ok()) { // Got an error // !input_strings_escaped indicates the old API, where everything is // parsable. if (opt_info.IsByName()) { status = Status::OK(); } } return status; } Status GetBlockBasedTableOptionsFromString( const BlockBasedTableOptions& table_options, const std::string& opts_str, BlockBasedTableOptions* new_table_options) { ConfigOptions config_options; config_options.input_strings_escaped = false; config_options.ignore_unknown_options = false; config_options.invoke_prepare_options = false; return GetBlockBasedTableOptionsFromString(config_options, table_options, opts_str, new_table_options); } Status GetBlockBasedTableOptionsFromString( const ConfigOptions& config_options, const BlockBasedTableOptions& table_options, const std::string& opts_str, BlockBasedTableOptions* new_table_options) { std::unordered_map<std::string, std::string> opts_map; Status s = StringToMap(opts_str, &opts_map); if (!s.ok()) { return s; } s = GetBlockBasedTableOptionsFromMap(config_options, table_options, opts_map, new_table_options); // Translate any errors (NotFound, NotSupported, to InvalidArgument if (s.ok() || s.IsInvalidArgument()) { return s; } else { return Status::InvalidArgument(s.getState()); } } Status GetBlockBasedTableOptionsFromMap( const BlockBasedTableOptions& table_options, const std::unordered_map<std::string, std::string>& opts_map, BlockBasedTableOptions* new_table_options, bool input_strings_escaped, bool ignore_unknown_options) { ConfigOptions config_options; config_options.input_strings_escaped = input_strings_escaped; config_options.ignore_unknown_options = ignore_unknown_options; config_options.invoke_prepare_options = false; return GetBlockBasedTableOptionsFromMap(config_options, table_options, opts_map, new_table_options); } Status GetBlockBasedTableOptionsFromMap( const ConfigOptions& config_options, const BlockBasedTableOptions& table_options, const std::unordered_map<std::string, std::string>& opts_map, BlockBasedTableOptions* new_table_options) { assert(new_table_options); BlockBasedTableFactory bbtf(table_options); Status s = bbtf.ConfigureFromMap(config_options, opts_map); if (s.ok()) { *new_table_options = *(bbtf.GetOptions<BlockBasedTableOptions>()); } else { *new_table_options = table_options; } return s; } #endif // !ROCKSDB_LITE TableFactory* NewBlockBasedTableFactory( const BlockBasedTableOptions& _table_options) { return new BlockBasedTableFactory(_table_options); } const std::string BlockBasedTablePropertyNames::kIndexType = "rocksdb.block.based.table.index.type"; const std::string BlockBasedTablePropertyNames::kWholeKeyFiltering = "rocksdb.block.based.table.whole.key.filtering"; const std::string BlockBasedTablePropertyNames::kPrefixFiltering = "rocksdb.block.based.table.prefix.filtering"; const std::string kHashIndexPrefixesBlock = "rocksdb.hashindex.prefixes"; const std::string kHashIndexPrefixesMetadataBlock = "rocksdb.hashindex.metadata"; const std::string kPropTrue = "1"; const std::string kPropFalse = "0"; } // namespace ROCKSDB_NAMESPACE
43.875
82
0.642021
[ "vector" ]
ca6bab1f40845363eb9d27f5f25d721d91f67c22
2,394
cpp
C++
tools/tightCut.cpp
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
tools/tightCut.cpp
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
tools/tightCut.cpp
krzysg/FaspHeuristic
1929c40e3fbc49e68b04acfc5522539a18758031
[ "MIT" ]
null
null
null
/* * Simple tool that reads from stdin unweighted simple graph data and calculates FASP size (number of edges to cut to make a graph acyclic) * * Graph format (first number is src vertex, next numbers are dst vertices of src vertex): * * 1 3 5 * 3 5 * 5 1 * * As a output (for above example) it will print out: * * Input graph: #vertices=3 #edges=4 * FASP size (#edges to cut): 1 */ #include <iostream> #include <string> #include <FaspTightCut/graphFasp.h> int main() { using VERTEX_TYPE = int; // Read graph from input Graph::Graph<VERTEX_TYPE> graph; int lineCnt = 1; for (std::string line; std::getline(std::cin, line); lineCnt++) { std::istringstream iss(line); std::vector<std::string> tokens; std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), back_inserter(tokens)); // We expect at least vertex without any outgoing connections if (tokens.size() >= 1) { try { typename Graph::Graph<VERTEX_TYPE>::Vertex src = std::stoi(tokens[0]); graph.addVertexSafe(src); // Add edges to destination vertices if defined for (size_t i = 1; i < tokens.size(); ++i) { typename Graph::Graph<VERTEX_TYPE>::Vertex dst = std::stoi(tokens[i]); graph.addVertexSafe(dst); graph.addEdge(src, dst); } } catch (const std::invalid_argument &e) { std::cout << "Invalid line #" << lineCnt << std::endl; std::cout << "\"" << line << "\"" << std::endl; std::cout<< "Error: '" << e.what() << "'" << std::endl; exit(1); } } } // Print info about read graph std::cout << "# Input graph: #vertices=" << graph.getNumOfVertices() << " #edges=" << graph.getNumOfEdges() << std::endl; // Run TIGHT-CUT heuristic auto [capacity, removedEdges, saEdgesCnt, saRndEdgesCnt, redRndEdgesCnt] = Graph::Fasp::tightCut<true, VERTEX_TYPE>(graph); // Print result std::cout << "# FASP size (#edges to cut): " << capacity << std::endl; std::cout << "# Feedback arcs:" << std::endl; for (const auto &edge : removedEdges) std::cout << edge.src << ' ' << edge.dst << '\n'; return 0; }
35.731343
139
0.556809
[ "vector" ]
ca6ef6bbb4174e0f8ac2b1fd444b1d3d5300b41d
6,490
cc
C++
maxutils/maxsql/src/queryresult.cc
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxsql/src/queryresult.cc
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
maxutils/maxsql/src/queryresult.cc
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-04-28 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <maxsql/queryresult.hh> #include <mysql.h> #include <maxbase/assert.h> #include <maxbase/format.hh> #include <memory> using std::string; using mxb::string_printf; namespace { const string type_integer = "integer"; const string type_uinteger = "unsigned integer"; const string type_boolean = "boolean"; } namespace maxsql { bool QueryResult::next_row() { if (advance_row()) { m_current_row_ind++; m_error = ConversionError(); // Reset error return true; } else { m_current_row_ind = -1; return false; } } int64_t QueryResult::get_current_row_index() const { return m_current_row_ind; } int64_t QueryResult::get_col_index(const string& col_name) const { auto iter = m_col_indexes.find(col_name); return (iter != m_col_indexes.end()) ? iter->second : -1; } string QueryResult::get_string(int64_t column_ind) const { mxb_assert(column_ind < get_col_count() && column_ind >= 0); auto data = row_elem(column_ind); return data ? data : ""; } string QueryResult::get_string(const std::string& name) const { auto idx = get_col_index(name); if (idx != -1) { return get_string(idx); } return ""; } int64_t QueryResult::get_int(int64_t column_ind) const { int64_t rval = 0; auto int_parser = [&rval](const char* data_elem) { bool success = false; errno = 0; char* endptr = nullptr; auto parsed = strtoll(data_elem, &endptr, 10); if (errno == 0 && *endptr == '\0') { rval = parsed; success = true; } return success; }; call_parser(int_parser, column_ind, type_integer); return rval; } int64_t QueryResult::get_int(const std::string& name) const { auto idx = get_col_index(name); if (idx != -1) { return get_int(idx); } return 0; } uint64_t QueryResult::get_uint(int64_t column_ind) const { uint64_t rval = 0; auto uint_parser = [&rval](const char* data_elem) { bool success = false; errno = 0; char* endptr = nullptr; auto parsed = strtoull(data_elem, &endptr, 10); if (errno == 0 && *endptr == '\0') { rval = parsed; success = true; } return success; }; call_parser(uint_parser, column_ind, type_uinteger); return rval; } bool QueryResult::get_bool(int64_t column_ind) const { bool rval = false; auto bool_parser = [&rval](const char* data_elem) { bool success = false; char c = *data_elem; if (c == '1' || c == 'Y' || c == 'y') { rval = true; success = true; } else if (c == '0' || c == 'N' || c == 'n') { success = true; } return success; }; call_parser(bool_parser, column_ind, type_boolean); return rval; } bool QueryResult::get_bool(const std::string& name) const { auto idx = get_col_index(name); if (idx != -1) { return get_bool(idx); } return 0; } void QueryResult::call_parser(const std::function<bool(const char*)>& parser, int64_t column_ind, const std::string& target_type) const { mxb_assert(column_ind < get_col_count() && column_ind >= 0); auto data_elem = row_elem(column_ind); if (data_elem == nullptr || !parser(data_elem)) { set_error(column_ind, target_type); } } bool QueryResult::field_is_null(int64_t column_ind) const { mxb_assert(column_ind < get_col_count() && column_ind >= 0); return row_elem(column_ind) == nullptr; } void QueryResult::set_error(int64_t column_ind, const string& target_type) const { string col_name; // Find the column name. for (const auto& elem : m_col_indexes) { if (elem.second == column_ind) { col_name = elem.first; break; } } mxb_assert(!col_name.empty()); // If the field value is null, then that is the cause of the error. auto field_value = row_elem(column_ind); if (field_value == nullptr) { m_error.set_null_value_error(target_type); } else { m_error.set_value_error(field_value, target_type); } } bool QueryResult::error() const { return m_error.error(); } string QueryResult::error_string() const { return m_error.to_string(); } QueryResult::QueryResult(std::vector<std::string>&& col_names) { for (size_t column_index = 0; column_index < col_names.size(); column_index++) { const auto& key = col_names[column_index]; // TODO: Think of a way to handle duplicate names nicely. Currently this should only be used // for known queries. mxb_assert(m_col_indexes.count(key) == 0); m_col_indexes[key] = column_index; } } void QueryResult::ConversionError::set_value_error(const string& field_value, const string& target_type) { mxb_assert(!target_type.empty()); // The error container only has space for one error. if (m_target_type.empty()) { m_field_value = field_value; m_target_type = target_type; } } void QueryResult::ConversionError::set_null_value_error(const string& target_type) { mxb_assert(!target_type.empty()); if (m_target_type.empty()) { m_field_was_null = true; m_target_type = target_type; } } string QueryResult::ConversionError::to_string() const { string rval; if (!m_target_type.empty()) { rval = "Cannot convert "; if (m_field_was_null) { rval += mxb::string_printf("a null field to %s.", m_target_type.c_str()); } else { rval += mxb::string_printf("field '%s' to %s.", m_field_value.c_str(), m_target_type.c_str()); } } return rval; } bool QueryResult::ConversionError::error() const { return !m_target_type.empty(); } }
24.307116
106
0.603082
[ "vector" ]
ca7b5d3783ab85bde34d23602e0d86c52e514f4f
1,720
cpp
C++
Old/Source/ComponentCircleCollider.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
1
2020-02-07T04:50:57.000Z
2020-02-07T04:50:57.000Z
Old/Source/ComponentCircleCollider.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
null
null
null
Old/Source/ComponentCircleCollider.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
1
2020-02-07T04:51:00.000Z
2020-02-07T04:51:00.000Z
#include "ComponentCircleCollider.h" #include "Physics2DModule.h" #include "Application.h" #include <Dynamics/b2Fixture.h> #include <Collision/Shapes/b2CircleShape.h> #include "ComponentPhysicsBody.h" #include "GameObject.h" #include "Component.h" #include "Data.h" #include "ComponentTransform.h" #include <algorithm> ComponentCircleCollider::ComponentCircleCollider(GameObject& gameObject, const char* componentName) : ComponentCollider(gameObject, componentName, COMPONENT_TYPE::CIRCLE_COLLIDER) { if (physBody != nullptr) { ComponentTransform* transform = (ComponentTransform*)gameObject.GetComponentOfType(Component::TRANSFORM); glm::vec2 scale = transform->GetGlobalScale(); float maxScale = std::max(scale.x, scale.y); fixture = App->physics2DModule->CreateCircleCollider(physBody->GetBody(), maxScale * 0.5f); } radius = 0.5f; } ComponentCircleCollider::~ComponentCircleCollider() { } void ComponentCircleCollider::SetRadius(float radius) { ComponentTransform* transform = (ComponentTransform*)gameObject->GetComponentOfType(Component::TRANSFORM); b2CircleShape& shape = *(b2CircleShape*)fixture->GetShape(); glm::vec2 scale = transform->GetGlobalScale(); shape.m_radius = 0.02f * scale.x * radius; this->radius = radius; } float ComponentCircleCollider::GetRadius() const { return radius; } void ComponentCircleCollider::SetOffset(glm::vec2 offset) { glm::vec2 diff = offset - this->offset; b2CircleShape& shape = *(b2CircleShape*)fixture->GetShape(); shape.m_p.x += diff.x; shape.m_p.y += diff.y; this->offset = offset; } void ComponentCircleCollider::SaveData(Data & data) { data.AddInt("Type", GetComponentType()); } void ComponentCircleCollider::LoadData(Data & data) { }
26.875
107
0.760465
[ "shape", "transform" ]
ca7db6f1f8b7865334927debd17e46360879e1d5
150,585
cpp
C++
NVEncCore/rgy_input_avcodec.cpp
somerendoguy/NVEnc
413dbd28b423ae90223e5ccb0b4272e54ae7b3f7
[ "MIT" ]
null
null
null
NVEncCore/rgy_input_avcodec.cpp
somerendoguy/NVEnc
413dbd28b423ae90223e5ccb0b4272e54ae7b3f7
[ "MIT" ]
null
null
null
NVEncCore/rgy_input_avcodec.cpp
somerendoguy/NVEnc
413dbd28b423ae90223e5ccb0b4272e54ae7b3f7
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------------------- // QSVEnc/NVEnc by rigaya // ----------------------------------------------------------------------------------------- // The MIT License // // Copyright (c) 2011-2016 rigaya // // 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 <fcntl.h> #include <algorithm> #include <numeric> #include <array> #include <map> #include <cctype> #include <cmath> #include <climits> #include <limits> #include <memory> #include <cppcodec/base64_rfc4648.hpp> #include "rgy_thread.h" #include "rgy_input_avcodec.h" #include "rgy_bitstream.h" #include "rgy_avlog.h" #include "rgy_filesystem.h" #include "rgy_language.h" #if ENABLE_AVSW_READER #if USE_CUSTOM_INPUT static int funcReadPacket(void *opaque, uint8_t *buf, int buf_size) { RGYInputAvcodec *reader = reinterpret_cast<RGYInputAvcodec *>(opaque); return reader->readPacket(buf, buf_size); } static int funcWritePacket(void *opaque, uint8_t *buf, int buf_size) { RGYInputAvcodec *reader = reinterpret_cast<RGYInputAvcodec *>(opaque); return reader->writePacket(buf, buf_size); } static int64_t funcSeek(void *opaque, int64_t offset, int whence) { RGYInputAvcodec *reader = reinterpret_cast<RGYInputAvcodec *>(opaque); return reader->seek(offset, whence); } #endif //USE_CUSTOM_INPUT static inline void extend_array_size(VideoFrameData *dataset) { static int default_capacity = 8 * 1024; int current_cap = dataset->capacity; dataset->capacity = (current_cap) ? current_cap * 2 : default_capacity; dataset->frame = (FramePos *)realloc(dataset->frame, dataset->capacity * sizeof(dataset->frame[0])); memset(dataset->frame + current_cap, 0, sizeof(dataset->frame[0]) * (dataset->capacity - current_cap)); } RGYInputAvcodecPrm::RGYInputAvcodecPrm(RGYInputPrm base) : RGYInputPrm(base), inputRetry(0), memType(0), pInputFormat(nullptr), readVideo(false), videoTrack(0), videoStreamId(0), readAudio(0), readSubtitle(false), readData(false), readAttachment(false), readChapter(false), videoAvgFramerate(), analyzeSec(-1.0), probesize(-1), nTrimCount(0), pTrimList(nullptr), trackStartAudio(0), trackStartSubtitle(0), trackStartData(0), nAudioSelectCount(0), ppAudioSelect(nullptr), nSubtitleSelectCount(0), ppSubtitleSelect(nullptr), nDataSelectCount(0), ppDataSelect(nullptr), AVSyncMode(RGY_AVSYNC_ASSUME_CFR), procSpeedLimit(0), seekSec(0.0), logFramePosList(), logCopyFrameData(), logPackets(), threadInput(0), queueInfo(nullptr), HWDecCodecCsp(nullptr), videoDetectPulldown(false), caption2ass(FORMAT_INVALID), parseHDRmetadata(false), hdr10plusMetadataCopy(false), interlaceAutoFrame(false), qpTableListRef(nullptr), lowLatency(false), inputOpt() { } RGYInputAvcodec::RGYInputAvcodec() : m_Demux(), m_logFramePosList(), m_fpPacketList(), m_hevcMp42AnnexbBuffer(), m_cap2ass() { memset(&m_Demux.format, 0, sizeof(m_Demux.format)); memset(&m_Demux.video, 0, sizeof(m_Demux.video)); m_readerName = _T("av" DECODER_NAME "/avsw"); } RGYInputAvcodec::~RGYInputAvcodec() { Close(); } void RGYInputAvcodec::CloseThread() { m_Demux.thread.bAbortInput = true; if (m_Demux.thread.thInput.joinable()) { AddMessage(RGY_LOG_DEBUG, _T("Closing Input thread.\n")); m_Demux.qVideoPkt.set_capacity(SIZE_MAX); m_Demux.qVideoPkt.set_keep_length(0); m_Demux.thread.thInput.join(); AddMessage(RGY_LOG_DEBUG, _T("Closed Input thread.\n")); } m_Demux.thread.bAbortInput = false; } void RGYInputAvcodec::CloseFormat(AVDemuxFormat *format) { //close video file if (format->fpInput) { AddMessage(RGY_LOG_DEBUG, _T("Closing file pointer...\n")); if (format->formatCtx) { if (format->formatCtx->pb) { if (format->formatCtx->pb->buffer) { AddMessage(RGY_LOG_DEBUG, _T("Closing pb->buffer...\n")); av_freep(&format->formatCtx->pb->buffer); AddMessage(RGY_LOG_DEBUG, _T("Closed pb->buffer.\n")); } AddMessage(RGY_LOG_DEBUG, _T("Closing avio context...\n")); avio_context_free(&format->formatCtx->pb); AddMessage(RGY_LOG_DEBUG, _T("Closed avio context.\n")); } } fclose(format->fpInput); AddMessage(RGY_LOG_DEBUG, _T("Closed file pointer.\n")); } if (format->formatCtx) { AddMessage(RGY_LOG_DEBUG, _T("Closing avformat context...\n")); avformat_close_input(&format->formatCtx); AddMessage(RGY_LOG_DEBUG, _T("Closed avformat context.\n")); } if (format->formatOptions) { AddMessage(RGY_LOG_DEBUG, _T("Free formatOptions...\n")); av_dict_free(&format->formatOptions); AddMessage(RGY_LOG_DEBUG, _T("Freed formatOptions.\n")); } memset(format, 0, sizeof(format[0])); } void RGYInputAvcodec::CloseVideo(AVDemuxVideo *video) { //close parser if (video->pParserCtx) { AddMessage(RGY_LOG_DEBUG, _T("Close parser...\n")); av_parser_close(video->pParserCtx); AddMessage(RGY_LOG_DEBUG, _T("Closed parser.\n")); } if (video->pCodecCtxParser) { AddMessage(RGY_LOG_DEBUG, _T("Close codecCtx for parser...\n")); avcodec_free_context(&video->pCodecCtxParser); AddMessage(RGY_LOG_DEBUG, _T("Closed codecCtx for parser.\n")); } if (video->codecCtxDecode) { AddMessage(RGY_LOG_DEBUG, _T("Close codecCtx...\n")); avcodec_free_context(&video->codecCtxDecode); AddMessage(RGY_LOG_DEBUG, _T("Closed codecCtx.\n")); } if (video->contentLight) { AddMessage(RGY_LOG_DEBUG, _T("Free content light metadata...\n")); av_freep(&video->contentLight); AddMessage(RGY_LOG_DEBUG, _T("Freed content light metadata.\n")); } if (video->masteringDisplay) { AddMessage(RGY_LOG_DEBUG, _T("Free mastering display metadata...\n")); av_freep(&video->masteringDisplay); AddMessage(RGY_LOG_DEBUG, _T("Freed mastering display metadata.\n")); } //close bitstreamfilter if (video->bsfcCtx) { AddMessage(RGY_LOG_DEBUG, _T("Free bsf...\n")); av_bsf_free(&video->bsfcCtx); AddMessage(RGY_LOG_DEBUG, _T("Freed bsf.\n")); } if (video->frame) { AddMessage(RGY_LOG_DEBUG, _T("Free video frame...\n")); av_frame_free(&video->frame); AddMessage(RGY_LOG_DEBUG, _T("Freed video frame.\n")); } if (video->extradata) { AddMessage(RGY_LOG_DEBUG, _T("Free extra data...\n")); av_free(video->extradata); AddMessage(RGY_LOG_DEBUG, _T("Freed extra data.\n")); } memset(video, 0, sizeof(video[0])); video->index = -1; } void RGYInputAvcodec::CloseStream(AVDemuxStream *stream) { if (stream->pktSample.data) { AddMessage(RGY_LOG_DEBUG, _T("Free packet sample...\n")); av_packet_unref(&stream->pktSample); AddMessage(RGY_LOG_DEBUG, _T("Freed packet sample.\n")); } if (stream->subtitleHeader) { AddMessage(RGY_LOG_DEBUG, _T("Free subtitleHeader...\n")); av_free(stream->subtitleHeader); AddMessage(RGY_LOG_DEBUG, _T("Freed subtitleHeader.\n")); } memset(stream, 0, sizeof(stream[0])); stream->appliedTrimBlock = -1; stream->aud0_fin = AV_NOPTS_VALUE; stream->index = -1; } void RGYInputAvcodec::Close() { AddMessage(RGY_LOG_DEBUG, _T("Closing...\n")); //リソースの解放 CloseThread(); m_Demux.qVideoPkt.close([](AVPacket *pkt) { av_packet_unref(pkt); }); for (uint32_t i = 0; i < m_Demux.qStreamPktL1.size(); i++) { av_packet_unref(&m_Demux.qStreamPktL1[i]); } m_Demux.qStreamPktL1.clear(); m_Demux.qStreamPktL2.close([](AVPacket *pkt) { av_packet_unref(pkt); }); AddMessage(RGY_LOG_DEBUG, _T("Closed Stream Packet Buffer.\n")); m_cap2ass.close(); AddMessage(RGY_LOG_DEBUG, _T("Closed caption handler.\n")); CloseFormat(&m_Demux.format); AddMessage(RGY_LOG_DEBUG, _T("Closed format.\n")); CloseVideo(&m_Demux.video); AddMessage(RGY_LOG_DEBUG, _T("Closed video.\n")); for (int i = 0; i < (int)m_Demux.stream.size(); i++) { AddMessage(RGY_LOG_DEBUG, _T("Closing Stream #%d...\n"), i); CloseStream(&m_Demux.stream[i]); AddMessage(RGY_LOG_DEBUG, _T("Closed Stream #%d.\n"), i); } m_Demux.stream.clear(); m_Demux.chapter.clear(); m_trimParam.list.clear(); m_trimParam.offset = 0; m_hevcMp42AnnexbBuffer.clear(); //free input buffer (使用していない) //if (buffer) { // free(buffer); // buffer = nullptr; //} m_encSatusInfo.reset(); if (m_logFramePosList.length()) { m_Demux.frames.printList(m_logFramePosList.c_str()); AddMessage(RGY_LOG_DEBUG, _T("Output logFramePosList.\n")); } m_Demux.frames.clear(); AddMessage(RGY_LOG_DEBUG, _T("Cleared frame pos list.\n")); m_fpPacketList.reset(); AddMessage(RGY_LOG_DEBUG, _T("Closed.\n")); } RGY_ERR RGYInputAvcodec::initVideoBsfs() { if (m_Demux.video.bsfcCtx != nullptr) { AddMessage(RGY_LOG_DEBUG, _T("initVideoBsfs: Free old bsf...\n")); av_bsf_free(&m_Demux.video.bsfcCtx); AddMessage(RGY_LOG_DEBUG, _T("initVideoBsfs: Freed old bsf.\n")); } if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_HEVC) { m_Demux.video.bUseHEVCmp42AnnexB = true; } else if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_H264 || m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_HEVC) { const char *filtername = nullptr; switch (m_Demux.video.stream->codecpar->codec_id) { case AV_CODEC_ID_H264: filtername = "h264_mp4toannexb"; break; case AV_CODEC_ID_HEVC: filtername = "hevc_mp4toannexb"; break; default: break; } if (filtername == nullptr) { AddMessage(RGY_LOG_ERROR, _T("failed to set bitstream filter.\n")); return RGY_ERR_NOT_FOUND; } auto filter = av_bsf_get_by_name(filtername); if (filter == nullptr) { AddMessage(RGY_LOG_ERROR, _T("failed to find %s.\n"), char_to_tstring(filtername).c_str()); return RGY_ERR_NOT_FOUND; } int ret = av_bsf_alloc(filter, &m_Demux.video.bsfcCtx); if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to allocate memory for %s: %s.\n"), char_to_tstring(filter->name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_NULL_PTR; } m_Demux.video.bsfcCtx->time_base_in = av_stream_get_codec_timebase(m_Demux.video.stream); if (0 > (ret = avcodec_parameters_copy(m_Demux.video.bsfcCtx->par_in, m_Demux.video.stream->codecpar))) { AddMessage(RGY_LOG_ERROR, _T("failed to set parameter for %s: %s.\n"), char_to_tstring(filter->name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_NULL_PTR; } m_Demux.video.bsfcCtx->time_base_in = m_Demux.video.stream->time_base; if (0 > (ret = av_bsf_init(m_Demux.video.bsfcCtx))) { AddMessage(RGY_LOG_ERROR, _T("failed to init %s: %s.\n"), char_to_tstring(filter->name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_NULL_PTR; } AddMessage(RGY_LOG_DEBUG, _T("initialized %s filter.\n"), char_to_tstring(filter->name).c_str()); } return RGY_ERR_NONE; } RGY_ERR RGYInputAvcodec::initVideoParser() { if (m_Demux.video.pParserCtx) { AddMessage(RGY_LOG_DEBUG, _T("initVideoParser: Close old parser...\n")); av_parser_close(m_Demux.video.pParserCtx); AddMessage(RGY_LOG_DEBUG, _T("initVideoParser: Closed old parser.\n")); m_Demux.video.pParserCtx = nullptr; } if (m_Demux.video.stream->codecpar->extradata != nullptr && m_Demux.video.extradata == nullptr) { return RGY_ERR_MORE_DATA; } //parserはseek後に初期化すること //parserが使用されていれば、ここでも使用するようにする //たとえば、入力がrawcodecなどでは使用しない m_Demux.video.pParserCtx = av_parser_init(m_Demux.video.stream->codecpar->codec_id); if (m_Demux.video.pParserCtx) { m_Demux.video.pParserCtx->flags |= PARSER_FLAG_COMPLETE_FRAMES; if (nullptr == (m_Demux.video.pCodecCtxParser = avcodec_alloc_context3(avcodec_find_decoder(m_Demux.video.stream->codecpar->codec_id)))) { AddMessage(RGY_LOG_ERROR, _T("failed to allocate context for parser.\n")); return RGY_ERR_NULL_PTR; } unique_ptr_custom<AVCodecParameters> codecParamCopy(avcodec_parameters_alloc(), [](AVCodecParameters *pCodecPar) { avcodec_parameters_free(&pCodecPar); }); int ret = 0; if (0 > (ret = avcodec_parameters_copy(codecParamCopy.get(), m_Demux.video.stream->codecpar))) { AddMessage(RGY_LOG_ERROR, _T("failed to copy codec param to context for parser: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } if (m_Demux.video.bsfcCtx || m_Demux.video.bUseHEVCmp42AnnexB) { SetExtraData(codecParamCopy.get(), m_Demux.video.extradata, m_Demux.video.extradataSize); } if (0 > (ret = avcodec_parameters_to_context(m_Demux.video.pCodecCtxParser, codecParamCopy.get()))) { AddMessage(RGY_LOG_ERROR, _T("failed to set codec param to context for parser: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } m_Demux.video.pCodecCtxParser->time_base = av_stream_get_codec_timebase(m_Demux.video.stream); m_Demux.video.pCodecCtxParser->pkt_timebase = m_Demux.video.stream->time_base; AddMessage(RGY_LOG_DEBUG, _T("initialized %s codec context for parser: time_base: %d/%d, pkt_timebase: %d/%d.\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), m_Demux.video.pCodecCtxParser->time_base.num, m_Demux.video.pCodecCtxParser->time_base.den, m_Demux.video.pCodecCtxParser->pkt_timebase.num, m_Demux.video.pCodecCtxParser->pkt_timebase.den); } else if (m_Demux.video.HWDecodeDeviceId >= 0) { AddMessage(RGY_LOG_ERROR, _T("failed to init parser for %s.\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str()); return RGY_ERR_NULL_PTR; } return RGY_ERR_NONE; } RGY_ERR RGYInputAvcodec::parseVideoExtraData(const AVPacket *pkt) { const char *bsf_name = "extract_extradata"; const auto bsf = av_bsf_get_by_name(bsf_name); if (bsf == nullptr) { AddMessage(RGY_LOG_ERROR, _T("failed to bsf %s.\n"), char_to_tstring(bsf_name).c_str()); return RGY_ERR_NULL_PTR; } int ret = 0; AVBSFContext *bsfctmp = nullptr; if (0 > (ret = av_bsf_alloc(bsf, &bsfctmp))) { AddMessage(RGY_LOG_ERROR, _T("failed to allocate memory for %s: %s.\n"), char_to_tstring(bsf_name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_NULL_PTR; } unique_ptr<AVBSFContext, RGYAVDeleter<AVBSFContext>> bsfc(bsfctmp, RGYAVDeleter<AVBSFContext>(av_bsf_free)); bsfctmp = nullptr; if (0 > (ret = avcodec_parameters_copy(bsfc->par_in, m_Demux.video.stream->codecpar))) { AddMessage(RGY_LOG_ERROR, _T("failed to copy parameter for %s: %s.\n"), char_to_tstring(bsf_name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } if (0 > (ret = av_bsf_init(bsfc.get()))) { AddMessage(RGY_LOG_ERROR, _T("failed to init %s: %s.\n"), char_to_tstring(bsf_name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } AddMessage(RGY_LOG_DEBUG, _T("Initialized bsf %s\n"), char_to_tstring(bsf_name).c_str()); unique_ptr<AVPacket, decltype(&av_packet_unref)> pktCopy(av_packet_clone(pkt), av_packet_unref); if (0 > (ret = av_bsf_send_packet(bsfc.get(), pktCopy.get()))) { AddMessage(RGY_LOG_ERROR, _T("failed to send packet to %s bitstream filter: %s.\n"), char_to_tstring(bsfc->filter->name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } ret = av_bsf_receive_packet(bsfc.get(), pktCopy.get()); if (ret == AVERROR(EAGAIN)) { return RGY_ERR_NONE; } else if ((ret < 0 && ret != AVERROR_EOF) || pktCopy->size < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to run %s bitstream filter: %s.\n"), char_to_tstring(bsfc->filter->name).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } int side_data_size = 0; auto side_data = av_packet_get_side_data(pktCopy.get(), AV_PKT_DATA_NEW_EXTRADATA, &side_data_size); if (side_data) { AddMessage(RGY_LOG_DEBUG, _T("Found extradata of codec %s: size %d\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), side_data_size); } return RGY_ERR_NONE; } void RGYInputAvcodec::SetExtraData(AVCodecParameters *codecParam, const uint8_t *data, uint32_t size) { if (data == nullptr || size == 0) return; if (codecParam->extradata) av_free(codecParam->extradata); codecParam->extradata_size = size; codecParam->extradata = (uint8_t *)av_malloc(codecParam->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); memcpy(codecParam->extradata, data, size); memset(codecParam->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); }; RGY_CODEC RGYInputAvcodec::checkHWDecoderAvailable(AVCodecID id, AVPixelFormat pixfmt, const CodecCsp *HWDecCodecCsp) { for (int i = 0; i < _countof(HW_DECODE_LIST); i++) { if (HW_DECODE_LIST[i].avcodec_id == id) { auto rgy_codec = HW_DECODE_LIST[i].rgy_codec; if (HWDecCodecCsp->count(rgy_codec) > 0) { const auto rgy_csp = csp_avpixfmt_to_rgy(pixfmt); auto& csp_list = HWDecCodecCsp->at(rgy_codec); if (std::find(csp_list.begin(), csp_list.end(), rgy_csp) != csp_list.end()) { return rgy_codec; } } return RGY_CODEC_UNKNOWN; } } return RGY_CODEC_UNKNOWN; } // コーデックの情報が得られている動画があるかを確認 bool RGYInputAvcodec::hasVideoWithStreamInfo() const { for (uint32_t i = 0; i < m_Demux.format.formatCtx->nb_streams; i++) { const AVStream *stream = m_Demux.format.formatCtx->streams[i]; if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (stream->codecpar->width > 0 && stream->codecpar->height > 0) { return true; } } } return false; } vector<int> RGYInputAvcodec::getStreamIndex(AVMediaType type) { vector<int> streams; const int n_streams = m_Demux.format.formatCtx->nb_streams; for (int i = 0; i < n_streams; i++) { const AVStream *stream = m_Demux.format.formatCtx->streams[i]; if (type == AVMEDIA_TYPE_ATTACHMENT) { if (stream->codecpar->codec_type == type || (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) != 0) { streams.push_back(i); } } else if (stream->codecpar->codec_type == type && (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) == 0) { streams.push_back(i); } } if (type == AVMEDIA_TYPE_VIDEO) { std::sort(streams.begin(), streams.end(), [formatCtx = m_Demux.format.formatCtx](int streamIdA, int streamIdB) { auto pStreamA = formatCtx->streams[streamIdA]; auto pStreamB = formatCtx->streams[streamIdB]; if (pStreamA->codecpar == nullptr) { return false; } if (pStreamB->codecpar == nullptr) { return true; } const int resA = pStreamA->codecpar->width * pStreamA->codecpar->height; const int resB = pStreamB->codecpar->width * pStreamB->codecpar->height; return (resA > resB); }); } return streams; } bool RGYInputAvcodec::vc1StartCodeExists(uint8_t *ptr) { uint32_t code = readUB32(ptr); return check_range_unsigned(code, 0x010A, 0x010F) || check_range_unsigned(code, 0x011B, 0x011F); } void RGYInputAvcodec::vc1FixHeader(int nLengthFix) { if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_WMV3) { m_Demux.video.extradataSize += nLengthFix; uint32_t datasize = m_Demux.video.extradataSize; vector<uint8_t> buffer(20 + datasize, 0); uint32_t header = 0xC5000000; uint32_t width = m_Demux.video.stream->codecpar->width; uint32_t height = m_Demux.video.stream->codecpar->height; uint8_t *dataPtr = m_Demux.video.extradata - nLengthFix; memcpy(buffer.data() + 0, &header, sizeof(header)); memcpy(buffer.data() + 4, &datasize, sizeof(datasize)); memcpy(buffer.data() + 8, dataPtr, datasize); memcpy(buffer.data() + 8 + datasize, &height, sizeof(height)); memcpy(buffer.data() + 12 + datasize, &width, sizeof(width)); m_Demux.video.extradata = (uint8_t *)av_realloc(m_Demux.video.extradata, sizeof(buffer) + AV_INPUT_BUFFER_PADDING_SIZE); m_Demux.video.extradataSize = (int)buffer.size(); memcpy(m_Demux.video.extradata, buffer.data(), buffer.size()); } else { m_Demux.video.extradataSize += nLengthFix; memmove(m_Demux.video.extradata, m_Demux.video.extradata - nLengthFix, m_Demux.video.extradataSize); } } void RGYInputAvcodec::vc1AddFrameHeader(AVPacket *pkt) { uint32_t size = pkt->size; if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_WMV3) { av_grow_packet(pkt, 8); memmove(pkt->data + 8, pkt->data, size); memcpy(pkt->data, &size, sizeof(size)); memset(pkt->data + 4, 0, 4); } else if (!vc1StartCodeExists(pkt->data)) { uint32_t startCode = 0x0D010000; av_grow_packet(pkt, sizeof(startCode)); memmove(pkt->data + sizeof(startCode), pkt->data, size); memcpy(pkt->data, &startCode, sizeof(startCode)); } } bool RGYInputAvcodec::isSelectedLangTrack(const std::string &lang, const AVStream *stream) { if (lang.length() == 0) return false; const auto &streamLang = getTrackLang(stream); if (streamLang.length() == 0) return false; return rgy_lang_equal(lang, streamLang); } bool RGYInputAvcodec::isSelectedCodecTrack(const std::string &selectCodec, const AVStream *stream) { const auto desc = avcodec_descriptor_get_by_name(selectCodec.c_str()); if (desc == nullptr) return false; return desc->id == stream->codecpar->codec_id; } void RGYInputAvcodec::hevcMp42Annexb(AVPacket *pkt) { static const uint8_t SC[] = { 0, 0, 0, 1 }; const uint8_t *ptr, *ptr_fin; if (pkt == NULL) { m_hevcMp42AnnexbBuffer.reserve(m_Demux.video.extradataSize + 128); ptr = m_Demux.video.extradata; ptr_fin = ptr + m_Demux.video.extradataSize; ptr += 0x16; } else { m_hevcMp42AnnexbBuffer.reserve(pkt->size + 128); ptr = pkt->data; ptr_fin = ptr + pkt->size; } const int numOfArrays = *ptr; ptr += !!numOfArrays; while (ptr + 6 < ptr_fin) { ptr += !!numOfArrays; const int count = readUB16(ptr); ptr += 2; int units = (numOfArrays) ? count : 1; for (int i = (std::max)(1, units); i; i--) { uint32_t size = readUB16(ptr); ptr += 2; uint32_t uppper = count << 16; size += (numOfArrays) ? 0 : uppper; m_hevcMp42AnnexbBuffer.insert(m_hevcMp42AnnexbBuffer.end(), SC, SC+4); m_hevcMp42AnnexbBuffer.insert(m_hevcMp42AnnexbBuffer.end(), ptr, ptr+size); ptr += size; } } if (pkt) { if (pkt->buf->size < (int)m_hevcMp42AnnexbBuffer.size()) { av_grow_packet(pkt, (int)m_hevcMp42AnnexbBuffer.size()); } memcpy(pkt->data, m_hevcMp42AnnexbBuffer.data(), m_hevcMp42AnnexbBuffer.size()); pkt->size = (int)m_hevcMp42AnnexbBuffer.size(); } else { if (m_Demux.video.extradata) { av_free(m_Demux.video.extradata); } m_Demux.video.extradata = (uint8_t *)av_malloc(m_hevcMp42AnnexbBuffer.size()); m_Demux.video.extradataSize = (int)m_hevcMp42AnnexbBuffer.size(); memcpy(m_Demux.video.extradata, m_hevcMp42AnnexbBuffer.data(), m_hevcMp42AnnexbBuffer.size()); } m_hevcMp42AnnexbBuffer.clear(); } const AVPacket *RGYInputAvcodec::findFirstAudioStreamPackets(const AVDemuxStream& streamInfo) { //まず、L2キューを探す for (int j = 0; j < (int)m_Demux.qStreamPktL2.size(); j++) { if (m_Demux.qStreamPktL2.get(j)->data.stream_index == streamInfo.index) { return &(m_Demux.qStreamPktL2.get(j)->data); } } //それで見つからなかったら、L1キューを探す for (int j = 0; j < (int)m_Demux.qStreamPktL1.size(); j++) { if (m_Demux.qStreamPktL1[j].stream_index == streamInfo.index) { return &m_Demux.qStreamPktL1[j]; } } return nullptr; } RGY_ERR RGYInputAvcodec::getFirstFramePosAndFrameRate(const sTrim *pTrimList, int nTrimCount, bool bDetectpulldown, bool lowLatency, rgy_rational<int> fpsOverride) { AVRational fpsDecoder = m_Demux.video.stream->avg_frame_rate; const bool fpsDecoderInvalid = (fpsDecoder.den == 0 || fpsDecoder.num == 0); //timebaseが60で割り切れない場合には、ptsが完全には割り切れない値である場合があり、より多くのフレーム数を解析する必要がある int maxCheckFrames = 0; double maxCheckSec = 0.0; if (fpsOverride.is_valid()) { //あらかじめfpsが指定されていればそれを採用する maxCheckFrames = 1; maxCheckSec = 1e99; } else if (m_Demux.format.analyzeSec >= 0.0) { if (m_Demux.format.analyzeSec <= 1.0) { // analyzeが1秒以下の場合 if (!fpsDecoderInvalid) { //fpsDecoderが有効な値ならそれを使用する maxCheckFrames = 1; maxCheckSec = 1e99; fpsOverride = rgy_rational<int>(fpsDecoder.num, fpsDecoder.den); } else { // なるべく短く判定を行う maxCheckFrames = (m_Demux.video.stream->time_base.den >= 1000 && m_Demux.video.stream->time_base.den % 60) ? 128 : 24; maxCheckSec = std::max(m_Demux.format.analyzeSec, 1.0); } } else { maxCheckFrames = 7200; maxCheckSec = m_Demux.format.analyzeSec; } } else { maxCheckFrames = (m_Demux.video.stream->time_base.den >= 1000 && m_Demux.video.stream->time_base.den % 60) ? 128 : ((lowLatency) ? 32 : 48); maxCheckSec = 1e99; } AddMessage(RGY_LOG_DEBUG, _T("fps decoder %d/%d, invalid: %s\n"), fpsDecoder.num, fpsDecoder.den, fpsDecoderInvalid ? _T("true") : _T("false")); AVPacket pkt; av_init_packet(&pkt); const bool bCheckDuration = m_Demux.video.stream->time_base.num * m_Demux.video.stream->time_base.den > 0; const double timebase = (bCheckDuration) ? m_Demux.video.stream->time_base.num / (double)m_Demux.video.stream->time_base.den : 1.0; m_Demux.video.streamFirstKeyPts = 0; int i_samples = 0; std::vector<int> frameDurationList; vector<std::pair<int, int>> durationHistgram; bool bPulldown = false; for (int i_retry = 0; ; i_retry++) { if (i_retry > 0) { //フレームレート推定がうまくいかなそうだった場合、もう少しフレームを解析してみる maxCheckFrames <<= 1; if (maxCheckSec != 1e99) { maxCheckSec *= 2.0; } //ヒストグラム生成などは最初からやり直すので、一度クリアする durationHistgram.clear(); frameDurationList.clear(); } AddMessage(RGY_LOG_DEBUG, _T("maxCheckFrames %d, maxCheckSec: %.3e\n"), maxCheckFrames, maxCheckSec); int ret = 0; for (; i_samples < maxCheckFrames && ((ret = getSample(&pkt)) == 0); i_samples++) { m_Demux.qVideoPkt.push(pkt); if (bCheckDuration) { int64_t diff = 0; if (pkt.dts != AV_NOPTS_VALUE && m_Demux.frames.list(0).dts != AV_NOPTS_VALUE) { diff = (int)(pkt.dts - m_Demux.frames.list(0).dts); } else if (pkt.pts != AV_NOPTS_VALUE && m_Demux.frames.list(0).pts != AV_NOPTS_VALUE) { diff = (int)(pkt.pts - m_Demux.frames.list(0).pts); } const double duration = diff * timebase; if (duration >= maxCheckSec) { break; } } } if (ret != 0 && ret != AVERROR_EOF) { return RGY_ERR_UNKNOWN; } if (m_Demux.qVideoPkt.size() == 0) { AddMessage(RGY_LOG_ERROR, _T("No video packets found!\n")); return RGY_ERR_UNKNOWN; } #if _DEBUG && 0 for (int i = 0; i < m_Demux.frames.frameNum(); i++) { fprintf(stderr, "%3d: pts:%lld, poc:%3d, duration:%5d, duration2:%5d, repeat:%d\n", i, (long long int)m_Demux.frames.list(i).pts, m_Demux.frames.list(i).poc, m_Demux.frames.list(i).duration, m_Demux.frames.list(i).duration2, m_Demux.frames.list(i).repeat_pict); } #endif //ここまで集めたデータでpts, pocを確定させる double dEstFrameDurationByFpsDecoder = 0.0; if (av_isvalid_q(fpsDecoder) && av_isvalid_q(m_Demux.video.stream->time_base)) { dEstFrameDurationByFpsDecoder = av_q2d(av_inv_q(fpsDecoder)) * av_q2d(av_inv_q(m_Demux.video.stream->time_base)); } m_Demux.frames.checkPtsStatus(dEstFrameDurationByFpsDecoder); const int nFramesToCheck = m_Demux.frames.fixedNum(); AddMessage(RGY_LOG_DEBUG, _T("read %d packets.\n"), m_Demux.frames.frameNum()); AddMessage(RGY_LOG_DEBUG, _T("checking %d frame samples.\n"), nFramesToCheck); if (fpsOverride.is_valid()) { //あらかじめfpsが指定されていればそれを採用するので、ここでちゃんと分析する必要はない //この後の分析のため、音声のパケットも取得しておきたい //音声の最初のパケットが見つかっていればOK、そうでなければやり直す bool audioStreamPacketNotFound = false; for (const auto& streamInfo : m_Demux.stream) { if (streamInfo.stream && avcodec_get_type(streamInfo.stream->codecpar->codec_id) == AVMEDIA_TYPE_AUDIO && findFirstAudioStreamPackets(streamInfo) == nullptr) { audioStreamPacketNotFound = true; break; } } if (!audioStreamPacketNotFound) { break; //対象のすべてのストリームの音声の最初のパケットが見つかっていればOK } } else if (nFramesToCheck > 0) { frameDurationList.reserve(nFramesToCheck); int rff_frames = 0; for (int i = 0; i < nFramesToCheck; i++) { #if _DEBUG && 0 fprintf(stderr, "%3d: pts:%lld, poc:%3d, duration:%5d, duration2:%5d, repeat:%d\n", i, (long long int)m_Demux.frames.list(i).pts, m_Demux.frames.list(i).poc, m_Demux.frames.list(i).duration, m_Demux.frames.list(i).duration2, m_Demux.frames.list(i).repeat_pict); #endif if (m_Demux.frames.list(i).poc != FRAMEPOS_POC_INVALID) { int duration = m_Demux.frames.list(i).duration + m_Demux.frames.list(i).duration2; auto repeat_pict = m_Demux.frames.list(i).repeat_pict; //RFF用の補正 if (repeat_pict > 1) { duration = (int)(duration * 2 / (double)(repeat_pict + 1) + 0.5); rff_frames++; } frameDurationList.push_back(duration); } } bPulldown = (bDetectpulldown && ((rff_frames + 1/*たまたま切り捨てられることのないように*/) / (double)nFramesToCheck > 0.45)); //durationのヒストグラムを作成 std::for_each(frameDurationList.begin(), frameDurationList.end(), [&durationHistgram](const int& duration) { auto target = std::find_if(durationHistgram.begin(), durationHistgram.end(), [duration](const std::pair<int, int>& pair) { return pair.first == duration; }); if (target != durationHistgram.end()) { target->second++; } else { durationHistgram.push_back(std::make_pair(duration, 1)); } }); //多い順にソートする std::sort(durationHistgram.begin(), durationHistgram.end(), [](const std::pair<int, int>& pairA, const std::pair<int, int>& pairB) { return pairA.second > pairB.second; }); const auto codec_timebase = av_stream_get_codec_timebase(m_Demux.video.stream); AddMessage(RGY_LOG_DEBUG, _T("stream timebase %d/%d\n"), codec_timebase.num, codec_timebase.den); AddMessage(RGY_LOG_DEBUG, _T("decoder fps %d/%d\n"), fpsDecoder.num, fpsDecoder.den); AddMessage(RGY_LOG_DEBUG, _T("duration histgram of %d frames\n"), durationHistgram.size()); for (const auto& sample : durationHistgram) { AddMessage(RGY_LOG_DEBUG, _T("%3d [%3d frames]\n"), sample.first, sample.second); } //ここでやめてよいか判定する if (i_retry == 0) { //初回は、唯一のdurationが得られている場合を除き再解析する if (durationHistgram.size() <= 1) { break; } } else if (durationHistgram.size() <= 1 //唯一のdurationが得られている || durationHistgram[0].second / (double)frameDurationList.size() > 0.95 //大半がひとつのdurationである || std::abs(durationHistgram[0].first - durationHistgram[1].first) <= 1) { //durationのブレが貧弱なtimebaseによる丸めによるもの(mkvなど) break; } } if (i_retry >= 4) { break; } //再度解析を行う場合は、音声がL2キューに入らないよう、一度fixedNumを0に戻す m_Demux.frames.clearPtsStatus(); } if (fpsOverride.is_valid()) { //あらかじめfpsが指定されていればそれを採用 m_Demux.video.nAvgFramerate = av_make_q(fpsOverride); } else { //durationが0でなく、最も頻繁に出てきたもの auto& mostPopularDuration = durationHistgram[durationHistgram.size() > 1 && durationHistgram[0].first == 0]; struct Rational64 { uint64_t num; uint64_t den; } estimatedAvgFps = { 0 }, nAvgFramerate64 = { 0 }, fpsDecoder64 = { (uint64_t)fpsDecoder.num, (uint64_t)fpsDecoder.den }; if (mostPopularDuration.first == 0) { m_Demux.video.streamPtsInvalid |= RGY_PTS_ALL_INVALID; } else { //avgFpsとtargetFpsが近いかどうか auto fps_near = [](double avgFps, double targetFps) { return std::abs(1 - avgFps / targetFps) < 0.5; }; //durationの平均を求める (ただし、先頭は信頼ならないので、cutoff分は計算に含めない) //std::accumulateの初期値に"(uint64_t)0"と与えることで、64bitによる計算を実行させ、桁あふれを防ぐ //大きすぎるtimebaseの時に必要 double avgDuration = std::accumulate(frameDurationList.begin(), frameDurationList.end(), (uint64_t)0, [this](const uint64_t sum, const int& duration) { return sum + duration; }) / (double)(frameDurationList.size()); if (bPulldown) { avgDuration *= 1.25; } double avgFps = m_Demux.video.stream->time_base.den / (double)(avgDuration * m_Demux.video.stream->time_base.num); double torrelance = (fps_near(avgFps, 25.0) || fps_near(avgFps, 50.0)) ? 0.05 : 0.0008; //25fps, 50fps近辺は基準が甘くてよい if (mostPopularDuration.second / (double)frameDurationList.size() > 0.95 && std::abs(1 - mostPopularDuration.first / avgDuration) < torrelance) { avgDuration = mostPopularDuration.first; AddMessage(RGY_LOG_DEBUG, _T("using popular duration...\n")); } //durationから求めた平均fpsを計算する const uint64_t mul = (uint64_t)ceil(1001.0 / m_Demux.video.stream->time_base.num); estimatedAvgFps.num = (uint64_t)(m_Demux.video.stream->time_base.den / avgDuration * (double)m_Demux.video.stream->time_base.num * mul + 0.5); estimatedAvgFps.den = (uint64_t)m_Demux.video.stream->time_base.num * mul; AddMessage(RGY_LOG_DEBUG, _T("fps mul: %d\n"), mul); AddMessage(RGY_LOG_DEBUG, _T("raw avgDuration: %lf\n"), avgDuration); AddMessage(RGY_LOG_DEBUG, _T("estimatedAvgFps: %llu/%llu\n"), (long long int)estimatedAvgFps.num, (long long int)estimatedAvgFps.den); } if (m_Demux.video.streamPtsInvalid & RGY_PTS_ALL_INVALID) { //ptsとdurationをpkt_timebaseで適当に作成する nAvgFramerate64 = (fpsDecoderInvalid) ? estimatedAvgFps : fpsDecoder64; } else { if (fpsDecoderInvalid) { nAvgFramerate64 = estimatedAvgFps; } else { double dFpsDecoder = fpsDecoder.num / (double)fpsDecoder.den; double dEstimatedAvgFps = estimatedAvgFps.num / (double)estimatedAvgFps.den; //2フレーム分程度がもたらす誤差があっても許容する if (std::abs(dFpsDecoder / dEstimatedAvgFps - 1.0) < (2.0 / frameDurationList.size())) { AddMessage(RGY_LOG_DEBUG, _T("use decoder fps...\n")); nAvgFramerate64 = fpsDecoder64; } else { double dEstimatedAvgFpsCompare = estimatedAvgFps.num / (double)(estimatedAvgFps.den + ((dFpsDecoder < dEstimatedAvgFps) ? 1 : -1)); //durationから求めた平均fpsがデコーダの出したfpsの近似値と分かれば、デコーダの出したfpsを採用する nAvgFramerate64 = (std::abs(dEstimatedAvgFps - dFpsDecoder) < std::abs(dEstimatedAvgFpsCompare - dFpsDecoder)) ? fpsDecoder64 : estimatedAvgFps; } } } AddMessage(RGY_LOG_DEBUG, _T("final AvgFps (raw64): %llu/%llu\n"), (long long int)estimatedAvgFps.num, (long long int)estimatedAvgFps.den); //フレームレートが2000fpsを超えることは考えにくいので、誤判定 //ほかのなにか使えそうな値で代用する const auto codec_timebase = av_stream_get_codec_timebase(m_Demux.video.stream); if (nAvgFramerate64.num / (double)nAvgFramerate64.den > 2000.0) { if (fpsDecoder.den > 0 && fpsDecoder.num > 0) { nAvgFramerate64.num = fpsDecoder.num; nAvgFramerate64.den = fpsDecoder.den; } else if (codec_timebase.den > 0 && codec_timebase.num > 0) { const AVCodec *codec = avcodec_find_decoder(m_Demux.video.stream->codecpar->codec_id); AVCodecContext *pCodecCtx = avcodec_alloc_context3(codec); nAvgFramerate64.num = codec_timebase.den * pCodecCtx->ticks_per_frame; nAvgFramerate64.den = codec_timebase.num; avcodec_free_context(&pCodecCtx); } } rgy_reduce(nAvgFramerate64.num, nAvgFramerate64.den); m_Demux.video.nAvgFramerate = av_make_q((int)nAvgFramerate64.num, (int)nAvgFramerate64.den); AddMessage(RGY_LOG_DEBUG, _T("final AvgFps (gcd): %d/%d\n"), m_Demux.video.nAvgFramerate.num, m_Demux.video.nAvgFramerate.den); struct KnownFpsList { std::vector<int> base; std::vector<int> mul; int timebase_num; }; const KnownFpsList knownFpsSmall = { std::vector<int>{1, 2, 3, 4, 5, 10}, std::vector<int>{1}, 1 }; const KnownFpsList knownFps1 = { std::vector<int>{10, 12, 25}, std::vector<int>{1, 2, 3, 4, 5, 6, 10, 12, 20}, 1 }; const KnownFpsList knownFps1001 = { std::vector<int>{12000, 15000}, std::vector<int>{1, 2, 3, 4, 6, 8, 12, 16}, 1001 }; const double fpsAvg = av_q2d(m_Demux.video.nAvgFramerate); double fpsDiff = std::numeric_limits<double>::max(); AVRational fpsNear = m_Demux.video.nAvgFramerate; auto round_fps = [&fpsDiff, &fpsNear, fpsAvg](const KnownFpsList& known_fps) { for (auto b : known_fps.base) { for (auto m : known_fps.mul) { double fpsKnown = b * m / (double)known_fps.timebase_num; double diff = std::abs(fpsKnown - fpsAvg); if (diff < fpsDiff) { fpsDiff = diff; fpsNear = av_make_q(b * m, known_fps.timebase_num); } } } }; round_fps(knownFpsSmall); round_fps(knownFps1); round_fps(knownFps1001); if (fpsDiff / fpsAvg < 2.0 / 60.0) { m_Demux.video.nAvgFramerate = fpsNear; } } AddMessage(RGY_LOG_DEBUG, _T("final AvgFps (round): %d/%d\n\n"), m_Demux.video.nAvgFramerate.num, m_Demux.video.nAvgFramerate.den); auto trimList = make_vector(pTrimList, nTrimCount); //出力時の音声・字幕解析用に1パケットコピーしておく if (m_Demux.qStreamPktL1.size() > 0 || m_Demux.qStreamPktL2.size() > 0) { if (!m_Demux.frames.isEof() && m_Demux.qStreamPktL2.size() > 0) { //最後まで読み込んでいなかったら、すべてのパケットはqStreamPktL1にあるはず AddMessage(RGY_LOG_ERROR, _T("qStreamPktL2 > 0, this is internal error.\n")); return RGY_ERR_UNDEFINED_BEHAVIOR; } for (auto streamInfo = m_Demux.stream.begin(); streamInfo != m_Demux.stream.end(); streamInfo++) { if (streamInfo->stream && avcodec_get_type(streamInfo->stream->codecpar->codec_id) == AVMEDIA_TYPE_AUDIO) { AddMessage(RGY_LOG_DEBUG, _T("checking for stream #%d\n"), streamInfo->index); const AVPacket *pkt1 = nullptr; //最初のパケット const AVPacket *pkt2 = nullptr; //2番目のパケット //まず、L2キューを探す for (int j = 0; j < (int)m_Demux.qStreamPktL2.size(); j++) { if (m_Demux.qStreamPktL2.get(j)->data.stream_index == streamInfo->index) { if (pkt1) { pkt2 = &(m_Demux.qStreamPktL2.get(j)->data); break; } pkt1 = &(m_Demux.qStreamPktL2.get(j)->data); } } if (pkt2 == nullptr) { //それで見つからなかったら、L1キューを探す for (int j = 0; j < (int)m_Demux.qStreamPktL1.size(); j++) { if (m_Demux.qStreamPktL1[j].stream_index == streamInfo->index) { if (pkt1) { pkt2 = &m_Demux.qStreamPktL1[j]; break; } pkt1 = &m_Demux.qStreamPktL1[j]; } } } if (pkt1 != nullptr) { //1パケット目はたまにおかしいので、可能なら2パケット目を使用する av_packet_ref(&streamInfo->pktSample, (pkt2) ? pkt2 : pkt1); } else { //音声の最初のサンプルを取得できていない AddMessage(RGY_LOG_WARN, _T("failed to find stream #%d in preread.\n"), streamInfo->index); streamInfo = m_Demux.stream.erase(streamInfo) - 1; } } } if (m_Demux.stream.size() == 0) { //音声・字幕の最初のサンプルを取得できていないため、音声がすべてなくなってしまった AddMessage(RGY_LOG_ERROR, _T("failed to find audio/subtitle stream in preread.\n")); return RGY_ERR_UNDEFINED_BEHAVIOR; } } return RGY_ERR_NONE; } RGY_ERR RGYInputAvcodec::parseHDRData() { //まずはstreamのside_dataを探す int size = 0; auto data = av_stream_get_side_data(m_Demux.video.stream, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, &size); if (data) { m_Demux.video.masteringDisplay = av_mastering_display_metadata_alloc(); memcpy(m_Demux.video.masteringDisplay, data, size); AddMessage(RGY_LOG_DEBUG, _T("Mastering Display: R(%f,%f) G(%f,%f) B(%f %f) WP(%f, %f) L(%f,%f)\n"), av_q2d(m_Demux.video.masteringDisplay->display_primaries[0][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[0][1]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[1][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[1][1]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[2][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[2][1]), av_q2d(m_Demux.video.masteringDisplay->white_point[0]), av_q2d(m_Demux.video.masteringDisplay->white_point[1]), av_q2d(m_Demux.video.masteringDisplay->min_luminance), av_q2d(m_Demux.video.masteringDisplay->max_luminance)); } data = av_stream_get_side_data(m_Demux.video.stream, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, &size); if (data) { size_t st_size = 0; m_Demux.video.contentLight = av_content_light_metadata_alloc(&st_size); memcpy(m_Demux.video.contentLight, data, st_size); AddMessage(RGY_LOG_DEBUG, _T("MaxCLL=%d, MaxFALL=%d\n"), m_Demux.video.contentLight->MaxCLL, m_Demux.video.contentLight->MaxFALL); } if (m_Demux.video.masteringDisplay || m_Demux.video.contentLight) { return RGY_ERR_NONE; } if (m_Demux.video.stream->codecpar->codec_id != AV_CODEC_ID_HEVC) { return RGY_ERR_NONE; } //codec側に格納されている値は、streamからは取得できない //HDR関連のmeta情報を取得するために、decoderをキックし、先頭のフレームにセットされる情報を取得する auto codecDecode = avcodec_find_decoder(m_Demux.video.stream->codecpar->codec_id); if (codecDecode == nullptr) { AddMessage(RGY_LOG_ERROR, errorMesForCodec(_T("Failed to find decoder"), m_Demux.video.stream->codecpar->codec_id).c_str()); return RGY_ERR_NOT_FOUND; } std::unique_ptr<AVCodecContext, RGYAVDeleter<AVCodecContext>> codecCtxDec(avcodec_alloc_context3(codecDecode), RGYAVDeleter<AVCodecContext>(avcodec_free_context)); if (!codecCtxDec) { AddMessage(RGY_LOG_ERROR, errorMesForCodec(_T("Failed to allocate decoder"), m_Demux.video.stream->codecpar->codec_id).c_str()); return RGY_ERR_NULL_PTR; } unique_ptr_custom<AVCodecParameters> codecParamCopy(avcodec_parameters_alloc(), [](AVCodecParameters *pCodecPar) { avcodec_parameters_free(&pCodecPar); }); auto ret = avcodec_parameters_copy(codecParamCopy.get(), m_Demux.video.stream->codecpar); if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to copy codec param to context for parser: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } if (m_Demux.video.bsfcCtx || m_Demux.video.bUseHEVCmp42AnnexB) { SetExtraData(codecParamCopy.get(), m_Demux.video.extradata, m_Demux.video.extradataSize); } if (0 > (ret = avcodec_parameters_to_context(codecCtxDec.get(), codecParamCopy.get()))) { AddMessage(RGY_LOG_ERROR, _T("failed to set codec param to context for decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } AVDictionary *pDict = nullptr; av_dict_set_int(&pDict, "threads", 1, 0); if (0 > (ret = av_opt_set_dict(codecCtxDec.get(), &pDict))) { AddMessage(RGY_LOG_ERROR, _T("Failed to set threads for decode (codec: %s): %s\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } av_dict_free(&pDict); codecCtxDec->time_base = av_stream_get_codec_timebase(m_Demux.video.stream); codecCtxDec->pkt_timebase = m_Demux.video.stream->time_base; if (0 > (ret = avcodec_open2(codecCtxDec.get(), codecDecode, nullptr))) { AddMessage(RGY_LOG_ERROR, _T("Failed to open decoder for %s: %s\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNSUPPORTED; } std::unique_ptr<AVFrame, RGYAVDeleter<AVFrame>> frameDec(av_frame_alloc(), RGYAVDeleter<AVFrame>(av_frame_free)); bool got_frame = false; for (uint32_t i = 0; i < m_Demux.qVideoPkt.size() && !got_frame; i++) { AVPacket *pkt = &m_Demux.qVideoPkt.get(i)->data; ret = avcodec_send_packet(codecCtxDec.get(), pkt); if (ret == AVERROR_EOF) { //これ以上パケットを送れない AddMessage(RGY_LOG_DEBUG, _T("failed to send packet to video decoder, already flushed: %s.\n"), qsv_av_err2str(ret).c_str()); } else if (ret < 0 && ret != AVERROR(EAGAIN)) { AddMessage(RGY_LOG_ERROR, _T("failed to send packet to video decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNDEFINED_BEHAVIOR; } ret = avcodec_receive_frame(codecCtxDec.get(), frameDec.get()); if (ret == AVERROR(EAGAIN)) { //もっとパケットを送る必要がある continue; } if (ret == AVERROR_EOF) { //最後まで読み込んだ return RGY_ERR_MORE_DATA; } if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to receive frame from video decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNDEFINED_BEHAVIOR; } got_frame = true; } if (got_frame) { auto side_data = av_frame_get_side_data(frameDec.get(), AV_FRAME_DATA_MASTERING_DISPLAY_METADATA); if (side_data) { m_Demux.video.masteringDisplay = av_mastering_display_metadata_alloc(); memcpy(m_Demux.video.masteringDisplay, side_data->data, sizeof(AVMasteringDisplayMetadata)); AddMessage(RGY_LOG_DEBUG, _T("Mastering Display: R(%f,%f) G(%f,%f) B(%f %f) WP(%f, %f) L(%f,%f)\n"), av_q2d(m_Demux.video.masteringDisplay->display_primaries[0][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[0][1]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[1][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[1][1]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[2][0]), av_q2d(m_Demux.video.masteringDisplay->display_primaries[2][1]), av_q2d(m_Demux.video.masteringDisplay->white_point[0]), av_q2d(m_Demux.video.masteringDisplay->white_point[1]), av_q2d(m_Demux.video.masteringDisplay->min_luminance), av_q2d(m_Demux.video.masteringDisplay->max_luminance)); } side_data = av_frame_get_side_data(frameDec.get(), AV_FRAME_DATA_CONTENT_LIGHT_LEVEL); if (side_data) { size_t st_size = 0; m_Demux.video.contentLight = av_content_light_metadata_alloc(&st_size); memcpy(m_Demux.video.contentLight, side_data->data, st_size); AddMessage(RGY_LOG_DEBUG, _T("MaxCLL=%d, MaxFALL=%d\n"), m_Demux.video.contentLight->MaxCLL, m_Demux.video.contentLight->MaxFALL); } } return RGY_ERR_NONE; } RGY_ERR RGYInputAvcodec::parseHDR10plus(AVPacket *pkt) { if (m_Demux.video.stream->codecpar->codec_id != AV_CODEC_ID_HEVC) { return RGY_ERR_NONE; } const auto nal_list = parse_nal_unit_hevc(pkt->data, pkt->size); for (const auto& nal_unit : nal_list) { if (nal_unit.type != NALU_HEVC_PREFIX_SEI) { continue; } const uint8_t *ptr = nal_unit.ptr; //nal header if (ptr[0] == 0x00 && ptr[1] == 0x00 && ptr[2] == 0x01) { ptr += 3; } else if (ptr[0] == 0x00 && ptr[1] == 0x00 && ptr[2] == 0x00 && ptr[3] == 0x01) { ptr += 4; } else { continue; } if (ptr[0] == ((uint8_t)NALU_HEVC_PREFIX_SEI << 1) && ptr[1] == 0x01 && ptr[2] == USER_DATA_REGISTERED_ITU_T_T35) { ptr += 3; const auto data_unnal = unnal(ptr, nal_unit.ptr + nal_unit.size - ptr); ptr = data_unnal.data(); size_t size = 0; while (*ptr == 0xff) { size += *ptr++; } size += *ptr++; //AVDictionaryに格納するため、base64 encodeを行う const auto encoded = cppcodec::base64_rfc4648::encode(ptr, size); AVDictionary *frameDict = nullptr; int ret = av_dict_set(&frameDict, HDR10PLUS_METADATA_KEY, encoded.c_str(), 0); if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("Failed to set dictionary for key=%s\n"), char_to_tstring(HDR10PLUS_METADATA_KEY).c_str()); return RGY_ERR_UNKNOWN; } int frameDictSize = 0; uint8_t *frameDictData = av_packet_pack_dictionary(frameDict, &frameDictSize); if (frameDictData == nullptr) { AddMessage(RGY_LOG_ERROR, _T("Failed to pack dictionary for key=%s\n"), char_to_tstring(HDR10PLUS_METADATA_KEY).c_str()); return RGY_ERR_UNKNOWN; } ret = av_packet_add_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, frameDictData, frameDictSize); if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("Failed to add side packet hdr10plus metadata.\n"), char_to_tstring(HDR10PLUS_METADATA_KEY).c_str()); return RGY_ERR_UNKNOWN; } av_dict_free(&frameDict); AddMessage(RGY_LOG_TRACE, _T("Added hdr10plus metadata to packet timestamp %lld (%s), size %d, encoded size %d\n"), pkt->pts, getTimestampString(pkt->pts, m_Demux.format.formatCtx->streams[pkt->stream_index]->time_base).c_str(), size, (int)encoded.size()); } } return RGY_ERR_NONE; } RGYFrameDataHDR10plus *RGYInputAvcodec::getHDR10plusMetaData(const AVFrame *frame) { auto ptrDictMetadata = av_dict_get(frame->metadata, HDR10PLUS_METADATA_KEY, nullptr, 0); if (ptrDictMetadata) { const auto ptrDictMetadataValLen = strlen(ptrDictMetadata->value); const auto decoded = cppcodec::base64_rfc4648::decode(ptrDictMetadata->value, ptrDictMetadataValLen); AddMessage(RGY_LOG_TRACE, _T("Got hdr10plus metadata to packet timestamp %lld (%s), size %d, decoded size %d\n"), frame->pts, getTimestampString(frame->pts, m_Demux.video.stream->time_base).c_str(), ptrDictMetadataValLen, (int)decoded.size()); return new RGYFrameDataHDR10plus(decoded.data(), decoded.size(), frame->pts); } return nullptr; } RGYFrameDataHDR10plus *RGYInputAvcodec::getHDR10plusMetaData(const AVPacket *pkt) { int side_data_size = 0; auto side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &side_data_size); if (side_data) { AVDictionary *dict = nullptr; auto ret = av_packet_unpack_dictionary(side_data, side_data_size, &dict); if (ret == 0) { const auto ptrDictMetadata = av_dict_get(dict, HDR10PLUS_METADATA_KEY, nullptr, 0); if (ptrDictMetadata) { const auto ptrDictMetadataValLen = strlen(ptrDictMetadata->value); const auto decoded = cppcodec::base64_rfc4648::decode(ptrDictMetadata->value, ptrDictMetadataValLen); AddMessage(RGY_LOG_TRACE, _T("Got hdr10plus metadata to packet timestamp %lld (%s), size %d, decoded size %d\n"), pkt->pts, getTimestampString(pkt->pts, m_Demux.video.stream->time_base).c_str(), ptrDictMetadataValLen, (int)decoded.size()); return new RGYFrameDataHDR10plus(decoded.data(), decoded.size(), pkt->pts); } } } return nullptr; } RGY_ERR RGYInputAvcodec::initFormatCtx(const TCHAR *strFileName, const RGYInputAvcodecPrm *input_prm, const int iretry) { CloseFormat(&m_Demux.format); const auto retry_multi = rgy_pow_int(rgy_rational(3, 2), iretry); // input-retryを行うときに、probesize/analyzedurationにかける倍率 int ret = 0; std::string filename_char; if (0 == tchar_to_string(strFileName, filename_char, CP_UTF8)) { AddMessage(RGY_LOG_ERROR, _T("failed to convert filename to utf-8 characters.\n")); return RGY_ERR_UNSUPPORTED; } m_Demux.format.isPipe = (0 == strcmp(filename_char.c_str(), "-")) || (0 == strncmp(filename_char.c_str(), "pipe:", strlen("pipe:"))) || filename_char.c_str() == strstr(filename_char.c_str(), R"(\\.\pipe\)"); m_Demux.format.analyzeSec = input_prm->analyzeSec; m_Demux.format.formatCtx = avformat_alloc_context(); if (input_prm->probesize >= 0 || input_prm->analyzeSec >= 0) { // probesizeの設定 // avformat_find_stream_infoで各コーデックの詳細情報を解析する長さのほか、avformat_open_inputでフォーマットを分析する際の長さにも使用される // analyzeSec が指定され、probesizeが特に指定されていないときは、大きめにとってanalyzeSec分必ず分析されるようにする const int64_t probesize = (input_prm->probesize > 0) ? input_prm->probesize * retry_multi.n() / retry_multi.d() : 1 << 29; if (0 != (ret = av_dict_set_int(&m_Demux.format.formatOptions, "probesize", probesize, 0))) { AddMessage(RGY_LOG_ERROR, _T("failed to set probesize to %s: error %d\n"), rgy_print_num_with_siprefix(probesize).c_str(), ret); return RGY_ERR_INVALID_PARAM; } else { AddMessage(RGY_LOG_DEBUG, _T("set probesize: %s\n"), rgy_print_num_with_siprefix(probesize).c_str()); } } if (m_Demux.format.analyzeSec >= 0) { const auto value = (int64_t)(m_Demux.format.analyzeSec * AV_TIME_BASE * retry_multi.qdouble() + 0.5); if (0 != (ret = av_dict_set_int(&m_Demux.format.formatOptions, "analyzeduration", value, 0))) { AddMessage(RGY_LOG_ERROR, _T("failed to set analyzeduration to %.2f sec, error %s\n"), value / (double)AV_TIME_BASE, qsv_av_err2str(ret).c_str()); } else { AddMessage(RGY_LOG_DEBUG, _T("set analyzeduration: %.2f sec\n"), value / (double)AV_TIME_BASE); } } if (0 == strcmp(filename_char.c_str(), "-")) { #if defined(_WIN32) || defined(_WIN64) if (_setmode(_fileno(stdin), _O_BINARY) < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to switch stdin to binary mode.\n")); return RGY_ERR_UNDEFINED_BEHAVIOR; } #endif //#if defined(_WIN32) || defined(_WIN64) AddMessage(RGY_LOG_DEBUG, _T("input source set to stdin.\n")); filename_char = "pipe:0"; } for (const auto& inputOpt : input_prm->inputOpt) { const std::string optName = tchar_to_string(inputOpt.first); const std::string optValue = tchar_to_string(inputOpt.second); const int err = av_dict_set(&m_Demux.format.formatOptions, optName.c_str(), optValue.c_str(), 0); if (err < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to set input opt: %s = %s.\n"), inputOpt.first.c_str(), inputOpt.second.c_str()); return RGY_ERR_INVALID_PARAM; } AddMessage(RGY_LOG_DEBUG, _T("set input opt: %s = %s.\n"), inputOpt.first.c_str(), inputOpt.second.c_str()); } //ts向けの設定 bool scan_all_pmts_set = false; if (!av_dict_get(m_Demux.format.formatOptions, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) { av_dict_set(&m_Demux.format.formatOptions, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE); scan_all_pmts_set = true; } //入力フォーマットが指定されていれば、それを渡す AVInputFormat *inFormat = nullptr; if (input_prm->pInputFormat) { if (nullptr == (inFormat = av_find_input_format(tchar_to_string(input_prm->pInputFormat).c_str()))) { AddMessage(RGY_LOG_ERROR, _T("Unknown Input format: %s.\n"), input_prm->pInputFormat); return RGY_ERR_INVALID_FORMAT; } } #if USE_CUSTOM_INPUT if (m_Demux.format.isPipe || (!usingAVProtocols(filename_char, 0) && input_prm->inputOpt.size() == 0 && (inFormat == nullptr || !(inFormat->flags & (AVFMT_NEEDNUMBER | AVFMT_NOFILE))))) { if (0 == _tcscmp(strFileName, _T("-"))) { m_Demux.format.fpInput = stdin; } else { m_Demux.format.fpInput = _tfsopen(strFileName, _T("rb"), _SH_DENYWR); if (m_Demux.format.fpInput == NULL) { errno_t error = errno; AddMessage(RGY_LOG_ERROR, _T("failed to open input file \"%s\": %s.\n"), strFileName, _tcserror(error)); return RGY_ERR_FILE_OPEN; // Couldn't open file } if (!m_Demux.format.isPipe) { if (rgy_get_filesize(strFileName, &m_Demux.format.inputFilesize) && m_Demux.format.inputFilesize == 0) { AddMessage(RGY_LOG_ERROR, _T("size of input file \"%s\" is 0\n"), strFileName); return RGY_ERR_FILE_OPEN; } } } m_Demux.format.inputBufferSize = 4 * 1024; m_Demux.format.inputBuffer = (char *)av_malloc(m_Demux.format.inputBufferSize); if (NULL == (m_Demux.format.formatCtx->pb = avio_alloc_context((unsigned char *)m_Demux.format.inputBuffer, m_Demux.format.inputBufferSize, 0, this, funcReadPacket, funcWritePacket, (m_Demux.format.isPipe) ? nullptr : funcSeek))) { AddMessage(RGY_LOG_ERROR, _T("failed to alloc avio context.\n")); return RGY_ERR_NULL_PTR; } } else if (m_cap2ass.enabled()) { AddMessage(RGY_LOG_ERROR, (input_prm->inputOpt.size() > 0) ? _T("--caption2ass cannot be used with --input-option.\n") : _T("--caption2ass only supported when input is file or pipe.\n")); m_cap2ass.disable(); } #endif //ファイルのオープン if ((ret = avformat_open_input(&(m_Demux.format.formatCtx), filename_char.c_str(), inFormat, &m_Demux.format.formatOptions)) != 0) { AddMessage(RGY_LOG_ERROR, _T("error opening file \"%s\": %s\n"), char_to_tstring(filename_char, CP_UTF8).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_FILE_OPEN; // Couldn't open file } AddMessage(RGY_LOG_DEBUG, _T("opened file \"%s\".\n"), char_to_tstring(filename_char, CP_UTF8).c_str()); //不正なオプションを渡していないかチェック for (const AVDictionaryEntry *t = NULL; NULL != (t = av_dict_get(m_Demux.format.formatOptions, "", t, AV_DICT_IGNORE_SUFFIX));) { if (strcmp(t->key, "scan_all_pmts") != 0) { AddMessage(RGY_LOG_WARN, _T("Unknown input option: %s=%s, ignored.\n"), char_to_tstring(t->key).c_str(), char_to_tstring(t->value).c_str()); } } m_Demux.format.formatCtx->flags |= AVFMT_FLAG_NONBLOCK; // ffmpeg_opt.cのopen_input_file()と同様にフラグを立てる if (avformat_find_stream_info(m_Demux.format.formatCtx, nullptr) < 0) { AddMessage(RGY_LOG_ERROR, _T("error finding stream information.\n")); return RGY_ERR_UNKNOWN; // Couldn't find stream information } AddMessage(RGY_LOG_DEBUG, _T("got stream information.\n")); av_dump_format(m_Demux.format.formatCtx, 0, filename_char.c_str(), 0); //dump_format(dec.formatCtx, 0, argv[1], 0); return RGY_ERR_NONE; } #pragma warning(push) #pragma warning(disable:4100) #pragma warning(disable:4127) //warning C4127: 条件式が定数です。 RGY_ERR RGYInputAvcodec::Init(const TCHAR *strFileName, VideoInfo *inputInfo, const RGYInputPrm *prm) { const RGYInputAvcodecPrm *input_prm = dynamic_cast<const RGYInputAvcodecPrm*>(prm); if (input_prm->readVideo) { if (inputInfo->type != RGY_INPUT_FMT_AVANY) { m_readerName = (inputInfo->type != RGY_INPUT_FMT_AVSW) ? _T("av" DECODER_NAME) : _T("avsw"); } } else { m_readerName = _T("avsw"); } m_Demux.video.readVideo = input_prm->readVideo; m_Demux.thread.queueInfo = input_prm->queueInfo; if (input_prm->readVideo) { m_inputVideoInfo = *inputInfo; } else { m_inputVideoInfo = VideoInfo(); } if (!check_avcodec_dll()) { AddMessage(RGY_LOG_ERROR, error_mes_avcodec_dll_not_found()); return RGY_ERR_NULL_PTR; } m_convert = std::unique_ptr<RGYConvertCSP>(new RGYConvertCSP(prm->threadCsp)); for (int i = 0; i < input_prm->nAudioSelectCount; i++) { tstring audioLog = strsprintf(_T("select audio track %s, codec %s"), (input_prm->ppAudioSelect[i]->trackID) ? strsprintf(_T("#%d"), input_prm->ppAudioSelect[i]->trackID).c_str() : _T("all"), input_prm->ppAudioSelect[i]->encCodec.c_str()); if (input_prm->ppAudioSelect[i]->extractFormat.length() > 0) { audioLog += tstring(_T("format ")) + input_prm->ppAudioSelect[i]->extractFormat; } if (input_prm->ppAudioSelect[i]->encCodec.length() > 0 && !avcodecIsCopy(input_prm->ppAudioSelect[i]->encCodec)) { audioLog += strsprintf(_T("bitrate %d"), input_prm->ppAudioSelect[i]->encBitrate); } if (input_prm->ppAudioSelect[i]->extractFilename.length() > 0) { audioLog += tstring(_T("filename \"")) + input_prm->ppAudioSelect[i]->extractFilename + tstring(_T("\"")); } AddMessage(RGY_LOG_DEBUG, audioLog); } av_log_set_level((m_printMes->getLogLevel() == RGY_LOG_DEBUG) ? AV_LOG_DEBUG : RGY_AV_LOG_LEVEL); av_qsv_log_set(m_printMes); if (input_prm->caption2ass != FORMAT_INVALID) { auto err = m_cap2ass.init(m_printMes, input_prm->caption2ass); if (err != RGY_ERR_NONE) { return err; } } if (input_prm->logPackets.length() > 0) { m_fpPacketList.reset(_tfopen(input_prm->logPackets.c_str(), _T("w"))); } // input-probesizeやinput-analyzeが小さすぎて動画情報を得られなかったときのためのretryループ (デフォルトでは無効) for (int iretry = 0; iretry < input_prm->inputRetry + 1; iretry++) { if (iretry > 0) { AddMessage(RGY_LOG_WARN, _T("Failed to get video stream information, retry opening input (%d/%d)!\n"), iretry, input_prm->inputRetry); } auto err = initFormatCtx(strFileName, input_prm, iretry); if (err != RGY_ERR_NONE) { return err; } if (!input_prm->readVideo) { // 動画が必要なければこのループから抜ける break; } if (hasVideoWithStreamInfo()) { // コーデックの情報が得られている動画があればこのループから抜ける break; } } //キュー関連初期化 //getFirstFramePosAndFrameRateで大量にパケットを突っ込む可能性があるので、この段階ではcapacityは無限大にしておく m_Demux.qVideoPkt.init(4096, SIZE_MAX, 4); m_Demux.qVideoPkt.set_keep_length(1); // 読み込み終了の判定に使うので、0にしてはならない m_Demux.qStreamPktL2.init(4096); //動画ストリームを探す //動画ストリームは動画を処理しなかったとしても同期のため必要 auto videoStreams = getStreamIndex(AVMEDIA_TYPE_VIDEO); if (videoStreams.size()) { if (input_prm->videoTrack) { if (videoStreams.size() < (uint32_t)std::abs(input_prm->videoTrack)) { AddMessage(RGY_LOG_ERROR, _T("track %d was selected for video, but input only contains %d video tracks.\n"), input_prm->videoTrack, videoStreams.size()); return RGY_ERR_INVALID_VIDEO_PARAM; } else if (input_prm->videoTrack < 0) { //逆順に並べ替え std::reverse(videoStreams.begin(), videoStreams.end()); } m_Demux.video.index = videoStreams[std::abs(input_prm->videoTrack)-1]; } else if (input_prm->videoStreamId) { auto streamIndexFound = std::find_if(videoStreams.begin(), videoStreams.end(), [formatCtx = m_Demux.format.formatCtx, nSearchId = input_prm->videoStreamId](int nStreamIndex) { return (formatCtx->streams[nStreamIndex]->id == nSearchId); }); if (streamIndexFound == videoStreams.end()) { AddMessage(RGY_LOG_ERROR, _T("stream id %d (0x%x) not found in video tracks.\n"), input_prm->videoStreamId, input_prm->videoStreamId); return RGY_ERR_INVALID_VIDEO_PARAM; } m_Demux.video.index = *streamIndexFound; } else { m_Demux.video.index = videoStreams[0]; } auto selectedStream = std::find(videoStreams.begin(), videoStreams.end(), m_Demux.video.index); if (selectedStream == videoStreams.end()) { AddMessage(RGY_LOG_ERROR, _T("video stream lost!\n")); return RGY_ERR_UNDEFINED_BEHAVIOR; } //もし、選択された動画ストリームが先頭にないのなら、先頭に入れ替える if (selectedStream != videoStreams.begin()) { int nSelectedStreamIndex = *selectedStream; videoStreams.erase(selectedStream); videoStreams.insert(videoStreams.begin(), nSelectedStreamIndex); } AddMessage(RGY_LOG_DEBUG, _T("found video stream, stream idx %d\n"), m_Demux.video.index); auto stream = m_Demux.format.formatCtx->streams[m_Demux.video.index]; //HEVC入力の際に大量にメッセージが出て劇的に遅くなることがあるのを回避 #if 0 if (stream->codecpar->codec_id == AV_CODEC_ID_HEVC) { AVDictionary *pDict = nullptr; av_dict_set_int(&pDict, "log_level_offset", AV_LOG_ERROR, 0); if (0 > (ret = av_opt_set_dict(stream->codec, &pDict))) { AddMessage(RGY_LOG_WARN, _T("failed to set log_level_offset for HEVC codec reader.\n")); } else { AddMessage(RGY_LOG_DEBUG, _T("set log_level_offset for HEVC codec reader.\n")); } av_dict_free(&pDict); } #endif m_Demux.video.stream = stream; } //音声ストリームを探す if (input_prm->readAudio || input_prm->readSubtitle || input_prm->readData || input_prm->readAttachment) { vector<int> mediaStreams; if (input_prm->readAudio) { auto audioStreams = getStreamIndex(AVMEDIA_TYPE_AUDIO); //他のファイルから音声を読み込む場合もあるので、ここでチェックはできない //if (audioStreams.size() == 0) { // AddMessage(RGY_LOG_ERROR, _T("--audio-encode/--audio-copy/--audio-file is set, but no audio stream found.\n")); // return RGY_ERR_NOT_FOUND; //} m_Demux.format.audioTracks = (int)audioStreams.size(); vector_cat(mediaStreams, audioStreams); } if (input_prm->readSubtitle) { auto subStreams = getStreamIndex(AVMEDIA_TYPE_SUBTITLE); if (subStreams.size() == 0 && !m_cap2ass.enabled()) { AddMessage(RGY_LOG_WARN, _T("--sub-copy%s is set, but no subtitle stream found.\n"), (ENCODER_NVENC) ? _T("/--vpp-subburn") : _T("")); } else { m_Demux.format.subtitleTracks = (int)subStreams.size(); vector_cat(mediaStreams, subStreams); } } if (input_prm->readData) { auto dataStreams = getStreamIndex(AVMEDIA_TYPE_DATA); m_Demux.format.dataTracks = (int)dataStreams.size(); vector_cat(mediaStreams, dataStreams); } if (input_prm->readAttachment) { auto attachmentStreams = getStreamIndex(AVMEDIA_TYPE_ATTACHMENT); m_Demux.format.attachmentTracks = (int)attachmentStreams.size(); vector_cat(mediaStreams, attachmentStreams); } for (int iTrack = 0; iTrack < (int)mediaStreams.size(); iTrack++) { const AVStream *srcStream = m_Demux.format.formatCtx->streams[mediaStreams[iTrack]]; const AVCodecID codecId = srcStream->codecpar->codec_id; AVMediaType mediaType = srcStream->codecpar->codec_type; bool useStream = false; AudioSelect *pAudioSelect = nullptr; //トラックに対応するAudioSelect (字幕ストリームの場合はnullptrのまま) if (mediaType == AVMEDIA_TYPE_ATTACHMENT || (srcStream->disposition & AV_DISPOSITION_ATTACHED_PIC) != 0) { //Attachmentの場合 for (int i = 0; !useStream && i < input_prm->nAttachmentSelectCount; i++) { if (input_prm->ppAttachmentSelect[i]->trackID == 0 //特に指定なし = 全指定かどうか || input_prm->ppAttachmentSelect[i]->trackID - 1 == (iTrack - m_Demux.format.audioTracks - m_Demux.format.subtitleTracks - m_Demux.format.dataTracks)) { useStream = true; mediaType = AVMEDIA_TYPE_ATTACHMENT; } } } else if (mediaType == AVMEDIA_TYPE_SUBTITLE) { //字幕・データの場合 for (int i = 0; !useStream && i < input_prm->nSubtitleSelectCount; i++) { if (input_prm->ppSubtitleSelect[i]->trackID == 0 //特に指定なし = 全指定かどうか || (input_prm->ppSubtitleSelect[i]->trackID == TRACK_SELECT_BY_LANG && isSelectedLangTrack(input_prm->ppSubtitleSelect[i]->lang, srcStream)) || (input_prm->ppSubtitleSelect[i]->trackID == TRACK_SELECT_BY_CODEC && isSelectedCodecTrack(input_prm->ppSubtitleSelect[i]->selectCodec, srcStream)) || input_prm->ppSubtitleSelect[i]->trackID - 1 == (iTrack - m_Demux.format.audioTracks)) { useStream = true; } } } else if (mediaType == AVMEDIA_TYPE_DATA) { //データの場合 for (int i = 0; !useStream && i < input_prm->nDataSelectCount; i++) { if (input_prm->ppDataSelect[i]->trackID == 0 //特に指定なし = 全指定かどうか || (input_prm->ppDataSelect[i]->trackID == TRACK_SELECT_BY_LANG && isSelectedLangTrack(input_prm->ppDataSelect[i]->lang, srcStream)) || (input_prm->ppDataSelect[i]->trackID == TRACK_SELECT_BY_CODEC && isSelectedCodecTrack(input_prm->ppDataSelect[i]->selectCodec, srcStream)) || input_prm->ppDataSelect[i]->trackID - 1 == (iTrack - m_Demux.format.audioTracks - m_Demux.format.subtitleTracks)) { useStream = true; } } } else { //音声の場合 for (int i = 0; !useStream && i < input_prm->nAudioSelectCount; i++) { if ((input_prm->ppAudioSelect[i]->trackID == TRACK_SELECT_BY_LANG && isSelectedLangTrack(input_prm->ppAudioSelect[i]->lang, srcStream)) || (input_prm->ppAudioSelect[i]->trackID == TRACK_SELECT_BY_CODEC && isSelectedCodecTrack(input_prm->ppAudioSelect[i]->selectCodec, srcStream)) || (input_prm->ppAudioSelect[i]->trackID - 1 == (iTrack))) { useStream = true; pAudioSelect = input_prm->ppAudioSelect[i]; } } if (pAudioSelect == nullptr) { //見つからなかったら、全指定(trackID = 0)のものを使用する for (int i = 0; !useStream && i < input_prm->nAudioSelectCount; i++) { if (input_prm->ppAudioSelect[i]->trackID == 0) { useStream = true; pAudioSelect = input_prm->ppAudioSelect[i]; } } } } if (useStream) { //存在するチャンネルまでのchannel_layoutのマスクを作成する //特に引数を指定せず--audio-channel-layoutを指定したときには、 //pnStreamChannelsはchannelの存在しない不要なビットまで立っているのをここで修正 if (pAudioSelect //字幕ストリームの場合は無視 && isSplitChannelAuto(pAudioSelect->streamChannelSelect)) { const uint64_t channel_layout_mask = UINT64_MAX >> (sizeof(channel_layout_mask) * 8 - m_Demux.format.formatCtx->streams[mediaStreams[iTrack]]->codecpar->channels); for (uint32_t iSubStream = 0; iSubStream < MAX_SPLIT_CHANNELS; iSubStream++) { pAudioSelect->streamChannelSelect[iSubStream] &= channel_layout_mask; } for (uint32_t iSubStream = 0; iSubStream < MAX_SPLIT_CHANNELS; iSubStream++) { pAudioSelect->streamChannelOut[iSubStream] &= channel_layout_mask; } } //必要であれば、サブストリームを追加する for (uint32_t iSubStream = 0; iSubStream == 0 || //初回は字幕・音声含め、かならず登録する必要がある (iSubStream < MAX_SPLIT_CHANNELS //最大サブストリームの上限 && pAudioSelect != nullptr //字幕ではない && pAudioSelect->streamChannelSelect[iSubStream]); //audio-splitが指定されている iSubStream++) { AVDemuxStream stream = { 0 }; switch (mediaType) { case AVMEDIA_TYPE_SUBTITLE: stream.trackId = trackFullID(AVMEDIA_TYPE_SUBTITLE, iTrack - m_Demux.format.audioTracks + input_prm->trackStartSubtitle); break; case AVMEDIA_TYPE_DATA: stream.trackId = trackFullID(AVMEDIA_TYPE_DATA, iTrack - m_Demux.format.audioTracks - m_Demux.format.subtitleTracks + input_prm->trackStartData); break; case AVMEDIA_TYPE_ATTACHMENT: stream.trackId = trackFullID(AVMEDIA_TYPE_ATTACHMENT, iTrack - m_Demux.format.audioTracks - m_Demux.format.subtitleTracks - m_Demux.format.dataTracks + input_prm->trackStartData); break; case AVMEDIA_TYPE_AUDIO: stream.trackId = trackFullID(AVMEDIA_TYPE_AUDIO, iTrack + input_prm->trackStartAudio); break; default: AddMessage(RGY_LOG_ERROR, _T("Unknoen media type!")); return RGY_ERR_INVALID_PARAM; } stream.index = mediaStreams[iTrack]; stream.subStreamId = iSubStream; stream.sourceFileIndex = input_prm->fileIndex; stream.stream = m_Demux.format.formatCtx->streams[stream.index]; stream.timebase = stream.stream->time_base; stream.extractErrExcess = 0; stream.appliedTrimBlock = -1; stream.trimOffset = 0; stream.aud0_fin = AV_NOPTS_VALUE; strncpy_s(stream.lang, _countof(stream.lang), getTrackLang(m_Demux.format.formatCtx->streams[stream.index]).c_str(), 3); if (pAudioSelect) { stream.addDelayMs = pAudioSelect->addDelayMs; memcpy(stream.streamChannelSelect, pAudioSelect->streamChannelSelect, sizeof(stream.streamChannelSelect)); memcpy(stream.streamChannelOut, pAudioSelect->streamChannelOut, sizeof(stream.streamChannelOut)); } m_Demux.stream.push_back(stream); AddMessage(RGY_LOG_DEBUG, _T("found %s stream, stream idx %d, trackID %d.%d, %s, frame_size %d, timebase %d/%d, delay %d ms\n"), get_media_type_string(codecId).c_str(), stream.index, trackID(stream.trackId), stream.subStreamId, char_to_tstring(avcodec_get_name(codecId)).c_str(), stream.stream->codecpar->frame_size, stream.stream->time_base.num, stream.stream->time_base.den, stream.addDelayMs); } } } //指定されたすべての音声トラックが発見されたかを確認する for (int i = 0; i < input_prm->nAudioSelectCount; i++) { //全指定のトラック=0は無視 if (input_prm->ppAudioSelect[i]->trackID > 0) { bool audioFound = false; for (const auto& stream : m_Demux.stream) { if (trackID(stream.trackId) == input_prm->ppAudioSelect[i]->trackID) { audioFound = true; break; } } if (!audioFound) { AddMessage(RGY_LOG_WARN, _T("could not find audio track #%d\n"), input_prm->ppAudioSelect[i]->trackID); } } } } if (m_cap2ass.enabled()) { const int maxSubTrackId = std::accumulate(m_Demux.stream.begin(), m_Demux.stream.end(), 0, [](int a, const AVDemuxStream& b) { return trackMediaType(b.trackId) == AVMEDIA_TYPE_SUBTITLE ? std::max(a, trackID(b.trackId)) : a; }); m_cap2ass.setIndex(m_Demux.format.formatCtx->nb_streams, trackFullID(AVMEDIA_TYPE_SUBTITLE, maxSubTrackId+1)); m_Demux.stream.push_back(m_cap2ass.stream()); m_Demux.format.subtitleTracks++; } if (input_prm->readChapter) { m_Demux.chapter = make_vector((const AVChapter **)m_Demux.format.formatCtx->chapters, m_Demux.format.formatCtx->nb_chapters); } //動画処理の初期化を行う if (input_prm->readVideo) { if (m_Demux.video.stream == nullptr) { AddMessage(RGY_LOG_ERROR, _T("unable to find video stream.\n")); return RGY_ERR_NOT_FOUND; } if (m_Demux.video.stream->codecpar->width == 0 || m_Demux.video.stream->codecpar->height == 0) { AddMessage(RGY_LOG_ERROR, _T("Input video info not parsed yet [%dx%d]!\n"), m_Demux.video.stream->codecpar->width, m_Demux.video.stream->codecpar->height); AddMessage(RGY_LOG_ERROR, _T("Consider increasing the value for the --input-analyze and/or --input-probesize!\n"), input_prm->analyzeSec, input_prm->probesize); return RGY_ERR_NOT_FOUND; } AddMessage(RGY_LOG_DEBUG, _T("use video stream #%d for input, codec %s, stream time_base %d/%d, codec_timebase %d/%d.\n"), m_Demux.video.stream->index, char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), m_Demux.video.stream->time_base.num, m_Demux.video.stream->time_base.den, av_stream_get_codec_timebase(m_Demux.video.stream).num, av_stream_get_codec_timebase(m_Demux.video.stream).den); m_logFramePosList.clear(); if (input_prm->logFramePosList.length() > 0) { m_logFramePosList = input_prm->logFramePosList; AddMessage(RGY_LOG_DEBUG, _T("Opened framepos log file: \"%s\"\n"), input_prm->logCopyFrameData.c_str()); } m_Demux.video.hdr10plusMetadataCopy = input_prm->hdr10plusMetadataCopy; AddMessage(RGY_LOG_DEBUG, _T("hdr10plusMetadataCopy: %s\n"), m_Demux.video.hdr10plusMetadataCopy ? _T("on") : _T("off")); m_Demux.video.HWDecodeDeviceId = -1; if (m_inputVideoInfo.type != RGY_INPUT_FMT_AVSW) { for (const auto& devCodecCsp : *input_prm->HWDecCodecCsp) { //VC-1では、pixelFormatがAV_PIX_FMT_NONEとなっている場合があるので、その場合は試しにAV_PIX_FMT_YUV420Pとして処理してみる if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_VC1 && (AVPixelFormat)m_Demux.video.stream->codecpar->format == AV_PIX_FMT_NONE) { AddMessage(RGY_LOG_WARN, _T("pixel format of input file reported as %s, will try decode as %s.\n"), char_to_tstring(av_get_pix_fmt_name(AV_PIX_FMT_NONE)).c_str(), char_to_tstring(av_get_pix_fmt_name((AVPixelFormat)m_Demux.video.stream->codecpar->format)).c_str()); m_Demux.video.stream->codecpar->format = AV_PIX_FMT_YUV420P; } m_inputVideoInfo.codec = checkHWDecoderAvailable( m_Demux.video.stream->codecpar->codec_id, (AVPixelFormat)m_Demux.video.stream->codecpar->format, &devCodecCsp.second); if (m_inputVideoInfo.codec != RGY_CODEC_UNKNOWN) { m_Demux.video.HWDecodeDeviceId = devCodecCsp.first; break; } if (m_inputVideoInfo.type != RGY_INPUT_FMT_AVHW) { break; //RGY_INPUT_FMT_AVANYのときは、HWデコードできなくても優先度の高いGPUを使用する } } if (m_inputVideoInfo.codec == RGY_CODEC_UNKNOWN //wmv3はAdvanced Profile (3)のみの対応 || (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_WMV3 && m_Demux.video.stream->codecpar->profile != 3)) { if (m_inputVideoInfo.type == RGY_INPUT_FMT_AVHW) { //HWデコードが指定されている場合にはエラー終了する AddMessage(RGY_LOG_ERROR, _T("codec %s(%s) unable to decode by " DECODER_NAME ".\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), char_to_tstring(av_get_pix_fmt_name((AVPixelFormat)m_Demux.video.stream->codecpar->format)).c_str()); return RGY_ERR_INVALID_CODEC; } } else { AddMessage(RGY_LOG_DEBUG, _T("can be decoded by %s.\n"), _T(DECODER_NAME)); } } m_readerName = (m_Demux.video.HWDecodeDeviceId >= 0) ? _T("av" DECODER_NAME) : _T("avsw"); m_inputVideoInfo.type = (m_Demux.video.HWDecodeDeviceId >= 0) ? RGY_INPUT_FMT_AVHW : RGY_INPUT_FMT_AVSW; //念のため初期化 m_trimParam.list.clear(); m_trimParam.offset = 0; //必要ならbitstream filterを初期化 if ((m_inputVideoInfo.codec != RGY_CODEC_UNKNOWN || m_Demux.video.hdr10plusMetadataCopy) && m_Demux.video.stream->codecpar->extradata && m_Demux.video.stream->codecpar->extradata[0] == 1) { RGY_ERR sts = initVideoBsfs(); if (sts != RGY_ERR_NONE) { AddMessage(RGY_LOG_ERROR, _T("failed to init bsfs.\n")); return sts; } //HWデコードする場合には、ヘッダーが必要 } else if (m_Demux.video.HWDecodeDeviceId >= 0 && (m_inputVideoInfo.codec != RGY_CODEC_VP8 && m_inputVideoInfo.codec != RGY_CODEC_VP9) && m_Demux.video.stream->codecpar->extradata == nullptr && m_Demux.video.stream->codecpar->extradata_size == 0) { AddMessage(RGY_LOG_ERROR, _T("video header not extracted by libavcodec.\n")); return RGY_ERR_UNKNOWN; } if (m_Demux.video.stream->codecpar->extradata_size) { m_inputVideoInfo.codecExtra = m_Demux.video.stream->codecpar->extradata; m_inputVideoInfo.codecExtraSize = m_Demux.video.stream->codecpar->extradata_size; } AddMessage(RGY_LOG_DEBUG, _T("start predecode.\n")); //ヘッダーの取得を確認する RGY_ERR sts = RGY_ERR_NONE; RGYBitstream bitstream = RGYBitstreamInit(); if (m_Demux.video.stream->codecpar->extradata) { sts = GetHeader(&bitstream); if (sts != RGY_ERR_NONE) { //bsfsがオンであるために失敗した可能性がある //一部のHEVCファイルでは、codecpar->extradataにヘッダの一部(たとえばextradata_size=23)しか //格納されていないため、正常にヘッダの取得が行えない。 //またこのため、bsfs(HEVCmp42AnnexB)やparserが正常に動作しない。 //一方、swデコーダではbsfsは不要であることから、とりあえずそちらに切り替えてしまって動作させることにした if (sts == RGY_ERR_MORE_DATA && (m_Demux.video.bsfcCtx || m_Demux.video.bUseHEVCmp42AnnexB) && !m_Demux.video.hdr10plusMetadataCopy) { AddMessage(RGY_LOG_WARN, _T("Failed to get header for hardware decoder, switching to software decoder...\n")); m_inputVideoInfo.codec = RGY_CODEC_UNKNOWN; //hwデコードをオフにする m_Demux.video.HWDecodeDeviceId = -1; //close bitstreamfilter if (m_Demux.video.bsfcCtx) { AddMessage(RGY_LOG_DEBUG, _T("Free bsf...\n")); av_bsf_free(&m_Demux.video.bsfcCtx); AddMessage(RGY_LOG_DEBUG, _T("Freed bsf.\n")); } //bUseHEVCmp42AnnexBも無効化 m_Demux.video.bUseHEVCmp42AnnexB = false; if (m_Demux.video.stream->codecpar->extradata_size) { m_inputVideoInfo.codecExtra = m_Demux.video.stream->codecpar->extradata; m_inputVideoInfo.codecExtraSize = m_Demux.video.stream->codecpar->extradata_size; } sts = GetHeader(&bitstream); } if (sts != RGY_ERR_NONE) { AddMessage(RGY_LOG_ERROR, _T("failed to get header.\n")); return sts; } } m_inputVideoInfo.codecExtra = m_Demux.video.extradata; m_inputVideoInfo.codecExtraSize = m_Demux.video.extradataSize; } if (input_prm->seekSec > 0.0f) { AVPacket firstpkt; if (getSample(&firstpkt)) { //現在のtimestampを取得する AddMessage(RGY_LOG_ERROR, _T("Failed to get firstpkt of video!\n")); return RGY_ERR_UNKNOWN; } const auto seek_time = av_rescale_q(1, av_d2q((double)input_prm->seekSec, 1<<24), m_Demux.video.stream->time_base); int seek_ret = av_seek_frame(m_Demux.format.formatCtx, m_Demux.video.index, firstpkt.pts + seek_time, 0); if (0 > seek_ret) { seek_ret = av_seek_frame(m_Demux.format.formatCtx, m_Demux.video.index, firstpkt.pts + seek_time, AVSEEK_FLAG_ANY); } av_packet_unref(&firstpkt); if (0 > seek_ret) { AddMessage(RGY_LOG_ERROR, _T("failed to seek %s.\n"), print_time(input_prm->seekSec).c_str()); return RGY_ERR_UNKNOWN; } //seekのために行ったgetSampleの結果は破棄する m_Demux.frames.clear(); } //parserはseek後に初期化すること //parserが使用されていれば、ここでも使用するようにする //たとえば、入力がrawcodecなどでは使用しない sts = initVideoParser(); if (sts != RGY_ERR_MORE_DATA && sts != RGY_ERR_NONE) { return sts; } #if _DEBUG if (input_prm->logCopyFrameData.length() > 0) { if (m_Demux.frames.setLogCopyFrameData(input_prm->logCopyFrameData.c_str())) { AddMessage(RGY_LOG_WARN, _T("failed to open copy-framedata log file: \"%s\"\n"), input_prm->logCopyFrameData.c_str()); } else { AddMessage(RGY_LOG_DEBUG, _T("Opened copy-framedata log file: \"%s\"\n"), input_prm->logCopyFrameData.c_str()); } } #endif if (RGY_ERR_NONE != (sts = getFirstFramePosAndFrameRate(input_prm->pTrimList, input_prm->nTrimCount, input_prm->videoDetectPulldown, input_prm->lowLatency, input_prm->videoAvgFramerate))) { AddMessage(RGY_LOG_ERROR, _T("failed to get first frame position.\n")); return sts; } if (m_cap2ass.enabled()) { m_cap2ass.setVidFirstKeyPts(m_Demux.video.streamFirstKeyPts); } m_trimParam.list = make_vector(input_prm->pTrimList, input_prm->nTrimCount); //キーフレームに到達するまでQSVではフレームが出てこない //そのぶんのずれを記録しておき、Trim値などに補正をかける if (m_trimParam.offset) { for (int i = (int)m_trimParam.list.size() - 1; i >= 0; i--) { if (m_trimParam.list[i].fin - m_trimParam.offset < 0) { m_trimParam.list.erase(m_trimParam.list.begin() + i); } else { m_trimParam.list[i].start = (std::max)(0, m_trimParam.list[i].start - m_trimParam.offset); if (m_trimParam.list[i].fin != TRIM_MAX) { m_trimParam.list[i].fin = (std::max)(0, m_trimParam.list[i].fin - m_trimParam.offset); } } } //ずれが存在し、範囲指定がない場合はダミーの全域指定を追加する //これにより、自動的に音声側との同期がとれるようになる if (m_trimParam.list.size() == 0) { m_trimParam.list.push_back({ 0, TRIM_MAX }); } AddMessage(RGY_LOG_DEBUG, _T("adjust trim by offset %d.\n"), m_trimParam.offset); } struct pixfmtInfo { AVPixelFormat pix_fmt; int bit_depth; RGY_CHROMAFMT chroma_format; RGY_CSP output_csp; }; static const pixfmtInfo pixfmtDataList[] = { { AV_PIX_FMT_YUV420P, 8, RGY_CHROMAFMT_YUV420, RGY_CSP_NV12 }, { AV_PIX_FMT_YUVJ420P, 8, RGY_CHROMAFMT_YUV420, RGY_CSP_NV12 }, { AV_PIX_FMT_NV12, 8, RGY_CHROMAFMT_YUV420, RGY_CSP_NV12 }, { AV_PIX_FMT_NV21, 8, RGY_CHROMAFMT_YUV420, RGY_CSP_NV12 }, { AV_PIX_FMT_YUVJ422P, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NA }, { AV_PIX_FMT_YUYV422, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_YUY2 }, { AV_PIX_FMT_UYVY422, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NA }, #if ENCODER_QSV || ENCODER_VCEENC { AV_PIX_FMT_YUV422P, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NV12 }, { AV_PIX_FMT_NV16, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NV12 }, #else { AV_PIX_FMT_YUV422P, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NV16 }, { AV_PIX_FMT_NV16, 8, RGY_CHROMAFMT_YUV422, RGY_CSP_NV16 }, #endif { AV_PIX_FMT_YUV444P, 8, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444 }, { AV_PIX_FMT_YUVJ444P, 8, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444 }, { AV_PIX_FMT_YUV420P16LE, 16, RGY_CHROMAFMT_YUV420, RGY_CSP_P010 }, { AV_PIX_FMT_YUV420P14LE, 14, RGY_CHROMAFMT_YUV420, RGY_CSP_P010 }, { AV_PIX_FMT_YUV420P12LE, 12, RGY_CHROMAFMT_YUV420, RGY_CSP_P010 }, { AV_PIX_FMT_YUV420P10LE, 10, RGY_CHROMAFMT_YUV420, RGY_CSP_P010 }, { AV_PIX_FMT_YUV420P9LE, 9, RGY_CHROMAFMT_YUV420, RGY_CSP_P010 }, { AV_PIX_FMT_NV20LE, 10, RGY_CHROMAFMT_YUV420, RGY_CSP_NA }, #if ENCODER_QSV || ENCODER_VCEENC { AV_PIX_FMT_YUV422P16LE, 16, RGY_CHROMAFMT_YUV422, RGY_CSP_P010 }, { AV_PIX_FMT_YUV422P14LE, 14, RGY_CHROMAFMT_YUV422, RGY_CSP_P010 }, { AV_PIX_FMT_YUV422P12LE, 12, RGY_CHROMAFMT_YUV422, RGY_CSP_P010 }, { AV_PIX_FMT_YUV422P10LE, 10, RGY_CHROMAFMT_YUV422, RGY_CSP_P010 }, #else { AV_PIX_FMT_YUV422P16LE, 16, RGY_CHROMAFMT_YUV422, RGY_CSP_P210 }, { AV_PIX_FMT_YUV422P14LE, 14, RGY_CHROMAFMT_YUV422, RGY_CSP_P210 }, { AV_PIX_FMT_YUV422P12LE, 12, RGY_CHROMAFMT_YUV422, RGY_CSP_P210 }, { AV_PIX_FMT_YUV422P10LE, 10, RGY_CHROMAFMT_YUV422, RGY_CSP_P210 }, #endif { AV_PIX_FMT_YUV444P16LE, 16, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444_16 }, { AV_PIX_FMT_YUV444P14LE, 14, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444_16 }, { AV_PIX_FMT_YUV444P12LE, 12, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444_16 }, { AV_PIX_FMT_YUV444P10LE, 10, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444_16 }, { AV_PIX_FMT_YUV444P9LE, 9, RGY_CHROMAFMT_YUV444, RGY_CSP_YUV444_16 }, { AV_PIX_FMT_RGB24, 8, RGY_CHROMAFMT_RGB_PACKED, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, { AV_PIX_FMT_BGR24, 8, RGY_CHROMAFMT_RGB_PACKED, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, { AV_PIX_FMT_RGBA, 8, RGY_CHROMAFMT_RGB_PACKED, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, { AV_PIX_FMT_BGRA, 8, RGY_CHROMAFMT_RGB_PACKED, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, { AV_PIX_FMT_GBRP, 8, RGY_CHROMAFMT_RGB, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, { AV_PIX_FMT_GBRAP, 8, RGY_CHROMAFMT_RGB, (ENCODER_NVENC) ? RGY_CSP_RGB : RGY_CSP_RGB32 }, }; const auto pixfmt = (AVPixelFormat)m_Demux.video.stream->codecpar->format; const auto pixfmtData = std::find_if(pixfmtDataList, pixfmtDataList + _countof(pixfmtDataList), [pixfmt](const pixfmtInfo& tableData) { return tableData.pix_fmt == pixfmt; }); if (pixfmtData == (pixfmtDataList + _countof(pixfmtDataList)) || pixfmtData->output_csp == RGY_CSP_NA) { AddMessage(RGY_LOG_ERROR, _T("Invalid pixel format \"%s\" from input file.\n"), char_to_tstring(av_get_pix_fmt_name(pixfmt)).c_str()); return RGY_ERR_INVALID_COLOR_FORMAT; } const auto aspectRatio = m_Demux.video.stream->codecpar->sample_aspect_ratio; const bool bAspectRatioUnknown = aspectRatio.num * aspectRatio.den <= 0; if (!(m_Demux.video.HWDecodeDeviceId >= 0)) { if (nullptr == (m_Demux.video.codecDecode = avcodec_find_decoder(m_Demux.video.stream->codecpar->codec_id))) { AddMessage(RGY_LOG_ERROR, errorMesForCodec(_T("Failed to find decoder"), m_Demux.video.stream->codecpar->codec_id).c_str()); return RGY_ERR_NOT_FOUND; } if (nullptr == (m_Demux.video.codecCtxDecode = avcodec_alloc_context3(m_Demux.video.codecDecode))) { AddMessage(RGY_LOG_ERROR, errorMesForCodec(_T("Failed to allocate decoder"), m_Demux.video.stream->codecpar->codec_id).c_str()); return RGY_ERR_NULL_PTR; } unique_ptr_custom<AVCodecParameters> codecParamCopy(avcodec_parameters_alloc(), [](AVCodecParameters *pCodecPar) { avcodec_parameters_free(&pCodecPar); }); int ret = 0; if (0 > (ret = avcodec_parameters_copy(codecParamCopy.get(), m_Demux.video.stream->codecpar))) { AddMessage(RGY_LOG_ERROR, _T("failed to copy codec param to context for parser: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } if (m_Demux.video.bsfcCtx || m_Demux.video.bUseHEVCmp42AnnexB) { SetExtraData(codecParamCopy.get(), m_Demux.video.extradata, m_Demux.video.extradataSize); } if (0 > (ret = avcodec_parameters_to_context(m_Demux.video.codecCtxDecode, codecParamCopy.get()))) { AddMessage(RGY_LOG_ERROR, _T("failed to set codec param to context for decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } cpu_info_t cpu_info; if (get_cpu_info(&cpu_info)) { AVDictionary *pDict = nullptr; av_dict_set_int(&pDict, "threads", std::min(cpu_info.logical_cores, 16u), 0); if (0 > (ret = av_opt_set_dict(m_Demux.video.codecCtxDecode, &pDict))) { AddMessage(RGY_LOG_ERROR, _T("Failed to set threads for decode (codec: %s): %s\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNKNOWN; } av_dict_free(&pDict); } m_Demux.video.codecCtxDecode->time_base = av_stream_get_codec_timebase(m_Demux.video.stream); m_Demux.video.codecCtxDecode->pkt_timebase = m_Demux.video.stream->time_base; if (0 > (ret = avcodec_open2(m_Demux.video.codecCtxDecode, m_Demux.video.codecDecode, nullptr))) { AddMessage(RGY_LOG_ERROR, _T("Failed to open decoder for %s: %s\n"), char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id)).c_str(), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNSUPPORTED; } const auto pixCspConv = csp_avpixfmt_to_rgy(m_Demux.video.codecCtxDecode->pix_fmt); if (pixCspConv == RGY_CSP_NA) { AddMessage(RGY_LOG_ERROR, _T("invalid color format: %s\n"), char_to_tstring(av_get_pix_fmt_name(m_Demux.video.codecCtxDecode->pix_fmt)).c_str()); return RGY_ERR_INVALID_COLOR_FORMAT; } m_inputCsp = pixCspConv; //出力フォーマットへの直接変換を持たないものは、pixfmtDataListに従う const auto prefered_csp = m_inputVideoInfo.csp; if (prefered_csp == RGY_CSP_NA) { //ロスレスの場合は、入力側で出力フォーマットを決める m_inputVideoInfo.csp = pixfmtData->output_csp; } else { m_inputVideoInfo.csp = (m_convert->getFunc(m_inputCsp, prefered_csp, false, prm->simdCsp) != nullptr) ? prefered_csp : pixfmtData->output_csp; //QSVではNV16->P010がサポートされていない if (ENCODER_QSV && m_inputVideoInfo.csp == RGY_CSP_NV16 && prefered_csp == RGY_CSP_P010) { m_inputVideoInfo.csp = RGY_CSP_P210; } //なるべく軽いフォーマットでGPUに転送するように if (ENCODER_NVENC && RGY_CSP_BIT_PER_PIXEL[pixfmtData->output_csp] < RGY_CSP_BIT_PER_PIXEL[prefered_csp] && m_convert->getFunc(m_inputCsp, pixfmtData->output_csp, false, prm->simdCsp) != nullptr) { m_inputVideoInfo.csp = pixfmtData->output_csp; } } if (m_convert->getFunc(m_inputCsp, m_inputVideoInfo.csp, false, prm->simdCsp) == nullptr && m_inputCsp == RGY_CSP_YUY2) { //YUY2用の特別処理 m_inputVideoInfo.csp = RGY_CSP_CHROMA_FORMAT[pixfmtData->output_csp] == RGY_CHROMAFMT_YUV420 ? RGY_CSP_NV12 : RGY_CSP_YUV444; m_convert->getFunc(m_inputCsp, m_inputVideoInfo.csp, false, prm->simdCsp); } if (m_convert->getFunc() == nullptr) { AddMessage(RGY_LOG_ERROR, _T("color conversion not supported: %s -> %s.\n"), RGY_CSP_NAMES[pixCspConv], RGY_CSP_NAMES[m_inputVideoInfo.csp]); return RGY_ERR_INVALID_COLOR_FORMAT; } m_inputVideoInfo.bitdepth = RGY_CSP_BIT_DEPTH[m_inputVideoInfo.csp]; if (cspShiftUsed(m_inputVideoInfo.csp) && RGY_CSP_BIT_DEPTH[m_inputVideoInfo.csp] > RGY_CSP_BIT_DEPTH[m_inputCsp]) { m_inputVideoInfo.bitdepth = RGY_CSP_BIT_DEPTH[m_inputCsp]; } if (nullptr == (m_Demux.video.frame = av_frame_alloc())) { AddMessage(RGY_LOG_ERROR, _T("Failed to allocate frame for decoder.\n")); return RGY_ERR_NULL_PTR; } m_Demux.video.qpTableListRef = input_prm->qpTableListRef; } else { //HWデコードの場合は、色変換がかからないので、入力フォーマットがそのまま出力フォーマットとなる m_inputVideoInfo.csp = pixfmtData->output_csp; m_inputVideoInfo.bitdepth = pixfmtData->bit_depth; } m_Demux.format.AVSyncMode = input_prm->AVSyncMode; if (input_prm->parseHDRmetadata) { auto err = parseHDRData(); if (err != RGY_ERR_NONE) { AddMessage(RGY_LOG_ERROR, _T("Failed to parse HDR metadata header from input.\n")); return err; } } //情報を格納 m_inputVideoInfo.srcWidth = m_Demux.video.stream->codecpar->width; m_inputVideoInfo.srcHeight = m_Demux.video.stream->codecpar->height; m_inputVideoInfo.sar[0] = (bAspectRatioUnknown) ? 0 : m_Demux.video.stream->codecpar->sample_aspect_ratio.num; m_inputVideoInfo.sar[1] = (bAspectRatioUnknown) ? 0 : m_Demux.video.stream->codecpar->sample_aspect_ratio.den; m_inputVideoInfo.picstruct = (input_prm->interlaceAutoFrame) ? RGY_PICSTRUCT_AUTO : m_Demux.frames.getVideoPicStruct(); m_inputVideoInfo.frames = 0; //getFirstFramePosAndFrameRateをもとにfpsを決定 m_inputVideoInfo.fpsN = m_Demux.video.nAvgFramerate.num; m_inputVideoInfo.fpsD = m_Demux.video.nAvgFramerate.den; m_inputVideoInfo.vui.chromaloc = (CspChromaloc)m_Demux.video.stream->codecpar->chroma_location; m_inputVideoInfo.vui.matrix = (CspMatrix)m_Demux.video.stream->codecpar->color_space; m_inputVideoInfo.vui.colorprim = (CspColorprim)m_Demux.video.stream->codecpar->color_primaries; m_inputVideoInfo.vui.transfer = (CspTransfer)m_Demux.video.stream->codecpar->color_trc; m_inputVideoInfo.vui.colorrange = (CspColorRange)m_Demux.video.stream->codecpar->color_range; m_inputVideoInfo.vui.descriptpresent = 1; if (m_Demux.video.HWDecodeDeviceId >= 0) { tstring mes = strsprintf(_T("av" DECODER_NAME ": %s, %dx%d, %d/%d fps"), CodecToStr(m_inputVideoInfo.codec).c_str(), m_inputVideoInfo.srcWidth, m_inputVideoInfo.srcHeight, m_inputVideoInfo.fpsN, m_inputVideoInfo.fpsD); if (input_prm->seekSec > 0.0f) { mes += strsprintf(_T("\n seek: %s"), print_time(input_prm->seekSec).c_str()); } AddMessage(RGY_LOG_DEBUG, mes); m_inputInfo += mes; } else { CreateInputInfo((tstring(_T("avsw: ")) + char_to_tstring(avcodec_get_name(m_Demux.video.stream->codecpar->codec_id))).c_str(), RGY_CSP_NAMES[m_convert->getFunc()->csp_from], RGY_CSP_NAMES[m_convert->getFunc()->csp_to], get_simd_str(m_convert->getFunc()->simd), &m_inputVideoInfo); if (input_prm->seekSec > 0.0f) { m_inputInfo += strsprintf(_T("\n seek: %s"), print_time(input_prm->seekSec).c_str()); } AddMessage(RGY_LOG_DEBUG, m_inputInfo); } if (m_Demux.video.stream) { AddMessage(RGY_LOG_DEBUG, _T("streamFirstKeyPts: %lld\n"), (long long int)m_Demux.video.streamFirstKeyPts); AddMessage(RGY_LOG_DEBUG, m_inputVideoInfo.vui.print_all()); AddMessage(RGY_LOG_DEBUG, _T("sar %d:%d, bitdepth %d\n"), m_inputVideoInfo.sar[0], m_inputVideoInfo.sar[1], m_inputVideoInfo.bitdepth); } *inputInfo = m_inputVideoInfo; //スレッド関連初期化 m_Demux.thread.bAbortInput = false; #if 1 auto nPrmInputThread = input_prm->threadInput; m_Demux.thread.threadInput = ((nPrmInputThread == RGY_INPUT_THREAD_AUTO) | (m_Demux.video.stream != nullptr)) ? 0 : nPrmInputThread; #else //NVEncではいまのところ、常に無効 m_Demux.thread.threadInput = 0; #endif if (m_Demux.thread.threadInput) { m_Demux.thread.thInput = std::thread(&RGYInputAvcodec::ThreadFuncRead, this); //はじめcapacityを無限大にセットしたので、この段階で制限をかける //入力をスレッド化しない場合には、自動的に同期が保たれるので、ここでの制限は必要ない m_Demux.qVideoPkt.set_capacity(256); } } else { //音声との同期とかに使うので、動画の情報を格納する m_Demux.video.nAvgFramerate = av_make_q(input_prm->videoAvgFramerate); if (input_prm->nTrimCount) { m_trimParam.list = vector<sTrim>(input_prm->pTrimList, input_prm->pTrimList + input_prm->nTrimCount); } if (m_Demux.video.stream) { //動画の最初のフレームを取得しておく AVPacket pkt; av_init_packet(&pkt); //音声のみ処理モードでは、動画の先頭をキーフレームとする必要はなく、 //先頭がキーフレームでなくてもframePosListに追加するようにして、trimをoffsetなしで反映できるようにする //そこで、bTreatFirstPacketAsKeyframe=trueにして最初のパケットを処理する if (getSample(&pkt, true)) { AddMessage(RGY_LOG_ERROR, _T("Failed to get first packet of the video!\n")); return RGY_ERR_UNKNOWN; } av_packet_unref(&pkt); m_Demux.frames.checkPtsStatus(); } tstring mes; for (const auto& stream : m_Demux.stream) { if (mes.length()) mes += _T(", "); tstring codec_name = char_to_tstring(avcodec_get_name(stream.stream->codecpar->codec_id)); mes += codec_name; AddMessage(RGY_LOG_DEBUG, _T("avcodec %s: %s from %s\n"), get_media_type_string(stream.stream->codecpar->codec_id).c_str(), codec_name.c_str(), strFileName); } m_inputInfo += _T("avcodec audio: ") + mes; } return RGY_ERR_NONE; } #pragma warning(pop) vector<const AVStream *> RGYInputAvcodec::GetInputAttachmentStreams() { vector<const AVStream *> streams; if (m_Demux.format.formatCtx) { for (unsigned int ist = 0; ist < m_Demux.format.formatCtx->nb_streams; ist++) { const AVStream *stream = m_Demux.format.formatCtx->streams[ist]; if (stream->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) { streams.push_back(stream); } } } return streams; } vector<const AVChapter *> RGYInputAvcodec::GetChapterList() { return m_Demux.chapter; } int RGYInputAvcodec::GetSubtitleTrackCount() { return m_Demux.format.subtitleTracks; } int RGYInputAvcodec::GetDataTrackCount() { return m_Demux.format.dataTracks; } int RGYInputAvcodec::GetAudioTrackCount() { return m_Demux.format.audioTracks; } int64_t RGYInputAvcodec::GetVideoFirstKeyPts() { return m_Demux.video.streamFirstKeyPts; } FramePosList *RGYInputAvcodec::GetFramePosList() { return &m_Demux.frames; } int RGYInputAvcodec::getVideoFrameIdx(int64_t pts, AVRational timebase, int iStart) { const int framePosCount = m_Demux.frames.frameNum(); const AVRational vid_pkt_timebase = (m_Demux.video.stream) ? m_Demux.video.stream->time_base : av_inv_q(m_Demux.video.nAvgFramerate); if (av_cmp_q(timebase, vid_pkt_timebase) == 0) { for (int i = (std::max)(0, iStart); i < framePosCount; i++) { if (pts == m_Demux.frames.list(i).pts) { return i; } //pts < demux.videoFramePts[i]であるなら、その前のフレームを返す if (pts < m_Demux.frames.list(i).pts) { //0フレーム目なら、仮想的に -1 フレーム目を考えて、それよりも前かどうかを判定する //-2を返すことで、そのパケットは削除される if (i == 0 && pts < m_Demux.frames.list(i).pts - m_Demux.frames.list(i).duration) { i--; } return i-1; } } } else { for (int i = (std::max)(0, iStart); i < framePosCount; i++) { //pts < demux.videoFramePts[i]であるなら、その前のフレームを返す if (av_compare_ts(pts, timebase, m_Demux.frames.list(i).pts, vid_pkt_timebase) < 0) { //0フレーム目なら、仮想的に -1 フレーム目を考えて、それよりも前かどうかを判定する //-2を返すことで、そのパケットは削除される if (i == 0 && av_compare_ts(pts, timebase, m_Demux.frames.list(i).pts - m_Demux.frames.list(i).duration, vid_pkt_timebase) < 0) { i--; } return i-1; } } } return framePosCount; } int64_t RGYInputAvcodec::convertTimebaseVidToStream(int64_t pts, const AVDemuxStream *stream) { const AVRational vid_pkt_timebase = (m_Demux.video.stream) ? m_Demux.video.stream->time_base : av_inv_q(m_Demux.video.nAvgFramerate); return av_rescale_q(pts, vid_pkt_timebase, stream->timebase); } bool RGYInputAvcodec::checkStreamPacketToAdd(AVPacket *pkt, AVDemuxStream *stream) { // EPGやbin_dataなど、data streamでtimestampがついていない // 一度もtimestampが設定されていない場合でもそれはすべて転送する if (stream->aud0_fin == AV_NOPTS_VALUE //一度もtimestampが設定されていない && pkt->pts == AV_NOPTS_VALUE //timestampが設定されていない && avcodec_get_type(stream->stream->codecpar->codec_id) == AVMEDIA_TYPE_DATA // data stream ) { return true; } if (pkt->pts != AV_NOPTS_VALUE) { //pkt->ptsがAV_NOPTS_VALUEの場合は、以前のフレームの継続とみなして更新しない stream->lastVidIndex = getVideoFrameIdx(pkt->pts, stream->timebase, stream->lastVidIndex); } //該当フレームが-1フレーム未満なら、その音声はこの動画には含まれない if (stream->lastVidIndex < -1) { return false; } //映像がないなら判定しない if (!m_Demux.video.stream) { return true; } const auto vidFramePos = &m_Demux.frames.list((std::max)(stream->lastVidIndex, 0)); const int64_t vid1_fin = convertTimebaseVidToStream(vidFramePos->pts + ((stream->lastVidIndex >= 0) ? vidFramePos->duration : 0), stream); const int64_t vid2_start = convertTimebaseVidToStream(m_Demux.frames.list((std::max)(stream->lastVidIndex+1, 0)).pts, stream); int64_t aud1_start = pkt->pts; int64_t aud1_fin = pkt->pts + pkt->duration; //block index (空白がtrimで削除された領域) // #0 #0 #1 #1 #2 #2 // | |----------| |----------| |------ const auto frame_is_in_range = frame_inside_range(stream->lastVidIndex, m_trimParam.list); const auto next_is_in_range = frame_inside_range(stream->lastVidIndex + 1, m_trimParam.list); const auto frame_trim_block_index = frame_is_in_range.second; const auto next_trim_block_index = next_is_in_range.second; bool result = true; //動画に含まれる音声かどうか if (frame_is_in_range.first) { if (aud1_fin < vid1_fin || next_is_in_range.first) { ; //完全に動画フレームの範囲内か、次のフレームも範囲内なら、その音声パケットは含まれる // vid1_fin //動画 <-----------| //音声 |-----------| // aud1_start aud1_fin } else if (pkt->duration / 2 > (aud1_fin - vid1_fin + stream->extractErrExcess)) { //はみ出した領域が少ないなら、その音声パケットは含まれる if (stream->stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { //字幕の場合は表示時間を調整する pkt->duration -= vid1_fin - aud1_fin; aud1_fin = vid1_fin; } else { stream->extractErrExcess += aud1_fin - vid1_fin; } } else { //はみ出した領域が多いなら、その音声パケットは含まれない stream->extractErrExcess -= vid1_fin - aud1_start; result = false; } } else if (next_is_in_range.first && aud1_fin > vid2_start) { // vid2_start //動画 |------------> //音声 |-----------| // aud1_start aud1_fin if (pkt->duration / 2 > (vid2_start - aud1_start + stream->extractErrExcess)) { if (stream->stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { //字幕の場合は表示時間を調整する pkt->pts += vid2_start - aud1_start; pkt->duration -= vid2_start - aud1_start; aud1_start = vid2_start; } else { stream->extractErrExcess += vid2_start - aud1_start; } } else { stream->extractErrExcess -= aud1_fin - vid2_start; result = false; } } else { result = false; } if (result) { if (stream->appliedTrimBlock < frame_trim_block_index) { stream->appliedTrimBlock = frame_trim_block_index; if (stream->aud0_fin == AV_NOPTS_VALUE) { //まだ一度も音声のパケットが渡されていない //基本的には動画の情報を基準に情報を修正する const int first_vid_frame = (m_trimParam.list.size() > 0) ? m_trimParam.list[0].start : 0; const int64_t vid0_start = convertTimebaseVidToStream(m_Demux.frames.list(first_vid_frame).pts, stream); stream->trimOffset += std::min(aud1_start, vid0_start) - m_Demux.video.streamFirstKeyPts; } else { assert(frame_trim_block_index > 0); const int last_valid_vid_frame = m_trimParam.list[frame_trim_block_index-1].start; assert(last_valid_vid_frame >= 0); const int64_t vid0_fin = convertTimebaseVidToStream(m_Demux.frames.list(last_valid_vid_frame).pts, stream); const int64_t vid1_start = convertTimebaseVidToStream(vidFramePos->pts, stream); const int64_t vid_start = (frame_is_in_range.first) ? vid1_start : vid2_start; if (vid_start - vid0_fin > aud1_start - stream->aud0_fin) { stream->trimOffset += aud1_start - stream->aud0_fin; } else { stream->trimOffset += vid_start - vid0_fin - stream->extractErrExcess; stream->extractErrExcess = 0; } } } stream->aud0_fin = aud1_fin; //最終的に時刻を補正 pkt->pts -= stream->trimOffset; pkt->dts -= stream->trimOffset; } return result; } AVDemuxStream *RGYInputAvcodec::getPacketStreamData(const AVPacket *pkt) { int streamIndex = pkt->stream_index; for (int i = 0; i < (int)m_Demux.stream.size(); i++) { if (m_Demux.stream[i].index == streamIndex) { return &m_Demux.stream[i]; } } return nullptr; } int RGYInputAvcodec::getSample(AVPacket *pkt, bool bTreatFirstPacketAsKeyframe) { av_init_packet(pkt); int i_samples = 0; int ret_read_frame = 0; while ((ret_read_frame = av_read_frame(m_Demux.format.formatCtx, pkt)) >= 0 //trimからわかるフレーム数の上限値よりfixedNumがある程度の量の処理を進めたら読み込みを打ち切る && m_Demux.frames.fixedNum() - TRIM_OVERREAD_FRAMES < getVideoTrimMaxFramIdx()) { if (m_fpPacketList) { fprintf(m_fpPacketList.get(), "stream %2d, %12s, pts, %s\n", pkt->stream_index, avcodec_get_name(m_Demux.format.formatCtx->streams[pkt->stream_index]->codecpar->codec_id), pkt->pts == AV_NOPTS_VALUE ? "Unknown" : strsprintf("%lld", pkt->pts).c_str()); } if (pkt->stream_index == m_Demux.video.index) { if (pkt->flags & AV_PKT_FLAG_CORRUPT) { const auto timestamp = (pkt->pts == AV_NOPTS_VALUE) ? pkt->dts : pkt->pts; AddMessage(RGY_LOG_WARN, _T("corrupt packet in video: %lld (%s)\n"), (long long int)timestamp, getTimestampString(timestamp, m_Demux.video.stream->time_base).c_str()); } if (m_Demux.video.bsfcCtx) { auto ret = av_bsf_send_packet(m_Demux.video.bsfcCtx, pkt); if (ret < 0) { av_packet_unref(pkt); AddMessage(RGY_LOG_ERROR, _T("failed to send packet to %s bitstream filter: %s.\n"), char_to_tstring(m_Demux.video.bsfcCtx->filter->name).c_str(), qsv_av_err2str(ret).c_str()); return 1; } ret = av_bsf_receive_packet(m_Demux.video.bsfcCtx, pkt); if (ret == AVERROR(EAGAIN)) { continue; //もっとpacketを送らないとダメ } else if (ret < 0 && ret != AVERROR_EOF) { AddMessage(RGY_LOG_ERROR, _T("failed to run %s bitstream filter: %s.\n"), char_to_tstring(m_Demux.video.bsfcCtx->filter->name).c_str(), qsv_av_err2str(ret).c_str()); return 1; } } if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_VC1) { vc1AddFrameHeader(pkt); } if (m_Demux.video.bUseHEVCmp42AnnexB) { hevcMp42Annexb(pkt); } if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_HEVC && m_Demux.video.hdr10plusMetadataCopy) { parseHDR10plus(pkt); } FramePos pos = { 0 }; pos.pts = pkt->pts; pos.dts = pkt->dts; pos.duration = (int)pkt->duration; pos.duration2 = 0; pos.poc = FRAMEPOS_POC_INVALID; pos.flags = (uint8_t)pkt->flags; pos.pict_type = AV_PICTURE_TYPE_NONE; if (m_Demux.video.pParserCtx) { uint8_t* dummy = nullptr; int dummy_size = 0; av_parser_parse2(m_Demux.video.pParserCtx, m_Demux.video.pCodecCtxParser, &dummy, &dummy_size, pkt->data, pkt->size, pkt->pts, pkt->dts, pkt->pos); pos.pict_type = (uint8_t)(std::max)(m_Demux.video.pParserCtx->pict_type, 0); switch (m_Demux.video.pParserCtx->picture_structure) { //フィールドとして符号化されている case AV_PICTURE_STRUCTURE_TOP_FIELD: pos.pic_struct = RGY_PICSTRUCT_FIELD_TOP; break; case AV_PICTURE_STRUCTURE_BOTTOM_FIELD: pos.pic_struct = RGY_PICSTRUCT_FIELD_BOTTOM; break; //フレームとして符号化されている default: switch (m_Demux.video.pParserCtx->field_order) { case AV_FIELD_TT: case AV_FIELD_TB: pos.pic_struct = RGY_PICSTRUCT_FRAME_TFF; break; case AV_FIELD_BT: case AV_FIELD_BB: pos.pic_struct = RGY_PICSTRUCT_FRAME_BFF; break; default: pos.pic_struct = RGY_PICSTRUCT_FRAME; break; } } pos.repeat_pict = (uint8_t)m_Demux.video.pParserCtx->repeat_pict; } //mkv入りのVC-1をカットしたものなど、動画によってはpkt->flagsにフラグがセットされていないことがある //parserの情報も活用してキーフレームかどうかを判定する const bool keyframe = (pkt->flags & AV_PKT_FLAG_KEY) != 0 || pos.pict_type == AV_PICTURE_TYPE_I; //最初のキーフレームを取得するまではスキップする //スキップした枚数はi_samplesでカウントし、trim時に同期を適切にとるため、m_trimParam.offsetに格納する // ただし、bTreatFirstPacketAsKeyframeが指定されている場合には、キーフレームでなくてもframePosListへの追加を許可する // このモードは、対象の入力ファイルから--audio-sourceなどで音声のみ拾ってくる場合に使用する if (!bTreatFirstPacketAsKeyframe && !m_Demux.video.gotFirstKeyframe && !keyframe) { av_packet_unref(pkt); i_samples++; continue; } else { if (!m_Demux.video.gotFirstKeyframe) { if (pkt->flags & AV_PKT_FLAG_DISCARD) { //timestampが正常に設定されておらず、移乗動作の原因となるので、 //AV_PKT_FLAG_DISCARDがついている最初のフレームは無視する continue; } //ここに入った場合は、必ず最初のキーフレーム m_Demux.video.streamFirstKeyPts = (pkt->pts == AV_NOPTS_VALUE) ? pkt->dts : pkt->pts; if (m_Demux.video.streamFirstKeyPts == AV_NOPTS_VALUE) { if (m_Demux.stream.size() > 0) { AddMessage(RGY_LOG_WARN, _T("first key frame had timestamp AV_NOPTS_VALUE, this might lead to avsync error.\n")); } m_Demux.video.streamFirstKeyPts = 0; } m_Demux.video.gotFirstKeyframe = true; //キーフレームに到達するまでQSVではフレームが出てこない //そのため、getSampleでも最初のキーフレームを取得するまでパケットを出力しない //だが、これが原因でtrimの値とずれを生じてしまう //そこで、そのぶんのずれを記録しておき、Trim値などに補正をかける m_trimParam.offset = i_samples; AddMessage(RGY_LOG_DEBUG, _T("found first key frame: timestamp %lld (%s), offset %d\n"), (long long int)m_Demux.video.streamFirstKeyPts, getTimestampString(m_Demux.video.streamFirstKeyPts, m_Demux.video.stream->time_base).c_str(), m_trimParam.offset); } #if ENCODER_NVENC //NVENCのhwデコーダでは、opengopなどでキーフレームのパケットよりあとにその前のフレームが来た場合、 //フレーム位置がさらにずれるので補正する else if (!(pkt->flags & AV_PKT_FLAG_KEY) && (pkt->pts != AV_NOPTS_VALUE) && (m_Demux.video.streamFirstKeyPts != AV_NOPTS_VALUE) && pkt->pts < m_Demux.video.streamFirstKeyPts && m_Demux.video.HWDecodeDeviceId >= 0) { //trim調整の適用はavhwリーダーのみ m_trimParam.offset++; } #endif //#if ENCODER_NVENC m_Demux.frames.add(pos); } //ptsの確定したところまで、音声を出力する CheckAndMoveStreamPacketList(); return 0; } const auto *stream = getPacketStreamData(pkt); if (stream != nullptr) { if (pkt->flags & AV_PKT_FLAG_CORRUPT) { const auto timestamp = (pkt->pts == AV_NOPTS_VALUE) ? pkt->dts : pkt->pts; AddMessage(RGY_LOG_WARN, _T("corrupt packet in stream %d: %lld (%s)\n"), pkt->stream_index, (long long int)timestamp, getTimestampString(timestamp, stream->stream->time_base).c_str()); } //音声/字幕パケットはひとまずすべてバッファに格納する m_Demux.qStreamPktL1.push_back(*pkt); } else { av_packet_unref(pkt); } } //ファイルの終わりに到達 if (ret_read_frame != AVERROR_EOF && ret_read_frame < 0) { AddMessage(RGY_LOG_ERROR, _T("error occured while reading file: %d frames, %s\n"), m_Demux.frames.frameNum(), qsv_av_err2str(ret_read_frame).c_str()); return 1; } AddMessage(RGY_LOG_DEBUG, _T("%d frames, %s\n"), m_Demux.frames.frameNum(), qsv_av_err2str(ret_read_frame).c_str()); pkt->data = nullptr; pkt->size = 0; //動画の終端を表す最後のptsを挿入する int64_t videoFinPts = 0; const int nFrameNum = m_Demux.frames.frameNum(); if (m_Demux.video.streamPtsInvalid & RGY_PTS_ALL_INVALID) { videoFinPts = nFrameNum * m_Demux.frames.list(0).duration; } else if (nFrameNum) { const FramePos *lastFrame = &m_Demux.frames.list(nFrameNum - 1); videoFinPts = lastFrame->pts + lastFrame->duration; } //もし選択範囲が手動で決定されていないのなら、音声を最大限取得する if (m_trimParam.list.size() == 0 || m_trimParam.list.back().fin == TRIM_MAX) { for (uint32_t i = 0; i < m_Demux.qStreamPktL2.size(); i++) { videoFinPts = (std::max)(videoFinPts, m_Demux.qStreamPktL2[i].data.pts); } for (uint32_t i = 0; i < m_Demux.qStreamPktL1.size(); i++) { videoFinPts = (std::max)(videoFinPts, m_Demux.qStreamPktL1[i].pts); } } //最後のフレーム情報をセットし、m_Demux.framesの内部状態を終了状態に移行する m_Demux.frames.fin(framePos(videoFinPts, videoFinPts, 0), m_Demux.format.formatCtx->duration); //映像キューのサイズ維持制限を解除する → パイプラインに最後まで読み取らせる m_Demux.qVideoPkt.set_keep_length(0); //音声をすべて出力する //m_Demux.frames.finをしたので、ここで実行すれば、qAudioPktL1のデータがすべてqAudioPktL2に移される CheckAndMoveStreamPacketList(); //音声のみ読み込みの場合はm_encSatusInfoはnullptrなので、nullチェックを行う #if !FOR_AUO //auoでここからUpdateDisplay()してしまうと、メインスレッド以外からのGUI更新となり、例外で落ちる if (m_encSatusInfo) { m_encSatusInfo->UpdateDisplay(100.0); } #endif return AVERROR_EOF; } //動画ストリームの1フレーム分のデータをbitstreamに追加する (リーダー側のデータは消す) RGY_ERR RGYInputAvcodec::GetNextBitstream(RGYBitstream *pBitstream) { AVPacket pkt; if (!m_Demux.thread.thInput.joinable() //入力スレッドがなければ、自分で読み込む && m_Demux.qVideoPkt.get_keep_length() > 0) { //keep_length == 0なら読み込みは終了していて、これ以上読み込む必要はない const int ret = getSample(&pkt); if (ret == 0) { m_Demux.qVideoPkt.push(pkt); } else if (ret != AVERROR_EOF) { return RGY_ERR_UNKNOWN; } } bool bGetPacket = false; for (int i = 0; false == (bGetPacket = m_Demux.qVideoPkt.front_copy_and_pop_no_lock(&pkt, (m_Demux.thread.queueInfo) ? &m_Demux.thread.queueInfo->usage_vid_in : nullptr)) && m_Demux.qVideoPkt.size() > 0; i++) { m_Demux.qVideoPkt.wait_for_push(); } RGY_ERR sts = RGY_ERR_MORE_BITSTREAM; if (bGetPacket) { if (pkt.data) { auto pts = (0 == (m_Demux.frames.getStreamPtsStatus() & (~RGY_PTS_NORMAL))) ? pkt.pts : AV_NOPTS_VALUE; sts = pBitstream->copy(pkt.data, pkt.size, pkt.dts, pts); } if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_HEVC && m_Demux.video.hdr10plusMetadataCopy) { pBitstream->addFrameData(getHDR10plusMetaData(&pkt)); } av_packet_unref(&pkt); m_Demux.video.nSampleGetCount++; m_encSatusInfo->m_sData.frameIn++; } return sts; } //動画ストリームの1フレーム分のデータをbitstreamに追加する (リーダー側のデータは残す) RGY_ERR RGYInputAvcodec::GetNextBitstreamNoDelete(RGYBitstream *pBitstream) { AVPacket pkt; if (!m_Demux.thread.thInput.joinable() //入力スレッドがなければ、自分で読み込む && m_Demux.qVideoPkt.get_keep_length() > 0) { //keep_length == 0なら読み込みは終了していて、これ以上読み込む必要はない const int ret = getSample(&pkt); if (ret == 0) { m_Demux.qVideoPkt.push(pkt); } else if (ret != AVERROR_EOF) { return RGY_ERR_UNKNOWN; } } bool bGetPacket = false; for (int i = 0; false == (bGetPacket = m_Demux.qVideoPkt.front_copy_no_lock(&pkt, (m_Demux.thread.queueInfo) ? &m_Demux.thread.queueInfo->usage_vid_in : nullptr)) && m_Demux.qVideoPkt.size() > 0; i++) { m_Demux.qVideoPkt.wait_for_push(); } RGY_ERR sts = RGY_ERR_MORE_BITSTREAM; if (bGetPacket) { if (pkt.data) { auto pts = (0 == (m_Demux.frames.getStreamPtsStatus() & (~RGY_PTS_NORMAL))) ? pkt.pts : AV_NOPTS_VALUE; sts = pBitstream->copy(pkt.data, pkt.size, pkt.dts, pts); } } return sts; } void RGYInputAvcodec::GetAudioDataPacketsWhenNoVideoRead(int inputFrame) { if (m_Demux.video.nSampleGetCount >= inputFrame) { return; } m_Demux.video.nSampleGetCount = inputFrame; const double vidEstDurationSec = inputFrame * (double)m_Demux.video.nAvgFramerate.den / (double)m_Demux.video.nAvgFramerate.num; //1フレームの時間(秒) AVPacket pkt; av_init_packet(&pkt); if (m_Demux.video.stream) { //動画に映像がある場合、getSampleを呼んで1フレーム分の音声データをm_Demux.qStreamPktL1に取得する //同時に映像フレームをロードし、ロードしたptsデータを突っ込む if (!getSample(&pkt)) { //動画データ自体は不要なので解放 av_packet_unref(&pkt); CheckAndMoveStreamPacketList(); } return; } auto move_pkt = [this](double vidEstDurationSec) { while (!m_Demux.qStreamPktL1.empty()) { auto pkt2 = m_Demux.qStreamPktL1.front(); AVDemuxStream *pStream2 = getPacketStreamData(&pkt2); const double pkt2timeSec = pkt2.pts * (double)pStream2->stream->time_base.num / (double)pStream2->stream->time_base.den; if (pkt2timeSec > vidEstDurationSec + 5.0) { break; } pkt2.flags = (pkt2.flags & 0xffff) | ((uint32_t)pStream2->trackId << 16); //flagsの上位16bitには、trackIdへのポインタを格納しておく m_Demux.qStreamPktL2.push(pkt2); //Writer側に渡したパケットはWriter側で開放する m_Demux.qStreamPktL1.pop_front(); } }; //動画に映像がない場合、 //およそ1フレーム分のパケットを取得する while (av_read_frame(m_Demux.format.formatCtx, &pkt) >= 0) { const auto codec_type = m_Demux.format.formatCtx->streams[pkt.stream_index]->codecpar->codec_type; if (codec_type != AVMEDIA_TYPE_AUDIO && codec_type != AVMEDIA_TYPE_SUBTITLE) { av_packet_unref(&pkt); } else { AVDemuxStream *pStream = getPacketStreamData(&pkt); const auto delay_ts = av_rescale_q(pStream->addDelayMs, av_make_q(1, 1000), pStream->timebase); if (pkt.pts == AV_NOPTS_VALUE) pkt.pts += delay_ts; if (pkt.dts == AV_NOPTS_VALUE) pkt.dts += delay_ts; if (checkStreamPacketToAdd(&pkt, pStream)) { m_Demux.qStreamPktL1.push_back(pkt); } else { av_packet_unref(&pkt); //Writer側に渡さないパケットはここで開放する } //最初のパケットは参照用にコピーしておく if (pStream->pktSample.data == nullptr) { av_packet_ref(&pStream->pktSample, &pkt); } auto pktt = (pkt.pts == AV_NOPTS_VALUE) ? pkt.dts : pkt.pts; auto pkt_dist = pktt - pStream->pktSample.pts; //1フレーム分のサンプルを取得したら終了 if (pkt_dist * (double)pStream->stream->time_base.num / (double)pStream->stream->time_base.den > vidEstDurationSec + 2.5) { //およそ1フレーム分のパケットを設定する int64_t pts = inputFrame; m_Demux.frames.add(framePos(pts, pts, 1, 0, inputFrame, AV_PKT_FLAG_KEY)); if (m_Demux.frames.getStreamPtsStatus() == RGY_PTS_UNKNOWN) { m_Demux.frames.checkPtsStatus(); } move_pkt(vidEstDurationSec); return; } } } move_pkt(vidEstDurationSec); if (!m_Demux.frames.isEof()) { //読み込みが終了 int64_t pts = inputFrame; m_Demux.frames.fin(framePos(pts, pts, 1, 0, inputFrame, AV_PKT_FLAG_KEY), inputFrame); } } const AVDictionary *RGYInputAvcodec::GetInputFormatMetadata() { return m_Demux.format.formatCtx->metadata; } const AVStream *RGYInputAvcodec::GetInputVideoStream() { return m_Demux.video.stream; } double RGYInputAvcodec::GetInputVideoDuration() { return (m_Demux.format.formatCtx->duration * (1.0 / (double)AV_TIME_BASE)); } rgy_rational<int> RGYInputAvcodec::getInputTimebase() { return to_rgy(GetInputVideoStream()->time_base); } //qStreamPktL1をチェックし、framePosListから必要な音声パケットかどうかを判定し、 //必要ならqStreamPktL2に移し、不要ならパケットを開放する void RGYInputAvcodec::CheckAndMoveStreamPacketList() { if (m_Demux.frames.fixedNum() == 0) { return; } //出力するパケットを選択する const AVRational vid_pkt_timebase = (m_Demux.video.stream) ? m_Demux.video.stream->time_base : av_inv_q(m_Demux.video.nAvgFramerate); while (!m_Demux.qStreamPktL1.empty()) { auto pkt = m_Demux.qStreamPktL1.front(); AVDemuxStream *pStream = getPacketStreamData(&pkt); const auto delay_ts = av_rescale_q(pStream->addDelayMs, av_make_q(1, 1000), pStream->timebase); //音声のptsが映像の終わりのptsを行きすぎたらやめる const auto fixedLastFrame = m_Demux.frames.list(m_Demux.frames.fixedNum() - 1); if (!m_Demux.frames.isEof() // 最後まで読み込んでいたらすべて転送するようにする && 0 < av_compare_ts(pkt.pts + delay_ts, pStream->timebase, fixedLastFrame.pts, vid_pkt_timebase)) { break; } if (pkt.pts != AV_NOPTS_VALUE) pkt.pts += delay_ts; if (pkt.dts != AV_NOPTS_VALUE) pkt.dts += delay_ts; if (checkStreamPacketToAdd(&pkt, pStream)) { pkt.flags = (pkt.flags & 0xffff) | ((uint32_t)pStream->trackId << 16); //flagsの上位16bitには、trackIdへのポインタを格納しておく m_Demux.qStreamPktL2.push(pkt); //Writer側に渡したパケットはWriter側で開放する } else { av_packet_unref(&pkt); //Writer側に渡さないパケットはここで開放する } m_Demux.qStreamPktL1.pop_front(); } } vector<AVPacket> RGYInputAvcodec::GetStreamDataPackets(int inputFrame) { if (!m_Demux.video.readVideo) { GetAudioDataPacketsWhenNoVideoRead(inputFrame); } //出力するパケットを選択する vector<AVPacket> packets; AVPacket pkt; while (m_Demux.qStreamPktL2.front_copy_and_pop_no_lock(&pkt, (m_Demux.thread.queueInfo) ? &m_Demux.thread.queueInfo->usage_aud_in : nullptr)) { packets.push_back(pkt); } return packets; } vector<AVDemuxStream> RGYInputAvcodec::GetInputStreamInfo() { return vector<AVDemuxStream>(m_Demux.stream.begin(), m_Demux.stream.end()); } RGY_ERR RGYInputAvcodec::GetHeader(RGYBitstream *pBitstream) { if (pBitstream == nullptr) { return RGY_ERR_NULL_PTR; } if (pBitstream->bufptr() == nullptr) { auto sts = pBitstream->init(AVCODEC_READER_INPUT_BUF_SIZE); if (sts != RGY_ERR_NONE) { return sts; } } if (m_Demux.video.extradata == nullptr) { if (m_Demux.video.stream->codecpar->extradata == nullptr || m_Demux.video.stream->codecpar->extradata_size == 0) { pBitstream->clear(); return RGY_ERR_NONE; } m_Demux.video.extradataSize = m_Demux.video.stream->codecpar->extradata_size; //ここでav_mallocを使用しないと正常に動作しない m_Demux.video.extradata = (uint8_t *)av_malloc(m_Demux.video.stream->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); //ヘッダのデータをコピーしておく memcpy(m_Demux.video.extradata, m_Demux.video.stream->codecpar->extradata, m_Demux.video.extradataSize); memset(m_Demux.video.extradata + m_Demux.video.extradataSize, 0, AV_INPUT_BUFFER_PADDING_SIZE); if (m_Demux.video.bUseHEVCmp42AnnexB) { hevcMp42Annexb(nullptr); } else if (m_Demux.video.bsfcCtx && m_Demux.video.extradata[0] == 1) { if (m_Demux.video.extradataSize < m_Demux.video.bsfcCtx->par_out->extradata_size) { m_Demux.video.extradata = (uint8_t *)av_realloc(m_Demux.video.extradata, m_Demux.video.bsfcCtx->par_out->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); } memcpy(m_Demux.video.extradata, m_Demux.video.bsfcCtx->par_out->extradata, m_Demux.video.bsfcCtx->par_out->extradata_size); AddMessage(RGY_LOG_DEBUG, _T("GetHeader: changed %d bytes -> %d bytes by %s.\n"), m_Demux.video.extradataSize, m_Demux.video.bsfcCtx->par_out->extradata_size, char_to_tstring(m_Demux.video.bsfcCtx->filter->name).c_str()); m_Demux.video.extradataSize = m_Demux.video.bsfcCtx->par_out->extradata_size; memset(m_Demux.video.extradata + m_Demux.video.extradataSize, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_VC1) { //int lengthFix = (0 == strcmp(m_Demux.format.formatCtx->iformat->name, "mpegts")) ? 0 : -1; //vc1FixHeader(lengthFix); } AddMessage(RGY_LOG_DEBUG, _T("GetHeader: %d bytes.\n"), m_Demux.video.extradataSize); if (m_Demux.video.extradataSize == 0 && m_Demux.video.extradata != nullptr) { av_free(m_Demux.video.extradata); m_Demux.video.extradata = nullptr; AddMessage(RGY_LOG_DEBUG, _T("Failed to get header: 0 byte.")); return RGY_ERR_MORE_DATA; } //抽出されたextradataが大きすぎる場合、適当に縮める //NVEncのデコーダが受け取れるヘッダは1024byteまで if (m_Demux.video.extradataSize > 1024) { if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_H264) { std::vector<nal_info> nal_list = parse_nal_unit_h264(m_Demux.video.extradata, m_Demux.video.extradataSize); const auto h264_sps_nal = std::find_if(nal_list.begin(), nal_list.end(), [](nal_info info) { return info.type == NALU_H264_SPS; }); const auto h264_pps_nal = std::find_if(nal_list.begin(), nal_list.end(), [](nal_info info) { return info.type == NALU_H264_PPS; }); const bool header_check = (nal_list.end() != h264_sps_nal) && (nal_list.end() != h264_pps_nal); if (header_check) { m_Demux.video.extradataSize = (int)(h264_sps_nal->size + h264_pps_nal->size); uint8_t *new_ptr = (uint8_t *)av_malloc(m_Demux.video.extradataSize + AV_INPUT_BUFFER_PADDING_SIZE); memcpy(new_ptr, h264_sps_nal->ptr, h264_sps_nal->size); memcpy(new_ptr + h264_sps_nal->size, h264_pps_nal->ptr, h264_pps_nal->size); if (m_Demux.video.extradata) { av_free(m_Demux.video.extradata); } m_Demux.video.extradata = new_ptr; } } else if (m_Demux.video.stream->codecpar->codec_id == AV_CODEC_ID_HEVC) { std::vector<nal_info> nal_list = parse_nal_unit_hevc(m_Demux.video.extradata, m_Demux.video.extradataSize); const auto hevc_vps_nal = std::find_if(nal_list.begin(), nal_list.end(), [](nal_info info) { return info.type == NALU_HEVC_VPS; }); const auto hevc_sps_nal = std::find_if(nal_list.begin(), nal_list.end(), [](nal_info info) { return info.type == NALU_HEVC_SPS; }); const auto hevc_pps_nal = std::find_if(nal_list.begin(), nal_list.end(), [](nal_info info) { return info.type == NALU_HEVC_PPS; }); const bool header_check = (nal_list.end() != hevc_vps_nal) && (nal_list.end() != hevc_sps_nal) && (nal_list.end() != hevc_pps_nal); if (header_check) { m_Demux.video.extradataSize = (int)(hevc_vps_nal->size + hevc_sps_nal->size + hevc_pps_nal->size); uint8_t *new_ptr = (uint8_t *)av_malloc(m_Demux.video.extradataSize + AV_INPUT_BUFFER_PADDING_SIZE); memcpy(new_ptr, hevc_vps_nal->ptr, hevc_vps_nal->size); memcpy(new_ptr + hevc_vps_nal->size, hevc_sps_nal->ptr, hevc_sps_nal->size); memcpy(new_ptr + hevc_vps_nal->size + hevc_sps_nal->size, hevc_pps_nal->ptr, hevc_pps_nal->size); if (m_Demux.video.extradata) { av_free(m_Demux.video.extradata); } m_Demux.video.extradata = new_ptr; } } AddMessage(RGY_LOG_DEBUG, _T("GetHeader: shrinked header to %d bytes.\n"), m_Demux.video.extradataSize); } } pBitstream->copy(m_Demux.video.extradata, m_Demux.video.extradataSize); return RGY_ERR_NONE; } #pragma warning(push) #pragma warning(disable:4100) RGY_ERR RGYInputAvcodec::LoadNextFrame(RGYFrame *pSurface) { if (m_Demux.video.codecCtxDecode) { //動画のデコードを行う int got_frame = 0; while (!got_frame) { AVPacket pkt; av_init_packet(&pkt); if (!m_Demux.thread.thInput.joinable() //入力スレッドがなければ、自分で読み込む && m_Demux.qVideoPkt.get_keep_length() > 0) { //keep_length == 0なら読み込みは終了していて、これ以上読み込む必要はない const int ret = getSample(&pkt); if (ret == 0) { m_Demux.qVideoPkt.push(pkt); } else if (ret != AVERROR_EOF) { return RGY_ERR_UNKNOWN; } } bool bGetPacket = false; for (int i = 0; false == (bGetPacket = m_Demux.qVideoPkt.front_copy_no_lock(&pkt, (m_Demux.thread.queueInfo) ? &m_Demux.thread.queueInfo->usage_vid_in : nullptr)) && m_Demux.qVideoPkt.size() > 0; i++) { m_Demux.qVideoPkt.wait_for_push(); } if (!bGetPacket) { //flushするためのパケット pkt.data = nullptr; pkt.size = 0; } int ret = avcodec_send_packet(m_Demux.video.codecCtxDecode, &pkt); //AVERROR(EAGAIN) -> パケットを送る前に受け取る必要がある //パケットが受け取られていないのでpopしない if (ret != AVERROR(EAGAIN)) { m_Demux.qVideoPkt.pop(); av_packet_unref(&pkt); } if (ret == AVERROR_EOF) { //これ以上パケットを送れない AddMessage(RGY_LOG_DEBUG, _T("failed to send packet to video decoder, already flushed: %s.\n"), qsv_av_err2str(ret).c_str()); } else if (ret < 0 && ret != AVERROR(EAGAIN)) { AddMessage(RGY_LOG_ERROR, _T("failed to send packet to video decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNDEFINED_BEHAVIOR; } ret = avcodec_receive_frame(m_Demux.video.codecCtxDecode, m_Demux.video.frame); if (ret == AVERROR(EAGAIN)) { //もっとパケットを送る必要がある continue; } if (ret == AVERROR_EOF) { //最後まで読み込んだ return RGY_ERR_MORE_DATA; } if (ret < 0) { AddMessage(RGY_LOG_ERROR, _T("failed to receive frame from video decoder: %s.\n"), qsv_av_err2str(ret).c_str()); return RGY_ERR_UNDEFINED_BEHAVIOR; } got_frame = TRUE; } pSurface->setTimestamp(m_Demux.video.frame->pts); pSurface->setDuration(m_Demux.video.frame->pkt_duration); if (pSurface->picstruct() == RGY_PICSTRUCT_AUTO) { //autoの時は、frameのインタレ情報をセットする pSurface->setPicstruct(picstruct_avframe_to_rgy(m_Demux.video.frame)); } #if ENCODER_NVENC pSurface->dataList().clear(); if (m_Demux.video.qpTableListRef != nullptr) { int qp_stride = 0; int qscale_type = 0; #pragma warning(push) #pragma warning(disable:4996) // warning C4996: 'av_frame_get_qp_table': が古い形式として宣言されました。 RGY_DISABLE_WARNING_PUSH RGY_DISABLE_WARNING_STR("-Wdeprecated-declarations") const auto qp_table = av_frame_get_qp_table(m_Demux.video.frame, &qp_stride, &qscale_type); RGY_DISABLE_WARNING_POP #pragma warning(pop) if (qp_table != nullptr) { auto table = m_Demux.video.qpTableListRef->get(); const int qpw = (qp_stride) ? qp_stride : (pSurface->width() + 15) / 16; const int qph = (qp_stride) ? (pSurface->height() + 15) / 16 : 1; table->setQPTable(qp_table, qpw, qph, qp_stride, qscale_type, m_Demux.video.frame->pict_type, m_Demux.video.frame->pts); pSurface->dataList().push_back(table); } } #endif //#if ENCODER_NVENC #if ENABLE_DHDR10_INFO { auto hdr10plus = std::shared_ptr<RGYFrameData>(getHDR10plusMetaData(m_Demux.video.frame)); if (hdr10plus) { pSurface->dataList().push_back(hdr10plus); } } #endif //#if ENABLE_DHDR10_INFO //フレームデータをコピー void *dst_array[3]; pSurface->ptrArray(dst_array, m_convert->getFunc()->csp_to == RGY_CSP_RGB24 || m_convert->getFunc()->csp_to == RGY_CSP_RGB32); m_convert->run(m_Demux.video.frame->interlaced_frame != 0, dst_array, (const void **)m_Demux.video.frame->data, m_inputVideoInfo.srcWidth, m_Demux.video.frame->linesize[0], m_Demux.video.frame->linesize[1], pSurface->pitch(), m_inputVideoInfo.srcHeight, m_inputVideoInfo.srcHeight, m_inputVideoInfo.crop.c); if (got_frame) { av_frame_unref(m_Demux.video.frame); } m_encSatusInfo->m_sData.frameIn++; } else { if (m_Demux.qVideoPkt.size() == 0) { //m_Demux.qVideoPkt.size() == 0となるのは、最後まで読み込んだときか、中断した時しかありえない return RGY_ERR_MORE_DATA; //ファイルの終わりに到達 } } //進捗表示 double progressPercent = 0.0; if (m_Demux.format.formatCtx->duration) { progressPercent = m_Demux.frames.duration() * (m_Demux.video.stream->time_base.num / (double)m_Demux.video.stream->time_base.den); } return m_encSatusInfo->UpdateDisplayByCurrentDuration(progressPercent); } #pragma warning(pop) int RGYInputAvcodec::GetHWDecDeviceID() { return m_Demux.video.HWDecodeDeviceId; } HANDLE RGYInputAvcodec::getThreadHandleInput() { #if defined(WIN32) || defined(WIN64) return m_Demux.thread.thInput.native_handle(); #else return NULL; #endif //#if defined(WIN32) || defined(WIN64) } //出力する動画の情報をセット void RGYInputAvcodec::setOutputVideoInfo(int w, int h, int sar_x, int sar_y, bool mux) { if (m_cap2ass.enabled()) { if (mux) { m_cap2ass.setOutputResolution(w, h, sar_x, sar_y); m_cap2ass.printParam(RGY_LOG_DEBUG); } else { //muxしないなら処理する必要はない AddMessage(RGY_LOG_WARN, _T("caption2ass will be disabled as muxer is disabled.\n")); m_cap2ass.disable(); } } } RGY_ERR RGYInputAvcodec::ThreadFuncRead() { while (!m_Demux.thread.bAbortInput) { AVPacket pkt; if (getSample(&pkt)) { break; } m_Demux.qVideoPkt.push(pkt); } return RGY_ERR_NONE; } const AVMasteringDisplayMetadata *RGYInputAvcodec::getMasteringDisplay() const { return m_Demux.video.masteringDisplay; }; const AVContentLightMetadata *RGYInputAvcodec::getContentLight() const { return m_Demux.video.contentLight; }; #if USE_CUSTOM_INPUT int RGYInputAvcodec::readPacket(uint8_t *buf, int buf_size) { auto ret = (int)_fread_nolock(buf, 1, buf_size, m_Demux.format.fpInput); if (m_cap2ass.enabled()) { if (m_cap2ass.proc(buf, ret, m_Demux.qStreamPktL1) != RGY_ERR_NONE) { AddMessage(RGY_LOG_ERROR, _T("failed to process ts caption.\n")); return AVERROR_INVALIDDATA; } } return (ret == 0) ? AVERROR_EOF : ret; } int RGYInputAvcodec::writePacket(uint8_t *buf, int buf_size) { return (int)fwrite(buf, 1, buf_size, m_Demux.format.fpInput); } int64_t RGYInputAvcodec::seek(int64_t offset, int whence) { if (whence == AVSEEK_SIZE) { //たまにwhence=65536(AVSEEK_SIZE)とかいう要求が来ることがある return (m_Demux.format.inputFilesize) ? m_Demux.format.inputFilesize : -1; } if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { return -1; } if (m_cap2ass.enabled() && whence == SEEK_SET && offset == 0) { m_cap2ass.reset(); } return _fseeki64(m_Demux.format.fpInput, offset, whence); } #endif //USE_CUSTOM_INPUT #endif //ENABLE_AVSW_READER
50.907708
240
0.606163
[ "vector", "3d" ]
ca7f55cdc58ae19a32de8b44f7aea8c739fbf91e
1,656
cpp
C++
Graph/334 - Identifying Concurrent Events/334 - Identifying Concurrent Events.cpp
matheuscr30/UVA
2623f15de4a3948146fe4148a236d932750633b3
[ "MIT" ]
2
2019-03-27T18:49:28.000Z
2019-09-06T19:05:26.000Z
Graph/334 - Identifying Concurrent Events/334 - Identifying Concurrent Events.cpp
matheuscr30/UVA
2623f15de4a3948146fe4148a236d932750633b3
[ "MIT" ]
null
null
null
Graph/334 - Identifying Concurrent Events/334 - Identifying Concurrent Events.cpp
matheuscr30/UVA
2623f15de4a3948146fe4148a236d932750633b3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl '\n' using namespace std; typedef long long int ll; bool dist[205][205]; map<string, ll>mapa; map<ll, string>blala; vector< pair<string, string> >vet; main() { ll nc, ne, nm, cases=1; string s1, ant; while(cin >> nc && nc) { mapa.clear(); blala.clear(); vet.clear(); memset(dist, false, sizeof dist); ll indice = 0; for(ll i = 0 ; i < nc; i++) { cin >> ne; for(ll j = 0; j < ne; j++) { cin >> s1; if(!mapa.count(s1)) mapa[s1] = indice, blala[indice]=s1, indice++; if (j != 0) dist[mapa[ant]][mapa[s1]] = true; ant = s1; } } cin >> nm; for(ll i = 0; i < nm; i++) { cin.ignore(); cin >> ant >> s1; dist[mapa[ant]][mapa[s1]] = true; } for(ll k = 0; k < indice; k++) for(ll i = 0; i < indice; i++) for(ll j = 0 ; j < indice; j++) dist[i][j] |= (dist[i][k] & dist[k][j]); ll cont = 0; for(ll i = 0; i < indice; i++) { for(ll j = i+1; j < indice; j++) { if(!dist[i][j] and !dist[j][i]) { cont++; vet.push_back( {blala[i], blala[j] } ); } } } if(cont == 0) cout << "Case " << cases++ << ", " << "no concurrent events." << endl; else if (cont >= 2){ cout << "Case " << cases++ << ", " << cont << " concurrent events:" << endl; for(ll i = 0 ; i < 2; i++) { cout << "(" << vet[i].first << "," << vet[i].second << ") "; } cout << endl; } else { cout << "Case " << cases++ << ", " << cont << " concurrent events:" << endl; cout << "(" << vet[0].first << "," << vet[0].second << ") " << endl; } } }
18.4
79
0.447464
[ "vector" ]
ca80c6c163676b4b23f31a20c96b2ecd76414176
2,001
cpp
C++
src/Asteroid.cpp
BryGo1995/last-line
b236238f587fbce921d24e3fec17e1180822444e
[ "Unlicense", "MIT" ]
null
null
null
src/Asteroid.cpp
BryGo1995/last-line
b236238f587fbce921d24e3fec17e1180822444e
[ "Unlicense", "MIT" ]
null
null
null
src/Asteroid.cpp
BryGo1995/last-line
b236238f587fbce921d24e3fec17e1180822444e
[ "Unlicense", "MIT" ]
null
null
null
#include"Asteroid.h" void Asteroid::updateLocation(float dt) { // Add the velocity to the postion this->Position += this->Velocity * dt; } bool Asteroid::boxBoxCollision(GameObject* object) { // Collision on x axis bool collisionX = this->Position.x + this->Size.x >= object->Position.x && object->Position.x + object->Size.x >= this->Position.x; // Collision on y axis bool collisionY = this->Position.y + this->Size.y >= object->Position.y && object->Position.y + object->Size.y >= this->Position.y; return collisionX && collisionY; } bool Asteroid::boxCircleCollision(GameObject& object) { // Calculate the asteroid center glm::vec2 center; center.x = this->Position.x + (this->Size.x / 2); center.y = this->Position.y + (this->Size.y / 2); // Find the closest edge to the asteroid glm::vec2 edge; if (center.x < object.Position.x) { edge.x = object.Position.x; } else { edge.x = object.Position.x + object.Size.x; } if (center.y < object.Position.y) { edge.y = object.Position.y; } else { edge.y = object.Position.y + object.Size.y; } // Take the difference between the two vectors glm::vec2 diff = edge - center; // Check if the difference is smaller than the radius return glm::length(diff) < this->hitboxRadius; } bool Asteroid::circleCircleCollision(GameObject* object) { // Calculate the radius of both circular hitboxes float asteroidRadius = this->Size.x / 2; float objectRadius = object->Size.x / 2; // Calculate the center of the asteroid and objects glm::vec2 asteroidCenter, objectCenter; asteroidCenter = glm::vec2(this->Position.x + this->Size.x / 2, this->Position.y + this->Size.y / 2); objectCenter = glm::vec2(object->Position.x + object->Size.x / 2, object->Position.y + object->Size.y / 2); // Calculate the distance between the two centers float distance = glm::length(asteroidCenter - objectCenter); // Compare the distance to the sum of the two radii return distance <= (asteroidRadius + objectRadius); }
28.585714
76
0.694653
[ "object" ]
ca838395a5c283790a40af92a544bd68dc6985bf
1,762
cpp
C++
test_pliib.cpp
cartoonist/pliib
d89afc5df172b1e809119c5d97821113df05bb06
[ "MIT" ]
null
null
null
test_pliib.cpp
cartoonist/pliib
d89afc5df172b1e809119c5d97821113df05bb06
[ "MIT" ]
null
null
null
test_pliib.cpp
cartoonist/pliib
d89afc5df172b1e809119c5d97821113df05bb06
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "pliib.hpp" #include <fstream> #include <string> #include <algorithm> #include <cstdint> using namespace std; using namespace pliib; TEST_CASE("fast split function performs as expected", "[split]"){ char* to_split = new char[26]; strcpy(to_split, ";A;StrING;DeLIMITeD:.;by;"); to_split[25] = '\0'; SECTION("The countChar function works as expected"){ std::size_t num; countChar(to_split, ';', num); REQUIRE(num == 5); } char** ret; std::size_t retsz; int* split_sizes; split(to_split, ';', ret, retsz, split_sizes); //for (int i = 0; i < retsz; ++i){ // cout << '"' << ret[i] << '"' << endl; //} REQUIRE(retsz == 6); REQUIRE(strlen(ret[0]) == 0); REQUIRE(strcmp(ret[1], "A") == 0); REQUIRE(strcmp(ret[2], "StrING") == 0); REQUIRE(split_sizes[3] == 11); REQUIRE(split_sizes[0] == 0); REQUIRE(split_sizes[1] == 1); SECTION("split works for strings"){ string s = "ANOTHER:Separated:String"; vector<string> ret; split(s, ':', ret); REQUIRE(ret.size() == 3); REQUIRE(ret[0].compare("ANOTHER") == 0); REQUIRE(ret[2].compare("String") == 0); } delete[] to_split; } TEST_CASE("pliib can fill arrays using its fill_array function", "[fill_array]"){ int* x = new int[25]; x[0] = 1; pliib::fill_array(x, 0, 25); REQUIRE(x[0] == 0); REQUIRE(x[10] == 0); delete [] x; uint64_t* x_long = new uint64_t[1000]; pliib::fill_array<uint64_t>(x_long, 0, 1000); REQUIRE(x_long[0] == 0); REQUIRE(x_long[100] == 0); pliib::fill_array<uint64_t>(x_long, 10, 1000); REQUIRE(x_long[0] == 10); REQUIRE(x_long[100] == 10); delete [] x_long; }
23.810811
81
0.586833
[ "vector" ]
ca876c5e49736340a28b3b25461bd147b15ad9be
5,685
cpp
C++
tui/widget.cpp
GravisZro/put
89e45861c9bf53d4826becae122858c742e07f98
[ "Unlicense" ]
4
2018-12-08T01:45:14.000Z
2021-03-14T11:29:56.000Z
tui/widget.cpp
GravisZro/put
89e45861c9bf53d4826becae122858c742e07f98
[ "Unlicense" ]
null
null
null
tui/widget.cpp
GravisZro/put
89e45861c9bf53d4826becae122858c742e07f98
[ "Unlicense" ]
null
null
null
#include "widget.h" namespace tui { Widget::Widget(void) noexcept : m_geometry({{ 0, 0 }, { 0, 0 }}), m_layout(nullptr), m_sizePolicy(SizePolicy::Preferred, SizePolicy::Preferred), m_minimumSize({ 0, 0 }), m_maximumSize({ 0, 0 }), m_sizeHint({ 0, 0 }), m_focusPolicy(NoFocus) { } size2d_t Widget::minimumSize(void) const noexcept { if (isEmpty()) return size2d_t { 0, 0 }; return calculateMinSize(m_sizeHint, minimumSizeHint(), m_minimumSize, m_maximumSize, sizePolicy()); } size2d_t Widget::maximumSize(void) const noexcept { if (isEmpty()) return size2d_t { 0, 0 }; return calculateMaxSize(m_sizeHint, m_minimumSize, m_maximumSize, sizePolicy(), alignment()); } size2d_t Widget::minimumSizeHint(void) const noexcept { if (isEmpty()) return size2d_t { 0, 0 }; return layout()->minimumSize(); } size2d_t Widget::sizeHint(void) const noexcept { if (isEmpty()) return size2d_t { 0, 0 }; size2d_t sz = m_sizeHint .expandedTo(minimumSizeHint()) .boundedTo(m_maximumSize) .expandedTo(m_minimumSize); if (sizePolicy().horizontalPolicy() == SizePolicy::Policy::Ignored) sz.width = 0; if (sizePolicy().verticalPolicy() == SizePolicy::Policy::Ignored) sz.height = 0; return sz; } void Widget::setGeometry(const rect_t& rect) noexcept { if (isEmpty()) return; size2d_t& sz = m_geometry.size; uint16_t& x = m_geometry.pos.x; uint16_t& y = m_geometry.pos.y; sz = rect.size.boundedTo(maximumSize()); x = rect.x(); y = rect.y(); if (alignment() & (Align::HorizontalMask | Align::VerticalMask)) { size2d_t pref(sizeHint()); SizePolicy sp = sizePolicy(); if (sp.horizontalPolicy() == SizePolicy::Policy::Ignored) pref.width = m_sizeHint.expandedTo(m_minimumSize).width; if (sp.verticalPolicy() == SizePolicy::Policy::Ignored) pref.height = m_sizeHint.expandedTo(m_minimumSize).height; if (alignment() & Align::HorizontalMask) sz.width = tui::min(sz.width , pref.width); if (alignment() & Align::VerticalMask) sz.height = tui::min(sz.height, pref.height); } Align alignHoriz = alignment();// QStyle::visualAlignment(wid->layoutDirection(), alignment()); if (alignHoriz & Align::Right) // right x += rect.width() - sz.width; else if (!(alignHoriz & Align::Left)) // left x += (rect.width() - sz.width) / 2; if (alignment() & Align::Bottom) // bottom y += rect.height() - sz.height; else if (!(alignment() & Align::Top)) // middle y += (rect.height() - sz.height) / 2; // wid->setGeometry(x, y, s.width, s.height); } void Widget::repaint(void) noexcept { // TODO: invoke paintEvent() directly } void Widget::update(void) noexcept { Object::singleShot(this, &Widget::repaint); } void Widget::focusInEvent(FocusEvent* event) noexcept { if(focusPolicy() != NoFocus) update(); event->accept(); // TODO: verify in Qt source code } void Widget::focusOutEvent(FocusEvent* event) noexcept { if(focusPolicy() != NoFocus) update(); event->accept(); // TODO: verify in Qt source code } // === Keyboard events === void Widget::keyPressEvent(KeyEvent* event) noexcept { // TODO: verify in Qt source code } void Widget::keyReleaseEvent(KeyEvent* event) noexcept { // TODO: verify in Qt source code } // === Mouse events === // Mouse: drag and drop void Widget::dragEnterEvent(DragEnterEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::dragLeaveEvent(DragLeaveEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::dragMoveEvent(DragMoveEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::dropEvent(DropEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } // Mouse: position void Widget::enterEvent(Event* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::leaveEvent(Event* event) noexcept { event->accept(); // TODO: verify in Qt source code } // Mouse: buttons void Widget::mouseDoubleClickEvent(MouseEvent* event) noexcept { mousePressEvent(event); // verified correct } void Widget::mouseMoveEvent(MouseEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::mousePressEvent(MouseEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::mouseReleaseEvent(MouseEvent* event) noexcept { event->accept(); // TODO: verify in Qt source code } void Widget::wheelEvent(WheelEvent* event) noexcept { event->ignore(); // verified correct } // Paint/Layout events void Widget::hideEvent(HideEvent* event) noexcept { // TODO! } void Widget::moveEvent(MoveEvent* event) noexcept { // TODO! } void Widget::paintEvent(PaintEvent* event) noexcept { // TODO! } void Widget::resizeEvent(ResizeEvent* event) noexcept { // TODO! } void Widget::showEvent(ShowEvent* event) noexcept { // TODO! } // === Misc. events === void Widget::actionEvent(ActionEvent* event) noexcept { // TODO! } void Widget::changeEvent(Event* event) noexcept { // TODO! } void Widget::closeEvent(CloseEvent* event) noexcept { // TODO! } void Widget::contextMenuEvent(ContextMenuEvent* event) noexcept { // TODO! } }
23.886555
103
0.630079
[ "object" ]
ca8e07bcfc10ea54bd3b6d9cb33a007515b118b0
8,924
cc
C++
services/video_capture/device_factory_media_to_mojo_adapter.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
services/video_capture/device_factory_media_to_mojo_adapter.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
services/video_capture/device_factory_media_to_mojo_adapter.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "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 2016 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 "services/video_capture/device_factory_media_to_mojo_adapter.h" #include <sstream> #include <utility> #include "base/bind.h" #include "base/containers/contains.h" #include "base/notreached.h" #include "build/chromeos_buildflags.h" #include "media/capture/video/fake_video_capture_device.h" #include "media/capture/video/video_capture_device_info.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/video_capture/device_media_to_mojo_adapter.h" #include "services/video_capture/public/mojom/producer.mojom.h" #include "services/video_capture/public/uma/video_capture_service_event.h" namespace { // Translates a set of device infos reported by a VideoCaptureSystem to a set // of device infos that the video capture service exposes to its client. // A translation is needed, because the actual video frames, on their way // from the VideoCaptureSystem to clients of the Video Capture Service, will // pass through an instance of VideoCaptureDeviceClient, which performs certain // format conversions. // TODO(chfremer): A cleaner design would be to have this translation // happen in VideoCaptureDeviceClient, and talk only to VideoCaptureDeviceClient // instead of VideoCaptureSystem. static void TranslateDeviceInfos( video_capture::mojom::DeviceFactory::GetDeviceInfosCallback callback, const std::vector<media::VideoCaptureDeviceInfo>& device_infos) { std::vector<media::VideoCaptureDeviceInfo> translated_device_infos; for (const auto& device_info : device_infos) { media::VideoCaptureDeviceInfo translated_device_info; translated_device_info.descriptor = device_info.descriptor; for (const auto& format : device_info.supported_formats) { media::VideoCaptureFormat translated_format; if (format.pixel_format == media::PIXEL_FORMAT_Y16 || format.pixel_format == media::PIXEL_FORMAT_NV12) { translated_format.pixel_format = format.pixel_format; } else { translated_format.pixel_format = media::PIXEL_FORMAT_I420; } translated_format.frame_size = format.frame_size; translated_format.frame_rate = format.frame_rate; if (base::Contains(translated_device_info.supported_formats, translated_format)) continue; translated_device_info.supported_formats.push_back(translated_format); } // We explicitly need to include device infos for which there are zero // supported formats reported until https://crbug.com/792260 is resolved. translated_device_infos.push_back(translated_device_info); } std::move(callback).Run(translated_device_infos); } static void DiscardDeviceInfosAndCallContinuation( base::OnceClosure continuation, const std::vector<media::VideoCaptureDeviceInfo>&) { std::move(continuation).Run(); } } // anonymous namespace namespace video_capture { DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry::ActiveDeviceEntry() = default; DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry::~ActiveDeviceEntry() = default; DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry::ActiveDeviceEntry( DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry&& other) = default; DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry& DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry::operator=( DeviceFactoryMediaToMojoAdapter::ActiveDeviceEntry&& other) = default; #if BUILDFLAG(IS_CHROMEOS_ASH) DeviceFactoryMediaToMojoAdapter::DeviceFactoryMediaToMojoAdapter( std::unique_ptr<media::VideoCaptureSystem> capture_system, media::MojoMjpegDecodeAcceleratorFactoryCB jpeg_decoder_factory_callback, scoped_refptr<base::SequencedTaskRunner> jpeg_decoder_task_runner) : capture_system_(std::move(capture_system)), jpeg_decoder_factory_callback_(std::move(jpeg_decoder_factory_callback)), jpeg_decoder_task_runner_(std::move(jpeg_decoder_task_runner)), has_called_get_device_infos_(false), weak_factory_(this) {} #else DeviceFactoryMediaToMojoAdapter::DeviceFactoryMediaToMojoAdapter( std::unique_ptr<media::VideoCaptureSystem> capture_system) : capture_system_(std::move(capture_system)), has_called_get_device_infos_(false) {} #endif // BUILDFLAG(IS_CHROMEOS_ASH) DeviceFactoryMediaToMojoAdapter::~DeviceFactoryMediaToMojoAdapter() = default; void DeviceFactoryMediaToMojoAdapter::GetDeviceInfos( GetDeviceInfosCallback callback) { capture_system_->GetDeviceInfosAsync( base::BindOnce(&TranslateDeviceInfos, std::move(callback))); has_called_get_device_infos_ = true; } void DeviceFactoryMediaToMojoAdapter::CreateDevice( const std::string& device_id, mojo::PendingReceiver<mojom::Device> device_receiver, CreateDeviceCallback callback) { auto active_device_iter = active_devices_by_id_.find(device_id); if (active_device_iter != active_devices_by_id_.end()) { // The requested device is already in use. // Revoke the access and close the device, then bind to the new receiver. ActiveDeviceEntry& device_entry = active_device_iter->second; device_entry.receiver->reset(); device_entry.device->Stop(); device_entry.receiver->Bind(std::move(device_receiver)); device_entry.receiver->set_disconnect_handler(base::BindOnce( &DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose, base::Unretained(this), device_id)); std::move(callback).Run(media::VideoCaptureError::kNone); return; } auto create_and_add_new_device_cb = base::BindOnce(&DeviceFactoryMediaToMojoAdapter::CreateAndAddNewDevice, weak_factory_.GetWeakPtr(), device_id, std::move(device_receiver), std::move(callback)); if (has_called_get_device_infos_) { std::move(create_and_add_new_device_cb).Run(); return; } capture_system_->GetDeviceInfosAsync( base::BindOnce(&DiscardDeviceInfosAndCallContinuation, std::move(create_and_add_new_device_cb))); has_called_get_device_infos_ = true; } void DeviceFactoryMediaToMojoAdapter::AddSharedMemoryVirtualDevice( const media::VideoCaptureDeviceInfo& device_info, mojo::PendingRemote<mojom::Producer> producer, bool send_buffer_handles_to_producer_as_raw_file_descriptors, mojo::PendingReceiver<mojom::SharedMemoryVirtualDevice> virtual_device_receiver) { NOTIMPLEMENTED(); } void DeviceFactoryMediaToMojoAdapter::AddTextureVirtualDevice( const media::VideoCaptureDeviceInfo& device_info, mojo::PendingReceiver<mojom::TextureVirtualDevice> virtual_device_receiver) { NOTIMPLEMENTED(); } void DeviceFactoryMediaToMojoAdapter::AddGpuMemoryBufferVirtualDevice( const media::VideoCaptureDeviceInfo& device_info, mojo::PendingReceiver<mojom::GpuMemoryBufferVirtualDevice> virtual_device_receiver) { NOTIMPLEMENTED(); } void DeviceFactoryMediaToMojoAdapter::RegisterVirtualDevicesChangedObserver( mojo::PendingRemote<mojom::DevicesChangedObserver> observer, bool raise_event_if_virtual_devices_already_present) { NOTIMPLEMENTED(); } void DeviceFactoryMediaToMojoAdapter::CreateAndAddNewDevice( const std::string& device_id, mojo::PendingReceiver<mojom::Device> device_receiver, CreateDeviceCallback callback) { media::VideoCaptureErrorOrDevice device_status = capture_system_->CreateDevice(device_id); if (!device_status.ok()) { std::move(callback).Run(device_status.error()); return; } // Add entry to active_devices to keep track of it ActiveDeviceEntry device_entry; std::unique_ptr<media::VideoCaptureDevice> media_device = device_status.ReleaseDevice(); #if BUILDFLAG(IS_CHROMEOS_ASH) device_entry.device = std::make_unique<DeviceMediaToMojoAdapter>( std::move(media_device), jpeg_decoder_factory_callback_, jpeg_decoder_task_runner_); #else device_entry.device = std::make_unique<DeviceMediaToMojoAdapter>(std::move(media_device)); #endif // BUILDFLAG(IS_CHROMEOS_ASH) device_entry.receiver = std::make_unique<mojo::Receiver<mojom::Device>>( device_entry.device.get(), std::move(device_receiver)); device_entry.receiver->set_disconnect_handler(base::BindOnce( &DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose, base::Unretained(this), device_id)); active_devices_by_id_[device_id] = std::move(device_entry); std::move(callback).Run(media::VideoCaptureError::kNone); } void DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose( const std::string& device_id) { video_capture::uma::LogVideoCaptureServiceEvent( video_capture::uma::SERVICE_LOST_CONNECTION_TO_BROWSER); active_devices_by_id_[device_id].device->Stop(); active_devices_by_id_.erase(device_id); } } // namespace video_capture
40.93578
80
0.778799
[ "vector" ]
ca8e72b52574bd7b38e27e59acd6b7164221d142
4,300
cc
C++
third_party/libaddressinput/chromium/cpp/test/address_ui_test.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-04-27T20:21:55.000Z
2019-04-27T20:21:55.000Z
third_party/libaddressinput/chromium/cpp/test/address_ui_test.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/libaddressinput/chromium/cpp/test/address_ui_test.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2013 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <libaddressinput/address_ui.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_ui_component.h> #include <set> #include <string> #include <vector> #include <gtest/gtest.h> #include "grit.h" namespace i18n { namespace addressinput { namespace { // Returns testing::AssertionSuccess if the |components| are valid. testing::AssertionResult ComponentsAreValid( const std::vector<AddressUiComponent>& components) { if (components.empty()) { return testing::AssertionFailure() << "no components"; } std::set<AddressField> fields; for (std::vector<AddressUiComponent>::const_iterator component_it = components.begin(); component_it != components.end(); ++component_it) { static const AddressField kMinAddressField = COUNTRY; static const AddressField kMaxAddressField = RECIPIENT; if (component_it->field < kMinAddressField || component_it->field > kMaxAddressField) { return testing::AssertionFailure() << "unexpected input field " << component_it->field; } if (fields.find(component_it->field) != fields.end()) { return testing::AssertionFailure() << "duplicate input field " << component_it->field; } fields.insert(component_it->field); if (component_it->name_id == INVALID_MESSAGE_ID) { return testing::AssertionFailure() << "invalid field name_id for field " << component_it->field; } } return testing::AssertionSuccess(); } // Tests for address UI functions. class AddressUiTest : public testing::TestWithParam<std::string> {}; // Verifies that a region code consists of two characters, for example "TW". TEST_P(AddressUiTest, RegionCodeHasTwoCharacters) { EXPECT_EQ(2U, GetParam().size()); } // Verifies that BuildComponents() returns valid UI components for a region // code. TEST_P(AddressUiTest, ComponentsAreValid) { EXPECT_TRUE(ComponentsAreValid(BuildComponents(GetParam()))); } // Verifies that BuildComponents() returns a non-empty vector for a region code. TEST_P(AddressUiTest, RequiredFieldsExist) { EXPECT_FALSE(GetRequiredFields(GetParam()).empty()); } // Test all regions codes. INSTANTIATE_TEST_CASE_P( AllRegions, AddressUiTest, testing::ValuesIn(GetRegionCodes())); // Verifies that BuildComponents() and GetRequiredFields() return an empty // vector for an invalid region code. TEST_F(AddressUiTest, InvalidRegionCodeReturnsEmptyVector) { EXPECT_TRUE(BuildComponents("INVALID-REGION-CODE").empty()); EXPECT_TRUE(GetRequiredFields("INVALID-REGION-CODE").empty()); } struct SeparatorData { SeparatorData(const std::string& language_code, const std::string& compact_line_separator) : language_code(language_code), compact_line_separator(compact_line_separator) {} ~SeparatorData() {} std::string language_code; std::string compact_line_separator; }; // Tests for compact line separator. class CompactLineSeparatorTest : public testing::TestWithParam<SeparatorData> {}; TEST_P(CompactLineSeparatorTest, BasicTest) { EXPECT_EQ(GetParam().compact_line_separator, GetCompactAddressLinesSeparator(GetParam().language_code)); } INSTANTIATE_TEST_CASE_P( CompactLineSeparators, CompactLineSeparatorTest, testing::Values( SeparatorData("ja", ""), SeparatorData("zh", ""), SeparatorData("zh-hans", ""), SeparatorData("ar", "، "), SeparatorData("ko", " "), SeparatorData("th", " "), SeparatorData("en", ", "))); } // namespace } // namespace addressinput } // namespace i18n
31.617647
80
0.700465
[ "vector" ]
ca98c69a67fa472cad56139b8dd9b440e521ba14
881
cpp
C++
2020/day_08/part1.cpp
DankersW/advent_of_code
1ac9258c0fc175ee33474e81302c8ae8bac037eb
[ "Apache-2.0" ]
null
null
null
2020/day_08/part1.cpp
DankersW/advent_of_code
1ac9258c0fc175ee33474e81302c8ae8bac037eb
[ "Apache-2.0" ]
null
null
null
2020/day_08/part1.cpp
DankersW/advent_of_code
1ac9258c0fc175ee33474e81302c8ae8bac037eb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <vector> struct Instruction { std::string opp; int arg; }; int main() { std::ifstream file("input_test.txt"); std::string line; std::vector<Instruction> instructions; while (std::getline(file, line)) { instructions.push_back({line.substr(0, 3), std::stoi(line.substr(4))}); } auto instruction_set_size = instructions.size(); bool visited[instruction_set_size] = {0}; auto acc = 0; for (auto i=0; i<instruction_set_size; i++) { if (instructions[i].opp.compare("acc") == 0) { acc += instructions[i].arg; } else if (instructions[i].opp.compare("jmp") == 0){ i += instructions[i].arg -1; } if (visited[i]) { break; } else { visited[i] = 1; } } std::cout << "acc: " << acc << std::endl; return 0; }
23.810811
89
0.577753
[ "vector" ]
ca991ec4aaf63ffb556953e0d7a03dc6fc46367c
8,524
hpp
C++
locobot_recorder_ros/catkin_ws/src/rgbd_ros_to_lcm/include/bot_core/images_t.hpp
ARG-NCTU/LabelFusion
01066ff6f20bbc0e7afd89694b8d066bb057403f
[ "BSD-3-Clause" ]
null
null
null
locobot_recorder_ros/catkin_ws/src/rgbd_ros_to_lcm/include/bot_core/images_t.hpp
ARG-NCTU/LabelFusion
01066ff6f20bbc0e7afd89694b8d066bb057403f
[ "BSD-3-Clause" ]
null
null
null
locobot_recorder_ros/catkin_ws/src/rgbd_ros_to_lcm/include/bot_core/images_t.hpp
ARG-NCTU/LabelFusion
01066ff6f20bbc0e7afd89694b8d066bb057403f
[ "BSD-3-Clause" ]
null
null
null
/** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY * BY HAND!! * * Generated by lcm-gen **/ #ifndef __bot_core_images_t_hpp__ #define __bot_core_images_t_hpp__ #include <lcm/lcm_coretypes.h> #include <vector> #include "bot_core/image_t.hpp" namespace bot_core { /** * simple array of images * introduced to support Multisense SL disparity data * this message is now integrated into libbot * and should be sync'ed there */ class images_t { public: int64_t utime; int32_t n_images; std::vector< int16_t > image_types; std::vector< bot_core::image_t > images; public: // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t LEFT = 0; // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t RIGHT = 1; // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t DISPARITY = 2; /// 16bit as in the multisense // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t MASK_ZIPPED = 3; /// gray scale mask of left image, zipped with zlib // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t DEPTH_MM = 4; /// z depth, values similar to the OpenNI format // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t DISPARITY_ZIPPED = 5; /// 16bit as in the multisense, zipped with zlib // If you're using C++11 and are getting compiler errors saying // things like ‘constexpr’ needed for in-class initialization of // static data member then re-run lcm-gen with '--cpp-std=c++11' // to generate code that is compliant with C++11 static const int16_t DEPTH_MM_ZIPPED = 6; public: /** * Encode a message into binary form. * * @param buf The output buffer. * @param offset Encoding starts at thie byte offset into @p buf. * @param maxlen Maximum number of bytes to write. This should generally be * equal to getEncodedSize(). * @return The number of bytes encoded, or <0 on error. */ inline int encode(void *buf, int offset, int maxlen) const; /** * Check how many bytes are required to encode this message. */ inline int getEncodedSize() const; /** * Decode a message from binary form into this instance. * * @param buf The buffer containing the encoded message. * @param offset The byte offset into @p buf where the encoded message starts. * @param maxlen The maximum number of bytes to read while decoding. * @return The number of bytes decoded, or <0 if an error occured. */ inline int decode(const void *buf, int offset, int maxlen); /** * Retrieve the 64-bit fingerprint identifying the structure of the message. * Note that the fingerprint is the same for all instances of the same * message type, and is a fingerprint on the message type definition, not on * the message contents. */ inline static int64_t getHash(); /** * Returns "images_t" */ inline static const char* getTypeName(); // LCM support functions. Users should not call these inline int _encodeNoHash(void *buf, int offset, int maxlen) const; inline int _getEncodedSizeNoHash() const; inline int _decodeNoHash(const void *buf, int offset, int maxlen); inline static uint64_t _computeHash(const __lcm_hash_ptr *p); }; int images_t::encode(void *buf, int offset, int maxlen) const { int pos = 0, tlen; int64_t hash = getHash(); tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos); if (tlen < 0) return tlen; else pos += tlen; return pos; } int images_t::decode(const void *buf, int offset, int maxlen) { int pos = 0, thislen; int64_t msg_hash; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1); if (thislen < 0) return thislen; else pos += thislen; if (msg_hash != getHash()) return -1; thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } int images_t::getEncodedSize() const { return 8 + _getEncodedSizeNoHash(); } int64_t images_t::getHash() { static int64_t hash = static_cast<int64_t>(_computeHash(NULL)); return hash; } const char* images_t::getTypeName() { return "images_t"; } int images_t::_encodeNoHash(void *buf, int offset, int maxlen) const { int pos = 0, tlen; tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->n_images, 1); if(tlen < 0) return tlen; else pos += tlen; if(this->n_images > 0) { tlen = __int16_t_encode_array(buf, offset + pos, maxlen - pos, &this->image_types[0], this->n_images); if(tlen < 0) return tlen; else pos += tlen; } for (int a0 = 0; a0 < this->n_images; a0++) { tlen = this->images[a0]._encodeNoHash(buf, offset + pos, maxlen - pos); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int images_t::_decodeNoHash(const void *buf, int offset, int maxlen) { int pos = 0, tlen; tlen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->n_images, 1); if(tlen < 0) return tlen; else pos += tlen; if(this->n_images) { this->image_types.resize(this->n_images); tlen = __int16_t_decode_array(buf, offset + pos, maxlen - pos, &this->image_types[0], this->n_images); if(tlen < 0) return tlen; else pos += tlen; } try { this->images.resize(this->n_images); } catch (...) { return -1; } for (int a0 = 0; a0 < this->n_images; a0++) { tlen = this->images[a0]._decodeNoHash(buf, offset + pos, maxlen - pos); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int images_t::_getEncodedSizeNoHash() const { int enc_size = 0; enc_size += __int64_t_encoded_array_size(NULL, 1); enc_size += __int32_t_encoded_array_size(NULL, 1); enc_size += __int16_t_encoded_array_size(NULL, this->n_images); for (int a0 = 0; a0 < this->n_images; a0++) { enc_size += this->images[a0]._getEncodedSizeNoHash(); } return enc_size; } uint64_t images_t::_computeHash(const __lcm_hash_ptr *p) { const __lcm_hash_ptr *fp; for(fp = p; fp != NULL; fp = fp->parent) if(fp->v == images_t::getHash) return 0; const __lcm_hash_ptr cp = { p, images_t::getHash }; uint64_t hash = 0xfbe98784e0a4fbadLL + bot_core::image_t::_computeHash(&cp); return (hash<<1) + ((hash>>63)&1); } } #endif
34.232932
110
0.631394
[ "vector" ]
ca9d20b0c5eb197006091e45df4f2edd2a4e8b4c
11,483
cpp
C++
src/Core/Resource/Factory/CWorldLoader.cpp
liakman/PrimeWorldEditor
483184719701fbc59ad66212afcade9488956186
[ "MIT" ]
32
2018-12-17T20:22:32.000Z
2019-06-14T06:48:25.000Z
src/Core/Resource/Factory/CWorldLoader.cpp
liakman/PrimeWorldEditor
483184719701fbc59ad66212afcade9488956186
[ "MIT" ]
10
2019-11-25T04:54:05.000Z
2022-02-12T20:20:56.000Z
src/Core/Resource/Factory/CWorldLoader.cpp
liakman/PrimeWorldEditor
483184719701fbc59ad66212afcade9488956186
[ "MIT" ]
10
2019-11-22T09:16:00.000Z
2021-11-21T22:55:54.000Z
#include "CWorldLoader.h" #include "Core/GameProject/CGameProject.h" #include "Core/GameProject/CResourceStore.h" #include <Common/Log.h> CWorldLoader::CWorldLoader() = default; void CWorldLoader::LoadPrimeMLVL(IInputStream& rMLVL) { /* * This function loads MLVL files from Prime 1/2 * We start immediately after the "version" value (0x8 in the file) */ // Header if (mVersion < EGame::CorruptionProto) { mpWorld->mpWorldName = gpResourceStore->LoadResource(rMLVL.ReadULong(), EResourceType::StringTable); if (mVersion == EGame::Echoes) mpWorld->mpDarkWorldName = gpResourceStore->LoadResource(rMLVL.ReadULong(), EResourceType::StringTable); if (mVersion >= EGame::Echoes) mpWorld->mTempleKeyWorldIndex = rMLVL.ReadULong(); if (mVersion >= EGame::Prime) mpWorld->mpSaveWorld = gpResourceStore->LoadResource(rMLVL.ReadULong(), EResourceType::SaveWorld); mpWorld->mpDefaultSkybox = gpResourceStore->LoadResource(rMLVL.ReadULong(), EResourceType::Model); } else { mpWorld->mpWorldName = gpResourceStore->LoadResource(rMLVL.ReadULongLong(), EResourceType::StringTable); rMLVL.Seek(0x4, SEEK_CUR); // Skipping unknown value mpWorld->mpSaveWorld = gpResourceStore->LoadResource(rMLVL.ReadULongLong(), EResourceType::SaveWorld); mpWorld->mpDefaultSkybox = gpResourceStore->LoadResource(rMLVL.ReadULongLong(), EResourceType::Model); } // Memory relays - only in MP1 if (mVersion == EGame::Prime) { const uint32 NumMemoryRelays = rMLVL.ReadULong(); mpWorld->mMemoryRelays.reserve(NumMemoryRelays); for (uint32 iMem = 0; iMem < NumMemoryRelays; iMem++) { auto& MemRelay = mpWorld->mMemoryRelays.emplace_back(); MemRelay.InstanceID = rMLVL.ReadULong(); MemRelay.TargetID = rMLVL.ReadULong(); MemRelay.Message = rMLVL.ReadUShort(); MemRelay.Active = rMLVL.ReadBool(); } } // Areas - here's the real meat of the file const uint32 NumAreas = rMLVL.ReadULong(); if (mVersion == EGame::Prime) rMLVL.Seek(0x4, SEEK_CUR); mpWorld->mAreas.resize(NumAreas); for (uint32 iArea = 0; iArea < NumAreas; iArea++) { // Area header CWorld::SArea *pArea = &mpWorld->mAreas[iArea]; pArea->pAreaName = gpResourceStore->LoadResource<CStringTable>( CAssetID(rMLVL, mVersion) ); pArea->Transform = CTransform4f(rMLVL); pArea->AetherBox = CAABox(rMLVL); pArea->AreaResID = CAssetID(rMLVL, mVersion); pArea->AreaID = CAssetID(rMLVL, mVersion); // Attached areas const uint32 NumAttachedAreas = rMLVL.ReadULong(); pArea->AttachedAreaIDs.reserve(NumAttachedAreas); for (uint32 iAttached = 0; iAttached < NumAttachedAreas; iAttached++) pArea->AttachedAreaIDs.push_back(rMLVL.ReadUShort()); // Skip dependency list - this is very fast to regenerate so there's no use in caching it if (mVersion < EGame::CorruptionProto) { rMLVL.Seek(0x4, SEEK_CUR); const uint32 NumDependencies = rMLVL.ReadULong(); rMLVL.Seek(NumDependencies * 8, SEEK_CUR); const uint32 NumDependencyOffsets = rMLVL.ReadULong(); rMLVL.Seek(NumDependencyOffsets * 4, SEEK_CUR); } // Docks const uint32 NumDocks = rMLVL.ReadULong(); pArea->Docks.resize(NumDocks); for (uint32 iDock = 0; iDock < NumDocks; iDock++) { const uint32 NumConnectingDocks = rMLVL.ReadULong(); CWorld::SArea::SDock* pDock = &pArea->Docks[iDock]; pDock->ConnectingDocks.reserve(NumConnectingDocks); for (uint32 iConnect = 0; iConnect < NumConnectingDocks; iConnect++) { auto& ConnectingDock = pDock->ConnectingDocks.emplace_back(); ConnectingDock.AreaIndex = rMLVL.ReadULong(); ConnectingDock.DockIndex = rMLVL.ReadULong(); } const uint32 NumCoordinates = rMLVL.ReadULong(); ASSERT(NumCoordinates == 4); pDock->DockCoordinates.resize(NumCoordinates); for (auto& coordinate : pDock->DockCoordinates) coordinate = CVector3f(rMLVL); } // Rels if (mVersion == EGame::EchoesDemo || mVersion == EGame::Echoes) { const uint32 NumRels = rMLVL.ReadULong(); pArea->RelFilenames.resize(NumRels); for (auto& filename : pArea->RelFilenames) filename = rMLVL.ReadString(); if (mVersion == EGame::Echoes) { const uint32 NumRelOffsets = rMLVL.ReadULong(); // Don't know what these offsets correspond to pArea->RelOffsets.resize(NumRelOffsets); for (auto& offset : pArea->RelOffsets) offset = rMLVL.ReadULong(); } } // Internal name - MP1 doesn't have this, we'll get it from the GameInfo file later if (mVersion >= EGame::EchoesDemo) pArea->InternalName = rMLVL.ReadString(); } // MapWorld mpWorld->mpMapWorld = gpResourceStore->LoadResource(CAssetID(rMLVL, mVersion), EResourceType::MapWorld); rMLVL.Seek(0x5, SEEK_CUR); // Unknown values which are always 0 // Audio Groups - we don't need this info as we regenerate it on cook if (mVersion == EGame::Prime) { const uint32 NumAudioGrps = rMLVL.ReadULong(); rMLVL.Seek(0x8 * NumAudioGrps, SEEK_CUR); rMLVL.Seek(0x1, SEEK_CUR); // Unknown values which are always 0 } // Layer flags rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant area count for (uint32 iArea = 0; iArea < NumAreas; iArea++) { CWorld::SArea* pArea = &mpWorld->mAreas[iArea]; const uint32 NumLayers = rMLVL.ReadULong(); if (NumLayers != pArea->Layers.size()) pArea->Layers.resize(NumLayers); const uint64 LayerFlags = rMLVL.ReadULongLong(); for (uint32 iLayer = 0; iLayer < NumLayers; iLayer++) pArea->Layers[iLayer].Active = (((LayerFlags >> iLayer) & 0x1) == 1); } // Layer names rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant layer count for (size_t iArea = 0; iArea < NumAreas; iArea++) { CWorld::SArea* pArea = &mpWorld->mAreas[iArea]; const size_t NumLayers = pArea->Layers.size(); for (size_t iLayer = 0; iLayer < NumLayers; iLayer++) pArea->Layers[iLayer].LayerName = rMLVL.ReadString(); } // Layer state IDs if (mVersion >= EGame::Corruption) { rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant layer count for (size_t iArea = 0; iArea < NumAreas; iArea++) { CWorld::SArea *pArea = &mpWorld->mAreas[iArea]; const size_t NumLayers = pArea->Layers.size(); for (size_t iLayer = 0; iLayer < NumLayers; iLayer++) pArea->Layers[iLayer].LayerStateID = CSavedStateID(rMLVL); } } // Last part of the file is layer name offsets, but we don't need it } void CWorldLoader::LoadReturnsMLVL(IInputStream& rMLVL) { mpWorld->mpWorldName = gpResourceStore->LoadResource<CStringTable>(rMLVL.ReadULongLong()); CWorld::STimeAttackData& rData = mpWorld->mTimeAttackData; rData.HasTimeAttack = rMLVL.ReadBool(); if (rData.HasTimeAttack) { rData.ActNumber = rMLVL.ReadString(); rData.BronzeTime = rMLVL.ReadFloat(); rData.SilverTime = rMLVL.ReadFloat(); rData.GoldTime = rMLVL.ReadFloat(); rData.ShinyGoldTime = rMLVL.ReadFloat(); } mpWorld->mpSaveWorld = gpResourceStore->LoadResource(rMLVL.ReadULongLong(), EResourceType::SaveWorld); mpWorld->mpDefaultSkybox = gpResourceStore->LoadResource<CModel>(rMLVL.ReadULongLong()); // Areas const uint32 NumAreas = rMLVL.ReadULong(); mpWorld->mAreas.resize(NumAreas); for (auto& area : mpWorld->mAreas) { // Area header area.pAreaName = gpResourceStore->LoadResource<CStringTable>(rMLVL.ReadULongLong()); area.Transform = CTransform4f(rMLVL); area.AetherBox = CAABox(rMLVL); area.AreaResID = rMLVL.ReadULongLong(); area.AreaID = rMLVL.ReadULongLong(); rMLVL.Seek(0x4, SEEK_CUR); area.InternalName = rMLVL.ReadString(); } // Layer flags rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant area count for (auto& area : mpWorld->mAreas) { const uint32 NumLayers = rMLVL.ReadULong(); area.Layers.resize(NumLayers); const uint64 LayerFlags = rMLVL.ReadULongLong(); for (uint32 iLayer = 0; iLayer < NumLayers; iLayer++) area.Layers[iLayer].Active = (((LayerFlags >> iLayer) & 0x1) == 1); } // Layer names rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant layer count for (auto& area : mpWorld->mAreas) { const size_t NumLayers = area.Layers.size(); for (size_t iLayer = 0; iLayer < NumLayers; iLayer++) area.Layers[iLayer].LayerName = rMLVL.ReadString(); } // Layer state IDs rMLVL.Seek(0x4, SEEK_CUR); // Skipping redundant layer count for (auto& area : mpWorld->mAreas) { const size_t NumLayers = area.Layers.size(); for (uint32 iLayer = 0; iLayer < NumLayers; iLayer++) area.Layers[iLayer].LayerStateID = CSavedStateID(rMLVL); } // Last part of the file is layer name offsets, but we don't need it } void CWorldLoader::GenerateEditorData() { const CGameInfo *pGameInfo = mpWorld->Entry()->ResourceStore()->Project()->GameInfo(); if (mVersion > EGame::Prime) return; for (size_t iArea = 0; iArea < mpWorld->NumAreas(); iArea++) { CWorld::SArea& rArea = mpWorld->mAreas[iArea]; rArea.InternalName = pGameInfo->GetAreaName(rArea.AreaResID); ASSERT(!rArea.InternalName.IsEmpty()); } } std::unique_ptr<CWorld> CWorldLoader::LoadMLVL(IInputStream& rMLVL, CResourceEntry *pEntry) { if (!rMLVL.IsValid()) return nullptr; const uint32 Magic = rMLVL.ReadULong(); if (Magic != 0xDEAFBABE) { errorf("%s: Invalid MLVL magic: 0x%08X", *rMLVL.GetSourceString(), Magic); return nullptr; } const uint32 FileVersion = rMLVL.ReadULong(); const EGame Version = GetFormatVersion(FileVersion); if (Version == EGame::Invalid) { errorf("%s: Unsupported MLVL version: 0x%X", *rMLVL.GetSourceString(), FileVersion); return nullptr; } // Filestream is valid, magic+version are valid; everything seems good! auto ptr = std::make_unique<CWorld>(pEntry); CWorldLoader Loader; Loader.mpWorld = ptr.get(); Loader.mVersion = Version; if (Version != EGame::DKCReturns) Loader.LoadPrimeMLVL(rMLVL); else Loader.LoadReturnsMLVL(rMLVL); Loader.GenerateEditorData(); return ptr; } EGame CWorldLoader::GetFormatVersion(uint32 Version) { switch (Version) { case 0xD: return EGame::PrimeDemo; case 0x11: return EGame::Prime; case 0x14: return EGame::EchoesDemo; case 0x17: return EGame::Echoes; case 0x19: return EGame::Corruption; case 0x1B: return EGame::DKCReturns; default: return EGame::Invalid; } }
34.902736
116
0.627711
[ "model", "transform" ]
caa137b4f4ea16e6b3ce8f8dbad6b57502590c0f
9,149
cpp
C++
magic3d/src/sound/sound.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
4
2016-03-25T23:35:08.000Z
2019-05-15T18:56:07.000Z
magic3d/src/sound/sound.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
null
null
null
magic3d/src/sound/sound.cpp
magic-tech/Magic3D
a626a2302c8be9349cf0371077fb9f67821dfae3
[ "Zlib" ]
2
2016-03-17T09:01:12.000Z
2020-01-18T13:04:05.000Z
/****************************************************************************** @Copyright Copyright (C) 2008 - 2016 by MagicTech. @Platform ANSI compatible ******************************************************************************/ /* Magic3D Engine Copyright (c) 2008-2016 Thiago C. Moraes http://www.magictech.com.br This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <magic3d/magic3d.h> #include <magic3d/sound/sound_ogg.h> bool Magic3D::Sound::enabled = false; Magic3D::Sound::Sound(const Sound& sound, std::string name) : Object(sound, name) { this->fileName = sound.fileName; this->box = sound.box; this->gain = sound.gain; this->pitch = sound.pitch; this->distance = sound.distance; this->loop = sound.loop; this->needPlay = sound.needPlay; this->child = sound.child ? static_cast<Sound*>(sound.child->spawn(name)) : NULL; } Magic3D::Sound::Sound(std::string name) : Object(eOBJECT_SOUND, eRENDER_3D, name) { box = Box(Vector3(-0.125f, -0.125f, -0.125f), Vector3(0.125f, 0.125f, 0.125f)); gain = 1.0f; pitch = 1.0f; distance = 100.0f; loop = true; needPlay = false; child = NULL; } Magic3D::Sound::~Sound() { if (child) { child->stop(); delete child; child = NULL; } } void* Magic3D::Sound::spawn(std::string name) const { return (new Sound(*this, name)); } void Magic3D::Sound::setFileName(std::string name) { fileName = name; load(); } const std::string& Magic3D::Sound::getFileName() { return fileName; } void Magic3D::Sound::load() { std::string lower = getFileName(); const int length = lower.length(); for(int i=0; i!=length; ++i) { lower[i] = tolower(lower[i]); } std::string ending = ".ogg"; if (lower.compare (lower.length() - ending.length(), ending.length(), ending) == 0) { if (child) { child->stop(); delete child; child = NULL; } if (!child) { child = new SoundOGG(getName()); updateChild(); child->setFileName(getFileName()); } } else { } } bool Magic3D::Sound::start() { Log::log(eLOG_PLAINTEXT, "Start Initializing OpenAL..."); ALCdevice* device; //Open device device = alcOpenDevice(NULL); if (device != NULL) { //Create context(s) ALCcontext* context = alcCreateContext(device,NULL); //Set active context if (alcMakeContextCurrent(context)) { enabled = true; } char* defaultDeviceName = (char*)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); Log::log(eLOG_RENDERER, defaultDeviceName); //delete[] defaultDeviceName; } else { Log::log(eLOG_FAILURE, "Default sound device not found..."); } Log::log(eLOG_SUCCESS, "OpenAL sucessfully started."); return enabled; } bool Magic3D::Sound::finish() { ALCcontext *context; ALCdevice *device; //Unregister extensions //Get active context context = alcGetCurrentContext(); //Get device for active context device = alcGetContextsDevice(context); //Disable context alcMakeContextCurrent(NULL); //Release context(s) alcDestroyContext(context); //Close device alcCloseDevice(device); enabled = false; Log::log(eLOG_SUCCESS, "OpenAL sucessfully finished."); return true; } bool Magic3D::Sound::isEnabled() { return enabled; } void Magic3D::Sound::updateChild() { if (child) { child->setParent(getParent()); child->setMatrix(getMatrix()); child->setGain(getGain()); child->setPitch(getPitch()); child->setDistance(getDistance()); child->setLooping(isLooping()); } } bool Magic3D::Sound::update() { bool result = false; Object::update(); if (isEnabled() && isVisible() && getLayer() && getLayer()->isVisible()) { if (needPlay) { play(); needPlay = false; } ViewPort* view = Renderer::getInstance()->getCurrentViewPort(); Camera* camera = view->getPerspective(); if (camera) { updateListener(camera->getPositionFromParent(), camera->getDirectionFront(), camera->getDirectionUp()); } updateChild(); render(); result = true; } if (isPlaying() && getLayer() && !getLayer()->isVisible()) { stop(); } return result; } const Magic3D::Box& Magic3D::Sound::getBoundingBox() { return box; } void Magic3D::Sound::updateListener(Vector3 position, Vector3 front, Vector3 up) { float orientation[6]; orientation[0] = front.getX(); orientation[1] = front.getY(); orientation[2] = front.getZ(); orientation[3] = up.getX(); orientation[4] = up.getY(); orientation[5] = up.getZ(); alListener3f(AL_POSITION, position.getX(), position.getY(), position.getZ()); alListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f); alListenerfv(AL_ORIENTATION, orientation); alListenerf(AL_GAIN, Scene::getInstance()->getVolumeMaster()); } void Magic3D::Sound::render() { if (child) { child->render(); } } void Magic3D::Sound::play() { if (child && getLayer() && getLayer()->isVisible()) { child->play(); } } void Magic3D::Sound::stop() { if (child) { child->stop(); } } void Magic3D::Sound::setGain(float gain) { this->gain = gain; } float Magic3D::Sound::getGain() { return gain; } void Magic3D::Sound::setPitch(float pitch) { this->pitch = pitch; } float Magic3D::Sound::getPitch() { return pitch; } void Magic3D::Sound::setDistance(float distance) { this->distance = distance; } float Magic3D::Sound::getDistance() { return distance; } void Magic3D::Sound::setLooping(bool loop) { this->loop = loop; } bool Magic3D::Sound::isLooping() { return loop; } bool Magic3D::Sound::isPlaying() { bool result = false; if (child) { result = child->isPlaying(); } return result; } Magic3D::XMLElement* Magic3D::Sound::save(XMLElement* root) { Object::save(root); if (root) { XMLElement* sound = root->GetDocument()->NewElement(M3D_SOUND_XML); root->LinkEndChild(sound); saveFloat( sound, M3D_SOUND_XML_GAIN, gain); saveFloat( sound, M3D_SOUND_XML_PITCH, pitch); saveFloat( sound, M3D_SOUND_XML_DISTANCE, distance); saveInt( sound, M3D_SOUND_XML_LOOP, loop ? 1 : 0); saveString(sound, M3D_SOUND_XML_FILE, fileName); saveInt( sound, M3D_SOUND_XML_PLAYING, isPlaying()); } return root; } Magic3D::XMLElement* Magic3D::Sound::load(XMLElement* root) { Object::load(root); if (root) { XMLElement* sound = root->FirstChildElement(M3D_SOUND_XML); gain = loadFloat( sound, M3D_SOUND_XML_GAIN); pitch = loadFloat( sound, M3D_SOUND_XML_PITCH); distance = loadFloat( sound, M3D_SOUND_XML_DISTANCE); loop = loadInt( sound, M3D_SOUND_XML_LOOP); setFileName(loadString(sound, M3D_SOUND_XML_FILE)); needPlay = loadInt(sound, M3D_SOUND_XML_PLAYING); } return root; } void Magic3D::Sound::logError(int index) { int error = alGetError(); bool show = error != AL_NO_ERROR; if (show) { std::stringstream sstm; sstm << "OpenAL ERROR: " << index << " - "; switch (error) { case AL_INVALID_NAME: sstm << "AL_INVALID_NAME"; break; case AL_INVALID_ENUM: sstm << "AL_INVALID_ENUM"; break; case AL_INVALID_VALUE: sstm << "AL_INVALID_VALUE"; break; case AL_INVALID_OPERATION: sstm << "AL_INVALID_OPERATION"; break; case AL_OUT_OF_MEMORY : sstm << "AL_OUT_OF_MEMORY"; break; } Log::log(eLOG_FAILURE, sstm.str().c_str()); } }
24.660377
131
0.581703
[ "render", "object" ]
caa2fc4afa127710f29210290d143f6840422521
7,833
cpp
C++
src/rpcupdate.cpp
dlhendo70/crown-core
e34163e206c4c0c586a02c8d1d8e9975c1e1cc5f
[ "MIT" ]
12
2018-08-26T13:59:10.000Z
2022-01-02T14:31:27.000Z
src/rpcupdate.cpp
dlhendo70/crown-core
e34163e206c4c0c586a02c8d1d8e9975c1e1cc5f
[ "MIT" ]
43
2018-09-17T16:45:59.000Z
2021-08-05T11:01:38.000Z
src/rpcupdate.cpp
dlhendo70/crown-core
e34163e206c4c0c586a02c8d1d8e9975c1e1cc5f
[ "MIT" ]
12
2018-06-11T01:11:03.000Z
2022-01-03T10:57:10.000Z
// Copyright (c) 2014-2018 The Crown developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcupdate.h" #include "init.h" #include "clientversion.h" #include "rpcserver.h" #include "util.h" #include <boost/thread.hpp> using namespace json_spirit; using namespace std; using namespace boost::filesystem; bool RPCUpdate::started = false; Object RPCUpdate::statusObj; std::string RPCUpdate::GetArchivePath() const { std::string url = updater.GetDownloadUrl(); return (tempDir / path(url).filename()).string(); } bool RPCUpdate::Download() { statusObj.clear(); // Create temporary directory tempDir = GetTempPath() / unique_path(); bool result = TryCreateDirectory(tempDir); if (!result) { throw runtime_error("Failed to create directory" + tempDir.string()); } // Download archive std::string archivePath = GetArchivePath(); updater.DownloadFile(updater.GetDownloadUrl(), archivePath, &ProgressFunction); if (updater.GetStopDownload()) { started = false; statusObj[0] = Pair("Download", "Stopped"); remove_all(tempDir); return false; } if (CheckSha(archivePath)) { statusObj[0] = Pair("Download", "Done - " + archivePath); } else { statusObj[0] = Pair("Download", "Error. SHA-256 verification failed."); remove_all(tempDir); return false; } return true; } void RPCUpdate::Install() { statusObj.clear(); if (!Download()) { return; } // Extract archive bool result = TryCreateDirectory(tempDir / "archive"); if (!result) { throw runtime_error(strprintf("Failed to create directory %s", (tempDir / "archive").string())); } std::string strCommand = strprintf("unzip -q %s -d %s", GetArchivePath(), (tempDir / "archive").string()); int nErr = ::system(strCommand.c_str()); if (nErr) { LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); statusObj.push_back(Pair("Extract", "Error. Check debug.log")); } else { statusObj.push_back(Pair("Extract", "Done")); } // Copy files to /usr/ if (!nErr) { strCommand = strprintf("cp -rf %s /usr/local/", (tempDir / "archive/*/*").string()); nErr = ::system(strCommand.c_str()); if (nErr) { LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); statusObj.push_back(Pair("Install", "Error. Check debug.log.")); } else { statusObj.push_back(Pair("Install", "Done")); } // Restart crownd StartRestart(); } boost::filesystem::remove_all(tempDir); } void RPCUpdate::ProgressFunction(curl_off_t now, curl_off_t total) { int percent = 0; if (total != 0) { percent = now * 100 / total; } if (statusObj.size() == 0) { statusObj.push_back(Pair("Download", "In Progress")); } if ((now == total) && now != 0) { started = false; statusObj[0] = Pair("Download", "Done"); } else if (now != total) { started = true; statusObj[0] = Pair("Download", strprintf("%0.1f/%0.1fMB, %d%%", static_cast<double>(now) / 1024 / 1024, static_cast<double>(total) / 1024 / 1024, percent)); } } bool RPCUpdate::IsStarted() const { return started; } Object RPCUpdate::GetStatusObject() const { return statusObj; } bool RPCUpdate::CheckSha(const std::string& fileName) const { bool result = false; std::string newSha = updater.GetDownloadSha256Sum(); try { std::string sha = Sha256Sum(fileName); if (!sha.empty()) { if (newSha.compare(sha) == 0) { result = true; } else { result = false; } } else { result = false; } } catch(std::runtime_error &e) { result = false; } return result; } Value update(const Array& params, bool fHelp) { RPCUpdate rpcUpdate; string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "check" && strCommand != "download" && strCommand != "status" && strCommand != "install" && strCommand != "stop")) throw runtime_error( "update \"command\"... ( \"passphrase\" )\n" "Set of commands to check and download application updates\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "2. \"passphrase\" (string, optional) The wallet passphrase\n" "\nAvailable commands:\n" " check - Check for application updates\n" " download - Download a new version\n" " status - Check download status\n" " install - Install update\n" " stop - Stop update/install\n" ); if (strCommand == "check") { if (params.size() > 1) { throw runtime_error("Too many parameters\n"); } if (updater.GetStatus()) { // There is an update Object obj; obj.push_back(Pair("Current Version", FormatVersion(CLIENT_VERSION))); obj.push_back(Pair("Update Version", FormatVersion(updater.GetVersion()))); obj.push_back(Pair("OS", updater.GetOsString())); obj.push_back(Pair("Url", updater.GetDownloadUrl())); obj.push_back(Pair("Sha256hash", updater.GetDownloadSha256Sum())); return obj; } return "You are running the latest version of Crown - " + FormatVersion(CLIENT_VERSION); } if (strCommand == "download") { if (!updater.GetStatus()) { return "You are running the latest version of Crown - " + FormatVersion(CLIENT_VERSION); } if (rpcUpdate.IsStarted()) { return "Download is in progress. Run 'crown-cli update status' to check the status."; } boost::thread t(boost::bind(&RPCUpdate::Download, rpcUpdate)); return "Crown download started. \nRun 'crown-cli update status' to check download status."; } if (strCommand == "status") { return rpcUpdate.GetStatusObject(); } if (strCommand == "stop") { updater.StopDownload(); return "Crown download stopped."; } if (strCommand == "install") { if (!fServer) { throw runtime_error("Command is available only in server mode." "\ncrown-qt will automatically check and notify if there is an updates\n"); } if (updater.GetOS() != Updater::LINUX_32 && updater.GetOS() != Updater::LINUX_64) { throw runtime_error("Command is available only in Linux."); } if (::system("command -v unzip")) { throw runtime_error("The command 'unzip' could not be found. Please install it and try again."); } if (!updater.GetStatus()) { return "You are running the latest version of Crown - " + FormatVersion(CLIENT_VERSION); } if (rpcUpdate.IsStarted()) { return "Download is in progress. Run 'crown-cli update status' to check the status."; } boost::thread t(boost::bind(&RPCUpdate::Install, rpcUpdate)); return "Crown install started. \nRun 'crown-cli update status' to check download status."; } return ""; }
31.207171
110
0.56696
[ "object" ]
caa89591be92e9c7f366b344de20475fe6d07ca0
948
cpp
C++
src/backends/x11/window/event/send.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/x11/window/event/send.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/x11/window/event/send.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#include <awl/exception.hpp> #include <awl/backends/x11/display.hpp> #include <awl/backends/x11/window/base.hpp> #include <awl/backends/x11/window/event/mask.hpp> #include <awl/backends/x11/window/event/object.hpp> #include <awl/backends/x11/window/event/send.hpp> #include <fcppt/text.hpp> #include <fcppt/config/external_begin.hpp> #include <X11/Xlib.h> #include <fcppt/config/external_end.hpp> void awl::backends::x11::window::event::send( awl::backends::x11::window::base const &_window, awl::backends::x11::window::event::mask const _mask, awl::backends::x11::window::event::object const &_event) { if (::XSendEvent( _window.display().get().get(), _window.get(), False, // propagate _mask.get(), // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast<XEvent *>(&_event.get())) == 0) { throw awl::exception{FCPPT_TEXT("XSendEvent() failed!")}; } }
33.857143
66
0.672996
[ "object" ]
caa91ad497fd2777975b35ec890b557ada393c85
2,936
cpp
C++
lib/table/src/record.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/table/src/record.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/table/src/record.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #include <cyng/table/record.h> #include <cyng/factory/factory.hpp> namespace cyng { namespace table { record::record(meta_table_ptr meta) : meta_(meta) , key_() , data_() , generation_(0) {} record::record(meta_table_ptr meta, key_type const& key, data_type const& data, std::uint64_t generation) : meta_(meta) , key_(key) , data_(data) , generation_(generation) {} record::record(record const& rec) : meta_(rec.meta_) , key_(rec.key_) , data_(rec.data_) , generation_(rec.generation_) {} record& record::operator=(record const& other) { if (this != &other) { meta_ = other.meta_; key_ = other.key_; data_ = other.data_; generation_ = other.generation_; } return *this; } bool record::empty() const { return !meta_->check_record(key_, data_); } object record::operator[](std::size_t idx) const { return get(idx); } object record::operator[](std::string col) const { const auto r = meta_->get_record_index(col); return (r.second) ? get(r.first) : make_object() ; } object record::get(std::size_t idx) const { if (meta_->is_key(idx)) { return key_.at(idx); } else if (meta_->is_body(idx)) { // // fix the offset // const auto r = meta_->get_body_index(idx); if (r.second) { return data_.at(r.first); } } return make_object(); } key_type const& record::key() const { return key_; } data_type const& record::data() const { return data_; } std::uint64_t record::get_generation() const { return generation_; } tuple_t record::convert() const { param_map_t key, data; meta_->loop([&](column&& col){ if (col.pk_) { key[col.name_] = get(col.pos_); } else { data[col.name_] = get(col.pos_); } }); // // generation_ is part of the data body // data["gen"] = make_object(generation_); return cyng::tuple_factory(cyng::param_factory("key", key) , cyng::param_factory("data", data)); } tuple_t record::convert(param_map_t const& pm) const { param_map_t key, data; meta_->loop([&](column&& col) { if (col.pk_) { key[col.name_] = get(col.pos_); } else { data[col.name_] = get(col.pos_); } }); // // generation_ is part of the data body // data["gen"] = make_object(generation_); // // additional parameters // std::for_each(pm.begin(), pm.end(), [&data](param_map_value const& val) { data[val.first] = val.second; }); return cyng::tuple_factory(cyng::param_factory("key", key) , cyng::param_factory("data", data)); } tuple_t record::convert_data() const { tuple_t tpl; meta_->loop([&](column&& col) { tpl.push_back(get(col.pos_)); }); return tpl; } } // table }
16.971098
107
0.589237
[ "object" ]
caa9b7b054053c3c8bc303bc22dda31b8ff23fe7
5,625
cpp
C++
src/Object.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
1
2018-04-25T08:43:36.000Z
2018-04-25T08:43:36.000Z
src/Object.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
null
null
null
src/Object.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include "cg/Object.hpp" #include "cg/cg_utils.hpp" #include "utils/exceptions.hpp" namespace obj { const static long double PI = std::acos(-1.0L); scene object::scn = scene(); object::object() : transform(1.0), parent() {} cg::Mat4 object::get_xform() const { if (parent != NULL) { // Do child transform THEN parent to get expected result return parent->get_xform() * transform; } else { return transform; } } cg::Clr3_ptr light::shadow(const cg::Vec3 &position) const { // Return clr (indicating full light). Ambient lights are so easy. :) return cg::Clr3_ptr(new cg::Clr3(this->clr)); } cg::Vec3 light::light_dir(const cg::Vec3 &pos, const cg::Vec3 &nml) const { return -nml; } cg::Clr3_ptr dist_lght::shadow(const cg::Vec3 &position) const { // Compute shadow ray rt::Ray shdwray; shdwray.pos = position; shdwray.dir = this->dir_to_light.normalized(); // Shoot shadow ray double min = 1e8; rt::RayHit_ptr hit; std::shared_ptr<obj::geo> sh_obj; for(auto tmp_obj : this->scn.scene_geo) { rt::RayHit_ptr rh = tmp_obj->trace(shdwray); if(rh) { return cg::Clr3_ptr(); // If we hit something, then we are shadowing, so bail early. if(rh->distance < min) { hit = rh; min = hit->distance; sh_obj = tmp_obj; } } } // Lazily return our parent's implementation for now. return light::shadow(position); } cg::Vec3 dist_lght::light_dir(const cg::Vec3 &pos, const cg::Vec3 &nml) const { return -dir_to_light; } rt::RayHit_ptr geo::trace(const rt::Ray &ray) const { cg::Mat4 xform = this->get_xform(); xform = this->scn.scene_camera->get_cam_xform() * xform; return g->intersect(ray, xform); } cg::Clr3_ptr geo::shade(const rt::Ray &surf, const cg::Vec3 &I) const { // Color to hold result. Init to black. cg::Clr3_ptr rval(new cg::Clr3(0.0)); cg::Clr3 &clr = *rval; // useful constants cg::Vec3 ii = I.normalized(); cg::Vec3 P = surf.pos; cg::Vec3 N = surf.dir.normalized(); for(auto lght_ptr : this->scn.scene_lights) // Compute light contribution { cg::Clr3_ptr unshadowed = lght_ptr->shadow(surf.pos); // If shadow pointer is null, we are fully in shadow, so skip the rest. if(unshadowed) { // Check for ambient light if(typeid(*lght_ptr) == typeid(obj::light)) { clr += *unshadowed * this->g->diffuse; } else { // Compute diffuse cg::Vec3 L = lght_ptr->light_dir(P, N); double NdotL = N.dot(-L.normalized()); double diff = cg::utils::clamp(NdotL, 0.0, 1.0); clr += *unshadowed * this->g->diffuse * diff; // Compute Specular cg::Vec3 R = 2 * (N.dot(L)) * N - L; double phong = std::max(0.0, ii.dot(R)); phong = std::pow(phong, this->g->phong); clr += *unshadowed * this->g->specular * phong; } } } if(this->g->reflect && surf.depth < rt::MAX_RAY_DEPTH) // Whether to compute reflection { //Compute primary ray dir ii = -ii; cg::Vec3 R = 2 * (N.dot(ii)) * N - ii; rt::Ray refl_ray; refl_ray.dir = R.normalized(); refl_ray.pos = P; // Shoot primary ray double min = 1e8; rt::RayHit_ptr hit; std::shared_ptr<obj::geo> hit_obj; for(auto tmp_obj : this->scn.scene_geo) { rt::RayHit_ptr rh = tmp_obj->trace(refl_ray); if(rh) { if(rh->distance < min) { hit = rh; min = hit->distance; hit_obj = tmp_obj; } } } if(hit) { rt::Ray rtmp = hit->data; rtmp.pos += rtmp.dir * 1e-12; rtmp.depth = surf.depth + 1; cg::Clr3_ptr refl_clr = hit_obj->shade(rtmp, R.normalized()); clr += *refl_clr * 0.7; } else { clr += this->scn.scene_camera->bg * this->g->reflection; } } return rval; } void geo::set_geo(cg::geo_ptr g_in) { this->g = g_in; } camera::camera(cg::Vec3 from, cg::Vec3 at, cg::Vec3 up, double fov_in, uint16_t w, uint16_t h, cg::Clr3 bg_clr) : lookfrom(from), lookat(at), lookup(up), fov(fov_in), aspect(double(w)/double(h)), xres(w), yres(h), bg(bg_clr) { this->xform = cg::matrix::lookat(this->lookfrom - this->lookat, this->lookup); this->xform *= cg::matrix::translate(this->lookfrom.x, this->lookfrom.y, this->lookfrom.z); this->xform = cg::matrix::inverted(this->xform); this->angle = std::tan(PI * 0.5 * (this->fov * 2)/180.0); } uint16_t camera::get_width() const { return xres; } uint16_t camera::get_height() const { return yres; } // TODO: Fix primary ray generation rt::Ray_ptr camera::get_ray(float x, float y) const { double invw = 1.0/this->xres, invy = 1.0/this->yres; cg::Vec3 pray; pray.x = (2 * ((x + 0.5) * invw) - 1) * this->angle * this->aspect; pray.y = (1 - 2 * ((y + 0.5) * invy)) * this->angle; pray.z = -1; rt::Ray_ptr rval(new rt::Ray()); rval->dir = pray.normalized(); return rval; } cg::Mat4 camera::get_cam_xform() const { return this->xform; } } // end namespace "obj"
26.913876
96
0.543111
[ "object", "transform" ]
caac5f8e615cbceb0efa18e2121c8ce287589b31
636
cpp
C++
test/training_data/plag_original_codes/12_113.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/12_113.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/12_113.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
// 引用元 : https://atcoder.jp/contests/abc099/submissions/5997146 // 得点 : 300 // コード長 : 531 // 実行時間 : 3 #include<iostream> #include<vector> #include<string> #include<cmath> #include<algorithm> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) int main(){ int N; cin >> N; int ans = N; rep(i, N+1){ int res = 0; int t = i; while(t > 0){ res += t%9; t = t/9; } t = N - i; while(t > 0){ res += t%6; t = t/6; } if(res < ans)ans = res; } cout << int(ans); }
17.189189
63
0.426101
[ "vector" ]
cab016eb077c7ceb48b65a8f27a63a2476aa0b42
2,812
cc
C++
src/lm/kenlm-test.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
36
2019-11-12T22:41:43.000Z
2022-02-01T15:24:02.000Z
src/lm/kenlm-test.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
8
2017-09-06T00:12:00.000Z
2019-03-22T08:03:19.000Z
src/lm/kenlm-test.cc
LanceaKing/kaldi
eb205a83f08fb8056ba1deb03c505ec8b722d4d9
[ "Apache-2.0" ]
29
2020-01-03T22:28:27.000Z
2022-03-30T23:00:27.000Z
#ifdef HAVE_KENLM #include "util/text-utils.h" #include "util/kaldi-io.h" #include "lm/kenlm.h" namespace kaldi { void UnitTestKenLm() { // construct symbol_to_symbol_id to map word string to kaldi symbol index, // in practice, hypothesis is already intergerized, no need for this mapping. std::unordered_map<std::string, int32> symbol_to_symbol_id; std::ifstream symbol_table_stream("test_data/words.txt"); std::string line; while (std::getline(symbol_table_stream, line)) { std::vector<std::string> fields; SplitStringToVector(line, " ", true, &fields); if (fields.size() == 2) { std::string symbol = fields[0]; uint32 symbol_id = -1; ConvertStringToInteger(fields[1], &symbol_id); symbol_to_symbol_id[symbol] = symbol_id; } } // open testing stream, one sentence per line, in raw text form std::ifstream is("test_data/sentences.txt"); KenLm lm; lm.Load("test_data/lm.kenlm", "test_data/words.txt"); KenLmDeterministicOnDemandFst<fst::StdArc> lm_fst(&lm); std::string sentence; while(std::getline(is, sentence)) { std::vector<std::string> words; SplitStringToVector(sentence, " ", true, &words); words.push_back("</s>"); // 1. test KenLm interface: this is only for test purpose, // you should not use kenlm this way in Kaldi. std::string sentence_log = "[KENLM]"; KenLm::State state[2]; KenLm::State* istate = &state[0]; KenLm::State* ostate = &state[1]; lm.SetStateToBeginOfSentence(istate); for (int i = 0; i < words.size(); i++) { std::string word = words[i]; BaseFloat log10_word_score = lm.Score(istate, lm.GetWordIndex(word), ostate); sentence_log += " " + word + "[" + std::to_string(lm.GetWordIndex(word)) + "]=" + std::to_string(-log10_word_score * M_LN10); //convert to -ln() std::swap(istate, ostate); } KALDI_LOG << sentence_log; // 2. test Fst wrapper interface (KenLmDeterministicFst), // this is the recommanded way to interact with Kaldi's Fst framework. sentence_log = "(KALDI)"; KenLmDeterministicOnDemandFst<fst::StdArc>::StateId s = lm_fst.Start(); for (int i = 0; i < words.size(); i++) { int32 symbol_id = symbol_to_symbol_id[words[i]]; sentence_log += " " + words[i] + "(" + std::to_string(symbol_id) + ")="; if (words[i] == "</s>") { sentence_log += std::to_string(lm_fst.Final(s).Value()); } else { fst::StdArc arc; lm_fst.GetArc(s, symbol_id, &arc); s = arc.nextstate; sentence_log += std::to_string(arc.weight.Value()); } } KALDI_LOG << sentence_log; } } } // namespace kaldi int main(int argc, char *argv[]) { using namespace kaldi; UnitTestKenLm(); return 0; } #endif
33.47619
84
0.633357
[ "vector" ]
cab13b822a4baaa6a30eac5185b9f5c2a7bea36f
5,994
cpp
C++
src/shadereditor/src/shadereditor/nodes/vnode_multiply.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/shadereditor/src/shadereditor/nodes/vnode_multiply.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/shadereditor/src/shadereditor/nodes/vnode_multiply.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
 #include "cbase.h" #include "editorCommon.h" CNodeMultiply::CNodeMultiply(CNodeView *p) : BaseClass("Multiply", p) { m_bMatrixRotation = false; GenerateJacks_Input(2); GenerateJacks_Output(1); SetJackFlags_Input(0, HLSLJACKFLAGS_ALL); SetJackFlags_Input(1, HLSLJACKFLAGS_ALL); SetJackFlags_Output(0, HLSLJACKFLAGS_ALL); GetJack_In(0)->SetName("A"); GetJack_In(1)->SetName("B"); } CNodeMultiply::~CNodeMultiply() { } KeyValues *CNodeMultiply::AllocateKeyValues(int NodeIndex) { KeyValues *pKV = BaseClass::AllocateKeyValues(NodeIndex); pKV->SetInt("i_mat_rotation", m_bMatrixRotation ? 1 : 0); return pKV; } void CNodeMultiply::RestoreFromKeyValues_Specific(KeyValues *pKV) { m_bMatrixRotation = pKV->GetInt("i_mat_rotation") != 0; OnUpdateHierachy(NULL, NULL); } int CNodeMultiply::UpdateInputsValid() { int baseLevel = BaseClass::UpdateInputsValid(); int locallevel = ERRORLEVEL_NONE; int vartype_jack_0 = GetJack_In(0)->GetSmartType(); int vartype_jack_1 = GetJack_In(1)->GetSmartType(); int autoTest = TestJackFlags_In(); if (autoTest == ERRORLEVEL_NONE) { if (vartype_jack_0 != vartype_jack_1) { bool bOneIsF1 = (vartype_jack_0 == HLSLVAR_FLOAT1) || (vartype_jack_1 == HLSLVAR_FLOAT1); if (!bOneIsF1) { // unequal types && none is float1 // 3 * 3x3 -> float3 // 3 * 4x3 - append 1 -> float3 // 4 * 4x3 -> float3 // 3 * 4x4 - append 1 -> float4 // 4 * 4x4 -> float4 if (vartype_jack_0 != HLSLVAR_FLOAT3 && vartype_jack_0 != HLSLVAR_FLOAT4 && vartype_jack_0 != HLSLVAR_MATRIX3X3 && vartype_jack_0 != HLSLVAR_MATRIX4X3) locallevel = ERRORLEVEL_FAIL; else if (vartype_jack_0 == HLSLVAR_FLOAT3 && vartype_jack_1 != HLSLVAR_MATRIX3X3 && vartype_jack_1 != HLSLVAR_MATRIX4X3 && vartype_jack_1 != HLSLVAR_MATRIX4X4) locallevel = ERRORLEVEL_FAIL; else if (vartype_jack_0 == HLSLVAR_FLOAT4 && vartype_jack_1 != HLSLVAR_MATRIX4X3 && vartype_jack_1 != HLSLVAR_MATRIX4X4) locallevel = ERRORLEVEL_FAIL; else if (vartype_jack_0 == HLSLVAR_MATRIX3X3 && vartype_jack_1 != HLSLVAR_FLOAT3) locallevel = ERRORLEVEL_FAIL; } } else { // equal types: // 1 * 1 // 2 * 2 // 3 * 3 // 4 * 4 // 3x3 * 3x3 // 4x4 * 4x4 if (vartype_jack_0 == HLSLVAR_MATRIX4X3) locallevel = ERRORLEVEL_FAIL; } } return max(locallevel, baseLevel); } void CNodeMultiply::UpdateOutputs() { if (!GetNumJacks_Out() || !GetNumJacks_In()) return; if (GetErrorLevel() != ERRORLEVEL_NONE) return SetOutputsUndefined(); CJack *pJO = GetJack_Out(0); int vartype_jack_0 = GetJack_In(0)->GetSmartType(); int vartype_jack_1 = GetJack_In(1)->GetSmartType(); int iGoalSmarttype = HLSLVAR_FLOAT4; // matrices out if (vartype_jack_0 == HLSLVAR_MATRIX3X3 && vartype_jack_1 == HLSLVAR_MATRIX3X3) iGoalSmarttype = HLSLVAR_MATRIX3X3; else if (vartype_jack_0 == HLSLVAR_MATRIX4X4 && vartype_jack_1 == HLSLVAR_MATRIX4X4) iGoalSmarttype = HLSLVAR_MATRIX4X4; else if (vartype_jack_0 == HLSLVAR_MATRIX4X3 && vartype_jack_1 == HLSLVAR_MATRIX4X4) iGoalSmarttype = HLSLVAR_MATRIX4X4; // vector out else if (vartype_jack_0 == HLSLVAR_FLOAT1 || vartype_jack_1 == HLSLVAR_FLOAT1) iGoalSmarttype = max(vartype_jack_0, vartype_jack_1); else if (vartype_jack_0 == vartype_jack_1) iGoalSmarttype = vartype_jack_0; // vector transform out else if (vartype_jack_1 == HLSLVAR_MATRIX3X3 || vartype_jack_0 == HLSLVAR_MATRIX3X3 || vartype_jack_1 == HLSLVAR_MATRIX4X3 || (vartype_jack_1 == HLSLVAR_MATRIX4X4 && m_bMatrixRotation)) iGoalSmarttype = HLSLVAR_FLOAT3; return pJO->SetSmartType(iGoalSmarttype); //GetJack_Out( 0 )->SetSmartType( max( GetJack_In(0)->GetSmartType(), GetJack_In(1)->GetSmartType() ) ); } bool CNodeMultiply::CreateSolvers(GenericShaderData *ShaderData) { if (GetNumJacks_In_Connected() < 2) return false; CJack *pJ1 = GetJack_In(0); CJack *pJ2 = GetJack_In(1); CJack *pJ_Out = GetJack_Out(0); int type1 = pJ1->GetSmartType(); int type2 = pJ2->GetSmartType(); const int res = pJ_Out->GetResourceType(); CHLSL_Var *tg = NULL; if (type1 == type2 || type1 == HLSLVAR_FLOAT1 || type2 == HLSLVAR_FLOAT1) tg = GetInputToWriteTo(max(type1, type2)); else if (type1 == HLSLVAR_FLOAT3 && type2 == HLSLVAR_MATRIX3X3) tg = GetInputToWriteTo(HLSLVAR_FLOAT3); else if (type1 == HLSLVAR_FLOAT3 && type2 == HLSLVAR_MATRIX4X3) tg = GetInputToWriteTo(HLSLVAR_FLOAT3); else if (type1 == HLSLVAR_FLOAT4 && type2 == HLSLVAR_MATRIX4X4) tg = GetInputToWriteTo(HLSLVAR_FLOAT4); else if (type1 == HLSLVAR_MATRIX3X3 && type2 == HLSLVAR_FLOAT3) tg = GetInputToWriteTo(HLSLVAR_FLOAT3); SetAllocating(!tg); if (!tg) tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_Multiply *solver = new CHLSL_Solver_Multiply(GetUniqueIndex()); solver->SetMatrixRotationOnly(m_bMatrixRotation); solver->SetResourceType(res); solver->AddSourceVar(pJ1->GetTemporaryVarTarget_End()); solver->AddSourceVar(pJ2->GetTemporaryVarTarget_End()); solver->AddTargetVar(tg); AddSolver(solver); //Msg("add solver has %i src vars\n", solver->GetNumSourceVars()); return true; }
36.108434
108
0.622789
[ "vector", "transform" ]
cab3e7647da82b2398c0ad4b264637b2963fd176
18,962
cc
C++
ui/base/clipboard/clipboard_android.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/base/clipboard/clipboard_android.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/base/clipboard/clipboard_android.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "ui/base/clipboard/clipboard_android.h" #include <algorithm> #include <map> #include <string> #include <utility> #include <vector> #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/callback.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/task/post_task.h" #include "base/thread_annotations.h" #include "base/time/time.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard_constants.h" #include "ui/base/ui_base_jni_headers/Clipboard_jni.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/geometry/size.h" // TODO:(andrewhayden) Support additional formats in Android: Bitmap, URI, HTML, // HTML+text now that Android's clipboard system supports them, then nuke the // legacy implementation note below. // Legacy implementation note: // The Android clipboard system used to only support text format. So we used the // Android system when some text was added or retrieved from the system. For // anything else, we STILL store the value in some process wide static // variable protected by a lock. So the (non-text) clipboard will only work // within the same process. using base::android::AttachCurrentThread; using base::android::ClearException; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; namespace ui { namespace { using ReadImageCallback = ClipboardAndroid::ReadImageCallback; // Fetching image data from Java. SkBitmap GetImageData( const base::android::ScopedJavaGlobalRef<jobject>& clipboard_manager) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> jbitmap = Java_Clipboard_getImage(env, clipboard_manager); if (jbitmap.is_null()) { return SkBitmap(); } gfx::JavaBitmap java_bitmap(jbitmap); if (java_bitmap.size().IsEmpty() || java_bitmap.stride() == 0U || java_bitmap.pixels() == nullptr) { return SkBitmap(); } return gfx::CreateSkBitmapFromJavaBitmap(java_bitmap); } class ClipboardMap { public: ClipboardMap(); void SetModifiedCallback(ClipboardAndroid::ModifiedCallback cb); void SetJavaSideNativePtr(Clipboard* clipboard); std::string Get(const std::string& format); void GetImage(ReadImageCallback callback); uint64_t GetSequenceNumber() const; base::Time GetLastModifiedTime() const; void ClearLastModifiedTime(); bool HasFormat(const std::string& format); std::vector<std::string> GetFormats(); void OnPrimaryClipboardChanged(); void OnPrimaryClipTimestampInvalidated(int64_t timestamp_ms); void Set(const std::string& format, const std::string& data); void CommitToAndroidClipboard(); void Clear(); // Unlike the functions above, does not call |modified_cb_|. void SetLastModifiedTimeWithoutRunningCallback(base::Time time); private: enum class MapState { kOutOfDate, kUpToDate, kPreparingCommit, }; // Updates |last_modified_time_| to |time| and writes it to |local_state_|. void UpdateLastModifiedTime(base::Time time); // Updates |map_| and |map_state_| if necessary by fetching data from Java. void UpdateFromAndroidClipboard(); // TODO(huangdarwin): Refactor this to hold base::string16. std::map<std::string, std::string> map_ GUARDED_BY(lock_); MapState map_state_; // This lock is for read/write |map_|. base::Lock lock_; uint64_t sequence_number_; base::Time last_modified_time_; ClipboardAndroid::ModifiedCallback modified_cb_; // Java class and methods for the Android ClipboardManager. ScopedJavaGlobalRef<jobject> clipboard_manager_; }; base::LazyInstance<ClipboardMap>::Leaky g_map = LAZY_INSTANCE_INITIALIZER; ClipboardMap::ClipboardMap() : map_state_(MapState::kOutOfDate) { clipboard_manager_.Reset(Java_Clipboard_getInstance(AttachCurrentThread())); DCHECK(clipboard_manager_.obj()); } void ClipboardMap::SetModifiedCallback(ClipboardAndroid::ModifiedCallback cb) { modified_cb_ = std::move(cb); } void ClipboardMap::SetJavaSideNativePtr(Clipboard* clipboard) { JNIEnv* env = AttachCurrentThread(); Java_Clipboard_setNativePtr(env, clipboard_manager_, reinterpret_cast<intptr_t>(clipboard)); } std::string ClipboardMap::Get(const std::string& format) { base::AutoLock lock(lock_); UpdateFromAndroidClipboard(); std::map<std::string, std::string>::const_iterator it = map_.find(format); return it == map_.end() ? std::string() : it->second; } void ClipboardMap::GetImage(ReadImageCallback callback) { base::PostTaskAndReplyWithResult( FROM_HERE, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&GetImageData, clipboard_manager_), std::move(callback)); } uint64_t ClipboardMap::GetSequenceNumber() const { return sequence_number_; } base::Time ClipboardMap::GetLastModifiedTime() const { return last_modified_time_; } void ClipboardMap::ClearLastModifiedTime() { UpdateLastModifiedTime(base::Time()); } bool ClipboardMap::HasFormat(const std::string& format) { base::AutoLock lock(lock_); UpdateFromAndroidClipboard(); return base::Contains(map_, format); } std::vector<std::string> ClipboardMap::GetFormats() { base::AutoLock lock(lock_); UpdateFromAndroidClipboard(); std::vector<std::string> formats; formats.reserve(map_.size()); for (const auto& it : map_) formats.push_back(it.first); return formats; } void ClipboardMap::OnPrimaryClipboardChanged() { sequence_number_++; UpdateLastModifiedTime(base::Time::Now()); map_state_ = MapState::kOutOfDate; } void ClipboardMap::OnPrimaryClipTimestampInvalidated(int64_t timestamp_ms) { base::Time timestamp = base::Time::FromJavaTime(timestamp_ms); if (GetLastModifiedTime() < timestamp) { sequence_number_++; UpdateLastModifiedTime(timestamp); map_state_ = MapState::kOutOfDate; } } void ClipboardMap::Set(const std::string& format, const std::string& data) { base::AutoLock lock(lock_); map_[format] = data; map_state_ = MapState::kPreparingCommit; } void ClipboardMap::CommitToAndroidClipboard() { JNIEnv* env = AttachCurrentThread(); base::AutoLock lock(lock_); if (base::Contains(map_, ClipboardFormatType::GetHtmlType().GetName())) { // Android's API for storing HTML content on the clipboard requires a plain- // text representation to be available as well. if (!base::Contains(map_, ClipboardFormatType::GetPlainTextType().GetName())) return; ScopedJavaLocalRef<jstring> html = ConvertUTF8ToJavaString( env, map_[ClipboardFormatType::GetHtmlType().GetName()]); ScopedJavaLocalRef<jstring> text = ConvertUTF8ToJavaString( env, map_[ClipboardFormatType::GetPlainTextType().GetName()]); DCHECK(html.obj() && text.obj()); Java_Clipboard_setHTMLText(env, clipboard_manager_, html, text); } else if (base::Contains( map_, ClipboardFormatType::GetPlainTextType().GetName())) { ScopedJavaLocalRef<jstring> str = ConvertUTF8ToJavaString( env, map_[ClipboardFormatType::GetPlainTextType().GetName()]); DCHECK(str.obj()); Java_Clipboard_setText(env, clipboard_manager_, str); } else { Java_Clipboard_clear(env, clipboard_manager_); // TODO(huangdarwin): Implement raw clipboard support for arbitrary formats. NOTIMPLEMENTED(); } map_state_ = MapState::kUpToDate; sequence_number_++; UpdateLastModifiedTime(base::Time::Now()); } void ClipboardMap::Clear() { JNIEnv* env = AttachCurrentThread(); base::AutoLock lock(lock_); map_.clear(); Java_Clipboard_clear(env, clipboard_manager_); map_state_ = MapState::kUpToDate; sequence_number_++; UpdateLastModifiedTime(base::Time::Now()); } void ClipboardMap::SetLastModifiedTimeWithoutRunningCallback(base::Time time) { last_modified_time_ = time; } // Add a key:jstr pair to map, if jstr is null or is empty, then remove that // entry. void JNI_Clipboard_AddMapEntry(JNIEnv* env, std::map<std::string, std::string>* map, const char* key, const ScopedJavaLocalRef<jstring>& jstr) { if (jstr.is_null()) { map->erase(key); return; } std::string str = ConvertJavaStringToUTF8(env, jstr.obj()); if (!str.empty()) { (*map)[key] = str; } else { map->erase(key); } } void ClipboardMap::UpdateLastModifiedTime(base::Time time) { last_modified_time_ = time; // |modified_cb_| may be null in tests. if (modified_cb_) modified_cb_.Run(time); } void ClipboardMap::UpdateFromAndroidClipboard() { DCHECK_NE(MapState::kPreparingCommit, map_state_); if (map_state_ == MapState::kUpToDate) return; // Fetch the current Android clipboard state. lock_.AssertAcquired(); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> jtext = Java_Clipboard_getCoercedText(env, clipboard_manager_); ScopedJavaLocalRef<jstring> jhtml = Java_Clipboard_getHTMLText(env, clipboard_manager_); ScopedJavaLocalRef<jstring> jimageuri = Java_Clipboard_getImageUriString(env, clipboard_manager_); JNI_Clipboard_AddMapEntry( env, &map_, ClipboardFormatType::GetPlainTextType().GetName().c_str(), jtext); JNI_Clipboard_AddMapEntry( env, &map_, ClipboardFormatType::GetHtmlType().GetName().c_str(), jhtml); JNI_Clipboard_AddMapEntry(env, &map_, kMimeTypeImageURI, jimageuri); map_state_ = MapState::kUpToDate; } } // namespace // Clipboard factory method. // static Clipboard* Clipboard::Create() { return new ClipboardAndroid; } // ClipboardAndroid implementation. void ClipboardAndroid::OnPrimaryClipChanged( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj) { g_map.Get().OnPrimaryClipboardChanged(); } void ClipboardAndroid::OnPrimaryClipTimestampInvalidated( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, const jlong j_timestamp_ms) { g_map.Get().OnPrimaryClipTimestampInvalidated(j_timestamp_ms); } int64_t ClipboardAndroid::GetLastModifiedTimeToJavaTime(JNIEnv* env) { return GetLastModifiedTime().ToJavaTime(); } void ClipboardAndroid::SetModifiedCallback(ModifiedCallback cb) { g_map.Get().SetModifiedCallback(std::move(cb)); } void ClipboardAndroid::SetLastModifiedTimeWithoutRunningCallback( base::Time time) { g_map.Get().SetLastModifiedTimeWithoutRunningCallback(time); } ClipboardAndroid::ClipboardAndroid() { DCHECK(CalledOnValidThread()); g_map.Get().SetJavaSideNativePtr(this); } ClipboardAndroid::~ClipboardAndroid() { DCHECK(CalledOnValidThread()); } void ClipboardAndroid::OnPreShutdown() {} uint64_t ClipboardAndroid::GetSequenceNumber( ClipboardBuffer /* buffer */) const { DCHECK(CalledOnValidThread()); return g_map.Get().GetSequenceNumber(); } bool ClipboardAndroid::IsFormatAvailable(const ClipboardFormatType& format, ClipboardBuffer buffer) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); if (ClipboardFormatType::GetBitmapType().Equals(format)) { return g_map.Get().HasFormat(kMimeTypeImageURI); } return g_map.Get().HasFormat(format.GetName()); } void ClipboardAndroid::Clear(ClipboardBuffer buffer) { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); g_map.Get().Clear(); } void ClipboardAndroid::ReadAvailableTypes(ClipboardBuffer buffer, std::vector<base::string16>* types, bool* contains_filenames) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); if (!types || !contains_filenames) { NOTREACHED(); return; } types->clear(); // would be nice to ask the ClipboardMap to enumerate the types it supports, // rather than hardcode the list here. if (IsFormatAvailable(ClipboardFormatType::GetPlainTextType(), buffer)) types->push_back(base::UTF8ToUTF16(kMimeTypeText)); if (IsFormatAvailable(ClipboardFormatType::GetHtmlType(), buffer)) types->push_back(base::UTF8ToUTF16(kMimeTypeHTML)); // these formats aren't supported by the ClipboardMap currently, but might // be one day? if (IsFormatAvailable(ClipboardFormatType::GetRtfType(), buffer)) types->push_back(base::UTF8ToUTF16(kMimeTypeRTF)); if (IsFormatAvailable(ClipboardFormatType::GetBitmapType(), buffer)) types->push_back(base::UTF8ToUTF16(kMimeTypePNG)); *contains_filenames = false; } std::vector<base::string16> ClipboardAndroid::ReadAvailablePlatformSpecificFormatNames( ClipboardBuffer buffer) const { DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); std::vector<std::string> formats = g_map.Get().GetFormats(); std::vector<base::string16> types; types.reserve(formats.size()); for (const std::string& format : formats) types.push_back(base::UTF8ToUTF16(format)); return types; } void ClipboardAndroid::ReadText(ClipboardBuffer buffer, base::string16* result) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); std::string utf8; ReadAsciiText(buffer, &utf8); *result = base::UTF8ToUTF16(utf8); } void ClipboardAndroid::ReadAsciiText(ClipboardBuffer buffer, std::string* result) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); *result = g_map.Get().Get(ClipboardFormatType::GetPlainTextType().GetName()); } // Note: |src_url| isn't really used. It is only implemented in Windows void ClipboardAndroid::ReadHTML(ClipboardBuffer buffer, base::string16* markup, std::string* src_url, uint32_t* fragment_start, uint32_t* fragment_end) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); if (src_url) src_url->clear(); std::string input = g_map.Get().Get(ClipboardFormatType::GetHtmlType().GetName()); *markup = base::UTF8ToUTF16(input); *fragment_start = 0; *fragment_end = static_cast<uint32_t>(markup->length()); } void ClipboardAndroid::ReadRTF(ClipboardBuffer buffer, std::string* result) const { DCHECK(CalledOnValidThread()); NOTIMPLEMENTED(); } void ClipboardAndroid::ReadImage(ClipboardBuffer buffer, ReadImageCallback callback) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); g_map.Get().GetImage(std::move(callback)); } void ClipboardAndroid::ReadCustomData(ClipboardBuffer buffer, const base::string16& type, base::string16* result) const { DCHECK(CalledOnValidThread()); NOTIMPLEMENTED(); } void ClipboardAndroid::ReadBookmark(base::string16* title, std::string* url) const { DCHECK(CalledOnValidThread()); NOTIMPLEMENTED(); } void ClipboardAndroid::ReadData(const ClipboardFormatType& format, std::string* result) const { DCHECK(CalledOnValidThread()); *result = g_map.Get().Get(format.GetName()); } base::Time ClipboardAndroid::GetLastModifiedTime() const { DCHECK(CalledOnValidThread()); return g_map.Get().GetLastModifiedTime(); } void ClipboardAndroid::ClearLastModifiedTime() { DCHECK(CalledOnValidThread()); g_map.Get().ClearLastModifiedTime(); } // Main entry point used to write several values in the clipboard. void ClipboardAndroid::WritePortableRepresentations(ClipboardBuffer buffer, const ObjectMap& objects) { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); g_map.Get().Clear(); for (const auto& object : objects) DispatchPortableRepresentation(object.first, object.second); g_map.Get().CommitToAndroidClipboard(); } void ClipboardAndroid::WritePlatformRepresentations( ClipboardBuffer buffer, std::vector<Clipboard::PlatformRepresentation> platform_representations) { DCHECK(CalledOnValidThread()); DCHECK_EQ(buffer, ClipboardBuffer::kCopyPaste); g_map.Get().Clear(); DispatchPlatformRepresentations(std::move(platform_representations)); g_map.Get().CommitToAndroidClipboard(); } void ClipboardAndroid::WriteText(const char* text_data, size_t text_len) { g_map.Get().Set(ClipboardFormatType::GetPlainTextType().GetName(), std::string(text_data, text_len)); } void ClipboardAndroid::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { g_map.Get().Set(ClipboardFormatType::GetHtmlType().GetName(), std::string(markup_data, markup_len)); } void ClipboardAndroid::WriteRTF(const char* rtf_data, size_t data_len) { NOTIMPLEMENTED(); } // Note: according to other platforms implementations, this really writes the // URL spec. void ClipboardAndroid::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { g_map.Get().Set(ClipboardFormatType::GetUrlType().GetName(), std::string(url_data, url_len)); } // Write an extra flavor that signifies WebKit was the last to modify the // pasteboard. This flavor has no data. void ClipboardAndroid::WriteWebSmartPaste() { g_map.Get().Set(ClipboardFormatType::GetWebKitSmartPasteType().GetName(), std::string()); } // Note: we implement this to pass all unit tests but it is currently unclear // how some code would consume this. void ClipboardAndroid::WriteBitmap(const SkBitmap& bitmap) { gfx::Size size(bitmap.width(), bitmap.height()); std::string packed(reinterpret_cast<const char*>(&size), sizeof(size)); packed += std::string(static_cast<const char*>(bitmap.getPixels()), bitmap.computeByteSize()); g_map.Get().Set(ClipboardFormatType::GetBitmapType().GetName(), packed); } void ClipboardAndroid::WriteData(const ClipboardFormatType& format, const char* data_data, size_t data_len) { g_map.Get().Set(format.GetName(), std::string(data_data, data_len)); } } // namespace ui
33.383803
80
0.7081
[ "geometry", "object", "vector" ]
cac40f2dccbb161d4caff600dcebf8605c98a7a4
9,787
cpp
C++
computenest-20210601/src/compute_nest_20210601.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-02-01T03:20:23.000Z
2022-01-28T02:13:49.000Z
computenest-20210601/src/compute_nest_20210601.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
4
2021-05-03T08:34:12.000Z
2022-01-28T02:13:33.000Z
computenest-20210601/src/compute_nest_20210601.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-04-02T02:59:04.000Z
2022-02-24T02:33:44.000Z
// This file is auto-generated, don't edit it. Thanks. #include <alibabacloud/compute_nest_20210601.hpp> #include <alibabacloud/endpoint_util.hpp> #include <alibabacloud/open_api.hpp> #include <alibabacloud/open_api_util.hpp> #include <boost/any.hpp> #include <boost/throw_exception.hpp> #include <darabonba/core.hpp> #include <darabonba/util.hpp> #include <iostream> #include <map> #include <vector> using namespace std; using namespace Alibabacloud_ComputeNest20210601; Alibabacloud_ComputeNest20210601::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) { _endpointRule = make_shared<string>("regional"); checkConfig(config); _endpoint = make_shared<string>(getEndpoint(make_shared<string>("computenest"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint)); }; string Alibabacloud_ComputeNest20210601::Client::getEndpoint(shared_ptr<string> productId, shared_ptr<string> regionId, shared_ptr<string> endpointRule, shared_ptr<string> network, shared_ptr<string> suffix, shared_ptr<map<string, string>> endpointMap, shared_ptr<string> endpoint) { if (!Darabonba_Util::Client::empty(endpoint)) { return *endpoint; } if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[regionId]))) { return (*endpointMap)[regionId]; } return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix); } ContinueDeployServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::continueDeployServiceInstanceWithOptions(shared_ptr<ContinueDeployServiceInstanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return ContinueDeployServiceInstanceResponse(doRPCRequest(make_shared<string>("ContinueDeployServiceInstance"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } ContinueDeployServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::continueDeployServiceInstance(shared_ptr<ContinueDeployServiceInstanceRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return continueDeployServiceInstanceWithOptions(request, runtime); } CreateServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::createServiceInstanceWithOptions(shared_ptr<CreateServiceInstanceRequest> tmpReq, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(tmpReq); shared_ptr<CreateServiceInstanceShrinkRequest> request = make_shared<CreateServiceInstanceShrinkRequest>(); Alibabacloud_OpenApiUtil::Client::convert(tmpReq, request); if (!Darabonba_Util::Client::isUnset<map<string, boost::any>>(tmpReq->parameters)) { request->parametersShrink = make_shared<string>(Alibabacloud_OpenApiUtil::Client::arrayToStringWithSpecifiedStyle(tmpReq->parameters, make_shared<string>("Parameters"), make_shared<string>("json"))); } shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return CreateServiceInstanceResponse(doRPCRequest(make_shared<string>("CreateServiceInstance"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } CreateServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::createServiceInstance(shared_ptr<CreateServiceInstanceRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return createServiceInstanceWithOptions(request, runtime); } DeleteServiceInstancesResponse Alibabacloud_ComputeNest20210601::Client::deleteServiceInstancesWithOptions(shared_ptr<DeleteServiceInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return DeleteServiceInstancesResponse(doRPCRequest(make_shared<string>("DeleteServiceInstances"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } DeleteServiceInstancesResponse Alibabacloud_ComputeNest20210601::Client::deleteServiceInstances(shared_ptr<DeleteServiceInstancesRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return deleteServiceInstancesWithOptions(request, runtime); } GetServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::getServiceInstanceWithOptions(shared_ptr<GetServiceInstanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return GetServiceInstanceResponse(doRPCRequest(make_shared<string>("GetServiceInstance"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } GetServiceInstanceResponse Alibabacloud_ComputeNest20210601::Client::getServiceInstance(shared_ptr<GetServiceInstanceRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return getServiceInstanceWithOptions(request, runtime); } ListServiceInstanceLogsResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstanceLogsWithOptions(shared_ptr<ListServiceInstanceLogsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return ListServiceInstanceLogsResponse(doRPCRequest(make_shared<string>("ListServiceInstanceLogs"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } ListServiceInstanceLogsResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstanceLogs(shared_ptr<ListServiceInstanceLogsRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return listServiceInstanceLogsWithOptions(request, runtime); } ListServiceInstanceResourcesResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstanceResourcesWithOptions(shared_ptr<ListServiceInstanceResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return ListServiceInstanceResourcesResponse(doRPCRequest(make_shared<string>("ListServiceInstanceResources"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } ListServiceInstanceResourcesResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstanceResources(shared_ptr<ListServiceInstanceResourcesRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return listServiceInstanceResourcesWithOptions(request, runtime); } ListServiceInstancesResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstancesWithOptions(shared_ptr<ListServiceInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); return ListServiceInstancesResponse(doRPCRequest(make_shared<string>("ListServiceInstances"), make_shared<string>("2021-06-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime)); } ListServiceInstancesResponse Alibabacloud_ComputeNest20210601::Client::listServiceInstances(shared_ptr<ListServiceInstancesRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return listServiceInstancesWithOptions(request, runtime); }
71.437956
279
0.784204
[ "vector" ]
cacb7047994a472cd7ea6dfa1dbd86ba5943ed99
3,664
hh
C++
src/Components/Camera.hh
BoydOrg/BoydEngine
ebe0fae7c70fbf3038f79e6a2c9ba55582ae09da
[ "BSD-3-Clause" ]
1
2021-07-31T14:56:02.000Z
2021-07-31T14:56:02.000Z
src/Components/Camera.hh
BoydOrg/BoydEngine
ebe0fae7c70fbf3038f79e6a2c9ba55582ae09da
[ "BSD-3-Clause" ]
1
2020-01-27T12:42:53.000Z
2020-03-17T17:12:57.000Z
src/Components/Camera.hh
BoydOrg/BoydEngine
ebe0fae7c70fbf3038f79e6a2c9ba55582ae09da
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <entt/entt.hpp> #include <fmt/format.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <limits> #include "../Core/Platform.hh" #include "../Core/Registrar.hh" namespace boyd { namespace comp { /// A 3D camera (pretty much a projection matrix). /// Attach it to an entity with a transform to move it! struct BOYD_API Camera { enum Mode { Persp = 0, Ortho = 1, } mode; float fov; ///< Vertical FOV (*in degrees*) for Persp cameras. float left, right, bottom, top; ///< Left, right, bottom, top for Ortho cameras. float zNear, zFar; ///< Near and far clipping planes. /// Set to +/-infinity on Ortho cameras to get an infinite viewing volume. /// Creates a perspective camera. fov is the vertical FoV *in degrees*. static Camera Perspective(float fov, float zNear = 0.1f, float zFar = 1000.0f) { return {Persp, fov, 0.0f, 0.0f, 0.0f, 0.0f, zNear, zFar}; } /// Creates a orthographic camera. static Camera Orthographic(float left, float right, float bottom, float top, float zNear = -std::numeric_limits<float>::infinity(), float zFar = std::numeric_limits<float>::infinity()) { return {Ortho, 0.0f, left, right, bottom, top, zNear, zFar}; } }; /// Marks a Camera as the currently-active one. /// Attach it to the same entity with the Camera to be made active. using ActiveCamera = entt::tag<"ActiveCamera"_hs>; } // namespace comp template <typename TRegister> struct Registrar<comp::Camera, TRegister> { static constexpr const char *TYPENAME = "Camera"; /// Creates a perspective camera. fov is the horizontal FoV *in degrees*. static comp::Camera Perspective(const comp::Camera *self, float fov, float zNear = 0.1f, float zFar = 1000.0f) { (void)self; return {comp::Camera::Persp, fov, 0.0f, 0.0f, 0.0f, 0.0f, zNear, zFar}; } /// Creates a orthographic camera. static comp::Camera Orthographic(comp::Camera *self, float left, float right, float bottom, float top, float zNear = -std::numeric_limits<float>::infinity(), float zFar = std::numeric_limits<float>::infinity()) { (void)self; return {comp::Camera::Ortho, 0.0f, left, right, bottom, top, zNear, zFar}; } static std::string ToString(const comp::Camera *self) { return fmt::format(FMT_STRING("{} Camera"), self->mode ? "Perspective" : "Orthographic"); } static TRegister Register(TRegister &reg) { // clang-format off return reg.template beginClass<comp::Camera>(TYPENAME) .template addConstructor<void(*)(void)>() .addFunction("perspective", Perspective) .addFunction("ortographic", Orthographic) .addFunction("__tostring", ToString) .endClass(); // clang-format on } }; template <typename TRegister> struct Registrar<comp::ActiveCamera, TRegister> { static constexpr const char *TYPENAME = "ActiveCamera"; static std::string ToString(const comp::ActiveCamera *self) { (void)self; return "ActiveCamera"; } static TRegister Register(TRegister &reg) { // clang-format off return reg.template beginClass<comp::ActiveCamera>(TYPENAME) .template addConstructor<void(*)(void)>() .addFunction("__tostring", ToString) .endClass(); // clang-format on } }; } // namespace boyd
31.86087
114
0.608897
[ "transform", "3d" ]
cad93c8cc0d555cea4de11f8c7c0284c305504f2
2,149
cc
C++
Geometry/HcalCommonData/plugins/HcalDDDSimulationConstantsESModule.cc
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
2
2020-01-21T11:23:39.000Z
2020-01-21T11:23:42.000Z
Geometry/HcalCommonData/plugins/HcalDDDSimulationConstantsESModule.cc
gputtley/cmssw
c1ef8454804e4ebea8b65f59c4a952a6c94fde3b
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
Geometry/HcalCommonData/plugins/HcalDDDSimulationConstantsESModule.cc
p2l1pfp/cmssw
9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
// -*- C++ -*- // // Package: HcalDDDSimulationConstantsESModule // Class: HcalDDDSimulationConstantsESModule // /**\class HcalDDDSimulationConstantsESModule Geometry/HcalCommonData/plugins/HcalDDDSimulationConstantsESModule.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Sunanda Banerjee // Created: Mon Aug 12 16:40:29 PDT 2019 // // #include <memory> #include <FWCore/Framework/interface/ModuleFactory.h> #include <FWCore/Framework/interface/ESProducer.h> #include <FWCore/MessageLogger/interface/MessageLogger.h> #include <Geometry/HcalCommonData/interface/HcalDDDSimulationConstants.h> #include <Geometry/Records/interface/HcalSimNumberingRecord.h> //#define EDM_ML_DEBUG class HcalDDDSimulationConstantsESModule : public edm::ESProducer { public: HcalDDDSimulationConstantsESModule(const edm::ParameterSet&); using ReturnType = std::unique_ptr<HcalDDDSimulationConstants>; static void fillDescriptions(edm::ConfigurationDescriptions&); ReturnType produce(const HcalSimNumberingRecord&); private: edm::ESGetToken<HcalSimulationParameters, HcalParametersRcd> parSimToken_; }; HcalDDDSimulationConstantsESModule::HcalDDDSimulationConstantsESModule(const edm::ParameterSet&) { #ifdef EDM_ML_DEBUG edm::LogVerbatim("HcalGeom") << "constructing HcalDDDSimulationConstantsESModule"; #endif auto cc = setWhatProduced(this); parSimToken_ = cc.consumesFrom<HcalSimulationParameters, HcalParametersRcd>(edm::ESInputTag{}); } void HcalDDDSimulationConstantsESModule::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; descriptions.add("hcalDDDSimulationConstants", desc); } // ------------ method called to produce the data ------------ HcalDDDSimulationConstantsESModule::ReturnType HcalDDDSimulationConstantsESModule::produce( const HcalSimNumberingRecord& iRecord) { const auto& parSim = iRecord.get(parSimToken_); return std::make_unique<HcalDDDSimulationConstants>(&parSim); } //define this as a plug-in DEFINE_FWK_EVENTSETUP_MODULE(HcalDDDSimulationConstantsESModule);
32.560606
114
0.793392
[ "geometry" ]
cadc885b9f689db9ce971d0e8905b8890508921c
3,522
cpp
C++
wav/src/v20210129/model/ExternalUserMappingInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
wav/src/v20210129/model/ExternalUserMappingInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
wav/src/v20210129/model/ExternalUserMappingInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/wav/v20210129/model/ExternalUserMappingInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Wav::V20210129::Model; using namespace std; ExternalUserMappingInfo::ExternalUserMappingInfo() : m_corpExternalUserIdHasBeenSet(false), m_externalUserIdHasBeenSet(false) { } CoreInternalOutcome ExternalUserMappingInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("CorpExternalUserId") && !value["CorpExternalUserId"].IsNull()) { if (!value["CorpExternalUserId"].IsString()) { return CoreInternalOutcome(Core::Error("response `ExternalUserMappingInfo.CorpExternalUserId` IsString=false incorrectly").SetRequestId(requestId)); } m_corpExternalUserId = string(value["CorpExternalUserId"].GetString()); m_corpExternalUserIdHasBeenSet = true; } if (value.HasMember("ExternalUserId") && !value["ExternalUserId"].IsNull()) { if (!value["ExternalUserId"].IsString()) { return CoreInternalOutcome(Core::Error("response `ExternalUserMappingInfo.ExternalUserId` IsString=false incorrectly").SetRequestId(requestId)); } m_externalUserId = string(value["ExternalUserId"].GetString()); m_externalUserIdHasBeenSet = true; } return CoreInternalOutcome(true); } void ExternalUserMappingInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_corpExternalUserIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CorpExternalUserId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_corpExternalUserId.c_str(), allocator).Move(), allocator); } if (m_externalUserIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExternalUserId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_externalUserId.c_str(), allocator).Move(), allocator); } } string ExternalUserMappingInfo::GetCorpExternalUserId() const { return m_corpExternalUserId; } void ExternalUserMappingInfo::SetCorpExternalUserId(const string& _corpExternalUserId) { m_corpExternalUserId = _corpExternalUserId; m_corpExternalUserIdHasBeenSet = true; } bool ExternalUserMappingInfo::CorpExternalUserIdHasBeenSet() const { return m_corpExternalUserIdHasBeenSet; } string ExternalUserMappingInfo::GetExternalUserId() const { return m_externalUserId; } void ExternalUserMappingInfo::SetExternalUserId(const string& _externalUserId) { m_externalUserId = _externalUserId; m_externalUserIdHasBeenSet = true; } bool ExternalUserMappingInfo::ExternalUserIdHasBeenSet() const { return m_externalUserIdHasBeenSet; }
31.446429
160
0.736513
[ "model" ]
cade179cbe46e74c49e7939acfda82875400b91a
1,766
cc
C++
tools/src/file_mask.cc
lechaosx/light-field-image-format
8d6270a32ccd246fcf6035379827ca1a4a0bf42a
[ "BSD-2-Clause" ]
1
2021-11-26T06:25:08.000Z
2021-11-26T06:25:08.000Z
tools/src/file_mask.cc
lechaosx/light-field-image-format
8d6270a32ccd246fcf6035379827ca1a4a0bf42a
[ "BSD-2-Clause" ]
null
null
null
tools/src/file_mask.cc
lechaosx/light-field-image-format
8d6270a32ccd246fcf6035379827ca1a4a0bf42a
[ "BSD-2-Clause" ]
1
2019-08-09T15:34:47.000Z
2019-08-09T15:34:47.000Z
/******************************************************************************\ * SOUBOR: file_mask.cc * AUTOR: Drahomir Dlabaja (xdlaba02) \******************************************************************************/ #include "file_mask.h" #include <cmath> #include <iomanip> FileMask::FileMask(const std::string &input_file_mask): m_filename_mask{input_file_mask}, m_mask_indexes{} { for (size_t i = 0; m_filename_mask[i] != '\0'; i++) { if (m_filename_mask[i] == '#') { m_mask_indexes.push_back(i); } } } std::string FileMask::operator [](size_t index) const { std::string file_name {m_filename_mask}; std::stringstream image_number {}; image_number << std::setw(m_mask_indexes.size()) << std::setfill('0') << std::to_string(index); for (size_t i = 0; i < m_mask_indexes.size(); i++) { file_name[m_mask_indexes[i]] = image_number.str()[i]; } return file_name; } size_t FileMask::count() { return pow(10, m_mask_indexes.size()); } size_t get_mask_names_count(const std::string &mask, char masking_char) { size_t cnt {}; for (size_t i = 0; mask[i] != '\0'; i++) { if (mask[i] == masking_char) { cnt++; } } return pow(10, cnt); } std::string get_name_from_mask(const std::string &mask, char masking_char, size_t index) { std::vector<size_t> mask_indices {}; std::stringstream image_number {}; std::string name { mask }; for (size_t i = 0; mask[i] != '\0'; i++) { if (mask[i] == masking_char) { mask_indices.push_back(i); } } image_number << std::setw(mask_indices.size()) << std::setfill('0') << std::to_string(index); for (size_t i = 0; i < mask_indices.size(); i++) { name[mask_indices[i]] = image_number.str()[i]; } return name; }
26.358209
108
0.570781
[ "vector" ]
cade69a6f95dd3495064af1db4129abbd19bf465
1,465
cpp
C++
sorting.cpp
agentcox/TheAgencyRazorOne
5b8c8e50061caefe44345f86fc4df2a2a795441c
[ "MIT" ]
null
null
null
sorting.cpp
agentcox/TheAgencyRazorOne
5b8c8e50061caefe44345f86fc4df2a2a795441c
[ "MIT" ]
null
null
null
sorting.cpp
agentcox/TheAgencyRazorOne
5b8c8e50061caefe44345f86fc4df2a2a795441c
[ "MIT" ]
null
null
null
#include "agencyinclude.h" #include "guns.h" int SortCompareWeaponArmory(PPOTYPE WOne, PPOTYPE WTwo) { if(!WOne ||!WTwo){ return 0; } if(WOne->weapon.filingtype != WTwo->weapon.filingtype) { return WTwo->weapon.filingtype - WOne->weapon.filingtype; } else if(WOne->weapon.classtype != WTwo->weapon.classtype) { return WTwo->weapon.classtype - WOne->weapon.classtype; } else return (strcmp(WTwo->weapon.longname, WOne->weapon.longname)); } void SwapWeaponIndex(PPOTYPE WOne, PPOTYPE WTwo) { int temp; if(WOne && WTwo){ temp = WTwo->weapon.index; WTwo->weapon.index = WOne->weapon.index; WOne->weapon.index = temp; } } void SwapWeaponID(PPOTYPE WOne, PPOTYPE WTwo) { int temp; if(WOne && WTwo){ temp = WTwo->weapon.id; WTwo->weapon.id = WOne->weapon.id; WOne->weapon.id = temp; } } void SortArmoryWeapons(PLIST armorylist) { sortList(armorylist, SortCompareWeaponArmory, NULL, CompareWeaponID); ReorderWeaponArmoryIDs(armorylist); } void SortPersonalWeapons(PLIST weaponlist) { sortList(weaponlist, SortCompareWeaponArmory, SwapWeaponIndex, CompareWeaponIndex); } void ReorderWeaponArmoryIDs(PLIST armorylist) { int counter = 1; if(!armorylist){ return; } PLIST walker = armorylist; for(walker->current = walker->head; walker->current != NULL; walker->current = walker->current->nextnode) { walker->current->object.weapon.id = counter; counter++; } }
21.544118
107
0.690785
[ "object" ]
cae8ba23e4c236a425e2163b221e920f64f157ac
2,987
cpp
C++
VNS Implementierung/VNS Implementierung/UpdateXij.cpp
franneck94/Variable-Neighborhood-Search-FLP
891cea0be1c3250cd9990eb35ef5701cb20bf964
[ "MIT" ]
1
2019-10-05T08:26:52.000Z
2019-10-05T08:26:52.000Z
VNS Implementierung/VNS Implementierung/UpdateXij.cpp
franneck94/Variable-Neighborhood-Search-FLP
891cea0be1c3250cd9990eb35ef5701cb20bf964
[ "MIT" ]
1
2018-05-28T09:54:53.000Z
2018-05-28T09:54:53.000Z
VNS Implementierung/VNS Implementierung/UpdateXij.cpp
franneck94/Variable-Neighborhood-Search-FLP
891cea0be1c3250cd9990eb35ef5701cb20bf964
[ "MIT" ]
2
2019-10-05T08:26:59.000Z
2020-05-02T09:21:54.000Z
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <tuple> #include <random> #include <iterator> #include <numeric> #include <boost/numeric/ublas/storage.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublas/io.hpp> #include "VNS.hpp" #include "MODI.hpp" #include "Solution.hpp" #include "Helper.hpp" using namespace std; using namespace t_simplex; namespace ublas = boost::numeric::ublas; /*********************************************************************************/ /* UPDATE XIJ PROCEDURES */ /*********************************************************************************/ // CFLP with Modi procedure (gets optimal solution in deterministic time) bool VNS::updateXij( ublas::matrix<double> &cij, const vector<double> &dj, const vector<double> &bi, const vector<bool> &yi, const unsigned int &update_xij_mode, double &fx) { if (!canUpdateXij(bi, yi, m_sum_dj)) return false; unsigned int open_facilities = 0, i_out = 0, flow_vars = 0; double transportation_cost = 0.0, gap = 0.0, sum_bi = 0.0; bool check = false; open_facilities = accumulate(yi.begin(), yi.end(), 0); ublas::matrix<double> custom_cij(open_facilities, m_customerNumber, 0.0); int *customers = new int[m_customerNumber]; double *demand = new double[m_customerNumber]; int *facilities = new int[open_facilities]; double *capacity = new double[open_facilities]; for (size_t j = 0; j != cij.size2(); ++j) { customers[j] = j; demand[j] = dj[j]; } for (size_t i = 0; i != cij.size1(); ++i) { if (yi[i] == 1) { facilities[i_out] = i; capacity[i_out] = bi[i]; sum_bi += bi[i]; ublas::matrix_row<ublas::matrix<double>> row_custom_cij(custom_cij, i_out); ublas::matrix_row<ublas::matrix<double>> row_cij(cij, i); row_custom_cij = row_cij; i_out++; } } // Signature of Facilities and Customers TsSignature *facility = new TsSignature(open_facilities, facilities, capacity); TsSignature *customer = new TsSignature(m_customerNumber, customers, demand); // Save Stepping Stone Path TsFlow *flow = new TsFlow[open_facilities + m_customerNumber - 1]; // Result value transportation_cost = t_simplex::transportSimplex(update_xij_mode, custom_cij, flow, &flow_vars, facility, customer ,m_sum_dj, sum_bi, dj); // f(x) and Return Value fx = f(yi, m_fi, transportation_cost); // Flow Xij for checkSolution m_flow_tpl.resize(flow_vars); for (size_t i = 0; i < flow_vars; ++i) m_flow_tpl[i] = make_tuple(facilities[flow[i].from], flow[i].to, flow[i].amount); check = checkSolution(yi, m_flow_tpl, flow_vars, cij, bi, dj, m_sum_dj); delete[] capacity; capacity = NULL; delete[] demand; demand = NULL; delete[] facilities; facilities = NULL; delete[] customers; customers = NULL; delete facility; facility = NULL; delete customer; customer = NULL; return check; }
27.40367
86
0.655172
[ "vector" ]
caeaeeffa747cd1b0931c64b61b0d07bd9186c10
4,745
hpp
C++
src/sparse/fronts/FrontalMatrixHODLRMPI.hpp
sarahorsak/STRUMPACK
1c23ba83a07082b3bce5cf7092e990c71af0ee67
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/sparse/fronts/FrontalMatrixHODLRMPI.hpp
sarahorsak/STRUMPACK
1c23ba83a07082b3bce5cf7092e990c71af0ee67
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/sparse/fronts/FrontalMatrixHODLRMPI.hpp
sarahorsak/STRUMPACK
1c23ba83a07082b3bce5cf7092e990c71af0ee67
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* * STRUMPACK -- STRUctured Matrices PACKage, Copyright (c) 2014, The * Regents of the University of California, through Lawrence Berkeley * National Laboratory (subject to receipt of any required approvals * from the U.S. Dept. of Energy). All rights reserved. * * If you have questions about your rights to use or distribute this * software, please contact Berkeley Lab's Technology Transfer * Department at TTD@lbl.gov. * * NOTICE. This software is owned by the U.S. Department of Energy. As * such, the U.S. Government has been granted for itself and others * acting on its behalf a paid-up, nonexclusive, irrevocable, * worldwide license in the Software to reproduce, prepare derivative * works, and perform publicly and display publicly. Beginning five * (5) years after the date permission to assert copyright is obtained * from the U.S. Department of Energy, and subject to any subsequent * five (5) year renewals, the U.S. Government igs granted for itself * and others acting on its behalf a paid-up, nonexclusive, * irrevocable, worldwide license in the Software to reproduce, * prepare derivative works, distribute copies to the public, perform * publicly and display publicly, and to permit others to do so. * * Developers: Pieter Ghysels, Francois-Henry Rouet, Xiaoye S. Li. * (Lawrence Berkeley National Lab, Computational Research * Division). * */ #ifndef FRONTAL_MATRIX_HODLR_MPI_HPP #define FRONTAL_MATRIX_HODLR_MPI_HPP #include "FrontalMatrixMPI.hpp" #include "HODLR/HODLRMatrix.hpp" #include "HODLR/ButterflyMatrix.hpp" #define STRUMPACK_PERMUTE_CB namespace strumpack { template<typename scalar_t,typename integer_t> class FrontalMatrixHODLRMPI : public FrontalMatrixMPI<scalar_t,integer_t> { using SpMat_t = CompressedSparseMatrix<scalar_t,integer_t>; using F_t = FrontalMatrix<scalar_t,integer_t>; using FMPI_t = FrontalMatrixMPI<scalar_t,integer_t>; using DenseM_t = DenseMatrix<scalar_t>; using DistM_t = DistributedMatrix<scalar_t>; using DistMW_t = DistributedMatrixWrapper<scalar_t>; using Opts_t = SPOptions<scalar_t>; using VecVec_t = std::vector<std::vector<std::size_t>>; public: FrontalMatrixHODLRMPI (integer_t sep, integer_t sep_begin, integer_t sep_end, std::vector<integer_t>& upd, const MPIComm& comm, int _total_procs); FrontalMatrixHODLRMPI(const FrontalMatrixHODLRMPI&) = delete; FrontalMatrixHODLRMPI& operator=(FrontalMatrixHODLRMPI const&) = delete; void release_work_memory() override; void sample_CB (Trans op, const DistM_t& R, DistM_t& S, F_t* pa) const override; void sample_children_CB(Trans op, const DistM_t& R, DistM_t& S); void skinny_extend_add(DistM_t& cSl, DistM_t& cSr, DistM_t& S); void multifrontal_factorization (const SpMat_t& A, const Opts_t& opts, int etree_level=0, int task_depth=0) override; void forward_multifrontal_solve (DenseM_t& bloc, DistM_t* bdist, DistM_t& bupd, DenseM_t& seqbupd, int etree_level=0) const override; void backward_multifrontal_solve (DenseM_t& yloc, DistM_t* ydist, DistM_t& yupd, DenseM_t& seqyupd, int etree_level=0) const override; long long node_factor_nonzeros() const; integer_t maximum_rank(int task_depth) const; std::string type() const override { return "FrontalMatrixHODLRMPI"; } void extract_CB_sub_matrix_2d (const std::vector<std::vector<std::size_t>>& I, const std::vector<std::vector<std::size_t>>& J, std::vector<DistM_t>& B) const override; void partition (const Opts_t& opts, const SpMat_t& A, integer_t* sorder, bool is_root=true, int task_depth=0) override; private: HODLR::HODLRMatrix<scalar_t> F11_; HODLR::ButterflyMatrix<scalar_t> F12_, F21_; std::unique_ptr<HODLR::HODLRMatrix<scalar_t>> F22_; HSS::HSSPartitionTree sep_tree_; #if defined(STRUMPACK_PERMUTE_CB) std::vector<integer_t> CB_perm_, CB_iperm_; #endif void construct_hierarchy(const SpMat_t& A, const Opts_t& opts); void compress_sampling(const SpMat_t& A, const Opts_t& opts); void compress_extraction(const SpMat_t& A, const Opts_t& opts); void compress_flops_F11(); void compress_flops_F12_F21(); void compress_flops_F22(); void compress_flops_Schur(long long int invf11_mult_flops); using F_t::lchild_; using F_t::rchild_; using F_t::sep_begin_; using F_t::sep_end_; using F_t::dim_sep; using F_t::dim_upd; using F_t::dim_blk; using FMPI_t::visit; using FMPI_t::grid; using FMPI_t::Comm; template<typename _scalar_t,typename _integer_t> friend class ExtendAdd; }; } // end namespace strumpack #endif // FRONTAL_MATRIX_HODLR_MPI_HPP
38.577236
77
0.738672
[ "vector" ]
caf05a82b0de86410b83758199d75fbc48603fc0
21,131
cc
C++
src/meas/base/SincCoeffs.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/meas/base/SincCoeffs.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
src/meas/base/SincCoeffs.cc
DarkEnergySurvey/cosmicRays
5c29bd9fc4a9f37e298e897623ec98fff4a8d539
[ "NCSA" ]
null
null
null
// -*- lsst-c++ -*- /* * LSST Data Management System * Copyright 2008-2013 LSST Corporation. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ #include <complex> #include "boost/math/special_functions/bessel.hpp" #include "boost/shared_array.hpp" #include "fftw3.h" #include "lsst/meas/base/SincCoeffs.h" #include "lsst/geom/Angle.h" #include "lsst/geom/Extent.h" #include "lsst/afw/image/Image.h" #include "lsst/afw/math/Integrate.h" namespace lsst { namespace meas { namespace base { namespace { // Convenient wrapper for a Bessel function inline double J1(double const x) { return boost::math::cyl_bessel_j(1, x); } // sinc function template <typename T> inline T sinc(T const x) { return (x != 0.0) ? (std::sin(x) / x) : 1.0; } /* * Define a circular aperture function object g_i, cos-tapered? */ template <typename CoordT> class CircularAperture { public: CircularAperture( CoordT const radius1, ///< inner radius of the aperture CoordT const radius2, ///< outer radius of the aperture CoordT const taperwidth ///< width to cosine taper from 1.0 to 0.0 (ie. 0.5*cosine period) ) : _radius1(radius1), _radius2(radius2), _taperwidth1(taperwidth), _taperwidth2(taperwidth), _k1(1.0 / (2.0 * taperwidth)), _k2(1.0 / (2.0 * taperwidth)), _taperLo1(radius1 - 0.5 * taperwidth), _taperHi1(radius1 + 0.5 * taperwidth), _taperLo2(radius2 - 0.5 * taperwidth), _taperHi2(radius2 + 0.5 * taperwidth) { // if we're asked for a radius smaller than our taperwidth, // adjust the taper width smaller so it fits exactly // with smooth derivative=0 at r=0 if (_radius1 > _radius2) { throw LSST_EXCEPT( pex::exceptions::InvalidParameterError, (boost::format("rad2 less than rad1: (rad1=%.2f, rad2=%.2f) ") % _radius1 % _radius2) .str()); } if (_radius1 < 0.0 || _radius2 < 0.0) { throw LSST_EXCEPT( pex::exceptions::InvalidParameterError, (boost::format("radii must be >= 0 (rad1=%.2f, rad2=%.2f) ") % _radius1 % _radius2) .str()); } if (_radius1 == 0) { _taperwidth1 = 0.0; _k1 = 0.0; } // if we don't have room to taper at r=0 if (_radius1 < 0.5 * _taperwidth1) { _taperwidth1 = 2.0 * _radius1; _k1 = 1.0 / (2.0 * _taperwidth1); } // if we don't have room to taper between r1 and r2 if ((_radius2 - _radius1) < 0.5 * (_taperwidth1 + _taperwidth2)) { // if we *really* don't have room ... taper1 by itself is too big // - set taper1,2 to be equal and split the r2-r1 range if ((_radius2 - _radius2) < 0.5 * _taperwidth1) { _taperwidth1 = _taperwidth2 = 0.5 * (_radius2 - _radius1); _k1 = _k2 = 1.0 / (2.0 * _taperwidth1); // if there's room for taper1, but not taper1 and 2 } else { _taperwidth2 = _radius2 - _radius1 - _taperwidth1; _k2 = 1.0 / (2.0 * _taperwidth2); } _taperLo1 = _radius1 - 0.5 * _taperwidth1; _taperHi1 = _radius1 + 0.5 * _taperwidth1; _taperLo2 = _radius2 - 0.5 * _taperwidth2; _taperHi2 = _radius2 + 0.5 * _taperwidth2; } } // When called, return the throughput at the requested x,y // todo: replace the sinusoid taper with a band-limited CoordT operator()(CoordT const x, CoordT const y) const { CoordT const xyrad = std::sqrt(x * x + y * y); if (xyrad < _taperLo1) { return 0.0; } else if (xyrad >= _taperLo1 && xyrad <= _taperHi1) { return 0.5 * (1.0 + std::cos((geom::TWOPI * _k1) * (xyrad - _taperHi1))); } else if (xyrad > _taperHi1 && xyrad <= _taperLo2) { return 1.0; } else if (xyrad > _taperLo2 && xyrad <= _taperHi2) { return 0.5 * (1.0 + std::cos((geom::TWOPI * _k2) * (xyrad - _taperLo2))); } else { return 0.0; } } CoordT getRadius1() { return _radius1; } CoordT getRadius2() { return _radius2; } private: CoordT _radius1, _radius2; CoordT _taperwidth1, _taperwidth2; CoordT _k1, _k2; // the angular wavenumber corresponding to a cosine with wavelength 2*taperwidth CoordT _taperLo1, _taperHi1; CoordT _taperLo2, _taperHi2; }; template <typename CoordT> class CircApPolar : public std::unary_function<CoordT, CoordT> { public: CircApPolar(double radius, double taperwidth) : _ap(CircularAperture<CoordT>(0.0, radius, taperwidth)) {} CoordT operator()(double r) const { return r * _ap(r, 0.0); } private: CircularAperture<CoordT> _ap; }; /* * Define a Sinc functor to be integrated over for Sinc interpolation */ template <typename IntegrandT> class SincAperture : public std::binary_function<IntegrandT, IntegrandT, IntegrandT> { public: SincAperture(CircularAperture<IntegrandT> const& ap, int const ix, // sinc center x int const iy // sinc center y ) : _ap(ap), _ix(ix), _iy(iy) {} IntegrandT operator()(IntegrandT const x, IntegrandT const y) const { double const fourierConvention = geom::PI; double const dx = fourierConvention * (x - _ix); double const dy = fourierConvention * (y - _iy); double const fx = sinc<double>(dx); double const fy = sinc<double>(dy); return (1.0 + _ap(x, y) * fx * fy); } private: CircularAperture<IntegrandT> const& _ap; double _ix, _iy; }; class GaussPowerFunctor : public std::binary_function<double, double, double> { public: GaussPowerFunctor(double sigma) : _sigma(sigma) {} double operator()(double kx, double ky) const { double const k = ::sqrt(kx * kx + ky * ky); double const gauss = ::exp(-0.5 * k * k * _sigma * _sigma); return gauss * gauss; } private: double _sigma; }; std::pair<double, double> computeGaussLeakage(double const sigma) { GaussPowerFunctor gaussPower(sigma); double lim = geom::PI; // total power: integrate GaussPowerFunctor -inf<x<inf, -inf<y<inf (can be done analytically) double powerInf = geom::PI / (sigma * sigma); // true power: integrate GaussPowerFunctor -lim<x<lim, -lim<y<lim (must be done numerically) double truePower = afw::math::integrate2d(gaussPower, -lim, lim, -lim, lim, 1.0e-8); double trueLeak = (powerInf - truePower) / powerInf; // estimated power: function is circular, but coords are cartesian // - true power does the actual integral numerically, but we can estimate it by integrating // in polar coords over lim <= radius < infinity. The integral is analytic. double estLeak = ::exp(-sigma * sigma * geom::PI * geom::PI) / powerInf; return std::pair<double, double>(trueLeak, estLeak); } template <typename PixelT> std::shared_ptr<afw::image::Image<PixelT>> calcImageRealSpace(double const rad1, double const rad2, double const taperwidth) { PixelT initweight = 0.0; // initialize the coeff values int log2 = static_cast<int>(::ceil(::log10(2.0 * rad2) / log10(2.0))); if (log2 < 3) { log2 = 3; } int hwid = pow(2, log2); int width = 2 * hwid - 1; int const xwidth = width; int const ywidth = width; int const x0 = -xwidth / 2; int const y0 = -ywidth / 2; // create an image to hold the coefficient image auto coeffImage = std::make_shared<afw::image::Image<PixelT>>(geom::ExtentI(xwidth, ywidth), initweight); coeffImage->setXY0(x0, y0); // create the aperture function object // determine the radius to use that makes 'radius' the effective radius of the aperture double tolerance = 1.0e-12; double dr = 1.0e-6; double err = 2.0 * tolerance; double apEff = geom::PI * rad2 * rad2; double radIn = rad2; int maxIt = 20; int i = 0; while (err > tolerance && i < maxIt) { CircApPolar<double> apPolar1(radIn, taperwidth); CircApPolar<double> apPolar2(radIn + dr, taperwidth); double a1 = geom::TWOPI * afw::math::integrate(apPolar1, 0.0, radIn + taperwidth, tolerance); double a2 = geom::TWOPI * afw::math::integrate(apPolar2, 0.0, radIn + dr + taperwidth, tolerance); double dadr = (a2 - a1) / dr; double radNew = radIn - (a1 - apEff) / dadr; err = (a1 - apEff) / apEff; radIn = radNew; i++; } CircularAperture<double> ap(rad1, rad2, taperwidth); /* ******************************* */ // integrate over the aperture // the limits of the integration over the sinc aperture double const limit = rad2 + taperwidth; double const x1 = -limit; double const x2 = limit; double const y1 = -limit; double const y2 = limit; for (int iY = y0; iY != y0 + coeffImage->getHeight(); ++iY) { int iX = x0; typename afw::image::Image<PixelT>::x_iterator end = coeffImage->row_end(iY - y0); for (typename afw::image::Image<PixelT>::x_iterator ptr = coeffImage->row_begin(iY - y0); ptr != end; ++ptr) { // create a sinc function in the CircularAperture at our location SincAperture<double> sincAp(ap, iX, iY); // integrate the sinc PixelT integral = afw::math::integrate2d(sincAp, x1, x2, y1, y2, 1.0e-8); // we actually integrated function+1.0 and now must subtract the excess volume // - just force it to zero in the corners double const dx = iX; double const dy = iY; *ptr = (std::sqrt(dx * dx + dy * dy) < xwidth / 2) ? integral - (x2 - x1) * (y2 - y1) : 0.0; ++iX; } } double sum = 0.0; for (int iY = y0; iY != y0 + coeffImage->getHeight(); ++iY) { typename afw::image::Image<PixelT>::x_iterator end = coeffImage->row_end(iY - y0); for (typename afw::image::Image<PixelT>::x_iterator ptr = coeffImage->row_begin(iY - y0); ptr != end; ++ptr) { sum += *ptr; } } #if 0 // debugging coeffImage->writeFits("cimage.fits"); #endif return coeffImage; } class FftShifter { public: FftShifter(int xwid) : _xwid(xwid) {} int shift(int x) { if (x >= _xwid / 2) { return x - _xwid / 2; } else { return x + _xwid / 2 + 1; } } private: int _xwid; }; std::pair<double, double> rotate(double x, double y, double angle) { double c = ::cos(angle); double s = ::sin(angle); return std::pair<double, double>(x * c + y * s, -x * s + y * c); } /* todo * - try sub pixel shift if it doesn't break even symmetry * - put values directly in an Image * - precompute the plan */ template <typename PixelT> std::shared_ptr<afw::image::Image<PixelT>> calcImageKSpaceCplx(double const rad1, double const rad2, double const posAng, double const ellipticity) { // we only need a half-width due to symmetry // make the hwid 2*rad2 so we have some buffer space and round up to the next power of 2 int log2 = static_cast<int>(::ceil(::log10(2.0 * rad2) / log10(2.0))); if (log2 < 3) { log2 = 3; } int hwid = pow(2, log2); int wid = 2 * hwid - 1; int xcen = wid / 2, ycen = wid / 2; FftShifter fftshift(wid); boost::shared_array<std::complex<double>> cimg(new std::complex<double>[wid * wid]); std::complex<double>* c = cimg.get(); // fftplan args: nx, ny, *in, *out, direction, flags // - done in-situ if *in == *out fftw_plan plan = fftw_plan_dft_2d(wid, wid, reinterpret_cast<fftw_complex*>(c), reinterpret_cast<fftw_complex*>(c), FFTW_BACKWARD, FFTW_ESTIMATE); // compute the k-space values and put them in the cimg array double const twoPiRad1 = geom::TWOPI * rad1; double const twoPiRad2 = geom::TWOPI * rad2; double const scale = (1.0 - ellipticity); for (int iY = 0; iY < wid; ++iY) { int const fY = fftshift.shift(iY); double const ky = (static_cast<double>(iY) - ycen) / wid; for (int iX = 0; iX < wid; ++iX) { int const fX = fftshift.shift(iX); double const kx = static_cast<double>(iX - xcen) / wid; // rotate std::pair<double, double> coo = rotate(kx, ky, posAng); double kxr = coo.first; double kyr = coo.second; // rescale double const k = ::sqrt(kxr * kxr + scale * scale * kyr * kyr); double const airy1 = (rad1 > 0 ? rad1 * J1(twoPiRad1 * k) : 0.0) / k; double const airy2 = rad2 * J1(twoPiRad2 * k) / k; double const airy = airy2 - airy1; c[fY * wid + fX] = std::complex<double>(scale * airy, 0.0); } } c[0] = scale * geom::PI * (rad2 * rad2 - rad1 * rad1); // perform the fft and clean up after ourselves fftw_execute(plan); fftw_destroy_plan(plan); // put the coefficients into an image auto coeffImage = std::make_shared<afw::image::Image<PixelT>>(geom::ExtentI(wid, wid), 0.0); for (int iY = 0; iY != coeffImage->getHeight(); ++iY) { int iX = 0; typename afw::image::Image<PixelT>::x_iterator end = coeffImage->row_end(iY); for (typename afw::image::Image<PixelT>::x_iterator ptr = coeffImage->row_begin(iY); ptr != end; ++ptr) { int fX = fftshift.shift(iX); int fY = fftshift.shift(iY); *ptr = static_cast<PixelT>(c[fY * wid + fX].real() / (wid * wid)); iX++; } } // reset the origin to be the middle of the image coeffImage->setXY0(-wid / 2, -wid / 2); return coeffImage; } // I'm not sure why this doesn't work with DCT-I (REDFT00), the DCT should take advantage of symmetry // and be much faster than the DFT. It runs but the numbers are slightly off ... // but I have to do it as real-to-halfcplx (R2HC) to get the correct numbers. template <typename PixelT> std::shared_ptr<afw::image::Image<PixelT>> calcImageKSpaceReal(double const rad1, double const rad2) { // we only need a half-width due to symmertry // make the hwid 2*rad2 so we have some buffer space and round up to the next power of 2 int log2 = static_cast<int>(::ceil(::log10(2.0 * rad2) / log10(2.0))); if (log2 < 3) { log2 = 3; } int hwid = pow(2, log2); int wid = 2 * hwid - 1; int xcen = wid / 2, ycen = wid / 2; FftShifter fftshift(wid); boost::shared_array<double> cimg(new double[wid * wid]); double* c = cimg.get(); // fftplan args: nx, ny, *in, *out, kindx, kindy, flags // - done in-situ if *in == *out fftw_plan plan = fftw_plan_r2r_2d(wid, wid, c, c, FFTW_R2HC, FFTW_R2HC, FFTW_ESTIMATE); // compute the k-space values and put them in the cimg array double const twoPiRad1 = geom::TWOPI * rad1; double const twoPiRad2 = geom::TWOPI * rad2; for (int iY = 0; iY < wid; ++iY) { int const fY = fftshift.shift(iY); double const ky = (static_cast<double>(iY) - ycen) / wid; for (int iX = 0; iX < wid; ++iX) { int const fX = fftshift.shift(iX); // emacs indent breaks if this isn't separte double const iXcen = static_cast<double>(iX - xcen); double const kx = iXcen / wid; double const k = ::sqrt(kx * kx + ky * ky); double const airy1 = (rad1 > 0 ? rad1 * J1(twoPiRad1 * k) : 0.0) / k; double const airy2 = rad2 * J1(twoPiRad2 * k) / k; double const airy = airy2 - airy1; c[fY * wid + fX] = airy; } } int fxy = fftshift.shift(wid / 2); c[fxy * wid + fxy] = geom::PI * (rad2 * rad2 - rad1 * rad1); // perform the fft and clean up after ourselves fftw_execute(plan); fftw_destroy_plan(plan); // put the coefficients into an image auto coeffImage = std::make_shared<afw::image::Image<PixelT>>(geom::ExtentI(wid, wid), 0.0); for (int iY = 0; iY != coeffImage->getHeight(); ++iY) { int iX = 0; typename afw::image::Image<PixelT>::x_iterator end = coeffImage->row_end(iY); for (typename afw::image::Image<PixelT>::x_iterator ptr = coeffImage->row_begin(iY); ptr != end; ++ptr) { // now need to reflect the quadrant we solved to the other three int fX = iX < hwid ? hwid - iX - 1 : iX - hwid + 1; int fY = iY < hwid ? hwid - iY - 1 : iY - hwid + 1; *ptr = static_cast<PixelT>(c[fY * wid + fX] / (wid * wid)); iX++; } } // reset the origin to be the middle of the image coeffImage->setXY0(-wid / 2, -wid / 2); return coeffImage; } } // namespace template <typename PixelT> SincCoeffs<PixelT>& SincCoeffs<PixelT>::getInstance() { static SincCoeffs<PixelT> instance; return instance; } template <typename PixelT> void SincCoeffs<PixelT>::cache(float r1, float r2) { if (r1 < 0.0 || r2 < r1) { throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, (boost::format("Invalid r1,r2 = %f,%f") % r1 % r2).str()); } double const innerFactor = r1 / r2; afw::geom::ellipses::Axes axes(r2, r2, 0.0); if (!getInstance()._lookup(axes, innerFactor)) { PTR(typename SincCoeffs<PixelT>::CoeffT) coeff = calculate(axes, innerFactor); getInstance()._cache[r2][innerFactor] = coeff; } } template <typename PixelT> CONST_PTR(typename SincCoeffs<PixelT>::CoeffT) SincCoeffs<PixelT>::get(afw::geom::ellipses::Axes const& axes, float const innerFactor) { CONST_PTR(CoeffT) coeff = getInstance()._lookup(axes, innerFactor); return coeff ? coeff : calculate(axes, innerFactor); } template <typename PixelT> CONST_PTR(typename SincCoeffs<PixelT>::CoeffT) SincCoeffs<PixelT>::_lookup(afw::geom::ellipses::Axes const& axes, double const innerFactor) const { if (innerFactor < 0.0 || innerFactor > 1.0) { throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, (boost::format("innerFactor = %f is not between 0 and 1") % innerFactor).str()); } CONST_PTR(typename SincCoeffs<PixelT>::CoeffT) const null = CONST_PTR(SincCoeffs<PixelT>::CoeffT)(); // We only cache circular apertures if (!FuzzyCompare<float>().isEqual(axes.getA(), axes.getB())) { return null; } typename CoeffMapMap::const_iterator iter1 = _cache.find(axes.getA()); if (iter1 == _cache.end()) { return null; } typename CoeffMap::const_iterator iter2 = iter1->second.find(innerFactor); return (iter2 == iter1->second.end()) ? null : iter2->second; } template <typename PixelT> PTR(typename SincCoeffs<PixelT>::CoeffT) SincCoeffs<PixelT>::calculate(afw::geom::ellipses::Axes const& axes, double const innerFactor) { if (innerFactor < 0.0 || innerFactor > 1.0) { throw LSST_EXCEPT(pex::exceptions::InvalidParameterError, (boost::format("innerFactor = %f is not between 0 and 1") % innerFactor).str()); } // Kspace-real is fastest, but only slightly faster than kspace cplx // but real won't work for elliptical apertures due to symmetries assumed for real transform double const rad1 = axes.getA() * innerFactor; double const rad2 = axes.getA(); // if there's no angle and no ellipticity if (FuzzyCompare<float>().isEqual(axes.getA(), axes.getB())) { // here we call the real transform return calcImageKSpaceReal<PixelT>(rad1, rad2); } else { // here we call the complex transform double const ellipticity = 1.0 - axes.getB() / axes.getA(); return calcImageKSpaceCplx<PixelT>(rad1, rad2, axes.getTheta(), ellipticity); } } template class SincCoeffs<float>; template class SincCoeffs<double>; } // namespace base } // namespace meas } // namespace lsst
37.599644
109
0.597511
[ "object", "transform" ]
caf0bbdbe7c09f451a3869ab152f9cc11628d1f5
45,602
cc
C++
geometry/render/gl_renderer/shape_meshes.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
geometry/render/gl_renderer/shape_meshes.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
geometry/render/gl_renderer/shape_meshes.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/geometry/render/gl_renderer/shape_meshes.h" #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <map> #include <string> #include <tuple> #include <vector> #include <fmt/format.h> #include <tiny_obj_loader.h> #include "drake/common/drake_assert.h" #include "drake/common/eigen_types.h" #include "drake/common/text_logging.h" namespace drake { namespace geometry { namespace render { namespace internal { using Eigen::Vector2d; using Eigen::Vector3d; using std::make_tuple; using std::map; using std::string; using std::tuple; using std::vector; MeshData LoadMeshFromObj(std::istream* input_stream, const std::string& filename) { tinyobj::attrib_t attrib; vector<tinyobj::shape_t> shapes; vector<tinyobj::material_t> materials; string warn; string err; /* This renderer assumes everything is triangles -- we rely on tinyobj to triangulate for us. */ const bool do_tinyobj_triangulation = true; drake::log()->trace("LoadMeshFromObj('{}')", filename); /* Tinyobj doesn't infer the search directory from the directory containing the obj file. We have to provide that directory; of course, this assumes that the material library reference is relative to the obj directory. Ignore material-library file. */ tinyobj::MaterialReader* material_reader = nullptr; const bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, input_stream, material_reader, do_tinyobj_triangulation); if (!ret) { throw std::runtime_error( fmt::format("tinyobj::LoadObj failed to load file: {}", filename)); } if (shapes.empty()) { throw std::runtime_error(fmt::format( "The OBJ data appears to have no faces; it could be missing faces or " "might not be an OBJ file: {}", filename)); } /* The parsed product needs to be further processed. The MeshData assumes that all vertex quantities (positions, normals, texture coordinates) are indexed with a common index; a face that references vertex i, will get its position from positions[i], its normal from normals[i], and its texture coordinate from uvs[i]. However, we _cannot_ assume that each vertex position is associated with a single per-vertex quantity (normal, uv) in the OBJ file. OBJ allows a vertex position to be associated with arbitrary per-vertex quantities in each face definition independently. So, we need to create the unique association here. To accomplish this: 1. Every vertex referenced by a face in the parsed OBJ is a "meta" vertex consisting of a tuple of indices: (p, n, uv), the index in vertex positions, normals, and texture coordinates. For example, imagine one face refers to meta index (p, n₀, uv) and another face refers to index (p, n₁, uv). Although the two faces appear to share a single vertex (and a common texture coordinate), those vertices have different normals which require two different vertices in the mesh data. We copy the vertex position and texture coordinate and then associate one copy with each normal. A similar operation would apply if they only differed in texture coordinate (or in both). 2. Given a mapping (p, n, uv) --> i (a mapping from the meta vertex in the parsed OBJ data to the unique index in the resultant mesh data), we can build the faces in the final mesh data by mapping the (p, n, uv) tuple in the OBJ face specification to the final mesh data vertex index i. 3. When done, we should have an equal number of vertex positions as normals and texture coordinates. And all indices in the faces should be valid indices into all three vectors of data. NOTE: In the case of meta vertices (p, n₀, uv) and (p, n₁, uv) we are not confirming that normals[n₀] and normals[n₁] are actually different normals; we're assuming different indices implies different values. Again, the same applies to different texture coordinate indices. */ /* The map from (p, n, uv) --> i. */ map<tuple<int, int, int>, int> obj_vertex_to_new_vertex; /* Accumulators for vertex positions, normals, and triangles. */ vector<Vector3d> positions; vector<Vector3d> normals; vector<Vector2d> uvs; vector<Vector3<int>> triangles; // TODO(SeanCurtis-TRI) Revisit how we handle normals: // 1. If normals are absent, generate normals so that we get faceted meshes. // 2. Make use of smoothing groups. if (attrib.normals.size() == 0) { throw std::runtime_error(fmt::format( "OBJ has no normals; RenderEngineGl requires OBJs with normals: {}", filename)); } bool has_tex_coord{attrib.texcoords.size() > 0}; for (const auto& shape : shapes) { /* Each face is a sequence of indices. All of the face indices are concatenated together in one long sequence: [i1, i2, ..., iN]. Because we have nothing but triangles, that sequence can be partitioned into triples, each representing one triangle: [(i1, i2, i3), (i4, i5, i6), ..., (iN-2, iN-1, iN)]. We maintain an index into that long sequence (v_index) and simply increment it knowing that every three increments takes us to a new face. */ int v_index = 0; const auto& shape_mesh = shape.mesh; const int num_faces = static_cast<int>(shape_mesh.num_face_vertices.size()); for (int f = 0; f < num_faces; ++f) { DRAKE_DEMAND(shape_mesh.num_face_vertices[f] == 3); /* Captures the [i0, i1, i2] new index values for the face. */ int face_vertices[3] = {-1, -1, -1}; for (int i = 0; i < 3; ++i) { const int position_index = shape_mesh.indices[v_index].vertex_index; const int norm_index = shape_mesh.indices[v_index].normal_index; const int uv_index = shape_mesh.indices[v_index].texcoord_index; // TODO(SeanCurtis-TRI) PR 14656 changed parse semantics. This error // condition appears to no longer be reachable (it no longer appears // in the unit tests) and the condition that this detects won't trigger // this helpful message. Either clean up this case or find a way to give // this feedback under the new tinyobj. if (norm_index < 0) { throw std::runtime_error( fmt::format("Not all faces reference normals: {}", filename)); } if (has_tex_coord) { if (uv_index < 0) { throw std::runtime_error(fmt::format( "Not all faces reference texture coordinates: {}", filename)); } } else { DRAKE_DEMAND(uv_index < 0); } const auto obj_indices = make_tuple(position_index, norm_index, uv_index); if (obj_vertex_to_new_vertex.count(obj_indices) == 0) { obj_vertex_to_new_vertex[obj_indices] = static_cast<int>(positions.size()); /* Guarantee that the positions.size() == normals.size() == uvs.size() by always growing them in lock step. */ positions.emplace_back( Vector3d{attrib.vertices[3 * position_index], attrib.vertices[3 * position_index + 1], attrib.vertices[3 * position_index + 2]}); normals.emplace_back(attrib.normals[3 * norm_index], attrib.normals[3 * norm_index + 1], attrib.normals[3 * norm_index + 2]); if (has_tex_coord) { uvs.emplace_back(attrib.texcoords[2 * uv_index], attrib.texcoords[2 * uv_index + 1]); } else { uvs.emplace_back(0.0, 0.0); } } face_vertices[i] = obj_vertex_to_new_vertex[obj_indices]; ++v_index; } triangles.emplace_back(&face_vertices[0]); } } DRAKE_DEMAND(positions.size() == normals.size()); DRAKE_DEMAND(positions.size() == uvs.size()); MeshData mesh_data; mesh_data.indices.resize(triangles.size(), 3); for (int t = 0; t < mesh_data.indices.rows(); ++t) { mesh_data.indices.row(t) = triangles[t].cast<GLuint>(); } mesh_data.positions.resize(positions.size(), 3); for (int v = 0; v < mesh_data.positions.rows(); ++v) { mesh_data.positions.row(v) = positions[v].cast<GLfloat>(); } mesh_data.normals.resize(normals.size(), 3); for (int n = 0; n < mesh_data.normals.rows(); ++n) { mesh_data.normals.row(n) = normals[n].cast<GLfloat>(); } mesh_data.has_tex_coord = has_tex_coord; mesh_data.uvs.resize(uvs.size(), 2); for (int uv = 0; uv < mesh_data.uvs.rows(); ++uv) { mesh_data.uvs.row(uv) = uvs[uv].cast<GLfloat>(); } return mesh_data; } MeshData LoadMeshFromObj(const string& filename) { std::ifstream input_stream(filename); if (!input_stream.is_open()) { throw std::runtime_error( fmt::format("Cannot load the obj file '{}'", filename)); } return LoadMeshFromObj(&input_stream, filename); } namespace { /* Creates a triangle mesh for a revolute surface. It is, essentially, a curve that is revolved around the z-axis. The revolute surface is discrete, so the curve is evaluted at fixed angular samples (determined by the `rotate_sample_count`). The curve is defined implicitly and is sampled along its length a fixed number of times (determined by the `curve_sample_count`). This assumes that the two end points of the curve *lie on* the Cz axes. So, the top and bottom of the revolute mesh are single vertices (with a triangle fan radiating outward). Another way to consider this is that we're lofting circles to symmetrically fit the curve path (i.e., every circle's center lies on the z axis). The total number of circles is `curve_sample_count` with the expectation that the first and last circles have radius zero. They are enumerated c_0, c_2, ..., c_C, where `C = curve_sample_count - 1`. For a given circle index, we need to know the circle's radius and its position on the z-axis. To accommodate texture coordinates, each circle has overlapping vertices at the beginning/end. In other words, if `R = rotate_sample_count` each circle will have R + 1 vertices where the first and last vertices are coincident. This will allow for the first vertex to have the texture coordinate (0, v) and the last to have texture coordinate (1, v). @param rotate_sample_count The total number of radial samples in each circle. @param curve_sample_count The total number of circles lofting. @param calc_radius_i A function that reports the radius of the ith circle. The first and last circles (with zero radius) should have indices 0 and `curve_sample_count - 1`, respectively. @param calc_z_i A function that reports the position of the ith circle center along the z axis. Circle indices for this function should have the same semantics as for `calc_radius_i`. @pre `calc_radius_i(0)` and `calc_radius_i(curve_sample_count - 1) = 0`. */ MeshData MakeRevoluteShape(int rotate_sample_count, int curve_sample_count, const std::function<GLfloat(int i)>& calc_radius_i, const std::function<GLfloat(int i)>& calc_z_i) { const GLfloat delta_theta = static_cast<GLfloat>(2 * M_PI / rotate_sample_count); /* We have R rotation samples and C curve samples. Vertex count: The first and last curve samples are single vertices. Every other curve sample forms a ring with R + 1 vertices. So, total vertices = (C - 2) * (R + 1) + 2. Triangle count: We create triangles by spanning between rings. Because rings 0 and C-1 are zero-radius, we span rings 0 and 1 with a triangle fan of R triangles. The same between rings C-2 and C-1. Between all other adjacent rings, we create 2R triangles. There are C - 2 non-zero-radius rings that bound C - 3 spanning bands. So, total triangles: R + R + (C - 3) * 2R = 2R + (C - 3) * 2R = 2R(1 + (C - 3)) = 2R(C - 2). */ const int vert_count = (curve_sample_count - 2) * (rotate_sample_count + 1) + 2; const int tri_count = (curve_sample_count - 2) * 2 * rotate_sample_count; MeshData mesh_data; auto& vertices = mesh_data.positions; vertices.resize(vert_count, 3); auto& indices = mesh_data.indices; indices.resize(tri_count, 3); /* Insertion points into vertices and indices for each new vertex and tri. */ int v_index = 0; int t_index = 0; /* The index of the ring we're operating on; this the ring for which vertices are being generated and added. */ int ring_i = 0; /* Ring 0 is a single point; add that "ring". */ vertices.row(v_index) << 0, 0, calc_z_i(ring_i); ++v_index; /* Computes the vertex position for the index `v` of the vertex in the ring, v ∈ [0, R] (inclusive), with the given z-value and ring radius r. */ auto make_vertex = [delta_theta](int v, GLfloat v_z, GLfloat r) { const GLfloat theta = v * delta_theta; const GLfloat v_x = r * ::cosf(theta); const GLfloat v_y = r * ::sinf(theta); return Vector3<GLfloat>{v_x, v_y, v_z}; }; /* Now start with the rings that have non-zero radius. */ ++ring_i; GLfloat z_i = calc_z_i(ring_i); GLfloat r_i = calc_radius_i(ring_i); /* Triangles spanning ring 0 to ring 1 are simply a triangle fan around vertex 0. */ /* We add R + 1 vertices, but R triangles. To do that, we add the first R vertices and build triangles referencing the about-to-be-added *next* vertex. Finally, we copy the first vertex in the set so we know they are *perfectly* coincident. We use this same strategy in populating all the interior rings and bands and again at the triangle fan spanning the last two rings. */ for (int v_j = 0; v_j < rotate_sample_count; ++v_j, ++v_index) { vertices.row(v_index) = make_vertex(v_j, z_i, r_i); indices.row(t_index++) << 0, v_index, v_index + 1; } vertices.row(v_index) << vertices.row(v_index - rotate_sample_count); ++v_index; /* All of the remaining rings from the curve samples with non-zero radius (i.e., rings 2 to N-1, inclusive). */ /* We add all the vertices for ring_i and build triangles between ring_i and ring_i-1. The triangles are formed with the following vertices: │ b │ c ────•──────•──── <-- ring i-1 │ ╲ │ │ ╲ │ │ v ╲│ v+1 ────•──────•──── <-- ring i │ │ The vertices are labeled by their *global indices* v, v+1, b, and c. v: the jth vertex for ring i -- added in this iteration of the for loop. v+1: the subsequent vertex to v in the same ring b = v - (R + 1) = v - R - 1 = c - 1 c = v + 1 - (R + 1) = v - R */ for (ring_i = 2; ring_i < curve_sample_count - 1; ++ring_i) { z_i = calc_z_i(ring_i); r_i = calc_radius_i(ring_i); for (int v_j = 0; v_j < rotate_sample_count; ++v_j, ++v_index) { vertices.row(v_index) = make_vertex(v_j, z_i, r_i); const int c = v_index - rotate_sample_count; const int b = c - 1; indices.row(t_index++) << v_index, v_index + 1, b; indices.row(t_index++) << v_index + 1, c, b; } vertices.row(v_index) << vertices.row(v_index - rotate_sample_count); ++v_index; } /* Triangles spanning ring C-2 to ring C-1; a triangle fan around the last vertex. We're only missing the last vertex, all other vertices exist. */ vertices.row(v_index) << 0.f, 0.f, calc_z_i(ring_i); const int prev_ring_start = v_index - rotate_sample_count - 1; /* Post-increment v_index so its value represents the total number of vertices added. */ const int ring_C_vertex = v_index++; /* We *now* have all the vertices, we just need to create the spanning triangles. */ for (int v_j = 0; v_j < rotate_sample_count; ++v_j) { const int v = prev_ring_start + v_j; indices.row(t_index++) << v, ring_C_vertex, v + 1; } /* The process of building should match our predicted counts. */ DRAKE_DEMAND(v_index == vert_count); DRAKE_DEMAND(t_index == tri_count); return mesh_data; } } // namespace MeshData MakeLongLatUnitSphere(int longitude_bands, int latitude_bands) { /* For notational convenience: T = number of latitude bands G = number of longitude bands. G Longitudinal bands t_0 ******* **╱ │ ╲** <-- polar band t_1 **─┼───┼───┼─** * │ │ │ * t_2 *──┼────┼────┼──* <-- medial bands T Latiduinal bands * │ │ │ * t_3 **─┼───┼───┼─** **╲ │ ╱** <-- polar band t_4 ******* Vertex count: For T latitude bands, there are T + 1 "rings" of vertices. Two rings have radius 0 and a single vertex (the north and south pole). The other rings all have G + 1 vertices (due to the fact that MakeRevoluteShape() introduces a "seam" on each ring to allow for texture coordinates). Total number of vertices = (T - 1) * (G + 1) + 2. Triangle count: Every medial latitudinal band produces G quads or 2G triangles. There are T - 2 medial bands. The two polar bands produce G triangles. So, total number of triangles = (T - 2) * 2G + 2 * G = (2(T - 2) + 2) * G = (2T - 2) * G We enumerate the latitude rings from 0 to T. Latitude rings t_0 and t_T are at the poles. The height of the ring centers from the sphere center are not uniformly spaced along the Cz axis (this would lead to ill-aspected triangles). Instead, we define z_i (the height of the ith ring center) so that the _longitudinal_ circle is uniformly sampled. Every interior latitude ring t_i has radius r_i = sqrt(R² - z_i²), R = 1 for the unit sphere. The algorithm starts at the north pole and works to the south pole, tracking which longitude ring we're on. For 0 < t_i < T, we also generate the triangles spanning rings t_i and t_i-1. The poles are treated as a special cases. As a revolute shape, the number of longitude bands is exactly the number of rotation samples. The "curve" we're revolving is a half circle. We are sampling it from pole to pole forming `latitude_bands` number of bands; which means, from the revolute surface function's perspective, we are sampling the half circle `latitude_bands + 1` times. */ /* Minimum values that create a sphere approximation with volume. */ DRAKE_DEMAND(longitude_bands >= 3); DRAKE_DEMAND(latitude_bands >= 2); const int vert_count = (latitude_bands - 1) * (longitude_bands + 1) + 2; const int tri_count = (2 * latitude_bands - 2) * longitude_bands; /* Angle separating latitudinal rings measured in the longitudinal direction (defines the height of rings). */ const GLfloat delta_phi = static_cast<GLfloat>(M_PI / latitude_bands); auto calc_z_i = [delta_phi, latitude_bands](int ring_i) { DRAKE_DEMAND(ring_i >= 0 && ring_i <= latitude_bands); return ::cosf(ring_i * delta_phi); }; auto calc_radius_i = [calc_z_i, latitude_bands](int ring_i) { DRAKE_DEMAND(ring_i >= 0 && ring_i <= latitude_bands); if (ring_i == 0 || ring_i == latitude_bands) return 0.f; const GLfloat z_i = calc_z_i(ring_i); return sqrtf(1.0 - z_i * z_i); }; MeshData mesh_data = MakeRevoluteShape(longitude_bands, latitude_bands + 1, calc_radius_i, calc_z_i); /* The process of building should match our predicted counts. */ DRAKE_DEMAND(mesh_data.positions.rows() == vert_count); DRAKE_DEMAND(mesh_data.indices.rows() == tri_count); /* We can add the normals in a post-hoc manner; every vertex normal is simply the normalized position vector (given this is the unit sphere, the two quantities should be the same). */ mesh_data.normals.resize(vert_count, 3); for (int v = 0; v < vert_count; ++v) { const auto p_MV = mesh_data.positions.row(v); mesh_data.normals.row(v) = p_MV.normalized(); } /* Post hoc addition of texture coordinates. Note: the values at the north and south poles, (<0, 1> and <0, 0>, respectively) will lead to visual artifacts. There is no known good solution for polar texture coordinates without those artifacts. */ mesh_data.uvs.resize(vert_count, 2); /* North pole. */ mesh_data.uvs.row(0) << 0, 1; /* All lines of latitude. */ int v_index = 1; const double delta_u = 1.0 / longitude_bands; const double delta_v = 1.0 / latitude_bands; for (int ring = 1; ring < latitude_bands; ++ring) { const double v = 1.0 - ring * delta_v; for (int vertex = 0; vertex <= longitude_bands; ++vertex, ++v_index) { const double u = vertex * delta_u; mesh_data.uvs.row(v_index) << u, v; } } /* South pole. */ mesh_data.uvs.row(v_index) << 0, 0; DRAKE_DEMAND(++v_index == vert_count); return mesh_data; } MeshData MakeUnitCylinder(int num_strips, int num_bands) { /* For notational convenience S = number of strips B = number of bands ***** ***╲ ╱*** cap --> *─────*─────* <─── Ring 0 (center vertex) ****╱ │ ╲**** <─── Ring 1 (circle edge) * │*****│ * * │ │ │ * <──┐ b * │ │ │ * │ a <─── Ring 1 barrel --> *╲ │ │ │ ╱* │ n * ─│──│──│─ * │ d * │ │ │ * <──┘ s * │ │ │ * <─── Ring 2 *** │ *** │ ***** │ │ │ │ │ └───┴──┴──┘ strips The cylinder has one barrel and two caps. The caps are divided into triangle fans consisting of S triangles around a central vertex. The barrel is decomposed into B bands of 2S triangles each. Revolute vertex count We create the cylinder by creating a single revolute surface and then subsequently breaking it apart to introduce normal discontinuities. In the revolute, connected cylinder mesh, there are B + 1 rings of vertices plus two more vertices in the centers of the caps. Each ring has S + 1 vertices (due to the fact that MakeRevoluteShape() introduces a "seam" on each ring to allow for texture coordinates), for a total vertex count of: (B + 1) * (S + 1) + 2. The final mesh duplicates Ring 1 and Ring B + 2 (see the notes below on creating normals). This leads to a final vertex count of: (B + 1) * (S + 1) + 2 + (S + 1) * 2 = (B + 3) * (S + 1) + 2. Triange count Each band on the barrel creates 2S triangles. Each cap produces S triangles for a total triangle count of: B * 2S + 2 * S = 2(B + 1) * S. Treated as a revolute surface, the curve we're revolving is a half box: 0 1 ┆ ┆ z0 ┆ ┆ z1 o━━━━━━━o┄┄┄┄┄┄ 0.5 ┆ ┃ z2 ┆───────o ┆ ┃ z3 ┄┄┄┄┼┄┄┄┄┄┄┄o┄┄┄┄┄ ┆ ┃ z4 ┆───────o z6 ┆ ┃ z5 o━━━━━━━o┄┄┄┄┄┄ -0.5 ┆ The number of strips is exactly the number of rotation samples. For `num_bands` bands of triangles on the barrels we need `num_bands` + 1 curve samples. We need two *more* samples at the points where the half box touches the vertical axis giving us a total of `num_bands + 3` curve samples. In the example above, we have 4 bands creating seven curve samples. Note that circles 0 and 1 have a z-value of 0.5 (the top of the unit cylinder) and circles 5 and 6 similarly have a z-value of -0.5 (the bottom of the unit cylinder). The z-values of circles 2, 3, and 4 are uniformly distrubted between the top and bottom. */ DRAKE_DEMAND(num_strips >= 3); DRAKE_DEMAND(num_bands >= 1); const int rev_vert_count = (num_bands + 1) * (num_strips + 1) + 2; const int tri_count = 2 * (num_bands + 1) * num_strips; /* The height of each band along the length of the barrel. */ const GLfloat band_height = 1.f / num_bands; /* As illustrated above, circle 0 & 1 have a z-value of 0.5, circles C-2 and C-1 are at -0.5, and all other circles are distributed between. Because C = B + 3, C-2 = B + 1 and C-1 = B + 2. */ auto calc_z_i = [band_height, num_bands](int ring_i) { DRAKE_DEMAND(ring_i >= 0 && ring_i <= num_bands + 2); if (ring_i < 2) return 0.5f; if (ring_i > num_bands) return -0.5f; /* Circles 2, 3, ... C - 3 should have a displacement of 1, 2, ..., C-4 band_height below the top cap. */ return 0.5f - (ring_i - 1) * band_height; }; auto calc_radius_i = [num_bands](int ring_i) { /* Circles 0 and C-1 are zero-radius circles. C-1 = (B + 3) -1 = B + 2. */ DRAKE_DEMAND(ring_i >= 0 && ring_i <= num_bands + 2); if (ring_i == 0 || ring_i == num_bands + 2) return 0.f; return 1.f; }; MeshData mesh_data = MakeRevoluteShape(num_strips, num_bands + 3, calc_radius_i, calc_z_i); /* The process of building should match our predicted counts. */ DRAKE_DEMAND(mesh_data.positions.rows() == rev_vert_count); DRAKE_DEMAND(mesh_data.indices.rows() == tri_count); /* To have a hard-edge on the cylinder cap, we need to have 2 * (num_strips + 1) more vertices; the vertices on the top and bottom rings (those that run along the perimeter of the caps) need to be duplicated. The vertices returned by MakeRevoluteShape are as follows: |__|___|___|...|___|___|___|...|___|___|...|___|__| c₀ r₁₀ r₁₁ ... r₁ₙ r₂₀ r₂₁ ... rₘ₀ rₘ₁ ... rₘₙ c₁ The first and last vertices (c₀ and c₁) are the centers of the top and bottom caps. There are M = num_bands + 1 blocks of N + 1 = num_strips + 1 vertices representing a single "ring" of vertices. Each vertex is denoted as rⱼᵢ for the iᵗʰ vertex in ring j. The first and last rings (r₁ and rₘ₋₁) will be duplicated. The first ring will be duplicated immediately after c₀ and the last ring directly before c₁. All triangle indices will be modified to reflect the shift. */ const int old_v_count = mesh_data.positions.rows(); const int new_v_count = old_v_count + 2 * (num_strips + 1); MeshData full_mesh_data; full_mesh_data.positions.resize(new_v_count, 3); full_mesh_data.normals.resize(new_v_count, 3); full_mesh_data.uvs.resize(new_v_count, 2); const int t_count = mesh_data.indices.rows(); full_mesh_data.indices.resize(t_count, 3); /* The first and last k = S + 2 vertices are referenced by cap triangles. */ const int cap_v_count = num_strips + 2; /* Total number of vertices referenced by barrel triangles. */ const int barrel_v_count = old_v_count - 2; /* Copy vertex positions; the first N + 1 vertices are the bottom cap and the last N + 1 are the top cap. */ full_mesh_data.positions.block(0, 0, cap_v_count, 3) = mesh_data.positions.block(0, 0, cap_v_count, 3); full_mesh_data.positions.block(cap_v_count, 0, barrel_v_count, 3) = mesh_data.positions.block(1, 0, barrel_v_count, 3); full_mesh_data.positions.block(new_v_count - cap_v_count, 0, cap_v_count, 3) = mesh_data.positions.block(old_v_count - cap_v_count, 0, cap_v_count, 3); /* Write all the normal data. */ /* Top cap. */ int v = 0; for (; v < cap_v_count; ++v) { full_mesh_data.normals.row(v) << 0, 0, 1; } /* All barrel vertices. */ for (; v < barrel_v_count + cap_v_count; ++v) { const auto p_MV = full_mesh_data.positions.row(v); const Vector2d p_MV_xy(p_MV(0, 0), p_MV(0, 1)); const Vector2d n_MV_xy = p_MV_xy.normalized(); full_mesh_data.normals.row(v) << n_MV_xy(0), n_MV_xy(1), 0; } /* Bottom cap. */ for (; v < new_v_count; ++v) { full_mesh_data.normals.row(v) << 0, 0, -1; } /* Transform indices in the triangles. */ /* Top cap remains unchanged; so we'll skip the first num_strips triangles. */ full_mesh_data.indices = mesh_data.indices; const auto offset = Vector3<GLuint>::Constant(num_strips + 1).transpose(); int t = num_strips; for (; t < t_count - num_strips; ++t) { full_mesh_data.indices.row(t) += offset; } for (; t < t_count; ++t) { full_mesh_data.indices.row(t) += 2 * offset; } /* TODO(SeanCurtis-TRI) Consider treating cylinders like capsules; rather than scaling a single unit cylinder (which will lead to funny texture artifacts), consider creating unique cylinders so their texture coordinates stretch over non-unit cylinders well. */ /* Texture coordinates. The u-direction goes from zero to 1, radially, joining at the seam created by the revolute mesh. The v-direction, like the sphere, spans from the north pole (1) to the south pole (0) and is scaled according to the geodesic distance. The radius and heights of this cylinder are both 1. So, the top 1/3 of the cylinder's texture will *always* apply to the top face, the next third to the barrel, and the last third to the bottom face. Even if the cylinder is scaled to arbitrary radius/length this mapping will still be true. */ const int ring_size = num_strips + 1; const GLfloat arc_length = 3; /* Two radii + length. */ int uv_index = 0; /* North pole. */ full_mesh_data.uvs.row(uv_index) << 0, 1; ++uv_index; /* Now handle the rings of vertices. Each ring has a constant v-coordinate and a set of u-values that span [0, 1]. So, we'll create the u- and v-values that we'll write into the data as blocks. */ VectorX<GLfloat> u_values(ring_size); u_values.setLinSpaced(0.f, 1.f); VectorX<GLfloat> v_values(ring_size); v_values.setConstant(2.f / arc_length); /* First two rings are duplicates with matching uv coordinates. */ full_mesh_data.uvs.block(uv_index, 0, ring_size, 1) = u_values; full_mesh_data.uvs.block(uv_index, 1, ring_size, 1) = v_values; uv_index += ring_size; full_mesh_data.uvs.block(uv_index, 0, ring_size, 1) = u_values; full_mesh_data.uvs.block(uv_index, 1, ring_size, 1) = v_values; uv_index += ring_size; /* For B bands, there are B - 1 rings located *strictly* on the barrel. */ const GLfloat v_delta = 1 / arc_length / num_bands; for (int barrel_ring = 0; barrel_ring < num_bands - 1; ++barrel_ring) { v_values.setConstant(v_values(0) - v_delta); full_mesh_data.uvs.block(uv_index, 0, ring_size, 1) = u_values; full_mesh_data.uvs.block(uv_index, 1, ring_size, 1) = v_values; uv_index += ring_size; } /* Last two rings are duplicates with matching uv coordinates. */ v_values.setConstant(1.f / arc_length); full_mesh_data.uvs.block(uv_index, 0, ring_size, 1) = u_values; full_mesh_data.uvs.block(uv_index, 1, ring_size, 1) = v_values; uv_index += ring_size; full_mesh_data.uvs.block(uv_index, 0, ring_size, 1) = u_values; full_mesh_data.uvs.block(uv_index, 1, ring_size, 1) = v_values; uv_index += ring_size; /* South pole. */ full_mesh_data.uvs.row(uv_index) << 0, 0; DRAKE_DEMAND(++uv_index == new_v_count); return full_mesh_data; } MeshData MakeSquarePatch(GLfloat measure, int resolution) { DRAKE_DEMAND(measure > 0); DRAKE_DEMAND(resolution >= 1); const int vert_count = (resolution + 1) * (resolution + 1); const int tri_count = 2 * resolution * resolution; MeshData mesh_data; mesh_data.positions.resize(vert_count, 3); mesh_data.normals.resize(vert_count, 3); mesh_data.uvs.resize(vert_count, 2); mesh_data.indices.resize(tri_count, 3); /* The size of each square sub-patch. */ const GLfloat delta_pos = measure / resolution; /* The size of each square sub-patch in *texture coordinates*. */ const GLfloat delta_uv = 1.f / resolution; /* Build the following grid. Where N = resolution. +y ↑ ┆ ○───○───○───○─┆─○───○───○───○ <- v_index = (N + 1)^2 - 1 │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ○───○───○───○─┆─○───○───○───○ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ○───○───○───○─┆─○───○───○───○ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ○───○───○───○─┆─○───○───○───○ ←┄┄┄┄┼┄╱┄┼┄╱┄┼┄╱┄┼┄┼┄┼┄╱┄┼┄╱┄┼┄╱┄┼┄┄┄┄┄→ +x ○───○───○───○─┆─○───○───○───○ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ○───○───○───○─┆─○───○───○───○ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ○───○───○───○─┆─○───○───○───○ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ ╱ │ v_index = 0 -> ○───○───○───○─┆─○───○───○───○ <- v_index = N ^ ┆ (x0, y0) ↓ */ /* First add the vertices. */ int v_index = 0; GLfloat x0 = -measure / 2; GLfloat y0 = -measure / 2; for (int i = 0; i <= resolution; ++i) { const GLfloat y = y0 + i * delta_pos; const GLfloat v = i * delta_uv; for (int j = 0; j <= resolution; ++j) { mesh_data.normals.row(v_index) << 0, 0, 1; const GLfloat x = x0 + j * delta_pos; mesh_data.positions.row(v_index) << x, y, 0; const GLfloat u = j * delta_uv; mesh_data.uvs.row(v_index++) << u, v; } } DRAKE_DEMAND(v_index == vert_count); /* Build triangles in the same order we add vertices. v_u = v_index + N + 1 n_u = v_index + 1 + N + 1 ╲ │ │╱ ──○───────○── │ ╱ │ │ ╱ │ │ ╱ │ ──○───────○── ╱ │ │ ╲ v = v_index n = v_index + 1 */ int t_index = 0; v_index = 0; for (int i = 0; i < resolution; ++i) { for (int j = 0; j < resolution; ++j) { const int v = v_index++; const int n = v + 1; const int v_u = v + resolution + 1; const int n_u = n + resolution + 1; mesh_data.indices.row(t_index++) << v, n, n_u; mesh_data.indices.row(t_index++) << v, n_u, v_u; } ++v_index; } DRAKE_DEMAND(t_index == tri_count); return mesh_data; } MeshData MakeUnitBox() { /* The box is 24 vertices (8 vertex positions duplicated three times each -- once per adjacent face) and twelve faces. We duplicate the vertex positions because each adjacent face requires a different normal direction. h____ g z /│ /│ │ y d/_│__c/ │ │ / │ │ │ │ │/____ x │ e│___│_│ f │ / │ / │/_____│/ a b */ MeshData mesh_data; mesh_data.positions.resize(24, 3); mesh_data.normals.resize(24, 3); mesh_data.uvs.resize(24, 2); mesh_data.indices.resize(12, 3); /* clang-format off */ mesh_data.positions << -0.5f, -0.5f, -0.5f, /* -y face: a b c d. */ 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, /* +x face: b f g c. */ 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, /* +z face: d c g h */ 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, /* -x face: e a d h */ -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, /* -z face: e f b a */ 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, /* +y face: f e h g */ -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f; mesh_data.normals << 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0; /* The ordering of the face vertex indices have been defined such that we can specify each face's vertex coordinates with the same clockwise pattern: (0, 0) -> (1, 0) -> (1, 1) -> (0, 1). */ mesh_data.uvs << 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1; mesh_data.indices << 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23; /* clang-format on */ return mesh_data; } MeshData MakeCapsule(int samples, double radius, double length) { /* Based on samples, we'll create a unit sphere, guaranteeing that there are vertices on the equator. We'll use the unit sphere to create the capsule by duplicating the equator vertices, translating the northern hemisphere upwards, the southern downwards, and inserting a band of triangles to connect the two. */ // TODO(SeanCurtis-TRI) Would this look better using MakeRevoluteShape? /* To get roughly "square" quads on the sphere, we need as many vertices around a longitudinal line as we do around the equator (samples). That many vertices will form samples / 2 latitudinal bands. We require an even number of bands to guarantee vertices at the equator). */ const int half_samples = samples / 2; const int lat_bands = half_samples + (half_samples % 2); const MeshData sphere_data = MakeLongLatUnitSphere(samples, lat_bands); /* The number of vertices in a "ring" is samples + 1 because the revolute surface duplicates the first vertex on each ring to accommodate texture coordinates. */ const int ring_size = samples + 1; /* There should be `2H + ring_size` vertices in the sphere, where H is the number of vertices in a hemisphere *excluding* the vertices on the equator. The resulting capsule will have `2H + 2 * ring_size` vertices, normals, and uvs and `T + 2 * samples` triangles, where T is the number of triangles in the sphere. */ const int H = (sphere_data.positions.rows() - ring_size) / 2; DRAKE_DEMAND(2 * H + ring_size == sphere_data.positions.rows()); MeshData data; const int vert_count = 2 * (H + ring_size); data.positions.resize(vert_count, 3); data.normals.resize(vert_count, 3); data.uvs.resize(vert_count, 2); const int tri_count = sphere_data.indices.rows() + (2 * samples); data.indices.resize(tri_count, 3); /* Process vertices and normals. Vertices get scaled by radius and offset half the length, normals and uvs get copied. (The copied uv values will be modified later to account for the difference between spheres and capsules. */ int sphere_v = -1; int capsule_v = -1; /* Northern hemisphere plus the equator. */ const Vector3<GLfloat> offset(0, 0, length / 2); for (int i = 0; i < H + ring_size; ++i) { const Vector3<GLfloat> p_SV = sphere_data.positions.row(++sphere_v); data.positions.row(++capsule_v) = p_SV * radius + offset; data.normals.row(capsule_v) = sphere_data.normals.row(sphere_v); data.uvs.row(capsule_v) = sphere_data.uvs.row(sphere_v); } /* Back up our *reading* index so that we get a copy of the equator. */ sphere_v -= ring_size; for (int i = 0; i < H + ring_size; ++i) { const Vector3<GLfloat> p_SV = sphere_data.positions.row(++sphere_v); data.positions.row(++capsule_v) = p_SV * radius - offset; data.normals.row(capsule_v) = sphere_data.normals.row(sphere_v); data.uvs.row(capsule_v) = sphere_data.uvs.row(sphere_v); } /* Process the faces. The first half can be taken verbatim. Then we inject the barrel vertices (connecting the two equators), the southern hemisphere needs all indices offset by `ring_size`. */ const int hemisphere_tri_count = sphere_data.indices.rows() / 2; data.indices.block(0, 0, hemisphere_tri_count, 3) = sphere_data.indices.block(0, 0, hemisphere_tri_count, 3); /* We add all the triangles for the barrel spanning the two equators. Given a vertex index lying on the southern equator v, we walk around the equator building triangle pairs as shown: │ b │ c ────•──────•──── <-- northern equator │ ╲ │ │ ╲ │ │ v ╲│ v+1 ────•──────•──── <-- southern equator │ │ The vertices are labeled by their *global* _indices_ v, v+1, b, and c and R = ring_size. v: the jth vertex for the southern equator. v+1: the subsequent vertex to v. b = v - R c = v + 1 - R */ int capsule_t = hemisphere_tri_count; int v = H + ring_size; /* the "first" vertex of the southern equator. */ for (int i = 0; i < samples; ++i, ++v, capsule_t += 2) { data.indices.row(capsule_t) << v, v + 1, v - ring_size; data.indices.row(capsule_t + 1) << v + 1, v + 1 - ring_size, v - ring_size; } /* Now the southern hemisphere gets its indices offset to account for the injection of `ring_size` new vertices. */ const Vector3<GLuint> i_offset(ring_size, ring_size, ring_size); for (int sphere_t = hemisphere_tri_count; sphere_t < sphere_data.indices.rows(); ++sphere_t, ++capsule_t) { auto tri = sphere_data.indices.row(sphere_t); data.indices.row(capsule_t) = tri + i_offset.transpose(); } /* Texture coordinates. We've copied the *sphere's* texture coordinates along with positions and normals. The u-values in the texture coordinates are all properly inherited from the sphere. However, the v-values are not correct. They need to be redistributed to account for the length of the cylindrical barrel and arbitrary radius. The geodesic distance between the sphere's poles is 1/2 the circumference: πR (R = 1 for the unit sphere). The distance for the capsule is `L = πR + length`. This will lead to a re-parameterization of the v-values. The geodesic distance (or arc length) from pole to equator is πR / 2. Its fraction of the full geodesic distance is πR / 2 / L = πR / 2L. Therefore, over the span from pole to equator, the v-values change by πR / 2L. The v-value at the north pole starts at 1 and decreases by πR / 2L and the south pole starts at 0 and increases by the same amount. In each hemisphere, the v-value should change an *equal* amount from one latitude ring to the next. We constructed the sphere with B = lat_bands number of bands (an even number). So, that means there are B/2 bands in each hemisphere to span πR / 2L values of v, so: delta_v = πR / 2L / (B/2) = πR / BL */ const GLfloat arc_length = length + M_PI * radius; const GLfloat delta_v = M_PI * radius / (lat_bands * arc_length); int uv_index = 0; /* Skipping north and south pole; they are the same as with the sphere. */ /* The latitude rings on the northern hemisphere. */ for (int r = 1; r <= lat_bands / 2; ++r) { /* The v-value for this ring. */ const GLfloat v_value = 1.f - r * delta_v; for (int i = 0; i < ring_size; ++i) { data.uvs(++uv_index, 1) = v_value; } } /* The latitude rings for the southern hemisphere. */ for (int r = 0; r < lat_bands / 2; ++r) { /* The v-value for this ring. */ const GLfloat v_value = (lat_bands - r) * delta_v; for (int i = 0; i < ring_size; ++i) { data.uvs(++uv_index, 1) = v_value; } } /* The index is of the second-to-last texture coordinate. Increment one for the last, and one more for the total count. */ DRAKE_DEMAND(uv_index + 2 == vert_count); return data; } } // namespace internal } // namespace render } // namespace geometry } // namespace drake
41.913603
80
0.598811
[ "mesh", "geometry", "render", "shape", "vector", "transform" ]
caf0c1bd735618a7987b6578eeff7147f0bf12a0
4,515
cpp
C++
Core/GDCore/Extensions/Platform.cpp
mahmoudeid789/GDevelop
943fac772d7910c1b9de47adc41b3ea9a652beaa
[ "MIT" ]
1
2020-03-07T22:06:55.000Z
2020-03-07T22:06:55.000Z
Core/GDCore/Extensions/Platform.cpp
KairoMartins18/KGE
64e934c15da38c7140abb5e1521321e161d82568
[ "MIT" ]
6
2020-07-20T19:44:47.000Z
2022-03-25T19:06:28.000Z
Core/GDCore/Extensions/Platform.cpp
KairoMartins18/KGE
64e934c15da38c7140abb5e1521321e161d82568
[ "MIT" ]
null
null
null
/* * GDevelop Core * Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights * reserved. This project is released under the MIT License. */ #include "Platform.h" #include "GDCore/Extensions/PlatformExtension.h" #include "GDCore/Project/Object.h" #include "GDCore/String.h" using namespace std; #undef CreateEvent namespace gd { Platform::Platform(): enableExtensionLoadingLogs(true) {} Platform::~Platform() {} bool Platform::AddExtension(std::shared_ptr<gd::PlatformExtension> extension) { if (!extension) return false; if (enableExtensionLoadingLogs) std::cout << "Loading " << extension->GetName() << "..."; if (IsExtensionLoaded(extension->GetName())) { if (enableExtensionLoadingLogs) std::cout << " (replacing existing extension)"; RemoveExtension(extension->GetName()); } if (enableExtensionLoadingLogs) std::cout << std::endl; extensionsLoaded.push_back(extension); // Load all creation/destruction functions for objects provided by the // extension vector<gd::String> objectsTypes = extension->GetExtensionObjectsTypes(); for (std::size_t i = 0; i < objectsTypes.size(); ++i) { creationFunctionTable[objectsTypes[i]] = extension->GetObjectCreationFunctionPtr(objectsTypes[i]); } return true; } void Platform::RemoveExtension(const gd::String& name) { // Unload all creation/destruction functions for objects provided by the // extension for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { auto& extension = extensionsLoaded[i]; if (extension->GetName() == name) { vector<gd::String> objectsTypes = extension->GetExtensionObjectsTypes(); for (std::size_t i = 0; i < objectsTypes.size(); ++i) { creationFunctionTable.erase(objectsTypes[i]); } } } extensionsLoaded.erase( remove_if(extensionsLoaded.begin(), extensionsLoaded.end(), [&name](std::shared_ptr<PlatformExtension> extension) { return extension->GetName() == name; }), extensionsLoaded.end()); } bool Platform::IsExtensionLoaded(const gd::String& name) const { for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { if (extensionsLoaded[i]->GetName() == name) return true; } return false; } std::shared_ptr<gd::PlatformExtension> Platform::GetExtension( const gd::String& name) const { for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { if (extensionsLoaded[i]->GetName() == name) return extensionsLoaded[i]; } return std::shared_ptr<gd::PlatformExtension>(); } std::unique_ptr<gd::Object> Platform::CreateObject( gd::String type, const gd::String& name) const { if (creationFunctionTable.find(type) == creationFunctionTable.end()) { std::cout << "Tried to create an object with an unknown type: " << type << " for platform " << GetName() << "!" << std::endl; type = ""; if (creationFunctionTable.find("") == creationFunctionTable.end()) { std::cout << "Unable to create a Base object!" << std::endl; return nullptr; } } // Create a new object with the type we want. std::unique_ptr<gd::Object> object = (creationFunctionTable.find(type)->second)(name); object->SetType(type); return std::unique_ptr<gd::Object>(std::move(object)); } gd::Behavior* Platform::GetBehavior(const gd::String& behaviorType) const { for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { gd::Behavior* behavior = extensionsLoaded[i]->GetBehavior(behaviorType); if (behavior) return behavior; } return nullptr; } gd::BehaviorsSharedData* Platform::GetBehaviorSharedDatas( const gd::String& behaviorType) const { for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { gd::BehaviorsSharedData* behaviorSharedData = extensionsLoaded[i]->GetBehaviorSharedDatas(behaviorType); if (behaviorSharedData) return behaviorSharedData; } return nullptr; } #if defined(GD_IDE_ONLY) std::shared_ptr<gd::BaseEvent> Platform::CreateEvent( const gd::String& eventType) const { for (std::size_t i = 0; i < extensionsLoaded.size(); ++i) { std::shared_ptr<gd::BaseEvent> event = extensionsLoaded[i]->CreateEvent(eventType); if (event != std::shared_ptr<gd::BaseEvent>()) return event; } return std::shared_ptr<gd::BaseEvent>(); } #endif } // namespace gd
32.956204
92
0.654707
[ "object", "vector" ]
cafcbeb57de57849d95c389bf3cd4c5ebc41ae78
83,437
cpp
C++
llvm-5.0.1.src/utils/TableGen/GlobalISelEmitter.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
60
2017-12-21T06:49:58.000Z
2022-02-24T09:43:52.000Z
llvm-5.0.1.src/utils/TableGen/GlobalISelEmitter.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
null
null
null
llvm-5.0.1.src/utils/TableGen/GlobalISelEmitter.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
17
2017-12-20T09:54:56.000Z
2021-06-24T05:39:36.000Z
//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// This tablegen backend emits code for use by the GlobalISel instruction /// selector. See include/llvm/CodeGen/TargetGlobalISel.td. /// /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen /// backend, filters out the ones that are unsupported, maps /// SelectionDAG-specific constructs to their GlobalISel counterpart /// (when applicable: MVT to LLT; SDNode to generic Instruction). /// /// Not all patterns are supported: pass the tablegen invocation /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped, /// as well as why. /// /// The generated file defines a single method: /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const; /// intended to be used in InstructionSelector::select as the first-step /// selector for the patterns that don't require complex C++. /// /// FIXME: We'll probably want to eventually define a base /// "TargetGenInstructionSelector" class. /// //===----------------------------------------------------------------------===// #include "CodeGenDAGPatterns.h" #include "SubtargetFeatureInfo.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Error.h" #include "llvm/Support/LowLevelTypeImpl.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include <string> #include <numeric> using namespace llvm; #define DEBUG_TYPE "gisel-emitter" STATISTIC(NumPatternTotal, "Total number of patterns"); STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG"); STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped"); STATISTIC(NumPatternEmitted, "Number of patterns emitted"); /// A unique identifier for a MatchTable. static unsigned CurrentMatchTableID = 0; cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel"); static cl::opt<bool> WarnOnSkippedPatterns( "warn-on-skipped-patterns", cl::desc("Explain why a pattern was skipped for inclusion " "in the GlobalISel selector"), cl::init(false), cl::cat(GlobalISelEmitterCat)); namespace { //===- Helper functions ---------------------------------------------------===// /// This class stands in for LLT wherever we want to tablegen-erate an /// equivalent at compiler run-time. class LLTCodeGen { private: LLT Ty; public: LLTCodeGen(const LLT &Ty) : Ty(Ty) {} void emitCxxEnumValue(raw_ostream &OS) const { if (Ty.isScalar()) { OS << "GILLT_s" << Ty.getSizeInBits(); return; } if (Ty.isVector()) { OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits(); return; } llvm_unreachable("Unhandled LLT"); } void emitCxxConstructorCall(raw_ostream &OS) const { if (Ty.isScalar()) { OS << "LLT::scalar(" << Ty.getSizeInBits() << ")"; return; } if (Ty.isVector()) { OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getScalarSizeInBits() << ")"; return; } llvm_unreachable("Unhandled LLT"); } const LLT &get() const { return Ty; } /// This ordering is used for std::unique() and std::sort(). There's no /// particular logic behind the order. bool operator<(const LLTCodeGen &Other) const { if (!Ty.isValid()) return Other.Ty.isValid(); if (Ty.isScalar()) { if (!Other.Ty.isValid()) return false; if (Other.Ty.isScalar()) return Ty.getSizeInBits() < Other.Ty.getSizeInBits(); return false; } if (Ty.isVector()) { if (!Other.Ty.isValid() || Other.Ty.isScalar()) return false; if (Other.Ty.isVector()) { if (Ty.getNumElements() < Other.Ty.getNumElements()) return true; if (Ty.getNumElements() > Other.Ty.getNumElements()) return false; return Ty.getSizeInBits() < Other.Ty.getSizeInBits(); } return false; } llvm_unreachable("Unhandled LLT"); } }; class InstructionMatcher; /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) { MVT VT(SVT); if (VT.isVector() && VT.getVectorNumElements() != 1) return LLTCodeGen( LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits())); if (VT.isInteger() || VT.isFloatingPoint()) return LLTCodeGen(LLT::scalar(VT.getSizeInBits())); return None; } static std::string explainPredicates(const TreePatternNode *N) { std::string Explanation = ""; StringRef Separator = ""; for (const auto &P : N->getPredicateFns()) { Explanation += (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str(); if (P.isAlwaysTrue()) Explanation += " always-true"; if (P.isImmediatePattern()) Explanation += " immediate"; } return Explanation; } std::string explainOperator(Record *Operator) { if (Operator->isSubClassOf("SDNode")) return (" (" + Operator->getValueAsString("Opcode") + ")").str(); if (Operator->isSubClassOf("Intrinsic")) return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str(); return " (Operator not understood)"; } /// Helper function to let the emitter report skip reason error messages. static Error failedImport(const Twine &Reason) { return make_error<StringError>(Reason, inconvertibleErrorCode()); } static Error isTrivialOperatorNode(const TreePatternNode *N) { std::string Explanation = ""; std::string Separator = ""; if (N->isLeaf()) { if (isa<IntInit>(N->getLeafValue())) return Error::success(); Explanation = "Is a leaf"; Separator = ", "; } if (N->hasAnyPredicate()) { Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")"; Separator = ", "; } if (N->getTransformFn()) { Explanation += Separator + "Has a transform function"; Separator = ", "; } if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn()) return Error::success(); return failedImport(Explanation); } static Record *getInitValueAsRegClass(Init *V) { if (DefInit *VDefInit = dyn_cast<DefInit>(V)) { if (VDefInit->getDef()->isSubClassOf("RegisterOperand")) return VDefInit->getDef()->getValueAsDef("RegClass"); if (VDefInit->getDef()->isSubClassOf("RegisterClass")) return VDefInit->getDef(); } return nullptr; } std::string getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) { std::string Name = "GIFBS"; for (const auto &Feature : FeatureBitset) Name += ("_" + Feature->getName()).str(); return Name; } //===- Matchers -----------------------------------------------------------===// class OperandMatcher; class MatchAction; /// Generates code to check that a match rule matches. class RuleMatcher { /// A list of matchers that all need to succeed for the current rule to match. /// FIXME: This currently supports a single match position but could be /// extended to support multiple positions to support div/rem fusion or /// load-multiple instructions. std::vector<std::unique_ptr<InstructionMatcher>> Matchers; /// A list of actions that need to be taken when all predicates in this rule /// have succeeded. std::vector<std::unique_ptr<MatchAction>> Actions; /// A map of instruction matchers to the local variables created by /// emitCaptureOpcodes(). std::map<const InstructionMatcher *, unsigned> InsnVariableIDs; /// ID for the next instruction variable defined with defineInsnVar() unsigned NextInsnVarID; std::vector<Record *> RequiredFeatures; public: RuleMatcher() : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {} RuleMatcher(RuleMatcher &&Other) = default; RuleMatcher &operator=(RuleMatcher &&Other) = default; InstructionMatcher &addInstructionMatcher(); void addRequiredFeature(Record *Feature); const std::vector<Record *> &getRequiredFeatures() const; template <class Kind, class... Args> Kind &addAction(Args &&... args); /// Define an instruction without emitting any code to do so. /// This is used for the root of the match. unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher); /// Define an instruction and emit corresponding state-machine opcodes. unsigned defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher, unsigned InsnVarID, unsigned OpIdx); unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const; void emitCaptureOpcodes(raw_ostream &OS); void emit(raw_ostream &OS); /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. bool isHigherPriorityThan(const RuleMatcher &B) const; /// Report the maximum number of temporary operands needed by the rule /// matcher. unsigned countRendererFns() const; // FIXME: Remove this as soon as possible InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); } }; template <class PredicateTy> class PredicateListMatcher { private: typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec; PredicateVec Predicates; public: /// Construct a new operand predicate and add it to the matcher. template <class Kind, class... Args> Kind &addPredicate(Args&&... args) { Predicates.emplace_back( llvm::make_unique<Kind>(std::forward<Args>(args)...)); return *static_cast<Kind *>(Predicates.back().get()); } typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); } typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); } iterator_range<typename PredicateVec::const_iterator> predicates() const { return make_range(predicates_begin(), predicates_end()); } typename PredicateVec::size_type predicates_size() const { return Predicates.size(); } /// Emit MatchTable opcodes that tests whether all the predicates are met. template <class... Args> void emitPredicateListOpcodes(raw_ostream &OS, Args &&... args) const { if (Predicates.empty()) { OS << "// No predicates\n"; return; } for (const auto &Predicate : predicates()) Predicate->emitPredicateOpcodes(OS, std::forward<Args>(args)...); } }; /// Generates code to check a predicate of an operand. /// /// Typical predicates include: /// * Operand is a particular register. /// * Operand is assigned a particular register bank. /// * Operand is an MBB. class OperandPredicateMatcher { public: /// This enum is used for RTTI and also defines the priority that is given to /// the predicate when generating the matcher code. Kinds with higher priority /// must be tested first. /// /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter /// but OPM_Int must have priority over OPM_RegBank since constant integers /// are represented by a virtual register defined by a G_CONSTANT instruction. enum PredicateKind { OPM_ComplexPattern, OPM_Instruction, OPM_IntrinsicID, OPM_Int, OPM_LiteralInt, OPM_LLT, OPM_RegBank, OPM_MBB, }; protected: PredicateKind Kind; public: OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} virtual ~OperandPredicateMatcher() {} PredicateKind getKind() const { return Kind; } /// Return the OperandMatcher for the specified operand or nullptr if there /// isn't one by that name in this operand predicate matcher. /// /// InstructionOperandMatcher is the only subclass that can return non-null /// for this. virtual Optional<const OperandMatcher *> getOptionalOperand(StringRef SymbolicName) const { assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); return None; } /// Emit MatchTable opcodes to capture instructions into the MIs table. /// /// Only InstructionOperandMatcher needs to do anything for this method the /// rest just walk the tree. virtual void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const {} /// Emit MatchTable opcodes that check the predicate for the given operand. virtual void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const = 0; /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const { return Kind < B.Kind; }; /// Report the maximum number of temporary operands needed by the predicate /// matcher. virtual unsigned countRendererFns() const { return 0; } }; /// Generates code to check that an operand is a particular LLT. class LLTOperandMatcher : public OperandPredicateMatcher { protected: LLTCodeGen Ty; public: LLTOperandMatcher(const LLTCodeGen &Ty) : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_LLT; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckType, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", /*Type*/"; Ty.emitCxxEnumValue(OS); OS << ", \n"; } }; /// Generates code to check that an operand is a particular target constant. class ComplexPatternOperandMatcher : public OperandPredicateMatcher { protected: const OperandMatcher &Operand; const Record &TheDef; unsigned getAllocatedTemporariesBaseID() const; public: ComplexPatternOperandMatcher(const OperandMatcher &Operand, const Record &TheDef) : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand), TheDef(TheDef) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_ComplexPattern; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { unsigned ID = getAllocatedTemporariesBaseID(); OS << " GIM_CheckComplexPattern, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", /*Renderer*/" << ID << ", GICP_" << TheDef.getName() << ",\n"; } unsigned countRendererFns() const override { return 1; } }; /// Generates code to check that an operand is in a particular register bank. class RegisterBankOperandMatcher : public OperandPredicateMatcher { protected: const CodeGenRegisterClass &RC; public: RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) : OperandPredicateMatcher(OPM_RegBank), RC(RC) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_RegBank; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckRegBankForClass, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", /*RC*/" << RC.getQualifiedName() << "RegClassID,\n"; } }; /// Generates code to check that an operand is a basic block. class MBBOperandMatcher : public OperandPredicateMatcher { public: MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_MBB; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckIsMBB, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ",\n"; } }; /// Generates code to check that an operand is a G_CONSTANT with a particular /// int. class ConstantIntOperandMatcher : public OperandPredicateMatcher { protected: int64_t Value; public: ConstantIntOperandMatcher(int64_t Value) : OperandPredicateMatcher(OPM_Int), Value(Value) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_Int; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckConstantInt, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", " << Value << ",\n"; } }; /// Generates code to check that an operand is a raw int (where MO.isImm() or /// MO.isCImm() is true). class LiteralIntOperandMatcher : public OperandPredicateMatcher { protected: int64_t Value; public: LiteralIntOperandMatcher(int64_t Value) : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_LiteralInt; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckLiteralInt, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", " << Value << ",\n"; } }; /// Generates code to check that an operand is an intrinsic ID. class IntrinsicIDOperandMatcher : public OperandPredicateMatcher { protected: const CodeGenIntrinsic *II; public: IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II) : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_IntrinsicID; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID, unsigned OpIdx) const override { OS << " GIM_CheckIntrinsicID, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ", Intrinsic::" << II->EnumName << ",\n"; } }; /// Generates code to check that a set of predicates match for a particular /// operand. class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> { protected: InstructionMatcher &Insn; unsigned OpIdx; std::string SymbolicName; /// The index of the first temporary variable allocated to this operand. The /// number of allocated temporaries can be found with /// countRendererFns(). unsigned AllocatedTemporariesBaseID; public: OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx, const std::string &SymbolicName, unsigned AllocatedTemporariesBaseID) : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName), AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {} bool hasSymbolicName() const { return !SymbolicName.empty(); } const StringRef getSymbolicName() const { return SymbolicName; } void setSymbolicName(StringRef Name) { assert(SymbolicName.empty() && "Operand already has a symbolic name"); SymbolicName = Name; } unsigned getOperandIndex() const { return OpIdx; } std::string getOperandExpr(unsigned InsnVarID) const { return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" + llvm::to_string(OpIdx) + ")"; } Optional<const OperandMatcher *> getOptionalOperand(StringRef DesiredSymbolicName) const { assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand"); if (DesiredSymbolicName == SymbolicName) return this; for (const auto &OP : predicates()) { const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName); if (MaybeOperand.hasValue()) return MaybeOperand.getValue(); } return None; } InstructionMatcher &getInstructionMatcher() const { return Insn; } /// Emit MatchTable opcodes to capture instructions into the MIs table. void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID) const { for (const auto &Predicate : predicates()) Predicate->emitCaptureOpcodes(OS, Rule, InsnVarID, OpIdx); } /// Emit MatchTable opcodes that test whether the instruction named in /// InsnVarID matches all the predicates and all the operands. void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID) const { OS << " // MIs[" << InsnVarID << "] "; if (SymbolicName.empty()) OS << "Operand " << OpIdx; else OS << SymbolicName; OS << "\n"; emitPredicateListOpcodes(OS, Rule, InsnVarID, OpIdx); } /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. bool isHigherPriorityThan(const OperandMatcher &B) const { // Operand matchers involving more predicates have higher priority. if (predicates_size() > B.predicates_size()) return true; if (predicates_size() < B.predicates_size()) return false; // This assumes that predicates are added in a consistent order. for (const auto &Predicate : zip(predicates(), B.predicates())) { if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) return true; if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) return false; } return false; }; /// Report the maximum number of temporary operands needed by the operand /// matcher. unsigned countRendererFns() const { return std::accumulate( predicates().begin(), predicates().end(), 0, [](unsigned A, const std::unique_ptr<OperandPredicateMatcher> &Predicate) { return A + Predicate->countRendererFns(); }); } unsigned getAllocatedTemporariesBaseID() const { return AllocatedTemporariesBaseID; } }; unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const { return Operand.getAllocatedTemporariesBaseID(); } /// Generates code to check a predicate on an instruction. /// /// Typical predicates include: /// * The opcode of the instruction is a particular value. /// * The nsw/nuw flag is/isn't set. class InstructionPredicateMatcher { protected: /// This enum is used for RTTI and also defines the priority that is given to /// the predicate when generating the matcher code. Kinds with higher priority /// must be tested first. enum PredicateKind { IPM_Opcode, }; PredicateKind Kind; public: InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} virtual ~InstructionPredicateMatcher() {} PredicateKind getKind() const { return Kind; } /// Emit MatchTable opcodes that test whether the instruction named in /// InsnVarID matches the predicate. virtual void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID) const = 0; /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const { return Kind < B.Kind; }; /// Report the maximum number of temporary operands needed by the predicate /// matcher. virtual unsigned countRendererFns() const { return 0; } }; /// Generates code to check the opcode of an instruction. class InstructionOpcodeMatcher : public InstructionPredicateMatcher { protected: const CodeGenInstruction *I; public: InstructionOpcodeMatcher(const CodeGenInstruction *I) : InstructionPredicateMatcher(IPM_Opcode), I(I) {} static bool classof(const InstructionPredicateMatcher *P) { return P->getKind() == IPM_Opcode; } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID) const override { OS << " GIM_CheckOpcode, /*MI*/" << InsnVarID << ", " << I->Namespace << "::" << I->TheDef->getName() << ",\n"; } /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override { if (InstructionPredicateMatcher::isHigherPriorityThan(B)) return true; if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this)) return false; // Prioritize opcodes for cosmetic reasons in the generated source. Although // this is cosmetic at the moment, we may want to drive a similar ordering // using instruction frequency information to improve compile time. if (const InstructionOpcodeMatcher *BO = dyn_cast<InstructionOpcodeMatcher>(&B)) return I->TheDef->getName() < BO->I->TheDef->getName(); return false; }; }; /// Generates code to check that a set of predicates and operands match for a /// particular instruction. /// /// Typical predicates include: /// * Has a specific opcode. /// * Has an nsw/nuw flag or doesn't. class InstructionMatcher : public PredicateListMatcher<InstructionPredicateMatcher> { protected: typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec; /// The operands to match. All rendered operands must be present even if the /// condition is always true. OperandVec Operands; public: /// Add an operand to the matcher. OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName, unsigned AllocatedTemporariesBaseID) { Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName, AllocatedTemporariesBaseID)); return *Operands.back(); } OperandMatcher &getOperand(unsigned OpIdx) { auto I = std::find_if(Operands.begin(), Operands.end(), [&OpIdx](const std::unique_ptr<OperandMatcher> &X) { return X->getOperandIndex() == OpIdx; }); if (I != Operands.end()) return **I; llvm_unreachable("Failed to lookup operand"); } Optional<const OperandMatcher *> getOptionalOperand(StringRef SymbolicName) const { assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); for (const auto &Operand : Operands) { const auto &OM = Operand->getOptionalOperand(SymbolicName); if (OM.hasValue()) return OM.getValue(); } return None; } const OperandMatcher &getOperand(StringRef SymbolicName) const { Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName); if (OM.hasValue()) return *OM.getValue(); llvm_unreachable("Failed to lookup operand"); } unsigned getNumOperands() const { return Operands.size(); } OperandVec::iterator operands_begin() { return Operands.begin(); } OperandVec::iterator operands_end() { return Operands.end(); } iterator_range<OperandVec::iterator> operands() { return make_range(operands_begin(), operands_end()); } OperandVec::const_iterator operands_begin() const { return Operands.begin(); } OperandVec::const_iterator operands_end() const { return Operands.end(); } iterator_range<OperandVec::const_iterator> operands() const { return make_range(operands_begin(), operands_end()); } /// Emit MatchTable opcodes to check the shape of the match and capture /// instructions into the MIs table. void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnID) { OS << " GIM_CheckNumOperands, /*MI*/" << InsnID << ", /*Expected*/" << getNumOperands() << ",\n"; for (const auto &Operand : Operands) Operand->emitCaptureOpcodes(OS, Rule, InsnID); } /// Emit MatchTable opcodes that test whether the instruction named in /// InsnVarName matches all the predicates and all the operands. void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID) const { emitPredicateListOpcodes(OS, Rule, InsnVarID); for (const auto &Operand : Operands) Operand->emitPredicateOpcodes(OS, Rule, InsnVarID); } /// Compare the priority of this object and B. /// /// Returns true if this object is more important than B. bool isHigherPriorityThan(const InstructionMatcher &B) const { // Instruction matchers involving more operands have higher priority. if (Operands.size() > B.Operands.size()) return true; if (Operands.size() < B.Operands.size()) return false; for (const auto &Predicate : zip(predicates(), B.predicates())) { if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) return true; if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) return false; } for (const auto &Operand : zip(Operands, B.Operands)) { if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand))) return true; if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand))) return false; } return false; }; /// Report the maximum number of temporary operands needed by the instruction /// matcher. unsigned countRendererFns() const { return std::accumulate(predicates().begin(), predicates().end(), 0, [](unsigned A, const std::unique_ptr<InstructionPredicateMatcher> &Predicate) { return A + Predicate->countRendererFns(); }) + std::accumulate( Operands.begin(), Operands.end(), 0, [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) { return A + Operand->countRendererFns(); }); } }; /// Generates code to check that the operand is a register defined by an /// instruction that matches the given instruction matcher. /// /// For example, the pattern: /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3)) /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match /// the: /// (G_ADD $src1, $src2) /// subpattern. class InstructionOperandMatcher : public OperandPredicateMatcher { protected: std::unique_ptr<InstructionMatcher> InsnMatcher; public: InstructionOperandMatcher() : OperandPredicateMatcher(OPM_Instruction), InsnMatcher(new InstructionMatcher()) {} static bool classof(const OperandPredicateMatcher *P) { return P->getKind() == OPM_Instruction; } InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; } Optional<const OperandMatcher *> getOptionalOperand(StringRef SymbolicName) const override { assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); return InsnMatcher->getOptionalOperand(SymbolicName); } void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnID, unsigned OpIdx) const override { unsigned InsnVarID = Rule.defineInsnVar(OS, *InsnMatcher, InsnID, OpIdx); InsnMatcher->emitCaptureOpcodes(OS, Rule, InsnVarID); } void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, unsigned InsnVarID_, unsigned OpIdx_) const override { unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher); InsnMatcher->emitPredicateOpcodes(OS, Rule, InsnVarID); } }; //===- Actions ------------------------------------------------------------===// class OperandRenderer { public: enum RendererKind { OR_Copy, OR_CopySubReg, OR_Imm, OR_Register, OR_ComplexPattern }; protected: RendererKind Kind; public: OperandRenderer(RendererKind Kind) : Kind(Kind) {} virtual ~OperandRenderer() {} RendererKind getKind() const { return Kind; } virtual void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const = 0; }; /// A CopyRenderer emits code to copy a single operand from an existing /// instruction to the one being built. class CopyRenderer : public OperandRenderer { protected: unsigned NewInsnID; /// The matcher for the instruction that this operand is copied from. /// This provides the facility for looking up an a operand by it's name so /// that it can be used as a source for the instruction being built. const InstructionMatcher &Matched; /// The name of the operand. const StringRef SymbolicName; public: CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched, StringRef SymbolicName) : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched), SymbolicName(SymbolicName) {} static bool classof(const OperandRenderer *R) { return R->getKind() == OR_Copy; } const StringRef getSymbolicName() const { return SymbolicName; } void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { const OperandMatcher &Operand = Matched.getOperand(SymbolicName); unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); OS << " GIR_Copy, /*NewInsnID*/" << NewInsnID << ", /*OldInsnID*/" << OldInsnVarID << ", /*OpIdx*/" << Operand.getOperandIndex() << ", // " << SymbolicName << "\n"; } }; /// A CopySubRegRenderer emits code to copy a single register operand from an /// existing instruction to the one being built and indicate that only a /// subregister should be copied. class CopySubRegRenderer : public OperandRenderer { protected: unsigned NewInsnID; /// The matcher for the instruction that this operand is copied from. /// This provides the facility for looking up an a operand by it's name so /// that it can be used as a source for the instruction being built. const InstructionMatcher &Matched; /// The name of the operand. const StringRef SymbolicName; /// The subregister to extract. const CodeGenSubRegIndex *SubReg; public: CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched, StringRef SymbolicName, const CodeGenSubRegIndex *SubReg) : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched), SymbolicName(SymbolicName), SubReg(SubReg) {} static bool classof(const OperandRenderer *R) { return R->getKind() == OR_CopySubReg; } const StringRef getSymbolicName() const { return SymbolicName; } void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { const OperandMatcher &Operand = Matched.getOperand(SymbolicName); unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); OS << " GIR_CopySubReg, /*NewInsnID*/" << NewInsnID << ", /*OldInsnID*/" << OldInsnVarID << ", /*OpIdx*/" << Operand.getOperandIndex() << ", /*SubRegIdx*/" << SubReg->EnumValue << ", // " << SymbolicName << "\n"; } }; /// Adds a specific physical register to the instruction being built. /// This is typically useful for WZR/XZR on AArch64. class AddRegisterRenderer : public OperandRenderer { protected: unsigned InsnID; const Record *RegisterDef; public: AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef) : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) { } static bool classof(const OperandRenderer *R) { return R->getKind() == OR_Register; } void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { OS << " GIR_AddRegister, /*InsnID*/" << InsnID << ", " << (RegisterDef->getValue("Namespace") ? RegisterDef->getValueAsString("Namespace") : "") << "::" << RegisterDef->getName() << ",\n"; } }; /// Adds a specific immediate to the instruction being built. class ImmRenderer : public OperandRenderer { protected: unsigned InsnID; int64_t Imm; public: ImmRenderer(unsigned InsnID, int64_t Imm) : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {} static bool classof(const OperandRenderer *R) { return R->getKind() == OR_Imm; } void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { OS << " GIR_AddImm, /*InsnID*/" << InsnID << ", /*Imm*/" << Imm << ",\n"; } }; /// Adds operands by calling a renderer function supplied by the ComplexPattern /// matcher function. class RenderComplexPatternOperand : public OperandRenderer { private: unsigned InsnID; const Record &TheDef; /// The name of the operand. const StringRef SymbolicName; /// The renderer number. This must be unique within a rule since it's used to /// identify a temporary variable to hold the renderer function. unsigned RendererID; unsigned getNumOperands() const { return TheDef.getValueAsDag("Operands")->getNumArgs(); } public: RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef, StringRef SymbolicName, unsigned RendererID) : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef), SymbolicName(SymbolicName), RendererID(RendererID) {} static bool classof(const OperandRenderer *R) { return R->getKind() == OR_ComplexPattern; } void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { OS << " GIR_ComplexRenderer, /*InsnID*/" << InsnID << ", /*RendererID*/" << RendererID << ",\n"; } }; /// An action taken when all Matcher predicates succeeded for a parent rule. /// /// Typical actions include: /// * Changing the opcode of an instruction. /// * Adding an operand to an instruction. class MatchAction { public: virtual ~MatchAction() {} /// Emit the C++ statements to implement the action. /// /// \param RecycleInsnID If given, it's an instruction to recycle. The /// requirements on the instruction vary from action to /// action. virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, unsigned RecycleInsnID) const = 0; }; /// Generates a comment describing the matched rule being acted upon. class DebugCommentAction : public MatchAction { private: const PatternToMatch &P; public: DebugCommentAction(const PatternToMatch &P) : P(P) {} void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, unsigned RecycleInsnID) const override { OS << " // " << *P.getSrcPattern() << " => " << *P.getDstPattern() << "\n"; } }; /// Generates code to build an instruction or mutate an existing instruction /// into the desired instruction when this is possible. class BuildMIAction : public MatchAction { private: unsigned InsnID; const CodeGenInstruction *I; const InstructionMatcher &Matched; std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers; /// True if the instruction can be built solely by mutating the opcode. bool canMutate() const { if (OperandRenderers.size() != Matched.getNumOperands()) return false; for (const auto &Renderer : enumerate(OperandRenderers)) { if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) { const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName()); if (&Matched != &OM.getInstructionMatcher() || OM.getOperandIndex() != Renderer.index()) return false; } else return false; } return true; } public: BuildMIAction(unsigned InsnID, const CodeGenInstruction *I, const InstructionMatcher &Matched) : InsnID(InsnID), I(I), Matched(Matched) {} template <class Kind, class... Args> Kind &addRenderer(Args&&... args) { OperandRenderers.emplace_back( llvm::make_unique<Kind>(std::forward<Args>(args)...)); return *static_cast<Kind *>(OperandRenderers.back().get()); } void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, unsigned RecycleInsnID) const override { if (canMutate()) { OS << " GIR_MutateOpcode, /*InsnID*/" << InsnID << ", /*RecycleInsnID*/ " << RecycleInsnID << ", /*Opcode*/" << I->Namespace << "::" << I->TheDef->getName() << ",\n"; if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) { for (auto Def : I->ImplicitDefs) { auto Namespace = Def->getValue("Namespace") ? Def->getValueAsString("Namespace") : ""; OS << " GIR_AddImplicitDef, " << InsnID << ", " << Namespace << "::" << Def->getName() << ",\n"; } for (auto Use : I->ImplicitUses) { auto Namespace = Use->getValue("Namespace") ? Use->getValueAsString("Namespace") : ""; OS << " GIR_AddImplicitUse, " << InsnID << ", " << Namespace << "::" << Use->getName() << ",\n"; } } return; } // TODO: Simple permutation looks like it could be almost as common as // mutation due to commutative operations. OS << " GIR_BuildMI, /*InsnID*/" << InsnID << ", /*Opcode*/" << I->Namespace << "::" << I->TheDef->getName() << ",\n"; for (const auto &Renderer : OperandRenderers) Renderer->emitRenderOpcodes(OS, Rule); OS << " GIR_MergeMemOperands, /*InsnID*/" << InsnID << ",\n" << " GIR_EraseFromParent, /*InsnID*/" << RecycleInsnID << ",\n"; } }; /// Generates code to constrain the operands of an output instruction to the /// register classes specified by the definition of that instruction. class ConstrainOperandsToDefinitionAction : public MatchAction { unsigned InsnID; public: ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {} void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, unsigned RecycleInsnID) const override { OS << " GIR_ConstrainSelectedInstOperands, /*InsnID*/" << InsnID << ",\n"; } }; /// Generates code to constrain the specified operand of an output instruction /// to the specified register class. class ConstrainOperandToRegClassAction : public MatchAction { unsigned InsnID; unsigned OpIdx; const CodeGenRegisterClass &RC; public: ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx, const CodeGenRegisterClass &RC) : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {} void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, unsigned RecycleInsnID) const override { OS << " GIR_ConstrainOperandRC, /*InsnID*/" << InsnID << ", /*Op*/" << OpIdx << ", /*RC " << RC.getName() << "*/ " << RC.EnumValue << ",\n"; } }; InstructionMatcher &RuleMatcher::addInstructionMatcher() { Matchers.emplace_back(new InstructionMatcher()); return *Matchers.back(); } void RuleMatcher::addRequiredFeature(Record *Feature) { RequiredFeatures.push_back(Feature); } const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const { return RequiredFeatures; } template <class Kind, class... Args> Kind &RuleMatcher::addAction(Args &&... args) { Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...)); return *static_cast<Kind *>(Actions.back().get()); } unsigned RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) { unsigned NewInsnVarID = NextInsnVarID++; InsnVariableIDs[&Matcher] = NewInsnVarID; return NewInsnVarID; } unsigned RuleMatcher::defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher, unsigned InsnID, unsigned OpIdx) { unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher); OS << " GIM_RecordInsn, /*DefineMI*/" << NewInsnVarID << ", /*MI*/" << InsnID << ", /*OpIdx*/" << OpIdx << ", // MIs[" << NewInsnVarID << "]\n"; return NewInsnVarID; } unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const { const auto &I = InsnVariableIDs.find(&InsnMatcher); if (I != InsnVariableIDs.end()) return I->second; llvm_unreachable("Matched Insn was not captured in a local variable"); } /// Emit MatchTable opcodes to check the shape of the match and capture /// instructions into local variables. void RuleMatcher::emitCaptureOpcodes(raw_ostream &OS) { assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front()); Matchers.front()->emitCaptureOpcodes(OS, *this, InsnVarID); } void RuleMatcher::emit(raw_ostream &OS) { if (Matchers.empty()) llvm_unreachable("Unexpected empty matcher!"); // The representation supports rules that require multiple roots such as: // %ptr(p0) = ... // %elt0(s32) = G_LOAD %ptr // %1(p0) = G_ADD %ptr, 4 // %elt1(s32) = G_LOAD p0 %1 // which could be usefully folded into: // %ptr(p0) = ... // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr // on some targets but we don't need to make use of that yet. assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); OS << " const static int64_t MatchTable" << CurrentMatchTableID << "[] = {\n"; if (!RequiredFeatures.empty()) { OS << " GIM_CheckFeatures, " << getNameForFeatureBitset(RequiredFeatures) << ",\n"; } emitCaptureOpcodes(OS); Matchers.front()->emitPredicateOpcodes(OS, *this, getInsnVarID(*Matchers.front())); // We must also check if it's safe to fold the matched instructions. if (InsnVariableIDs.size() >= 2) { // Invert the map to create stable ordering (by var names) SmallVector<unsigned, 2> InsnIDs; for (const auto &Pair : InsnVariableIDs) { // Skip the root node since it isn't moving anywhere. Everything else is // sinking to meet it. if (Pair.first == Matchers.front().get()) continue; InsnIDs.push_back(Pair.second); } std::sort(InsnIDs.begin(), InsnIDs.end()); for (const auto &InsnID : InsnIDs) { // Reject the difficult cases until we have a more accurate check. OS << " GIM_CheckIsSafeToFold, /*InsnID*/" << InsnID << ",\n"; // FIXME: Emit checks to determine it's _actually_ safe to fold and/or // account for unsafe cases. // // Example: // MI1--> %0 = ... // %1 = ... %0 // MI0--> %2 = ... %0 // It's not safe to erase MI1. We currently handle this by not // erasing %0 (even when it's dead). // // Example: // MI1--> %0 = load volatile @a // %1 = load volatile @a // MI0--> %2 = ... %0 // It's not safe to sink %0's def past %1. We currently handle // this by rejecting all loads. // // Example: // MI1--> %0 = load @a // %1 = store @a // MI0--> %2 = ... %0 // It's not safe to sink %0's def past %1. We currently handle // this by rejecting all loads. // // Example: // G_CONDBR %cond, @BB1 // BB0: // MI1--> %0 = load @a // G_BR @BB1 // BB1: // MI0--> %2 = ... %0 // It's not always safe to sink %0 across control flow. In this // case it may introduce a memory fault. We currentl handle this // by rejecting all loads. } } for (const auto &MA : Actions) MA->emitCxxActionStmts(OS, *this, 0); OS << " GIR_Done,\n" << " };\n" << " State.MIs.resize(1);\n" << " DEBUG(dbgs() << \"Processing MatchTable" << CurrentMatchTableID << "\\n\");\n" << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, MatchTable" << CurrentMatchTableID << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n" << " return true;\n" << " }\n\n"; } bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const { // Rules involving more match roots have higher priority. if (Matchers.size() > B.Matchers.size()) return true; if (Matchers.size() < B.Matchers.size()) return false; for (const auto &Matcher : zip(Matchers, B.Matchers)) { if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher))) return true; if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher))) return false; } return false; } unsigned RuleMatcher::countRendererFns() const { return std::accumulate( Matchers.begin(), Matchers.end(), 0, [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) { return A + Matcher->countRendererFns(); }); } //===- GlobalISelEmitter class --------------------------------------------===// class GlobalISelEmitter { public: explicit GlobalISelEmitter(RecordKeeper &RK); void run(raw_ostream &OS); private: const RecordKeeper &RK; const CodeGenDAGPatterns CGP; const CodeGenTarget &Target; CodeGenRegBank CGRegs; /// Keep track of the equivalence between SDNodes and Instruction. /// This is defined using 'GINodeEquiv' in the target description. DenseMap<Record *, const CodeGenInstruction *> NodeEquivs; /// Keep track of the equivalence between ComplexPattern's and /// GIComplexOperandMatcher. Map entries are specified by subclassing /// GIComplexPatternEquiv. DenseMap<const Record *, const Record *> ComplexPatternEquivs; // Map of predicates to their subtarget features. SubtargetFeatureInfoMap SubtargetFeatures; void gatherNodeEquivs(); const CodeGenInstruction *findNodeEquiv(Record *N) const; Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates); Expected<InstructionMatcher &> createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher, const TreePatternNode *Src, unsigned &TempOpIdx) const; Error importChildMatcher(InstructionMatcher &InsnMatcher, const TreePatternNode *SrcChild, unsigned OpIdx, unsigned &TempOpIdx) const; Expected<BuildMIAction &> createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst, const InstructionMatcher &InsnMatcher); Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder, TreePatternNode *DstChild, const InstructionMatcher &InsnMatcher) const; Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const; Error importImplicitDefRenderers(BuildMIAction &DstMIBuilder, const std::vector<Record *> &ImplicitDefs) const; /// Analyze pattern \p P, returning a matcher for it if possible. /// Otherwise, return an Error explaining why we don't support it. Expected<RuleMatcher> runOnPattern(const PatternToMatch &P); void declareSubtargetFeature(Record *Predicate); }; void GlobalISelEmitter::gatherNodeEquivs() { assert(NodeEquivs.empty()); for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) NodeEquivs[Equiv->getValueAsDef("Node")] = &Target.getInstruction(Equiv->getValueAsDef("I")); assert(ComplexPatternEquivs.empty()); for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) { Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); if (!SelDAGEquiv) continue; ComplexPatternEquivs[SelDAGEquiv] = Equiv; } } const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const { return NodeEquivs.lookup(N); } GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {} //===- Emitter ------------------------------------------------------------===// Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates) { for (const Init *Predicate : Predicates) { const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate); declareSubtargetFeature(PredicateDef->getDef()); M.addRequiredFeature(PredicateDef->getDef()); } return Error::success(); } Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher, const TreePatternNode *Src, unsigned &TempOpIdx) const { const CodeGenInstruction *SrcGIOrNull = nullptr; // Start with the defined operands (i.e., the results of the root operator). if (Src->getExtTypes().size() > 1) return failedImport("Src pattern has multiple results"); if (Src->isLeaf()) { Init *SrcInit = Src->getLeafValue(); if (isa<IntInit>(SrcInit)) { InsnMatcher.addPredicate<InstructionOpcodeMatcher>( &Target.getInstruction(RK.getDef("G_CONSTANT"))); } else return failedImport( "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); } else { SrcGIOrNull = findNodeEquiv(Src->getOperator()); if (!SrcGIOrNull) return failedImport("Pattern operator lacks an equivalent Instruction" + explainOperator(Src->getOperator())); auto &SrcGI = *SrcGIOrNull; // The operators look good: match the opcode InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI); } unsigned OpIdx = 0; for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { auto OpTyOrNone = MVTToLLT(Ty.getConcrete()); if (!OpTyOrNone) return failedImport( "Result of Src pattern operator has an unsupported type"); // Results don't have a name unless they are the root node. The caller will // set the name if appropriate. OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); } if (Src->isLeaf()) { Init *SrcInit = Src->getLeafValue(); if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) { OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue()); } else return failedImport( "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); } else { assert(SrcGIOrNull && "Expected to have already found an equivalent Instruction"); // Match the used operands (i.e. the children of the operator). for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) { TreePatternNode *SrcChild = Src->getChild(i); // For G_INTRINSIC, the operand immediately following the defs is an // intrinsic ID. if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) { if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) { OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx); OM.addPredicate<IntrinsicIDOperandMatcher>(II); continue; } return failedImport("Expected IntInit containing instrinsic ID)"); } if (auto Error = importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx)) return std::move(Error); } } return InsnMatcher; } Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher, const TreePatternNode *SrcChild, unsigned OpIdx, unsigned &TempOpIdx) const { OperandMatcher &OM = InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx); if (SrcChild->hasAnyPredicate()) return failedImport("Src pattern child has predicate (" + explainPredicates(SrcChild) + ")"); ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes(); if (ChildTypes.size() != 1) return failedImport("Src pattern child has multiple results"); // Check MBB's before the type check since they are not a known type. if (!SrcChild->isLeaf()) { if (SrcChild->getOperator()->isSubClassOf("SDNode")) { auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { OM.addPredicate<MBBOperandMatcher>(); return Error::success(); } } } auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); if (!OpTyOrNone) return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")"); OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); // Check for nested instructions. if (!SrcChild->isLeaf()) { // Map the node to a gMIR instruction. InstructionOperandMatcher &InsnOperand = OM.addPredicate<InstructionOperandMatcher>(); auto InsnMatcherOrError = createAndImportSelDAGMatcher( InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx); if (auto Error = InsnMatcherOrError.takeError()) return Error; return Error::success(); } // Check for constant immediates. if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) { OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue()); return Error::success(); } // Check for def's like register classes or ComplexPattern's. if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { auto *ChildRec = ChildDefInit->getDef(); // Check for register classes. if (ChildRec->isSubClassOf("RegisterClass") || ChildRec->isSubClassOf("RegisterOperand")) { OM.addPredicate<RegisterBankOperandMatcher>( Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit))); return Error::success(); } // Check for ComplexPattern's. if (ChildRec->isSubClassOf("ComplexPattern")) { const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); if (ComplexPattern == ComplexPatternEquivs.end()) return failedImport("SelectionDAG ComplexPattern (" + ChildRec->getName() + ") not mapped to GlobalISel"); OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second); TempOpIdx++; return Error::success(); } if (ChildRec->isSubClassOf("ImmLeaf")) { return failedImport( "Src pattern child def is an unsupported tablegen class (ImmLeaf)"); } return failedImport( "Src pattern child def is an unsupported tablegen class"); } return failedImport("Src pattern child is an unsupported kind"); } Error GlobalISelEmitter::importExplicitUseRenderer( BuildMIAction &DstMIBuilder, TreePatternNode *DstChild, const InstructionMatcher &InsnMatcher) const { // The only non-leaf child we accept is 'bb': it's an operator because // BasicBlockSDNode isn't inline, but in MI it's just another operand. if (!DstChild->isLeaf()) { if (DstChild->getOperator()->isSubClassOf("SDNode")) { auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator()); if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstChild->getName()); return Error::success(); } } return failedImport("Dst pattern child isn't a leaf node or an MBB"); } // Otherwise, we're looking for a bog-standard RegisterClass operand. if (DstChild->hasAnyPredicate()) return failedImport("Dst pattern child has predicate (" + explainPredicates(DstChild) + ")"); if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) { auto *ChildRec = ChildDefInit->getDef(); ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes(); if (ChildTypes.size() != 1) return failedImport("Dst pattern child has multiple results"); auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); if (!OpTyOrNone) return failedImport("Dst operand has an unsupported type"); if (ChildRec->isSubClassOf("Register")) { DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec); return Error::success(); } if (ChildRec->isSubClassOf("RegisterClass") || ChildRec->isSubClassOf("RegisterOperand")) { DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstChild->getName()); return Error::success(); } if (ChildRec->isSubClassOf("ComplexPattern")) { const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); if (ComplexPattern == ComplexPatternEquivs.end()) return failedImport( "SelectionDAG ComplexPattern not mapped to GlobalISel"); const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName()); DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 0, *ComplexPattern->second, DstChild->getName(), OM.getAllocatedTemporariesBaseID()); return Error::success(); } if (ChildRec->isSubClassOf("SDNodeXForm")) return failedImport("Dst pattern child def is an unsupported tablegen " "class (SDNodeXForm)"); return failedImport( "Dst pattern child def is an unsupported tablegen class"); } return failedImport("Dst pattern child is an unsupported kind"); } Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer( RuleMatcher &M, const TreePatternNode *Dst, const InstructionMatcher &InsnMatcher) { Record *DstOp = Dst->getOperator(); if (!DstOp->isSubClassOf("Instruction")) { if (DstOp->isSubClassOf("ValueType")) return failedImport( "Pattern operator isn't an instruction (it's a ValueType)"); return failedImport("Pattern operator isn't an instruction"); } CodeGenInstruction *DstI = &Target.getInstruction(DstOp); unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs; unsigned ExpectedDstINumUses = Dst->getNumChildren(); bool IsExtractSubReg = false; // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy. if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") { DstI = &Target.getInstruction(RK.getDef("COPY")); DstINumUses--; // Ignore the class constraint. ExpectedDstINumUses--; } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") { DstI = &Target.getInstruction(RK.getDef("COPY")); IsExtractSubReg = true; } auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher); // Render the explicit defs. for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) { const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I]; DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name); } // EXTRACT_SUBREG needs to use a subregister COPY. if (IsExtractSubReg) { if (!Dst->getChild(0)->isLeaf()) return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); if (DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) { CodeGenRegisterClass *RC = CGRegs.getRegClass( getInitValueAsRegClass(Dst->getChild(0)->getLeafValue())); CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); const auto &SrcRCDstRCPair = RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); if (SrcRCDstRCPair.hasValue()) { assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); if (SrcRCDstRCPair->first != RC) return failedImport("EXTRACT_SUBREG requires an additional COPY"); } DstMIBuilder.addRenderer<CopySubRegRenderer>( 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx); return DstMIBuilder; } return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); } // Render the explicit uses. unsigned Child = 0; unsigned NumDefaultOps = 0; for (unsigned I = 0; I != DstINumUses; ++I) { const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[DstI->Operands.NumDefs + I]; // If the operand has default values, introduce them now. // FIXME: Until we have a decent test case that dictates we should do // otherwise, we're going to assume that operands with default values cannot // be specified in the patterns. Therefore, adding them will not cause us to // end up with too many rendered operands. if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) { DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps"); if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps)) return std::move(Error); ++NumDefaultOps; continue; } if (auto Error = importExplicitUseRenderer( DstMIBuilder, Dst->getChild(Child), InsnMatcher)) return std::move(Error); ++Child; } if (NumDefaultOps + ExpectedDstINumUses != DstINumUses) return failedImport("Expected " + llvm::to_string(DstINumUses) + " used operands but found " + llvm::to_string(ExpectedDstINumUses) + " explicit ones and " + llvm::to_string(NumDefaultOps) + " default ones"); return DstMIBuilder; } Error GlobalISelEmitter::importDefaultOperandRenderers( BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const { for (const auto *DefaultOp : DefaultOps->getArgs()) { // Look through ValueType operators. if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) { if (const DefInit *DefaultDagOperator = dyn_cast<DefInit>(DefaultDagOp->getOperator())) { if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) DefaultOp = DefaultDagOp->getArg(0); } } if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) { DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef()); continue; } if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) { DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue()); continue; } return failedImport("Could not add default op"); } return Error::success(); } Error GlobalISelEmitter::importImplicitDefRenderers( BuildMIAction &DstMIBuilder, const std::vector<Record *> &ImplicitDefs) const { if (!ImplicitDefs.empty()) return failedImport("Pattern defines a physical register"); return Error::success(); } Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) { // Keep track of the matchers and actions to emit. RuleMatcher M; M.addAction<DebugCommentAction>(P); if (auto Error = importRulePredicates(M, P.getPredicates()->getValues())) return std::move(Error); // Next, analyze the pattern operators. TreePatternNode *Src = P.getSrcPattern(); TreePatternNode *Dst = P.getDstPattern(); // If the root of either pattern isn't a simple operator, ignore it. if (auto Err = isTrivialOperatorNode(Dst)) return failedImport("Dst pattern root isn't a trivial operator (" + toString(std::move(Err)) + ")"); if (auto Err = isTrivialOperatorNode(Src)) return failedImport("Src pattern root isn't a trivial operator (" + toString(std::move(Err)) + ")"); if (Dst->isLeaf()) return failedImport("Dst pattern root isn't a known leaf"); // Start with the defined operands (i.e., the results of the root operator). Record *DstOp = Dst->getOperator(); if (!DstOp->isSubClassOf("Instruction")) return failedImport("Pattern operator isn't an instruction"); auto &DstI = Target.getInstruction(DstOp); if (DstI.Operands.NumDefs != Src->getExtTypes().size()) return failedImport("Src pattern results and dst MI defs are different (" + to_string(Src->getExtTypes().size()) + " def(s) vs " + to_string(DstI.Operands.NumDefs) + " def(s))"); InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(); unsigned TempOpIdx = 0; auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx); if (auto Error = InsnMatcherOrError.takeError()) return std::move(Error); InstructionMatcher &InsnMatcher = InsnMatcherOrError.get(); // The root of the match also has constraints on the register bank so that it // matches the result instruction. unsigned OpIdx = 0; for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { (void)Ty; const auto &DstIOperand = DstI.Operands[OpIdx]; Record *DstIOpRec = DstIOperand.Rec; if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); if (DstIOpRec == nullptr) return failedImport( "COPY_TO_REGCLASS operand #1 isn't a register class"); } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { if (!Dst->getChild(0)->isLeaf()) return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf"); // We can assume that a subregister is in the same bank as it's super // register. DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); if (DstIOpRec == nullptr) return failedImport( "EXTRACT_SUBREG operand #0 isn't a register class"); } else if (DstIOpRec->isSubClassOf("RegisterOperand")) DstIOpRec = DstIOpRec->getValueAsDef("RegClass"); else if (!DstIOpRec->isSubClassOf("RegisterClass")) return failedImport("Dst MI def isn't a register class" + to_string(*Dst)); OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); OM.setSymbolicName(DstIOperand.Name); OM.addPredicate<RegisterBankOperandMatcher>( Target.getRegisterClass(DstIOpRec)); ++OpIdx; } auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst, InsnMatcher); if (auto Error = DstMIBuilderOrError.takeError()) return std::move(Error); BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get(); // Render the implicit defs. // These are only added to the root of the result. if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs())) return std::move(Error); // Constrain the registers to classes. This is normally derived from the // emitted instruction but a few instructions require special handling. if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { // COPY_TO_REGCLASS does not provide operand constraints itself but the // result is constrained to the class given by the second child. Record *DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); if (DstIOpRec == nullptr) return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class"); M.addAction<ConstrainOperandToRegClassAction>( 0, 0, Target.getRegisterClass(DstIOpRec)); // We're done with this pattern! It's eligible for GISel emission; return // it. ++NumPatternImported; return std::move(M); } if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { // EXTRACT_SUBREG selects into a subregister COPY but unlike most // instructions, the result register class is controlled by the // subregisters of the operand. As a result, we must constrain the result // class rather than check that it's already the right one. if (!Dst->getChild(0)->isLeaf()) return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); if (!SubRegInit) return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); // Constrain the result to the same register bank as the operand. Record *DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); if (DstIOpRec == nullptr) return failedImport("EXTRACT_SUBREG operand #1 isn't a register class"); CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec); // It would be nice to leave this constraint implicit but we're required // to pick a register class so constrain the result to a register class // that can hold the correct MVT. // // FIXME: This may introduce an extra copy if the chosen class doesn't // actually contain the subregisters. assert(Src->getExtTypes().size() == 1 && "Expected Src of EXTRACT_SUBREG to have one result type"); const auto &SrcRCDstRCPair = SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second); M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first); // We're done with this pattern! It's eligible for GISel emission; return // it. ++NumPatternImported; return std::move(M); } M.addAction<ConstrainOperandsToDefinitionAction>(0); // We're done with this pattern! It's eligible for GISel emission; return it. ++NumPatternImported; return std::move(M); } void GlobalISelEmitter::run(raw_ostream &OS) { // Track the GINodeEquiv definitions. gatherNodeEquivs(); emitSourceFileHeader(("Global Instruction Selector for the " + Target.getName() + " target").str(), OS); std::vector<RuleMatcher> Rules; // Look through the SelectionDAG patterns we found, possibly emitting some. for (const PatternToMatch &Pat : CGP.ptms()) { ++NumPatternTotal; auto MatcherOrErr = runOnPattern(Pat); // The pattern analysis can fail, indicating an unsupported pattern. // Report that if we've been asked to do so. if (auto Err = MatcherOrErr.takeError()) { if (WarnOnSkippedPatterns) { PrintWarning(Pat.getSrcRecord()->getLoc(), "Skipped pattern: " + toString(std::move(Err))); } else { consumeError(std::move(Err)); } ++NumPatternImportsSkipped; continue; } Rules.push_back(std::move(MatcherOrErr.get())); } std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A, const RuleMatcher &B) { if (A.isHigherPriorityThan(B)) { assert(!B.isHigherPriorityThan(A) && "Cannot be more important " "and less important at " "the same time"); return true; } return false; }); std::vector<Record *> ComplexPredicates = RK.getAllDerivedDefinitions("GIComplexOperandMatcher"); std::sort(ComplexPredicates.begin(), ComplexPredicates.end(), [](const Record *A, const Record *B) { if (A->getName() < B->getName()) return true; return false; }); unsigned MaxTemporaries = 0; for (const auto &Rule : Rules) MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns()); OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n" << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size() << ";\n" << "using PredicateBitset = " "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n" << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n"; OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n" << " mutable MatcherState State;\n" << " typedef " "ComplexRendererFn(" << Target.getName() << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n" << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> " "MatcherInfo;\n" << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n"; OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n" << ", State(" << MaxTemporaries << "),\n" << "MatcherInfo({TypeObjects, FeatureBitsets, {\n" << " nullptr, // GICP_Invalid\n"; for (const auto &Record : ComplexPredicates) OS << " &" << Target.getName() << "InstructionSelector::" << Record->getValueAsString("MatcherFn") << ", // " << Record->getName() << "\n"; OS << "}})\n" << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n"; OS << "#ifdef GET_GLOBALISEL_IMPL\n"; SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, OS); // Separate subtarget features by how often they must be recomputed. SubtargetFeatureInfoMap ModuleFeatures; std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), std::inserter(ModuleFeatures, ModuleFeatures.end()), [](const SubtargetFeatureInfoMap::value_type &X) { return !X.second.mustRecomputePerFunction(); }); SubtargetFeatureInfoMap FunctionFeatures; std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), std::inserter(FunctionFeatures, FunctionFeatures.end()), [](const SubtargetFeatureInfoMap::value_type &X) { return X.second.mustRecomputePerFunction(); }); SubtargetFeatureInfo::emitComputeAvailableFeatures( Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures", ModuleFeatures, OS); SubtargetFeatureInfo::emitComputeAvailableFeatures( Target.getName(), "InstructionSelector", "computeAvailableFunctionFeatures", FunctionFeatures, OS, "const MachineFunction *MF"); // Emit a table containing the LLT objects needed by the matcher and an enum // for the matcher to reference them with. std::vector<LLTCodeGen> TypeObjects = { LLT::scalar(8), LLT::scalar(16), LLT::scalar(32), LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1), LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1), LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8), LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16), LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32), LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32), LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64), }; std::sort(TypeObjects.begin(), TypeObjects.end()); OS << "enum {\n"; for (const auto &TypeObject : TypeObjects) { OS << " "; TypeObject.emitCxxEnumValue(OS); OS << ",\n"; } OS << "};\n" << "const static LLT TypeObjects[] = {\n"; for (const auto &TypeObject : TypeObjects) { OS << " "; TypeObject.emitCxxConstructorCall(OS); OS << ",\n"; } OS << "};\n\n"; // Emit a table containing the PredicateBitsets objects needed by the matcher // and an enum for the matcher to reference them with. std::vector<std::vector<Record *>> FeatureBitsets; for (auto &Rule : Rules) FeatureBitsets.push_back(Rule.getRequiredFeatures()); std::sort( FeatureBitsets.begin(), FeatureBitsets.end(), [&](const std::vector<Record *> &A, const std::vector<Record *> &B) { if (A.size() < B.size()) return true; if (A.size() > B.size()) return false; for (const auto &Pair : zip(A, B)) { if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName()) return true; if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName()) return false; } return false; }); FeatureBitsets.erase( std::unique(FeatureBitsets.begin(), FeatureBitsets.end()), FeatureBitsets.end()); OS << "enum {\n" << " GIFBS_Invalid,\n"; for (const auto &FeatureBitset : FeatureBitsets) { if (FeatureBitset.empty()) continue; OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n"; } OS << "};\n" << "const static PredicateBitset FeatureBitsets[] {\n" << " {}, // GIFBS_Invalid\n"; for (const auto &FeatureBitset : FeatureBitsets) { if (FeatureBitset.empty()) continue; OS << " {"; for (const auto &Feature : FeatureBitset) { const auto &I = SubtargetFeatures.find(Feature); assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); OS << I->second.getEnumBitName() << ", "; } OS << "},\n"; } OS << "};\n\n"; // Emit complex predicate table and an enum to reference them with. OS << "enum {\n" << " GICP_Invalid,\n"; for (const auto &Record : ComplexPredicates) OS << " GICP_" << Record->getName() << ",\n"; OS << "};\n" << "// See constructor for table contents\n\n"; OS << "bool " << Target.getName() << "InstructionSelector::selectImpl(MachineInstr &I) const {\n" << " MachineFunction &MF = *I.getParent()->getParent();\n" << " MachineRegisterInfo &MRI = MF.getRegInfo();\n" << " // FIXME: This should be computed on a per-function basis rather " "than per-insn.\n" << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, " "&MF);\n" << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n" << " NewMIVector OutMIs;\n" << " State.MIs.clear();\n" << " State.MIs.push_back(&I);\n\n"; for (auto &Rule : Rules) { Rule.emit(OS); ++CurrentMatchTableID; ++NumPatternEmitted; assert(CurrentMatchTableID == NumPatternEmitted && "Statistic deviates from number of emitted tables"); } OS << " return false;\n" << "}\n" << "#endif // ifdef GET_GLOBALISEL_IMPL\n"; OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n" << "PredicateBitset AvailableModuleFeatures;\n" << "mutable PredicateBitset AvailableFunctionFeatures;\n" << "PredicateBitset getAvailableFeatures() const {\n" << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n" << "}\n" << "PredicateBitset\n" << "computeAvailableModuleFeatures(const " << Target.getName() << "Subtarget *Subtarget) const;\n" << "PredicateBitset\n" << "computeAvailableFunctionFeatures(const " << Target.getName() << "Subtarget *Subtarget,\n" << " const MachineFunction *MF) const;\n" << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n"; OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n" << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n" << "AvailableFunctionFeatures()\n" << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n"; } void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) { if (SubtargetFeatures.count(Predicate) == 0) SubtargetFeatures.emplace( Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size())); } } // end anonymous namespace //===----------------------------------------------------------------------===// namespace llvm { void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { GlobalISelEmitter(RK).run(OS); } } // End llvm namespace
36.968099
94
0.653751
[ "render", "object", "shape", "vector", "transform" ]
caff944d90ffa5ada292f3c371468954217251fb
15,279
cc
C++
includes/openvdb/openvdb/unittest/TestNodeMask.cc
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
6
2020-02-06T03:30:25.000Z
2021-10-12T11:38:24.000Z
includes/openvdb/openvdb/unittest/TestNodeMask.cc
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
1
2021-07-29T17:38:23.000Z
2021-07-29T17:38:23.000Z
includes/openvdb/openvdb/unittest/TestNodeMask.cc
ibfernandes/NarvalEngine
fb9ad53ebc7b244f4eed76f43e7aac2faa94772a
[ "MIT" ]
1
2020-02-14T06:42:03.000Z
2020-02-14T06:42:03.000Z
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) DreamWorks Animation LLC // // All rights reserved. This software is distributed under the // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ ) // // Redistributions of source code must retain the above copyright // and license notice and the following restrictions and disclaimer. // // * Neither the name of DreamWorks Animation 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 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. // IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE // LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00. // /////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <openvdb/Exceptions.h> #include <openvdb/util/NodeMasks.h> #include <openvdb/io/Compression.h> using openvdb::Index; template<typename MaskType> void TestAll(); class TestNodeMask: public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestNodeMask); CPPUNIT_TEST(testAll4); CPPUNIT_TEST(testAll3); CPPUNIT_TEST(testAll2); CPPUNIT_TEST(testAll1); CPPUNIT_TEST(testCompress); CPPUNIT_TEST_SUITE_END(); void testAll4() { TestAll<openvdb::util::NodeMask<4> >(); } void testAll3() { TestAll<openvdb::util::NodeMask<3> >(); } void testAll2() { TestAll<openvdb::util::NodeMask<2> >(); } void testAll1() { TestAll<openvdb::util::NodeMask<1> >(); } void testCompress(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestNodeMask); template<typename MaskType> void TestAll() { CPPUNIT_ASSERT(MaskType::memUsage() == MaskType::SIZE/8); const Index SIZE = MaskType::SIZE > 512 ? 512 : MaskType::SIZE; {// default constructor MaskType m;//all bits are off for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(m.isOff(i)); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(!m.isOn(i)); CPPUNIT_ASSERT(m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(m.countOn() == 0); CPPUNIT_ASSERT(m.countOff()== MaskType::SIZE); m.toggle();//all bits are on CPPUNIT_ASSERT(m.isOn()); CPPUNIT_ASSERT(!m.isOff()); CPPUNIT_ASSERT(m.countOn() == MaskType::SIZE); CPPUNIT_ASSERT(m.countOff()== 0); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(!m.isOff(i)); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(m.isOn(i)); } {// On constructor MaskType m(true);//all bits are on CPPUNIT_ASSERT(m.isOn()); CPPUNIT_ASSERT(!m.isOff()); CPPUNIT_ASSERT(m.countOn() == MaskType::SIZE); CPPUNIT_ASSERT(m.countOff()== 0); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(!m.isOff(i)); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(m.isOn(i)); m.toggle(); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(m.isOff(i)); for (Index i=0; i<SIZE; ++i) CPPUNIT_ASSERT(!m.isOn(i)); CPPUNIT_ASSERT(m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(m.countOn() == 0); CPPUNIT_ASSERT(m.countOff()== MaskType::SIZE); } {// Off constructor MaskType m(false); CPPUNIT_ASSERT(m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(m.countOn() == 0); CPPUNIT_ASSERT(m.countOff()== MaskType::SIZE); m.setOn(); CPPUNIT_ASSERT(m.isOn()); CPPUNIT_ASSERT(!m.isOff()); CPPUNIT_ASSERT(m.countOn() == MaskType::SIZE); CPPUNIT_ASSERT(m.countOff()== 0); m = MaskType();//copy asignment CPPUNIT_ASSERT(m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(m.countOn() == 0); CPPUNIT_ASSERT(m.countOff()== MaskType::SIZE); } {// test setOn, setOff, findFirstOn and findFiratOff MaskType m; for (Index i=0; i<SIZE; ++i) { m.setOn(i); CPPUNIT_ASSERT(m.countOn() == 1); CPPUNIT_ASSERT(m.findFirstOn() == i); CPPUNIT_ASSERT(m.findFirstOff() == (i==0 ? 1 : 0)); for (Index j=0; j<SIZE; ++j) { CPPUNIT_ASSERT( i==j ? m.isOn(j) : m.isOff(j) ); } m.setOff(i); CPPUNIT_ASSERT(m.countOn() == 0); CPPUNIT_ASSERT(m.findFirstOn() == MaskType::SIZE); } } {// OnIterator MaskType m; for (Index i=0; i<SIZE; ++i) { m.setOn(i); for (typename MaskType::OnIterator iter=m.beginOn(); iter; ++iter) { CPPUNIT_ASSERT( iter.pos() == i ); } CPPUNIT_ASSERT(m.countOn() == 1); m.setOff(i); CPPUNIT_ASSERT(m.countOn() == 0); } } {// OffIterator MaskType m(true); for (Index i=0; i<SIZE; ++i) { m.setOff(i); CPPUNIT_ASSERT(m.countOff() == 1); for (typename MaskType::OffIterator iter=m.beginOff(); iter; ++iter) { CPPUNIT_ASSERT( iter.pos() == i ); } CPPUNIT_ASSERT(m.countOn() == MaskType::SIZE-1); m.setOn(i); CPPUNIT_ASSERT(m.countOff() == 0); CPPUNIT_ASSERT(m.countOn() == MaskType::SIZE); } } {// isConstant MaskType m(true);//all bits are on bool isOn = false; CPPUNIT_ASSERT(!m.isOff()); CPPUNIT_ASSERT(m.isOn()); CPPUNIT_ASSERT(m.isConstant(isOn)); CPPUNIT_ASSERT(isOn); m.setOff(MaskType::SIZE-1);//sets last bit off CPPUNIT_ASSERT(!m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(!m.isConstant(isOn)); m.setOff();//sets all bits off CPPUNIT_ASSERT(m.isOff()); CPPUNIT_ASSERT(!m.isOn()); CPPUNIT_ASSERT(m.isConstant(isOn)); CPPUNIT_ASSERT(!isOn); } {// DenseIterator MaskType m(false); for (Index i=0; i<SIZE; ++i) { m.setOn(i); CPPUNIT_ASSERT(m.countOn() == 1); for (typename MaskType::DenseIterator iter=m.beginDense(); iter; ++iter) { CPPUNIT_ASSERT( iter.pos()==i ? *iter : !*iter ); } m.setOff(i); CPPUNIT_ASSERT(m.countOn() == 0); } } } void TestNodeMask::testCompress() { using namespace openvdb; using ValueT = int; using MaskT = openvdb::util::NodeMask<1>; { // no inactive values MaskT valueMask(true); MaskT childMask; std::vector<int> values = {0,1,2,3,4,5,6,7}; int background = 0; CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(8)); CPPUNIT_ASSERT_EQUAL(childMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_OR_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], background); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // all inactive values are +background MaskT valueMask; MaskT childMask; std::vector<int> values = {10,10,10,10,10,10,10,10}; int background = 10; CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_OR_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], background); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // all inactive values are -background MaskT valueMask; MaskT childMask; std::vector<int> values = {-10,-10,-10,-10,-10,-10,-10,-10}; int background = 10; CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(0)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(maskCompress.metadata, int8_t(openvdb::io::NO_MASK_AND_MINUS_BG)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], -background); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // all inactive vals have the same non-background val MaskT valueMask(true); MaskT childMask; std::vector<int> values = {0,1,500,500,4,500,500,7}; int background = 10; valueMask.setOff(2); valueMask.setOff(3); valueMask.setOff(5); valueMask.setOff(6); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(4)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::NO_MASK_AND_ONE_INACTIVE_VAL)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 500); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // mask selects between -background and +background MaskT valueMask; MaskT childMask; std::vector<int> values = {0,10,10,-10,4,10,-10,10}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_NO_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], -background); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // mask selects between -background and +background MaskT valueMask; MaskT childMask; std::vector<int> values = {0,-10,-10,10,4,-10,10,-10}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_NO_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], -background); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // mask selects between backgd and one other inactive val MaskT valueMask; MaskT childMask; std::vector<int> values = {0,500,500,10,4,500,10,500}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_ONE_INACTIVE_VAL)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 500); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], background); } { // mask selects between two non-background inactive vals MaskT valueMask; MaskT childMask; std::vector<int> values = {0,500,500,2000,4,500,2000,500}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 500); // first unique value CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], 2000); // second unique value } { // mask selects between two non-background inactive vals MaskT valueMask; MaskT childMask; std::vector<int> values = {0,2000,2000,500,4,2000,500,2000}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 2000); // first unique value CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], 500); // second unique value } { // > 2 inactive vals, so no mask compression at all MaskT valueMask; MaskT childMask; std::vector<int> values = {0,1000,2000,3000,4,2000,500,2000}; int background = 10; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::NO_MASK_AND_ALL_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 1000); // first unique value CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], 2000); // second unique value } { // mask selects between two non-background inactive vals (selective child mask) MaskT valueMask; MaskT childMask; std::vector<int> values = {0,1000,2000,3000,4,2000,500,2000}; int background = 0; valueMask.setOn(0); valueMask.setOn(4); CPPUNIT_ASSERT_EQUAL(valueMask.countOn(), Index32(2)); childMask.setOn(3); childMask.setOn(6); CPPUNIT_ASSERT_EQUAL(childMask.countOn(), Index32(2)); openvdb::io::MaskCompress<ValueT, MaskT> maskCompress( valueMask, childMask, values.data(), background); CPPUNIT_ASSERT_EQUAL(int(maskCompress.metadata), int(openvdb::io::MASK_AND_TWO_INACTIVE_VALS)); CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[0], 1000); // first unique value CPPUNIT_ASSERT_EQUAL(maskCompress.inactiveVal[1], 2000); // secone unique value } } // Copyright (c) DreamWorks Animation LLC // All rights reserved. This software is distributed under the // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
37.913151
105
0.628641
[ "vector" ]
caffca5de3f8ad867a07ca27fdbad138b628116e
21,446
cc
C++
components/sync/driver/glue/sync_engine_backend.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
components/sync/driver/glue/sync_engine_backend.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
components/sync/driver/glue/sync_engine_backend.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 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 "components/sync/driver/glue/sync_engine_backend.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/public/invalidation_util.h" #include "components/sync/base/invalidation_adapter.h" #include "components/sync/base/legacy_directory_deletion.h" #include "components/sync/base/sync_base_switches.h" #include "components/sync/driver/configure_context.h" #include "components/sync/driver/glue/sync_engine_impl.h" #include "components/sync/driver/model_type_controller.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/engine/cycle/sync_cycle_snapshot.h" #include "components/sync/engine/engine_components_factory.h" #include "components/sync/engine/events/protocol_event.h" #include "components/sync/engine/net/http_post_provider_factory.h" #include "components/sync/engine/sync_manager.h" #include "components/sync/engine/sync_manager_factory.h" #include "components/sync/invalidations/switches.h" #include "components/sync/model/forwarding_model_type_controller_delegate.h" #include "components/sync/nigori/nigori_model_type_processor.h" #include "components/sync/nigori/nigori_storage_impl.h" #include "components/sync/nigori/nigori_sync_bridge_impl.h" #include "components/sync/protocol/sync_invalidations_payload.pb.h" // Helper macros to log with the syncer thread name; useful when there // are multiple syncers involved. #define SDVLOG(verbose_level) DVLOG(verbose_level) << name_ << ": " namespace syncer { namespace { const base::FilePath::CharType kNigoriStorageFilename[] = FILE_PATH_LITERAL("Nigori.bin"); class SyncInvalidationAdapter : public InvalidationInterface { public: explicit SyncInvalidationAdapter(const std::string& payload) : payload_(payload) {} ~SyncInvalidationAdapter() override = default; bool IsUnknownVersion() const override { return true; } const std::string& GetPayload() const override { return payload_; } int64_t GetVersion() const override { // TODO(crbug.com/1102322): implement versions. This method is not called // until IsUnknownVersion() returns true. NOTREACHED(); return 0; } void Acknowledge() override { NOTIMPLEMENTED(); } void Drop() override { NOTIMPLEMENTED(); } private: const std::string payload_; }; } // namespace SyncEngineBackend::RestoredLocalTransportData::RestoredLocalTransportData() = default; SyncEngineBackend::RestoredLocalTransportData::RestoredLocalTransportData( RestoredLocalTransportData&&) = default; SyncEngineBackend::RestoredLocalTransportData::~RestoredLocalTransportData() = default; SyncEngineBackend::SyncEngineBackend(const std::string& name, const base::FilePath& sync_data_folder, const base::WeakPtr<SyncEngineImpl>& host) : name_(name), sync_data_folder_(sync_data_folder), host_(host) { DCHECK(host); // This is constructed on the UI thread but used from another thread. DETACH_FROM_SEQUENCE(sequence_checker_); } SyncEngineBackend::~SyncEngineBackend() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void SyncEngineBackend::OnSyncCycleCompleted( const SyncCycleSnapshot& snapshot) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_.Call(FROM_HERE, &SyncEngineImpl::HandleSyncCycleCompletedOnFrontendLoop, snapshot); } void SyncEngineBackend::DoRefreshTypes(ModelTypeSet types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->RefreshTypes(types); } void SyncEngineBackend::OnConnectionStatusChange(ConnectionStatus status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_.Call(FROM_HERE, &SyncEngineImpl::HandleConnectionStatusChangeOnFrontendLoop, status); } void SyncEngineBackend::OnActionableError(const SyncProtocolError& sync_error) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_.Call(FROM_HERE, &SyncEngineImpl::HandleActionableErrorEventOnFrontendLoop, sync_error); } void SyncEngineBackend::OnMigrationRequested(ModelTypeSet types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_.Call(FROM_HERE, &SyncEngineImpl::HandleMigrationRequestedOnFrontendLoop, types); } void SyncEngineBackend::OnProtocolEvent(const ProtocolEvent& event) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (forward_protocol_events_) { std::unique_ptr<ProtocolEvent> event_clone(event.Clone()); host_.Call(FROM_HERE, &SyncEngineImpl::HandleProtocolEventOnFrontendLoop, std::move(event_clone)); } } void SyncEngineBackend::OnSyncStatusChanged(const SyncStatus& status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); host_.Call(FROM_HERE, &SyncEngineImpl::HandleSyncStatusChanged, status); } void SyncEngineBackend::DoOnInvalidatorStateChange( invalidation::InvalidatorState state) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->SetInvalidatorEnabled(state == invalidation::INVALIDATIONS_ENABLED); } void SyncEngineBackend::RecordRedundantInvalidationsMetric( const invalidation::Invalidation& invalidation, ModelType type) const { auto last_invalidation = last_invalidation_versions_.find(type); if (!invalidation.is_unknown_version() && last_invalidation != last_invalidation_versions_.end() && invalidation.version() <= last_invalidation->second) { UMA_HISTOGRAM_ENUMERATION("Sync.RedundantInvalidationPerModelType2", ModelTypeHistogramValue(type)); } } void SyncEngineBackend::DoOnIncomingInvalidation( const invalidation::TopicInvalidationMap& invalidation_map) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); for (const invalidation::Topic& topic : invalidation_map.GetTopics()) { ModelType type; if (!NotificationTypeToRealModelType(topic, &type)) { DLOG(WARNING) << "Notification has invalid topic: " << topic; } else { UMA_HISTOGRAM_ENUMERATION("Sync.InvalidationPerModelType", ModelTypeHistogramValue(type)); invalidation::SingleTopicInvalidationSet invalidation_set = invalidation_map.ForTopic(topic); for (invalidation::Invalidation invalidation : invalidation_set) { RecordRedundantInvalidationsMetric(invalidation, type); std::unique_ptr<InvalidationInterface> inv_adapter( new InvalidationAdapter(invalidation)); sync_manager_->OnIncomingInvalidation(type, std::move(inv_adapter)); if (!invalidation.is_unknown_version()) last_invalidation_versions_[type] = invalidation.version(); } } } host_.Call(FROM_HERE, &SyncEngineImpl::UpdateInvalidationVersions, last_invalidation_versions_); } void SyncEngineBackend::DoInitialize( SyncEngine::InitParams params, RestoredLocalTransportData restored_local_transport_data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Make sure that the directory exists before initializing the backend. // If it already exists, this will do no harm. if (!base::CreateDirectory(sync_data_folder_)) { DLOG(FATAL) << "Sync Data directory creation failed."; } // Load the previously persisted set of invalidation versions into memory. last_invalidation_versions_ = restored_local_transport_data.invalidation_versions; authenticated_account_id_ = params.authenticated_account_info.account_id; auto nigori_processor = std::make_unique<NigoriModelTypeProcessor>(); nigori_controller_ = std::make_unique<ModelTypeController>( NIGORI, std::make_unique<ForwardingModelTypeControllerDelegate>( nigori_processor->GetControllerDelegate().get())); sync_encryption_handler_ = std::make_unique<NigoriSyncBridgeImpl>( std::move(nigori_processor), std::make_unique<NigoriStorageImpl>( sync_data_folder_.Append(kNigoriStorageFilename), &encryptor_), &encryptor_, base::BindRepeating(&Nigori::GenerateScryptSalt), params.encryption_bootstrap_token, restored_local_transport_data.keystore_encryption_bootstrap_token); sync_manager_ = params.sync_manager_factory->CreateSyncManager(name_); sync_manager_->AddObserver(this); SyncManager::InitArgs args; args.service_url = params.service_url; args.enable_local_sync_backend = params.enable_local_sync_backend; args.local_sync_backend_folder = params.local_sync_backend_folder; args.post_factory = std::move(params.http_factory_getter).Run(); args.encryption_observer_proxy = std::move(params.encryption_observer_proxy); args.extensions_activity = params.extensions_activity.get(); args.invalidator_client_id = params.invalidator_client_id; args.engine_components_factory = std::move(params.engine_components_factory); args.encryption_handler = sync_encryption_handler_.get(); args.cancelation_signal = &stop_syncing_signal_; args.poll_interval = restored_local_transport_data.poll_interval; args.cache_guid = restored_local_transport_data.cache_guid; args.birthday = restored_local_transport_data.birthday; args.bag_of_chips = restored_local_transport_data.bag_of_chips; sync_manager_->Init(&args); LoadAndConnectNigoriController(); ConfigureReason reason = sync_manager_->InitialSyncEndedTypes().Empty() ? CONFIGURE_REASON_NEW_CLIENT : CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE; ModelTypeSet new_control_types = Difference(ControlTypes(), sync_manager_->InitialSyncEndedTypes()); SDVLOG(1) << "Control Types " << ModelTypeSetToString(new_control_types) << " added; calling ConfigureSyncer"; sync_manager_->ConfigureSyncer( reason, new_control_types, SyncManager::SyncFeatureState::INITIALIZING, base::BindOnce(&SyncEngineBackend::DoInitialProcessControlTypes, weak_ptr_factory_.GetWeakPtr())); } void SyncEngineBackend::DoUpdateCredentials( const SyncCredentials& credentials) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // UpdateCredentials can be called during backend initialization, possibly // when backend initialization has failed but hasn't notified the UI thread // yet. In that case, the sync manager may have been destroyed on another // thread before this task was executed, so we do nothing. if (sync_manager_) { sync_manager_->UpdateCredentials(credentials); } } void SyncEngineBackend::DoInvalidateCredentials() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (sync_manager_) { sync_manager_->InvalidateCredentials(); } } void SyncEngineBackend::DoStartConfiguration() { sync_manager_->StartConfiguration(); } void SyncEngineBackend::DoStartSyncing(base::Time last_poll_time) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->StartSyncingNormally(last_poll_time); } void SyncEngineBackend::DoSetEncryptionPassphrase( const std::string& passphrase) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->GetEncryptionHandler()->SetEncryptionPassphrase(passphrase); } void SyncEngineBackend::DoAddTrustedVaultDecryptionKeys( const std::vector<std::vector<uint8_t>>& keys) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->GetEncryptionHandler()->AddTrustedVaultDecryptionKeys(keys); } void SyncEngineBackend::DoInitialProcessControlTypes() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DVLOG(1) << "Initilalizing Control Types"; // Initialize encryption. sync_manager_->GetEncryptionHandler()->NotifyInitialStateToObservers(); if (!sync_manager_->InitialSyncEndedTypes().HasAll(ControlTypes())) { LOG(ERROR) << "Failed to download control types"; host_.Call(FROM_HERE, &SyncEngineImpl::HandleInitializationFailureOnFrontendLoop); return; } host_.Call(FROM_HERE, &SyncEngineImpl::HandleInitializationSuccessOnFrontendLoop, sync_manager_->GetDebugInfoListener(), sync_manager_->GetModelTypeConnectorProxy(), sync_manager_->birthday(), sync_manager_->bag_of_chips()); } void SyncEngineBackend::DoSetDecryptionPassphrase( const std::string& passphrase) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->GetEncryptionHandler()->SetDecryptionPassphrase(passphrase); } void SyncEngineBackend::ShutdownOnUIThread() { // This will cut short any blocking network tasks, cut short any in-progress // sync cycles, and prevent the creation of new blocking network tasks and new // sync cycles. If there was an in-progress network request, it would have // had a reference to the RequestContextGetter. This reference will be // dropped by the time this function returns. // // It is safe to call this even if Sync's backend classes have not been // initialized yet. Those classes will receive the message when the sync // thread finally getes around to constructing them. stop_syncing_signal_.Signal(); } void SyncEngineBackend::DoShutdown(ShutdownReason reason) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // |sync_manager_| and |nigori_controller_| may be null if DoInitialize() was // never called. if (sync_manager_) { // However, |sync_manager_| and |nigori_controller_| are always either both // null or both non-null. DCHECK(nigori_controller_); sync_manager_->GetModelTypeConnector()->DisconnectDataType(NIGORI); nigori_controller_->Stop(reason, base::DoNothing()); nigori_controller_.reset(); sync_manager_->RemoveObserver(this); sync_manager_->ShutdownOnSyncThread(); sync_manager_.reset(); } if (reason == DISABLE_SYNC) { DeleteLegacyDirectoryFilesAndNigoriStorage(sync_data_folder_); } host_.Reset(); weak_ptr_factory_.InvalidateWeakPtrs(); } void SyncEngineBackend::DoPurgeDisabledTypes(const ModelTypeSet& to_purge) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (to_purge.Has(NIGORI)) { // We are using USS implementation of Nigori and someone asked us to purge // it's data. For regular datatypes it's controlled DataTypeManager, but // for Nigori we need to do it here. // TODO(crbug.com/922900): try to find better way to implement this logic, // it's likely happen only due to BackendMigrator. // TODO(crbug.com/1142771): Evaluate whether this logic is necessary at all. // There's no "purging" logic for any other data type, so likely it's not // necessary for NIGORI either. sync_manager_->GetModelTypeConnector()->DisconnectDataType(NIGORI); nigori_controller_->Stop(ShutdownReason::DISABLE_SYNC, base::DoNothing()); LoadAndConnectNigoriController(); } } void SyncEngineBackend::DoConfigureSyncer( ModelTypeConfigurer::ConfigureParams params) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!params.ready_task.is_null()); base::OnceClosure chained_ready_task( base::BindOnce(&SyncEngineBackend::DoFinishConfigureDataTypes, weak_ptr_factory_.GetWeakPtr(), params.to_download, std::move(params.ready_task))); sync_manager_->ConfigureSyncer(params.reason, params.to_download, params.is_sync_feature_enabled ? SyncManager::SyncFeatureState::ON : SyncManager::SyncFeatureState::OFF, std::move(chained_ready_task)); } void SyncEngineBackend::DoFinishConfigureDataTypes( ModelTypeSet types_to_config, base::OnceCallback<void(ModelTypeSet, ModelTypeSet)> ready_task) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Update the enabled types for the bridge and sync manager. // TODO(crbug.com/1140938): track |enabled_types| directly in SyncEngineImpl. ModelTypeSet enabled_types = sync_manager_->GetEnabledTypes(); enabled_types.RemoveAll(ProxyTypes()); const ModelTypeSet failed_configuration_types = Difference(types_to_config, sync_manager_->InitialSyncEndedTypes()); const ModelTypeSet succeeded_configuration_types = Difference(types_to_config, failed_configuration_types); host_.Call(FROM_HERE, &SyncEngineImpl::FinishConfigureDataTypesOnFrontendLoop, enabled_types, succeeded_configuration_types, failed_configuration_types, std::move(ready_task)); } void SyncEngineBackend::SendBufferedProtocolEventsAndEnableForwarding() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); forward_protocol_events_ = true; if (sync_manager_) { // Grab our own copy of the buffered events. // The buffer is not modified by this operation. std::vector<std::unique_ptr<ProtocolEvent>> buffered_events = sync_manager_->GetBufferedProtocolEvents(); // Send them all over the fence to the host. for (auto& event : buffered_events) { host_.Call(FROM_HERE, &SyncEngineImpl::HandleProtocolEventOnFrontendLoop, std::move(event)); } } } void SyncEngineBackend::DisableProtocolEventForwarding() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); forward_protocol_events_ = false; } void SyncEngineBackend::DoOnCookieJarChanged(bool account_mismatch, base::OnceClosure callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sync_manager_->OnCookieJarChanged(account_mismatch); if (!callback.is_null()) { host_.Call(FROM_HERE, &SyncEngineImpl::OnCookieJarChangedDoneOnFrontendLoop, std::move(callback)); } } void SyncEngineBackend::DoOnInvalidatorClientIdChange( const std::string& client_id) { if (base::FeatureList::IsEnabled(switches::kSyncE2ELatencyMeasurement)) { // Don't populate the ID, if client participates in latency measurement // experiment. return; } sync_manager_->UpdateInvalidationClientId(client_id); } void SyncEngineBackend::DoOnInvalidationReceived(const std::string& payload) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(base::FeatureList::IsEnabled(switches::kSyncSendInterestedDataTypes) && base::FeatureList::IsEnabled(switches::kUseSyncInvalidations)); sync_pb::SyncInvalidationsPayload payload_message; // TODO(crbug.com/1119804): Track parsing failures in a histogram. if (!payload_message.ParseFromString(payload)) { return; } for (const auto& data_type_invalidation : payload_message.data_type_invalidations()) { const int field_number = data_type_invalidation.data_type_id(); ModelType model_type = GetModelTypeFromSpecificsFieldNumber(field_number); if (!IsRealDataType(model_type)) { DLOG(WARNING) << "Unknown field number " << field_number; continue; } // TODO(crbug.com/1119798): Use only enabled data types. std::unique_ptr<InvalidationInterface> inv_adapter = std::make_unique<SyncInvalidationAdapter>(payload_message.hint()); sync_manager_->OnIncomingInvalidation(model_type, std::move(inv_adapter)); } } void SyncEngineBackend::DoOnActiveDevicesChanged( size_t active_devices, std::vector<std::string> fcm_registration_tokens) { // If |active_devices| is 0, then current client doesn't know if there are any // other devices. It's safer to consider that there are some other active // devices. const bool single_client = active_devices == 1; sync_manager_->UpdateSingleClientStatus(single_client); sync_manager_->UpdateActiveDeviceFCMRegistrationTokens( std::move(fcm_registration_tokens)); } void SyncEngineBackend::GetNigoriNodeForDebugging(AllNodesCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); nigori_controller_->GetAllNodes(std::move(callback)); } bool SyncEngineBackend::HasUnsyncedItemsForTest() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(sync_manager_); return sync_manager_->HasUnsyncedItemsForTest(); } void SyncEngineBackend::LoadAndConnectNigoriController() { // The controller for Nigori is not exposed to the UI thread or the // DataTypeManager, so we need to start it here manually. ConfigureContext configure_context; configure_context.authenticated_account_id = authenticated_account_id_; configure_context.cache_guid = sync_manager_->cache_guid(); // TODO(crbug.com/922900): investigate whether we want to use // kTransportOnly in Butter mode. configure_context.sync_mode = SyncMode::kFull; configure_context.configuration_start_time = base::Time::Now(); nigori_controller_->LoadModels(configure_context, base::DoNothing()); DCHECK_EQ(nigori_controller_->state(), DataTypeController::MODEL_LOADED); // TODO(crbug.com/922900): Do we need to call RegisterDataType() for Nigori? sync_manager_->GetModelTypeConnector()->ConnectDataType( NIGORI, nigori_controller_->ActivateManuallyForNigori()); } } // namespace syncer
40.387947
80
0.760515
[ "vector", "model" ]
1b021affd7e3f53a80ae14e89d347495abdfc5fc
13,156
cpp
C++
core/os/dir_access.cpp
Segs/Engine
754aabfc2708a46f764979a604871633152ce479
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
8
2019-09-03T19:58:19.000Z
2021-06-18T07:11:26.000Z
core/os/dir_access.cpp
Segs/Engine
754aabfc2708a46f764979a604871633152ce479
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
24
2019-09-03T17:35:45.000Z
2020-10-27T14:36:02.000Z
core/os/dir_access.cpp
nemerle/SegsEngine
b9dd0b5481b92d956befa72c746758d33a1a08c9
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
6
2019-09-27T15:44:35.000Z
2021-01-23T18:52:51.000Z
/*************************************************************************/ /* dir_access.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "dir_access.h" #include "core/os/file_access.h" #include "core/os/memory.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/string_utils.h" String DirAccess::_get_root_path() const { switch (_access_type) { case ACCESS_RESOURCES: return ProjectSettings::get_singleton()->get_resource_path(); case ACCESS_USERDATA: return OS::get_singleton()->get_user_data_dir(); default: return String(); } } String DirAccess::_get_root_string() const { switch (_access_type) { case ACCESS_RESOURCES: return "res://"; case ACCESS_USERDATA: return "user://"; default: return String(); } } int DirAccess::get_current_drive() { String path = StringUtils::to_lower(get_current_dir()); for (int i = 0; i < get_drive_count(); i++) { String d = StringUtils::to_lower(get_drive(i)); if (StringUtils::begins_with(path,d)) return i; } return 0; } bool DirAccess::drives_are_shortcuts() { return false; } String DirAccess::get_current_dir_without_drive() { return get_current_dir(); } static Error _erase_recursive(DirAccess *da) { Vector<String> dirs; Vector<String> files; da->list_dir_begin(); String n(da->get_next()); while (!n.empty()) { if (n != "." && n != "..") { if (da->current_is_dir()) dirs.push_back(n); else files.push_back(n); } n = da->get_next(); } da->list_dir_end(); for (const String &E : dirs) { Error err = da->change_dir(E); if (err == OK) { err = _erase_recursive(da); if (err) { da->change_dir(".."); return err; } err = da->change_dir(".."); if (err) { return err; } err = da->remove(PathUtils::plus_file(da->get_current_dir(),E)); if (err) { return err; } } else { return err; } } for (const String &E : files) { Error err = da->remove(PathUtils::plus_file(da->get_current_dir(),E)); if (err) { return err; } } return OK; } Error DirAccess::erase_contents_recursive() { return _erase_recursive(this); } Error DirAccess::make_dir_recursive(StringView p_dir) { if (p_dir.length() < 1) { return OK; } String full_dir; if (PathUtils::is_rel_path(p_dir)) { //append current full_dir = PathUtils::plus_file(get_current_dir(),p_dir); } else { full_dir = p_dir; } full_dir = PathUtils::from_native_path(full_dir); //int slices = StringUtils::get_slice_count(full_dir"/"); String base; if (StringUtils::begins_with(full_dir,"res://")) base = "res://"; else if (StringUtils::begins_with(full_dir,"user://")) base = "user://"; else if (StringUtils::begins_with(full_dir,"/")) base = "/"; else if (StringUtils::contains(full_dir,":/")) { base = StringUtils::substr(full_dir,0, StringUtils::find(full_dir,":/") + 2); } else { ERR_FAIL_V(ERR_INVALID_PARAMETER); } full_dir = PathUtils::simplify_path(StringUtils::replace_first(full_dir,base, "")); FixedVector<StringView,16,true> subdirs; String::split_ref(subdirs,full_dir,'/'); String curpath = base; for (StringView dir : subdirs) { curpath = PathUtils::plus_file(curpath,dir); Error err = make_dir(curpath); if (err != OK && err != ERR_ALREADY_EXISTS) { ERR_FAIL_V(err); } } return OK; } String DirAccess::fix_path(StringView p_path) const { switch (_access_type) { case ACCESS_RESOURCES: { if (ProjectSettings::get_singleton()) { if (StringUtils::begins_with(p_path,"res://")) { String resource_path = ProjectSettings::get_singleton()->get_resource_path(); if (!resource_path.empty()) { return StringUtils::replace_first(p_path,"res:/", resource_path); } return StringUtils::replace_first(p_path,"res://", ""); } } } break; case ACCESS_USERDATA: { if (StringUtils::begins_with(p_path,"user://")) { String data_dir = OS::get_singleton()->get_user_data_dir(); if (!data_dir.empty()) { return StringUtils::replace_first(p_path,"user:/", data_dir); } return StringUtils::replace_first(p_path,"user://", ""); } } break; case ACCESS_FILESYSTEM: { return String(p_path); } case ACCESS_MAX: break; // Can't happen, but silences warning } return String(p_path); } DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { nullptr, nullptr, nullptr }; DirAccess *DirAccess::create_for_path(StringView p_path) { DirAccess *da = nullptr; if (StringUtils::begins_with(p_path,"res://")) { da = create(ACCESS_RESOURCES); } else if (StringUtils::begins_with(p_path,"user://")) { da = create(ACCESS_USERDATA); } else { da = create(ACCESS_FILESYSTEM); } return da; } DirAccess *DirAccess::open(StringView p_path, Error *r_error) { DirAccess *da = create_for_path(p_path); ERR_FAIL_COND_V_MSG(!da, nullptr, "Cannot create DirAccess for path '" + String(p_path) + "'."); Error err = da->change_dir(p_path); if (r_error) *r_error = err; if (err != OK) { memdelete(da); return nullptr; } return da; } DirAccess *DirAccess::create(AccessType p_access) { DirAccess *da = create_func[p_access] ? create_func[p_access]() : nullptr; if (da) { da->_access_type = p_access; } return da; } String DirAccess::get_full_path(StringView p_path, AccessType p_access) { DirAccess *d = DirAccess::create(p_access); if (!d) return String(p_path); d->change_dir(p_path); String full = d->get_current_dir(); memdelete(d); return full; } Error DirAccess::copy(StringView p_from, StringView p_to, int p_chmod_flags) { //printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data()); Error err; FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ, &err); if (err) { ERR_PRINT("Failed to open " + String(p_from)); return err; } FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE, &err); if (err) { fsrc->close(); memdelete(fsrc); ERR_PRINT("Failed to open " + String(p_to)); return err; } fsrc->seek_end(0); size_t size = fsrc->get_position(); fsrc->seek(0); err = OK; while (size--) { if (fsrc->get_error() != OK) { err = fsrc->get_error(); break; } if (fdst->get_error() != OK) { err = fdst->get_error(); break; } fdst->store_8(fsrc->get_8()); } if (err == OK && p_chmod_flags != -1) { fdst->close(); err = FileAccess::set_unix_permissions(p_to, p_chmod_flags); // If running on a platform with no chmod support (i.e., Windows), don't fail if (err == ERR_UNAVAILABLE) err = OK; } memdelete(fsrc); memdelete(fdst); return err; } void DirAccess::remove_file_or_error(StringView p_path) { DirAccess *da = create(ACCESS_FILESYSTEM); if (da->file_exists(p_path)) { if (da->remove(p_path) != OK) { ERR_FAIL_MSG("Cannot remove file or directory: " + String(p_path)); } } memdelete(da); } // Changes dir for the current scope, returning back to the original dir // when scope exits class DirChanger { DirAccess *da; String original_dir; public: DirChanger(DirAccess *p_da, StringView p_dir) : da(p_da), original_dir(p_da->get_current_dir()) { p_da->change_dir(p_dir); } ~DirChanger() { da->change_dir(original_dir); } }; Error DirAccess::_copy_dir(DirAccess *p_target_da, StringView p_to, int p_chmod_flags) { Vector<StringView> dirs; String curdir = get_current_dir(); list_dir_begin(); String n = get_next(); while (!n.empty()) { if (n != "." && n != "..") { if (current_is_dir()) dirs.push_back(n); else { StringView rel_path = n; if (!PathUtils::is_rel_path(n)) { list_dir_end(); return ERR_BUG; } Error err = copy(PathUtils::plus_file(get_current_dir(),n), String(p_to) + rel_path, p_chmod_flags); if (err) { list_dir_end(); return err; } } } n = get_next(); } list_dir_end(); for (StringView rel_path : dirs) { String target_dir = String(p_to) + rel_path; if (!p_target_da->dir_exists(target_dir)) { Error err = p_target_da->make_dir(target_dir); ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot create directory '" + target_dir + "'."); } Error err = change_dir(rel_path); ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot change current directory to '" + String(rel_path) + "'."); err = _copy_dir(p_target_da, String(p_to) + rel_path + "/", p_chmod_flags); if (err) { change_dir(".."); ERR_FAIL_V_MSG(err, "Failed to copy recursively."); } err = change_dir(".."); ERR_FAIL_COND_V_MSG(err != OK, err, "Failed to go back."); } return OK; } Error DirAccess::copy_dir(StringView p_from, StringView p_to, int p_chmod_flags) { ERR_FAIL_COND_V_MSG(!dir_exists(p_from), ERR_FILE_NOT_FOUND, "Source directory doesn't exist."); DirAccess *target_da = DirAccess::create_for_path(p_to); ERR_FAIL_COND_V_MSG(!target_da, ERR_CANT_CREATE, "Cannot create DirAccess for path '" + String(p_to) + "'."); if (!target_da->dir_exists(p_to)) { Error err = target_da->make_dir_recursive(p_to); if (err) { memdelete(target_da); } ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot create directory '" + String(p_to) + "'."); } DirChanger dir_changer(this, p_from); Error err; String p_to_fix(p_to); if (!p_to.ends_with('/')) { p_to_fix.push_back('/'); } err = _copy_dir(target_da, p_to_fix, p_chmod_flags); memdelete(target_da); return err; } bool DirAccess::exists(StringView p_dir) { DirAccess *da = DirAccess::create_for_path(p_dir); bool valid = da->change_dir(p_dir) == OK; memdelete(da); return valid; }
28.6
116
0.549179
[ "vector" ]
db44b1e0ab4d16993eb1ee035e0e4ca6372f56af
1,038
cpp
C++
cpp/0103_zigzagLevelOrder.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-16T12:54:56.000Z
2021-04-16T12:54:56.000Z
cpp/0103_zigzagLevelOrder.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
null
null
null
cpp/0103_zigzagLevelOrder.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-26T13:20:41.000Z
2021-04-26T13:20:41.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ // DFS: 无脑DFS。。奇数层reverse class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; traverse(root,res,0); if(res.size()<2) return res; for(auto i=1;i<res.size();i+=2) reverse(res[i].begin(),res[i].end()); return res; } void traverse(TreeNode* root,vector<vector<int>> &res,int depth) { if(root==nullptr) return; if(res.size()>depth) res[depth].push_back(root->val); else res.push_back({root->val}); traverse(root->left,res,depth+1); traverse(root->right,res,depth+1); } };
28.054054
93
0.550096
[ "vector" ]
db48aae48b7d499a1367387c0b1568fa7eac89eb
724
cpp
C++
cpp/ants.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
3
2021-11-12T09:20:21.000Z
2022-02-18T11:34:33.000Z
cpp/ants.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
1
2019-05-15T10:55:59.000Z
2019-05-15T10:56:31.000Z
cpp/ants.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
null
null
null
/*#include <gtest/gtest.h> int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } */ #define CATCH_CONFIG_MAIN #include <algorithm> #include <vector> #include "../../Catch/include/catch.hpp" std::pair<int,int> ant_time(int L/*Length*/,std::vector<int> N/*number*/) { int minT=0; int maxT=0; for (auto n:N) { minT = std::max(minT,std::min(n,L-n)); maxT = std::max(maxT,std::max(n,L-n)); } return std::make_pair(minT,maxT); } TEST_CASE("ants") { auto res = std::make_pair(4,8); std::vector<int> v={2,6,7}; REQUIRE(res==ant_time(10,v)); auto res2 = std::make_pair(4,9); std::vector<int> v2={2,6,7,8,5,9,4}; REQUIRE(res==ant_time(10,v)); }
20.111111
73
0.620166
[ "vector" ]
db48e0ca3c886ac77b3afc4261732be5a9550a6f
3,256
cpp
C++
read_mnist.cpp
oojiang/Neural-Net-From-Scratch
555847dee624c8f16ca6dd46b84e1114bdc0b4e3
[ "MIT" ]
null
null
null
read_mnist.cpp
oojiang/Neural-Net-From-Scratch
555847dee624c8f16ca6dd46b84e1114bdc0b4e3
[ "MIT" ]
null
null
null
read_mnist.cpp
oojiang/Neural-Net-From-Scratch
555847dee624c8f16ca6dd46b84e1114bdc0b4e3
[ "MIT" ]
null
null
null
#include <read_mnist.hpp> uint32_t swap_endian(uint32_t val) { val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF); return (val << 16) | (val >> 16); } void print_image(VectorXd image, int num_rows, int num_cols) { int threshold = 25; for (int i = 0; i < num_rows; i++) { for (int j = 0; j < num_cols; j++) { if (image[i * num_rows + j] > threshold) { cout << "*"; } else { cout << "."; } } cout << endl; } } void print_image_values(VectorXd image, int num_rows, int num_cols) { for (int i = 0; i < num_rows; i++) { for (int j = 0; j < num_cols; j++) { if (image[i * num_rows + j] == 0) { cout << "_._ "; } else { printf("%.1f ", ((float) image[i * num_rows + j])); } } cout << endl; } } vector<int> get_labels(string path) { ifstream file(path, ios::in|ios::binary); uint32_t magic; uint32_t num_items; char label; vector<int> labels; if (file.is_open()) { cout << "Reading label file: " << path << endl; file.read(reinterpret_cast<char*>(&magic), 4); magic = swap_endian(magic); if (magic != 2049) { cout << "Incorrect magic number: " << magic << "(Should be 2049)" << endl; return labels; } file.read(reinterpret_cast<char*>(&num_items), 4); num_items = swap_endian(num_items); for (int item_id = 0; item_id < num_items; item_id++) { file.read(&label, 1); labels.push_back(label); } } return labels; } vector<VectorXd> get_images(string path) { ifstream file(path, ios::in|ios::binary); uint32_t magic; uint32_t num_images; uint32_t num_rows; uint32_t num_cols; char* pixels; vector<VectorXd> images; if (file.is_open()) { cout << "Reading label file: " << path << endl; file.read(reinterpret_cast<char*>(&magic), 4); magic = swap_endian(magic); if (magic != 2051) { cout << "Incorrect magic number: " << magic << "(Should be 2051)" << endl; return images; } file.read(reinterpret_cast<char*>(&num_images), 4); num_images = swap_endian(num_images); file.read(reinterpret_cast<char*>(&num_rows), 4); num_rows = swap_endian(num_rows); file.read(reinterpret_cast<char*>(&num_cols), 4); num_cols = swap_endian(num_cols); cout << "Number of images: " << num_images << endl; cout << "Number of rows: " << num_rows << endl; cout << "Number of cols: " << num_cols << endl; pixels = new char[num_rows * num_cols]; for (int i = 0; i < num_images; i++) { file.read(pixels, num_rows * num_cols); VectorXd image(num_rows * num_cols); for (int j = 0; j < num_rows * num_cols; j++) { if (pixels[j] < 0) { image[j] = (float)(((int) pixels[j]) + 255) / 255; } else { image[j] = (float)(pixels[j]) / 255; } } images.push_back(image); } } return images; } inline VectorXd output_vector(int label) { VectorXd y = VectorXd::Constant(10, 0); y[label] = 1; return y; } vector<VectorXd> get_output_vectors(vector<int> labels) { vector<VectorXd> output_vectors; for (int i = 0; i < labels.size(); i++) { output_vectors.push_back(output_vector(labels[i])); } return output_vectors; }
27.133333
108
0.582002
[ "vector" ]
db493bc7b7ba0fb865316d64414e3649abd7c4bb
3,964
cpp
C++
lib/JunkDetection/CXX/CompilationDatabase.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
null
null
null
lib/JunkDetection/CXX/CompilationDatabase.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
null
null
null
lib/JunkDetection/CXX/CompilationDatabase.cpp
mewbak/mull
fe270faa614e3c91b5ae2baf37916eaca2f4fa08
[ "Apache-2.0" ]
null
null
null
#include "mull/JunkDetection/CXX/CompilationDatabase.h" #include "CompilationDatabaseParser.h" #include "mull/Logger.h" #include <clang/Basic/Version.h> #include <llvm/ADT/STLExtras.h> #include <llvm/ADT/SmallString.h> #include <llvm/Support/Path.h> #include <sstream> using namespace mull; static std::vector<std::string> filterFlags(const std::vector<std::string> &flags, bool stripCompiler) { std::vector<std::string> filteredFlags; if (flags.empty()) { return filteredFlags; } auto it = flags.begin(); auto end = flags.end(); if (stripCompiler) { ++it; } while (it != end) { std::string flag = *(it++); if (flag == "-c") { if (it != end) { ++it; } continue; } filteredFlags.push_back(flag); } return filteredFlags; } static std::vector<std::string> flagsFromString(const std::string &s) { std::vector<std::string> flags; std::istringstream stream(s); while (!stream.eof()) { std::string value; stream >> value; if (value.empty()) { continue; } flags.push_back(value); } return flags; } static std::vector<std::string> flagsFromCommand(const CompileCommand &command) { if (command.arguments.empty()) { return filterFlags(flagsFromString(command.command), true); } return filterFlags(command.arguments, true); } static std::vector<std::string> flagsFromCommand(const CompileCommand &command, const std::vector<std::string> &extraFlags) { std::vector<std::string> flags = flagsFromCommand(command); /// The compilation database produced from running /// clang ... -MJ <comp.database.json> /// contains a file name in the "arguments" array. Since the file name /// itself is not a compilation flag we filter it out. flags.erase(std::remove(flags.begin(), flags.end(), command.file), flags.end()); for (auto &extra : extraFlags) { flags.push_back(extra); } return flags; } static std::map<std::string, std::vector<std::string>> loadDatabaseFromFile(const std::string &path, const std::vector<std::string> &extraFlags) { std::map<std::string, std::vector<std::string>> database; if (path.empty()) { return database; } std::vector<CompileCommand> commands; auto bufferOrError = llvm::MemoryBuffer::getFile(path); if (!bufferOrError) { Logger::error() << "Can not read compilation database: " << path << '\n'; } else { auto buffer = bufferOrError->get(); llvm::yaml::Input json(buffer->getBuffer()); json >> commands; if (json.error()) { Logger::error() << "Can not read compilation database: " << path << '\n'; } } for (auto &command : commands) { std::string filePath = command.file; if (!filePath.empty() && !llvm::sys::path::is_absolute(filePath)) { filePath = command.directory + llvm::sys::path::get_separator().str() + filePath; } database[filePath] = flagsFromCommand(command, extraFlags); } return database; } CompilationDatabase::CompilationDatabase(CompilationDatabase::Path path, CompilationDatabase::Flags flags) : extraFlags(filterFlags(flagsFromString(flags.getFlags()), false)), database(loadDatabaseFromFile(path.getPath(), extraFlags)) {} const std::vector<std::string> & CompilationDatabase::compilationFlagsForFile(const std::string &filepath) const { if (database.empty()) { return extraFlags; } auto it = database.find(filepath); if (it != database.end()) { return it->second; } auto filename = llvm::sys::path::filename(filepath); it = database.find(filename); if (it != database.end()) { return it->second; } llvm::SmallString<128> dotlessPath(filepath); llvm::sys::path::remove_dots(dotlessPath, true); it = database.find(dotlessPath.str()); if (it != database.end()) { return it->second; } return extraFlags; }
27.72028
94
0.644803
[ "vector" ]
db4b036a8a96e881ed26108f28c848cc58491d3b
13,216
cpp
C++
server.cpp
stetorvs/puzzle_server
481d93d37e79fb266dbaef5b329174d58386658d
[ "BSD-2-Clause" ]
null
null
null
server.cpp
stetorvs/puzzle_server
481d93d37e79fb266dbaef5b329174d58386658d
[ "BSD-2-Clause" ]
null
null
null
server.cpp
stetorvs/puzzle_server
481d93d37e79fb266dbaef5b329174d58386658d
[ "BSD-2-Clause" ]
null
null
null
#include <errno.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <assert.h> #include <algorithm> #include <chrono> #include <cstdio> #include <deque> #include <fstream> #include <future> #include <iostream> #include <map> #include <mutex> #include <numeric> #include <sstream> #include <string> #include <vector> #define PORT 3490 #define MAXMSG 512 using namespace std; const string DEFAULT_EMAIL = "stetorvs@gmail.com"; constexpr time_t TIMEOUT_THRESHOLD = 3; // Concurrency mutex write_mutex; deque<future<void>> futures; // Group member data map<string, vector<string>> group_2_members = { {"The Hosts", {"victor"}}, }; // Group email data map<string, string> group_2_email = { {"The Hosts", "stetorvs@gmail.com"}, }; void verify_emails() { string emails; for (auto& [team, email] : group_2_email) { cout << "Verifying team: " << team << '\n'; assert(group_2_members.count(team) != 0U); emails += email; emails += ' '; } } int make_socket(uint16_t port) { int sock; struct sockaddr_in name; /* Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) { perror ("socket"); exit (EXIT_FAILURE); } // Reuse socket if it is in a time-out state (prevents bind: Address already in use error) int optval = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); /* Give the socket a name. */ name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl (INADDR_ANY); if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) { perror ("bind"); exit (EXIT_FAILURE); } return sock; } int reply_to_client(int filedes, string msg) { int msg_size = msg.length() + 1; int nbytes = write(filedes, msg.c_str(), msg_size); fprintf (stderr, "Server sent message: %swith nybtes successful: %d\n", msg.c_str(), nbytes); return nbytes >= 0; } map<string, string> get_member_2_group(const map<string, vector<string>>& group_2_members_map) { map<string, string> member_2_group; for (auto it : group_2_members_map) { for (auto member : it.second) { member_2_group.emplace(member, it.first); } } return member_2_group; } string get_response(const string& question, const string& ans, bool &correct) { string response = "Invalid question\n"; map<string, string> question_2_solution = {{"debug_msg", "fire"}, {"notes", "grebe"}, {"undo", "zztop"}, {"cheating", "hacked"}, {"x", "markets"}, {"difference", "glidergun"}, {"mines", "innovation"}, {"roman", "tokyoskytree"}, {"pigpen", "danbrown"}, {"training", "workshopshopper"}, {"crash", "stevemeyers"}, {"work", "howtotrainyourdragon"}, {"savings", "count"}}; map<string, map<string, string>> question_2_hints; question_2_hints["debug_msg"] = {{"lpr0onblank", "lpr0 on _?\n"}}; question_2_hints["undo"] = {{"savequitvim", "Replace this with the keyboard shortcut\n"}, {"savequitvimnocolon", "Replace this with the keyboard shortcut\n"}, {"quitvimnocolon", "With save, replace this with the keyboard shortcut\n"}}; question_2_hints["cheating"] = {{"cheating", "This is not getting you ANYWHERE\n"}, {"anywhere", "This is your last warning, or you will be REPORTED\n"}, {"reported", "Is this really worth the EFFORT?\n"}, {"effort", "Okay, you win. The answer is HACKED.\n"}}; question_2_hints["x"] = {{"monopoly", "Good start, but that is just the beginning\n"}}; question_2_hints["difference"] = {{"gameoflife", "Almost there, but please look at the other differences\n"}, {"glider", "What's producing the gliders?\n"}, {"gliders", "What's producing the gliders?\n"}, {"gliderguns", "There's just one of them\n"}, {"gospergliderguns", "Submit again without Gosper's name, and singular\n"}, {"gosperglidergun", "Submit again without Gosper's name\n"}}; question_2_hints["mines"] = {{"leadershipthisandcommunity", "What else would complete the trio?\n"}}; question_2_hints["roman"] = {{"tallest", "Almost there...\n"}, {"burjkhalifa", "Limit your search to just towers\n"}}; question_2_hints["pigpen"] = {{"lostsymbolauthor", "He also wrote The Da Vinci Code\n"}}; question_2_hints["training"] = {{"personnetwork", "Complete the loop between work and per\n"}, {"shop", "Please submit both compound words, not just the common word of the two\n"}}; question_2_hints["crash"] = {{"iwrote0321334876", "Almost there, you just need to know how to turn the number into a book\n"}}; question_2_hints["work"] = {{"jonahhill", "Getting close...\n"}, {"jaybaruchel", "Getting close...\n"}, {"gerardbutler", "Getting close...\n"}, {"jonahhill", "Getting close...\n"}}; correct = false; auto it = question_2_solution.find(question); if (it != question_2_solution.end()) { if (ans == it->second) { correct = true; response = "Correct!\n"; } else { auto hint_it = question_2_hints[question].find(ans); if (hint_it != question_2_hints[question].end()) { response = hint_it->second; } else { if (question == string("cheating")) { response = "please, no CHEATING\n"; } else { response = "Sorry, incorrect answer\n"; } } } } if (correct) { fprintf(stderr, "Correct answer!\n"); } else { fprintf(stderr, "Incorrect answer\n"); } return response; } string sanitize(string st) { size_t pos = st.find('\''); while (pos != string::npos) { st.replace(pos, 1, "'\\''"); pos = st.find('\'', pos+4); } return st; } void email(string msg, string subject, string to) { if (msg.back() == '\n') { msg.pop_back(); } if (subject.back() == '\n') { subject.pop_back(); } string cmd = "echo '" + sanitize(msg) + "' | mail -s 'Puzzle: " + sanitize(subject) + "' '" + sanitize(to) + "'"; system(cmd.c_str()); } void update_scoreboard(string group, string question) { lock_guard<mutex> write_lock(write_mutex); vector<string> questions = {"cheating", "crash", "debug_msg", "difference"}; // Laziness from static... static map<string, map<string, int>> score_standings; if (score_standings.empty()) { map<string, int> empty; transform(questions.begin(), questions.end(), inserter(empty, empty.end()), [] (string& name) { return pair(name, 0); }); for (auto& p : group_2_members) { score_standings[p.first] = empty; } } static map<string, string> last_solve; if (last_solve.empty()) { for (auto& p : group_2_members) { time_t ls_time = chrono::system_clock::to_time_t(chrono::system_clock::now()); string t(ctime(&ls_time)); last_solve[p.first] = t.substr(0, t.length()-1); // Strip newline } } // Now actually update if (score_standings[group][question] != 0) { return; } ofstream ofs("standings.txt"); if (question == "meta") { score_standings[group][question] = 3; } else { score_standings[group][question] = 1; } time_t ls_time = chrono::system_clock::to_time_t(chrono::system_clock::now()); string t(ctime(&ls_time)); last_solve[group] = t.substr(0, t.length()-1); // Strip newline // File update for (auto& p : group_2_members) { const string& team = p.first; ofs << "| " << team << " | "; ofs << accumulate(score_standings[team].begin(), score_standings[team].end(), 0, [] (int sum, const pair<string, int>& p) { return sum + p.second; }); ofs << " | " << last_solve[team] << " |"; for (auto& score_pair : score_standings[team]) { ofs << ' ' << score_pair.second << " |"; } ofs << '\n'; } } int read_from_client (int filedes, const string& ip) { char buffer[MAXMSG]; int nbytes; // static because I'm lazy static auto member_2_group_map = get_member_2_group(group_2_members); static map<pair<string, string>, chrono::time_point<chrono::system_clock>> ip_group_2_time; nbytes = read (filedes, buffer, MAXMSG); if (nbytes < 0) { /* Read error. */ return -2; } else if (nbytes == 0) /* End-of-file. */ return -1; else { /* Data read. */ buffer[nbytes] = '\0'; fprintf (stderr, "Server: got message: '%s'\n", buffer); string question, ans, user; stringstream ss; ss.str(string(buffer)); ss >> question; ss >> ans; ss >> user; for (char& c : question) c = tolower(c); for (char& c : ans) c = tolower(c); auto find_it = member_2_group_map.find(user); string response = string("Sorry, user ") + user + string(" does not belong to any team\n"); if (find_it != end(member_2_group_map)) { // Check timestamp chrono::time_point<chrono::system_clock> curr_t = chrono::system_clock::now(); auto& last_t = ip_group_2_time[pair(ip, find_it->second)]; chrono::duration<double> dur_t = curr_t - last_t; constexpr double timeout = 15.; if (dur_t.count() < timeout) { response = string("Please wait ") + to_string(timeout - dur_t.count()) + " seconds before submitting\n"; return reply_to_client(filedes, response); } last_t = curr_t; bool correct = false; auto group = find_it->second; response = get_response(question, ans, correct); response += "Team name: " + group + '\n'; string recipients = DEFAULT_EMAIL + " " + group_2_email[group]; if (correct) { futures.emplace_back(async(launch::async, [=] () { update_scoreboard(group, question); })); } futures.emplace_back(async(launch::async, [=] () { email(question+" "+ans+" "+user, response, recipients); })); } else if (user == "guest") { // Check timestamp string guest_email; ss >> guest_email; chrono::time_point<chrono::system_clock> curr_t = chrono::system_clock::now(); auto& last_t = ip_group_2_time[pair(ip, guest_email)]; chrono::duration<double> dur_t = curr_t - last_t; constexpr double timeout = 15.; if (dur_t.count() < timeout) { response = string("Please wait ") + to_string(timeout - dur_t.count()) + " seconds before submitting\n"; return reply_to_client(filedes, response); } last_t = curr_t; bool correct = false; auto group = find_it->second; response = get_response(question, ans, correct); response += "Guest team\n"; string recipients = DEFAULT_EMAIL + " " + guest_email; futures.emplace_back(async(launch::async, [=] () { email(question+" "+ans+" "+user, response, recipients); })); } return reply_to_client(filedes, response); } } int main (void) { int sock; fd_set active_fd_set, read_fd_set; int i; struct sockaddr_in clientname; socklen_t size; map<int, string> fd_to_ip; verify_emails(); /* Ignore SIGPIPE errors. */ signal(SIGPIPE, SIG_IGN); /* Create the socket and set it up to accept connections. */ sock = make_socket (PORT); if (listen (sock, 1) < 0) { perror ("listen"); exit (EXIT_FAILURE); } /* Initialize the set of active sockets. */ FD_ZERO (&active_fd_set); FD_SET (sock, &active_fd_set); cerr << "Server Ready\n"; while (1) { /* Clean up futures at a certain threshold. */ if (futures.size() > 100) { futures.erase(futures.begin(), futures.begin() + (futures.size() * 4/5)); } /* Block until input arrives on one or more active sockets. */ read_fd_set = active_fd_set; if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) { perror ("select"); exit (EXIT_FAILURE); } /* Service all the sockets with input pending. */ for (i = 0; i < FD_SETSIZE; ++i) if (FD_ISSET (i, &read_fd_set)) { if (i == sock) { /* Connection request on original socket. */ int new_fd; size = sizeof (clientname); new_fd = accept (sock, (struct sockaddr *) &clientname, &size); if (new_fd < 0) { perror ("accept"); exit (EXIT_FAILURE); } fprintf (stderr, "Server: connect from host %s, port %hu, fd %d.\n", inet_ntoa (clientname.sin_addr), ntohs (clientname.sin_port), new_fd); FD_SET (new_fd, &active_fd_set); fd_to_ip[new_fd] = inet_ntoa (clientname.sin_addr); } else { /* Data arriving on an already-connected socket. */ if (read_from_client (i, fd_to_ip[i]) < 0) { close (i); FD_CLR (i, &active_fd_set); } } } } }
31.845783
154
0.595415
[ "vector", "transform" ]
db4e36ad5cc7295c4c0c6bf1a484492fabdd73c3
3,722
cpp
C++
Bottomless-Blue.cpp
kawgit/Bottomless-Blue
c6cf9c5b0be6de5d652035f1b0a92d36bc8bf387
[ "MIT" ]
null
null
null
Bottomless-Blue.cpp
kawgit/Bottomless-Blue
c6cf9c5b0be6de5d652035f1b0a92d36bc8bf387
[ "MIT" ]
2
2021-09-03T19:15:10.000Z
2021-09-05T18:38:05.000Z
Bottomless-Blue.cpp
kawgit/Bottomless-Blue
c6cf9c5b0be6de5d652035f1b0a92d36bc8bf387
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <thread> #include <fstream> #include "src/ChessLibrary.hpp" #include "src/board.hpp" #include "src/move.hpp" #include "src/search.hpp" using namespace std; bool debug = false; string pop_cmd_var(string &cmd) { int split_index = cmd.rfind(" ", cmd.rfind(" ")-1); if (split_index != string::npos) { string var = cmd.substr(split_index+1); cmd = cmd.substr(0, split_index); return var; } return "no var found"; } void search_thread_func(Search &s) { s.search(); } int main() { cout.setf(ios::unitbuf); ChessLibrary::init(0x9382); Board board; Search s(board); thread search_thread; ofstream log; //ifstream is for input from plain text files log.open("log.txt", ios::out); //open input.txt if (!log) cout<<"failed to find log.txt"<<endl; while (true) { string command; cin>>command; log<<command<<endl; logic_start: if (command == "uci") {cout<<"id name Bottomless-Blue"<<endl<<"id author Kenneth Wilber (kawgit)"<<endl<<"uciok"<<endl;} else if (command == "isready") cout<<"readyok\n"; else if (command == "register") cout<<"register name Bottomless-Blue\n"; else if (command == "ucinewgame") { s.exit_search = true; if (search_thread.joinable()) search_thread.join(); s.exit_search = false; } else if (command == "position") { s.exit_search = true; if (search_thread.joinable()) search_thread.join(); s.exit_search = false; board = Board(); cin>>command; log<<command<<endl; if (command == "startpos"); else if (command == "fen") { string fen = ""; cout<<"h1"<<endl; for (int i = 0; i < 6; i++) { cin>>command; log<<command; fen += command + " "; } cout<<fen<<endl; board = Board(fen); } else { goto logic_start; } } else if (command == "moves") { vector<Move> legal_moves = board.get_legal_moves(); while (true) { cin>>command; log<<command<<endl; Move move = get_move_from_SAN(command, legal_moves); if (move != Move::NONE_MOVE) { board.make_move(move); legal_moves = board.get_legal_moves(); } else { cout<<"MOVE REJECT:"<<command<<endl; goto logic_start; } } } else if (command == "go") { s.exit_search = true; if (search_thread.joinable()) search_thread.join(); s.exit_search = false; s.calc_time = true; s.board = board; search_thread = thread(search_thread_func, ref(s)); } else if (command == "wtime") {string val; cin>>val; s.wtime = stoi(val);} else if (command == "btime") {string val; cin>>val; s.btime = stoi(val);} else if (command == "winc") {string val; cin>>val; s.winc = stoi(val);} else if (command == "binc") {string val; cin>>val; s.binc = stoi(val);} else if (command == "depth") {string val; cin>>val; s.max_depth = stoi(val);} else if (command == "nodes") {string val; cin>>val; s.max_nodes = stoi(val);} else if (command == "movetime") {string val; cin>>val; s.max_time = stoi(val); s.min_time = stoi(val);} else if (command == "ponder") {s.ponder = true; s.calc_time = false; } else if (command == "infinite") {s.max_time = -1; s.calc_time = false; } else if (command == "stop") { s.exit_search = true; if (search_thread.joinable()) search_thread.join(); s.exit_search = false; } else if (command == "quit") { s.exit_search = true; if (search_thread.joinable()) search_thread.join(); break; } else if (command == "d") board.print(); else if (command == "perft") { string val; cin>>val; cout<<board.perft(stoi(val), true)<<endl; } s.board = board; } log.close(); //close the file stream cout<<"returning main"<<endl; return 0; }
25.493151
122
0.617141
[ "vector" ]