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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eddcc618894b73c0c40a987bcb131ce85fe18443 | 5,940 | hpp | C++ | generator/generator_tests_support/test_feature.hpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | null | null | null | generator/generator_tests_support/test_feature.hpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | null | null | null | generator/generator_tests_support/test_feature.hpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "indexer/feature_decl.hpp"
#include "indexer/feature_meta.hpp"
#include "indexer/mwm_set.hpp"
#include "geometry/point2d.hpp"
#include <cstdint>
#include <map>
#include <string>
#include <utility>
#include <vector>
class FeatureBuilder1;
class FeatureType;
namespace osm
{
class Editor;
}
namespace generator
{
namespace tests_support
{
class TestFeature
{
public:
virtual ~TestFeature() = default;
bool Matches(FeatureType & feature) const;
inline void SetPostcode(std::string const & postcode) { m_postcode = postcode; }
inline uint64_t GetId() const { return m_id; }
inline std::string const & GetName() const { return m_name; }
inline feature::Metadata & GetMetadata() { return m_metadata; }
virtual void Serialize(FeatureBuilder1 & fb) const;
virtual std::string ToString() const = 0;
protected:
enum class Type
{
Point,
Area,
Unknown
};
TestFeature();
TestFeature(std::string const & name, std::string const & lang);
TestFeature(m2::PointD const & center, std::string const & name, std::string const & lang);
TestFeature(std::vector<m2::PointD> const & boundary, std::string const & name,
std::string const & lang);
uint64_t const m_id;
m2::PointD const m_center;
std::vector<m2::PointD> const m_boundary;
Type const m_type;
std::string const m_name;
std::string const m_lang;
std::string m_postcode;
feature::Metadata m_metadata;
private:
void Init();
};
class TestCountry : public TestFeature
{
public:
TestCountry(m2::PointD const & center, std::string const & name, std::string const & lang);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
};
class TestCity : public TestFeature
{
public:
TestCity(m2::PointD const & center, std::string const & name, std::string const & lang,
uint8_t rank);
TestCity(std::vector<m2::PointD> const & boundary, std::string const & name,
std::string const & lang, uint8_t rank);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
uint8_t const m_rank;
};
class TestVillage : public TestFeature
{
public:
TestVillage(m2::PointD const & center, std::string const & name, std::string const & lang, uint8_t rank);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
uint8_t const m_rank;
};
class TestStreet : public TestFeature
{
public:
TestStreet(std::vector<m2::PointD> const & points, std::string const & name, std::string const & lang);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
std::vector<m2::PointD> m_points;
};
class TestPOI : public TestFeature
{
public:
TestPOI(m2::PointD const & center, std::string const & name, std::string const & lang);
static std::pair<TestPOI, FeatureID> AddWithEditor(osm::Editor & editor,
MwmSet::MwmId const & mwmId,
std::string const & enName,
m2::PointD const & pt);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
inline void SetHouseNumber(std::string const & houseNumber) { m_houseNumber = houseNumber; }
inline void SetStreet(TestStreet const & street) { m_streetName = street.GetName(); }
inline void SetTypes(std::vector<std::vector<std::string>> const & types) { m_types = types; }
protected:
std::string m_houseNumber;
std::string m_streetName;
std::vector<std::vector<std::string>> m_types;
};
class TestMultilingualPOI : public TestPOI
{
public:
TestMultilingualPOI(m2::PointD const & center, std::string const & defaultName,
std::map<std::string, std::string> const & multilingualNames);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
std::map<std::string, std::string> m_multilingualNames;
};
class TestBuilding : public TestFeature
{
public:
TestBuilding(m2::PointD const & center, std::string const & name, std::string const & houseNumber,
std::string const & lang);
TestBuilding(m2::PointD const & center, std::string const & name, std::string const & houseNumber,
TestStreet const & street, std::string const & lang);
TestBuilding(std::vector<m2::PointD> const & boundary, std::string const & name, std::string const & houseNumber,
TestStreet const & street, std::string const & lang);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
void AddType(std::vector<std::string> const & path) { m_types.push_back(path); }
private:
std::vector<m2::PointD> const m_boundary;
std::string const m_houseNumber;
std::string const m_streetName;
std::vector<std::vector<std::string>> m_types;
};
class TestPark : public TestFeature
{
public:
TestPark(std::vector<m2::PointD> const & boundary, std::string const & name, std::string const & lang);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
std::vector<m2::PointD> m_boundary;
};
class TestRoad : public TestFeature
{
public:
TestRoad(std::vector<m2::PointD> const & points, std::string const & name, std::string const & lang);
// TestFeature overrides:
void Serialize(FeatureBuilder1 & fb) const override;
std::string ToString() const override;
private:
std::vector<m2::PointD> m_points;
};
std::string DebugPrint(TestFeature const & feature);
} // namespace tests_support
} // namespace generator
| 28.285714 | 115 | 0.692256 | [
"geometry",
"vector"
] |
ede7848acf2b7119d1c0e434232c90513df05c86 | 2,374 | cpp | C++ | ddopt/src/problem/bp/bp_orderings.cpp | ctjandra/ddopt-cut | 0ca4358e7c27a8a56fb2640d450356dcda91b7f0 | [
"MIT"
] | 6 | 2018-02-15T03:54:35.000Z | 2022-02-24T03:06:05.000Z | ddopt/src/problem/bp/bp_orderings.cpp | ctjandra/ddopt-cut | 0ca4358e7c27a8a56fb2640d450356dcda91b7f0 | [
"MIT"
] | null | null | null | ddopt/src/problem/bp/bp_orderings.cpp | ctjandra/ddopt-cut | 0ca4358e7c27a8a56fb2640d450356dcda91b7f0 | [
"MIT"
] | 2 | 2021-01-07T02:29:55.000Z | 2021-12-05T13:21:13.000Z | /**
* Orderings for a binary problem
*/
#include "bp_orderings.hpp"
#include "../../core/orderings.hpp"
using namespace boost;
Ordering* get_ordering_by_id_bp(int id, BPInstance* inst, Options& options)
{
// Read ordering type
switch (id) {
case 1:
return new RandomOrdering(inst);
case 2:
return new CuthillMcKeePairOrdering(inst);
case 3:
if (options.fixed_order_filename.empty()) {
cout << "Error: text file required for ordering\n\n";
exit(1);
}
return new FixedOrdering(inst, options.fixed_order_filename);
case 4:
return new NoOrdering();
}
return NULL;
}
void CuthillMcKeePairOrdering::construct_ordering()
{
typedef adjacency_list<vecS, vecS, undirectedS,
property<vertex_color_t, default_color_type, property<vertex_degree_t,int>>> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
map<int,int> var_to_graph;
vector<int> graph_to_var;
// Find relevant variables first
int k = 0;
for (BPRow* row : inst->rows) {
if (row->nnonz == 2) {
if (var_to_graph.find(row->ind[0]) == var_to_graph.end()) {
var_to_graph[row->ind[0]] = k++;
graph_to_var.push_back(row->ind[0]);
}
if (var_to_graph.find(row->ind[1]) == var_to_graph.end()) {
var_to_graph[row->ind[1]] = k++;
graph_to_var.push_back(row->ind[1]);
}
}
}
Graph graph(graph_to_var.size());
for (BPRow* row : inst->rows) {
if (row->nnonz == 2) {
add_edge(var_to_graph[row->ind[0]], var_to_graph[row->ind[1]], graph);
}
}
// typedef graph_traits<Graph>::edge_iterator edge_iterator;
// pair<edge_iterator, edge_iterator> ei = edges(graph);
// for (edge_iterator it = ei.first; it != ei.second; ++it) {
// cout << "(" << source(*it, graph) << ", " << target(*it, graph) << ")" << endl;
// }
property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, graph);
vector<Vertex> perm(num_vertices(graph));
// Run heuristic
cuthill_mckee_ordering(graph, perm.begin(), get(vertex_color, graph), get(vertex_degree, graph));
v_in_layer.clear();
// Add variables not in a pair constraint
for (BPVar* var : inst->vars) {
if (var_to_graph.find(var->index) == var_to_graph.end()) {
v_in_layer.push_back(var->index);
}
}
// Add variables to ordering
for (vector<Vertex>::const_iterator i = perm.begin(); i != perm.end(); ++i) {
v_in_layer.push_back(graph_to_var[index_map[*i]]);
}
}
| 26.377778 | 98 | 0.675232 | [
"vector"
] |
edeacaec9277fbdb76211e1eb4c30fdb287f5728 | 877 | cpp | C++ | Algorithms/04-Sorting/Big_Sorting/main.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | Algorithms/04-Sorting/Big_Sorting/main.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | Algorithms/04-Sorting/Big_Sorting/main.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::ofstream fout(getenv("OUTPUT_PATH"));
int length;
std::cin >> length;
std::vector<std::string> str_nums(length);
for (std::string &s : str_nums) {
std::cin >> s;
}
std::sort(str_nums.begin(), str_nums.end(), [](const std::string &s_a, const std::string &s_b) {
int length_a = s_a.length();
int length_b = s_b.length();
if (length_a == length_b) {
for (int i = 0; i < length_a; ++i) {
if (s_a[i] == s_b[i]) {
continue;
}
return s_a[i] < s_b[i];
}
}
return length_a < length_b;
});
for (std::string &s : str_nums) {
fout << s << "\n";
}
fout.close();
return 0;
}
| 22.487179 | 100 | 0.489168 | [
"vector"
] |
edef8be19eba81a71309397464a3f58e81ea7079 | 20,053 | cpp | C++ | python/DirectedConformerGeneratorPython.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | null | null | null | python/DirectedConformerGeneratorPython.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | null | null | null | python/DirectedConformerGeneratorPython.cpp | Dom1L/molassembler | dafc656b1aa846b65b1fd1e06f3740ceedcf22db | [
"BSD-3-Clause"
] | null | null | null | /*!@file
* @copyright This code is licensed under the 3-clause BSD license.
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
* See LICENSE.txt for details.
*/
#include "TypeCasters.h"
#include "pybind11/eigen.h"
#include "pybind11/functional.h"
#include "Molassembler/Molecule.h"
#include "Molassembler/DirectedConformerGenerator.h"
#include "Molassembler/BondStereopermutator.h"
#include "Molassembler/DistanceGeometry/Error.h"
#include "Utils/Geometry/AtomCollection.h"
using namespace Scine::Molassembler;
using ConformerVariantType = boost::variant<
Scine::Utils::PositionCollection,
DgError
>;
extern ConformerVariantType variantCast(outcome::result<Scine::Utils::PositionCollection>);
void init_directed_conformer_generator(pybind11::module& m) {
pybind11::class_<DirectedConformerGenerator> dirConfGen(
m,
"DirectedConformerGenerator",
R"delim(
Helper type for directed conformer generation.
Generates new combinations of BondStereopermutator assignments
and provides helper functions for the generation of conformers using these
combinations and the reverse, finding the combinations from conformers.
It is important that you lower your expectations for the modeling of
dihedral energy minima, however. Considering that Molassembler neither
requires you to supply a correct graph, never detects or kekulizes
aromatic systems nor asks you to supply an overall charge for a molecule,
it should be understandable that the manner in which Molassembler decides
where dihedral energy minima are is somewhat underpowered. The manner in
which shape vertices are aligned in stereopermutation enumeration isn't
even strictly based on a physical principle. We suggest the following to
make the most of what the library can do for you:
- Read the documentation for the various alignments. Consider using not
just the default
:class:`~scine_molassembler.BondStereopermutator.Alignment.Staggered`
alignment, but either
:class:`~scine_molassembler.BondStereopermutator.Alignemnt.EclipsedAndStaggered`
or
:class:`~scine_molassembler.BondStereopermutator.Alignment.BetweenEclipsedAndStaggered`
to improve your chances of capturing all rotational minima. This will
likely generate more conformers than strictly required, but should
capture all minima.
- Energy minimize all generated conformers with a suitable method and
then deduplicate.
- Consider using the
:class:`~scine_molassembler.DirectedConformerGenerator.Relabeler` to do
a final deduplication step.
>>> butane = io.experimental.from_smiles("CCCC")
>>> generator = DirectedConformerGenerator(butane)
>>> assert generator.bond_list()
>>> conformers = []
>>> while generator.decision_list_set_size() < generator.ideal_ensemble_size:
... conformers.append(
... generator.generate_random_conformation(
... generator.generate_decision_list()
... )
... )
>>> assert len(conformers) == generator.ideal_ensemble_size()
)delim"
);
pybind11::enum_<DirectedConformerGenerator::IgnoreReason>(
dirConfGen,
"IgnoreReason",
"Reason why a bond is ignored for directed conformer generation"
).value("AtomStereopermutatorPreconditionsUnmet", DirectedConformerGenerator::IgnoreReason::AtomStereopermutatorPreconditionsUnmet, "There is not an assigned stereopermutator on both ends of the bond")
.value("HasAssignedBondStereopermutator", DirectedConformerGenerator::IgnoreReason::HasAssignedBondStereopermutator, "There is already an assigned bond stereopermutator on the bond")
.value("HasTerminalConstitutingAtom", DirectedConformerGenerator::IgnoreReason::HasTerminalConstitutingAtom, "At least one consituting atom is terminal")
.value("InCycle", DirectedConformerGenerator::IgnoreReason::InCycle, "The bond is in a cycle (see C++ documentation for details why cycle bonds are excluded)")
.value("IsEtaBond", DirectedConformerGenerator::IgnoreReason::IsEtaBond, "The bond is an eta bond")
.value("RotationIsIsotropic", DirectedConformerGenerator::IgnoreReason::RotationIsIsotropic, "Rotation around this bond is isotropic (at least one side's rotating substituents all have the same ranking)");
dirConfGen.def_static(
"consider_bond",
&DirectedConformerGenerator::considerBond,
pybind11::arg("bond_index"),
pybind11::arg("molecule"),
pybind11::arg("alignment") = BondStereopermutator::Alignment::Staggered,
R"delim(
Decide whether to consider a bond's dihedral for directed conformer
generation or not. Returns either an IgnoreReason or an unowned
stereopermutator instance.
:param bond_index: Bond index to consider
:param molecule: The molecule in which bond_index is valid
:param alignment: Alignment to generate BondStereopermutator instances
with. Affects stereopermutation counts.
)delim"
);
dirConfGen.def_static(
"distance",
&DirectedConformerGenerator::distance,
pybind11::arg("decision_list_a"),
pybind11::arg("decision_list_b"),
pybind11::arg("bounds"),
R"delim(
Calculates a distance metric between two decision lists for dihedral
permutations given bounds on the values at each position of the decision
lists.
:param decision_list_a: The first decision list
:param decision_list_b: The second decision list
:param bounds: Value bounds on each entry in the decision lists
)delim"
);
dirConfGen.def(
pybind11::init<Molecule, BondStereopermutator::Alignment, const DirectedConformerGenerator::BondList&>(),
pybind11::arg("molecule"),
pybind11::arg("alignment") = BondStereopermutator::Alignment::Staggered,
pybind11::arg("bonds_to_consider") = std::vector<BondIndex> {},
R"delim(
Construct a generator for a particular molecule.
:param molecule: For which molecule to construct a generator
:param alignment: Alignment with which to generate BondStereopermutator
instances on considered bonds
:param bonds_to_consider: List of bonds that should be considered for
directed conformer generation. Bonds for which consider_bond yields an
IgnoreReason will still be ignored.
)delim"
);
dirConfGen.def(
"generate_decision_list",
[](DirectedConformerGenerator& cg) {
return cg.generateNewDecisionList();
},
R"delim(
Generate a new list of discrete dihedral arrangement choices. Guarantees
that the new list is not yet part of the underlying set. Inserts the
generated list into the underlying set. Will not generate the same
decision list twice.
.. note::
This function advances ``molassembler``'s global PRNG state.
)delim"
);
dirConfGen.def(
"insert",
&DirectedConformerGenerator::insert,
pybind11::arg("decision_list"),
R"delim(
Add a decision list to the underlying set-like data structure.
:param decision_list: Decision list to insert into the underlying data structure.
)delim"
);
dirConfGen.def(
"contains",
&DirectedConformerGenerator::contains,
pybind11::arg("decision_list"),
R"delim(
Checks whether a particular decision list is part of the underlying set
:param decision_list: Decision list to check for in the underlying data structure
)delim"
);
dirConfGen.def_property_readonly(
"bond_list",
&DirectedConformerGenerator::bondList,
R"delim(
Get a list of considered bond indices. These are the bonds for which no
ignore reason was found at construction-time.
)delim"
);
dirConfGen.def(
"decision_list_set_size",
&DirectedConformerGenerator::decisionListSetSize,
R"delim(
The number of conformer decision lists stored in the underlying set-liked
data structure
)delim"
);
dirConfGen.def_property_readonly(
"ideal_ensemble_size",
&DirectedConformerGenerator::idealEnsembleSize,
"Returns the number of conformers needed for a full ensemble"
);
dirConfGen.def(
"generate_random_conformation",
[](
DirectedConformerGenerator& generator,
const DirectedConformerGenerator::DecisionList& decisionList,
const DistanceGeometry::Configuration& configuration
) -> ConformerVariantType {
return variantCast(
generator.generateRandomConformation(decisionList, configuration)
);
},
pybind11::arg("decision_list"),
pybind11::arg("configuration") = DistanceGeometry::Configuration {},
R"delim(
Try to generate a conformer for a particular decision list.
:param decision_list: Decision list to use in conformer generation
:param configuration: Distance geometry configurations object. Defaults
are usually fine.
.. note::
This function advances ``molassembler``'s global PRNG state.
)delim"
);
dirConfGen.def(
"generate_conformation",
[](
DirectedConformerGenerator& generator,
const DirectedConformerGenerator::DecisionList& decisionList,
const unsigned seed,
const DistanceGeometry::Configuration& configuration
) -> ConformerVariantType {
return variantCast(
generator.generateConformation(decisionList, seed, configuration)
);
},
pybind11::arg("decision_list"),
pybind11::arg("seed"),
pybind11::arg("configuration") = DistanceGeometry::Configuration {},
R"delim(
Try to generate a conformer for a particular decision list.
:param decision_list: Decision list to use in conformer generation
:param seed: Seed to initialize a PRNG with for use in conformer
generation.
:param configuration: Distance geometry configurations object. Defaults
are usually fine.
)delim"
);
dirConfGen.def(
"conformation_molecule",
&DirectedConformerGenerator::conformationMolecule,
pybind11::arg("decision_list"),
R"delim(
Yields a molecule whose bond stereopermutators are set for a particular
decision list.
:param decision_list: List of assignments for the considered bonds of the
generator.
)delim"
);
dirConfGen.def(
"get_decision_list",
pybind11::overload_cast<const Scine::Utils::AtomCollection&, BondStereopermutator::FittingMode>(
&DirectedConformerGenerator::getDecisionList,
pybind11::const_
),
pybind11::arg("atom_collection"),
pybind11::arg("fitting_mode") = BondStereopermutator::FittingMode::Nearest,
R"delim(
Infer a decision list for the relevant bonds from positions.
For all bonds considered relevant (i.e. all bonds in bond_list()), fits
supplied positions to possible stereopermutations and returns the result.
Entries have a value equal to ``UNKNOWN_DECISION`` if no permutation
could be recovered. The usual BondStereopermutator fitting tolerances
apply.
Assumes several things about your supplied positions:
- There have only been dihedral changes
- No atom stereopermutator assignment changes
- No constitutional rearrangements
This variant of get_decision_lists checks that the element type sequence
matches that of the underlying molecule, which holds for conformers
generated using the underlying molecule.
:param atom_collection: Positions from which to interpret the decision
list from.
:param fitting_mode: Mode altering how decisions are fitted.
)delim"
);
dirConfGen.def(
"get_decision_list",
pybind11::overload_cast<const Scine::Utils::PositionCollection&, BondStereopermutator::FittingMode>(
&DirectedConformerGenerator::getDecisionList,
pybind11::const_
),
pybind11::arg("positions"),
pybind11::arg("fitting_mode") = BondStereopermutator::FittingMode::Nearest,
R"delim(
Infer a decision list for the relevant bonds from positions.
For all bonds considered relevant (i.e. all bonds in bond_list()), fits
supplied positions to possible stereopermutations and returns the result.
Entries have a value equal to ``UNKNOWN_DECISION`` if no permutation
could be recovered. The usual BondStereopermutator fitting tolerances
apply.
Assumes several things about your supplied positions:
- There have only been dihedral changes
- No atom stereopermutator assignment changes
- No constitutional rearrangements
:param atom_collection: Positions from which to interpret the decision
list from.
:param fitting_mode: Mode altering how decisions are fitted.
)delim"
);
dirConfGen.def_property_readonly_static(
"UNKNOWN_DECISION",
[](pybind11::object /* self */) {
return DirectedConformerGenerator::unknownDecision;
},
R"delim(
Value set in decision list interpretations from positions if no assignment
could be recovered.
)delim"
);
pybind11::class_<DirectedConformerGenerator::EnumerationSettings> enumerationSettings(
dirConfGen,
"EnumerationSettings",
R"delim(
Settings for conformer enumeration
)delim"
);
enumerationSettings.def(
pybind11::init<>(),
"Default-initialize enumeration settings"
);
enumerationSettings.def_readwrite(
"dihedral_retries",
&DirectedConformerGenerator::EnumerationSettings::dihedralRetries,
"Number of attempts to generate the dihedral decision"
);
enumerationSettings.def_readwrite(
"fitting",
&DirectedConformerGenerator::EnumerationSettings::fitting,
"Mode for fitting dihedral assignments"
);
enumerationSettings.def_readwrite(
"configuration",
&DirectedConformerGenerator::EnumerationSettings::configuration,
"Configuration for conformer generation scheme"
);
enumerationSettings.def(
"__repr__",
[](pybind11::object settings) -> std::string {
const std::vector<std::string> members {
"dihedral_retries",
"fitting",
"configuration"
};
std::string repr = "(";
for(const std::string& member : members) {
const std::string member_repr = pybind11::str(settings.attr(member.c_str()));
repr += member + "=" + member_repr + ", ";
}
repr.pop_back();
repr.pop_back();
repr += ")";
return repr;
}
);
dirConfGen.def(
"enumerate",
&DirectedConformerGenerator::enumerate,
pybind11::arg("callback"),
pybind11::arg("seed"),
pybind11::arg("settings") = DirectedConformerGenerator::EnumerationSettings {},
pybind11::call_guard<pybind11::gil_scoped_release>(),
R"delim(
Enumerate all conformers of the captured molecule
Clears the stored set of decision lists, then enumerates all conformers
of the molecule in parallel.
.. note::
This function is parallelized and will utilize ``OMP_NUM_THREADS``
threads. Callback invocations are unsequenced but the arguments are
reproducible.
:param callback: Function called with decision list and conformer
positions for each successfully generated pair.
:param seed: Randomness initiator for decision list and conformer
generation
:param settings: Further parameters for enumeration algorithms
)delim"
);
dirConfGen.def(
"enumerate_random",
&DirectedConformerGenerator::enumerateRandom,
pybind11::arg("callback"),
pybind11::arg("settings") = DirectedConformerGenerator::EnumerationSettings {},
pybind11::call_guard<pybind11::gil_scoped_release>(),
R"delim(
Enumerate all conformers of the captured molecule
Clears the stored set of decision lists, then enumerates all conformers
of the molecule in parallel.
.. note::
This function is parallelized and will utilize ``OMP_NUM_THREADS``
threads. Callback invocations are unsequenced but the arguments are
reproducible given the same global PRNG state.
.. note::
This function advances ``molassembler``'s global PRNG state.
:param callback: Function called with decision list and conformer
positions for each successfully generated pair.
:param settings: Further parameters for enumeration algorithms
)delim"
);
dirConfGen.def(
"relabeler",
&DirectedConformerGenerator::relabeler,
"Generate a Relabeler for the underlying molecule and bonds"
);
dirConfGen.def(
"bin_midpoint_integers",
&DirectedConformerGenerator::binMidpointIntegers,
"Relabels a decision list into bin midpoint integers"
);
pybind11::class_<DirectedConformerGenerator::Relabeler> relabeler(
dirConfGen,
"Relabeler",
R"delim(
Functionality for relabeling decision lists of minimized structures
Determines dihedral bins from true dihedral distributions of minimized
structures and generates bin membership lists for all processed
structures.
)delim"
);
relabeler.def_static(
"density_bins",
&DirectedConformerGenerator::Relabeler::densityBins,
pybind11::arg("dihedrals"),
pybind11::arg("delta"),
pybind11::arg("symmetry_order") = 1,
R"delim(
Simplest density-based binning function
Generates bins for a set of dihedral values by sorting the dihedral
values and then considering any values within the delta as part of the
same bin.
Returns a list of pairs representing bin intervals. It is not guaranteed
that the start of the interval is smaller than the end of the interval.
This is because of dihedral angle periodicity. The boundaries of the first
interval of the bins can have inverted order to indicate wrapping.
:param dihedrals: List of dihedral values to bin
:param delta: Maximum dihedral distance between dihedral values to
include in the same bin in radians
:raises RuntimeError: If the passed list of dihedrals is empty
>>> bins = DirectedConformerGenerator.Relabeler.bins
>>> bins([0.1, 0.2], 0.1)
[(0.1, 0.2)]
>>> bins([0.1, 0.2, 0.4], 0.1)
[(0.1, 0.2), (0.4, 0.4)]
>>> bins([0.1, 0.2, 3.1, -3.1], 0.1) # Inverted boundaries with wrap
[(3.1, -3.1), (0.1, 0.2)]
)delim"
);
relabeler.def(
"bins",
&DirectedConformerGenerator::Relabeler::bins,
pybind11::arg("delta") = M_PI / 6,
R"delim(
Generate bins for all observed dihedrals
:param delta: Maximum dihedral distance between dihedral values to
include in the same bin in radians
)delim"
);
relabeler.def(
"add",
&DirectedConformerGenerator::Relabeler::add,
pybind11::arg("positions"),
"Add a particular position to the set to relabel"
);
relabeler.def(
"bin_indices",
&DirectedConformerGenerator::Relabeler::binIndices,
pybind11::arg("bins"),
R"delim(
Determine relabeling for all added positions
Returns a list of bin membership indices for each added structure in
sequence.
:param bins: Bin intervals for all observed bonds (see bins function)
)delim"
);
relabeler.def(
"bin_midpoint_integers",
&DirectedConformerGenerator::Relabeler::binMidpointIntegers,
pybind11::arg("bin_indices"),
pybind11::arg("bins"),
R"delim(
Relabel bin indices into the rounded dihedral value of their bin midpoint
:param bin_indices: All structures' bin indices (see bin_indices)
:param bins: Bin intervals for all observed bonds (see bins function)
)delim"
);
relabeler.def_readonly(
"sequences",
&DirectedConformerGenerator::Relabeler::sequences,
"Dominant index sequences at each considered bond"
);
relabeler.def_readonly(
"dihedrals",
&DirectedConformerGenerator::Relabeler::observedDihedrals,
"Observed dihedrals at each bond in added structures"
);
}
| 36.001795 | 209 | 0.712412 | [
"geometry",
"object",
"shape",
"vector"
] |
edf441db2e8f27dfc37090e940d87b11819f1fb8 | 2,643 | hh | C++ | Gurvich-Wirzt/trunk/nachos-unr21a/code/userprog/executable.hh | swirzt/SistemasOoperativos2 | 2db49410837eb18a4b5afcabd229519f61a2e8ab | [
"MIT"
] | null | null | null | Gurvich-Wirzt/trunk/nachos-unr21a/code/userprog/executable.hh | swirzt/SistemasOoperativos2 | 2db49410837eb18a4b5afcabd229519f61a2e8ab | [
"MIT"
] | null | null | null | Gurvich-Wirzt/trunk/nachos-unr21a/code/userprog/executable.hh | swirzt/SistemasOoperativos2 | 2db49410837eb18a4b5afcabd229519f61a2e8ab | [
"MIT"
] | null | null | null | /// In order to run a user program, you must:
///
/// 1. Link with the `-N -T 0` option.
/// 2. Run `coff2noff` to convert the object file to Nachos format (Nachos
/// object code format is essentially just a simpler version of the UNIX
/// executable object code format).
/// 3. Load the NOFF file into the Nachos file system (if you have not
/// implemented the file system yet, you do not need to do this last
/// step).
///
/// Copyright (c) 2019-2021 Docentes de la Universidad Nacional de Rosario.
/// All rights reserved. See `copyright.h` for copyright notice and
/// limitation of liability and disclaimer of warranty provisions.
#ifndef NACHOS_USERPROG_EXECUTABLE__HH
#define NACHOS_USERPROG_EXECUTABLE__HH
#include "bin/noff.h"
#include "filesys/open_file.hh"
/// Assumes that the object code file is in NOFF format.
class Executable {
public:
Executable(OpenFile *new_file);
/// Check if the executable is valid and fix endianness if necessary.
///
/// Check if the executable conforms to the NOFF file format by checking
/// the magic number at the beginning of the header. Also detect if it
/// is reversed (due to mismatching endianness) and in that case swap the
/// entire header.
bool CheckMagic();
uint32_t GetSize() const;
uint32_t GetCodeSize() const;
uint32_t GetInitDataSize() const;
uint32_t GetUninitDataSize() const;
/// The following methods provide addresses where each segment is meant
/// to start. These addresses refer to main memory, not to the file.
/// Keep in mind that when a virtual addressing mechanism is used, these
/// addresses are to be considered virtual, not physical.
uint32_t GetCodeAddr() const;
uint32_t GetInitDataAddr() const;
uint32_t GetUninitDataAddr() const;
/// The following methods read a block from a given program segment into
/// memory. Reads are possible only from the code and the initialized
/// data segments, because these are the ones that actually encode their
/// contents in the file. The uninitialized data segment is composed of
/// all zeroes and these are not encoded in the file.
///
/// Parameters:
/// * `dest` is the start address of a memory array.
/// * `size` is the amount of bytes to read.
/// * `offset` is the relative position inside the respective segment
/// where the start of the block is to be found.
int ReadCodeBlock(char *dest, uint32_t size, uint32_t offset);
int ReadDataBlock(char *dest, uint32_t size, uint32_t offset);
private:
OpenFile *file;
noffHeader header;
};
#endif
| 36.708333 | 77 | 0.704124 | [
"object"
] |
edf66572f2f48c8a57561bfe7e0ff7b704533bfc | 15,619 | cpp | C++ | ias-libnntool/tool.cpp | dark-sunlight/nntool | 7d26e1a2e45399f51760697bec6dd68d36607e5c | [
"Apache-2.0"
] | null | null | null | ias-libnntool/tool.cpp | dark-sunlight/nntool | 7d26e1a2e45399f51760697bec6dd68d36607e5c | [
"Apache-2.0"
] | 8 | 2020-04-13T12:17:35.000Z | 2020-06-20T19:21:30.000Z | ias-libnntool/tool.cpp | dark-sunlight/nntool | 7d26e1a2e45399f51760697bec6dd68d36607e5c | [
"Apache-2.0"
] | 1 | 2020-05-02T14:27:06.000Z | 2020-05-02T14:27:06.000Z | /*!
\file tool.cpp
\author zafaco GmbH <info@zafaco.de>
\date Last update: 2019-11-13
Copyright (C) 2016 - 2019 zafaco GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tool.h"
//! \brief
//! Standard Constructor
CTool::CTool()
{
}
//! \brief
//! Virtual Destructor
CTool::~CTool()
{
}
//! \brief
//! Convert String to Int
//! \param s String
//! \return i Int
int CTool::toInt( string s )
{
int i;
stringstream sstr(s);
sstr >> i;
return i;
}
//! \brief
//! Convert String to Int
//! \param s String
//! \return i Int
unsigned int CTool::toUInt( string s )
{
unsigned int b;
stringstream sstr(s);
sstr >> b;
return b;
}
//! \brief
//! Convert String to unsigned long long
//! \param s String
//! \return b unsigned long long
unsigned long long CTool::toULL( string s )
{
unsigned long long b;
stringstream sstr(s);
sstr >> b;
return b;
}
//! \brief
//! Convert String to long long
//! \param s String
//! \return b long long
long long CTool::toLL( string s )
{
long long b;
stringstream sstr(s);
sstr >> b;
return b;
}
//! \brief
//! Convert String to float
//! \param s String
//! \return b float
float CTool::toFloat(string s)
{
float b;
stringstream sstr(s);
sstr >> b;
return b;
}
//! \brief
//! Convert to lower case
//! \param sText String
void CTool::toLower(string &sText)
{
for(unsigned int n = 0; n < sText.size(); n++)
{
sText.at(n) = tolower(sText.at(n));
}
}
//! \brief
//! Convert to upper case
//! \param sText String
void CTool::toUpper(string &sText)
{
for(unsigned int n = 0; n < sText.size(); n++)
{
sText.at(n) = toupper(sText.at(n));
}
}
string CTool::get_ip_str(const struct sockaddr *sa)
{
string ip;
switch(sa->sa_family)
{
case AF_INET:
{
char s1[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),s1, INET_ADDRSTRLEN);
ip = string(s1);
break;
}
case AF_INET6:
{
char s2[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),s2, INET6_ADDRSTRLEN);
ip = string(s2);
break;
}
default:
{
ip = "0.0.0.0";
}
}
return ip;
}
unsigned long long CTool::calculateResultsMin( map<int,unsigned long long> dmap )
{
unsigned long long min = dmap.begin()->second;
map<int, unsigned long long>::iterator AI;
//Starting multiple Instances for every Probe
for (AI = dmap.begin(); AI != dmap.end(); ++AI)
{
if( (*AI).second < min )
min = (*AI).second;
}
return min;
}
unsigned long long CTool::calculateResultsAvg( map<int,unsigned long long> dmap )
{
int count = 0;
unsigned long long avg = 0;
map<int, unsigned long long>::iterator AI;
//Starting multiple Instances for every Probe
for (AI = dmap.begin(); AI != dmap.end(); ++AI)
{
avg += (*AI).second;
count++;
}
if( count != 0 )
{
avg = avg/count;
}
return avg;
}
int CTool::calculateResults(struct measurement_data &sMeasurement)
{
return CTool::calculateResults(sMeasurement, 1, 0, 0);
}
int CTool::calculateResults(struct measurement_data &sMeasurement, double increment, int ai_offset, unsigned long long duration)
{
double count = 0;
unsigned long long min = std::next(sMeasurement.results.begin(), ai_offset)->second;
unsigned long long avg = 0;
unsigned long long max = 0;
unsigned long long sum = 0;
unsigned long long sumSq = 0;
double avgDouble = 0;
#ifdef NNTOOL
vector<double> medianVector;
#endif
map<int, unsigned long long>::iterator AI;
//Starting multiple Instances for every Probe
for (AI = std::next(sMeasurement.results.begin(), ai_offset); AI != sMeasurement.results.end(); ++AI)
{
if( (*AI).second < min )
min = (*AI).second;
if( (*AI).second > max )
max = (*AI).second;
sum += (*AI).second;
#ifdef NNTOOL
medianVector.push_back((*AI).second);
sumSq += (*AI).second * (*AI).second;
#endif
count += increment;
}
if( count != 0 )
{
if (duration != 0)
{
avg = avgDouble = (double)sum / ( (double)duration / 1e6);
}
else
{
avg = avgDouble = (double)sum / (double)count;
}
sMeasurement.min = min;
sMeasurement.avg = avg;
sMeasurement.max = max;
#ifdef NNTOOL
if (duration != 0)
{
sMeasurement.duration_ns = duration * 1000;
}
else
{
sMeasurement.duration_ns = count * 1000 * 1000 * 1000;
}
sMeasurement.interim_values = medianVector;
//calculate median
sort(medianVector.begin(), medianVector.end());
size_t samples = medianVector.size();
if (samples%2 == 0)
{
sMeasurement.median_ns = ((medianVector[samples/2-1] + medianVector[samples/2])/2) * 1000;
}
else
{
sMeasurement.median_ns = medianVector[samples/2] * 1000;
}
//calculate population standard deviation
double variancePopulation = (double)sumSq / (double)count - avgDouble * avgDouble;
sMeasurement.standard_deviation_ns = sqrt(variancePopulation) * 1000;
#endif
}
return 0;
}
//! \brief
//! Get Systeminfo OS
//! \return time Time in Milliseconds
string CTool::getSystemInfoOS()
{
struct utsname unameData;
if( uname(&unameData) != 0 )
return "-";
return unameData.sysname;
}
//! \brief
//! Get Systeminfo OS Version
//! \return time Time in Milliseconds
string CTool::getSystemInfoOSVersion()
{
struct utsname unameData;
if( uname(&unameData) != 0 )
return "-";
return unameData.release;
}
//! \brief
//! Get active IP
//! \param sInterface Name of Device
//! \param nType Switch between IPv4 and IPv6
//! \return sIp IP Adress
int CTool::validateIp(const string &ipAddress)
{
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
return (inet_pton(AF_INET6, ipAddress.c_str(), &(sa6.sin6_addr)) != 0) ? 6 : (inet_pton(AF_INET, ipAddress.c_str(), &(sa4.sin_addr)) != 0) ? 4 : 0;
}
//! \brief
//! Get Timestamps in ms
//! \return time Time in Milliseconds
int CTool::get_timestamp_usec()
{
struct timeval tp;
gettimeofday(&tp,NULL);
return tp.tv_usec;
}
//! \brief
//! Get Timestamps in s
//! \return time Time in Seconds
int CTool::get_timestamp_sec()
{
struct timeval tp;
gettimeofday(&tp,NULL);
return tp.tv_sec;
}
//! \brief
//! Get Timestamps complete
//! \return time Time in uSeconds
unsigned long long CTool::get_timestamp()
{
struct timeval tp;
gettimeofday(&tp,NULL);
return ( ( (unsigned long long)(tp.tv_sec) * 1000000 ) + (unsigned long long)(tp.tv_usec));
}
//! \brief
//! Get Timestamp-Offset CET / CEST
//! \return offset
int CTool::get_timestamp_offset()
{
struct tm * lt;
time_t t = time(NULL);
lt = localtime(&t);
long int offset = lt->tm_gmtoff;
return offset;
}
//! \brief
//! Get Timestamp-Offset CET / CEST
//! \return offset
string CTool::get_timestamp_string()
{
string date;
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
date = string( dt );
date.erase( remove(date.begin(), date.end(), '\r'), date.end() );
date.erase( remove(date.begin(), date.end(), '\n'), date.end() );
return date;
}
void CTool::replaceStringInPlace(string& subject, const string& search, const string& replace)
{
size_t pos = 0;
while((pos = subject.find(search, pos)) != string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
//! \brief
//! Tokenize a String into vector elements of type string
//! \param &str
//! \param &tokens
//! \param &delimiters
void CTool::tokenize(string &str,vector<string> &tokens, string &delimiters)
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while( string::npos != pos || string::npos != lastPos )
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
//! \brief
//! Fork a child process, execute Programm, and return it's pid.
//! \return -1 if fork failed.
pid_t CTool::spawn_process( char *args1[] )
{
pid_t pid = fork();
if (pid == -1)
{
TRC_ERR( "Error: Could not fork Process" );
return -1;
}
// If fork() returns 0, this is is the child process.
// If fork() returns non-zero, we are the parent and the return value is the PID of the child process.
if (pid == 0)
{
// when you call exec, it replaces the currently running process (the child process) with whatever we pass to exec.
execv( args1[0], args1 );
abort();
}
else
{
// parent, return the child's PID back to main.
return pid;
}
}
//! \brief
//! Get the WAN interface speed, configured in ntservice.ini
//! \param sString
//! \return s
string CTool::getDownloadSpeed( string sString )
{
string s;
size_t first;
size_t last;
const char seperator = '_';
last = sString.rfind(seperator);
first = sString.rfind(seperator, last - 1);
s = sString.substr( first + 1, last - first - 1 );
return s;
}
//! \brief
//! Fork a child process, execute Programm, and return it's pid.
//! \param sString
//! \return s
string CTool::getIpFromHostname( string sString )
{
return getIpFromHostname(sString, 6);
}
//! \brief
//! Fork a child process, execute Programm, and return it's pid.
//! \param sString
//! \return s
string CTool::getIpFromHostname( string sString, int nType )
{
int error = 0;
char host[NI_MAXHOST];
struct addrinfo query, *result;
// Request only one socket type from getaddrinfo(). Else we would get both SOCK_DGRAM and SOCK_STREAM, and print two copies of each numeric address.
memset(&query, 0, sizeof query);
if( nType == 4 )
query.ai_family = AF_INET; //IPv4
if( nType == 6)
query.ai_family = AF_INET6; //IPv6
query.ai_socktype = SOCK_DGRAM;
// Use getaddrinfo() to resolve "servername" and allocate a linked list of addresses.
// If we get an error, break loop and jump to end for saving results
if( ( error = getaddrinfo(sString.c_str(), NULL, &query, &result) ) != 0 )
{
query.ai_family = AF_INET; //IPv4
// Use getaddrinfo() to resolve "servername" and allocate a linked list of addresses.
// If we get an error, break loop and jump to end for saving results
if( ( error = getaddrinfo(sString.c_str(), NULL, &query, &result) ) != 0 )
{
TRC_ERR( "Could not Request DNS - DNS ERROR" );
return "1.1.1.1";
}
}
//Convert Server Name in Human Readable
getnameinfo(result->ai_addr, result->ai_addrlen,host, sizeof host, NULL, 0, NI_NUMERICHOST);
freeaddrinfo(result);
return string(host);
}
struct addrinfo* CTool::getIpsFromHostname( string sString, bool bReachable )
{
int error = 0;
struct addrinfo query, *ips;
memset(&query, 0, sizeof query);
query.ai_family = AF_UNSPEC;
if (bReachable)
{
query.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG);
}
else
{
query.ai_flags = AI_V4MAPPED;
}
if( ( error = getaddrinfo(sString.c_str(), NULL, &query, &ips) ) != 0 )
{
TRC_ERR( "Could not Request DNS - DNS ERROR" );
}
return ips;
}
//! \brief
//! Fork a child process, execute Programm, and return it's pid.
//! \param sString
//! \return s
string CTool::getHostname()
{
char hostname[1024];
gethostname(hostname, 1024);
return string(hostname);
}
//! \brief
//! Generate random data of size int
//! \param *sbuffer
//! \param size
//! \return 0
int CTool::randomData()
{
return (255 * (rand() / (RAND_MAX + 1.0)) );
}
//! \brief
//! Generate random data of size int
//! \param *sbuffer
//! \param size
//! \return 0
int CTool::randomData(char *sbuffer, int size)
{
// Provide seed for the random number generator.
srand(CTool::get_timestamp());
for (int counter = 0; counter < size; counter++)
{
sbuffer[counter] = (char)randomData();
}
return 0;
}
//! \brief
//! Generate random data of size int
//! \param *sbuffer
//! \param size
//! \return 0
int CTool::randomData(vector<char> &vVector, int size)
{
// Provide seed for the random number generator.
srand(CTool::get_timestamp());
for( int i = 0; i < size; i++ )
vVector.push_back( (char)randomData() );
return 0;
}
/** Print a demangled stack backtrace of the caller function to FILE* out. */
void CTool::print_stacktrace()
{
//backtrace under android doesn't work as is (no execinfo.h)
#ifndef __ANDROID__
char chTrace[1024];
TRC_DEBUG( "stack trace:" );
// storage array for stack trace address data
void* addrlist[64];
// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if (addrlen == 0)
{
TRC_DEBUG( " <empty, possibly corrupt>" );
return;
}
// resolve addresses into strings containing "filename(function+address)",
// this array must be free()-ed
char** symbollist = backtrace_symbols(addrlist, addrlen);
// allocate string which will be filled with the demangled function name
size_t funcnamesize = 256;
char* funcname = (char*)malloc(funcnamesize);
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 1; i < addrlen; i++)
{
char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for (char *p = symbollist[i]; *p; ++p)
{
if (*p == '(')
begin_name = p;
else if (*p == '+')
begin_offset = p;
else if (*p == ')' && begin_offset)
{
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset
&& begin_name < begin_offset)
{
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name,funcname, &funcnamesize, &status);
if (status == 0)
{
funcname = ret; // use possibly realloc()-ed string
snprintf(chTrace, sizeof(chTrace), " %s : %s+%s",symbollist[i], funcname, begin_offset);
TRC_DEBUG(chTrace);
}
else
{
// demangling failed. Output function name as a C function with
// no arguments.
snprintf(chTrace, sizeof(chTrace), " %s : %s()+%s",symbollist[i], begin_name, begin_offset);
TRC_DEBUG(chTrace);
}
}
else
{
// couldn't parse the line? print the whole line.
snprintf(chTrace, sizeof(chTrace), " %s", symbollist[i]);
TRC_DEBUG(chTrace);
}
}
free(funcname);
free(symbollist);
#endif
}
string CTool::to_string_precision(double value, const int precision)
{
std::ostringstream out;
out << std::fixed << std::setprecision(precision) << value;
return out.str();
}
| 22.281027 | 149 | 0.647929 | [
"vector"
] |
edfbd9cda60b845153cd4608b9492c06648d86d3 | 26,972 | cpp | C++ | Code/Engine/Math/PhysicsSystem.cpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:44.000Z | 2021-01-25T23:53:44.000Z | Code/Engine/Math/PhysicsSystem.cpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | null | null | null | Code/Engine/Math/PhysicsSystem.cpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:46.000Z | 2021-01-25T23:53:46.000Z | //------------------------------------------------------------------------------------------------------------------------------
#include "Engine/Math/PhysicsSystem.hpp"
#include "Engine/Core/EventSystems.hpp"
#include "Engine/Core/NamedProperties.hpp"
#include "Engine/Math/Collider2D.hpp"
#include "Engine/Math/CollisionHandler.hpp"
#include "Engine/Math/MathUtils.hpp"
#include "Engine/Math/RigidBodyBucket.hpp"
#include "Engine/Math/Rigidbody2D.hpp"
#include "Engine/Math/Trigger2D.hpp"
#include "Engine/Math/TriggerBucket.hpp"
#include "Engine/Renderer/Rgba.hpp"
PhysicsSystem* g_physicsSystem = nullptr;
//------------------------------------------------------------------------------------------------------------------------------
PhysicsSystem::PhysicsSystem()
{
m_rbBucket = new RigidBodyBucket;
m_triggerBucket = new TriggerBucket;
}
//------------------------------------------------------------------------------------------------------------------------------
PhysicsSystem::~PhysicsSystem()
{
}
//------------------------------------------------------------------------------------------------------------------------------
Rigidbody2D* PhysicsSystem::CreateRigidbody( eSimulationType simulationType )
{
Rigidbody2D *rigidbody = new Rigidbody2D(this, simulationType);
return rigidbody;
}
//------------------------------------------------------------------------------------------------------------------------------
Trigger2D* PhysicsSystem::CreateTrigger(eSimulationType simulationType)
{
Trigger2D *trigger = new Trigger2D(this, simulationType);
return trigger;
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::AddRigidbodyToVector(Rigidbody2D* rigidbody)
{
m_rbBucket->m_RbBucket[rigidbody->GetSimulationType()].push_back(rigidbody);
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::AddTriggerToVector(Trigger2D* trigger)
{
m_triggerBucket->m_triggerBucket[trigger->GetSimulationType()].push_back(trigger);
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::DestroyRigidbody( Rigidbody2D* rigidbody )
{
delete rigidbody;
rigidbody = nullptr;
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::SetGravity( const Vec2& gravity )
{
m_gravity = gravity;
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::CopyTransformsFromObjects()
{
// reset per frame stuff;
// copy all transforms over;
for(int rigidTypes = 0; rigidTypes < NUM_SIMULATION_TYPES; rigidTypes++)
{
int numRigidbodies = static_cast<int>(m_rbBucket->m_RbBucket[rigidTypes].size());
for(int rigidbodyIndex = 0; rigidbodyIndex < numRigidbodies; rigidbodyIndex++)
{
if(m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex] != nullptr)
{
m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_transform = *m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_object_transform;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::CopyTransformsToObjects()
{
// figure out movement, apply to actual game object;
for(int rigidTypes = 0; rigidTypes < NUM_SIMULATION_TYPES; rigidTypes++)
{
int numRigidbodies = static_cast<int>(m_rbBucket->m_RbBucket[rigidTypes].size());
for(int rigidbodyIndex = 0; rigidbodyIndex < numRigidbodies; rigidbodyIndex++)
{
if(m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex] != nullptr)
{
*m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_object_transform = m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_transform;
m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_transform.m_rotation = m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_rotation;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::Update( float deltaTime )
{
CopyTransformsFromObjects();
SetAllCollisionsToFalse();
RunStep( deltaTime );
CopyTransformsToObjects();
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::SetAllCollisionsToFalse()
{
for(int rigidTypes = 0; rigidTypes < NUM_SIMULATION_TYPES; rigidTypes++)
{
int numRigidbodies = static_cast<int>(m_rbBucket->m_RbBucket[rigidTypes].size());
for(int rigidbodyIndex = 0; rigidbodyIndex < numRigidbodies; rigidbodyIndex++)
{
if(m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex] != nullptr)
{
m_rbBucket->m_RbBucket[rigidTypes][rigidbodyIndex]->m_collider->SetCollision(false);
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::UpdateAllCollisions()
{
//Check Static vs Static to mark as collided
CheckStaticVsStaticCollisions();
//Dynamic vs Static set
ResolveDynamicVsStaticCollisions(true);
//Dynamic vs Dynamic set
ResolveDynamicVsDynamicCollisions(true);
//Dynamic vs static set with no resolution
ResolveDynamicVsStaticCollisions(false);
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::UpdateTriggers()
{
//Check if any dynamic object has entered/exited trigger
int numTriggers = (int)m_triggerBucket->m_triggerBucket->size();
for (int triggerIndex = 0; triggerIndex < numTriggers; triggerIndex++)
{
m_triggerBucket->m_triggerBucket[STATIC_SIMULATION][triggerIndex]->Update(m_frameCount);
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::PurgeDeletedObjects()
{
for (int rbTypes = 0; rbTypes < NUM_SIMULATION_TYPES; rbTypes++)
{
for (int rbIndex = 0; rbIndex < m_rbBucket->m_RbBucket[rbTypes].size(); rbIndex++)
{
if (!m_rbBucket->m_RbBucket[rbTypes][rbIndex]->m_isAlive)
{
delete m_rbBucket->m_RbBucket[rbTypes][rbIndex];
m_rbBucket->m_RbBucket[rbTypes][rbIndex] = nullptr;
m_rbBucket->m_RbBucket[rbTypes].erase(m_rbBucket->m_RbBucket[rbTypes].begin() + rbIndex);
rbIndex--;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::DebugRender( RenderContext* renderContext ) const
{
DebugRenderRigidBodies(renderContext);
DebugRenderTriggers(renderContext);
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::DebugRenderRigidBodies(RenderContext* renderContext) const
{
for (int rbTypes = 0; rbTypes < NUM_SIMULATION_TYPES; rbTypes++)
{
int numRigidbodies = static_cast<int>(m_rbBucket->m_RbBucket[rbTypes].size());
for (int rbIndex = 0; rbIndex < numRigidbodies; rbIndex++)
{
//Nullptr check first
if (m_rbBucket->m_RbBucket[rbTypes][rbIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[rbTypes][rbIndex]->m_isAlive)
{
continue;
}
eSimulationType simType = m_rbBucket->m_RbBucket[rbTypes][rbIndex]->GetSimulationType();
switch (simType)
{
case TYPE_UNKOWN:
break;
case STATIC_SIMULATION:
{
if (m_rbBucket->m_RbBucket[rbTypes][rbIndex]->m_collider->m_inCollision)
{
m_rbBucket->m_RbBucket[rbTypes][rbIndex]->DebugRender(renderContext, Rgba::MAGENTA);
}
else
{
m_rbBucket->m_RbBucket[rbTypes][rbIndex]->DebugRender(renderContext, Rgba::YELLOW);
}
}
break;
case DYNAMIC_SIMULATION:
{
if (m_rbBucket->m_RbBucket[rbTypes][rbIndex]->m_collider->m_inCollision)
{
m_rbBucket->m_RbBucket[rbTypes][rbIndex]->DebugRender(renderContext, Rgba::RED);
}
else
{
m_rbBucket->m_RbBucket[rbTypes][rbIndex]->DebugRender(renderContext, Rgba::BLUE);
}
}
break;
case NUM_SIMULATION_TYPES:
break;
default:
break;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::DebugRenderTriggers(RenderContext* renderContext) const
{
for (int triggerTypes = 0; triggerTypes < NUM_SIMULATION_TYPES; triggerTypes++)
{
int numTriggers = static_cast<int>(m_triggerBucket->m_triggerBucket[triggerTypes].size());
for (int triggerIndex = 0; triggerIndex < numTriggers; triggerIndex++)
{
//Nullptr check first
if (m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex] == nullptr)
{
continue;
}
eSimulationType simType = m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->GetSimulationType();
switch (simType)
{
case TYPE_UNKOWN:
break;
case STATIC_SIMULATION:
{
if (m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->m_collider->m_inCollision)
{
m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->DebugRender(renderContext, Rgba::WHITE);
}
else
{
m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->DebugRender(renderContext, Rgba::WHITE);
}
}
break;
case DYNAMIC_SIMULATION:
{
if (m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->m_collider->m_inCollision)
{
m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->DebugRender(renderContext, Rgba::WHITE);
}
else
{
m_triggerBucket->m_triggerBucket[triggerTypes][triggerIndex]->DebugRender(renderContext, Rgba::WHITE);
}
}
break;
case NUM_SIMULATION_TYPES:
break;
default:
break;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
const Vec2& PhysicsSystem::GetGravity() const
{
return m_gravity;
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::RunStep( float deltaTime )
{
m_frameCount++;
//First move all rigidbodies based on forces on them
MoveAllDynamicObjects(deltaTime);
UpdateAllCollisions();
UpdateTriggers();
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::MoveAllDynamicObjects(float deltaTime)
{
int numObjects = static_cast<int>(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION].size());
for (int objectIndex = 0; objectIndex < numObjects; objectIndex++)
{
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][objectIndex] != nullptr)
{
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][objectIndex]->Move(deltaTime);
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::CheckStaticVsStaticCollisions()
{
int numStaticObjects = static_cast<int>(m_rbBucket->m_RbBucket[STATIC_SIMULATION].size());
//Set colliding or not colliding here
for(int colliderIndex = 0; colliderIndex < numStaticObjects; colliderIndex++)
{
if(m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex]->m_isAlive)
{
continue;
}
for(int otherColliderIndex = 0; otherColliderIndex < numStaticObjects; otherColliderIndex++)
{
//check condition where the other collider is nullptr
if(m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_isAlive)
{
continue;
}
//Make sure we aren't the same rigidbody
if(m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex] == m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex])
{
continue;
}
Collision2D collision;
if(m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex]->m_collider->IsTouching(&collision, m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_collider))
{
//Set collision to true
m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex]->m_collider->SetCollision(true);
m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_collider->SetCollision(true);
//Call required collision events
NamedProperties args;
m_rbBucket->m_RbBucket[STATIC_SIMULATION][colliderIndex]->m_collider->FireCollisionEvent(args);
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::ResolveDynamicVsStaticCollisions(bool canResolve)
{
int numDynamicObjects = static_cast<int>(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION].size());
int numStaticObjects = static_cast<int>(m_rbBucket->m_RbBucket[STATIC_SIMULATION].size());
//Set colliding or not colliding here
for(int colliderIndex = 0; colliderIndex < numDynamicObjects; colliderIndex++)
{
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_isAlive)
{
continue;
}
for(int otherColliderIndex = 0; otherColliderIndex < numStaticObjects; otherColliderIndex++)
{
//check condition where the other collider is nullptr
if(m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_isAlive)
{
continue;
}
Collision2D collision;
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_collider->IsTouching(&collision, m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_collider))
{
//Set collision to true
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_collider->SetCollision(true);
m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_collider->SetCollision(true);
//Call the collision event
NamedProperties args;
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_collider->FireCollisionEvent(args);
m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex]->m_collider->FireCollisionEvent(args);
//Push the object out based on the collision manifold
if(collision.m_manifold.m_normal != Vec2::ZERO)
{
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_transform.m_position += collision.m_manifold.m_normal * collision.m_manifold.m_penetration;
}
if(canResolve)
{
Rigidbody2D* rb0 = m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex];
Rigidbody2D* rb1 = m_rbBucket->m_RbBucket[STATIC_SIMULATION][otherColliderIndex];
Vec2 velocity0 = rb0->m_velocity;
Vec2 velocity1 = rb1->m_velocity;
float mass0 = rb0->m_mass;
Manifold2D manifold = collision.m_manifold;
Vec2 contactPoint = manifold.m_contact + manifold.m_normal * (manifold.m_penetration);
//Get the vector from the object centre to the point of contact for both objects
Vec2 rb0toContact = contactPoint - rb0->m_object_transform->m_position;
Vec2 rb1toContact = contactPoint - rb1->m_object_transform->m_position;
//Get the perpendicular of the vector from center to point
Vec2 toPointPerpendicular0 = rb0toContact.GetRotated90Degrees();
Vec2 toPointPerpendicular1 = rb1toContact.GetRotated90Degrees();
//Get the velocity at the impact point for both objects
Vec2 velocityAtPoint0 = velocity0 + DegreesToRadians(rb0->m_angularVelocity) * toPointPerpendicular0;
Vec2 velocityAtPoint1 = velocity1 + DegreesToRadians(rb1->m_angularVelocity) * toPointPerpendicular1;
//Coefficient of restitution
float CoefficientOfRestitution = (collision.m_Obj->m_rigidbody->m_material.restitution) * (collision.m_otherObj->m_rigidbody->m_material.restitution);
//Generate Impulse along the normal
float j = -(1 + CoefficientOfRestitution) * GetDotProduct((velocityAtPoint0 - velocityAtPoint1), manifold.m_normal);
float constant0 = ( GetDotProduct(toPointPerpendicular0, manifold.m_normal) * GetDotProduct(toPointPerpendicular0, manifold.m_normal) / rb0->m_momentOfInertia ) ;
float d = (1 / mass0) + (constant0);
float impulseAlongNormal = j / d;
rb0->ApplyImpulseAt( impulseAlongNormal * collision.m_manifold.m_normal, contactPoint );
//Get updated velocity
velocity0 = rb0->m_velocity;
velocity1 = rb1->m_velocity;
//Get the velocity at the impact point for both objects
velocityAtPoint0 = velocity0 + DegreesToRadians(rb0->m_angularVelocity) * toPointPerpendicular0;
velocityAtPoint1 = velocity1 + DegreesToRadians(rb1->m_angularVelocity) * toPointPerpendicular1;
//Generate the impuse along the tangent
Vec2 tangent = manifold.m_normal.GetRotated90Degrees();
float jT = -(1 + CoefficientOfRestitution) * GetDotProduct((velocityAtPoint0 - velocityAtPoint1), tangent);
float constant0T = (GetDotProduct(toPointPerpendicular0, tangent) * GetDotProduct(toPointPerpendicular0, tangent) / rb0->m_momentOfInertia);
float dT = (1 / mass0) + (constant0T);
float impulseAlongTangent = jT / dT;
//Coulumb's law
float frictionCoefficient = sqrt(abs(rb0->m_friction * rb1->m_friction));
impulseAlongTangent = Clamp(impulseAlongTangent, -impulseAlongNormal, impulseAlongNormal);
impulseAlongTangent *= frictionCoefficient;
rb0->ApplyImpulseAt(impulseAlongTangent * tangent, contactPoint);
}
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
void PhysicsSystem::ResolveDynamicVsDynamicCollisions(bool canResolve)
{
int numDynamicObjects = static_cast<int>(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION].size());
//Set colliding or not colliding here
for(int colliderIndex = 0; colliderIndex < numDynamicObjects; colliderIndex++)
{
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_isAlive)
{
continue;
}
for(int otherColliderIndex = colliderIndex + 1; otherColliderIndex < numDynamicObjects; otherColliderIndex++)
{
//check condition where the other collider is nullptr
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex] == nullptr)
{
continue;
}
if (!m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->m_isAlive)
{
continue;
}
Collision2D collision;
if(m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_collider->IsTouching(&collision, m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->m_collider))
{
//Set collision to true
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_collider->SetCollision(true);
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->m_collider->SetCollision(true);
//Push the object out based on the collision manifold
if(collision.m_manifold.m_normal != Vec2::ZERO)
{
float mass0 = m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_mass;
float mass1 = m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->m_mass;
float totalMass = mass0 + mass1;
//Correction on system mass
float correct0 = mass1 / totalMass; // move myself along the correction normal
float correct1 = 1 - correct0; // move opposite along the normal
Vec2 move0 = collision.m_manifold.m_normal * collision.m_manifold.m_penetration * correct0;
Vec2 move1 = (collision.m_manifold.m_normal * -1) * collision.m_manifold.m_penetration * correct1;
//m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->m_transform.m_position += collision.m_manifold.m_normal * collision.m_manifold.m_penetration * correct0;
//m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->m_transform.m_position += (collision.m_manifold.m_normal * -1) * collision.m_manifold.m_penetration * correct1;
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex]->MoveBy(move0);
m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex]->MoveBy(move1);
}
if(canResolve)
{
//resolve
Rigidbody2D* rb0 = m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][colliderIndex];
Rigidbody2D* rb1 = m_rbBucket->m_RbBucket[DYNAMIC_SIMULATION][otherColliderIndex];
//Vec2 *contactPoint = new Vec2();
//float impulseAlongNormal = GetImpulseAlongNormal(contactPoint, collision, *rb0, *rb1);
Vec2 velocity0 = rb0->m_velocity;
Vec2 velocity1 = rb1->m_velocity;
float mass0 = rb0->m_mass;
float mass1 = rb1->m_mass;
float totalMass = mass0 + mass1;
//Correction on system mass
float correct0 = mass1 / totalMass; // move myself along the correction normal
//float correct1 = 1 - correct0; // move opposite along the normal
Manifold2D manifold = collision.m_manifold;
Vec2 contactPoint = manifold.m_contact + manifold.m_normal * (manifold.m_penetration * correct0);
//Get the vector from the object centre to the point of contact for both objects
Vec2 rb0toContact = contactPoint - rb0->m_object_transform->m_position;
Vec2 rb1toContact = contactPoint - rb1->m_object_transform->m_position;
//Get the perpendicular of the vector from center to point
Vec2 toPointPerpendicular0 = rb0toContact.GetRotated90Degrees();
Vec2 toPointPerpendicular1 = rb1toContact.GetRotated90Degrees();
//Get the velocity at the impact point for both objects
Vec2 velocityAtPoint0 = velocity0 + DegreesToRadians(rb0->m_angularVelocity) * toPointPerpendicular0;
Vec2 velocityAtPoint1 = velocity1 + DegreesToRadians(rb1->m_angularVelocity) * toPointPerpendicular1;
//Coefficient of restitution
float CoefficientOfRestitution = (collision.m_Obj->m_rigidbody->m_material.restitution) * (collision.m_otherObj->m_rigidbody->m_material.restitution);
//Impulse along the normal
float j = -(1 + CoefficientOfRestitution) * GetDotProduct((velocityAtPoint0 - velocityAtPoint1), manifold.m_normal);
float constant0 = (GetDotProduct(toPointPerpendicular0, manifold.m_normal) * GetDotProduct(toPointPerpendicular0, manifold.m_normal) / rb0->m_momentOfInertia);
float constant1 = (GetDotProduct(toPointPerpendicular1, manifold.m_normal) * GetDotProduct(toPointPerpendicular1, manifold.m_normal) / rb1->m_momentOfInertia);
float d = ((mass0 + mass1) / (mass0 * mass1)) + constant0 + constant1;
float impulseAlongNormal = j / d;
rb0->ApplyImpulseAt(impulseAlongNormal * collision.m_manifold.m_normal, contactPoint);
rb1->ApplyImpulseAt(-1.f * (impulseAlongNormal * collision.m_manifold.m_normal), contactPoint);
// Get updated velocities
velocity0 = rb0->m_velocity;
velocity1 = rb1->m_velocity;
//Get the velocity at the impact point for both objects
velocityAtPoint0 = velocity0 + DegreesToRadians(rb0->m_angularVelocity) * toPointPerpendicular0;
velocityAtPoint1 = velocity1 + DegreesToRadians(rb1->m_angularVelocity) * toPointPerpendicular1;
//Impulse along the tangent
Vec2 tangent = manifold.m_normal.GetRotated90Degrees();
float jT = -(1 + CoefficientOfRestitution) * GetDotProduct((velocityAtPoint0 - velocityAtPoint1), tangent);
float constant0T = (GetDotProduct(toPointPerpendicular0, tangent) * GetDotProduct(toPointPerpendicular0, tangent) / rb0->m_momentOfInertia);
float constant1T = (GetDotProduct(toPointPerpendicular1, tangent) * GetDotProduct(toPointPerpendicular1, tangent) / rb1->m_momentOfInertia);
float dT = ((mass0 + mass1) / (mass0 * mass1)) + constant0T + constant1T;
float impulseAlongTangent = jT / dT;
//Coulumb's law
float frictionCoefficient = sqrt(abs(rb0->m_friction * rb1->m_friction));
impulseAlongTangent = Clamp(impulseAlongTangent, -impulseAlongNormal, impulseAlongNormal);
impulseAlongTangent *= frictionCoefficient;
rb0->ApplyImpulseAt( impulseAlongTangent * tangent, contactPoint );
rb1->ApplyImpulseAt( -1.f * (impulseAlongTangent * tangent), contactPoint );
}
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------------
float PhysicsSystem::GetImpulseAlongNormal(Vec2 *out, const Collision2D& collision, const Rigidbody2D& rb0, const Rigidbody2D& rb1)
{
Vec2 velocity0 = rb0.m_velocity;
Vec2 velocity1 = rb1.m_velocity;
float mass0 = rb0.m_mass;
float mass1 = rb1.m_mass;
float totalMass = mass0 + mass1;
//Correction on system mass
float correct0 = mass1 / totalMass; // move myself along the correction normal
//float correct1 = 1 - correct0; // move opposite along the normal
Manifold2D manifold = collision.m_manifold;
Vec2 contactPoint = manifold.m_contact + manifold.m_normal * (manifold.m_penetration * correct0);
//Make sure we save the contact point to return it
*out = contactPoint;
//Get the vector from the object centre to the point of contact for both objects
Vec2 rb0toContact = contactPoint - rb0.m_object_transform->m_position;
Vec2 rb1toContact = contactPoint - rb1.m_object_transform->m_position;
//Get the perpendicular of the vector from center to point
Vec2 toPointPerpendicular0 = rb0toContact.GetRotated90Degrees();
Vec2 toPointPerpendicular1 = rb1toContact.GetRotated90Degrees();
//Generate the impulse along normal
//Get the velocity at the impact point for both objects
Vec2 velocityAtPoint0 = velocity0 + DegreesToRadians(rb0.m_angularVelocity) * toPointPerpendicular0;
Vec2 velocityAtPoint1 = velocity1 + DegreesToRadians(rb1.m_angularVelocity) * toPointPerpendicular1;
//Coefficient of restitution
float CoefficientOfRestitution = (collision.m_Obj->m_rigidbody->m_material.restitution) * (collision.m_otherObj->m_rigidbody->m_material.restitution);
float j = -(1 + CoefficientOfRestitution) * GetDotProduct((velocityAtPoint0 - velocityAtPoint1), manifold.m_normal);
float constant0 = ( GetDotProduct(toPointPerpendicular0, manifold.m_normal) * GetDotProduct(toPointPerpendicular0, manifold.m_normal) / rb0.m_momentOfInertia ) ;
float constant1 = ( GetDotProduct(toPointPerpendicular1, manifold.m_normal) * GetDotProduct(toPointPerpendicular1, manifold.m_normal) / rb1.m_momentOfInertia );
float d = ((mass0 + mass1) / (mass0 * mass1)) + constant0 + constant1;
float impulseAlongNormal = j / d;
return impulseAlongNormal;
} | 38.976879 | 182 | 0.65542 | [
"object",
"vector"
] |
edfef3b5fb169940b2e0cf386fbf6c4924eab9e1 | 126,474 | cc | C++ | chrome/browser/download/download_browsertest.cc | SlimKatLegacy/android_external_chromium_org | ee480ef5039d7c561fc66ccf52169ead186f1bea | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-04T02:36:53.000Z | 2016-06-25T11:22:17.000Z | chrome/browser/download/download_browsertest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/download/download_browsertest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2015-02-09T08:49:30.000Z | 2017-08-26T02:03:34.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sstream>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/test/test_file_util.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/common/cancelable_request.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_crx_util.h"
#include "chrome/browser/download/download_history.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_request_limiter.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/download/download_target_determiner.h"
#include "chrome/browser/download/download_test_file_activity_observer.h"
#include "chrome/browser/extensions/extension_install_prompt.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/history/download_row.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/net/url_request_mock_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_save_info.h"
#include "content/public/browser/download_url_parameters.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/context_menu_params.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/test_file_error_injector.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/test/net/url_request_mock_http_job.h"
#include "content/test/net/url_request_slow_download_job.h"
#include "extensions/common/feature_switch.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserContext;
using content::BrowserThread;
using content::DownloadItem;
using content::DownloadManager;
using content::DownloadUrlParameters;
using content::URLRequestMockHTTPJob;
using content::URLRequestSlowDownloadJob;
using content::WebContents;
using extensions::Extension;
using extensions::FeatureSwitch;
namespace {
class CreatedObserver : public content::DownloadManager::Observer {
public:
explicit CreatedObserver(content::DownloadManager* manager)
: manager_(manager),
waiting_(false) {
manager->AddObserver(this);
}
virtual ~CreatedObserver() {
if (manager_)
manager_->RemoveObserver(this);
}
void Wait() {
std::vector<DownloadItem*> downloads;
manager_->GetAllDownloads(&downloads);
if (!downloads.empty())
return;
waiting_ = true;
content::RunMessageLoop();
waiting_ = false;
}
private:
virtual void OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) OVERRIDE {
DCHECK_EQ(manager_, manager);
if (waiting_)
base::MessageLoopForUI::current()->Quit();
}
content::DownloadManager* manager_;
bool waiting_;
DISALLOW_COPY_AND_ASSIGN(CreatedObserver);
};
class PercentWaiter : public content::DownloadItem::Observer {
public:
explicit PercentWaiter(DownloadItem* item)
: item_(item),
waiting_(false),
error_(false),
prev_percent_(0) {
item_->AddObserver(this);
}
virtual ~PercentWaiter() {
if (item_)
item_->RemoveObserver(this);
}
bool WaitForFinished() {
if (item_->GetState() == DownloadItem::COMPLETE) {
return item_->PercentComplete() == 100;
}
waiting_ = true;
content::RunMessageLoop();
waiting_ = false;
return !error_;
}
private:
virtual void OnDownloadUpdated(content::DownloadItem* item) OVERRIDE {
DCHECK_EQ(item_, item);
if (!error_ &&
((prev_percent_ > item_->PercentComplete()) ||
(item_->GetState() == DownloadItem::COMPLETE &&
(item_->PercentComplete() != 100)))) {
error_ = true;
if (waiting_)
base::MessageLoopForUI::current()->Quit();
}
if (item_->GetState() == DownloadItem::COMPLETE && waiting_)
base::MessageLoopForUI::current()->Quit();
}
virtual void OnDownloadDestroyed(content::DownloadItem* item) OVERRIDE {
DCHECK_EQ(item_, item);
item_->RemoveObserver(this);
item_ = NULL;
}
content::DownloadItem* item_;
bool waiting_;
bool error_;
int prev_percent_;
DISALLOW_COPY_AND_ASSIGN(PercentWaiter);
};
// DownloadTestObserver subclass that observes one download until it transitions
// from a non-resumable state to a resumable state a specified number of
// times. Note that this observer can only observe a single download.
class DownloadTestObserverResumable : public content::DownloadTestObserver {
public:
// Construct a new observer. |transition_count| is the number of times the
// download should transition from a non-resumable state to a resumable state.
DownloadTestObserverResumable(DownloadManager* download_manager,
size_t transition_count)
: DownloadTestObserver(download_manager, 1,
ON_DANGEROUS_DOWNLOAD_FAIL),
was_previously_resumable_(false),
transitions_left_(transition_count) {
Init();
}
virtual ~DownloadTestObserverResumable() {}
private:
virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE {
bool is_resumable_now = download->CanResume();
if (!was_previously_resumable_ && is_resumable_now)
--transitions_left_;
was_previously_resumable_ = is_resumable_now;
return transitions_left_ == 0;
}
bool was_previously_resumable_;
size_t transitions_left_;
DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable);
};
// DownloadTestObserver subclass that observes a download until it transitions
// from IN_PROGRESS to another state, but only after StartObserving() is called.
class DownloadTestObserverNotInProgress : public content::DownloadTestObserver {
public:
DownloadTestObserverNotInProgress(DownloadManager* download_manager,
size_t count)
: DownloadTestObserver(download_manager, count,
ON_DANGEROUS_DOWNLOAD_FAIL),
started_observing_(false) {
Init();
}
virtual ~DownloadTestObserverNotInProgress() {}
void StartObserving() {
started_observing_ = true;
}
private:
virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE {
return started_observing_ &&
download->GetState() != DownloadItem::IN_PROGRESS;
}
bool started_observing_;
};
// IDs and paths of CRX files used in tests.
const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
const base::FilePath kLargeThemePath(
FILE_PATH_LITERAL("extensions/theme2.crx"));
// Get History Information.
class DownloadsHistoryDataCollector {
public:
explicit DownloadsHistoryDataCollector(Profile* profile)
: profile_(profile), result_valid_(false) {}
bool WaitForDownloadInfo(
scoped_ptr<std::vector<history::DownloadRow> >* results) {
HistoryService* hs = HistoryServiceFactory::GetForProfile(
profile_, Profile::EXPLICIT_ACCESS);
DCHECK(hs);
hs->QueryDownloads(
base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete,
base::Unretained(this)));
content::RunMessageLoop();
if (result_valid_) {
*results = results_.Pass();
}
return result_valid_;
}
private:
void OnQueryDownloadsComplete(
scoped_ptr<std::vector<history::DownloadRow> > entries) {
result_valid_ = true;
results_ = entries.Pass();
base::MessageLoopForUI::current()->Quit();
}
Profile* profile_;
scoped_ptr<std::vector<history::DownloadRow> > results_;
bool result_valid_;
CancelableRequestConsumer callback_consumer_;
DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
};
// Mock that simulates a permissions dialog where the user denies
// permission to install. TODO(skerner): This could be shared with
// extensions tests. Find a common place for this class.
class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt {
public:
MockAbortExtensionInstallPrompt() :
ExtensionInstallPrompt(NULL) {
}
// Simulate a user abort on an extension installation.
virtual void ConfirmInstall(
Delegate* delegate,
const Extension* extension,
const ShowDialogCallback& show_dialog_callback) OVERRIDE {
delegate->InstallUIAbort(true);
base::MessageLoopForUI::current()->Quit();
}
virtual void OnInstallSuccess(const Extension* extension,
SkBitmap* icon) OVERRIDE {
}
virtual void OnInstallFailure(
const extensions::CrxInstallerError& error) OVERRIDE {
}
};
// Mock that simulates a permissions dialog where the user allows
// installation.
class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt {
public:
explicit MockAutoConfirmExtensionInstallPrompt(
content::WebContents* web_contents)
: ExtensionInstallPrompt(web_contents) {}
// Proceed without confirmation prompt.
virtual void ConfirmInstall(
Delegate* delegate,
const Extension* extension,
const ShowDialogCallback& show_dialog_callback) OVERRIDE {
delegate->InstallUIProceed();
}
virtual void OnInstallSuccess(const Extension* extension,
SkBitmap* icon) OVERRIDE {
}
virtual void OnInstallFailure(
const extensions::CrxInstallerError& error) OVERRIDE {
}
};
static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
return BrowserContext::GetDownloadManager(browser->profile());
}
class TestRenderViewContextMenu : public RenderViewContextMenu {
public:
TestRenderViewContextMenu(WebContents* web_contents,
const content::ContextMenuParams& params)
: RenderViewContextMenu(web_contents, params) {
}
virtual ~TestRenderViewContextMenu() {}
private:
virtual void PlatformInit() OVERRIDE {}
virtual void PlatformCancel() OVERRIDE {}
virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) OVERRIDE {
return false;
}
DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);
};
bool WasAutoOpened(DownloadItem* item) {
return item->GetAutoOpened();
}
// Called when a download starts. Marks the download as hidden.
void SetHiddenDownloadCallback(DownloadItem* item, net::Error error) {
DownloadItemModel(item).SetShouldShowInShelf(false);
}
// Callback for HistoryObserver; used in DownloadHistoryCheck
bool HasDataAndName(const history::DownloadRow& row) {
return row.received_bytes > 0 && !row.target_path.empty();
}
} // namespace
class HistoryObserver : public DownloadHistory::Observer {
public:
typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback;
explicit HistoryObserver(Profile* profile)
: profile_(profile),
waiting_(false),
seen_stored_(false) {
DownloadServiceFactory::GetForBrowserContext(profile_)->
GetDownloadHistory()->AddObserver(this);
}
virtual ~HistoryObserver() {
DownloadService* service = DownloadServiceFactory::GetForBrowserContext(
profile_);
if (service && service->GetDownloadHistory())
service->GetDownloadHistory()->RemoveObserver(this);
}
void SetFilterCallback(const FilterCallback& callback) {
callback_ = callback;
}
virtual void OnDownloadStored(
content::DownloadItem* item,
const history::DownloadRow& info) OVERRIDE {
if (!callback_.is_null() && (!callback_.Run(info)))
return;
seen_stored_ = true;
if (waiting_)
base::MessageLoopForUI::current()->Quit();
}
virtual void OnDownloadHistoryDestroyed() OVERRIDE {
DownloadServiceFactory::GetForBrowserContext(profile_)->
GetDownloadHistory()->RemoveObserver(this);
}
void WaitForStored() {
if (seen_stored_)
return;
waiting_ = true;
content::RunMessageLoop();
waiting_ = false;
}
private:
Profile* profile_;
bool waiting_;
bool seen_stored_;
FilterCallback callback_;
DISALLOW_COPY_AND_ASSIGN(HistoryObserver);
};
class DownloadTest : public InProcessBrowserTest {
public:
// Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
enum DownloadMethod {
DOWNLOAD_NAVIGATE,
DOWNLOAD_DIRECT
};
// Information passed in to |DownloadFileCheckErrors()|.
struct DownloadInfo {
const char* url_name; // URL for the download.
DownloadMethod download_method; // Navigation or Direct.
// Download interrupt reason (NONE is OK).
content::DownloadInterruptReason reason;
bool show_download_item; // True if the download item appears on the shelf.
bool should_redirect_to_documents; // True if we save it in "My Documents".
};
struct FileErrorInjectInfo {
DownloadInfo download_info;
content::TestFileErrorInjector::FileErrorInfo error_info;
};
DownloadTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
ASSERT_TRUE(InitialSetup());
}
virtual void CleanUpOnMainThread() OVERRIDE {
// Needs to be torn down on the main thread. file_activity_observer_ holds a
// reference to the ChromeDownloadManagerDelegate which should be destroyed
// on the UI thread.
file_activity_observer_.reset();
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
command_line->AppendSwitch(switches::kDisablePluginsDiscovery);
}
// Returning false indicates a failure of the setup, and should be asserted
// in the caller.
virtual bool InitialSetup() {
bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
EXPECT_TRUE(have_test_dir);
if (!have_test_dir)
return false;
// Sanity check default values for window / tab count and shelf visibility.
int window_count = chrome::GetTotalBrowserCount();
EXPECT_EQ(1, window_count);
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Set up the temporary download folder.
bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
EXPECT_TRUE(created_downloads_dir);
if (!created_downloads_dir)
return false;
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kPromptForDownload, false);
DownloadManager* manager = DownloadManagerForBrowser(browser());
DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
manager->RemoveAllDownloads();
file_activity_observer_.reset(
new DownloadTestFileActivityObserver(browser()->profile()));
return true;
}
protected:
enum SizeTestType {
SIZE_TEST_TYPE_KNOWN,
SIZE_TEST_TYPE_UNKNOWN,
};
base::FilePath GetDownloadsDirectory() {
return downloads_directory_.path();
}
// Location of the file source (the place from which it is downloaded).
base::FilePath OriginFile(base::FilePath file) {
return test_dir_.Append(file);
}
// Location of the file destination (place to which it is downloaded).
base::FilePath DestinationFile(Browser* browser, base::FilePath file) {
return GetDownloadDirectory(browser).Append(file.BaseName());
}
// Must be called after browser creation. Creates a temporary
// directory for downloads that is auto-deleted on destruction.
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CreateAndSetDownloadsDirectory(Browser* browser) {
if (!browser)
return false;
if (!downloads_directory_.CreateUniqueTempDir())
return false;
browser->profile()->GetPrefs()->SetFilePath(
prefs::kDownloadDefaultDirectory,
downloads_directory_.path());
browser->profile()->GetPrefs()->SetFilePath(
prefs::kSaveFileDefaultDirectory,
downloads_directory_.path());
return true;
}
DownloadPrefs* GetDownloadPrefs(Browser* browser) {
return DownloadPrefs::FromDownloadManager(
DownloadManagerForBrowser(browser));
}
base::FilePath GetDownloadDirectory(Browser* browser) {
return GetDownloadPrefs(browser)->DownloadPath();
}
// Create a DownloadTestObserverTerminal that will wait for the
// specified number of downloads to finish.
content::DownloadTestObserver* CreateWaiter(
Browser* browser, int num_downloads) {
DownloadManager* download_manager = DownloadManagerForBrowser(browser);
return new content::DownloadTestObserverTerminal(
download_manager, num_downloads,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
}
// Create a DownloadTestObserverInProgress that will wait for the
// specified number of downloads to start.
content::DownloadTestObserver* CreateInProgressWaiter(
Browser* browser, int num_downloads) {
DownloadManager* download_manager = DownloadManagerForBrowser(browser);
return new content::DownloadTestObserverInProgress(
download_manager, num_downloads);
}
// Create a DownloadTestObserverTerminal that will wait for the
// specified number of downloads to finish, or for
// a dangerous download warning to be shown.
content::DownloadTestObserver* DangerousDownloadWaiter(
Browser* browser,
int num_downloads,
content::DownloadTestObserver::DangerousDownloadAction
dangerous_download_action) {
DownloadManager* download_manager = DownloadManagerForBrowser(browser);
return new content::DownloadTestObserverTerminal(
download_manager, num_downloads,
dangerous_download_action);
}
void CheckDownloadStatesForBrowser(Browser* browser,
size_t num,
DownloadItem::DownloadState state) {
std::vector<DownloadItem*> download_items;
GetDownloads(browser, &download_items);
EXPECT_EQ(num, download_items.size());
for (size_t i = 0; i < download_items.size(); ++i) {
EXPECT_EQ(state, download_items[i]->GetState()) << " Item " << i;
}
}
void CheckDownloadStates(size_t num, DownloadItem::DownloadState state) {
CheckDownloadStatesForBrowser(browser(), num, state);
}
// Download |url|, then wait for the download to finish.
// |disposition| indicates where the navigation occurs (current tab, new
// foreground tab, etc).
// |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
// values in the ui_test_utils::BrowserTestWaitFlags enum.
void DownloadAndWaitWithDisposition(Browser* browser,
const GURL& url,
WindowOpenDisposition disposition,
int browser_test_flags) {
// Setup notification, navigate, and block.
scoped_ptr<content::DownloadTestObserver> observer(
CreateWaiter(browser, 1));
// This call will block until the condition specified by
// |browser_test_flags|, but will not wait for the download to finish.
ui_test_utils::NavigateToURLWithDisposition(browser,
url,
disposition,
browser_test_flags);
// Waits for the download to complete.
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
// We don't expect a file chooser to be shown.
EXPECT_FALSE(DidShowFileChooser());
}
// Download a file in the current tab, then wait for the download to finish.
void DownloadAndWait(Browser* browser,
const GURL& url) {
DownloadAndWaitWithDisposition(
browser,
url,
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
}
// Should only be called when the download is known to have finished
// (in error or not).
// Returning false indicates a failure of the function, and should be asserted
// in the caller.
bool CheckDownload(Browser* browser,
const base::FilePath& downloaded_filename,
const base::FilePath& origin_filename) {
// Find the path to which the data will be downloaded.
base::FilePath downloaded_file(
DestinationFile(browser, downloaded_filename));
// Find the origin path (from which the data comes).
base::FilePath origin_file(OriginFile(origin_filename));
return CheckDownloadFullPaths(browser, downloaded_file, origin_file);
}
// A version of CheckDownload that allows complete path specification.
bool CheckDownloadFullPaths(Browser* browser,
const base::FilePath& downloaded_file,
const base::FilePath& origin_file) {
bool origin_file_exists = base::PathExists(origin_file);
EXPECT_TRUE(origin_file_exists) << origin_file.value();
if (!origin_file_exists)
return false;
// Confirm the downloaded data file exists.
bool downloaded_file_exists = base::PathExists(downloaded_file);
EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value();
if (!downloaded_file_exists)
return false;
int64 origin_file_size = 0;
EXPECT_TRUE(base::GetFileSize(origin_file, &origin_file_size));
std::string original_file_contents;
EXPECT_TRUE(base::ReadFileToString(origin_file, &original_file_contents));
EXPECT_TRUE(
VerifyFile(downloaded_file, original_file_contents, origin_file_size));
// Delete the downloaded copy of the file.
bool downloaded_file_deleted =
file_util::DieFileDie(downloaded_file, false);
EXPECT_TRUE(downloaded_file_deleted);
return downloaded_file_deleted;
}
content::DownloadTestObserver* CreateInProgressDownloadObserver(
size_t download_count) {
DownloadManager* manager = DownloadManagerForBrowser(browser());
return new content::DownloadTestObserverInProgress(
manager, download_count);
}
DownloadItem* CreateSlowTestDownload() {
scoped_ptr<content::DownloadTestObserver> observer(
CreateInProgressDownloadObserver(1));
GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
DownloadManager* manager = DownloadManagerForBrowser(browser());
EXPECT_EQ(0, manager->NonMaliciousInProgressCount());
EXPECT_EQ(0, manager->InProgressCount());
if (manager->InProgressCount() != 0)
return NULL;
ui_test_utils::NavigateToURLWithDisposition(
browser(), slow_download_url, CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
DownloadManager::DownloadVector items;
manager->GetAllDownloads(&items);
DownloadItem* new_item = NULL;
for (DownloadManager::DownloadVector::iterator iter = items.begin();
iter != items.end(); ++iter) {
if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
// There should be only one IN_PROGRESS item.
EXPECT_EQ(NULL, new_item);
new_item = *iter;
}
}
return new_item;
}
bool RunSizeTest(Browser* browser,
SizeTestType type,
const std::string& partial_indication,
const std::string& total_indication) {
EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
return false;
GURL url(type == SIZE_TEST_TYPE_KNOWN ?
URLRequestSlowDownloadJob::kKnownSizeUrl :
URLRequestSlowDownloadJob::kUnknownSizeUrl);
// TODO(ahendrickson) -- |expected_title_in_progress| and
// |expected_title_finished| need to be checked.
base::FilePath filename;
net::FileURLToFilePath(url, &filename);
base::string16 expected_title_in_progress(
ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
base::string16 expected_title_finished(
ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
// Download a partial web page in a background tab and wait.
// The mock system will not complete until it gets a special URL.
scoped_ptr<content::DownloadTestObserver> observer(
CreateWaiter(browser, 1));
ui_test_utils::NavigateToURL(browser, url);
// TODO(ahendrickson): check download status text before downloading.
// Need to:
// - Add a member function to the |DownloadShelf| interface class, that
// indicates how many members it has.
// - Add a member function to |DownloadShelf| to get the status text
// of a given member (for example, via the name in |DownloadItemView|'s
// GetAccessibleState() member function), by index.
// - Iterate over browser->window()->GetDownloadShelf()'s members
// to see if any match the status text we want. Start with the last one.
// Allow the request to finish. We do this by loading a second URL in a
// separate tab.
GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
ui_test_utils::NavigateToURLWithDisposition(
browser,
finish_url,
NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE);
EXPECT_EQ(2, browser->tab_strip_model()->count());
// TODO(ahendrickson): check download status text after downloading.
base::FilePath basefilename(filename.BaseName());
net::FileURLToFilePath(url, &filename);
base::FilePath download_path =
downloads_directory_.path().Append(basefilename);
EXPECT_TRUE(browser->window()->IsDownloadShelfVisible());
bool downloaded_path_exists = base::PathExists(download_path);
EXPECT_TRUE(downloaded_path_exists);
if (!downloaded_path_exists)
return false;
// Check the file contents.
size_t file_size = URLRequestSlowDownloadJob::kFirstDownloadSize +
URLRequestSlowDownloadJob::kSecondDownloadSize;
std::string expected_contents(file_size, '*');
EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size));
// Delete the file we just downloaded.
EXPECT_TRUE(file_util::DieFileDie(download_path, true));
EXPECT_FALSE(base::PathExists(download_path));
return true;
}
void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
DCHECK(downloads);
DownloadManager* manager = DownloadManagerForBrowser(browser);
manager->GetAllDownloads(downloads);
}
static void ExpectWindowCountAfterDownload(size_t expected) {
EXPECT_EQ(expected, chrome::GetTotalBrowserCount());
}
void EnableFileChooser(bool enable) {
file_activity_observer_->EnableFileChooser(enable);
}
bool DidShowFileChooser() {
return file_activity_observer_->TestAndResetDidShowFileChooser();
}
// Checks that |path| is has |file_size| bytes, and matches the |value|
// string.
bool VerifyFile(const base::FilePath& path,
const std::string& value,
const int64 file_size) {
std::string file_contents;
bool read = base::ReadFileToString(path, &file_contents);
EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
if (!read)
return false; // Couldn't read the file.
// Note: we don't handle really large files (more than size_t can hold)
// so we will fail in that case.
size_t expected_size = static_cast<size_t>(file_size);
// Check the size.
EXPECT_EQ(expected_size, file_contents.size());
if (expected_size != file_contents.size())
return false;
// Check the contents.
EXPECT_EQ(value, file_contents);
if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
return false;
return true;
}
// Attempts to download a file, based on information in |download_info|.
// If a Select File dialog opens, will automatically choose the default.
void DownloadFilesCheckErrorsSetup() {
ASSERT_TRUE(test_server()->Start());
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
EnableFileChooser(true);
}
void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info,
size_t i) {
std::stringstream s;
s << " " << __FUNCTION__ << "()"
<< " index = " << i
<< " url = '" << download_info.url_name << "'"
<< " method = "
<< ((download_info.download_method == DOWNLOAD_DIRECT) ?
"DOWNLOAD_DIRECT" : "DOWNLOAD_NAVIGATE")
<< " show_item = " << download_info.show_download_item
<< " reason = "
<< InterruptReasonDebugString(download_info.reason);
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
size_t downloads_expected = download_items.size();
std::string server_path = "files/downloads/";
server_path += download_info.url_name;
GURL url = test_server()->GetURL(server_path);
ASSERT_TRUE(url.is_valid()) << s.str();
DownloadManager* download_manager = DownloadManagerForBrowser(browser());
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents) << s.str();
scoped_ptr<content::DownloadTestObserver> observer(
new content::DownloadTestObserverTerminal(
download_manager,
1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
if (download_info.download_method == DOWNLOAD_DIRECT) {
// Go directly to download. Don't wait for navigation.
scoped_refptr<content::DownloadTestItemCreationObserver>
creation_observer(new content::DownloadTestItemCreationObserver);
scoped_ptr<DownloadUrlParameters> params(
DownloadUrlParameters::FromWebContents(web_contents, url));
params->set_callback(creation_observer->callback());
DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
// Wait until the item is created, or we have determined that it
// won't be.
creation_observer->WaitForDownloadItemCreation();
EXPECT_EQ(download_info.show_download_item,
creation_observer->succeeded());
if (download_info.show_download_item) {
EXPECT_EQ(net::OK, creation_observer->error());
EXPECT_NE(content::DownloadItem::kInvalidId,
creation_observer->download_id());
} else {
EXPECT_NE(net::OK, creation_observer->error());
EXPECT_EQ(content::DownloadItem::kInvalidId,
creation_observer->download_id());
}
} else {
// Navigate to URL normally, wait until done.
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
url,
1);
}
if (download_info.show_download_item) {
downloads_expected++;
observer->WaitForFinished();
DownloadItem::DownloadState final_state =
(download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ?
DownloadItem::COMPLETE :
DownloadItem::INTERRUPTED;
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state));
}
// Wait till the |DownloadFile|s are destroyed.
content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
// Validate that the correct files were downloaded.
download_items.clear();
GetDownloads(browser(), &download_items);
ASSERT_EQ(downloads_expected, download_items.size()) << s.str();
if (download_info.show_download_item) {
// Find the last download item.
DownloadItem* item = download_items[0];
for (size_t d = 1; d < downloads_expected; ++d) {
if (download_items[d]->GetStartTime() > item->GetStartTime())
item = download_items[d];
}
ASSERT_EQ(url, item->GetOriginalUrl()) << s.str();
ASSERT_EQ(download_info.reason, item->GetLastReason()) << s.str();
if (item->GetState() == content::DownloadItem::COMPLETE) {
// Clean up the file, in case it ended up in the My Documents folder.
base::FilePath destination_folder = GetDownloadDirectory(browser());
base::FilePath my_downloaded_file = item->GetTargetFilePath();
EXPECT_TRUE(base::PathExists(my_downloaded_file));
EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false));
EXPECT_EQ(download_info.should_redirect_to_documents ?
std::string::npos :
0u,
my_downloaded_file.value().find(destination_folder.value()));
if (download_info.should_redirect_to_documents) {
// If it's not where we asked it to be, it should be in the
// My Documents folder.
base::FilePath my_docs_folder;
EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS,
&my_docs_folder));
EXPECT_EQ(0u,
my_downloaded_file.value().find(my_docs_folder.value()));
}
}
}
}
// Attempts to download a set of files, based on information in the
// |download_info| array. |count| is the number of files.
// If a Select File dialog appears, it will choose the default and return
// immediately.
void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) {
DownloadFilesCheckErrorsSetup();
for (size_t i = 0; i < count; ++i) {
DownloadFilesCheckErrorsLoopBody(download_info[i], i);
}
}
void DownloadInsertFilesErrorCheckErrorsLoopBody(
scoped_refptr<content::TestFileErrorInjector> injector,
const FileErrorInjectInfo& info,
size_t i) {
std::stringstream s;
s << " " << __FUNCTION__ << "()"
<< " index = " << i
<< " url = " << info.error_info.url
<< " operation code = " <<
content::TestFileErrorInjector::DebugString(
info.error_info.code)
<< " instance = " << info.error_info.operation_instance
<< " error = " << content::InterruptReasonDebugString(
info.error_info.error);
injector->ClearErrors();
injector->AddError(info.error_info);
injector->InjectErrors();
DownloadFilesCheckErrorsLoopBody(info.download_info, i);
size_t expected_successes = info.download_info.show_download_item ? 1u : 0u;
EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str();
EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str();
if (info.download_info.show_download_item)
EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str();
}
void DownloadInsertFilesErrorCheckErrors(size_t count,
FileErrorInjectInfo* info) {
DownloadFilesCheckErrorsSetup();
// Set up file failures.
scoped_refptr<content::TestFileErrorInjector> injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
for (size_t i = 0; i < count; ++i) {
// Set up the full URL, for download file tracking.
std::string server_path = "files/downloads/";
server_path += info[i].download_info.url_name;
GURL url = test_server()->GetURL(server_path);
info[i].error_info.url = url.spec();
DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
}
}
// Attempts to download a file to a read-only folder, based on information
// in |download_info|.
void DownloadFilesToReadonlyFolder(size_t count,
DownloadInfo* download_info) {
DownloadFilesCheckErrorsSetup();
// Make the test folder unwritable.
base::FilePath destination_folder = GetDownloadDirectory(browser());
DVLOG(1) << " " << __FUNCTION__ << "()"
<< " folder = '" << destination_folder.value() << "'";
file_util::PermissionRestorer permission_restorer(destination_folder);
EXPECT_TRUE(file_util::MakeFileUnwritable(destination_folder));
for (size_t i = 0; i < count; ++i) {
DownloadFilesCheckErrorsLoopBody(download_info[i], i);
}
}
// A mock install prompt that simulates the user allowing an install request.
void SetAllowMockInstallPrompt() {
download_crx_util::SetMockInstallPromptForTesting(
scoped_ptr<ExtensionInstallPrompt>(
new MockAutoConfirmExtensionInstallPrompt(
browser()->tab_strip_model()->GetActiveWebContents())));
}
// This method:
// * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
// mock URL.
// * Injects |error| on the first write using |error_injector|.
// * Waits for the download to be interrupted.
// * Clears the errors on |error_injector|.
// * Returns the resulting interrupted download.
DownloadItem* StartMockDownloadAndInjectError(
content::TestFileErrorInjector* error_injector,
content::DownloadInterruptReason error) {
base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib"));
GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path);
content::TestFileErrorInjector::FileErrorInfo error_info;
error_info.url = url.spec();
error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
error_info.operation_instance = 0;
error_info.error = error;
error_injector->ClearErrors();
error_injector->AddError(error_info);
error_injector->InjectErrors();
scoped_ptr<content::DownloadTestObserver> observer(
new DownloadTestObserverResumable(
DownloadManagerForBrowser(browser()), 1));
ui_test_utils::NavigateToURL(browser(), url);
observer->WaitForFinished();
content::DownloadManager::DownloadVector downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
EXPECT_EQ(1u, downloads.size());
if (downloads.size() != 1)
return NULL;
error_injector->ClearErrors();
error_injector->InjectErrors();
DownloadItem* download = downloads[0];
EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
EXPECT_EQ(error, download->GetLastReason());
return download;
}
private:
static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
if (URLRequestSlowDownloadJob::NumberOutstandingRequests())
*result = false;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure());
}
// Location of the test data.
base::FilePath test_dir_;
// Location of the downloads directory for these tests
base::ScopedTempDir downloads_directory_;
scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_;
};
// NOTES:
//
// Files for these tests are found in DIR_TEST_DATA (currently
// "chrome\test\data\", see chrome_paths.cc).
// Mock responses have extension .mock-http-headers appended to the file name.
// Download a file due to the associated MIME type.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url);
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
}
#if defined(OS_WIN)
// Download a file and confirm that the zone identifier (on windows)
// is set to internet.
IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url);
// Check state. Special file state must be checked before CheckDownload,
// as CheckDownload will delete the output file.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
base::FilePath downloaded_file(DestinationFile(browser(), file));
if (file_util::VolumeSupportsADS(downloaded_file))
EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file));
CheckDownload(browser(), file, file);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
}
#endif
// Put up a Select File dialog when the file is downloaded, due to
// downloads preferences settings.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) {
// Re-enable prompting.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kPromptForDownload, true);
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
EnableFileChooser(true);
// Download the file and wait. We expect the Select File dialog to appear
// due to the MIME type, but we still wait until the download completes.
scoped_ptr<content::DownloadTestObserver> observer(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()),
1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
EXPECT_TRUE(DidShowFileChooser());
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
}
// Access a file with a viewable mime-type, verify that a download
// did not initiate.
IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
base::FilePath file(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
base::FilePath file_path(DestinationFile(browser(), file));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Check that we did not download the web page.
EXPECT_FALSE(base::PathExists(file_path));
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) {
ASSERT_TRUE(test_server()->Start());
// These files should all be displayed in the browser.
const char* mime_types[] = {
// It is unclear whether to display text/css or download it.
// Firefox 3: Display
// Internet Explorer 7: Download
// Safari 3.2: Download
// We choose to match Firefox due to the lot of complains
// from the users if css files are downloaded:
// http://code.google.com/p/chromium/issues/detail?id=7192
"text/css",
"text/javascript",
"text/plain",
"application/x-javascript",
"text/html",
"text/xml",
"text/xsl",
"application/xhtml+xml",
"image/png",
"image/gif",
"image/jpeg",
"image/bmp",
};
for (size_t i = 0; i < arraysize(mime_types); ++i) {
const char* mime_type = mime_types[i];
std::string path("contenttype?");
GURL url(test_server()->GetURL(path + mime_type));
ui_test_utils::NavigateToURL(browser(), url);
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
}
// Verify that when the DownloadResourceThrottle cancels a download, the
// download never makes it to the downloads system.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) {
// Navigate to a page with the same domain as the file to download. We can't
// navigate directly to the file we don't want to download because cross-site
// navigations reset the TabDownloadState.
base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html"));
GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path));
ui_test_utils::NavigateToURL(browser(), same_site_url);
// Make sure the initial navigation didn't trigger a download.
std::vector<content::DownloadItem*> items;
DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
EXPECT_EQ(0u, items.size());
// Disable downloads for the tab.
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
DownloadRequestLimiter::TabDownloadState* tab_download_state =
g_browser_process->download_request_limiter()->GetDownloadState(
web_contents, web_contents, true);
ASSERT_TRUE(tab_download_state);
tab_download_state->set_download_status(
DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED);
// Try to start the download via Javascript and wait for the corresponding
// load stop event.
content::TestNavigationObserver observer(web_contents);
bool download_assempted;
ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
browser()->tab_strip_model()->GetActiveWebContents(),
"window.domAutomationController.send(startDownload());",
&download_assempted));
ASSERT_TRUE(download_assempted);
observer.Wait();
// Check that we did not download the file.
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
base::FilePath file_path(DestinationFile(browser(), file));
EXPECT_FALSE(base::PathExists(file_path));
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Verify that there's no pending download. The resource throttle
// should have deleted it before it created a download item, so it
// shouldn't be available as a cancelled download either.
DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
EXPECT_EQ(0u, items.size());
}
// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header. This also ensures we properly handle empty file downloads.
// The download shelf should be visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
base::FilePath download_file(
FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
}
// Test that the download shelf is per-window by starting a download in one
// tab, opening a second tab, closing the shelf, going back to the first tab,
// and checking that the shelf is closed.
IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
base::FilePath download_file(
FILE_PATH_LITERAL("download-test3-attachment.gif"));
// Download a file and wait.
DownloadAndWait(browser(), url);
CheckDownload(browser(), download_file, file);
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
// Open a second tab and wait.
EXPECT_NE(static_cast<WebContents*>(NULL),
chrome::AddSelectedTabWithURL(browser(), GURL(),
content::PAGE_TRANSITION_TYPED));
EXPECT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
// Hide the download shelf.
browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Go to the first tab.
browser()->tab_strip_model()->ActivateTabAt(0, true);
EXPECT_EQ(2, browser()->tab_strip_model()->count());
// The download shelf should not be visible.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
// Check whether the downloads shelf is closed when the downloads tab is
// invoked.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseShelfOnDownloadsTab) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the file and wait. We do not expect the Select File dialog.
DownloadAndWait(browser(), url);
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
// Open the downloads tab.
chrome::ShowDownloads(browser());
// The shelf should now be closed.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish". At that time, the download will finish.
// These tests don't currently test much due to holes in |RunSizeTest()|. See
// comments in that routine for details.
IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
"32.0 KB - ", "100% - "));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
"71% - ", "100% - "));
}
// Test that when downloading an item in Incognito mode, we don't crash when
// closing the last Incognito window (http://crbug.com/13983).
// Also check that the download shelf is not visible after closing the
// Incognito window.
IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
Browser* incognito = CreateIncognitoBrowser();
ASSERT_TRUE(incognito);
int window_count = chrome::GetTotalBrowserCount();
EXPECT_EQ(2, window_count);
// Download a file in the Incognito window and wait.
CreateAndSetDownloadsDirectory(incognito);
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Since |incognito| is a separate browser, we have to set it up explicitly.
incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
false);
DownloadAndWait(incognito, url);
// We should still have 2 windows.
ExpectWindowCountAfterDownload(2);
// Verify that the download shelf is showing for the Incognito window.
EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_BROWSER_CLOSED,
content::Source<Browser>(incognito));
#endif
// Close the Incognito window and don't crash.
chrome::CloseWindow(incognito);
#if !defined(OS_MACOSX)
signal.Wait();
ExpectWindowCountAfterDownload(1);
#endif
// Verify that the regular window does not have a download shelf.
// On ChromeOS, the download panel is common to both profiles, so
// it is still visible.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
CheckDownload(browser(), file, file);
}
// Download one file on-record, then download the same file off-record, and test
// that the filename is deduplicated. The previous test tests for a specific
// bug; this next test tests that filename deduplication happens independently
// of DownloadManager/CDMD.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) {
ASSERT_TRUE(test_server()->Start());
GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
// Read the origin file now so that we can compare the downloaded files to it
// later.
base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
"downloads/a_zip_file.zip"))));
ASSERT_TRUE(base::PathExists(origin));
int64 origin_file_size = 0;
EXPECT_TRUE(base::GetFileSize(origin, &origin_file_size));
std::string original_contents;
EXPECT_TRUE(base::ReadFileToString(origin, &original_contents));
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
// Download a file in the on-record browser and check that it was downloaded
// correctly.
DownloadAndWaitWithDisposition(browser(),
url,
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NONE);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
GetDownloads(browser(), &download_items);
ASSERT_EQ(1UL, download_items.size());
ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
download_items[0]->GetTargetFilePath().BaseName());
ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
original_contents, origin_file_size));
// Setup an incognito window.
Browser* incognito = CreateIncognitoBrowser();
ASSERT_TRUE(incognito);
int window_count = BrowserList::GetInstance(
browser()->host_desktop_type())->size();
EXPECT_EQ(2, window_count);
incognito->profile()->GetPrefs()->SetFilePath(
prefs::kDownloadDefaultDirectory,
GetDownloadsDirectory());
incognito->profile()->GetPrefs()->SetFilePath(
prefs::kSaveFileDefaultDirectory,
GetDownloadsDirectory());
download_items.clear();
GetDownloads(incognito, &download_items);
ASSERT_TRUE(download_items.empty());
// Download a file in the incognito browser and check that it was downloaded
// correctly.
DownloadAndWaitWithDisposition(incognito,
url,
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NONE);
EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
GetDownloads(incognito, &download_items);
ASSERT_EQ(1UL, download_items.size());
ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
download_items[0]->GetTargetFilePath().BaseName());
ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
original_contents, origin_file_size));
}
// Navigate to a new background page, but don't download. Confirm that the
// download shelf is not visible and that we have two tabs.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
// Because it's an HTML link, it should open a web page rather than
// downloading.
base::FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// We should have two tabs now.
EXPECT_EQ(2, browser()->tab_strip_model()->count());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
// Download a file in a background tab. Verify that the tab is closed
// automatically, and that the download shelf is visible in the current tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
// Download a file in a new background tab and wait. The tab is automatically
// closed when the download begins.
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(
browser(),
url,
NEW_BACKGROUND_TAB,
0);
// When the download finishes, we should still have one tab.
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file in another tab via
// a Javascript call.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page1.html page contains an openNew() function that opens a
// tab and then downloads download-test1.lib.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
// Because it's an HTML link, it should open a web page rather than
// downloading.
base::FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait (via Javascript).
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should have two tabs.
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
EXPECT_EQ(2, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, open another tab via a Javascript call,
// then download a file in the new tab.
// Verify that we have 2 tabs, and the download shelf is visible in the current
// tab.
//
// The download_page2.html page contains an openNew() function that opens a
// tab.
IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
// Because it's an HTML link, it should open a web page rather than
// downloading.
base::FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url1);
// Open a new tab and wait.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
EXPECT_EQ(2, browser()->tab_strip_model()->count());
// Download a file and wait.
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadAndWaitWithDisposition(browser(),
url,
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, we should have two tabs.
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
EXPECT_EQ(2, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then download a file via Javascript,
// which will do so in a temporary tab.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page3.html page contains an openNew() function that opens a
// tab with download-test1.lib in the URL. When the URL is determined to be
// a download, the tab is closed automatically.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
// Because it's an HTML link, it should open a web page rather than
// downloading.
base::FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file and wait.
// The file to download is "download-test1.lib".
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(browser(),
GURL("javascript:openNew()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
}
// Open a web page in the current tab, then call Javascript via a button to
// download a file in a new tab, which is closed automatically when the
// download begins.
// Verify that we have 1 tab, and the download shelf is visible.
//
// The download_page4.html page contains a form with download-test1.lib as the
// action.
IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
// Because it's an HTML link, it should open a web page rather than
// downloading.
base::FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
// Open a web page and wait.
ui_test_utils::NavigateToURL(browser(), url);
// Download a file in a new tab and wait. The tab will automatically close
// when the download begins.
// The file to download is "download-test1.lib".
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
DownloadAndWaitWithDisposition(
browser(),
GURL("javascript:document.getElementById('form').submit()"),
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
// When the download finishes, we should still have one tab.
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
}
// Download a file in a new window.
// Verify that we have 2 windows, and the download shelf is not visible in the
// first window, but is visible in the second window.
// Close the new window.
// Verify that we have 1 window, and the download shelf is not visible.
//
// Regression test for http://crbug.com/44454
IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
#if !defined(OS_MACOSX)
// See below.
Browser* first_browser = browser();
#endif
// Download a file in a new window and wait.
DownloadAndWaitWithDisposition(browser(),
url,
NEW_WINDOW,
ui_test_utils::BROWSER_TEST_NONE);
// When the download finishes, the download shelf SHOULD NOT be visible in
// the first window.
ExpectWindowCountAfterDownload(2);
EXPECT_EQ(1, browser()->tab_strip_model()->count());
// Download shelf should close. Download panel stays open on ChromeOS.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// The download shelf SHOULD be visible in the second window.
std::set<Browser*> original_browsers;
original_browsers.insert(browser());
Browser* download_browser =
ui_test_utils::GetBrowserNotInSet(original_browsers);
ASSERT_TRUE(download_browser != NULL);
EXPECT_NE(download_browser, browser());
EXPECT_EQ(1, download_browser->tab_strip_model()->count());
EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
#if !defined(OS_MACOSX)
// On Mac OS X, the UI window close is delayed until the outermost
// message loop runs. So it isn't possible to get a BROWSER_CLOSED
// notification inside of a test.
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_BROWSER_CLOSED,
content::Source<Browser>(download_browser));
#endif
// Close the new window.
chrome::CloseWindow(download_browser);
#if !defined(OS_MACOSX)
signal.Wait();
EXPECT_EQ(first_browser, browser());
ExpectWindowCountAfterDownload(1);
#endif
EXPECT_EQ(1, browser()->tab_strip_model()->count());
// Download shelf should close. Download panel stays open on ChromeOS.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
CheckDownload(browser(), file, file);
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
GURL download_url(URLRequestSlowDownloadJob::kKnownSizeUrl);
base::FilePath file(net::GenerateFileName(download_url,
std::string(),
std::string(),
std::string(),
std::string(),
std::string()));
// We use the server so that we can get a redirect and test url_chain
// persistence.
ASSERT_TRUE(test_server()->Start());
GURL redirect_url = test_server()->GetURL(
"server-redirect?" + download_url.spec());
// Download the url and wait until the object has been stored.
base::Time start(base::Time::Now());
HistoryObserver observer(browser()->profile());
observer.SetFilterCallback(base::Bind(&HasDataAndName));
ui_test_utils::NavigateToURL(browser(), redirect_url);
observer.WaitForStored();
// Get the details on what was stored into the history.
scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
ASSERT_TRUE(DownloadsHistoryDataCollector(
browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
ASSERT_EQ(1u, downloads_in_database->size());
// Confirm history storage is what you expect for a partially completed
// slow download job.
history::DownloadRow& row(downloads_in_database->at(0));
EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
DestinationFile(browser(), file)),
row.current_path);
ASSERT_EQ(2u, row.url_chain.size());
EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec());
EXPECT_EQ(download_url.spec(), row.url_chain[1].spec());
EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row.danger_type);
EXPECT_LE(start, row.start_time);
EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize, row.received_bytes);
EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
+ URLRequestSlowDownloadJob::kSecondDownloadSize, row.total_bytes);
EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
EXPECT_FALSE(row.opened);
// Finish the download. We're ok relying on the history to be flushed
// at this point as our queries will be behind the history updates
// invoked by completion.
scoped_ptr<content::DownloadTestObserver> download_observer(
CreateWaiter(browser(), 1));
ui_test_utils::NavigateToURL(browser(),
GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl));
download_observer->WaitForFinished();
EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState(
DownloadItem::INTERRUPTED));
base::Time end(base::Time::Now());
// Get what was stored in the history.
ASSERT_TRUE(DownloadsHistoryDataCollector(
browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
ASSERT_EQ(1u, downloads_in_database->size());
// Confirm history storage is what you expect for an interrupted slow download
// job. The download isn't continuable, so there's no intermediate file.
history::DownloadRow& row1(downloads_in_database->at(0));
EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
EXPECT_TRUE(row1.current_path.empty());
ASSERT_EQ(2u, row1.url_chain.size());
EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec());
EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec());
EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row1.danger_type);
EXPECT_LE(start, row1.start_time);
EXPECT_GE(end, row1.end_time);
EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize,
row1.received_bytes);
EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
+ URLRequestSlowDownloadJob::kSecondDownloadSize, row1.total_bytes);
EXPECT_EQ(content::DownloadItem::INTERRUPTED, row1.state);
EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
row1.interrupt_reason);
EXPECT_FALSE(row1.opened);
}
// Make sure a dangerous file shows up properly in the history.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) {
#if defined(OS_WIN) && defined(USE_ASH)
// Disable this test in Metro+Ash for now (http://crbug.com/262796).
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
return;
#endif
// .swf file so that it's dangerous on all platforms (including CrOS).
base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
// Download the url and wait until the object has been stored.
scoped_ptr<content::DownloadTestObserver> download_observer(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE));
base::Time start(base::Time::Now());
HistoryObserver observer(browser()->profile());
observer.SetFilterCallback(base::Bind(&HasDataAndName));
ui_test_utils::NavigateToURL(browser(), download_url);
observer.WaitForStored();
// Get the details on what was stored into the history.
scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
ASSERT_TRUE(DownloadsHistoryDataCollector(
browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
ASSERT_EQ(1u, downloads_in_database->size());
// Confirm history storage is what you expect for an unvalidated
// dangerous file.
history::DownloadRow& row(downloads_in_database->at(0));
EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
DestinationFile(browser(), file)),
row.current_path);
EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, row.danger_type);
EXPECT_LE(start, row.start_time);
EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
EXPECT_FALSE(row.opened);
// Validate the download and wait for it to finish.
std::vector<DownloadItem*> downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
downloads[0]->ValidateDangerousDownload();
download_observer->WaitForFinished();
// Get history details and confirm it's what you expect.
downloads_in_database->clear();
ASSERT_TRUE(DownloadsHistoryDataCollector(
browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
ASSERT_EQ(1u, downloads_in_database->size());
history::DownloadRow& row1(downloads_in_database->at(0));
EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, row1.danger_type);
EXPECT_LE(start, row1.start_time);
EXPECT_EQ(content::DownloadItem::COMPLETE, row1.state);
EXPECT_FALSE(row1.opened);
// Not checking file size--not relevant to the point of the test, and
// the file size is actually different on Windows and other platforms,
// because for source control simplicity it's actually a text file, and
// there are CRLF transformations for those files.
}
IN_PROC_BROWSER_TEST_F(DownloadTest, PRE_DownloadTest_History) {
// Download a file and wait for it to be stored.
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
HistoryObserver observer(browser()->profile());
DownloadAndWait(browser(), download_url);
observer.WaitForStored();
HistoryServiceFactory::GetForProfile(
browser()->profile(), Profile::IMPLICIT_ACCESS)->FlushForTest(
base::Bind(&base::MessageLoop::Quit,
base::Unretained(base::MessageLoop::current()->current())));
content::RunMessageLoop();
}
#if defined(OS_CHROMEOS)
#define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
#else
#define MAYBE_DownloadTest_History DownloadTest_History
#endif
IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_History) {
// This starts up right after PRE_DownloadTest_History and shares the same
// profile directory.
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
std::vector<DownloadItem*> downloads;
content::DownloadManager* manager = DownloadManagerForBrowser(browser());
// Wait for the history to be loaded with a single DownloadItem. Check that
// it's the file that was downloaded in PRE_DownloadTest_History.
CreatedObserver created_observer(manager);
created_observer.Wait();
manager->GetAllDownloads(&downloads);
ASSERT_EQ(1UL, downloads.size());
DownloadItem* item = downloads[0];
EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value());
EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value());
EXPECT_EQ(download_url, item->GetURL());
// The following are set by download-test1.lib.mock-http-headers.
std::string etag = item->GetETag();
TrimWhitespaceASCII(etag, TRIM_ALL, &etag);
EXPECT_EQ("abracadabra", etag);
std::string last_modified = item->GetLastModifiedTime();
TrimWhitespaceASCII(last_modified, TRIM_ALL, &last_modified);
EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified);
}
// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
GURL flags_url(chrome::kChromeUIFlagsURL);
GURL extensions_url(chrome::kChromeUIExtensionsFrameURL);
ui_test_utils::NavigateToURL(browser(), flags_url);
DownloadAndWait(browser(), download_url);
ui_test_utils::NavigateToURL(browser(), extensions_url);
WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
bool webui_responded = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"window.domAutomationController.send(window.webuiResponded);",
&webui_responded));
EXPECT_TRUE(webui_responded);
}
// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) {
GURL downloads_url(chrome::kChromeUIFlagsURL);
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
ui_test_utils::NavigateToURL(browser(), downloads_url);
WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(contents);
bool result = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
contents,
"window.onunload = function() { var do_nothing = 0; }; "
"window.domAutomationController.send(true);",
&result));
EXPECT_TRUE(result);
DownloadAndWait(browser(), download_url);
content::WindowedNotificationObserver signal(
chrome::NOTIFICATION_BROWSER_CLOSED,
content::Source<Browser>(browser()));
chrome::CloseWindow(browser());
signal.Wait();
}
// Test to make sure the 'download' attribute in anchor tag is respected.
IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) {
base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// Create a download, wait until it's complete, and confirm
// we're in the expected state.
scoped_ptr<content::DownloadTestObserver> observer(
CreateWaiter(browser(), 1));
ui_test_utils::NavigateToURL(browser(), url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
// Confirm the downloaded data exists.
base::FilePath downloaded_file = GetDownloadDirectory(browser());
downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png"));
EXPECT_TRUE(base::PathExists(downloaded_file));
}
// Test to make sure auto-open works.
IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
ASSERT_TRUE(
GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
DownloadAndWait(browser(), url);
// Find the download and confirm it was opened.
std::vector<DownloadItem*> downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState());
// Unfortunately, this will block forever, causing a timeout, if
// the download is never opened.
content::DownloadUpdatedObserver(
downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway.
// As long as we're here, confirmed everything else is good.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
CheckDownload(browser(), file, file);
// Download shelf should close. Download panel stays open on ChromeOS.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
// Download an extension. Expect a dangerous download warning.
// Deny the download.
IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) {
FeatureSwitch::ScopedOverride enable_easy_off_store_install(
FeatureSwitch::easy_off_store_install(), true);
GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
ui_test_utils::NavigateToURL(browser(), extension_url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
// Download shelf should close.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Check that the CRX is not installed.
ExtensionService* extension_service = extensions::ExtensionSystem::Get(
browser()->profile())->extension_service();
ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
}
// Download an extension. Expect a dangerous download warning.
// Allow the download, deny the install.
IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) {
FeatureSwitch::ScopedOverride enable_easy_off_store_install(
FeatureSwitch::easy_off_store_install(), true);
GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
// Install a mock install UI that simulates a user denying permission to
// finish the install.
download_crx_util::SetMockInstallPromptForTesting(
scoped_ptr<ExtensionInstallPrompt>(
new MockAbortExtensionInstallPrompt()));
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
ui_test_utils::NavigateToURL(browser(), extension_url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
// Download shelf should close from auto-open.
content::DownloadManager::DownloadVector downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
content::DownloadUpdatedObserver(
downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Check that the extension was not installed.
ExtensionService* extension_service = extensions::ExtensionSystem::Get(
browser()->profile())->extension_service();
ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
}
// Download an extension. Expect a dangerous download warning.
// Allow the download, and the install.
IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) {
FeatureSwitch::ScopedOverride enable_easy_off_store_install(
FeatureSwitch::easy_off_store_install(), true);
GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
// Install a mock install UI that simulates a user allowing permission to
// finish the install.
SetAllowMockInstallPrompt();
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
ui_test_utils::NavigateToURL(browser(), extension_url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
// Download shelf should close from auto-open.
content::DownloadManager::DownloadVector downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
content::DownloadUpdatedObserver(
downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Check that the extension was installed.
ExtensionService* extension_service = extensions::ExtensionSystem::Get(
browser()->profile())->extension_service();
ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false));
}
// Test installing a CRX that fails integrity checks.
IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) {
base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file));
// Install a mock install UI that simulates a user allowing permission to
// finish the install, and dismisses any error message. We check that the
// install failed below.
SetAllowMockInstallPrompt();
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
ui_test_utils::NavigateToURL(browser(), extension_url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
// Check that the extension was not installed.
ExtensionService* extension_service = extensions::ExtensionSystem::Get(
browser()->profile())->extension_service();
ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
}
// Install a large (100kb) theme.
IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) {
FeatureSwitch::ScopedOverride enable_easy_off_store_install(
FeatureSwitch::easy_off_store_install(), true);
GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath));
// Install a mock install UI that simulates a user allowing permission to
// finish the install.
SetAllowMockInstallPrompt();
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
ui_test_utils::NavigateToURL(browser(), extension_url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
// Download shelf should close from auto-open.
content::DownloadManager::DownloadVector downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
content::DownloadUpdatedObserver(
downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
// Check that the extension was installed.
ExtensionService* extension_service = extensions::ExtensionSystem::Get(
browser()->profile())->extension_service();
ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false));
}
// Tests for download initiation functions.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
// DownloadUrl always prompts; return acceptance of whatever it prompts.
EnableFileChooser(true);
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
content::DownloadTestObserver* observer(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
scoped_ptr<DownloadUrlParameters> params(
DownloadUrlParameters::FromWebContents(web_contents, url));
params->set_prompt(true);
DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
EXPECT_TRUE(DidShowFileChooser());
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_TRUE(CheckDownload(browser(), file, file));
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
base::ScopedTempDir other_directory;
ASSERT_TRUE(other_directory.CreateUniqueTempDir());
base::FilePath target_file_full_path
= other_directory.path().Append(file.BaseName());
content::DownloadTestObserver* observer(CreateWaiter(browser(), 1));
scoped_ptr<DownloadUrlParameters> params(
DownloadUrlParameters::FromWebContents(web_contents, url));
params->set_file_path(target_file_full_path);
DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
// Check state.
EXPECT_EQ(1, browser()->tab_strip_model()->count());
ASSERT_TRUE(CheckDownloadFullPaths(browser(),
target_file_full_path,
OriginFile(file)));
// Temporary are treated as auto-opened, and after that open won't be
// visible; wait for auto-open and confirm not visible.
std::vector<DownloadItem*> downloads;
DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
ASSERT_EQ(1u, downloads.size());
content::DownloadUpdatedObserver(
downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) {
// Do initial setup.
ASSERT_TRUE(test_server()->Start());
EnableFileChooser(true);
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
// Navigate to a non-HTML resource. The resource also has
// Cache-Control: no-cache set, which normally requires revalidation
// each time.
GURL url = test_server()->GetURL("files/downloads/image.jpg");
ASSERT_TRUE(url.is_valid());
ui_test_utils::NavigateToURL(browser(), url);
// Stop the test server, and then try to save the page. If cache validation
// is not bypassed then this will fail since the server is no longer
// reachable.
ASSERT_TRUE(test_server()->Stop());
scoped_ptr<content::DownloadTestObserver> waiter(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
chrome::SavePage(browser());
waiter->WaitForFinished();
EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
// Validate that the correct file was downloaded.
GetDownloads(browser(), &download_items);
EXPECT_TRUE(DidShowFileChooser());
ASSERT_EQ(1u, download_items.size());
ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
// Try to download it via a context menu.
scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
content::ContextMenuParams context_menu_params;
context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
context_menu_params.src_url = url;
context_menu_params.page_url = url;
TestRenderViewContextMenu menu(
browser()->tab_strip_model()->GetActiveWebContents(),
context_menu_params);
menu.Init();
menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
waiter_context_menu->WaitForFinished();
EXPECT_EQ(
1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(2, DownloadItem::COMPLETE);
// Validate that the correct file was downloaded via the context menu.
download_items.clear();
GetDownloads(browser(), &download_items);
EXPECT_TRUE(DidShowFileChooser());
ASSERT_EQ(2u, download_items.size());
ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
ASSERT_EQ(url, download_items[1]->GetOriginalUrl());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) {
// Do initial setup.
ASSERT_TRUE(test_server()->Start());
EnableFileChooser(true);
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
// Navigate to a form page.
GURL form_url = test_server()->GetURL(
"files/downloads/form_page_to_post.html");
ASSERT_TRUE(form_url.is_valid());
ui_test_utils::NavigateToURL(browser(), form_url);
// Submit the form. This will send a POST reqeuest, and the response is a
// JPEG image. The resource also has Cache-Control: no-cache set,
// which normally requires revalidation each time.
GURL jpeg_url = test_server()->GetURL("files/post/downloads/image.jpg");
ASSERT_TRUE(jpeg_url.is_valid());
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents != NULL);
content::WindowedNotificationObserver observer(
content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<content::NavigationController>(
&web_contents->GetController()));
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
ASSERT_TRUE(render_view_host != NULL);
render_view_host->ExecuteJavascriptInWebFrame(
base::string16(), ASCIIToUTF16("SubmitForm()"));
observer.Wait();
EXPECT_EQ(jpeg_url, web_contents->GetURL());
// Stop the test server, and then try to save the page. If cache validation
// is not bypassed then this will fail since the server is no longer
// reachable. This will also fail if it tries to be retrieved via "GET"
// rather than "POST".
ASSERT_TRUE(test_server()->Stop());
scoped_ptr<content::DownloadTestObserver> waiter(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
chrome::SavePage(browser());
waiter->WaitForFinished();
EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
// Validate that the correct file was downloaded.
GetDownloads(browser(), &download_items);
EXPECT_TRUE(DidShowFileChooser());
ASSERT_EQ(1u, download_items.size());
ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
// Try to download it via a context menu.
scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
content::ContextMenuParams context_menu_params;
context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
context_menu_params.src_url = jpeg_url;
context_menu_params.page_url = jpeg_url;
TestRenderViewContextMenu menu(web_contents, context_menu_params);
menu.Init();
menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
waiter_context_menu->WaitForFinished();
EXPECT_EQ(
1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(2, DownloadItem::COMPLETE);
// Validate that the correct file was downloaded via the context menu.
download_items.clear();
GetDownloads(browser(), &download_items);
EXPECT_TRUE(DidShowFileChooser());
ASSERT_EQ(2u, download_items.size());
ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) {
DownloadInfo download_info[] = {
{ // Normal navigated download.
"a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_NONE,
true,
false
},
{ // Normal direct download.
"a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_NONE,
true,
false
},
{ // Direct download with 404 error.
"there_IS_no_spoon.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
true,
false
},
{ // Navigated download with 404 error.
"there_IS_no_spoon.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
false,
false
},
{ // Direct download with 400 error.
"zip_file_not_found.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
true,
false
},
{ // Navigated download with 400 error.
"zip_file_not_found.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
false,
false
}
};
DownloadFilesCheckErrors(ARRAYSIZE_UNSAFE(download_info), download_info);
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) {
FileErrorInjectInfo error_info[] = {
{ // Navigated download with injected "Disk full" error in Initialize().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
}
},
{ // Direct download with injected "Disk full" error in Initialize().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
}
},
{ // Navigated download with injected "Disk full" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
}
},
{ // Direct download with injected "Disk full" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
}
},
{ // Navigated download with injected "Failed" error in Initialize().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Direct download with injected "Failed" error in Initialize().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Navigated download with injected "Failed" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Direct download with injected "Failed" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Navigated download with injected "Name too long" error in
// Initialize().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
}
},
{ // Direct download with injected "Name too long" error in Initialize().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
}
},
{ // Navigated download with injected "Name too long" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_NAVIGATE,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Direct download with injected "Name too long" error in Write().
{ "a_zip_file.zip",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
0,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
}
},
{ // Direct download with injected "Disk full" error in 2nd Write().
{ "06bESSE21Evolution.ppt",
DOWNLOAD_DIRECT,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
1
},
{
"",
content::TestFileErrorInjector::FILE_OPERATION_WRITE,
1,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
}
}
};
DownloadInsertFilesErrorCheckErrors(ARRAYSIZE_UNSAFE(error_info), error_info);
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) {
DownloadInfo download_info[] = {
{
"a_zip_file.zip",
DOWNLOAD_DIRECT,
// This passes because we switch to the My Documents folder.
content::DOWNLOAD_INTERRUPT_REASON_NONE,
true,
true
},
{
"a_zip_file.zip",
DOWNLOAD_NAVIGATE,
// This passes because we switch to the My Documents folder.
content::DOWNLOAD_INTERRUPT_REASON_NONE,
true,
true
}
};
DownloadFilesToReadonlyFolder(ARRAYSIZE_UNSAFE(download_info), download_info);
}
// Test that we show a dangerous downloads warning for a dangerous file
// downloaded through a blob: URL.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) {
#if defined(OS_WIN)
// On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
// .msi) will be handled by the DownloadProtectionService. However, if the URL
// is non-standard (e.g. blob:) then those files won't be handled by the
// DPS. We should be showing the dangerous download warning for any file
// considered dangerous and isn't handled by the DPS.
const char kFilename[] = "foo.exe";
#else
const char kFilename[] = "foo.swf";
#endif
std::string path("files/downloads/download-dangerous-blob.html?filename=");
path += kFilename;
// Need to use http urls because the blob js doesn't work on file urls for
// security reasons.
ASSERT_TRUE(test_server()->Start());
GURL url(test_server()->GetURL(path));
content::DownloadTestObserver* observer(DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
ui_test_utils::NavigateToURL(browser(), url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) {
// Do initial setup.
ASSERT_TRUE(test_server()->Start());
EnableFileChooser(true);
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
// Navigate to a page with a referrer policy and a link on it. The link points
// to testserver's /echoheader.
GURL url = test_server()->GetURL("files/downloads/referrer_policy.html");
ASSERT_TRUE(url.is_valid());
ui_test_utils::NavigateToURL(browser(), url);
scoped_ptr<content::DownloadTestObserver> waiter(
new content::DownloadTestObserverTerminal(
DownloadManagerForBrowser(browser()), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
// Click on the link with the alt key pressed. This will download the link
// target.
WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
blink::WebMouseEvent mouse_event;
mouse_event.type = blink::WebInputEvent::MouseDown;
mouse_event.button = blink::WebMouseEvent::ButtonLeft;
mouse_event.x = 15;
mouse_event.y = 15;
mouse_event.clickCount = 1;
mouse_event.modifiers = blink::WebInputEvent::AltKey;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = blink::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
waiter->WaitForFinished();
EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
CheckDownloadStates(1, DownloadItem::COMPLETE);
// Validate that the correct file was downloaded.
GetDownloads(browser(), &download_items);
ASSERT_EQ(1u, download_items.size());
ASSERT_EQ(test_server()->GetURL("echoheader?Referer"),
download_items[0]->GetOriginalUrl());
// Check that the file contains the expected referrer.
base::FilePath file(download_items[0]->GetTargetFilePath());
std::string expected_contents = test_server()->GetURL(std::string()).spec();
ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, HiddenDownload) {
base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
DownloadManager* download_manager = DownloadManagerForBrowser(browser());
scoped_ptr<content::DownloadTestObserver> observer(
new content::DownloadTestObserverTerminal(
download_manager,
1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
// Download and set IsHiddenDownload to true.
WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
scoped_ptr<DownloadUrlParameters> params(
DownloadUrlParameters::FromWebContents(web_contents, url));
params->set_callback(base::Bind(&SetHiddenDownloadCallback));
download_manager->DownloadUrl(params.Pass());
observer->WaitForFinished();
// Verify that download shelf is not shown.
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
// Verify the multiple downloads infobar.
IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) {
#if defined(OS_WIN) && defined(USE_ASH)
// Disable this test in Metro+Ash for now (http://crbug.com/262796).
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
return;
#endif
ASSERT_TRUE(test_server()->Start());
// Create a downloads observer.
scoped_ptr<content::DownloadTestObserver> downloads_observer(
CreateWaiter(browser(), 2));
// Create an infobar observer.
content::WindowedNotificationObserver infobar_added_1(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::NotificationService::AllSources());
ui_test_utils::NavigateToURL(
browser(),
test_server()->GetURL("files/downloads/download-a_zip_file.html"));
infobar_added_1.Wait();
InfoBarService* infobar_service = InfoBarService::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents());
// Verify that there is only one infobar.
ASSERT_EQ(1u, infobar_service->infobar_count());
// Get the infobar at index 0.
InfoBar* infobar = infobar_service->infobar_at(0);
ConfirmInfoBarDelegate* confirm_infobar =
infobar->delegate()->AsConfirmInfoBarDelegate();
ASSERT_TRUE(confirm_infobar != NULL);
// Verify multi download warning infobar message.
EXPECT_EQ(confirm_infobar->GetMessageText(),
l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING));
// Click on the "Allow" button to allow multiple downloads.
if (confirm_infobar->Accept())
infobar_service->RemoveInfoBar(infobar);
// Verify that there are no more infobars.
EXPECT_EQ(0u, infobar_service->infobar_count());
// Waits for the download to complete.
downloads_observer->WaitForFinished();
EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
DownloadItem::COMPLETE));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) {
ASSERT_TRUE(test_server()->Start());
GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
content::DownloadManager* manager = DownloadManagerForBrowser(browser());
base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
"downloads/a_zip_file.zip"))));
ASSERT_TRUE(base::PathExists(origin_file));
std::string origin_contents;
ASSERT_TRUE(base::ReadFileToString(origin_file, &origin_contents));
// Download the same url several times and expect that all downloaded files
// after the zero-th contain a deduplication counter.
for (int index = 0; index < 5; ++index) {
DownloadAndWait(browser(), url);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
content::DownloadItem* item = manager->GetDownload(
content::DownloadItem::kInvalidId + 1 + index);
ASSERT_TRUE(item);
ASSERT_EQ(DownloadItem::COMPLETE, item->GetState());
base::FilePath target_path(item->GetTargetFilePath());
EXPECT_EQ(std::string("a_zip_file") +
(index == 0 ? std::string(".zip") :
base::StringPrintf(" (%d).zip", index)),
target_path.BaseName().AsUTF8Unsafe());
ASSERT_TRUE(base::PathExists(target_path));
ASSERT_TRUE(VerifyFile(target_path, origin_contents,
origin_contents.size()));
}
}
// Test that the entire download pipeline handles unicode correctly.
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_CrazyFilenames) {
const wchar_t* kCrazyFilenames[] = {
L"a_file_name.zip",
L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
L"\u043d\u0435\u0444\u0442\u0438.zip", // russian
L"Desocupa\xe7\xe3o est\xe1vel.zip",
// arabic:
L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
L"\u092d\u093e\u0930\u0924.zip", // hindi
L"d\xe9stabilis\xe9.zip", // french
// korean
L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
L"jiho....tiho...miho.zip",
L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
L"Wohoo-to hoo+I.zip",
L"Picture 1.zip",
L"This is a very very long english sentence with spaces and , and +.zip",
};
std::vector<DownloadItem*> download_items;
static const int kFlags = (base::PLATFORM_FILE_CREATE |
base::PLATFORM_FILE_WRITE);
base::FilePath origin(FILE_PATH_LITERAL("origin"));
ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin)));
for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) {
base::string16 crazy16;
std::string crazy8;
const wchar_t* crazy_w = kCrazyFilenames[index];
ASSERT_TRUE(WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8));
ASSERT_TRUE(WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16));
base::FilePath file_path(DestinationFile(browser(), origin.Append(
#if defined(OS_WIN)
crazy16
#elif defined(OS_POSIX)
crazy8
#endif
)));
// Create the file.
bool created = false;
base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX;
base::PlatformFile fd = base::CreatePlatformFile(
file_path, kFlags, &created, &error);
EXPECT_EQ(static_cast<int>(crazy8.size()),
base::WritePlatformFileAtCurrentPos(
fd, crazy8.c_str(), crazy8.size()));
EXPECT_TRUE(base::ClosePlatformFile(fd));
fd = base::kInvalidPlatformFileValue;
GURL file_url(net::FilePathToFileURL(file_path));
// Download the file and check that the filename is correct.
DownloadAndWait(browser(), file_url);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
GetDownloads(browser(), &download_items);
ASSERT_EQ(1UL, download_items.size());
base::FilePath downloaded(download_items[0]->GetTargetFilePath());
download_items[0]->Remove();
download_items.clear();
ASSERT_TRUE(CheckDownloadFullPaths(
browser(),
downloaded,
file_path));
}
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) {
ASSERT_TRUE(test_server()->Start());
GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_TRUE(download_items.empty());
// Download a file.
DownloadAndWaitWithDisposition(browser(),
url,
CURRENT_TAB,
ui_test_utils::BROWSER_TEST_NONE);
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
GetDownloads(browser(), &download_items);
ASSERT_EQ(1UL, download_items.size());
base::FilePath downloaded(download_items[0]->GetTargetFilePath());
// Remove the DownloadItem but not the file, then check that the file still
// exists.
download_items[0]->Remove();
download_items.clear();
GetDownloads(browser(), &download_items);
ASSERT_EQ(0UL, download_items.size());
ASSERT_TRUE(CheckDownloadFullPaths(
browser(), downloaded, OriginFile(base::FilePath(
FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) {
DownloadItem* download_item = CreateSlowTestDownload();
ASSERT_TRUE(download_item);
ASSERT_FALSE(download_item->GetTargetFilePath().empty());
EXPECT_FALSE(download_item->IsPaused());
EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
download_item->Pause();
EXPECT_TRUE(download_item->IsPaused());
download_item->Resume();
EXPECT_FALSE(download_item->IsPaused());
EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
download_item->Cancel(true);
EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
}
// The Mac downloaded files quarantine feature is implemented by the
// Contents/Info.plist file in cocoa apps. browser_tests cannot test
// quarantining files on Mac because it is not a cocoa app.
// TODO(benjhayden) test the equivalents on other platforms.
#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
// Timing out on ARM linux: http://crbug.com/238459
#define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
#elif defined(OS_MACOSX)
// Disable on mac: http://crbug.com/238831
#define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
#else
#define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
#endif
IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) {
// Write a huge file.
base::FilePath file_path(DestinationFile(
browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
int flags = (base::PLATFORM_FILE_CREATE |
base::PLATFORM_FILE_WRITE);
bool created = false;
base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX;
base::PlatformFile fd = base::CreatePlatformFile(
file_path, flags, &created, &error);
int64 size = 1 << 29;
EXPECT_EQ(size, base::SeekPlatformFile(
fd, base::PLATFORM_FILE_FROM_BEGIN, size));
EXPECT_EQ(1, base::WritePlatformFileAtCurrentPos(fd, "a", 1));
EXPECT_TRUE(base::ClosePlatformFile(fd));
fd = base::kInvalidPlatformFileValue;
#if defined(OS_POSIX)
// Make it readable by chronos on chromeos
base::SetPosixFilePermissions(file_path, 0755);
#endif
// Ensure that we have enough disk space.
int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(
GetDownloadDirectory(browser()));
ASSERT_LE(size, free_space) << "Not enough disk space to download. Got "
<< free_space;
GURL file_url(net::FilePathToFileURL(file_path));
scoped_ptr<content::DownloadTestObserver> progress_waiter(
CreateInProgressWaiter(browser(), 1));
// Start downloading a file, wait for it to be created.
ui_test_utils::NavigateToURLWithDisposition(
browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
progress_waiter->WaitForFinished();
EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState(
DownloadItem::IN_PROGRESS));
std::vector<DownloadItem*> download_items;
GetDownloads(browser(), &download_items);
ASSERT_EQ(1UL, download_items.size());
// Wait for the download to complete, checking along the way that the
// PercentComplete() never regresses.
PercentWaiter waiter(download_items[0]);
EXPECT_TRUE(waiter.WaitForFinished());
EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState());
ASSERT_EQ(100, download_items[0]->PercentComplete());
EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
// Check that the file downloaded correctly.
ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
int64 downloaded_size = 0;
ASSERT_TRUE(base::GetFileSize(
download_items[0]->GetTargetFilePath(), &downloaded_size));
#if defined(OS_WIN)
ASSERT_EQ(1, downloaded_size);
#else
ASSERT_EQ(size + 1, downloaded_size);
#endif
ASSERT_TRUE(file_util::DieFileDie(file_path, false));
ASSERT_TRUE(file_util::DieFileDie(download_items[0]->GetTargetFilePath(),
false));
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_DenyDanger) {
ASSERT_TRUE(test_server()->Start());
GURL url(test_server()->GetURL("files/downloads/dangerous/dangerous.crx"));
scoped_ptr<content::DownloadTestObserver> observer(
DangerousDownloadWaiter(
browser(), 1,
content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
ui_test_utils::NavigateToURL(browser(), url);
observer->WaitForFinished();
EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
}
IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadPrefs_SaveFilePath) {
DownloadPrefs* on_prefs = DownloadServiceFactory::GetForBrowserContext(
browser()->profile())->GetDownloadManagerDelegate()->download_prefs();
DownloadPrefs* off_prefs = DownloadServiceFactory::GetForBrowserContext(
browser()->profile()->GetOffTheRecordProfile())
->GetDownloadManagerDelegate()->download_prefs();
base::FilePath dir(on_prefs->SaveFilePath());
EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
EXPECT_EQ(dir.AppendASCII("on").value(), off_prefs->SaveFilePath().value());
on_prefs->SetSaveFilePath(dir);
EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
off_prefs->SetSaveFilePath(dir.AppendASCII("off"));
EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
}
// A download that is interrupted due to a file error should be able to be
// resumed.
IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDownloadResumption);
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
scoped_ptr<content::DownloadTestObserver> completion_observer(
CreateWaiter(browser(), 1));
EnableFileChooser(true);
DownloadItem* download = StartMockDownloadAndInjectError(
error_injector,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
ASSERT_TRUE(download);
download->Resume();
completion_observer->WaitForFinished();
EXPECT_EQ(
1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
EXPECT_FALSE(DidShowFileChooser());
}
// A download that's interrupted due to a reason that indicates that the target
// path is invalid or unusable should cause a prompt to be displayed on
// resumption.
IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDownloadResumption);
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
scoped_ptr<content::DownloadTestObserver> completion_observer(
CreateWaiter(browser(), 1));
EnableFileChooser(true);
DownloadItem* download = StartMockDownloadAndInjectError(
error_injector,
content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
ASSERT_TRUE(download);
download->Resume();
completion_observer->WaitForFinished();
EXPECT_EQ(
1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
EXPECT_TRUE(DidShowFileChooser());
}
// The user shouldn't be prompted on a resumed download unless a prompt is
// necessary due to the interrupt reason.
IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDownloadResumption);
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kPromptForDownload, true);
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
scoped_ptr<content::DownloadTestObserver> completion_observer(
CreateWaiter(browser(), 1));
EnableFileChooser(true);
DownloadItem* download = StartMockDownloadAndInjectError(
error_injector,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
ASSERT_TRUE(download);
// Prompts the user initially because of the kPromptForDownload preference.
EXPECT_TRUE(DidShowFileChooser());
download->Resume();
completion_observer->WaitForFinished();
EXPECT_EQ(
1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
// Shouldn't prompt for resumption.
EXPECT_FALSE(DidShowFileChooser());
}
// A download that is interrupted due to a transient error should be resumed
// automatically.
IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDownloadResumption);
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
DownloadItem* download = StartMockDownloadAndInjectError(
error_injector,
content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR);
ASSERT_TRUE(download);
// The number of times this the download is resumed automatically is defined
// in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
// created should be that number + 1 (for the original download request). We
// only care that it is greater than 1.
EXPECT_GT(1u, error_injector->TotalFileCount());
}
// An interrupting download should be resumable multiple times.
IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableDownloadResumption);
scoped_refptr<content::TestFileErrorInjector> error_injector(
content::TestFileErrorInjector::Create(
DownloadManagerForBrowser(browser())));
scoped_ptr<DownloadTestObserverNotInProgress> completion_observer(
new DownloadTestObserverNotInProgress(
DownloadManagerForBrowser(browser()), 1));
// Wait for two transitions to a resumable state
scoped_ptr<content::DownloadTestObserver> resumable_observer(
new DownloadTestObserverResumable(
DownloadManagerForBrowser(browser()), 2));
EnableFileChooser(true);
DownloadItem* download = StartMockDownloadAndInjectError(
error_injector,
content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
ASSERT_TRUE(download);
content::TestFileErrorInjector::FileErrorInfo error_info;
error_info.url = download->GetOriginalUrl().spec();
error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
error_info.operation_instance = 0;
error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
error_injector->AddError(error_info);
error_injector->InjectErrors();
// Resuming should cause the download to be interrupted again due to the
// errors we are injecting.
download->Resume();
resumable_observer->WaitForFinished();
ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState());
ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
download->GetLastReason());
error_injector->ClearErrors();
error_injector->InjectErrors();
// No errors this time. The download should complete successfully.
EXPECT_FALSE(completion_observer->IsFinished());
completion_observer->StartObserving();
download->Resume();
completion_observer->WaitForFinished();
EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
EXPECT_FALSE(DidShowFileChooser());
}
| 38.8553 | 80 | 0.721176 | [
"object",
"vector"
] |
61007dc3e2243fbd040e609663f0c71817b5599a | 2,673 | cpp | C++ | HelloWorldTest/chapter_10_06/10_6.cpp | choi2649/C-Study | 790f0fd8b8c13f392183d2194348b50ad66aba7c | [
"MIT"
] | null | null | null | HelloWorldTest/chapter_10_06/10_6.cpp | choi2649/C-Study | 790f0fd8b8c13f392183d2194348b50ad66aba7c | [
"MIT"
] | null | null | null | HelloWorldTest/chapter_10_06/10_6.cpp | choi2649/C-Study | 790f0fd8b8c13f392183d2194348b50ad66aba7c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <array>
#include <cassert>
#include <initializer_list>
using namespace std;
class IntArr
{
private:
int m_length = 0;
int *m_data = nullptr;
int beforeLen = 0;
int *beforeData = nullptr;
public:
void ixCheck(const int & ix) {
assert(ix <= m_length);
assert(ix >= 0);
}
//Constructor
IntArr() {}
IntArr(const int & len)
{
assert(len >= 0);
cout << "Constructor : " << len << endl;
m_length = len;
m_data = new int[m_length];
}
IntArr(const initializer_list<int> & list)
{
m_length = list.size();
//cout << "initializer_list : " << m_length << endl;
m_data = new int[m_length];
int a = 0;
for (auto & ele : list) {
m_data[a] = ele;
a++;
}
}
//Destrurctor
~IntArr() {
delete[] this -> m_data;
}
//initialize()
IntArr & operator = (const initializer_list<int> & list) {
delete[] m_data;
m_length = list.size();
m_data = new int[m_length];
if (m_data != nullptr) {
int a = 0;
for (auto & ele : list) {
m_data[a] = ele;
a++;
}
}
else {
m_data = nullptr;
}
return *this;
}
int getSize() {
return m_length;
}
void copyArr() {
beforeLen = m_length;
beforeData = new int[beforeLen];
for (int i = 0; i < beforeLen; i++) {
beforeData[i] = m_data[i];
}
}
//reset()
void reset() {
m_length = 0;
m_data = nullptr;
}
//resize()
void resize(const int & ix) {
this -> ixCheck(ix);
this -> copyArr();
m_length = ix;
m_data = new int[m_length];
for (int i = 0; i < m_length; i++) {
m_data[i] = beforeData[i];
}
delete[] beforeData;
}
//insertBefore(const int & value, const int & ix);
void insertBefore(const int & value, const int & ix) {
this->ixCheck(ix);
this->m_data[ix] = value;
}
//remover(const int & ix);
void remover(const int & ix) {
this->ixCheck(ix);
this->copyArr();
m_length = beforeLen - 1;
m_data = new int[m_length];
int count = 0;
for (int i = 0; i < beforeLen; i++) {
if (i != ix) {
m_data[count] = beforeData[i];
count++;
}
}
delete[] beforeData;
}
IntArr & push_back(const int &val) {
this->copyArr();
m_length = m_length + 1;
m_data = new int[m_length];
for (int i = 0; i < m_length; i++) {
if (m_length - 1 == i) {
m_data[i] = val;
}
else {
m_data[i] = beforeData[i];
}
}
delete[] beforeData;
return *this;
};
friend ostream & operator << (ostream & out, IntArr &iA) {
for (int i = 0; i < iA.m_length; i++) {
out << iA.m_data[i] << " ";
}
return out;
}
};
int main()
{
IntArr arr{ 1,2,3,4 };
cout << arr << endl;
cout << arr.getSize() << endl;
return 0;
} | 16.10241 | 59 | 0.568275 | [
"vector"
] |
6105eb5901139f26abe50e5bada2c9f8ed2ad7b4 | 13,526 | cc | C++ | src/ui/bin/root_presenter/presentation.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 2 | 2020-08-16T15:32:35.000Z | 2021-11-07T20:09:46.000Z | src/ui/bin/root_presenter/presentation.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | null | null | null | src/ui/bin/root_presenter/presentation.cc | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 1 | 2021-08-15T04:29:11.000Z | 2021-08-15T04:29:11.000Z | // Copyright 2015 The Fuchsia 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 "src/ui/bin/root_presenter/presentation.h"
#include <lib/fostr/fidl/fuchsia/ui/input/formatting.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/trace/event.h>
#include "src/ui/bin/root_presenter/safe_presenter.h"
// clang-format off
#include "src/ui/lib/glm_workaround/glm_workaround.h"
// clang-format on
#include <glm/ext.hpp>
#include <cmath>
#include "src/ui/bin/root_presenter/displays/display_configuration.h"
namespace root_presenter {
namespace {
// TODO(SCN-1276): Don't hardcode Z bounds in multiple locations.
constexpr float kDefaultRootViewDepth = 1000;
// TODO(SCN-1278): Remove this.
// Turn two floats (high bits, low bits) into a 64-bit uint.
trace_flow_id_t PointerTraceHACK(float fa, float fb) {
uint32_t ia, ib;
memcpy(&ia, &fa, sizeof(uint32_t));
memcpy(&ib, &fb, sizeof(uint32_t));
return (((uint64_t)ia) << 32) | ib;
}
} // namespace
Presentation::Presentation(
fuchsia::ui::scenic::Scenic* scenic, scenic::Session* session, scenic::ResourceId compositor_id,
fuchsia::ui::views::ViewHolderToken view_holder_token,
fidl::InterfaceRequest<fuchsia::ui::policy::Presentation> presentation_request,
SafePresenter* safe_presenter, ActivityNotifier* activity_notifier,
int32_t display_startup_rotation_adjustment)
: scenic_(scenic),
session_(session),
compositor_id_(compositor_id),
activity_notifier_(activity_notifier),
layer_(session_),
renderer_(session_),
scene_(session_),
camera_(scene_),
view_holder_node_(session),
root_node_(session_),
view_holder_(session, std::move(view_holder_token), "root_presenter"),
display_startup_rotation_adjustment_(display_startup_rotation_adjustment),
presentation_binding_(this),
a11y_binding_(this),
safe_presenter_(safe_presenter),
weak_factory_(this) {
FX_DCHECK(compositor_id != 0);
FX_DCHECK(safe_presenter_);
renderer_.SetCamera(camera_);
layer_.SetRenderer(renderer_);
scene_.AddChild(root_node_);
root_node_.SetTranslation(0.f, 0.f, -0.1f); // TODO(SCN-371).
root_node_.AddChild(view_holder_node_);
view_holder_node_.Attach(view_holder_);
// Create the root view's scene.
// TODO(SCN-1255): we add a directional light and a point light, expecting
// only one of them to be active at a time. This logic is implicit in
// EngineRenderer, since no shadow-mode supports both directional and point
// lights (either one or the other). When directional light support is added
// to PaperRenderer, the code here will result in over-brightening, and will
// need to be adjusted at that time.
scenic::AmbientLight ambient_light(session_);
scenic::DirectionalLight directional_light(session_);
scenic::PointLight point_light(session_);
scene_.AddLight(ambient_light);
scene_.AddLight(directional_light);
scene_.AddLight(point_light);
directional_light.SetDirection(1.f, 1.f, 2.f);
point_light.SetPosition(300.f, 300.f, -2000.f);
point_light.SetFalloff(0.f);
// Explicitly set "UNSHADOWED" as the default shadow type. In addition to
// setting the param, this sets appropriate light intensities.
{
// When no shadows, ambient light needs to be full brightness. Otherwise,
// ambient needs to be dimmed so that other lights don't "overbrighten".
ambient_light.SetColor(1.f, 1.f, 1.f);
directional_light.SetColor(0.f, 0.f, 0.f);
point_light.SetColor(0.f, 0.f, 0.f);
fuchsia::ui::gfx::RendererParam param;
param.set_shadow_technique(fuchsia::ui::gfx::ShadowTechnique::UNSHADOWED);
renderer_.SetParam(std::move(param));
}
SetScenicDisplayRotation();
// Link ourselves to the presentation interface once screen dimensions are
// available for us to present into.
FX_CHECK(!presentation_binding_.is_bound());
presentation_binding_.Bind(std::move(presentation_request));
scenic_->GetDisplayInfo(
[weak = weak_factory_.GetWeakPtr()](fuchsia::ui::gfx::DisplayInfo display_info) mutable {
if (weak) {
// Get display parameters and propagate values appropriately.
weak->InitializeDisplayModel(std::move(display_info));
weak->safe_presenter_->QueuePresent([] {});
}
});
}
Presentation::~Presentation() = default;
void Presentation::RegisterWithMagnifier(fuchsia::accessibility::Magnifier* magnifier) {
magnifier->RegisterHandler(a11y_binding_.NewBinding());
a11y_binding_.set_error_handler([this](auto) { ResetClipSpaceTransform(); });
}
void Presentation::InitializeDisplayModel(fuchsia::ui::gfx::DisplayInfo display_info) {
FX_DCHECK(!display_model_initialized_);
// Initialize display model.
display_configuration::InitializeModelForDisplay(display_info.width_in_px,
display_info.height_in_px, &display_model_);
display_model_initialized_ = true;
ApplyDisplayModelChanges(true, false);
}
bool Presentation::ApplyDisplayModelChanges(bool print_log, bool present_changes) {
bool updated = ApplyDisplayModelChangesHelper(print_log);
if (updated && present_changes) {
safe_presenter_->QueuePresent([] {});
}
return updated;
}
bool Presentation::ApplyDisplayModelChangesHelper(bool print_log) {
if (!display_model_initialized_)
return false;
DisplayMetrics metrics = display_model_.GetMetrics();
if (print_log) {
display_configuration::LogDisplayMetrics(metrics);
}
if (display_metrics_ == metrics)
return true;
display_metrics_ = metrics;
// Layout size
{
float metrics_width = display_metrics_.width_in_pp();
float metrics_height = display_metrics_.height_in_pp();
// Swap metrics on left/right tilt.
if (abs(display_startup_rotation_adjustment_ % 180) == 90) {
std::swap(metrics_width, metrics_height);
}
view_holder_.SetViewProperties(0.f, 0.f, -kDefaultRootViewDepth, metrics_width, metrics_height,
0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f);
FX_VLOGS(2) << "DisplayModel layout: " << metrics_width << ", " << metrics_height;
}
// Device pixel scale.
{
float metrics_scale_x = display_metrics_.x_scale_in_px_per_pp();
float metrics_scale_y = display_metrics_.y_scale_in_px_per_pp();
// Swap metrics on left/right tilt.
if (abs(display_startup_rotation_adjustment_ % 180) == 90) {
std::swap(metrics_scale_x, metrics_scale_y);
}
scene_.SetScale(metrics_scale_x, metrics_scale_y, 1.f);
FX_VLOGS(2) << "DisplayModel pixel scale: " << metrics_scale_x << ", " << metrics_scale_y;
}
// Anchor
{
float anchor_x = display_metrics_.width_in_pp() / 2;
float anchor_y = display_metrics_.height_in_pp() / 2;
// Swap anchors on left/right tilt.
if (abs(display_startup_rotation_adjustment_ % 180) == 90) {
std::swap(anchor_x, anchor_y);
}
view_holder_node_.SetAnchor(anchor_x, anchor_y, 0);
FX_VLOGS(2) << "DisplayModel anchor: " << anchor_x << ", " << anchor_y;
}
// Rotate
{
glm::quat display_rotation =
glm::quat(glm::vec3(0, 0, glm::radians<float>(display_startup_rotation_adjustment_)));
view_holder_node_.SetRotation(display_rotation.x, display_rotation.y, display_rotation.z,
display_rotation.w);
}
const DisplayModel::DisplayInfo& display_info = display_model_.display_info();
// Center everything.
{
float info_w = display_info.width_in_px;
float info_h = display_info.height_in_px;
float metrics_w = display_metrics_.width_in_px();
float metrics_h = display_metrics_.height_in_px();
float density_w = display_metrics_.x_scale_in_px_per_pp();
float density_h = display_metrics_.y_scale_in_px_per_pp();
// Swap metrics on left/right tilt.
if (abs(display_startup_rotation_adjustment_ % 180) == 90) {
std::swap(metrics_w, metrics_h);
std::swap(density_w, density_h);
}
float left_offset = (info_w - metrics_w) / density_w / 2;
float top_offset = (info_h - metrics_h) / density_h / 2;
view_holder_node_.SetTranslation(left_offset, top_offset, 0.f);
FX_VLOGS(2) << "DisplayModel translation: " << left_offset << ", " << top_offset;
}
// Today, a layer needs the display's physical dimensions to render correctly.
layer_.SetSize(static_cast<float>(display_info.width_in_px),
static_cast<float>(display_info.height_in_px));
return true;
}
void Presentation::OnDeviceAdded(ui_input::InputDeviceImpl* input_device) {
FX_VLOGS(1) << "OnDeviceAdded: device_id=" << input_device->id();
FX_DCHECK(device_states_by_id_.count(input_device->id()) == 0);
std::unique_ptr<ui_input::DeviceState> state;
if (input_device->descriptor()->sensor) {
ui_input::OnSensorEventCallback callback = [this](uint32_t device_id,
fuchsia::ui::input::InputReport event) {
OnSensorEvent(device_id, std::move(event));
};
state = std::make_unique<ui_input::DeviceState>(input_device->id(), input_device->descriptor(),
std::move(callback));
} else {
ui_input::OnEventCallback callback = [this](fuchsia::ui::input::InputEvent event) {
OnEvent(std::move(event));
};
state = std::make_unique<ui_input::DeviceState>(input_device->id(), input_device->descriptor(),
std::move(callback));
}
ui_input::DeviceState* state_ptr = state.get();
auto device_pair = std::make_pair(input_device, std::move(state));
state_ptr->OnRegistered();
device_states_by_id_.emplace(input_device->id(), std::move(device_pair));
}
void Presentation::OnDeviceRemoved(uint32_t device_id) {
FX_VLOGS(1) << "OnDeviceRemoved: device_id=" << device_id;
if (device_states_by_id_.count(device_id) != 0) {
device_states_by_id_[device_id].second->OnUnregistered();
device_states_by_id_.erase(device_id);
}
}
void Presentation::OnReport(uint32_t device_id, fuchsia::ui::input::InputReport input_report) {
// Media buttons should be processed by MediaButtonsHandler.
FX_DCHECK(!input_report.media_buttons);
TRACE_DURATION("input", "presentation_on_report", "id", input_report.trace_id);
TRACE_FLOW_END("input", "report_to_presentation", input_report.trace_id);
FX_VLOGS(2) << "OnReport device=" << device_id
<< ", count=" << device_states_by_id_.count(device_id) << ", report=" << input_report;
if (device_states_by_id_.count(device_id) == 0) {
FX_VLOGS(1) << "OnReport: Unknown device " << device_id;
return;
}
if (!display_model_initialized_)
return;
ui_input::DeviceState* state = device_states_by_id_[device_id].second.get();
fuchsia::math::Size size;
size.width = display_model_.display_info().width_in_px;
size.height = display_model_.display_info().height_in_px;
TRACE_FLOW_BEGIN("input", "report_to_device_state", input_report.trace_id);
state->Update(std::move(input_report), size);
}
void Presentation::SetClipSpaceTransform(float x, float y, float scale,
SetClipSpaceTransformCallback callback) {
camera_.SetClipSpaceTransform(x, y, scale);
// The callback is used to throttle magnification transition animations and is expected to
// approximate the framerate.
safe_presenter_->QueuePresent([callback = std::move(callback)] { callback(); });
}
void Presentation::ResetClipSpaceTransform() {
SetClipSpaceTransform(0, 0, 1, [] {});
}
void Presentation::OnEvent(fuchsia::ui::input::InputEvent event) {
TRACE_DURATION("input", "presentation_on_event");
FX_VLOGS(1) << "OnEvent " << event;
activity_notifier_->ReceiveInputEvent(event);
if (!event.is_pointer()) {
FX_LOGS(ERROR) << "Only pointer input events are handled.";
return;
}
// TODO(SCN-1278): Use proper trace_id for tracing flow.
const trace_flow_id_t trace_id =
PointerTraceHACK(event.pointer().radius_major, event.pointer().radius_minor);
TRACE_FLOW_END("input", "dispatch_event_to_presentation", trace_id);
fuchsia::ui::input::Command input_cmd;
{
fuchsia::ui::input::SendPointerInputCmd pointer_cmd;
pointer_cmd.pointer_event = std::move(event.pointer());
pointer_cmd.compositor_id = compositor_id_;
input_cmd.set_send_pointer_input(std::move(pointer_cmd));
}
TRACE_FLOW_BEGIN("input", "dispatch_event_to_scenic", trace_id);
session_->Enqueue(std::move(input_cmd));
}
void Presentation::OnSensorEvent(uint32_t device_id, fuchsia::ui::input::InputReport event) {
FX_VLOGS(2) << "OnSensorEvent(device_id=" << device_id << "): " << event;
FX_DCHECK(device_states_by_id_.count(device_id) > 0);
FX_DCHECK(device_states_by_id_[device_id].first);
FX_DCHECK(device_states_by_id_[device_id].first->descriptor());
FX_DCHECK(device_states_by_id_[device_id].first->descriptor()->sensor.get());
// No clients of sensor events at the moment.
}
void Presentation::SetScenicDisplayRotation() {
fuchsia::ui::gfx::Command command;
fuchsia::ui::gfx::SetDisplayRotationCmdHACK display_rotation_cmd;
display_rotation_cmd.compositor_id = compositor_id_;
display_rotation_cmd.rotation_degrees = display_startup_rotation_adjustment_;
command.set_set_display_rotation(std::move(display_rotation_cmd));
session_->Enqueue(std::move(command));
}
} // namespace root_presenter
| 37.057534 | 100 | 0.713441 | [
"render",
"model"
] |
6107436f558f735dd75c84bbe06f57e5ce47115e | 5,927 | cpp | C++ | Actor/Characters/Enemy/E5/EnemyE5_Missile.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E5/EnemyE5_Missile.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | Actor/Characters/Enemy/E5/EnemyE5_Missile.cpp | Bornsoul/Revenger_JoyContinue | 599716970ca87a493bf3a959b36de0b330b318f1 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "EnemyE5_Missile.h"
#include "EnemyE5.h"
#include "Actor/SaveData/Cpt_GameSave.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SphereComponent.h"
#include "Libraries/Components/ParticleMng/Cpt_ParticleMng.h"
#include "Kismet/KismetMathLibrary.h"
AEnemyE5_Missile::AEnemyE5_Missile()
{
PrimaryActorTick.bCanEverTick = true;
Tags.Add(FName("EnemyBullet"));
m_pCollider = CreateDefaultSubobject<USphereComponent>(TEXT("Collider"));
m_pCollider->OnComponentBeginOverlap.AddDynamic(this, &AEnemyE5_Missile::OnOverlapBegin);
m_pCollider->SetCollisionProfileName(TEXT("EnemyBullet"));
RootComponent = m_pCollider;
m_pMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
m_pMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);
m_pMesh->SetupAttachment(RootComponent);
m_pParticleMng = CreateDefaultSubobject<UCpt_ParticleMng>(TEXT("ParticleMng"));
m_pParticleMng->AddParticleInstance(TEXT("Explosion"), TEXT("ParticleSystem'/Game/1_Project_Main/2_Contents/Effects/Ex/StandardExplosion/P_Explosion_Small.P_Explosion_Small'"));
m_pParticleMng->AddParticleInstance(TEXT("Trail"), TEXT("ParticleSystem'/Game/0_Assets/MarketPlace/VFXS/VFX_Toolkit_V1/ParticleSystems/356Days/Par_Matra_01b_Trail.Par_Matra_01b_Trail'"));
//m_pSaveData = CreateDefaultSubobject<UCpt_GameSave>(TEXT("SaveData"));
}
void AEnemyE5_Missile::BeginPlay()
{
Super::BeginPlay();
m_bShooted = false;
m_bReflected = false;
m_bReflectWaitTime = false;
m_bChase = false;
}
void AEnemyE5_Missile::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
}
void AEnemyE5_Missile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
m_fLifeTime += DeltaTime;
if (m_fLifeTime > 2.0f)
{
Destroy();
return;
}
if (m_bShooted == true)
{
if (m_bReflected == false)
{
if (m_bChase == false && m_pTarget != nullptr)
{
FVector vDestLoc = m_pTarget->GetActorLocation();
vDestLoc.Z = GetActorLocation().Z;
FRotator vAngleRota = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), vDestLoc);
vAngleRota.Roll = 0.0f;
vAngleRota.Pitch = 0.0f;
FRotator vDestRota = GetActorRotation();
SetActorRotation(vDestRota);
}
}
if (m_bReflectWaitTime == false)
{
FVector vLoc = GetActorLocation();
float fSpeed = m_fMoveSpeed;
if (m_bReflected == true) fSpeed *= 2.0f;
vLoc += GetActorForwardVector() * fSpeed * DeltaTime;
SetActorLocation(vLoc);
}
}
if (m_bReflected == true)
{
if (m_bReflectWaitTime == true)
{
m_fReflectWiatTime_Curr += DeltaTime;
if (m_fReflectWiatTime_Curr >= m_fReflectWiatTime_Ago)
{
m_bReflectWaitTime = false;
}
}
}
}
void AEnemyE5_Missile::Shoot(AActor* pShooter, FVector vLocation, FVector vDestLoc)
{
m_bShooted = true;
m_pShooter = pShooter;
SetActorLocation(vLocation);
vDestLoc.Z = GetActorLocation().Z;
FRotator rView = UKismetMathLibrary::FindLookAtRotation(vLocation, vDestLoc);
SetActorRotation(rView);
}
void AEnemyE5_Missile::ShootToTarget(AActor* pShooter, FVector vLocation, AActor* pTarget)
{
m_bShooted = true;
m_pShooter = pShooter;
m_pTarget = pTarget;
FVector vDestLoc = m_pTarget->GetActorLocation();
SetActorLocation(vLocation);
vDestLoc.Z = GetActorLocation().Z;
FRotator rView = UKismetMathLibrary::FindLookAtRotation(vLocation, vDestLoc);
SetActorRotation(rView);
}
void AEnemyE5_Missile::Reflect(FVector vDestLoc)
{
m_bReflected = true;
m_bReflectWaitTime = true;
FVector vLocation = GetActorLocation();
FRotator rView = UKismetMathLibrary::FindLookAtRotation(vLocation, vDestLoc);
SetActorRotation(rView);
//ULOG(TEXT("Ref"));
}
float AEnemyE5_Missile::TakeDamage(float DamageAmount, struct FDamageEvent const & DamageEvent, class AController * EventInstigator, AActor * DamageCauser)
{
float fDamage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
if (m_bReflected == true) return 0.0f;
AEnemyE5* pActor = Cast<AEnemyE5>(m_pShooter);
if (pActor != nullptr)
{
if (pActor->GetShoot() == false)
{
return 0.0f;
}
FDamageEvent_Hit* pDamageEvent = (FDamageEvent_Hit*)&DamageEvent;
if (pDamageEvent != nullptr)
{
//m_pSaveData->Load_Data()->m_stPlayerData.m_nHitBulletCount += 1;
m_pDamageCauser = DamageCauser;
Reflect(pDamageEvent->m_vHitPoint);
m_fReflectDamage = DamageAmount;
pActor->SetShoot(false);
}
}
return 0.0f;
}
void AEnemyE5_Missile::Explosion()
{
//m_pSaveData->Save_Data("Test01", 0, -1.0f);
m_pParticleMng->SpawnParticleAtLocation(TEXT("Explosion"), GetWorld(), GetActorLocation(), FRotator::ZeroRotator, FVector::OneVector);
Destroy();
}
void AEnemyE5_Missile::OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (OtherActor && (OtherActor != this) && OtherComp)
{
if (OtherActor->ActorHasTag(FName(TEXT("Enemy"))) == true)
{
if (m_bReflected == true)
{
FDamageEvent* DamageEvent = new FDamageEvent_Hit(3, GetActorLocation(), GetActorLocation());
float fResultDamage = OtherActor->TakeDamage(3, *DamageEvent, nullptr, m_pDamageCauser);
Explosion();
}
else
{
return;
}
}
if (OtherActor->ActorHasTag(FName(TEXT("Player"))) == true)
{
if (m_bReflected == true)
{
}
else
{
FDamageEvent* DamageEvent = new FDamageEvent_Hit(3.0f, GetActorLocation(), GetActorLocation());
float fResultDamage = OtherActor->TakeDamage(3.0f, *DamageEvent, nullptr, m_pShooter);
if (fResultDamage != 0.0f)
{
Explosion();
}
}
}
else
{
//m_pSaveData->Load_Data()->m_stPlayerData.m_nNonHitBulletCount += 1;
if (OtherActor->GetName().Left(8) == "BP_Spawn")
{
return;
}
Explosion();
}
}
}
| 26.459821 | 214 | 0.734942 | [
"mesh"
] |
6107fafd3ed142849a6b2994bbfc77e8941c9f83 | 3,724 | cpp | C++ | src/NotesLoader.cpp | shockdude/stepmania_gh | f36a23f3a53187849cc97367d33c783a1083992a | [
"MIT"
] | 3 | 2016-04-09T04:13:17.000Z | 2021-06-17T06:06:02.000Z | src/NotesLoader.cpp | shockdude/stepmania_gh | f36a23f3a53187849cc97367d33c783a1083992a | [
"MIT"
] | null | null | null | src/NotesLoader.cpp | shockdude/stepmania_gh | f36a23f3a53187849cc97367d33c783a1083992a | [
"MIT"
] | 3 | 2017-07-25T17:04:51.000Z | 2021-08-30T05:12:15.000Z | #include "global.h"
#include "NotesLoader.h"
#include <array>
#include "NotesLoaderSM.h"
#include "NotesLoaderSMA.h"
#include "NotesLoaderSSC.h"
#include "NotesLoaderDWI.h"
#include "NotesLoaderBMS.h"
#include "NotesLoaderKSF.h"
#include "NotesLoaderChart.h"
#include "NotesLoaderMID.h"
#include "RageUtil.h"
using std::vector;
using std::string;
void NotesLoader::GetMainAndSubTitlesFromFullTitle( const std::string &sFullTitle, std::string &sMainTitleOut, std::string &sSubTitleOut )
{
std::array<std::string, 5> sLeftSeps =
{
{
"\t", " -", " ~", " (", " ["
}
};
for (auto const &sep: sLeftSeps)
{
size_t iBeginIndex = sFullTitle.find( sep );
if( iBeginIndex == string::npos )
continue;
sMainTitleOut = Rage::head(sFullTitle, iBeginIndex);
sSubTitleOut = sFullTitle.substr( iBeginIndex+1, sFullTitle.size()-iBeginIndex+1 );
return;
}
sMainTitleOut = sFullTitle;
sSubTitleOut = "";
};
bool NotesLoader::LoadFromDir( const std::string &sPath, Song &out, std::set<std::string> &BlacklistedImages, bool load_autosave )
{
vector<std::string> list;
BlacklistedImages.clear();
SSCLoader loaderSSC;
loaderSSC.GetApplicableFiles( sPath, list, load_autosave );
if( !list.empty() )
{
if( !loaderSSC.LoadFromDir( sPath, out, load_autosave ) )
{
return false;
}
return true;
}
SMALoader loaderSMA;
loaderSMA.GetApplicableFiles( sPath, list );
if (!list.empty() )
{
return loaderSMA.LoadFromDir( sPath, out );
}
SMLoader loaderSM;
loaderSM.GetApplicableFiles( sPath, list );
if (!list.empty() )
{
return loaderSM.LoadFromDir( sPath, out );
}
DWILoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
{
return DWILoader::LoadFromDir( sPath, out, BlacklistedImages );
}
BMSLoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
return BMSLoader::LoadFromDir( sPath, out );
/*
PMSLoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
{
return PMSLoader::LoadFromDir( sPath, out );
}
*/
KSFLoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
{
return KSFLoader::LoadFromDir( sPath, out );
}
MIDILoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
return MIDILoader::LoadFromDir( sPath, out );
CHARTLoader::GetApplicableFiles( sPath, list );
if( !list.empty() )
return CHARTLoader::LoadFromDir( sPath, out );
return false;
}
/*
* (c) 2001-2004,2007 Chris Danford, Glenn Maynard, Steve Checkoway
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 30.52459 | 138 | 0.719656 | [
"vector"
] |
6107ff9c71629278522e5171346eed7290f9318c | 4,375 | cpp | C++ | Modules/Spine/Sources/UI/Spine/Private/UISpineComponent.cpp | BlitzModder/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | 4 | 2019-11-15T11:30:00.000Z | 2021-12-27T21:16:31.000Z | Modules/Spine/Sources/UI/Spine/Private/UISpineComponent.cpp | TTopox/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | null | null | null | Modules/Spine/Sources/UI/Spine/Private/UISpineComponent.cpp | TTopox/dava.engine | 0c7a16e627fc0d12309250d6e5e207333b35361e | [
"BSD-3-Clause"
] | 4 | 2017-04-07T04:32:41.000Z | 2021-12-27T21:55:49.000Z | #include "UI/Spine/UISpineComponent.h"
#include "UI/Spine/UISpineSingleComponent.h"
#include "UI/Spine/UISpineSystem.h"
#include <Engine/Engine.h>
#include <Entity/ComponentManager.h>
#include <Reflection/ReflectionRegistrator.h>
#include <UI/UIControl.h>
#include <UI/UIControlSystem.h>
ENUM_DECLARE(DAVA::UISpineComponent::AnimationState)
{
ENUM_ADD_DESCR(DAVA::UISpineComponent::STOPPED, "Stopped");
ENUM_ADD_DESCR(DAVA::UISpineComponent::PLAYED, "Played");
}
namespace DAVA
{
DAVA_VIRTUAL_REFLECTION_IMPL(UISpineComponent)
{
ReflectionRegistrator<UISpineComponent>::Begin()[M::DisplayName("Spine")]
.ConstructorByPointer()
.DestructorByPointer([](UISpineComponent* c) { SafeRelease(c); })
.Field("skeletonPath", &UISpineComponent::GetSkeletonPath, &UISpineComponent::SetSkeletonPath)
.Field("atlasPath", &UISpineComponent::GetAtlasPath, &UISpineComponent::SetAtlasPath)
.Field("animationName", &UISpineComponent::GetAnimationName, &UISpineComponent::SetAnimationName) // Connect select to animationsNames
.Field("animationsNames", &UISpineComponent::GetAnimationsNames, &UISpineComponent::SetAnimationsNames)[M::ReadOnly()]
.Field("animationState", &UISpineComponent::GetAnimationState, &UISpineComponent::SetAnimationState)[M::EnumT<UISpineComponent::AnimationState>()]
.Field("skinName", &UISpineComponent::GetSkinName, &UISpineComponent::SetSkinName) // Connect select to skinsNames
.Field("skinsNames", &UISpineComponent::GetSkinsNames, &UISpineComponent::SetSkinsNames)[M::ReadOnly()]
.Field("timeScale", &UISpineComponent::GetTimeScale, &UISpineComponent::SetTimeScale)
.Field("loopedPlayback", &UISpineComponent::IsLoopedPlayback, &UISpineComponent::SetLoopedPlayback)
.End();
}
IMPLEMENT_UI_COMPONENT(UISpineComponent);
UISpineComponent::UISpineComponent(const UISpineComponent& copy)
: UIComponent(copy)
, skeletonPath(copy.skeletonPath)
, atlasPath(copy.atlasPath)
, animationName(copy.animationName)
, animationsNames(copy.animationsNames)
, animationState(copy.animationState)
, skinName(copy.skinName)
, skinsNames(copy.skinsNames)
, timeScale(copy.timeScale)
, animationLooped(copy.animationLooped)
{
}
UISpineComponent::~UISpineComponent() = default;
void UISpineComponent::Modify(bool needReload)
{
UIControl* control = GetControl();
if (control)
{
UIControlSystem* scene = control->GetScene();
if (scene)
{
UISpineSingleComponent* spineSingle = scene->GetSingleComponent<UISpineSingleComponent>();
if (spineSingle)
{
spineSingle->spineModified.insert(control);
if (needReload)
{
spineSingle->spineNeedReload.insert(control);
}
}
}
}
}
UISpineComponent* UISpineComponent::Clone() const
{
return new UISpineComponent(*this);
}
void UISpineComponent::SetSkeletonPath(const FilePath& path)
{
if (skeletonPath != path)
{
skeletonPath = path;
Modify(true);
}
}
void UISpineComponent::SetAtlasPath(const FilePath& path)
{
if (atlasPath != path)
{
atlasPath = path;
Modify(true);
}
}
void UISpineComponent::SetAnimationState(const AnimationState& state)
{
if (animationState != state)
{
animationState = state;
Modify(false);
}
}
void UISpineComponent::SetAnimationName(const String& name)
{
if (animationName != name)
{
animationName = name;
Modify(false);
}
}
void UISpineComponent::SetAnimationsNames(const Vector<String>& names)
{
if (animationsNames != names)
{
animationsNames = names;
Modify(false);
}
}
void UISpineComponent::SetTimeScale(float32 scale)
{
if (timeScale != scale)
{
timeScale = scale;
Modify(false);
}
}
void UISpineComponent::SetLoopedPlayback(bool loop)
{
if (animationLooped != loop)
{
animationLooped = loop;
Modify(false);
}
}
void UISpineComponent::SetSkinName(const String& name)
{
if (skinName != name)
{
skinName = name;
Modify(false);
}
}
void UISpineComponent::SetSkinsNames(const Vector<String>& names)
{
if (skinsNames != names)
{
skinsNames = names;
Modify(false);
}
}
}
| 27.173913 | 150 | 0.684114 | [
"vector"
] |
6109616ed19c14f6926df5f3aaa803128efd595e | 8,335 | cpp | C++ | tools/freebayes/vcflib/src/vcfannotategenotypes.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | null | null | null | tools/freebayes/vcflib/src/vcfannotategenotypes.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | null | null | null | tools/freebayes/vcflib/src/vcfannotategenotypes.cpp | benranco/test | 7cf9740108844da30dcc506e733015fd5dd76a05 | [
"MIT"
] | 1 | 2020-10-01T10:32:38.000Z | 2020-10-01T10:32:38.000Z | #include "Variant.h"
#include "split.h"
#include <string>
#include <list>
#include <iostream>
using namespace std;
using namespace vcf;
void annotateWithBlankGenotypes(Variant& var, string& annotationTag) {
var.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = var.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
sample[annotationTag].clear(); // means "no genotype" genotype
sample[annotationTag].push_back("./."); // means "no genotype" genotype
}
}
void annotateWithGenotypes(Variant& varA, Variant& varB, string& annotationTag) {
varA.addFormatField(annotationTag);
map<string, map<string, vector<string> > >::iterator s = varA.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = varA.samples.end();
map<string, int> varAAlleleInts;
int i = 1;
for (vector<string>::iterator a = varA.alt.begin(); a != varA.alt.end(); ++a, ++i) {
varAAlleleInts[*a] = i;
}
map<int, int> varBconvertToVarA; // maps alleles in the second file to allele numbers for the first
varBconvertToVarA[0] = 0; // reference == reference!
i = 1;
for (vector<string>::iterator a = varB.alt.begin(); a != varB.alt.end(); ++a, ++i) {
map<string, int>::iterator ita = varAAlleleInts.find(*a);
if (ita != varAAlleleInts.end()) {
varBconvertToVarA[i] = ita->second;
}
}
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
const string& name = s->first;
map<string, map<string, vector<string> > >::iterator o = varB.samples.find(name);
sample[annotationTag].clear();
if (o == varB.samples.end()) {
sample[annotationTag].push_back("./."); // means "no genotype"
} else {
map<string, vector<string> >& other = o->second;
string& otherGenotype = other["GT"].front();
// XXX this must compare the genotypes in the two files
map<int, int> gtB = decomposeGenotype(otherGenotype);
map<int, int> gtnew;
for (map<int, int>::iterator g = gtB.begin(); g != gtB.end(); ++g) {
map<int, int>::iterator f = varBconvertToVarA.find(g->first);
if (f != varBconvertToVarA.end()) {
gtnew[f->second] += g->second;
} else {
gtnew[-1] += g->second;
}
}
sample[annotationTag].push_back(genotypeToString(gtnew));
}
}
}
int main(int argc, char** argv) {
if (argc != 4) {
cerr << "usage: " << argv[0] << " <annotation-tag> <vcf file> <vcf file>" << endl
<< "annotates genotypes in the first file with genotypes in the second" << endl
<< "adding the genotype as another flag to each sample filed in the first file." << endl
<< "annotation-tag is the name of the sample flag which is added to store the annotation." << endl
<< "also adds a 'has_variant' flag for sites where the second file has a variant." << endl;
return 1;
}
string annotag = argv[1];
string filenameA = argv[2];
string filenameB = argv[3];
if (filenameA == filenameB) {
cerr << "it won't help to annotate samples with their own genotypes!" << endl;
return 1;
}
VariantCallFile variantFileA;
if (filenameA == "-") {
variantFileA.open(std::cin);
} else {
variantFileA.open(filenameA);
}
VariantCallFile variantFileB;
if (filenameB == "-") {
variantFileB.open(std::cin);
} else {
variantFileB.open(filenameB);
}
if (!variantFileA.is_open() || !variantFileB.is_open()) {
return 1;
}
Variant varA(variantFileA);
Variant varB(variantFileB);
// while the first file doesn't match the second positionally,
// step forward, annotating each genotype record with an empty genotype
// when the two match, iterate through the genotypes from the first file
// and get the genotypes reported in the second file
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
string line = "##INFO=<ID=" + annotag + ".has_variant,Number=0,Type=Flag,Description=\"True if "
+ annotag + " has a called alternate among samples under comparison.\">";
variantFileA.addHeaderLine(line);
line = "##FORMAT=<ID=" + annotag + ",Number=1,Type=String,Description=\"Genotype from "
+ annotag + ".\">";
variantFileA.addHeaderLine(line);
cout << variantFileA.header << endl;
do {
// this is broken. to do it right, it'll be necessary to get reference ids from the fasta reference used to make the alignments...
if (!variantFileB.done()
&& (varB.sequenceName != varA.sequenceName
|| (varB.sequenceName == varA.sequenceName && varB.position < varA.position))
) {
variantFileB.getNextVariant(varB);
}
if (!variantFileA.done()
&& (varA.sequenceName != varB.sequenceName
|| (varA.sequenceName == varB.sequenceName && varA.position < varB.position))
) {
cout << varA << endl;
variantFileA.getNextVariant(varA);
}
vector<Variant> varsA;
vector<Variant> varsB;
bool hasMultipleAlts = false;
long int thisPosition = 0;
string thisSequenceName;
if (varA.position == varB.position
&& varA.sequenceName == varB.sequenceName) {
thisPosition = varA.position;
thisSequenceName = varA.sequenceName;
}
while (!variantFileA.done()
&& !variantFileB.done()
&& thisPosition == varA.position
&& thisSequenceName == varA.sequenceName
&& varA.sequenceName == varB.sequenceName
&& varA.position == varB.position) {
// accumulate all the alts at the current position
varsA.push_back(varA);
varsB.push_back(varB);
if (varA.alt.size() > 1 || varB.alt.size() > 1)
hasMultipleAlts = true;
variantFileA.getNextVariant(varA);
variantFileB.getNextVariant(varB);
}
// multiple lines per position
if (!hasMultipleAlts && (varsA.size() > 1 || varsB.size() > 1)) {
map<pair<string, string>, Variant> varsAParsed;
map<pair<string, string>, Variant> varsBParsed;
for (vector<Variant>::iterator v = varsA.begin(); v != varsA.end(); ++v) {
varsAParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (vector<Variant>::iterator v = varsB.begin(); v != varsB.end(); ++v) {
varsBParsed[make_pair(v->ref, v->alt.front())] = *v;
}
for (map<pair<string, string>, Variant>::iterator vs = varsAParsed.begin(); vs != varsAParsed.end(); ++vs) {
Variant& varA = vs->second;
if (varsBParsed.find(make_pair(varA.ref, varA.alt.front())) != varsBParsed.end()) {
Variant& varB = varsBParsed[make_pair(varA.ref, varA.alt.front())]; // TODO cleanup
annotateWithGenotypes(varA, varB, annotag);
varA.infoFlags[annotag + ".has_variant"] = true;
} else {
annotateWithBlankGenotypes(varA, annotag);
}
cout << varA << endl;
}
} else if (!varsA.empty() && !varsB.empty()) { // one line per multi-allelic
Variant& varA = varsA.front();
Variant& varB = varsB.front();
annotateWithGenotypes(varA, varB, annotag);
// XXX TODO, and also allow for records with multiple alts
// XXX assume that if the other file has a corresponding record, some kind of variation was detected at the same site
varA.infoFlags[annotag + ".has_variant"] = true;
cout << varA << endl;
}
} while (!variantFileA.done() && !variantFileB.done());
return 0;
}
| 38.587963 | 139 | 0.572166 | [
"vector"
] |
610ac8df1bb843bfcda3e27c617260eddb4d3ce1 | 4,244 | cpp | C++ | ipz_app.cpp | wistron-corporation/openpower-vpd-parser | 73b589b85ec6194853f1474b76e62623468debdb | [
"Apache-2.0"
] | null | null | null | ipz_app.cpp | wistron-corporation/openpower-vpd-parser | 73b589b85ec6194853f1474b76e62623468debdb | [
"Apache-2.0"
] | null | null | null | ipz_app.cpp | wistron-corporation/openpower-vpd-parser | 73b589b85ec6194853f1474b76e62623468debdb | [
"Apache-2.0"
] | null | null | null | #include "config.h"
#include "defines.hpp"
#include "parser.hpp"
#include "utils.hpp"
#include <CLI/CLI.hpp>
#include <exception>
#include <fstream>
#include <iostream>
#include <iterator>
#include <nlohmann/json.hpp>
using namespace std;
using namespace openpower::vpd;
static void populateInterfaces(const nlohmann::json& js,
inventory::InterfaceMap& interfaces,
const Parsed& vpdMap)
{
for (const auto& ifs : js.items())
{
const string& inf = ifs.key();
inventory::PropertyMap props;
for (const auto& itr : ifs.value().items())
{
const string& rec = itr.value().value("recordName", "");
const string& kw = itr.value().value("keywordName", "");
if (!rec.empty() && !kw.empty() && vpdMap.count(rec) &&
vpdMap.at(rec).count(kw))
{
props.emplace(itr.key(), string(vpdMap.at(rec).at(kw).begin(),
vpdMap.at(rec).at(kw).end()));
}
}
interfaces.emplace(inf, move(props));
}
}
static void populateDbus(Store& vpdStore, nlohmann::json& js,
const string& objectPath, const string& filePath)
{
inventory::InterfaceMap interfaces;
inventory::ObjectMap objects;
sdbusplus::message::object_path object(objectPath);
const auto& vpdMap = vpdStore.getVpdMap();
string preIntrStr = "com.ibm.ipzvpd.";
// Each record in the VPD becomes an interface and all keywords within the
// record are properties under that interface.
for (const auto& record : vpdMap)
{
inventory::PropertyMap prop;
for (auto kwVal : record.second)
{
std::vector<uint8_t> vec(kwVal.second.begin(), kwVal.second.end());
std::string kw = kwVal.first;
if (kw[0] == '#')
{
kw = std::string("PD_") + kw[1];
}
prop.emplace(move(kw), move(vec));
}
interfaces.emplace(preIntrStr + record.first, move(prop));
}
// Populate interfaces and properties that are common to every FRU
// and additional interface that might be defined on a per-FRU basis.
if (js.find("commonInterfaces") != js.end())
{
populateInterfaces(js["commonInterfaces"], interfaces, vpdMap);
}
if (js["frus"][filePath].find("extraInterfaces") !=
js["frus"][filePath].end())
{
populateInterfaces(js["frus"][filePath]["extraInterfaces"], interfaces,
vpdMap);
}
objects.emplace(move(object), move(interfaces));
// Notify PIM
inventory::callPIM(move(objects));
}
int main(int argc, char** argv)
{
int rc = 0;
try
{
using namespace CLI;
using json = nlohmann::json;
App app{"ibm-read-vpd - App to read IPZ format VPD, parse it and store "
"in DBUS"};
string file{};
app.add_option("-f, --file", file, "File containing VPD in IPZ format")
->required()
->check(ExistingFile);
CLI11_PARSE(app, argc, argv);
// Make sure that the file path we get is for a supported EEPROM
ifstream inventoryJson(INVENTORY_JSON);
auto js = json::parse(inventoryJson);
if ((js.find("frus") == js.end()) ||
(js["frus"].find(file) == js["frus"].end()))
{
throw std::runtime_error("Device path missing in inventory JSON");
}
const string& objectPath = js["frus"][file].value("inventoryPath", "");
if (objectPath.empty())
{
throw std::runtime_error("Could not find D-Bus object path in "
"inventory JSON");
}
ifstream vpdFile(file, ios::binary);
Binary vpd((istreambuf_iterator<char>(vpdFile)),
istreambuf_iterator<char>());
// Use ipz vpd Parser
auto vpdStore = parse(move(vpd));
// Write it to the inventory
populateDbus(vpdStore, js, objectPath, file);
}
catch (exception& e)
{
cerr << e.what() << "\n";
rc = -1;
}
return rc;
}
| 29.678322 | 80 | 0.554194 | [
"object",
"vector"
] |
610c698dc1381d34d8d8760f890181541d19e0d3 | 2,476 | hpp | C++ | arbor/include/arbor/simulation.hpp | phoenixdong/arbor | 84284df75d7509b4d0d3ae07307cc9c674894d1c | [
"BSD-3-Clause"
] | null | null | null | arbor/include/arbor/simulation.hpp | phoenixdong/arbor | 84284df75d7509b4d0d3ae07307cc9c674894d1c | [
"BSD-3-Clause"
] | null | null | null | arbor/include/arbor/simulation.hpp | phoenixdong/arbor | 84284df75d7509b4d0d3ae07307cc9c674894d1c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <array>
#include <memory>
#include <unordered_map>
#include <vector>
#include <arbor/export.hpp>
#include <arbor/common_types.hpp>
#include <arbor/context.hpp>
#include <arbor/domain_decomposition.hpp>
#include <arbor/recipe.hpp>
#include <arbor/sampling.hpp>
#include <arbor/schedule.hpp>
#include <arbor/spike.hpp>
#include <arbor/util/handle_set.hpp>
namespace arb {
using spike_export_function = std::function<void(const std::vector<spike>&)>;
// simulation_state comprises private implementation for simulation class.
class simulation_state;
/*
A simulation is the executable form of a model and is used to interact with
and monitor the model state. In the simulation the neuron model is initiated
and the spike exchange and the integration for each cell group are scheduled.
*/
class ARB_ARBOR_API simulation {
public:
simulation(const recipe& rec, const domain_decomposition& decomp, const context& ctx);
void reset();
time_type run(time_type tfinal, time_type dt);
// Note: sampler functions may be invoked from a different thread than that
// which called the `run` method.
sampler_association_handle add_sampler(cell_member_predicate probe_ids,
schedule sched, sampler_function f, sampling_policy policy = sampling_policy::lax);
void remove_sampler(sampler_association_handle);
void remove_all_samplers();
// Return probe metadata, one entry per probe associated with supplied probe id,
// or an empty vector if no local match for probe id.
std::vector<probe_metadata> get_probe_metadata(cell_member_type probe_id) const;
std::size_t num_spikes() const;
// Set event binning policy on all our groups.
void set_binning_policy(binning_kind policy, time_type bin_interval);
// Register a callback that will perform a export of the global
// spike vector.
void set_global_spike_callback(spike_export_function = spike_export_function{});
// Register a callback that will perform a export of the rank local
// spike vector.
void set_local_spike_callback(spike_export_function = spike_export_function{});
// Add events directly to targets.
// Must be called before calling simulation::run, and must contain events that
// are to be delivered at or after the current simulation time.
void inject_events(const cse_vector& events);
~simulation();
private:
std::unique_ptr<simulation_state> impl_;
};
} // namespace arb
| 32.155844 | 91 | 0.754443 | [
"vector",
"model"
] |
610ed2ec86fbdedcc12f4936ac98f149b351b99c | 8,272 | cc | C++ | hstree/hstree-disk/src/index.cc | TsinghuaDatabaseGroup/Similarity-Search-and-Join | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 14 | 2018-01-29T06:54:06.000Z | 2021-07-09T18:18:51.000Z | hstree/hstree-disk/src/index.cc | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | null | null | null | hstree/hstree-disk/src/index.cc | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 11 | 2018-04-11T04:56:40.000Z | 2021-12-17T04:00:22.000Z | /*
* index.cc
*
* Created on: 2014-12-11
* Author: wangjin
*/
#include "index.h"
int maxLevel;
int maxPN;
bool *visited;
bool **curmatchpos;
set<match_entry> **matchinfo;
int **matrix;
int ***partLen;
int ***partPos;
vector<ssIndex> **substrings;
ContentMap *cfilter;
Groupset grps;
int calLevel(int length)
{
int maxlv = 0;
while(true)
{
int pn = 1 << (maxlv+1);
if(length / pn <= 1)
break;
maxlv++;
}
return (maxlv+1);
}
int Group::getMaxLevel()
{
return calLevel(len);
}
int Group::getMaxPN()
{
int maxlv = calLevel(len);
return (1<<(maxlv+1));
}
void Group::buildIndex(ofstream &pf)
{
int maxlv = getMaxLevel();
int maxpn;
//generate invertedlists
vector<vector<InvertedList> > tmplists;
tmplists.resize(maxlv);
for(int i = 0; i < maxlv; ++i)
tmplists[i].resize(getMaxPN());
for (int id = st; id <= en; ++id)
{
for(int lv = 0; lv < maxlv; ++lv)
{
maxpn = 1 << (lv + 1);
for(int pid = 0; pid < maxpn; ++pid)
{
#if defined (STORE_HASH)
tmplists[lv][pid][strHash(dict[id], partPos[len][lv][pid], partLen[len][lv][pid])].push_back(id);
#else
tmplists[lv][pid][dict[id].substr(partPos[len][lv][pid], partLen[len][lv][pid])].push_back(id);
#endif
}
}
}
//write inverted lists into disk
for(int lv = 0; lv < maxlv; ++lv)
{
maxpn = 1 << (lv + 1);
for(int pid = 0; pid < maxpn; ++pid)
{
InvertedList::iterator inv_itr;
ADDR offset = pf.tellp();
for(inv_itr = tmplists[lv][pid].begin(); inv_itr != tmplists[lv][pid].end(); ++inv_itr)
{
# if defined (STORE_HASH)
int64_t value = inv_itr->first;
#else
string value = inv_itr->first;
#endif
maps[lv][pid].insert(make_pair(value,offset));
vector<int> list;
vector<int>::iterator itr;
for(itr = inv_itr->second.begin(); itr != inv_itr->second.end(); ++itr )
{
list.push_back(*itr);
}
saveList(pf, list);
offset = pf.tellp();
}
}
}
}
void Group::printGroup()
{
//print basic info
printf("###############Group Information################\n");
printf("Group: %d, start: %d, end: %d\n", len, st,en);
//print partlen and part pos
int maxlv = getMaxLevel()-1;
cout<<"*************Print maps************"<<endl;
for(int lv = 0; lv < maxlv; ++lv)
{
int pn = 1 << (lv + 1);
printf("level: %d\n", lv);
for(int pid = 0; pid < pn; ++pid)
{
InvertedMap::iterator mitr;
printf("pid: %d\n", pid);
for(mitr = maps[lv][pid].begin(); mitr != maps[lv][pid].end(); ++mitr)
cout<<"list code: "<<mitr->first << " offset: "<<mitr->second<<endl;
}
}
}
#if defined (STORE_HASH)
ADDR Group::findOffset(uint64_t hv, int lv, int pid)
{
ADDR offset = maps[lv][pid].find(hv)->second;
return offset;
}
#else
ADDR Group::findOffset(string str, int lv, int pid)
{
ADDR offset = maps[lv][pid].find(str)->second;
return offset;
}
#endif
void sortData()
{
sort(dict.begin(), dict.end(), strLessT);
}
void initial()
{
maxLevel = calLevel(maxDictlen);
maxPN = 1<<(maxLevel+1);
visited = new bool[N];
cfilter = new ContentMap[N];
matrix = new int *[maxDictlen + 1];
substrings = new vector<ssIndex> *[maxLevel];
partLen = new int **[maxDictlen+1];
partPos = new int **[maxDictlen+1];
for(int lp = 0; lp <= maxDictlen; ++lp)
{
partLen[lp] = new int *[maxLevel];
partPos[lp] = new int *[maxLevel];
matrix[lp] = new int[maxDictlen + 1];
}
for(int len = 0; len <= maxDictlen; ++len)
for(int lv = 0; lv < maxLevel; ++lv)
{
partLen[len][lv] = new int [maxPN];
partPos[len][lv] = new int [maxPN];
}
for(int lv = 0; lv < maxLevel; ++lv)
substrings[lv] = new vector<ssIndex> [maxPN];
for(int i = 0; i <= maxDictlen; ++i)
{
matrix[i][0] = i;
matrix[0][i] = i;
}
cout<<"initial finished!"<<endl;
}
void createIndex(const string& path )
{
int start = 0, end = 0;
int tmplen = minDictlen;
int pn;
string idxpath = path+".idx";
string mempath = path+".idm";
ofstream writel;
writel.open(idxpath.c_str(), ios::out);
// deal with the first string in dict
for(int i = 0; i < static_cast<int>(dict[0].length()); ++i)
if(cfilter[0].find(dict[0].at(i)) != cfilter[0].end())
cfilter[0][dict[0].at(i)]++;
else
cfilter[0].insert(make_pair(dict[0].at(i), 1));
//calculate partlen and partpos
for (int len = minDictlen; len <= maxDictlen; ++len)
{
Groupset::iterator gitr;
int maxlv = calLevel(len);
//calculate partlen
partLen[len][0][0] = len >> 1;
partLen[len][0][1] = (len % 2) ? (partLen[len][0][0] +1):partLen[len][0][0];
if(maxlv > 1)
{
for(int lv = 1; lv < maxlv; ++lv )
{
pn = 1 << (lv+1);
for(int pid = 0; pid < pn; ++pid)
{
if(pid % 2)
partLen[len][lv][pid] = (partLen[len][lv-1][pid >> 1] % 2) ? (partLen[len][lv-1][pid >> 1] - partLen[len][lv][pid-1]):partLen[len][lv][pid-1] ;
else
partLen[len][lv][pid] = partLen[len][lv-1][pid >> 1] >> 1;
}
}
}
//calculate partpos
for(int lv = 0; lv < maxlv; ++lv)
{
pn = 1 << (lv + 1);
partPos[len][lv][0] = 0;
partPos[len][lv][pn] = len;
}
for(int lv = 0; lv < maxlv; ++lv)
{
pn = 1 << (lv + 1);
for(int pid = 1; pid < pn; ++pid)
partPos[len][lv][pid] = partPos[len][lv][pid-1] + partLen[len][lv][pid-1];
}
}
//generate inverted index
for(int id = 1; id < N; ++id)
{
if(dict[id].length() > dict[id - 1].length())
{
end = id - 1;
Group tmpgrp = Group(tmplen,start,end);
tmpgrp.buildIndex(writel);
grps.insert(make_pair(tmplen,tmpgrp));
start = id;
tmplen = dict[id].length();
}
for(int i = 0; i < dict[id].length(); ++i)
if(cfilter[id].find(dict[id].at(i)) != cfilter[id].end())
cfilter[id][dict[id].at(i)]++;
else
cfilter[id].insert(make_pair(dict[id].at(i), 1));
}
Group tmpgrp = Group(tmplen, start, N - 1);
tmpgrp.buildIndex(writel);
grps.insert(make_pair(tmplen,tmpgrp));
writel.close();
cout<<"create index finished."<<endl;
}
void printIndex()
{
Groupset::iterator gitr;
for(gitr = grps.begin(); gitr != grps.end(); ++gitr)
gitr->second.printGroup();
printf("print index finished!\n");
}
/*
*
* for(int id = 0; id < N; ++id)
{
curmatchpos[id] = new bool[maxDictlen + 1];
matchinfo[id] = new set<match_entry> [maxLevel];
}
for(int i = 0; i < N; ++i)
for(int j = 0; j<= maxDictlen; ++j)
curmatchpos[i][j] = 0;
* cout<<"*************Print partlen************"<<endl;
for(int lv = 0; lv < maxlv; ++lv)
{
int pn = 1 << (lv + 1);
for(int pid = 0; pid < pn; pid++)
printf("%d ", partLen[lv][pid]);
printf("\n");
}
cout<<"*************Print partpos************"<<endl;
for(int lv = 0; lv < maxlv; ++lv)
{
int pn = 1 << (lv + 1);
for(int pid = 0; pid <= pn; ++pid)
cout<<partPos[lv][pid]<<" ";
printf("\n");
}
*/
| 29.437722 | 167 | 0.465184 | [
"vector"
] |
6110e5eb5dac0b2da68660104e49ca27669b5135 | 13,729 | cpp | C++ | engine/executor/src/operators/matmul.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | engine/executor/src/operators/matmul.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | engine/executor/src/operators/matmul.cpp | alexsu52/neural-compressor | 7607ee46a015ee83a5e79dace8535a439d49cc8c | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "matmul.hpp"
namespace executor {
static unordered_map<string, dnnl::memory::data_type> type2mem{
{"fp32", dnnl::memory::data_type::f32},
{"s32", dnnl::memory::data_type::s32},
{"fp16", dnnl::memory::data_type::f16},
{"u8", dnnl::memory::data_type::u8},
{"s8", dnnl::memory::data_type::s8}};
MatmulOperator::MatmulOperator(const OperatorConfig& conf) :
Operator(conf), src0_perm_({}), src1_perm_({}), dst_perm_({}),
output_scale_(1.), format_any_(true) {
auto attrs_map = operator_conf_.attributes();
auto iter = attrs_map.find("src0_perm");
if (iter != attrs_map.end()) {
StringSplit<int64_t>(&src0_perm_, attrs_map["src0_perm"], ",");
}
iter = attrs_map.find("src1_perm");
if (iter != attrs_map.end()) {
StringSplit<int64_t>(&src1_perm_, attrs_map["src1_perm"], ",");
}
iter = attrs_map.find("dst_perm");
if (iter != attrs_map.end()) {
StringSplit<int64_t>(&dst_perm_, attrs_map["dst_perm"], ",");
}
iter = attrs_map.find("output_scale");
if (iter != attrs_map.end()) {
output_scale_ = StringToNum<float>(attrs_map["output_scale"]);
}
iter = attrs_map.find("format_any");
if (iter != attrs_map.end()) {
format_any_ = attrs_map["format_any"] == "true";
}
iter = attrs_map.find("is_symm");
if (iter != attrs_map.end()) {
is_asymm_ = attrs_map["is_symm"] == "true";
}
iter = attrs_map.find("output_dtype");
if (iter != attrs_map.end()) {
output_dtype_ = attrs_map["output_dtype"];
}
iter = attrs_map.find("append_op");
append_sum_ = (iter != attrs_map.end() && iter->second == "sum") ? true : false;
binary_add_ = (iter != attrs_map.end() && iter->second == "binary_add") ? true : false;
gelu_erf_ = (iter != attrs_map.end() && iter->second == "gelu_erf") ? true : false;
gelu_tanh_ = (iter != attrs_map.end() && iter->second == "gelu_tanh") ? true : false;
tanh_ = (iter != attrs_map.end() && iter->second == "tanh") ? true : false;
}
MatmulOperator::~MatmulOperator() {
}
void MatmulOperator::MapTensors(const vector<Tensor*>& input, const vector<Tensor*>& output) {
int input_size = input.size();
dst_ = output[0];
switch (input_size) {
case 2: {
src0_ = input[0];
src1_ = input[1];
break;
}
case 3: {
src0_ = input[0];
src1_ = input[1];
bias_ = (append_sum_ || binary_add_) ? nullptr : input[2];
post_ = (append_sum_ || binary_add_) ? input[2] : nullptr;
break;
}
case 4: {
src0_ = input[0];
src1_ = input[1];
bias_ = input[2];
post_ = (append_sum_ || binary_add_) ? input[3] : nullptr;
break;
}
case 6: {
src0_ = input[0];
src1_ = input[1];
src0_min_ = input[2];
src0_max_ = input[3];
src1_min_ = input[4];
src1_max_ = input[5];
break;
}
case 7: {
src0_ = input[0];
src1_ = input[1];
post_ = (append_sum_ || binary_add_) ? input[2] : nullptr;
src0_min_ = input[3];
src0_max_ = input[4];
src1_min_ = input[5];
src1_max_ = input[6];
break;
}
case 8: {
src0_ = input[0];
src1_ = input[1];
src0_min_ = input[2];
src0_max_ = input[3];
src1_min_ = input[4];
src1_max_ = input[5];
dst_min_ = input[6];
dst_max_ = input[7];
break;
}
case 9: {
src0_ = input[0];
src1_ = input[1];
bias_ = (append_sum_ || binary_add_) ? nullptr: input[2];
post_ = (append_sum_ || binary_add_) ? input[2] : nullptr;
src0_min_ = input[3];
src0_max_ = input[4];
src1_min_ = input[5];
src1_max_ = input[6];
dst_min_ = input[7];
dst_max_ = input[8];
break;
}
case 10: {
src0_ = input[0];
src1_ = input[1];
bias_ = input[2];
post_ = (append_sum_ || binary_add_) ? input[3] : nullptr;
src0_min_ = input[4];
src0_max_ = input[5];
src1_min_ = input[6];
src1_max_ = input[7];
dst_min_ = input[8];
dst_max_ = input[9];
break;
}
}
}
void MatmulOperator::Prepare(const vector<Tensor*>& input, const vector<Tensor*>& output) {
MapTensors(input, output);
dst_->set_dtype(output_dtype_);
}
// 1. Create primitive
void MatmulOperator::Reshape(const vector<Tensor*>& input, const vector<Tensor*>& output) {
bool has_bias = (input.size() == 4 || input.size() == 10) ||
((input.size() == 3 || input.size() == 9) && !append_sum_ && !binary_add_) ? true: false;
//// Part1: Derive operator's user proper shape and strides
// 1.1 Transpose tensor shape and get it
vector<int64_t> src0_shape_origin = src0_->shape();
vector<int64_t> src1_shape_origin = src1_->shape();
vector<int64_t> src0_shape = GetShapes(src0_shape_origin, src0_perm_);
vector<int64_t> src1_shape = GetShapes(src1_shape_origin, src1_perm_);
vector<int64_t> src0_stride = GetStrides(src0_shape_origin, src0_perm_);
vector<int64_t> src1_stride = GetStrides(src1_shape_origin, src1_perm_);
src0_->set_shape(src0_shape);
src1_->set_shape(src1_shape);
memory::dims bias_shape;
if (has_bias) bias_shape = bias_->shape();
// 1.2 malloc tensor for output
// src0_: M*K, src1_: K*N, DST: M*N
vector<int64_t> dst_shape_origin = src0_shape;
dst_shape_origin.back() = src1_shape.back();
// Sub-step3: fused post transpose, notice it's different that
// pre transpose will use the tranposed shape and stride, it's straight forward
// post transpose will use origin shape and that means the dst buffer in matmul
// is a buffer transposed back from dst_perm(understand tranpose to and transpose back)
// pre_transpose: src_buffer -> pre_transpose -> target_buffer in matmul
// post_transpose: target_buffer in matmul<- post transpose <-dst_buffer
vector<int64_t> dst_shape = GetShapes(dst_shape_origin, dst_perm_);
vector<int64_t> reverse_perm = ReversePerm(dst_perm_);
vector<int64_t> dst_stride = GetStrides(dst_shape, reverse_perm);
vector<int64_t> bias_stride = GetStrides(bias_shape, reverse_perm);
// 1.4 Prepare memory descriptors
memory::desc any_src0_md = memory::desc(src0_shape,
type2mem[src0_->dtype()], memory::format_tag::any);
memory::desc src0_md = memory::desc(src0_shape, type2mem[src0_->dtype()], src0_stride);
memory::desc any_src1_md = memory::desc(
src1_shape, type2mem[src1_->dtype()], memory::format_tag::any);
memory::desc src1_md = memory::desc(src1_shape, type2mem[src1_->dtype()], src1_stride);
memory::desc any_dst_md = memory::desc(
dst_shape_origin, type2mem[dst_->dtype()], memory::format_tag::any);
memory::desc dst_md = memory::desc(dst_shape_origin, type2mem[dst_->dtype()], dst_stride);
memory::desc bias_md;
memory::desc any_bias_md;
if (has_bias) {
bias_md = memory::desc(bias_shape, type2mem[bias_->dtype()], bias_stride);
any_bias_md = memory::desc(bias_shape, type2mem[bias_->dtype()], memory::format_tag::any);
}
// 1.5 Set dst shape and strides
dst_->set_shape(dst_shape);
// 2.2 Prepare op descriptors
dnnl::matmul::desc matmul_d = has_bias ?
dnnl::matmul::desc(src0_md, src1_md, bias_md, dst_md) :
dnnl::matmul::desc(src0_md, src1_md, dst_md);;
if (format_any_) {
matmul_d = has_bias ?
dnnl::matmul::desc(any_src0_md, any_src1_md, any_bias_md, any_dst_md) :
dnnl::matmul::desc(any_src0_md, any_src1_md, any_dst_md);
}
// 2.3 Prepare primitive descriptors (cached)
dnnl::primitive_attr attr;
vector<float> src0_scales;
vector<float> src1_scales;
vector<float> dst_scales;
vector<float> rescales;
vector<int> dst_zero_points;
int ic_dim = 0;
if (output_scale_ != 1.f || src0_min_ != nullptr || src1_min_ != nullptr) {
if (src0_min_ != nullptr && src1_max_ != nullptr) {
ic_dim = src1_min_->size() > 1 ? 0 | (1 << 1) : 0;
src0_scales = GetScales(src0_min_->data(), src0_max_->data(),
src0_min_->size(), src0_->dtype());
src1_scales = GetScales(src1_min_->data(), src1_max_->data(),
src1_min_->size(), src1_->dtype());
if (dst_min_ != nullptr)
dst_scales = GetScales(dst_min_->data(), dst_max_->data(),
dst_min_->size(), dst_->dtype());
rescales = GetRescales(src0_scales, src1_scales,
dst_scales, dst_->dtype());
} else {
rescales = vector<float>(1, 1.f);
}
if (output_scale_!= 1.f) {
for (int i = 0; i < rescales.size(); i++) {
rescales[i] *= output_scale_;
}
}
attr.set_output_scales(ic_dim, rescales);
}
if (dst_->dtype() == "u8") {
dst_zero_points = GetZeroPoints(dst_min_->data(), dst_scales, dst_->dtype());
attr.set_zero_points(DNNL_ARG_DST, ic_dim, dst_zero_points);
}
if (append_sum_) {
dnnl::post_ops po;
float beta = 1.0;
po.append_sum(beta);
attr.set_post_ops(po);
}
if (gelu_erf_) {
dnnl::post_ops po;
float op_scale = 1.0;
float op_alpha = 0.0;
float op_beta = 0.0;
po.append_eltwise(op_scale, algorithm::eltwise_gelu_erf, op_alpha, op_beta);
attr.set_post_ops(po);
}
if (gelu_tanh_) {
dnnl::post_ops po;
float op_scale = 1.0;
float op_alpha = 0.0;
float op_beta = 0.0;
po.append_eltwise(op_scale, algorithm::eltwise_gelu_tanh, op_alpha, op_beta);
attr.set_post_ops(po);
}
if (tanh_) {
dnnl::post_ops po;
auto op_scale = 1.0;
auto op_alpha = 0.0;
auto op_beta = 0.0;
po.append_eltwise(op_scale, algorithm::eltwise_tanh, op_alpha, op_beta);
attr.set_post_ops(po);
}
if (binary_add_) {
dnnl::post_ops po;
vector<int64_t> post_shape = post_->shape();
vector<int64_t> post_stride = GetStrides(post_shape);
memory::desc binary_md = memory::desc(
post_shape, type2mem[post_->dtype()], post_stride);
po.append_binary(algorithm::binary_add, binary_md);
attr.set_post_ops(po);
binary_m_ = memory(binary_md, eng_);
}
matmul_pd_ = dnnl::matmul::primitive_desc(matmul_d, attr, eng_);
// 2.4 Prepare primitive objects (cached)
matmul_p_ = dnnl::matmul(matmul_pd_);
// 2.5 Prepare memory objects (cached)
src0_m_ = memory(src0_md, eng_);
src1_m_ = memory(src1_md, eng_);
dst_m_ = memory(dst_md, eng_);
if (has_bias) {
bias_m_ = memory(bias_md, eng_, const_cast<void*>(bias_->data()));
memory any_bias_m = bias_m_;
if (matmul_pd_.bias_desc() != bias_m_.get_desc()) {
any_bias_m = memory(matmul_pd_.bias_desc(), eng_);
dnnl::reorder(bias_m_, any_bias_m).execute(eng_stream_, bias_m_, any_bias_m);
}
memory_args_[DNNL_ARG_BIAS] = any_bias_m;
}
}
// 2. inference kernel(for int8 and f32)
void MatmulOperator::Forward(const vector<Tensor*>& input, const vector<Tensor*>& output) {
// 0. Alias variables part
const auto& src0_data = src0_->data();
const auto& src1_data = src1_->data();
// when change data value please use mutable_data
if (post_ != nullptr && !binary_add_) {
void* post_ptr = post_->mutable_data();
post_->unref_data(true);
dst_->set_data(post_ptr);
}
auto dst_data = dst_->mutable_data();
// 1. Prepare memory objects with data_ptr
src0_m_.set_data_handle(const_cast<void*>(src0_data), eng_stream_);
src1_m_.set_data_handle(const_cast<void*>(src1_data), eng_stream_);
dst_m_.set_data_handle(reinterpret_cast<void*>(dst_data), eng_stream_);
memory any_src0_m = src0_m_;
memory any_src1_m = src1_m_;
memory any_dst_m = dst_m_;
// 2. Reorder the data when the primitive memory and user memory are different
if (matmul_pd_.src_desc() != src0_m_.get_desc()) {
any_src0_m = memory(matmul_pd_.src_desc(), eng_);
dnnl::reorder(src0_m_, any_src0_m).execute(eng_stream_, src0_m_, any_src0_m);
}
if (matmul_pd_.weights_desc() != src1_m_.get_desc()) {
any_src1_m = memory(matmul_pd_.weights_desc(), eng_);
dnnl::reorder(src1_m_, any_src1_m).execute(eng_stream_, src1_m_, any_src1_m);
}
if (matmul_pd_.dst_desc() != dst_m_.get_desc()) {
any_dst_m = memory(matmul_pd_.dst_desc(), eng_);
}
// 3. Insert memory args
memory_args_[DNNL_ARG_SRC_0] = any_src0_m;
memory_args_[DNNL_ARG_WEIGHTS] = any_src1_m;
memory_args_[DNNL_ARG_DST] = any_dst_m;
if (binary_add_) {
void* post_ptr = post_->mutable_data();
binary_m_.set_data_handle(reinterpret_cast<void*>(post_ptr), eng_stream_);
memory_args_[DNNL_ARG_ATTR_MULTIPLE_POST_OP(0) | DNNL_ARG_SRC_1] = binary_m_;
}
// 4. Execute the primitive
matmul_p_.execute(eng_stream_, memory_args_);
// 5. Reorder the data of dst memory (When it is format_any)
if (matmul_pd_.dst_desc() != dst_m_.get_desc()) {
dnnl::reorder(any_dst_m, dst_m_).execute(eng_stream_, any_dst_m, dst_m_);
}
// 6. unref tensors
this->unref_tensors(input);
}
REGISTER_OPERATOR_CLASS(Matmul);
} // namespace executor
| 36.224274 | 97 | 0.642946 | [
"shape",
"vector"
] |
611a5feb77d50db77c8edcefe0b7b134ba18c002 | 31,003 | cpp | C++ | test/message/unpack.cpp | rfrandse/phosphor-host-ipmid-1 | 152e98cd339f3df58d5832af5779eff541f0adc5 | [
"Apache-2.0"
] | null | null | null | test/message/unpack.cpp | rfrandse/phosphor-host-ipmid-1 | 152e98cd339f3df58d5832af5779eff541f0adc5 | [
"Apache-2.0"
] | null | null | null | test/message/unpack.cpp | rfrandse/phosphor-host-ipmid-1 | 152e98cd339f3df58d5832af5779eff541f0adc5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright © 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ipmid/api.hpp>
#include <ipmid/message.hpp>
#include <gtest/gtest.h>
TEST(Uints, Uint8)
{
std::vector<uint8_t> i = {0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint8_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint8_t k = 0x04;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint8TooManyBytes)
{
std::vector<uint8_t> i = {0x04, 0x86};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint8_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint8_t k = 0x04;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint8InsufficientBytes)
{
std::vector<uint8_t> i = {};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint8_t v = 0;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(Uints, Uint16)
{
std::vector<uint8_t> i = {0x04, 0x86};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint16_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint16_t k = 0x8604;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint16TooManyBytes)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint16_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint16_t k = 0x8604;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint16InsufficientBytes)
{
std::vector<uint8_t> i = {0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint16_t v = 0;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(Uints, Uint32)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00, 0x02};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint32_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint32_t k = 0x02008604;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint32TooManyBytes)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00, 0x02, 0x44};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint32_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint32_t k = 0x02008604;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint32InsufficientBytes)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint32_t v = 0;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(Uints, Uint64)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00, 0x02, 0x44, 0x33, 0x22, 0x11};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint64_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint64_t k = 0x1122334402008604ull;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint64TooManyBytes)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00, 0x02, 0x44,
0x33, 0x22, 0x11, 0x55};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint64_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint64_t k = 0x1122334402008604ull;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Uints, Uint64InsufficientBytes)
{
std::vector<uint8_t> i = {0x04, 0x86, 0x00, 0x02, 0x44, 0x33, 0x22};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint64_t v = 0;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(Uints, Uint24)
{
std::vector<uint8_t> i = {0x58, 0x23, 0x11};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint24_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint24_t k = 0x112358;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(FixedInts, Uint24TooManyBytes)
{
std::vector<uint8_t> i = {0x58, 0x23, 0x11, 0x00};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint24_t v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint24_t k = 0x112358;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(FixedInts, Uint24InsufficientBytes)
{
std::vector<uint8_t> i = {0x58, 0x23};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint24_t v = 0;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(FixedInts, Uint3Uint5)
{
// individual bytes are unpacked low-order-bits first
// v1 will use [2:0], v2 will use [7:3]
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint3_t v1;
uint5_t v2;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint3_t k1 = 0x1;
uint5_t k2 = 0x19;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
}
TEST(FixedInts, Uint3Uint4TooManyBits)
{
// high order bit should not get unpacked
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint3_t v1;
uint4_t v2;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
uint3_t k1 = 0x1;
uint4_t k2 = 0x9;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
}
TEST(FixedInts, Uint3Uint6InsufficientBits)
{
// insufficient bits to unpack v2
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint3_t v1;
uint6_t v2;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v1, v2), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
uint3_t k1 = 0x1;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
// check that v2 is zero
ASSERT_EQ(v2, 0);
}
TEST(Bools, Boolx8)
{
// individual bytes are unpacked low-order-bits first
// [v8, v7, v6, v5, v4, v3, v2, v1]
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
bool v8, v7, v6, v5;
bool v4, v3, v2, v1;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2, v3, v4, v5, v6, v7, v8), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
// check that the bytes were correctly unpacked (LSB first)
bool k8 = true, k7 = true, k6 = false, k5 = false;
bool k4 = true, k3 = false, k2 = false, k1 = true;
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
ASSERT_EQ(v5, k5);
ASSERT_EQ(v6, k6);
ASSERT_EQ(v7, k7);
ASSERT_EQ(v8, k8);
}
TEST(Bools, Boolx8TooManyBits)
{
// high order bit should not get unpacked
// individual bytes are unpacked low-order-bits first
// [v7, v6, v5, v4, v3, v2, v1]
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
bool v7, v6, v5;
bool v4, v3, v2, v1;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2, v3, v4, v5, v6, v7), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
// check that the bytes were correctly unpacked (LSB first)
bool k7 = true, k6 = false, k5 = false;
bool k4 = true, k3 = false, k2 = false, k1 = true;
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
ASSERT_EQ(v5, k5);
ASSERT_EQ(v6, k6);
ASSERT_EQ(v7, k7);
}
TEST(Bools, Boolx8InsufficientBits)
{
// individual bytes are unpacked low-order-bits first
// [v8, v7, v6, v5, v4, v3, v2, v1]
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
bool v9;
bool v8, v7, v6, v5;
bool v4, v3, v2, v1;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v1, v2, v3, v4, v5, v6, v7, v8, v9), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
// check that the bytes were correctly unpacked (LSB first)
bool k8 = true, k7 = true, k6 = false, k5 = false;
bool k4 = true, k3 = false, k2 = false, k1 = true;
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
ASSERT_EQ(v5, k5);
ASSERT_EQ(v6, k6);
ASSERT_EQ(v7, k7);
ASSERT_EQ(v8, k8);
}
TEST(Bitsets, Bitset8)
{
// individual bytes are unpacked low-order-bits first
// a bitset for 8 bits fills the full byte
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<8> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::bitset<8> k(0xc9);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Bitsets, Bitset7TooManyBits)
{
// individual bytes are unpacked low-order-bits first
// a bitset for 8 bits fills the full byte
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<7> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<7> k(0x49);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Bitsets, Bitset9InsufficientBits)
{
// individual bytes are unpacked low-order-bits first
// a bitset for 8 bits fills the full byte
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<9> v;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<9> k(0);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Bitsets, Bitset3Bitset5)
{
// individual bytes are unpacked low-order-bits first
// v1 will use [2:0], v2 will use [7:3]
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<3> v1;
std::bitset<5> v2;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::bitset<3> k1(0x1);
std::bitset<5> k2(0x19);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
}
TEST(Bitsets, Bitset3Bitset4TooManyBits)
{
// high order bit should not get unpacked
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<3> v1;
std::bitset<4> v2;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<3> k1 = 0x1;
std::bitset<4> k2 = 0x9;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
}
TEST(Bitsets, Bitset3Bitset6InsufficientBits)
{
// insufficient bits to unpack v2
std::vector<uint8_t> i = {0xc9};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<3> v1;
std::bitset<6> v2;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v1, v2), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<3> k1 = 0x1;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
// check that v2 is zero
ASSERT_EQ(v2, 0);
}
TEST(Bitsets, Bitset32)
{
// individual bytes are unpacked low-order-bits first
// v1 will use 4 bytes, but in LSByte first order
// v1[7:0] v1[15:9] v1[23:16] v1[31:24]
std::vector<uint8_t> i = {0xb4, 0x86, 0x91, 0xc2};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<32> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::bitset<32> k(0xc29186b4);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Bitsets, Bitset31TooManyBits)
{
// high order bit should not get unpacked
std::vector<uint8_t> i = {0xb4, 0x86, 0x91, 0xc2};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<31> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<31> k(0x429186b4);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(Bitsets, Bitset33InsufficientBits)
{
// insufficient bits to unpack v2
std::vector<uint8_t> i = {0xb4, 0x86, 0x91, 0xc2};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::bitset<33> v;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked (comprehends unpack errors)
ASSERT_FALSE(p.fullyUnpacked());
std::bitset<33> k(0);
// check that v is zero
ASSERT_EQ(v, 0);
}
TEST(Arrays, Array4xUint8)
{
// an array of bytes will be read verbatim, low-order element first
std::vector<uint8_t> i = {0x02, 0x00, 0x86, 0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint8_t, 4> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::array<uint8_t, 4> k = {{0x02, 0x00, 0x86, 0x04}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Arrays, Array4xUint8TooManyBytes)
{
// last byte should not get unpacked
// an array of bytes will be read verbatim, low-order element first
std::vector<uint8_t> i = {0x02, 0x00, 0x86, 0x04, 0x22};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint8_t, 4> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::array<uint8_t, 4> k = {{0x02, 0x00, 0x86, 0x04}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Arrays, Array4xUint8InsufficientBytes)
{
// last byte should not get unpacked
// an array of bytes will be read verbatim, low-order element first
std::vector<uint8_t> i = {0x02, 0x00, 0x86};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint8_t, 4> v;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
// arrays of uint8_t will be unpacked all at once
// so nothing will get unpacked
std::array<uint8_t, 4> k = {{0, 0, 0, 0}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Arrays, Array4xUint32)
{
// an array of multi-byte values will be unpacked in order low-order
// element first, each multi-byte element in LSByte order
// v[0][7:0] v[0][15:9] v[0][23:16] v[0][31:24]
// v[1][7:0] v[1][15:9] v[1][23:16] v[1][31:24]
// v[2][7:0] v[2][15:9] v[2][23:16] v[2][31:24]
// v[3][7:0] v[3][15:9] v[3][23:16] v[3][31:24]
std::vector<uint8_t> i = {0x44, 0x33, 0x22, 0x11, 0x88, 0x66, 0x44, 0x22,
0x99, 0x77, 0x55, 0x33, 0x78, 0x56, 0x34, 0x12};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint32_t, 4> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::array<uint32_t, 4> k = {
{0x11223344, 0x22446688, 0x33557799, 0x12345678}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Arrays, Array4xUint32TooManyBytes)
{
// last byte should not get unpacked
// an array of multi-byte values will be unpacked in order low-order
// element first, each multi-byte element in LSByte order
// v[0][7:0] v[0][15:9] v[0][23:16] v[0][31:24]
// v[1][7:0] v[1][15:9] v[1][23:16] v[1][31:24]
// v[2][7:0] v[2][15:9] v[2][23:16] v[2][31:24]
// v[3][7:0] v[3][15:9] v[3][23:16] v[3][31:24]
std::vector<uint8_t> i = {0x44, 0x33, 0x22, 0x11, 0x88, 0x66,
0x44, 0x22, 0x99, 0x77, 0x55, 0x33,
0x78, 0x56, 0x34, 0x12, 0xaa};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint32_t, 4> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::array<uint32_t, 4> k = {
{0x11223344, 0x22446688, 0x33557799, 0x12345678}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Arrays, Array4xUint32InsufficientBytes)
{
// last value should not get unpacked
// an array of multi-byte values will be unpacked in order low-order
// element first, each multi-byte element in LSByte order
// v[0][7:0] v[0][15:9] v[0][23:16] v[0][31:24]
// v[1][7:0] v[1][15:9] v[1][23:16] v[1][31:24]
// v[2][7:0] v[2][15:9] v[2][23:16] v[2][31:24]
// v[3][7:0] v[3][15:9] v[3][23:16] v[3][31:24]
std::vector<uint8_t> i = {0x44, 0x33, 0x22, 0x11, 0x88, 0x66, 0x44, 0x22,
0x99, 0x77, 0x55, 0x33, 0x78, 0x56, 0x34};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::array<uint32_t, 4> v;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
// arrays of uint32_t will be unpacked in a way that looks atomic
std::array<uint32_t, 4> k = {{0, 0, 0, 0}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Vectors, VectorUint32)
{
// a vector of multi-byte values will be unpacked in order low-order
// element first, each multi-byte element in LSByte order
// v[0][7:0] v[0][15:9] v[0][23:16] v[0][31:24]
// v[1][7:0] v[1][15:9] v[1][23:16] v[1][31:24]
// v[2][7:0] v[2][15:9] v[2][23:16] v[2][31:24]
// v[3][7:0] v[3][15:9] v[3][23:16] v[3][31:24]
std::vector<uint8_t> i = {0x44, 0x33, 0x22, 0x11, 0x88, 0x66, 0x44, 0x22,
0x99, 0x77, 0x55, 0x33, 0x78, 0x56, 0x34, 0x12};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::vector<uint32_t> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::vector<uint32_t> k = {0x11223344, 0x22446688, 0x33557799, 0x12345678};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
// combination of TooManyBytes and InsufficientBytes because
// vectors will attempt to unpack full <T>s until the end of the input
TEST(Vectors, VectorUint32NonIntegralBytes)
{
// last value should not get unpacked
// a vector of multi-byte values will be unpacked in order low-order
// element first, each multi-byte element in LSByte order,
// and will attempt to consume all bytes remaining
// v[0][7:0] v[0][15:9] v[0][23:16] v[0][31:24]
// v[1][7:0] v[1][15:9] v[1][23:16] v[1][31:24]
// v[2][7:0] v[2][15:9] v[2][23:16] v[2][31:24]
// v[3][7:0] v[3][15:9] v[3][23:16] v[3][31:24]
std::vector<uint8_t> i = {0x44, 0x33, 0x22, 0x11, 0x88, 0x66, 0x44, 0x22,
0x99, 0x77, 0x55, 0x33, 0x78, 0x56, 0x34};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::vector<uint32_t> v;
// check that the number of bytes matches
ASSERT_NE(p.unpack(v), 0);
// check that the payload was not fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
// arrays of uint32_t will be unpacked one at a time, so the
// last entry should not get unpacked properly
std::vector<uint32_t> k = {0x11223344, 0x22446688, 0x33557799};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(Vectors, VectorUint8)
{
// a vector of bytes will be unpacked verbatim, low-order element first
std::vector<uint8_t> i = {0x02, 0x00, 0x86, 0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::vector<uint8_t> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::vector<uint8_t> k = {0x02, 0x00, 0x86, 0x04};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
// Cannot test TooManyBytes or InsufficientBytes for vector<uint8_t>
// because it will always unpack whatever bytes are remaining
// TEST(Vectors, VectorUint8TooManyBytes) {}
// TEST(Vectors, VectorUint8InsufficientBytes) {}
TEST(UnpackAdvanced, OptionalOk)
{
// a vector of bytes will be unpacked verbatim, low-order element first
std::vector<uint8_t> i = {0xbe, 0x02, 0x00, 0x86, 0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::optional<std::tuple<uint8_t, uint32_t>> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
std::optional<std::tuple<uint8_t, uint32_t>> k{{0xbe, 0x04860002}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(UnpackAdvanced, OptionalInsufficientBytes)
{
// a vector of bytes will be unpacked verbatim, low-order element first
std::vector<uint8_t> i = {0x02, 0x00, 0x86, 0x04};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
std::optional<std::tuple<uint8_t, uint32_t>> v;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_FALSE(p.fullyUnpacked());
std::optional<std::tuple<uint8_t, uint32_t>> k = {{0, 0}};
// check that the bytes were correctly unpacked (in byte order)
ASSERT_EQ(v, k);
}
TEST(UnpackAdvanced, Uints)
{
// all elements will be unpacked in order, with each multi-byte
// element being processed LSByte first
// v1[7:0] v2[7:0] v2[15:8] v3[7:0] v3[15:8] v3[23:16] v3[31:24]
// v4[7:0] v4[15:8] v4[23:16] v4[31:24]
// v4[39:25] v4[47:40] v4[55:48] v4[63:56]
std::vector<uint8_t> i = {0x02, 0x04, 0x06, 0x11, 0x22, 0x33, 0x44, 0x55,
0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint8_t v1;
uint16_t v2;
uint32_t v3;
uint64_t v4;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2, v3, v4), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint8_t k1 = 0x02;
uint16_t k2 = 0x0604;
uint32_t k3 = 0x44332211;
uint64_t k4 = 0xccbbaa9988776655ull;
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
}
TEST(UnpackAdvanced, TupleInts)
{
// all elements will be unpacked in order, with each multi-byte
// element being processed LSByte first
// v1[7:0] v2[7:0] v2[15:8] v3[7:0] v3[15:8] v3[23:16] v3[31:24]
// v4[7:0] v4[15:8] v4[23:16] v4[31:24]
// v4[39:25] v4[47:40] v4[55:48] v4[63:56]
std::vector<uint8_t> i = {0x02, 0x04, 0x06, 0x11, 0x22, 0x33, 0x44, 0x55,
0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint8_t v1;
uint16_t v2;
uint32_t v3;
uint64_t v4;
auto v = std::make_tuple(v1, v2, v3, v4);
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint8_t k1 = 0x02;
uint16_t k2 = 0x0604;
uint32_t k3 = 0x44332211;
uint64_t k4 = 0xccbbaa9988776655ull;
auto k = std::make_tuple(k1, k2, k3, k4);
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v, k);
}
TEST(UnpackAdvanced, BoolsnBitfieldsnFixedIntsOhMy)
{
// each element will be unpacked, filling the low-order bits first
// with multi-byte values getting unpacked LSByte first
// v1 will use k[0][1:0]
// v2 will use k[0][2]
// v3[4:0] will use k[0][7:3], v3[6:5] will use k[1][1:0]
// v4 will use k[1][2]
// v5 will use k[1][7:3]
std::vector<uint8_t> i = {0x9e, 0xdb};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint2_t v1;
bool v2;
std::bitset<7> v3;
bool v4;
uint5_t v5;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2, v3, v4, v5), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint2_t k1 = 2; // binary 0b10
bool k2 = true; // binary 0b1
std::bitset<7> k3(0x73); // binary 0b1110011
bool k4 = false; // binary 0b0
uint5_t k5 = 27; // binary 0b11011
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
ASSERT_EQ(v5, k5);
}
TEST(UnpackAdvanced, UnalignedBitUnpacking)
{
// unaligned multi-byte values will be unpacked the same as
// other bits, effectively reading from a large value, low-order
// bits first, then consuming the stream LSByte first
// v1 will use k[0][1:0]
// v2[5:0] will use k[0][7:2], v2[7:6] will use k[1][1:0]
// v3 will use k[1][2]
// v4[4:0] will use k[1][7:3] v4[12:5] will use k[2][7:0]
// v4[15:13] will use k[3][2:0]
// v5 will use k[3][3]
// v6[3:0] will use k[3][7:0] v6[11:4] will use k[4][7:0]
// v6[19:12] will use k[5][7:0] v6[27:20] will use k[6][7:0]
// v6[31:28] will use k[7][3:0]
// v7 will use k[7][7:4]
std::vector<uint8_t> i = {0x96, 0xd2, 0x2a, 0xcd, 0xd3, 0x3b, 0xbc, 0x9d};
ipmi::message::Payload p(std::forward<std::vector<uint8_t>>(i));
uint2_t v1;
uint8_t v2;
bool v3;
uint16_t v4;
bool v5;
uint32_t v6;
uint4_t v7;
// check that the number of bytes matches
ASSERT_EQ(p.unpack(v1, v2, v3, v4, v5, v6, v7), 0);
// check that the payload was fully unpacked
ASSERT_TRUE(p.fullyUnpacked());
uint2_t k1 = 2; // binary 0b10
uint8_t k2 = 0xa5; // binary 0b10100101
bool k3 = false; // binary 0b0
uint16_t k4 = 0xa55a; // binary 0b1010010101011010
bool k5 = true; // binary 0b1
uint32_t k6 = 0xdbc3bd3c; // binary 0b11011011110000111011110100111100
uint4_t k7 = 9; // binary 0b1001
// check that the bytes were correctly unpacked (LSB first)
ASSERT_EQ(v1, k1);
ASSERT_EQ(v2, k2);
ASSERT_EQ(v3, k3);
ASSERT_EQ(v4, k4);
ASSERT_EQ(v5, k5);
ASSERT_EQ(v6, k6);
ASSERT_EQ(v7, k7);
}
| 36.134033 | 80 | 0.640132 | [
"vector"
] |
611b2de8cc9b9b18d71d4196b2800062570df680 | 2,156 | cc | C++ | ui/compositor/test/layer_animator_test_controller.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | ui/compositor/test/layer_animator_test_controller.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | ui/compositor/test/layer_animator_test_controller.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.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 <stddef.h>
#include "cc/animation/animation.h"
#include "cc/animation/animation_events.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/test/layer_animator_test_controller.h"
#include "ui/gfx/geometry/rect.h"
namespace ui {
LayerAnimatorTestController::LayerAnimatorTestController(
scoped_refptr<LayerAnimator> animator)
: animator_(animator) {
}
LayerAnimatorTestController::~LayerAnimatorTestController() {
}
LayerAnimationSequence* LayerAnimatorTestController::GetRunningSequence(
LayerAnimationElement::AnimatableProperty property) {
LayerAnimator::RunningAnimation* running_animation =
animator_->GetRunningAnimation(property);
if (running_animation)
return running_animation->sequence();
else
return NULL;
}
void LayerAnimatorTestController::StartThreadedAnimationsIfNeeded() {
std::vector<cc::TargetProperty::Type> threaded_properties;
threaded_properties.push_back(cc::TargetProperty::OPACITY);
threaded_properties.push_back(cc::TargetProperty::TRANSFORM);
for (size_t i = 0; i < threaded_properties.size(); i++) {
LayerAnimationElement::AnimatableProperty animatable_property =
LayerAnimationElement::ToAnimatableProperty(threaded_properties[i]);
LayerAnimationSequence* sequence = GetRunningSequence(animatable_property);
if (!sequence)
continue;
LayerAnimationElement* element = sequence->CurrentElement();
if (!(element->properties() & animatable_property))
continue;
if (!element->Started() ||
element->effective_start_time() != base::TimeTicks())
continue;
animator_->OnThreadedAnimationStarted(base::TimeTicks::Now(),
threaded_properties[i],
element->animation_group_id());
}
}
void LayerAnimatorTestController::Step(const base::TimeDelta& duration) {
animator_->Step(animator_->last_step_time() + duration);
}
} // namespace ui
| 33.6875 | 79 | 0.733766 | [
"geometry",
"vector",
"transform"
] |
611ec98a3ebb4f0f495992b49c1ca9f1b8060c91 | 110 | hpp | C++ | src/applications/utilities/mesh/manipulation/checkMesh/printMeshStats.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/mesh/manipulation/checkMesh/printMeshStats.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/utilities/mesh/manipulation/checkMesh/printMeshStats.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | namespace CML
{
class polyMesh;
void printMeshStats(const polyMesh& mesh, const bool allTopology);
}
| 15.714286 | 70 | 0.727273 | [
"mesh"
] |
6122b2c892ba7aaf92ad7bae5909075c7a879c90 | 1,375 | cpp | C++ | backend/src/utility/Functional.cpp | tomix86/hpcpm | 9fa8341249deb8c5689d0f3743f9b76d46b2dd69 | [
"MIT"
] | 2 | 2017-09-05T15:49:36.000Z | 2019-08-05T05:04:01.000Z | backend/src/utility/Functional.cpp | tomix86/hpcpm | 9fa8341249deb8c5689d0f3743f9b76d46b2dd69 | [
"MIT"
] | null | null | null | backend/src/utility/Functional.cpp | tomix86/hpcpm | 9fa8341249deb8c5689d0f3743f9b76d46b2dd69 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <boost/tokenizer.hpp>
#include "Exceptions.hpp"
#include "Functional.hpp"
namespace utility {
bool toBool( std::string str ) {
std::transform( str.begin(), str.end(), str.begin(), ::tolower );
if ( str != "true" && str != "false" ) {
throw utility::InvalidArgument( "toBool", "invalid argument: " + str );
}
return str == "true" ? true : false;
}
std::string toString( bool b ) {
return b ? "true" : "false";
}
int tryParseInt( std::string value, int minLegalValue, int maxLegalValue ) {
try {
auto val = std::stoi( value );
if ( val < minLegalValue || val > maxLegalValue ) {
throw utility::InvalidArgument( "tryParseInt", "Value out of legal range: " + value );
}
return val;
}
catch ( std::out_of_range ) {
throw utility::InvalidArgument( "tryParseInt", "Value out of legal range: " + value );
}
catch ( std::invalid_argument ) {
throw utility::InvalidArgument( "tryParseInt", "Invalid value: " + value );
}
}
std::vector<std::string> tokenizeString( std::string input, char separator ) {
boost::char_separator<char> sep( &separator );
boost::tokenizer<boost::char_separator<char> > tokenizer( input, sep );
std::vector<std::string> tokens;
for( auto token : tokenizer ) {
tokens.push_back( token );
}
return tokens;
}
} // namespace utility
| 25.943396 | 90 | 0.638545 | [
"vector",
"transform"
] |
6129b1d5a004a18d3e858c24bf7605dbf7e7650b | 1,679 | hpp | C++ | include/dish2/config/setup.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 29 | 2019-02-04T02:39:52.000Z | 2022-01-28T10:06:26.000Z | include/dish2/config/setup.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 95 | 2020-02-22T19:48:14.000Z | 2021-09-14T19:17:53.000Z | include/dish2/config/setup.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 6 | 2019-11-19T10:13:09.000Z | 2021-03-25T17:35:32.000Z | #pragma once
#ifndef DISH2_CONFIG_SETUP_HPP_INCLUDE
#define DISH2_CONFIG_SETUP_HPP_INCLUDE
#include <limits>
#include <string>
#include "../../../third-party/conduit/include/uitsl/mpi/comm_utils.hpp"
#include "../../../third-party/conduit/include/uitsl/mpi/mpi_flex_guard.hpp"
#include "../../../third-party/Empirical/include/emp/base/vector.hpp"
#include "../../../third-party/Empirical/include/emp/config/ArgManager.hpp"
#include "../run/setup_thread_local_random.hpp"
#include "dump_config_csv.hpp"
#include "dump_config.hpp"
#include "print_assets.hpp"
#include "print_config.hpp"
#include "print_extrospective_states.hpp"
#include "print_introspective_states.hpp"
#include "print_pwd.hpp"
#include "print_readable_states.hpp"
#include "print_writable_states.hpp"
#include "setup_assets.hpp"
#include "setup_config.hpp"
namespace dish2 {
template< typename Spec >
void setup( emp::ArgManager arg_manager ) {
if (
(arg_manager.ViewArg("N_THREADS").empty() && dish2::cfg.N_THREADS() == 1)
|| arg_manager.ViewArg("N_THREADS").back() == emp::vector<std::string>{"1"}
) uitsl::mpi_flex_guard.InitSingleThread();
else uitsl::mpi_flex_guard.InitMultithread();
setup_assets( arg_manager );
setup_config( arg_manager );
if ( uitsl::is_root() ) {
print_pwd();
print_assets();
print_config();
print_extrospective_states<Spec>();
print_introspective_states<Spec>();
print_readable_states<Spec>();
print_writable_states<Spec>();
}
dump_config();
dump_config_csv();
// setup main thread thread local random
dish2::setup_thread_local_random();
}
} // namespace dish2
#endif // #ifndef DISH2_CONFIG_SETUP_HPP_INCLUDE
| 26.650794 | 79 | 0.734366 | [
"vector"
] |
612a8725a6bccaf11eb6a8ff42d801eba25b29d9 | 20,719 | cc | C++ | tensorflow/compiler/mlir/quantization/tensorflow/passes/quantize_composite_functions.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | 1 | 2022-03-20T04:34:49.000Z | 2022-03-20T04:34:49.000Z | tensorflow/compiler/mlir/quantization/tensorflow/passes/quantize_composite_functions.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/quantization/tensorflow/passes/quantize_composite_functions.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/Quant/QuantOps.h" // from @llvm-project
#include "mlir/Dialect/Quant/QuantTypes.h" // from @llvm-project
#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/IR/Location.h" // from @llvm-project
#include "mlir/IR/OperationSupport.h" // from @llvm-project
#include "mlir/IR/PatternMatch.h" // from @llvm-project
#include "mlir/IR/Verifier.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/quantization/tensorflow/passes/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_dialect.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace quant {
namespace {
constexpr char kQuantizeFuncName[] = "quantize_i8";
constexpr char kDequantizeFuncName[] = "dequantize_i8";
constexpr char kAttrMapAttribute[] = "attr_map";
class QuantizeCompositeFunctionsPass
: public mlir::PassWrapper<QuantizeCompositeFunctionsPass,
OperationPass<ModuleOp>> {
public:
explicit QuantizeCompositeFunctionsPass() {}
StringRef getArgument() const final {
// This is the argument used to refer to the pass in
// the textual format (on the commandline for example).
return "quant-quantize-composite-functions";
}
StringRef getDescription() const final {
// This is a brief description of the pass.
return "Quantize composite functions with QDQ input/outputs.";
}
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<TF::TensorFlowDialect, QuantizationDialect>();
}
private:
void runOnOperation() override;
};
LogicalResult CreateUniformQuantizedTypeParams(UniformQuantizedType qtype,
Location loc,
PatternRewriter& rewriter,
Value& scale,
Value& zero_point) {
TensorType scale_type = RankedTensorType::get({}, rewriter.getF32Type());
TensorType zero_point_type = scale_type.clone(rewriter.getI32Type());
scale = rewriter.create<TF::ConstOp>(
loc, scale_type,
DenseFPElementsAttr::get(scale_type,
{static_cast<float>(qtype.getScale())}));
zero_point = rewriter.create<TF::ConstOp>(
loc, zero_point_type,
DenseIntElementsAttr::get(zero_point_type,
{static_cast<int32_t>(qtype.getZeroPoint())}));
return success(scale && zero_point);
}
LogicalResult CreateUniformQuantizedPerAxisTypeParams(
UniformQuantizedPerAxisType qtype, Location loc, PatternRewriter& rewriter,
Value& scale, Value& zero_point) {
// Consuming op should already know about Quantized channel information,
// so not passing it during conversion. This design might change if needed.
ArrayRef<double> scales = qtype.getScales();
ArrayRef<int64_t> zero_points = qtype.getZeroPoints();
const int num_channels = scales.size();
TensorType scale_type = RankedTensorType::get(
{static_cast<int64_t>(num_channels)}, rewriter.getF32Type());
TensorType zero_point_type = scale_type.clone(rewriter.getI32Type());
llvm::SmallVector<float, 4> float_scales;
llvm::SmallVector<int32_t, 4> int32_zero_points;
float_scales.reserve(num_channels);
int32_zero_points.reserve(num_channels);
for (int i = 0; i < num_channels; ++i) {
float_scales.push_back(scales[i]);
int32_zero_points.push_back(zero_points[i]);
}
scale = rewriter.create<TF::ConstOp>(
loc, scale_type, DenseFPElementsAttr::get(scale_type, float_scales));
zero_point = rewriter.create<TF::ConstOp>(
loc, zero_point_type,
DenseIntElementsAttr::get(zero_point_type, int32_zero_points));
return success(scale && zero_point);
}
LogicalResult CreateQuantizationParams(QuantizedType elem_type, Location loc,
PatternRewriter& rewriter, Value& scale,
Value& zero_point) {
if (!elem_type) {
return failure();
}
if (auto qtype = elem_type.dyn_cast<UniformQuantizedType>()) {
return CreateUniformQuantizedTypeParams(qtype, loc, rewriter, scale,
zero_point);
} else if (auto qtype = elem_type.dyn_cast<UniformQuantizedPerAxisType>()) {
return CreateUniformQuantizedPerAxisTypeParams(qtype, loc, rewriter, scale,
zero_point);
}
return failure();
}
// Replaces quant.qcast op to composite quantize_i8 function.
class ReplaceQuantizePattern : public mlir::OpRewritePattern<QuantizeCastOp> {
public:
explicit ReplaceQuantizePattern(MLIRContext* context)
: OpRewritePattern<QuantizeCastOp>(context) {}
private:
LogicalResult matchAndRewrite(QuantizeCastOp q_op,
PatternRewriter& rewriter) const override {
auto output_type = q_op.getType().cast<TensorType>();
auto elem_type = output_type.getElementType().dyn_cast<QuantizedType>();
const Location loc = q_op->getLoc();
Value scale, zero_point;
if (failed(CreateQuantizationParams(elem_type, loc, rewriter, scale,
zero_point))) {
return failure();
}
SmallVector<Type> output_types = {
output_type.clone(elem_type.getStorageType())};
SmallVector<Value> args = {q_op.arg(), scale, zero_point};
FlatSymbolRefAttr func_name =
FlatSymbolRefAttr::get(rewriter.getStringAttr(kQuantizeFuncName));
auto quantize_call = rewriter.create<TF::PartitionedCallOp>(
loc, output_types, args, func_name,
/*config=*/"", /*config_proto=*/"", /*executor_type=*/"");
auto scast_op = rewriter.create<quant::StorageCastOp>(
loc, output_type, quantize_call->getResult(0));
q_op->replaceAllUsesWith(scast_op);
return success();
}
};
// Replaces quant.dcast op to composite dequantize_i8 function.
class ReplaceDequantizePattern
: public mlir::OpRewritePattern<DequantizeCastOp> {
public:
explicit ReplaceDequantizePattern(MLIRContext* context)
: OpRewritePattern<DequantizeCastOp>(context) {}
private:
LogicalResult matchAndRewrite(DequantizeCastOp dq_op,
PatternRewriter& rewriter) const override {
auto input_type = dq_op.arg().getType().cast<TensorType>();
auto elem_type = input_type.getElementType().dyn_cast<QuantizedType>();
const Location loc = dq_op->getLoc();
Value scale, zero_point;
if (failed(CreateQuantizationParams(elem_type, loc, rewriter, scale,
zero_point))) {
return failure();
}
TensorType output_type = input_type.clone(elem_type.getStorageType());
auto scast_op =
rewriter.create<quant::StorageCastOp>(loc, output_type, dq_op.arg());
FlatSymbolRefAttr func_name =
FlatSymbolRefAttr::get(rewriter.getStringAttr(kDequantizeFuncName));
SmallVector<Value> args = {scast_op->getResult(0), scale, zero_point};
auto dequantize_call = rewriter.create<TF::PartitionedCallOp>(
loc, dq_op.getResult().getType(), args, func_name,
/*config=*/"", /*config_proto=*/"", /*executor_type=*/"");
dq_op->replaceAllUsesWith(dequantize_call);
return success();
}
};
// Determines if all float input/outputs are now quantized.
bool IsQuantizedCall(TF::PartitionedCallOp call_op) {
bool has_quantized_types = false;
for (Value input : call_op.args()) {
if (auto type = input.getType().dyn_cast<TensorType>()) {
if (type.getElementType().isa<FloatType>()) {
return false;
}
if (type.getElementType().isa<QuantizedType>()) {
has_quantized_types = true;
}
}
}
for (Value output : call_op.output()) {
if (auto type = output.getType().dyn_cast<TensorType>()) {
if (type.getElementType().isa<FloatType>()) {
return false;
}
if (type.getElementType().isa<QuantizedType>()) {
has_quantized_types = true;
}
}
}
return has_quantized_types;
}
// Transfers the attributes of the corresponding ops from the float function to
// the quantized function using the attr_map attribute. In the quantized
// function, this map (map1) is in {attr_name_1: attr_identifier} format; and in
// the float function, this map (map2) is in {attr_identifier: attr_name_2}
// format. Where, the attribute identifiers should match between two maps,
// attr_name_1 is the name of the of the attribute needs to be set in the
// quantized function, attr_name_2 is the name of the attribute corresponding to
// the attribute identifier in the float function.
LogicalResult TransferAttributes(FuncOp float_func, FuncOp quantized_func) {
// A map to find an attribute from its identifier.
llvm::StringMap<Attribute> identifier_to_attr;
for (Operation& inner_op : float_func.getBody().front().getOperations()) {
if (!inner_op.hasAttr(kAttrMapAttribute)) continue;
std::string attr_map_str =
inner_op.getAttrOfType<StringAttr>(kAttrMapAttribute).str();
for (absl::string_view element_str : absl::StrSplit(attr_map_str, ',')) {
std::vector<absl::string_view> key_and_value_pair =
absl::StrSplit(element_str, ':');
if (key_and_value_pair.size() != 2) {
float_func.emitError("The attr_map attribute is malformed");
return failure();
}
identifier_to_attr.insert(
{llvm::StringRef(std::string(key_and_value_pair[0])),
inner_op.getAttr(
llvm::StringRef(std::string(key_and_value_pair[1])))});
}
}
// Set the attributes for ops with the attr_map attribute.
for (Operation& inner_op : quantized_func.getBody().front().getOperations()) {
if (!inner_op.hasAttr(kAttrMapAttribute)) continue;
std::string attr_map_str =
inner_op.getAttrOfType<StringAttr>(kAttrMapAttribute).str();
for (absl::string_view element_str : absl::StrSplit(attr_map_str, ',')) {
std::vector<absl::string_view> key_and_value_pair =
absl::StrSplit(element_str, ':');
if (key_and_value_pair.size() != 2) {
float_func.emitError("The attr_map attribute is malformed");
return failure();
}
if (identifier_to_attr.count(
llvm::StringRef(std::string(key_and_value_pair[1]))) == 0) {
float_func.emitWarning(absl::StrCat("Using the default value for the '",
key_and_value_pair[0],
"' attribute"));
continue;
}
inner_op.setAttr(llvm::StringRef(std::string(key_and_value_pair[0])),
identifier_to_attr[llvm::StringRef(
std::string(key_and_value_pair[1]))]);
}
inner_op.removeAttr(kAttrMapAttribute);
}
return success();
}
// Unwraps quantization parameters of PartitionedCall ops with quantized
// input/outputs that are created from QuantizePass.
class QuantizeFunctionPattern
: public mlir::OpRewritePattern<TF::PartitionedCallOp> {
public:
explicit QuantizeFunctionPattern(MLIRContext* context)
: OpRewritePattern<TF::PartitionedCallOp>(context) {}
private:
LogicalResult matchAndRewrite(TF::PartitionedCallOp call_op,
PatternRewriter& rewriter) const override {
auto f_attr = call_op.fAttr().dyn_cast<FlatSymbolRefAttr>();
// removeAttr will return nullptr if no attribute was removed.
if (!call_op->removeAttr(kQuantTraitAttrName) || !f_attr) {
return failure();
}
if (!f_attr.getValue().startswith("fused_") || !IsQuantizedCall(call_op)) {
return failure();
}
llvm::Twine quantized_function_name = llvm::Twine(
"quantized_", f_attr.getValue().substr(6).rsplit('_').first);
SmallVector<Value, 4> args;
SmallVector<Value, 4> qparam_args;
SmallVector<Type, 4> result_types;
for (Value arg : call_op.args()) {
if (auto arg_type = arg.getType().dyn_cast<TensorType>()) {
QuantizedType qtype =
arg_type.getElementType().dyn_cast<QuantizedType>();
if (qtype &&
!qtype.isa<UniformQuantizedType, UniformQuantizedPerAxisType>()) {
return failure();
}
}
}
for (Value result : call_op->getResults()) {
if (auto result_type = result.getType().dyn_cast<TensorType>()) {
QuantizedType qtype =
result_type.getElementType().dyn_cast<QuantizedType>();
if (qtype &&
!qtype.isa<UniformQuantizedType, UniformQuantizedPerAxisType>()) {
return failure();
}
}
}
rewriter.setInsertionPoint(call_op);
for (Value arg : call_op.args()) {
TensorType arg_type = arg.getType().dyn_cast<TensorType>();
if (!arg_type) {
args.push_back(arg);
continue;
}
QuantizedType qtype = arg_type.getElementType().dyn_cast<QuantizedType>();
if (!qtype) {
args.push_back(arg);
continue;
}
Value scale, zero_point;
if (failed(CreateQuantizationParams(qtype, arg.getLoc(), rewriter, scale,
zero_point))) {
// As the quantized types are already checked, this is unexpected.
call_op->emitError(
"Failed to create quantization parameter for an argument.");
return failure();
}
auto scast_op = rewriter.create<StorageCastOp>(
arg.getLoc(), arg_type.clone(qtype.getStorageType()), arg);
args.push_back(scast_op.getResult());
qparam_args.push_back(scale);
qparam_args.push_back(zero_point);
}
DenseMap<Value, StorageCastOp> replace_map;
rewriter.setInsertionPointAfter(call_op);
for (Value result : call_op->getResults()) {
TensorType result_type = result.getType().dyn_cast<TensorType>();
if (!result_type) {
result_types.push_back(result.getType());
continue;
}
QuantizedType qtype =
result_type.getElementType().dyn_cast<QuantizedType>();
if (!qtype) {
result_types.push_back(result_type);
continue;
}
Value scale, zero_point;
if (failed(CreateQuantizationParams(qtype, result.getLoc(), rewriter,
scale, zero_point))) {
// As the quantized types are already checked, this is unexpected.
call_op->emitError(
"Failed to create quantization parameter for a result.");
return failure();
}
auto scast_op =
rewriter.create<StorageCastOp>(call_op.getLoc(), result_type, result);
replace_map.insert(std::make_pair(result, scast_op));
result_types.push_back(result_type.clone(qtype.getStorageType()));
qparam_args.push_back(scale);
qparam_args.push_back(zero_point);
}
for (auto replace_pair : replace_map) {
Value result = replace_pair.first;
StorageCastOp scast_op = replace_pair.second;
result.replaceAllUsesExcept(scast_op, scast_op);
}
args.insert(args.end(), qparam_args.begin(), qparam_args.end());
// Make a copy of the quantized function.
auto module = call_op->getParentOfType<ModuleOp>();
SymbolTable symbol_table(module);
FuncOp float_func =
dyn_cast<FuncOp>(symbol_table.lookup(f_attr.getValue()));
FuncOp quantized_func =
dyn_cast<FuncOp>(symbol_table.lookup(quantized_function_name.str()));
rewriter.setInsertionPointAfter(float_func);
FuncOp new_quantized_func = dyn_cast<FuncOp>(quantized_func->clone());
if (new_quantized_func == nullptr) {
return failure();
}
StringAttr new_quant_func_name = symbol_table.insert(new_quantized_func);
// Set the attributes for ops with the attr_map attribute.
if (failed(TransferAttributes(float_func, new_quantized_func))) {
return failure();
}
rewriter.setInsertionPoint(call_op);
rewriter.replaceOpWithNewOp<TF::PartitionedCallOp>(
call_op, result_types, args,
FlatSymbolRefAttr::get(new_quant_func_name));
return success();
}
};
// Converts const -> quant.qcast pattern to quantized constant, after
// quantization parameters are safely included to each quantize composite
// functions.
class QuantizeConstPattern : public OpRewritePattern<QuantizeCastOp> {
public:
// This pattern should have larger benefit than ReplaceQuantizePattern
explicit QuantizeConstPattern(MLIRContext* context)
: OpRewritePattern<QuantizeCastOp>(context, /*benefit=*/10) {}
LogicalResult matchAndRewrite(QuantizeCastOp q_op,
PatternRewriter& rewriter) const override {
DenseFPElementsAttr attr;
if (!matchPattern(q_op.arg(), m_Constant(&attr))) {
return failure();
}
ShapedType tensor_qtype = q_op.getResult().getType().cast<ShapedType>();
Attribute quantized_attr;
quantized_attr = Quantize(attr, tensor_qtype);
if (!quantized_attr) {
return failure();
}
Type storage_type =
tensor_qtype.getElementType().cast<QuantizedType>().getStorageType();
ShapedType new_type = tensor_qtype.clone(storage_type);
Location loc = q_op.arg().getLoc();
auto const_op = rewriter.create<TF::ConstOp>(loc, new_type, quantized_attr);
// Add scast op to match quantize -> composition pattern. The added scast
// is then removed by canonicalization. ([scast - scast] -> [])
auto scast_op = rewriter.create<quant::StorageCastOp>(loc, tensor_qtype,
const_op.output());
q_op->replaceAllUsesWith(scast_op);
return success();
}
};
static PassRegistration<QuantizeCompositeFunctionsPass> pass;
#include "tensorflow/compiler/mlir/quantization/tensorflow/passes/quantize_composite_functions.inc"
void QuantizeCompositeFunctionsPass::runOnOperation() {
MLIRContext* ctx = &getContext();
ModuleOp module = getOperation();
PassManager pm(ctx);
// Intermediate output from QuantizePass will have PartitionedCall ops with
// quantized input and output types, which are not allowed in TF dialect.
// This can be removed when the composite call supports quantized types.
pm.enableVerifier(false);
pm.addNestedPass<FuncOp>(CreatePrepareQuantizePass());
pm.addNestedPass<FuncOp>(CreateQuantizePass());
pm.addNestedPass<FuncOp>(CreatePostQuantizePass());
if (failed(pm.run(module))) {
signalPassFailure();
}
RewritePatternSet patterns(ctx);
patterns.add<QuantizeFunctionPattern>(ctx);
if (failed(applyPatternsAndFoldGreedily(module, std::move(patterns)))) {
signalPassFailure();
}
// Constant quantization is a lossy transformation, so they are applied only
// after all the other patterns have been aplied.
RewritePatternSet patterns_2(ctx);
populateWithGenerated(patterns_2);
patterns_2.add<ReplaceQuantizePattern, ReplaceDequantizePattern,
QuantizeConstPattern>(ctx);
if (failed(applyPatternsAndFoldGreedily(module, std::move(patterns_2))) ||
failed(verify(module))) {
signalPassFailure();
}
}
} // namespace
std::unique_ptr<OperationPass<ModuleOp>>
CreateQuantizeCompositeFunctionsPass() {
return std::make_unique<QuantizeCompositeFunctionsPass>();
}
} // namespace quant
} // namespace mlir
| 39.921002 | 99 | 0.678942 | [
"vector"
] |
612b729f26cca56875e70208b1be3afbd7e9989b | 6,093 | hh | C++ | extra/europa/extensions/Trigonometry.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | extra/europa/extensions/Trigonometry.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | extra/europa/extensions/Trigonometry.hh | miatauro/trex2-agent | d896f8335f3194237a8bba49949e86f5488feddb | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, MBARI.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the TREX Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef H_trex_europa_Trigonometry
# define H_trex_europa_Trigonometry
# include <trex/europa/config.hh>
// include plasma header as system files in order to disable warnings
# define TREX_PP_SYSTEM_FILE <Constraint.hh>
# include <trex/europa/bits/system_header.hh>
namespace TREX {
namespace europa {
class InCircle :public EUROPA::Constraint {
public:
InCircle(EUROPA::LabelStr const &name,
EUROPA::LabelStr const &propagatorName,
EUROPA::ConstraintEngineId const &cstrEngine,
std::vector<EUROPA::ConstrainedVariableId> const &vars);
private:
EUROPA::Domain &m_deg;
EUROPA::Domain &m_val;
void handleExecute();
};
class RadDeg :public EUROPA::Constraint {
public:
RadDeg(EUROPA::LabelStr const &name,
EUROPA::LabelStr const &propagatorName,
EUROPA::ConstraintEngineId const &cstrEngine,
std::vector<EUROPA::ConstrainedVariableId> const &vars);
private:
EUROPA::Domain &m_deg;
EUROPA::Domain &m_rad;
void handleExecute();
};
/** @brief Cosine constraint
*
* A constraint that compute the cosine of an angle in degree.
* The first argument is an angle domain and the second will store the
* resulting cosine value.
*
* @note As of today we do not restrict the angle based on the cosine
* domain even when the angle domain span would alow it. Nonetheless
* the domain of the cosine will be restricted even though the angle
* is not a singleton (ie cos([0 90], var) will restrict var to [0 1])
* @author Frederic Py <fpy@mbari.org>
* @ingroup europa
*/
class CosineConstraint :public EUROPA::Constraint {
public:
/** @brief Constructor
* @param[in] name the name of the constraint
* @param[in] propagatorName The name of the propagator handling this constraint
* @param[in] cstrEngine the constraint engine for this instance
* @param[in] vars the list of arguments
*
* @pre @p vars size is @e exactly 2
* @pre All the element of @p vars are IntervalDomain instances
*/
CosineConstraint(EUROPA::LabelStr const &name,
EUROPA::LabelStr const &propagatorName,
EUROPA::ConstraintEngineId const &cstrEngine,
std::vector<EUROPA::ConstrainedVariableId> const &vars);
private:
/** @brief Execute the constraint
*
* Recompute the cosine of the angle and restrict the second argument
* accordingly
*/
void handleExecute();
EUROPA::Domain &m_angle;
EUROPA::Domain &m_cos;
}; // TREX::europa::CosineConstraint
/** @brief Sine constraint
*
* A constraint that compute the sine of an angle in degree.
* The first argument is an angle domain and the second will store the
* resulting sine value.
*
* @note As of today we do not restrict the angle based on the sine
* domain even when the angle domain span would alow it. Nonetheless
* the domain of the sine will be restricted even though the angle
* is not a singleton (ie sin([0 90], var) will restrict var to [0 1])
* @author Frederic Py <fpy@mbari.org>
* @ingroup europa
*/
class SineConstraint :public EUROPA::Constraint {
public:
/** @brief Constructor
* @param[in] name the name of the constraint
* @param[in] propagatorName The name of the propagator handling this constraint
* @param[in] cstrEngine the constraint engine for this instance
* @param[in] vars the list of arguments
*
* @pre @p vars size is @e exactly 2
* @pre All the element of @p vars are IntervalDomain instances
*/
SineConstraint(EUROPA::LabelStr const &name,
EUROPA::LabelStr const &propagatorName,
EUROPA::ConstraintEngineId const &cstrEngine,
std::vector<EUROPA::ConstrainedVariableId> const &vars);
private:
/** @brief Execute the constraint
*
* Recompute the sine of the angle and restrict the second argument
* accordingly
*/
void handleExecute();
EUROPA::Domain &m_angle;
EUROPA::Domain &m_sin;
}; // TREX::europa::SineConstraint
} // TREX::europa
} // TREX
#endif // H_trex_europa_Trigonometry
| 38.320755 | 86 | 0.668144 | [
"vector"
] |
9ecf204ae458924d426ff3ea4cc099ea187fb142 | 6,204 | cpp | C++ | hPath.cpp | aaron-loa/sfml_pathfinding | b35d0cbf1b47418874f84a4b05788301adf0ac6e | [
"MIT"
] | null | null | null | hPath.cpp | aaron-loa/sfml_pathfinding | b35d0cbf1b47418874f84a4b05788301adf0ac6e | [
"MIT"
] | null | null | null | hPath.cpp | aaron-loa/sfml_pathfinding | b35d0cbf1b47418874f84a4b05788301adf0ac6e | [
"MIT"
] | null | null | null | #include "hNode.hpp"
#include "hPath.hpp"
#include <set>
#include <stack>
#include <vector>
#include "hGlobals.hpp"
#include <iostream>
#include <queue>
#include "hRender.hpp"
bool Compare_for_a_star::operator()(const Node *rhs, const Node *lhs)
{
return rhs->f <= lhs->f;
}
bool Compare_for_djikstra::operator()(const Node *rhs, const Node *lhs)
{
return rhs->g <= lhs->g;
}
void node_config(std::vector<std::vector<Node>> &grid)
{
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[0].size(); ++j)
{
grid[i][j].i = i;
grid[i][j].j = j;
grid[i][j].came_from = {-2, -2};
grid[i][j].g = INT32_MAX;
grid[i][j].f = INT32_MAX;
grid[i][j].h = INT32_MAX;
grid[i][j].neighbours.clear();
}
}
if (neighbour_4)
{
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[0].size(); ++j)
{
grid[i][j].gen_neighbours_4(grid);
}
}
}
else
{
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[0].size(); ++j)
{
grid[i][j].gen_neighbours_8(grid);
}
}
}
}
void construct_path(Node *current_node, std::vector<std::vector<Node>> &grid)
{
int next_i = current_node->came_from.first;
int i;
int next_j = current_node->came_from.second;
int j;
int counter = 0;
while (grid[next_i][next_j].came_from.first != -1)
{
// change_color(path_color, &grid[next_i][next_j]);
// update_screen();
grid[next_i][next_j].color = path_color;
i = grid[next_i][next_j].came_from.first;
j = grid[next_i][next_j].came_from.second;
next_i = i;
next_j = j;
++counter;
}
std::cout << " Distance: " << counter << std::endl;
update_screen();
}
bool djikstra(Node *start, Node *end, std::vector<std::vector<Node>> &grid)
{
node_config(grid_global);
Node *current;
int tmp_g;
std::set<Node *, Compare_for_djikstra> openSet;
start->g = 0;
openSet.insert(start);
while (!openSet.empty())
{
current = *openSet.begin();
if (current->i == end->i && current->j == end->j)
{
start->came_from = {-1, -1};
construct_path(end, grid);
return true;
}
openSet.erase(openSet.begin());
tmp_g = current->g + 1;
for (int i = 0; i < current->neighbours.size(); ++i)
{
change_color(djikstra_visited_color, current->neighbours[i]);
if (tmp_g < current->neighbours[i]->g)
{
current->neighbours[i]->g = tmp_g;
current->neighbours[i]->came_from = {current->i, current->j};
openSet.insert(current->neighbours[i]);
}
}
update_screen();
}
return false;
}
bool a_star(Node *start, Node *end, std::vector<std::vector<Node>> &grid)
{
node_config(grid_global);
int tmp_g = INT32_MAX;
Node *current;
std::set<Node *, Compare_for_a_star> openSet;
start->g = 0;
start->get_h(end);
start->came_from = {-1, -1};
openSet.insert(start);
while (!openSet.empty())
{
current = *openSet.begin();
if (current->i == end->i && current->j == end->j)
{
construct_path(current, grid);
return true;
}
tmp_g = current->g + 1;
openSet.erase(openSet.begin());
for (int i = 0; i < current->neighbours.size(); ++i)
{
// change_color(to_visit_color, current->neighbours[i]);
// update_screen();
if (tmp_g < current->neighbours[i]->g)
{
change_color(visited_color, current->neighbours[i]);
current->neighbours[i]->came_from = {current->i, current->j};
current->neighbours[i]->g = tmp_g;
current->neighbours[i]->get_h(end);
openSet.insert(current->neighbours[i]);
}
}
update_screen();
}
return false;
}
bool bfs(Node *start, Node *end, std::vector<std::vector<Node>> &grid)
{
node_config(grid_global);
std::queue<Node *> openSet;
start->came_from = {-1, -1};
openSet.push(start);
Node *current;
while (!openSet.empty())
{
current = openSet.front();
openSet.pop();
if (current->i == end->i && current->j == end->j)
{
construct_path(current, grid);
return true;
}
for (int i = 0; i < current->neighbours.size(); ++i)
{
if (current->neighbours[i]->came_from.first == -2)
{
change_color(bfs_visited_color, current->neighbours[i]);
current->neighbours[i]->came_from = {current->i, current->j};
openSet.push(current->neighbours[i]);
}
}
update_screen();
}
return false;
}
bool dfs(Node *start, Node *end, std::vector<std::vector<Node>> &grid)
{
node_config(grid_global);
std::stack<Node *> openSet;
start->came_from = {-1, -1};
openSet.push(start);
Node *current;
while (!openSet.empty())
{
current = openSet.top();
change_color(dfs_color, current);
openSet.pop();
if (current->i == end->i && current->j == end->j)
{
construct_path(current, grid);
return true;
}
for (int i = 0; i < current->neighbours.size(); ++i)
{
if (current->neighbours[i]->came_from.first == -2)
{
change_color(dfs_visited_color, current->neighbours[i]);
current->neighbours[i]->came_from = {current->i, current->j};
openSet.push(current->neighbours[i]);
}
}
update_screen();
}
return false;
} | 29.264151 | 78 | 0.495164 | [
"vector"
] |
9ed2a009416a45045bf2416413a365833d17b39d | 1,975 | hpp | C++ | geoloc/string_table.hpp | loadzero/geoloc | 020cc63660dbf4d32a07dabd5e8da1fcab29659a | [
"BSD-3-Clause"
] | 69 | 2015-03-17T12:35:46.000Z | 2019-12-07T17:19:22.000Z | geoloc/string_table.hpp | loadzero/geoloc | 020cc63660dbf4d32a07dabd5e8da1fcab29659a | [
"BSD-3-Clause"
] | 1 | 2015-03-18T08:59:11.000Z | 2015-08-12T20:33:25.000Z | geoloc/string_table.hpp | loadzero/geoloc | 020cc63660dbf4d32a07dabd5e8da1fcab29659a | [
"BSD-3-Clause"
] | 16 | 2015-03-18T04:19:16.000Z | 2017-08-28T12:24:07.000Z | /*
* Copyright 2015 Jason McSweeney
* Licensed under BSD 3 Clause - see LICENSE
*
* author: Jason McSweeney
* created: 2015-03-11
*
* This class is used for interning strings. It uses a hash map to track the
* string to id mapping. The layout of indices and the char vector makes it
* easier to serialize later.
*/
#ifndef STRING_TABLE_HPP_A3ADA5DC
#define STRING_TABLE_HPP_A3ADA5DC
#include "macros.hpp"
#include "hash_map.hpp"
class StringTable
{
public:
StringTable() {}
~StringTable() {}
size_t size() const
{
return indices_.size();
}
size_t byte_size() const
{
return strings_.size();
}
void insert(const std::string &s)
{
if (string_to_id_.count(s))
{
return;
}
unsigned index = indices_.size();
string_to_id_[s] = index;
indices_.push_back(strings_.size());
strings_.insert(strings_.end(), s.begin(), s.end());
strings_.push_back('\0');
}
unsigned index_of(const std::string &s) const
{
hash_map<std::string, unsigned>::const_iterator iter =
string_to_id_.find(s);
if (iter == string_to_id_.end())
{
return 0xFFFFFFFF;
}
return iter->second;
}
const char* operator[](size_t i) const
{
return &strings_[indices_[i]];
}
const std::vector<unsigned> &indices() const { return indices_; }
const std::vector<char> &strings() const { return strings_; }
private:
// default copy/assign would work in this class, but I am making
// it an error because it is unexpected.
DISALLOW_COPY_AND_ASSIGN(StringTable);
hash_map<std::string, unsigned> string_to_id_;
std::vector<unsigned> indices_;
std::vector<char> strings_;
};
inline void save_string_table(BinaryFile &bf, const StringTable &st)
{
bf.save_pod_vector(st.indices());
bf.save_pod_vector(st.strings());
}
#endif
| 21.467391 | 77 | 0.625823 | [
"vector"
] |
9ed2e16bc4401d09d9b6e5ed10d796a71b2be543 | 3,175 | cpp | C++ | UVA/1599.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | UVA/1599.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | UVA/1599.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
const int MAXN = 100000, INF = 200000;
int n, m;
std::vector< std::pair<int, int> > e[MAXN + 1];
int vis[MAXN + 1], ans;
int col[INF + 1];
void bfsK() {
static std::queue< std::pair<int, int> > qK;
memset(vis, -1, sizeof(vis));
qK.push( std::make_pair(n, 0) );
vis[n] = 0, ans = INF;
while (!qK.empty()) {
auto u = qK.front();
qK.pop();
if (u.first == 1 && u.second < ans) ans = u.second;
for (auto ed : e[u.first]) {
if (vis[ed.first] == -1) {
vis[ed.first] = u.second + 1;
qK.push(std::make_pair(ed.first, u.second + 1));
}
}
}
}
void bfsCol() {
static std::vector<int> qCol;
static bool mk[MAXN + 1];
memset(col, 0x3f, sizeof(col));
memset(mk, false, sizeof(mk));
qCol.clear();
qCol.push_back(1);
int cnt = ans - 1;
bool flag = true;
while (cnt >= 0) {
static std::vector<int> uSet;
if (flag) {
uSet.clear();
for (int each : qCol) uSet.push_back(each);
qCol.clear();
}
flag = true;
for (int u : uSet) {
for (auto ed : e[u]) {
if (vis[ed.first] == cnt) {
if (!mk[ed.first]) {
if (col[cnt] >= ed.second) {
if (col[cnt] > ed.second) qCol.clear();
col[cnt] = ed.second;
mk[ed.first] = true;
flag = false;
qCol.push_back(ed.first);
}
} else if (col[cnt] > ed.second) col[cnt] = ed.second;
}
}
}
if (flag) {
cnt--;
for (int u : uSet) {
for (auto ed : e[u]) {
if (vis[ed.first] == cnt) {
if (!mk[ed.first]) {
if (col[cnt] >= ed.second) {
if (col[cnt] > ed.second) qCol.clear();
col[cnt] = ed.second;
mk[ed.first] = true;
flag = false;
qCol.push_back(ed.first);
}
} else if (col[cnt] > ed.second) col[cnt] = ed.second;
}
}
}
}
}
}
int main() {
while (std::cin >> n >> m) {
for (int i = 1; i <= n; i++) e[i].clear();
for (int i = 0, x, y, z; i < m; i++) {
scanf("%d%d%d", &x, &y, &z);
if (x == y) continue;
e[x].push_back( std::make_pair(y, z) );
e[y].push_back( std::make_pair(x, z) );
}
for (int i = 1; i <= n; i++) std::sort(e[i].begin(), e[i].end());
bfsK();
bfsCol();
std::cout << ans << std::endl;
for (int i = ans - 1; i >= 0; i--) printf("%d%c", col[i], i == 0 ? '\n' : ' ');
}
return 0;
} | 28.863636 | 87 | 0.384882 | [
"vector"
] |
9ed7148764b6479af5a17893cf82c64c5a2cb946 | 7,185 | cpp | C++ | Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-28T08:06:58.000Z | 2022-03-28T08:06:58.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/MultiLinearManipulator.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "MultiLinearManipulator.h"
#include <AzCore/Memory/SystemAllocator.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzToolsFramework/Manipulators/ManipulatorDebug.h>
#include <AzToolsFramework/Manipulators/ManipulatorSnapping.h>
#include <AzToolsFramework/Maths/TransformUtils.h>
#include <AzToolsFramework/Viewport/ViewportMessages.h>
#include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
namespace AzToolsFramework
{
AZ_CLASS_ALLOCATOR_IMPL(MultiLinearManipulator, AZ::SystemAllocator, 0)
AZStd::shared_ptr<MultiLinearManipulator> MultiLinearManipulator::MakeShared(const AZ::Transform& worldFromLocal)
{
return AZStd::shared_ptr<MultiLinearManipulator>(aznew MultiLinearManipulator(worldFromLocal));
}
MultiLinearManipulator::MultiLinearManipulator(const AZ::Transform& worldFromLocal)
{
SetSpace(worldFromLocal);
AttachLeftMouseDownImpl();
}
MultiLinearManipulator::~MultiLinearManipulator()
{
ClearAxes();
}
void MultiLinearManipulator::InstallLeftMouseDownCallback(const MouseActionCallback& onMouseDownCallback)
{
m_onLeftMouseDownCallback = onMouseDownCallback;
}
void MultiLinearManipulator::InstallLeftMouseUpCallback(const MouseActionCallback& onMouseUpCallback)
{
m_onLeftMouseUpCallback = onMouseUpCallback;
}
void MultiLinearManipulator::InstallMouseMoveCallback(const MouseActionCallback& onMouseMoveCallback)
{
m_onMouseMoveCallback = onMouseMoveCallback;
}
static MultiLinearManipulator::Action BuildMultiLinearManipulatorAction(
const AZ::Transform& worldFromLocal,
const AZ::Vector3& nonUniformScale,
const AZ::Transform& localTransform,
const ViewportInteraction::MouseInteraction& interaction,
const AZStd::vector<LinearManipulator::Fixed>& fixedAxes,
const AZStd::vector<LinearManipulator::Starter>& starterStates,
const GridSnapParameters& gridSnapParams)
{
MultiLinearManipulator::Action action;
action.m_viewportId = interaction.m_interactionId.m_viewportId;
// build up action state for each axis
for (size_t fixedIndex = 0; fixedIndex < fixedAxes.size(); ++fixedIndex)
{
action.m_actions.push_back(CalculateLinearManipulationDataAction(
fixedAxes[fixedIndex], starterStates[fixedIndex], worldFromLocal, nonUniformScale, localTransform, gridSnapParams,
interaction));
}
return action;
}
void MultiLinearManipulator::OnLeftMouseDownImpl(
const ViewportInteraction::MouseInteraction& interaction, const float rayIntersectionDistance)
{
const AZ::Transform worldFromLocal = GetSpace();
const AzFramework::CameraState cameraState = GetCameraState(interaction.m_interactionId.m_viewportId);
// build up initial start state for each axis
for (const auto& fixed : m_fixedAxes)
{
// note: m_localTransform must not be made uniform as it may contain a local scale we want to snap
const auto linearStart = CalculateLinearManipulationDataStart(
fixed, worldFromLocal, GetNonUniformScale(), GetLocalTransform(), interaction, rayIntersectionDistance,
cameraState);
m_starters.push_back(linearStart);
}
if (m_onLeftMouseDownCallback)
{
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
// pass action containing all linear actions for each axis to handler
m_onLeftMouseDownCallback(BuildMultiLinearManipulatorAction(
worldFromLocal, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters,
gridSnapParams));
}
}
void MultiLinearManipulator::OnMouseMoveImpl(const ViewportInteraction::MouseInteraction& interaction)
{
if (m_onMouseMoveCallback)
{
const AZ::Transform worldFromLocal = GetSpace();
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
m_onMouseMoveCallback(BuildMultiLinearManipulatorAction(
worldFromLocal, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters, gridSnapParams));
}
}
void MultiLinearManipulator::OnLeftMouseUpImpl(const ViewportInteraction::MouseInteraction& interaction)
{
if (m_onLeftMouseUpCallback)
{
const AZ::Transform worldFromLocal = GetSpace();
const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId);
m_onLeftMouseUpCallback(BuildMultiLinearManipulatorAction(
worldFromLocal, GetNonUniformScale(), GetLocalTransform(), interaction, m_fixedAxes, m_starters, gridSnapParams));
m_starters.clear();
}
}
void MultiLinearManipulator::Draw(
const ManipulatorManagerState& managerState,
AzFramework::DebugDisplayRequests& debugDisplay,
const AzFramework::CameraState& cameraState,
const ViewportInteraction::MouseInteraction& mouseInteraction)
{
if (ed_manipulatorDrawDebug)
{
const AZ::Transform combined = GetSpace() * GetLocalTransform();
for (const auto& fixed : m_fixedAxes)
{
DrawAxis(debugDisplay, combined.GetTranslation(), TransformDirectionNoScaling(combined, fixed.m_axis));
}
}
for (auto& view : m_manipulatorViews)
{
view->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
debugDisplay, cameraState, mouseInteraction);
}
}
void MultiLinearManipulator::AddAxis(const AZ::Vector3& axis)
{
m_fixedAxes.push_back(LinearManipulator::Fixed{ axis });
}
void MultiLinearManipulator::AddAxes(const AZStd::vector<AZ::Vector3>& axes)
{
AZStd::transform(
axes.begin(), axes.end(), AZStd::back_inserter(m_fixedAxes),
[](const AZ::Vector3& axis)
{
return LinearManipulator::Fixed{ axis };
});
}
void MultiLinearManipulator::ClearAxes()
{
m_fixedAxes.clear();
}
void MultiLinearManipulator::InvalidateImpl()
{
for (auto& view : m_manipulatorViews)
{
view->Invalidate(GetManipulatorManagerId());
}
}
void MultiLinearManipulator::SetBoundsDirtyImpl()
{
for (auto& view : m_manipulatorViews)
{
view->SetBoundDirty(GetManipulatorManagerId());
}
}
} // namespace AzToolsFramework
| 38.42246 | 130 | 0.691858 | [
"vector",
"transform",
"3d"
] |
9ed9283d15a63e14724f437dc6f84c50e8b06720 | 19,648 | cpp | C++ | dev/Code/Sandbox/Editor/Prefabs/PrefabManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Code/Sandbox/Editor/Prefabs/PrefabManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Sandbox/Editor/Prefabs/PrefabManager.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "PrefabManager.h"
#include "PrefabItem.h"
#include "PrefabLibrary.h"
#include "GameEngine.h"
#include "DataBaseDialog.h"
#include "PrefabDialog.h"
#include "Objects/PrefabObject.h"
#include "PrefabEvents.h"
#define PREFABS_LIBS_PATH "Prefabs/"
//////////////////////////////////////////////////////////////////////////
// CUndoGroupObjectOpenClose implementation.
//////////////////////////////////////////////////////////////////////////
class CUndoGroupObjectOpenClose
: public IUndoObject
{
public:
CUndoGroupObjectOpenClose(CPrefabObject* prefabObj)
{
m_prefabObject = prefabObj;
m_bOpenForUndo = m_prefabObject->IsOpen();
}
protected:
virtual int GetSize() { return sizeof(*this); }; // Return size of xml state.
virtual QString GetDescription() { return "Prefab's Open/Close"; };
virtual void Undo(bool bUndo)
{
m_bRedo = bUndo;
Apply(m_bOpenForUndo);
}
virtual void Redo()
{
if (m_bRedo)
{
Apply(!m_bOpenForUndo);
}
}
void Apply(bool bOpen)
{
if (m_prefabObject)
{
if (bOpen)
{
m_prefabObject->Open();
}
else
{
m_prefabObject->Close();
}
}
}
private:
CPrefabObjectPtr m_prefabObject;
bool m_bRedo;
bool m_bOpenForUndo;
};
//////////////////////////////////////////////////////////////////////////
// CUndoAddObjectsToPrefab implementation.
//////////////////////////////////////////////////////////////////////////
CUndoAddObjectsToPrefab::CUndoAddObjectsToPrefab(CPrefabObject* prefabObj, TBaseObjects& objects)
{
m_pPrefabObject = prefabObj;
// Rearrange to parent-first
for (int i = 0; i < objects.size(); i++)
{
if (objects[i]->GetParent())
{
// Find later in array.
for (int j = i + 1; j < objects.size(); j++)
{
if (objects[j] == objects[i]->GetParent())
{
// Swap the objects.
std::swap(objects[i], objects[j]);
i--;
break;
}
}
}
}
m_addedObjects.reserve(objects.size());
for (size_t i = 0, count = objects.size(); i < count; ++i)
{
m_addedObjects.push_back(SObjectsLinks());
SObjectsLinks& addedObject = m_addedObjects.back();
addedObject.m_object = objects[i]->GetId();
// Store parent before the add operation
addedObject.m_objectParent = objects[i]->GetParent() ? objects[i]->GetParent()->GetId() : GUID_NULL;
// Store childs before the add operation
if (const size_t childsCount = objects[i]->GetChildCount())
{
addedObject.m_objectsChilds.reserve(childsCount);
for (size_t j = 0; j < childsCount; ++j)
{
addedObject.m_objectsChilds.push_back(objects[i]->GetChild(j)->GetId());
}
}
}
}
void CUndoAddObjectsToPrefab::Undo(bool bUndo)
{
// Start from the back where the childs are
for (int i = m_addedObjects.size() - 1; i >= 0; --i)
{
IObjectManager* pObjMan = GetIEditor()->GetObjectManager();
// Remove from prefab
if (CBaseObject* pMember = pObjMan->FindObject(m_addedObjects[i].m_object))
{
m_pPrefabObject->RemoveMember(pMember);
// Restore parent links
if (CBaseObject* pParent = pObjMan->FindObject(m_addedObjects[i].m_objectParent))
{
pParent->AttachChild(pMember);
}
// Restore child links
if (const int childsCount = m_addedObjects[i].m_objectsChilds.size())
{
for (int j = 0; j < childsCount; ++j)
{
if (CBaseObject* pChild = pObjMan->FindObject(m_addedObjects[i].m_objectsChilds[j]))
{
pMember->AttachChild(pChild);
}
}
}
}
}
}
void CUndoAddObjectsToPrefab::Redo()
{
for (int i = 0, count = m_addedObjects.size(); i < count; ++i)
{
if (CBaseObject* pMember = GetIEditor()->GetObjectManager()->FindObject(m_addedObjects[i].m_object))
{
m_pPrefabObject->AddMember(pMember);
}
}
}
//////////////////////////////////////////////////////////////////////////
// CPrefabManager implementation.
//////////////////////////////////////////////////////////////////////////
CPrefabManager::CPrefabManager()
: m_pPrefabEvents(NULL)
{
m_bUniqNameMap = true;
m_pLevelLibrary = (CBaseLibrary*)AddLibrary("Level", true);
m_pPrefabEvents = new CPrefabEvents();
m_skipPrefabUpdate = false;
}
//////////////////////////////////////////////////////////////////////////
CPrefabManager::~CPrefabManager()
{
SAFE_DELETE(m_pPrefabEvents);
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::ClearAll()
{
CBaseLibraryManager::ClearAll();
m_pPrefabEvents->RemoveAllEventData();
m_pLevelLibrary = (CBaseLibrary*)AddLibrary("Level", true);
}
//////////////////////////////////////////////////////////////////////////
CBaseLibraryItem* CPrefabManager::MakeNewItem()
{
return new CPrefabItem;
}
//////////////////////////////////////////////////////////////////////////
CBaseLibrary* CPrefabManager::MakeNewLibrary()
{
return new CPrefabLibrary(this);
}
//////////////////////////////////////////////////////////////////////////
QString CPrefabManager::GetRootNodeName()
{
return "PrefabsLibrary";
}
//////////////////////////////////////////////////////////////////////////
QString CPrefabManager::GetLibsPath()
{
if (m_libsPath.isEmpty())
{
m_libsPath = PREFABS_LIBS_PATH;
}
return m_libsPath;
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::Serialize(XmlNodeRef& node, bool bLoading)
{
CBaseLibraryManager::Serialize(node, bLoading);
}
//////////////////////////////////////////////////////////////////////////
CPrefabItem* CPrefabManager::MakeFromSelection()
{
// Prevent making legacy prefabs out of selections that include component entities
// Component entities use slices as their prefab mechanism
CSelectionGroup* selection = GetIEditor()->GetSelection();
for (size_t i = 0; i < selection->GetCount(); ++i)
{
auto* object = selection->GetObject(i);
if (OBJTYPE_AZENTITY == object->GetType())
{
CryMessageBox("Component Entities can not be added to prefab objects.\nPlease deselect any component entities and try again.\n\nTo construct pre-configured groups of component entities, create a slice instead.", "Invalid Selection", MB_OK | MB_ICONERROR);
return 0;
}
}
CBaseLibraryDialog* dlg = GetIEditor()->OpenDataBaseLibrary(EDB_TYPE_PREFAB);
CPrefabDialog* pPrefabDialog = qobject_cast<CPrefabDialog*>(dlg);
if (pPrefabDialog)
{
return pPrefabDialog->GetPrefabFromSelection();
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::AddSelectionToPrefab()
{
CSelectionGroup* pSel = GetIEditor()->GetSelection();
CPrefabObject* pPrefab = 0;
int selectedPrefabCount = 0;
for (int i = 0; i < pSel->GetCount(); i++)
{
CBaseObject* pObj = pSel->GetObject(i);
if (qobject_cast<CPrefabObject*>(pObj))
{
++selectedPrefabCount;
pPrefab = (CPrefabObject*) pObj;
}
}
if (selectedPrefabCount == 0)
{
Warning("Select a prefab and objects");
return;
}
if (selectedPrefabCount > 1)
{
Warning("Select only one prefab");
return;
}
TBaseObjects objects;
for (int i = 0; i < pSel->GetCount(); i++)
{
CBaseObject* pObj = pSel->GetObject(i);
if (pObj != pPrefab)
{
objects.push_back(pObj);
}
}
// Check objects if they can be added
bool invalidAddOperation = false;
for (int i = 0, count = objects.size(); i < count; ++i)
{
if (objects[i]->GetType() == OBJTYPE_AZENTITY)
{
// Component entities cannot be added to legacy prefabs.
Warning("Object %s is a component entity and not compatible with legacy prefabs. Use Slices instead.", objects[i]->GetName().toUtf8().constData());
invalidAddOperation = true;
}
else if (!pPrefab->CanObjectBeAddedAsMember(objects[i]))
{
Warning("Object %s is already part of a prefab (%s)", objects[i]->GetName().toUtf8().constData(), objects[i]->GetPrefab()->GetName().toUtf8().constData());
invalidAddOperation = true;
}
}
if (invalidAddOperation)
{
return;
}
CUndo undo("Add Objects To Prefab");
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoAddObjectsToPrefab(pPrefab, objects));
}
for (int i = 0; i < objects.size(); i++)
{
pPrefab->AddMember(objects[i]);
}
// If we have nested dependencies between these object send an modify event afterwards to resolve them properly (e.g. shape objects linked to area triggers)
for (int i = 0; i < objects.size(); i++)
{
objects[i]->UpdatePrefab();
}
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::ExtractObjectsFromPrefabs(std::vector<CBaseObject*>& childObjects, bool bSelectExtracted)
{
if (childObjects.empty())
{
return;
}
CUndo undo("Extract Object(s) from Prefab");
CSelectionGroup extractedObjects;
std::map<CPrefabObject*, CSelectionGroup> prefabObjectsToBeExtracted;
for (int i = 0, childCount = childObjects.size(); i < childCount; ++i)
{
if (CPrefabObject* pPrefab = childObjects[i]->GetPrefab())
{
CSelectionGroup& selGroup = prefabObjectsToBeExtracted[pPrefab];
ExpandGroup(childObjects[i], selGroup);
}
}
std::map<CPrefabObject*, CSelectionGroup>::iterator it = prefabObjectsToBeExtracted.begin();
std::map<CPrefabObject*, CSelectionGroup>::iterator end = prefabObjectsToBeExtracted.end();
for (; it != end; ++it)
{
(it->first)->CloneSelected(&(it->second), &extractedObjects);
}
for (int i = 0, childCount = childObjects.size(); i < childCount; ++i)
{
CPrefabObject* pPrefab = childObjects[i]->GetPrefab();
for (int j = 0, count = childObjects[i]->GetChildCount(); j < count; ++j)
{
CBaseObject* pChildToReparent = childObjects[i]->GetChild(j);
pPrefab->AttachChild(pChildToReparent);
pChildToReparent->UpdatePrefab();
}
GetIEditor()->GetObjectManager()->DeleteObject(childObjects[i]);
}
if (bSelectExtracted)
{
SelectObjectsIgnoringUndo(extractedObjects);
}
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::ExtractAllFromPrefabs(std::vector<CPrefabObject*>& pPrefabs, bool bSelectExtracted)
{
if (pPrefabs.empty())
{
return;
}
CSelectionGroup selectedPrefabs;
for (int i = 0, count = pPrefabs.size(); i < count; i++)
{
if (qobject_cast<CPrefabObject*>(pPrefabs[i]))
{
selectedPrefabs.AddObject(pPrefabs[i]);
}
}
CUndo undo("Extract All from Prefab(s)");
CSelectionGroup extractedObjects;
for (int i = 0, count = selectedPrefabs.GetCount(); i < count; i++)
{
if (CPrefabObject* pPrefab = static_cast<CPrefabObject*>(selectedPrefabs.GetObject(i)))
{
pPrefab->CloneAll(&extractedObjects);
}
}
if (bSelectExtracted)
{
SelectObjectsIgnoringUndo(extractedObjects);
}
for (int i = 0, count = selectedPrefabs.GetCount(); i < count; i++)
{
GetIEditor()->DeleteObject(selectedPrefabs.GetObject(i));
}
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::CloneObjectsFromPrefabs(std::vector<CBaseObject*>& childObjects, bool bSelectCloned)
{
if (childObjects.empty())
{
return;
}
CUndo undo("Clone Object(s) from Prefab");
CSelectionGroup clonedObjects;
CSelectionGroup selectedObjects;
for (int i = 0; i < childObjects.size(); ++i)
{
ExpandGroup(childObjects[i], selectedObjects);
}
if (CPrefabObject* pPrefab = childObjects[0]->GetPrefab())
{
pPrefab->CloneSelected(&selectedObjects, &clonedObjects);
}
if (bSelectCloned)
{
SelectObjectsIgnoringUndo(clonedObjects);
}
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::CloneAllFromPrefabs(std::vector<CPrefabObject*>& pPrefabs, bool bSelectCloned)
{
if (pPrefabs.empty())
{
return;
}
CSelectionGroup selectedPrefabs;
for (int i = 0, count = pPrefabs.size(); i < count; i++)
{
if (qobject_cast<CPrefabObject*>(pPrefabs[i]))
{
selectedPrefabs.AddObject(pPrefabs[i]);
}
}
CUndo undo("Clone All from Prefab(s)");
CSelectionGroup clonedObjects;
for (int i = 0, count = selectedPrefabs.GetCount(); i < count; i++)
{
static_cast<CPrefabObject*>(selectedPrefabs.GetObject(i))->CloneAll(&clonedObjects);
}
if (bSelectCloned)
{
SelectObjectsIgnoringUndo(clonedObjects);
}
}
//////////////////////////////////////////////////////////////////////////
bool CPrefabManager::OpenPrefabs(std::vector<CPrefabObject*>& prefabObjects, const char* undoDescription)
{
if (prefabObjects.empty())
{
return false;
}
bool bOpenedAtLeastOne = false;
CUndo undo(undoDescription);
for (int i = 0, iCount(prefabObjects.size()); i < iCount; ++i)
{
CPrefabObject* pPrefabObj = (CPrefabObject*)prefabObjects[i];
if (!pPrefabObj->IsOpen())
{
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoGroupObjectOpenClose(pPrefabObj));
}
pPrefabObj->Open();
bOpenedAtLeastOne = true;
}
}
return bOpenedAtLeastOne;
}
//////////////////////////////////////////////////////////////////////////
bool CPrefabManager::ClosePrefabs(std::vector<CPrefabObject*>& prefabObjects, const char* undoDescription)
{
if (prefabObjects.empty())
{
return false;
}
bool bClosedAtLeastOne = false;
CUndo undo(undoDescription);
for (int i = 0, iCount(prefabObjects.size()); i < iCount; ++i)
{
CPrefabObject* pPrefabObj = (CPrefabObject*)prefabObjects[i];
if (pPrefabObj->IsOpen())
{
if (CUndo::IsRecording())
{
CUndo::Record(new CUndoGroupObjectOpenClose(pPrefabObj));
}
pPrefabObj->Close();
bClosedAtLeastOne = true;
}
}
return bClosedAtLeastOne;
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::GetPrefabObjects(std::vector<CPrefabObject*>& outPrefabObjects)
{
std::vector<CBaseObject*> prefabObjects;
GetIEditor()->GetObjectManager()->FindObjectsOfType(&CPrefabObject::staticMetaObject, prefabObjects);
if (prefabObjects.empty())
{
return;
}
for (int i = 0, iCount(prefabObjects.size()); i < iCount; ++i)
{
CPrefabObject* pPrefabObj = (CPrefabObject*)prefabObjects[i];
if (pPrefabObj == NULL)
{
continue;
}
outPrefabObjects.push_back(pPrefabObj);
}
}
//////////////////////////////////////////////////////////////////////////
int CPrefabManager::GetPrefabInstanceCount(CPrefabItem* pPrefabItem)
{
int instanceCount = 0;
std::vector<CPrefabObject*> prefabObjects;
GetPrefabObjects(prefabObjects);
if (pPrefabItem)
{
for (int i = 0, prefabsFound(prefabObjects.size()); i < prefabsFound; ++i)
{
CPrefabObject* pPrefabObject = (CPrefabObject*)prefabObjects[i];
if (pPrefabObject->GetPrefab() == pPrefabItem)
{
++instanceCount;
}
}
}
return instanceCount;
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::DeleteItem(IDataBaseItem* pItem)
{
assert(pItem);
CPrefabItem* pPrefabItem = (CPrefabItem*)pItem;
// Delete all objects from object manager that have this prefab item
std::vector<GUID> guids;
CBaseObjectsArray objects;
IObjectManager* pObjMan = GetIEditor()->GetObjectManager();
pObjMan->GetObjects(objects);
for (int i = 0; i < objects.size(); ++i)
{
CBaseObject* pObj = objects[i];
if (qobject_cast<CPrefabObject*>(pObj))
{
CPrefabObject* pPrefab = (CPrefabObject*) pObj;
if (pPrefab->GetPrefab() == pPrefabItem)
{
// Collect guids first to delete objects later
guids.push_back(pPrefab->GetId());
}
}
}
for (int i = 0; i < guids.size(); ++i)
{
CBaseObject* pObj = pObjMan->FindObject(guids[i]);
if (pObj)
{
pObjMan->DeleteObject(pObj);
}
}
CBaseLibraryManager::DeleteItem(pItem);
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::SelectObjectsIgnoringUndo(CSelectionGroup& extractedObjects) const
{
GetIEditor()->ClearSelection();
GetIEditor()->SuspendUndo();
for (int i = 0, count = extractedObjects.GetCount(); i < count; ++i)
{
GetIEditor()->SelectObject(extractedObjects.GetObject(i));
}
GetIEditor()->ResumeUndo();
}
//////////////////////////////////////////////////////////////////////////
void CPrefabManager::ExpandGroup(CBaseObject* pObject, CSelectionGroup& selection) const
{
selection.AddObject(pObject);
if (qobject_cast<CGroup*>(pObject) && !qobject_cast<CPrefabObject*>(pObject))
{
CGroup* pGroup = static_cast<CGroup*>(pObject);
const TBaseObjects& groupMembers = pGroup->GetMembers();
for (int i = 0, count = groupMembers.size(); i < count; ++i)
{
ExpandGroup(groupMembers[i], selection);
}
}
}
//////////////////////////////////////////////////////////////////////////
IDataBaseLibrary* CPrefabManager::LoadLibrary(const QString& filename, bool bReload)
{
IDataBaseLibrary* pLibrary = CBaseLibraryManager::LoadLibrary(filename, bReload);
if (bReload && pLibrary)
{
CPrefabLibrary* pPrefabLibrary = (CPrefabLibrary*)pLibrary;
pPrefabLibrary->UpdatePrefabObjects();
}
return pLibrary;
} | 29.769697 | 267 | 0.549623 | [
"object",
"shape",
"vector"
] |
9edb7de5c67473d920554039a5494fbc4d8e1653 | 3,679 | cpp | C++ | Official Windows Platform Sample/XAML Navigation sample/[C++]-XAML Navigation sample/C++/Scenario1.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/XAML Navigation sample/[C++]-XAML Navigation sample/C++/Scenario1.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/XAML Navigation sample/[C++]-XAML Navigation sample/C++/Scenario1.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************
//
// Scenario1.xaml.cpp
// Implementation of the Scenario1 class
//
#include "pch.h"
#include "Scenario1.xaml.h"
#include "MainPage.xaml.h"
#include "SimplePage.xaml.h"
using namespace SDKSample;
using namespace SDKSample::Navigation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Interop;
// This Scenario shows the basic usage of Navigation in XAML.
Scenario1::Scenario1()
{
InitializeComponent();
}
void Scenario1::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
//These two methods will show info about the state of the navigation stacks
//and also enable or disable buttons from the User Interface.
ShowInfo();
UpdateUI();
}
void Scenario1::NavigateButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
//Navigate method will display SimplePage content inside the MyFrame element.
this->MyFrame->Navigate(TypeName(SDKSample::SimplePage::typeid));
ShowInfo();
UpdateUI();
}
void Scenario1::GoBackButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
//We should verify if there are pages in the navigation back stack
//before navigating to the previous page.
if (this->MyFrame != nullptr && MyFrame->CanGoBack)
{
//Using the GoBack method, the frame navigates to the previous page.
MyFrame->GoBack();
}
ShowInfo();
UpdateUI();
}
void Scenario1::GoForwardButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
//We should verify if there are pages in the navigation forward stack
//before navigating to the forward page.
if (this->MyFrame != nullptr && MyFrame->CanGoForward)
{
//Using the GoForward method, the frame navigates to the forward page.
MyFrame->GoForward();
}
ShowInfo();
UpdateUI();
}
void Scenario1::GoHomeButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Use the navigation frame to return to the topmost page
if (this->MyFrame != nullptr)
{
while (this->MyFrame->CanGoBack) this->MyFrame->GoBack();
}
ShowInfo();
UpdateUI();
}
void Scenario1::ClearStacksButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
//We can clear the navigation stacks using the Clear method of each stack.
MyFrame->ForwardStack->Clear();
MyFrame->BackStack->Clear();
ShowInfo();
UpdateUI();
}
void Scenario1::ShowInfo()
{
if (MyFrame != nullptr)
{
int backStackSize = this->MyFrame->BackStack->Size;
BackStackText->Text = "\nEntries in the navigation Back Stack: #" + backStackSize.ToString();
int fordwardStackSize = this->MyFrame->ForwardStack->Size;
ForwardStackText->Text = "\nEntries in the navigation Forward Stack: #" + fordwardStackSize.ToString();
BackStackListView->Items->Clear();
//Add the pages from the back stack
for (int i = 0; i < backStackSize; i++)
{
BackStackListView->Items->Append(this->MyFrame->BackStack->GetAt(i)->SourcePageType.Name);
}
ForwardStackListView->Items->Clear();
//Add the pages from the forward stack
for (int i = 0; i < fordwardStackSize; i++)
{
ForwardStackListView->Items->Append(this->MyFrame->ForwardStack->GetAt(i)->SourcePageType.Name);
}
}
}
void Scenario1::UpdateUI()
{
GoHomeBtn->IsEnabled = MyFrame->CanGoBack;
GoForwardBtn->IsEnabled = MyFrame->CanGoForward;
GoBackBtn->IsEnabled = MyFrame->CanGoBack;
ClearStacksBtn->IsEnabled = (MyFrame->BackStack->Size > 0 || MyFrame->ForwardStack->Size > 0) ? true : false;
}
| 29.198413 | 110 | 0.702908 | [
"object"
] |
9edc877f439bd35177b130308ec7ed9d0d0d0973 | 4,565 | cpp | C++ | src/mdMap.cpp | AngryFrogDev/Dungeon-Brawler | 85a6d19ceed20c02d55956f4c456eed7357aaf76 | [
"MIT"
] | 5 | 2018-03-04T15:16:28.000Z | 2021-04-26T13:57:43.000Z | src/mdMap.cpp | AngryFrogDev/ProjectII | 85a6d19ceed20c02d55956f4c456eed7357aaf76 | [
"MIT"
] | 55 | 2018-03-15T12:37:20.000Z | 2018-06-06T10:55:17.000Z | src/mdMap.cpp | AngryFrogDev/Dungeon-Brawler | 85a6d19ceed20c02d55956f4c456eed7357aaf76 | [
"MIT"
] | null | null | null | #include "DebLog.h"
#include "Application.h"
#include "mdRender.h"
#include "mdTextures.h"
#include "mdMap.h"
#include <math.h>
#include "Brofiler/Brofiler.h"
#include "mdAudio.h"
#include "mdEntities.h"
mdMap::mdMap() : Module(), map_loaded(false) {
name = "map";
}
// Destructor
mdMap::~mdMap()
{}
// Called before render is available
bool mdMap::awake(const pugi::xml_node& md_config) {
LOG("Loading Map Parser");
bool ret = true;
// Provisional, should be loaded from XML
////data.map_image = App->textures->load("assets/village.png");
////data.background_image = App->textures->load("assets/village_background.png");
////map_loaded = true;
// Load map characteristics, (Provisional, should be done thorugh xml)
data.camera_x_limit = 3400;
data.width = 512 * 6;
return ret;
}
void mdMap::draw() {
if (map_loaded) {
if (selected_map == 1) {
//Blit background
App->render->drawSprite(1, data.background_image, mapx, 0, (const SDL_Rect*)0, 6, false, 0.3);
App->render->drawSprite(1, data.background_image, mapx2, 0, (const SDL_Rect*)0, 6, false, 0.3);
//Blit map
App->render->drawSprite(2, data.map_image, 0, 200, (const SDL_Rect*)0, 5, false);
}
else if (selected_map == 2) {
//Blit background
App->render->drawSprite(1, data.background_image, mapx, 0, (const SDL_Rect*)0, 6, false, 0.3);
App->render->drawSprite(1, data.background_image, mapx2, 0, (const SDL_Rect*)0, 6, false, 0.3);
//Blit map
App->render->drawSprite(2, data.map_image, 0, 400, (const SDL_Rect*)0, 4, false);
}
else if (selected_map == 3) {
//Blit background
App->render->drawSprite(1, data.background_image, mapx, 100, (const SDL_Rect*)0, 6, false, 0.3);
App->render->drawSprite(1, data.background_image, mapx2, 100, (const SDL_Rect*)0, 6, false, 0.3);
//Blit map
App->render->drawSprite(2, data.map_image, -400, 750, (const SDL_Rect*)0, 4, false);
}
}
}
bool mdMap::update(float dt) {
if (map_loaded)
{
if (change_music)
{
if (selected_map == 1)
App->audio->playMusic(App->audio->loadMusic("SFX/BGM_2.ogg"));
else if (selected_map == 2)
App->audio->playMusic(App->audio->loadMusic("SFX/BGM_1.ogg"));
else if (selected_map == 3)
App->audio->playMusic(App->audio->loadMusic("SFX/BGM_2.ogg"));
change_music = false;
}
// Provisional: this is soooooo hardcoded
if (parallax && !App->entities->paused) {
if (firstfront) {
mapx -= parallax_speed;
mapx2 = mapx + data.width;
if (mapx2 <= 0) {
mapx = data.width;
firstfront = false;
}
}
else {
mapx2 -= parallax_speed;
mapx = mapx2 + data.width;
if (mapx <= 0) {
mapx2 = data.width;
firstfront = true;
}
}
}
draw();
}
else if (!change_music) {
App->audio->playMusic(App->audio->loadMusic("SFX/BGM_1.ogg"));
change_music = true;
}
return true;
}
bool mdMap::cleanUp() {
LOG("Unloading map");
App->textures->unload(data.map_image);
App->textures->unload(data.background_image);
map_loaded = false;
return true;
}
// Load map general properties
bool mdMap::loadMap(int mapIndex) {
BROFILER_CATEGORY("Loading Map", 0xFFEE82EE);
bool ret = true;
pugi::xml_node map = map_file.child("map");
loadMapPropierties(map);
//if (map == NULL) {
// LOG("Error parsing map xml file: Cannot find 'map' tag.");
// ret = false;
//}
//else {
selected_map = mapIndex;
if (mapIndex == 1) { // Load map characteristics, (Provisional, should be done thorugh xml)
data.map_image = App->textures->load("assets/ship.png");
data.background_image = App->textures->load("assets/ship_background.png");
parallax_speed = 5;
selected_map = 1;
}
else if (mapIndex == 2) {
data.map_image = App->textures->load("assets/water.png");
data.background_image = App->textures->load("assets/water_background.png");
selected_map = mapIndex;;
parallax_speed = 5;
}
else if (mapIndex == 3) {
data.map_image = App->textures->load("assets/train.png");
data.background_image = App->textures->load("assets/train_background.png");
selected_map = mapIndex;
parallax_speed = 10;
}
//}
return ret;
}
bool mdMap::unloadMap() {
BROFILER_CATEGORY("Unloading Map", 0xFF9ACD32);
bool ret = true;
App->textures->unload(data.map_image);
App->textures->unload(data.background_image);
map_loaded = false;
return ret;
}
bool mdMap::loadMapPropierties(pugi::xml_node& node) {
pugi::xml_node iterator = node.child("map").child("properties").child("property");
while (iterator != nullptr) {
// Load data from XML
}
return true;
} | 26.387283 | 100 | 0.660898 | [
"render"
] |
9edef55a7e9adec4981ff2475c4fad4f7e472af4 | 14,733 | cpp | C++ | source/tests.cpp | MarcusAlmert/programmiersprachen-raytracer | 73f186685c2e91a6de7ba86602cde20b69adf7cd | [
"MIT"
] | 1 | 2020-08-13T08:45:43.000Z | 2020-08-13T08:45:43.000Z | source/tests.cpp | MarcusAlmert/programmiersprachen-raytracer | 73f186685c2e91a6de7ba86602cde20b69adf7cd | [
"MIT"
] | null | null | null | source/tests.cpp | MarcusAlmert/programmiersprachen-raytracer | 73f186685c2e91a6de7ba86602cde20b69adf7cd | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <memory>
#include <shapes/triangle.hpp>
#include <iostream>
#include <glm/gtx/intersect.hpp>
#include <glm/glm.hpp>
#include <renderer.hpp>
#include <shapes/plane.hpp>
#include "shapes/shape.hpp"
#include "shapes/sphere.hpp"
#include "shapes/box.hpp"
#include "material.hpp"
#include "scene.hpp"
#include "light.hpp"
#include "shapes/composite.hpp"
#include "shapes/cylinder.hpp"
#include "shapes/plane.hpp"
#include "shapes/cone.hpp"
int main(int argc, char *argv[]) {
return Catch::Session().run(argc, argv);
}
/* Tests for Shapes */
TEST_CASE("Material print", "Material") {
Material red{"Red", Color{1, 1, 1}, Color{0, 0, 0}, Color{0.5, 0.5, 0.5}, 1.0f};
std::cout << red << std::endl;
}
TEST_CASE("Sphere standard Constructor", "[Sphere]") {
Sphere sp1 = Sphere();
CHECK(sp1.area() == 0);
CHECK(sp1.volume() == 0);
}
TEST_CASE("Sphere Constructor", "[Sphere]") {
Sphere sp1 = Sphere({1, 1, 1}, 10);
CHECK(sp1.area() == Approx(1256.637));
CHECK(sp1.volume() == Approx(4188.79));
}
TEST_CASE("Sphere area()", "[Sphere]") {
Sphere sp1 = Sphere({3, 4, 10}, 13);
CHECK(sp1.area() == Approx(2123.717));
sp1 = Sphere({2, 3, 1}, 2);
CHECK(sp1.area() == Approx(50.265));
sp1 = Sphere({2, 3, 1}, 0);
CHECK(sp1.area() == Approx(0));
}
TEST_CASE("Sphere volume()", "[Sphere]") {
Sphere sp1 = Sphere({3, 4, 10}, 13);
CHECK(sp1.volume() == Approx(9202.772));
sp1 = Sphere({2, 3, 1}, 2);
CHECK(sp1.volume() == Approx(33.51));
sp1 = Sphere({2, 3, 1}, 0);
CHECK(sp1.volume() == Approx(0));
}
TEST_CASE("Box standard Constructor", "[Box]") {
Box b1 = Box();
CHECK(b1.area() == 0);
CHECK(b1.volume() == 0);
}
TEST_CASE("Box Constructor", "[Box]") {
Box b1 = Box({0, 0, 0}, {10, 10, 10});
CHECK(b1.area() == Approx(600));
CHECK(b1.volume() == Approx(1000));
}
TEST_CASE("Box volume()", "[Box]") {
Box b1 = Box({0, 0, 0}, {10, 10, 10});
CHECK(b1.volume() == Approx(1000));
b1 = Box({10, 10, 10}, {0, 0, 0});
CHECK(b1.volume() == Approx(1000));
b1 = Box({12, 11, 3}, {1, 10, 23});
CHECK(b1.volume() == Approx(220));
}
TEST_CASE("Box area()", "[Box]") {
Box b1 = Box({0, 0, 0}, {10, 10, 10});
CHECK(b1.area() == Approx(600));
b1 = Box({10, 10, 10}, {0, 0, 0});
CHECK(b1.area() == Approx(600));
b1 = Box({12, 11, 3}, {1, 10, 23});
CHECK(b1.area() == Approx(502.0));
}
TEST_CASE("Print", "[Shapes]") {
Box b1{{1, 1, 1},
{0, 0, 0}};
Sphere sp1;
//std::cout << "--------- test ------------\n";
sp1.print(std::cout) << std::endl;
b1.print(std::cout);
//std::cout << "---------test over----------\n";
}
TEST_CASE ("intersect_ray_sphere", "[intersect]") {
// Ray
glm::vec3 ray_origin{0.0f, 0.0f, 0.0f};
// ray direction has to be normalized !
// you can use :
// v = glm :: normalize ( some_vector )
glm::vec3 ray_direction{0.0f, 0.0f, 1.0f};
// Sphere
glm::vec3 sphere_center{0.0f, 0.0f, 5.0f};
float sphere_radius{1.0f};
float distance = 0.0f;
auto result = glm::intersectRaySphere(
ray_origin, ray_direction,
sphere_center,
sphere_radius * sphere_radius, // squared radius !!!
distance);
CHECK (distance == Approx(4.0f));
Sphere s1{glm::vec3{5.0f, 5.0f, 5.0f}, 1.0f};
Sphere s2{glm::vec3{10.0f, 10.0f, 10.0f}, 1.0f};
Ray ray{{0.0f, 0.0f, 0.0f},
{1.0f, 1.0f, 1.0f}};
Ray raymissed{{0.0f, 0.0f, 0.0f},
{0.0f, -1.0f, 0.0f}};
Hitpoint hit = s1.intersect(ray);
Hitpoint missed = s2.intersect(raymissed);
CHECK(hit.hit_);
CHECK(hit.name_ == "No_name");
CHECK(!missed.hit_);
CHECK(missed.name_ == "miss");
}
TEST_CASE("Aufgabe 5.8", "Shape") {
glm::vec3 position{0.0f, 0.0f, 0.0f};
Sphere *s1 = new Sphere{position, 1.2f};
Shape *s2 = new Sphere{position, 1.2f};
s1->print(std::cout);
s2->print(std::cout);
delete s1;
delete s2;
}
//TODO more test cases
TEST_CASE("Aufgabe 6.3 intersect ray-box", "Box") {
Box b1{{0, 0, 0},
{10, 10, 10}};
Ray orig{{20, 5, 5},
{-1, 0, 0}};
Hitpoint hitp = b1.intersect(orig);
CHECK(hitp.hit_);
CHECK(hitp.hitpoint_.x == 10);
CHECK(hitp.hitpoint_.y == 5);
CHECK(hitp.hitpoint_.z == 5);
}
TEST_CASE("More intersect tests for boxes", "[intersect,Box]"){
Box b1{glm::vec3{0, 0, 0}, glm::vec3{10, 10, 10}};
Ray r1{glm::vec3{5, 20, 5}, glm::vec3{0, -1, 0}};
Hitpoint hitp = b1.intersect(r1);
CHECK(hitp.hit_);
CHECK(hitp.hitpoint_.x == 5);
CHECK(hitp.hitpoint_.y == 10);
CHECK(hitp.hitpoint_.z == 5);
Ray r2{glm::vec3{30, 30, 30}, glm::vec3{-1, -1, -1}};
/* Hitpoint hitp1 = b1.intersect(r2);
CHECK(hitp1.hit_);
CHECK(hitp1.hitpoint_.x == 10);
CHECK(hitp1.hitpoint_.y == 10);
CHECK(hitp1.hitpoint_.z == 10); */
}
TEST_CASE("read sdf", "SDF") {
Scene scene1 = read_sdf("../../SDF-Scene/example.sdf");
auto vec = scene1.mat_vector_;
CHECK(scene1.mat_vector_[0]->name_ == "red");
std::shared_ptr<Material> red = scene1.mat_vector_[0];
CHECK(red->ka_.r == 1);
CHECK(red->ka_.g == 0);
CHECK(red->ka_.b == 0);
CHECK(red->kd_.r == 1);
CHECK(red->kd_.g == 0);
CHECK(red->kd_.b == 0);
CHECK(red->ks_.r == 1);
CHECK(red->ks_.g == 0);
CHECK(red->ks_.b == 0);
CHECK(red->m_ == 20);
CHECK(red->glossy_ == 1);
CHECK(red->opacity_ == 2);
CHECK(red->refractive_index_ == 3);
CHECK(scene1.mat_vector_[1]->name_ == "green");
std::shared_ptr<Material> green = scene1.mat_vector_[1];
CHECK(green->ka_.r == 0);
CHECK(green->ka_.g == 1);
CHECK(green->ka_.b == 0);
CHECK(green->kd_.r == 0);
CHECK(green->kd_.g == 1);
CHECK(green->kd_.b == 0);
CHECK(green->ks_.r == 0);
CHECK(green->ks_.g == 1);
CHECK(green->ks_.b == 0);
CHECK(green->m_ == 50);
CHECK(green->glossy_ == 4);
CHECK(green->opacity_ == 5);
CHECK(green->refractive_index_ == 6);
CHECK(scene1.mat_vector_[2]->name_ == "blue");
std::shared_ptr<Material> blue = scene1.mat_vector_[2];
CHECK(blue->ka_.r == 0);
CHECK(blue->ka_.g == 0);
CHECK(blue->ka_.b == 1);
CHECK(blue->kd_.r == 0);
CHECK(blue->kd_.g == 0);
CHECK(blue->kd_.b == 1);
CHECK(blue->ks_.r == 0);
CHECK(blue->ks_.g == 0);
CHECK(blue->ks_.b == 1);
CHECK(blue->m_ == 10);
CHECK(blue->glossy_ == 7);
CHECK(blue->opacity_ == 8);
CHECK(blue->refractive_index_ == 9);
CHECK(scene1.shape_vector_[0]->name_ == "sphere1");
CHECK(scene1.shape_vector_[0]->material_->name_ == "red");
CHECK(scene1.shape_vector_[1]->material_->name_ == "blue");
std::cout << *scene1.shape_vector_[0];
std::cout << *scene1.shape_vector_[1];
CHECK(scene1.shape_vector_[1]->name_ == "box1");
CHECK(scene1.lights_[0].name_ == "licht");
CHECK(scene1.lights_[0].brightness_ == 50);
CHECK(scene1.lights_[0].color_.r == 0.5f);
CHECK(scene1.lights_[0].color_.g == 0.1f);
CHECK(scene1.lights_[0].color_.b == 0.3f);
CHECK(scene1.lights_[0].position_.x == 10);
CHECK(scene1.lights_[0].position_.y == 10);
CHECK(scene1.lights_[0].position_.z == 5);
CHECK(scene1.camera_.name == "eye");
CHECK(scene1.camera_.fov == 60);
CHECK(scene1.camera_.position.x == 0);
CHECK(scene1.camera_.position.y == 0);
CHECK(scene1.camera_.position.z == 0);
CHECK(scene1.ambient_ == 0.112f);
CHECK(scene1.camera_.direction.x == 0);
CHECK(scene1.camera_.direction.y == 0);
CHECK(scene1.camera_.direction.z == -1);
CHECK(scene1.camera_.upVector.x == 0);
CHECK(scene1.camera_.upVector.y == 1);
CHECK(scene1.camera_.upVector.z == 0);
}
// new with cylinder, cone , triangle and composite starts here
/*
TEST_CASE("Testcase SDF-Reader for new shapes") {
Scene scene = read_sdf("../../SDF-Scene/composite.sdf");
CHECK(scene.ambient_ == 0.2f);
CHECK(scene.shape_vector_[0]->name_ == "rbox");
CHECK(scene.shape_vector_[1]->name_ == "bsphere");
CHECK(scene.shape_vector_[2]->name_ == "bcylinder");
std::cout << scene.shape_vector_[2]->name_;
CHECK(scene.shape_vector_[3]->name_ == "rcone");
CHECK(scene.shape_vector_[4]->name_ == "gtriangle");
CHECK(scene.shape_vector_[5]->name_ == "root");
}*/
TEST_CASE("find()", "vec,map,set") {
Scene scene1 = read_sdf("../../SDF-Scene/example.sdf");
auto vec = scene1.mat_vector_;
CHECK(find(vec, "red")->name_ == "red");
}
TEST_CASE("struct Light, print", "[Light]"){
Light l1{"Testlicht", glm::vec3{0, 0, 0}, Color{0.0f, 0.0f, 0.0f}, 0.0f};
std::cout << l1 << std::endl;
CHECK(true);
}
TEST_CASE("struct Hitpoint, print", "[Hitpoint]"){
Hitpoint h1;
std::shared_ptr<Material> mat = std::make_shared<Material>(Material{});
Hitpoint h2{true, 550.0f, "Peter", mat, glm::vec3{1, 1, 1}, glm::vec3{1, 1, 1}, glm::vec3{1, 1, 1}};
std::cout << h1 << h2 << std::endl;
CHECK(true);
}
/*TEST_CASE("Simple_renderer Test"){
Scene scene1 = read_sdf("../../SDF-Scene/example.sdf");
Renderer test_renderer(600,600,"./test_ppm_example");
test_renderer.render(scene1);
}*/
//TODO make tests for composite, cone, triangle and cylinder
TEST_CASE("Composite functions", "Composite") {
}
TEST_CASE("Cylinder functions", "Cylinder") {
Cylinder cy1 = Cylinder();
Cylinder cy2 = Cylinder(glm::vec3{10.0f, 10.0f, 0.0f}, glm::vec3{10.0f, 10.0f, 10.0f}, 5.0f);
std::shared_ptr<Material> test_material = std::make_shared<Material>(Material{});
Cylinder cy3 = Cylinder(glm::vec3{10.0f, -10.0f, 0.0f}, glm::vec3{10.0f, -10.0f, 10.0f}, 3.0f, "Testzylinder", test_material);
CHECK(cy1.area() == 0.0f);
CHECK(cy2.area() == Approx(471.239));
CHECK(cy3.area() == Approx(245.044));
CHECK(cy1.volume() == 0.0f);
CHECK(cy2.volume() == Approx(785.398));
CHECK(cy3.volume() == Approx(282.743));
CHECK(cy1.get_height() == 0.0f);
CHECK(cy2.get_height() == 10.0f);
CHECK(cy3.get_height() == 10.0f);
std::cout << cy1 << cy2 << cy3 << std::endl;
Cylinder cy4 = Cylinder(glm::vec3{0.0f, 0.0f, 0.0f}, glm::vec3{0.0f, 10.0f, 0.0f}, 5.0f);
Ray ray1{glm::vec3{3.0f, 5.0f, 10.0f}, glm::vec3{0.0f, 0.0f ,-1.0f}};
Hitpoint hitpoint1 = cy4.intersect(ray1);
CHECK(hitpoint1.hit_);
CHECK(hitpoint1.direction_ == ray1.direction_);
std::cout << hitpoint1;
Ray ray2{glm::vec3{3.0f, 3.0f, 10.0f}, glm::vec3{0.0f, 0.0f, 1.0f}};
Hitpoint hitpoint2 = cy4.intersect(ray2);
CHECK(!hitpoint2.hit_);
Ray ray3{glm::vec3{0.0f, -10.0f, 0.0f}, glm::vec3{0.0f, 1.0f, 0.0f}};
Hitpoint hitpoint3 = cy4.intersect(ray3);
CHECK(hitpoint3.hit_);
CHECK(hitpoint3.distance_ == 10.0f);
CHECK(hitpoint3.hitpoint_.x == 0.0f); CHECK(hitpoint3.hitpoint_.y == 0.0f); CHECK(hitpoint3.hitpoint_.z == 0.0f);
CHECK(hitpoint3.normal_.x == 0.0f); CHECK(hitpoint3.normal_.y == -1.0f); CHECK(hitpoint3.normal_.x == 0.0f);
CHECK(hitpoint3.name_ == cy4.name_);
Ray ray4{glm::vec3{0.0f, 20.0f, 0.0f}, glm::vec3{0.0f, -1.0f, 0.0f}};
Hitpoint hitpoint4 = cy4.intersect(ray4);
CHECK(hitpoint4.hit_);
CHECK(hitpoint4.distance_ == 10.0f);
CHECK(hitpoint4.hitpoint_.x == 0.0f); CHECK(hitpoint4.hitpoint_.y == 10.0f); CHECK(hitpoint4.hitpoint_.z == 0.0f);
CHECK(hitpoint4.normal_.x == 0.0f); CHECK(hitpoint4.normal_.y == 1.0f); CHECK(hitpoint4.normal_.x == 0.0f);
Ray ray5{glm::vec3{0.0f, 11.0f, 0.0f}, glm::vec3{0.0f, -1.0f, -1.0f}};
Hitpoint hitpoint5 = cy4.intersect(ray5);
CHECK(hitpoint5.hit_);
CHECK(hitpoint5.hitpoint_.y == 10.0f);
Cylinder cy5 = Cylinder(glm::vec3{7.0f, 0.0f, 7.0f}, glm::vec3{7.0f, 12.0f, 7.0f}, 5.0f);
Ray ray6{glm::vec3{7.0f, -5.0f, 17.0f}, glm::vec3{0.0f, 1.0f, -1.0f}};
Hitpoint hitpoint6 = cy5.intersect(ray6);
CHECK(hitpoint6.hit_);
}
TEST_CASE("Cone functions", "Cone") {
Cone co1 = Cone();
Cone co2 = Cone(glm::vec3{0.0f, 0.0f, 0.0f}, glm::vec3{0.0f, 12.0, 0.0f}, 6.0f);
std::shared_ptr<Material> test_material = std::make_shared<Material>(Material{});
Cone co3 = Cone(glm::vec3{0.0f, 0.0f, 0.0f}, glm::vec3{0.0f, 15.0f, 0.0f}, 6.0f, "Testkegel", test_material);
CHECK(co1.area() == 0.0f);
CHECK(co2.area() == Approx(365.99f));
CHECK(co3.area() == Approx(417.621f));
CHECK(co1.volume() == 0.0f);
CHECK(co2.volume() == Approx(452.389));
CHECK(co3.volume() == Approx(565.486));
CHECK(co1.get_height() == 0.0f);
CHECK(co2.get_height() == 12.0f);
CHECK(co3.get_height() == 15.0f);
std::cout << co1 << co2 << co3 << std::endl;
Ray r1{glm::vec3{0.0f, 5.0f, 10.0f}, glm::vec3{0.0f, 0.0f, -1.0f}};
Hitpoint hitpoint1 = co3.intersect(r1);
CHECK(hitpoint1.hit_);
Ray r2{glm::vec3{7.0f, 7.0f, 0.0f}, glm::vec3{-0.5f, -0.5f, 0.0f}};
Hitpoint hitpoint2 = co3.intersect(r2);
CHECK(hitpoint2.hit_);
Ray r3{glm::vec3{0.0f, -5.0f, 0.0f}, glm::vec3{0.0f, 1.0f, 0.0f}};
Hitpoint hitpoint3 = co3.intersect(r3);
CHECK(hitpoint3.hit_);
Ray r4{glm::vec3{0.0f, 20.0f, 0.0f}, glm::vec3{0.0f, -1.0f, 0.0f}};
Hitpoint hitpoint4 = co3.intersect(r4);
CHECK(hitpoint4.hit_);
Cone co4 = Cone(glm::vec3{5.0f, 0.0f ,5.0f}, glm::vec3{5.0f, 12.0f, 5.0f}, 6.0f);
Ray r5{glm::vec3{5.0f, 3.0f, 12.0f}, glm::vec3{0.0f, -0.35f, -1.0f}};
Hitpoint hitpoint5 = co4.intersect(r5);
CHECK(hitpoint5.hit_);
Ray r6{glm::vec3{5.0f, 3.0f, 12.0f}, glm::vec3{0.0f, -0.08f, -1.0f}};
Hitpoint hitpoint6 = co4.intersect(r6);
CHECK(hitpoint6.hit_);
Ray r7{glm::vec3{0.0f, 1.0f, 20.0f}, glm::vec3{0.0f, 0.0f, -1.0f}};
Hitpoint hitpoint7 = co3.intersect(r7);
CHECK(hitpoint7.hit_);
}
TEST_CASE("Triangle functions", "Triangle") {
Triangle triangle1({1, 0, 1}, {1, 0, -1}, {1, 1, 0});
Ray ray{{0, 0, 0},
{1, 0, 0}};
Hitpoint hitp = triangle1.intersect(ray);
CHECK(hitp.hit_);
CHECK(hitp.name_ == "No_name");
CHECK(hitp.direction_ == ray.direction_);
CHECK(hitp.normal_.x == 1.0f);
CHECK(hitp.normal_.y == 0);
CHECK(hitp.normal_.z == 0);
}
TEST_CASE("Plane functions"){
Plane plane({1,1,1},{0,0,0},"plane1", nullptr);
std::cout << plane;
}
TEST_CASE("Extra test cases.", "[EXTRA]"){
Sphere sp1 = Sphere(glm::vec3{0.0f, 0.0f, 0.0f}, 100.0f);
Ray r1{glm::vec3{0.0f, 0.0f, 0.0f}, glm::vec3{0.0f, 0.0f, -1.0f}};
Hitpoint hitpoint1 = sp1.intersect(r1);
std::cout << hitpoint1 << std::endl;
Ray r2{glm::vec3{60.0f, 0.0f, 200.0f}, glm::vec3{0.0f, 0.0f, -1.0f}};
Hitpoint hitpoint2 = sp1.intersect(r2);
std::cout << hitpoint2 << std::endl;
}
| 35.246411 | 130 | 0.590986 | [
"render",
"shape"
] |
9ee19389ab774d5b8ed05bbc751233e6c0c168b4 | 37,238 | cc | C++ | Validation/RecoEgamma/plugins/ElectronMcMiniAODSignalValidator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 4 | 2020-06-27T23:27:21.000Z | 2020-11-19T09:17:01.000Z | Validation/RecoEgamma/plugins/ElectronMcMiniAODSignalValidator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 524 | 2018-01-29T15:50:45.000Z | 2021-08-04T14:03:21.000Z | Validation/RecoEgamma/plugins/ElectronMcMiniAODSignalValidator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 7 | 2018-02-19T11:17:13.000Z | 2020-10-12T21:57:00.000Z | // system include files
//#include <memory>
// user include files
#include "Validation/RecoEgamma/plugins/ElectronMcMiniAODSignalValidator.h"
#include "CLHEP/Units/GlobalPhysicalConstants.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
// user include files
using namespace reco;
using namespace pat;
typedef edm::Ptr<pat::Electron> PatElectronPtr;
ElectronMcSignalValidatorMiniAOD::ElectronMcSignalValidatorMiniAOD(const edm::ParameterSet& iConfig)
: ElectronDqmAnalyzerBase(iConfig) {
mcTruthCollection_ = consumes<edm::View<reco::GenParticle> >(
iConfig.getParameter<edm::InputTag>("mcTruthCollection")); // prunedGenParticles
electronToken_ =
consumes<pat::ElectronCollection>(iConfig.getParameter<edm::InputTag>("electrons")); // slimmedElectrons
edm::ParameterSet histosSet = iConfig.getParameter<edm::ParameterSet>("histosCfg");
edm::ParameterSet isolationSet = iConfig.getParameter<edm::ParameterSet>("isolationCfg");
//recomp
pfSumChargedHadronPtTmp_ =
consumes<edm::ValueMap<float> >(isolationSet.getParameter<edm::InputTag>("pfSumChargedHadronPtTmp")); // iConfig
pfSumNeutralHadronEtTmp_ =
consumes<edm::ValueMap<float> >(isolationSet.getParameter<edm::InputTag>("pfSumNeutralHadronEtTmp")); // iConfig
pfSumPhotonEtTmp_ =
consumes<edm::ValueMap<float> >(isolationSet.getParameter<edm::InputTag>("pfSumPhotonEtTmp")); // iConfig
maxPt_ = iConfig.getParameter<double>("MaxPt");
maxAbsEta_ = iConfig.getParameter<double>("MaxAbsEta");
deltaR_ = iConfig.getParameter<double>("DeltaR");
deltaR2_ = deltaR_ * deltaR_;
matchingIDs_ = iConfig.getParameter<std::vector<int> >("MatchingID");
matchingMotherIDs_ = iConfig.getParameter<std::vector<int> >("MatchingMotherID");
outputInternalPath_ = iConfig.getParameter<std::string>("OutputFolderName");
// histos bining and limits
xyz_nbin = histosSet.getParameter<int>("Nbinxyz");
pt_nbin = histosSet.getParameter<int>("Nbinpt");
pt2D_nbin = histosSet.getParameter<int>("Nbinpt2D");
pteff_nbin = histosSet.getParameter<int>("Nbinpteff");
pt_max = histosSet.getParameter<double>("Ptmax");
fhits_nbin = histosSet.getParameter<int>("Nbinfhits");
fhits_max = histosSet.getParameter<double>("Fhitsmax");
eta_nbin = histosSet.getParameter<int>("Nbineta");
eta2D_nbin = histosSet.getParameter<int>("Nbineta2D");
eta_min = histosSet.getParameter<double>("Etamin");
eta_max = histosSet.getParameter<double>("Etamax");
detamatch_nbin = histosSet.getParameter<int>("Nbindetamatch");
detamatch2D_nbin = histosSet.getParameter<int>("Nbindetamatch2D");
detamatch_min = histosSet.getParameter<double>("Detamatchmin");
detamatch_max = histosSet.getParameter<double>("Detamatchmax");
dphi_nbin = histosSet.getParameter<int>("Nbindphi");
dphi_min = histosSet.getParameter<double>("Dphimin");
dphi_max = histosSet.getParameter<double>("Dphimax");
dphimatch_nbin = histosSet.getParameter<int>("Nbindphimatch");
dphimatch2D_nbin = histosSet.getParameter<int>("Nbindphimatch2D");
dphimatch_min = histosSet.getParameter<double>("Dphimatchmin");
dphimatch_max = histosSet.getParameter<double>("Dphimatchmax");
hoe_nbin = histosSet.getParameter<int>("Nbinhoe");
hoe_min = histosSet.getParameter<double>("Hoemin");
hoe_max = histosSet.getParameter<double>("Hoemax");
mee_nbin = histosSet.getParameter<int>("Nbinmee");
mee_min = histosSet.getParameter<double>("Meemin");
mee_max = histosSet.getParameter<double>("Meemax");
poptrue_nbin = histosSet.getParameter<int>("Nbinpoptrue");
poptrue_min = histosSet.getParameter<double>("Poptruemin");
poptrue_max = histosSet.getParameter<double>("Poptruemax");
set_EfficiencyFlag = histosSet.getParameter<bool>("EfficiencyFlag");
set_StatOverflowFlag = histosSet.getParameter<bool>("StatOverflowFlag");
// so to please coverity...
h1_recEleNum = nullptr;
h1_ele_vertexPt = nullptr;
h1_ele_vertexEta = nullptr;
h1_ele_vertexPt_nocut = nullptr;
h1_scl_SigIEtaIEta_mAOD = nullptr;
h1_scl_SigIEtaIEta_mAOD_barrel = nullptr;
h1_scl_SigIEtaIEta_mAOD_endcaps = nullptr;
h2_ele_foundHitsVsEta = nullptr;
h2_ele_foundHitsVsEta_mAOD = nullptr;
h2_ele_PoPtrueVsEta = nullptr;
h2_ele_sigmaIetaIetaVsPt = nullptr;
h1_ele_HoE_mAOD = nullptr;
h1_ele_HoE_mAOD_barrel = nullptr;
h1_ele_HoE_mAOD_endcaps = nullptr;
h1_ele_mee_all = nullptr;
h1_ele_mee_os = nullptr;
h1_ele_fbrem_mAOD = nullptr;
h1_ele_fbrem_mAOD_barrel = nullptr;
h1_ele_fbrem_mAOD_endcaps = nullptr;
h1_ele_dEtaSc_propVtx_mAOD = nullptr;
h1_ele_dEtaSc_propVtx_mAOD_barrel = nullptr;
h1_ele_dEtaSc_propVtx_mAOD_endcaps = nullptr;
h1_ele_dPhiCl_propOut_mAOD = nullptr;
h1_ele_dPhiCl_propOut_mAOD_barrel = nullptr;
h1_ele_dPhiCl_propOut_mAOD_endcaps = nullptr;
h1_ele_chargedHadronRelativeIso_mAOD = nullptr;
h1_ele_chargedHadronRelativeIso_mAOD_barrel = nullptr;
h1_ele_chargedHadronRelativeIso_mAOD_endcaps = nullptr;
h1_ele_neutralHadronRelativeIso_mAOD = nullptr;
h1_ele_neutralHadronRelativeIso_mAOD_barrel = nullptr;
h1_ele_neutralHadronRelativeIso_mAOD_endcaps = nullptr;
h1_ele_photonRelativeIso_mAOD = nullptr;
h1_ele_photonRelativeIso_mAOD_barrel = nullptr;
h1_ele_photonRelativeIso_mAOD_endcaps = nullptr;
h1_ele_chargedHadronRelativeIso_mAOD_recomp = nullptr;
h1_ele_neutralHadronRelativeIso_mAOD_recomp = nullptr;
h1_ele_photonRelativeIso_mAOD_recomp = nullptr;
}
ElectronMcSignalValidatorMiniAOD::~ElectronMcSignalValidatorMiniAOD() {}
void ElectronMcSignalValidatorMiniAOD::bookHistograms(DQMStore::IBooker& iBooker,
edm::Run const&,
edm::EventSetup const&) {
iBooker.setCurrentFolder(outputInternalPath_);
setBookIndex(-1);
setBookPrefix("h");
setBookEfficiencyFlag(set_EfficiencyFlag);
setBookStatOverflowFlag(set_StatOverflowFlag);
// rec event collections sizes
h1_recEleNum = bookH1(iBooker, "recEleNum", "# rec electrons", 11, -0.5, 10.5, "N_{ele}");
// matched electrons
setBookPrefix("h_mc");
setBookPrefix("h_ele");
h1_ele_vertexPt =
bookH1withSumw2(iBooker, "vertexPt", "ele transverse momentum", pt_nbin, 0., pt_max, "p_{T vertex} (GeV/c)");
h1_ele_vertexEta = bookH1withSumw2(iBooker, "vertexEta", "ele momentum eta", eta_nbin, eta_min, eta_max, "#eta");
h1_ele_vertexPt_nocut =
bookH1withSumw2(iBooker, "vertexPt_nocut", "pT of prunned electrons", pt_nbin, 0., 20., "p_{T vertex} (GeV/c)");
h2_ele_PoPtrueVsEta = bookH2withSumw2(iBooker,
"PoPtrueVsEta",
"ele momentum / gen momentum vs eta",
eta2D_nbin,
eta_min,
eta_max,
50,
poptrue_min,
poptrue_max);
// h2_ele_sigmaIetaIetaVsPt = bookH2(iBooker,"sigmaIetaIetaVsPt","SigmaIetaIeta vs pt",pt_nbin,0.,pt_max,100,0.,0.05);
h2_ele_sigmaIetaIetaVsPt =
bookH2(iBooker, "sigmaIetaIetaVsPt", "SigmaIetaIeta vs pt", 100, 0., pt_max, 100, 0., 0.05);
// all electrons
setBookPrefix("h_ele");
h1_ele_mee_all = bookH1withSumw2(iBooker,
"mee_all",
"ele pairs invariant mass, all reco electrons",
mee_nbin,
mee_min,
mee_max,
"m_{ee} (GeV/c^{2})",
"Events",
"ELE_LOGY E1 P");
h1_ele_mee_os = bookH1withSumw2(iBooker,
"mee_os",
"ele pairs invariant mass, opp. sign",
mee_nbin,
mee_min,
mee_max,
"m_{e^{+}e^{-}} (GeV/c^{2})",
"Events",
"ELE_LOGY E1 P");
// matched electron, superclusters
setBookPrefix("h_scl");
h1_scl_SigIEtaIEta_mAOD = bookH1withSumw2(iBooker,
"SigIEtaIEta_mAOD",
"ele supercluster sigma ieta ieta",
100,
0.,
0.05,
"#sigma_{i#eta i#eta}",
"Events",
"ELE_LOGY E1 P");
h1_scl_SigIEtaIEta_mAOD_barrel = bookH1withSumw2(iBooker,
"SigIEtaIEta_mAOD_barrel",
"ele supercluster sigma ieta ieta, barrel",
100,
0.,
0.05,
"#sigma_{i#eta i#eta}",
"Events",
"ELE_LOGY E1 P");
h1_scl_SigIEtaIEta_mAOD_endcaps = bookH1withSumw2(iBooker,
"SigIEtaIEta_mAOD_endcaps",
"ele supercluster sigma ieta ieta, endcaps",
100,
0.,
0.05,
"#sigma_{i#eta i#eta}",
"Events",
"ELE_LOGY E1 P");
// matched electron, gsf tracks
setBookPrefix("h_ele");
h2_ele_foundHitsVsEta = bookH2(iBooker,
"foundHitsVsEta",
"ele track # found hits vs eta",
eta2D_nbin,
eta_min,
eta_max,
fhits_nbin,
0.,
fhits_max);
h2_ele_foundHitsVsEta_mAOD = bookH2(iBooker,
"foundHitsVsEta_mAOD",
"ele track # found hits vs eta",
eta2D_nbin,
eta_min,
eta_max,
fhits_nbin,
0.,
fhits_max);
// matched electrons, matching
setBookPrefix("h_ele");
h1_ele_HoE_mAOD = bookH1withSumw2(iBooker,
"HoE_mAOD",
"ele hadronic energy / em energy",
hoe_nbin,
hoe_min,
hoe_max,
"H/E",
"Events",
"ELE_LOGY E1 P");
h1_ele_HoE_mAOD_barrel = bookH1withSumw2(iBooker,
"HoE_mAOD_barrel",
"ele hadronic energy / em energy, barrel",
hoe_nbin,
hoe_min,
hoe_max,
"H/E",
"Events",
"ELE_LOGY E1 P");
h1_ele_HoE_mAOD_endcaps = bookH1withSumw2(iBooker,
"HoE_mAOD_endcaps",
"ele hadronic energy / em energy, endcaps",
hoe_nbin,
hoe_min,
hoe_max,
"H/E",
"Events",
"ELE_LOGY E1 P");
h1_ele_dEtaSc_propVtx_mAOD = bookH1withSumw2(iBooker,
"dEtaSc_propVtx_mAOD",
"ele #eta_{sc} - #eta_{tr}, prop from vertex",
detamatch_nbin,
detamatch_min,
detamatch_max,
"#eta_{sc} - #eta_{tr}",
"Events",
"ELE_LOGY E1 P");
h1_ele_dEtaSc_propVtx_mAOD_barrel = bookH1withSumw2(iBooker,
"dEtaSc_propVtx_mAOD_barrel",
"ele #eta_{sc} - #eta_{tr}, prop from vertex, barrel",
detamatch_nbin,
detamatch_min,
detamatch_max,
"#eta_{sc} - #eta_{tr}",
"Events",
"ELE_LOGY E1 P");
h1_ele_dEtaSc_propVtx_mAOD_endcaps = bookH1withSumw2(iBooker,
"dEtaSc_propVtx_mAOD_endcaps",
"ele #eta_{sc} - #eta_{tr}, prop from vertex, endcaps",
detamatch_nbin,
detamatch_min,
detamatch_max,
"#eta_{sc} - #eta_{tr}",
"Events",
"ELE_LOGY E1 P");
h1_ele_dPhiCl_propOut_mAOD = bookH1withSumw2(iBooker,
"dPhiCl_propOut_mAOD",
"ele #phi_{cl} - #phi_{tr}, prop from outermost",
dphimatch_nbin,
dphimatch_min,
dphimatch_max,
"#phi_{seedcl} - #phi_{tr} (rad)",
"Events",
"ELE_LOGY E1 P");
h1_ele_dPhiCl_propOut_mAOD_barrel = bookH1withSumw2(iBooker,
"dPhiCl_propOut_mAOD_barrel",
"ele #phi_{cl} - #phi_{tr}, prop from outermost, barrel",
dphimatch_nbin,
dphimatch_min,
dphimatch_max,
"#phi_{seedcl} - #phi_{tr} (rad)",
"Events",
"ELE_LOGY E1 P");
h1_ele_dPhiCl_propOut_mAOD_endcaps = bookH1withSumw2(iBooker,
"dPhiCl_propOut_mAOD_endcaps",
"ele #phi_{cl} - #phi_{tr}, prop from outermost, endcaps",
dphimatch_nbin,
dphimatch_min,
dphimatch_max,
"#phi_{seedcl} - #phi_{tr} (rad)",
"Events",
"ELE_LOGY E1 P");
// fbrem
h1_ele_fbrem_mAOD = bookH1withSumw2(
iBooker, "fbrem_mAOD", "ele brem fraction, mode of GSF components", 100, 0., 1., "P_{in} - P_{out} / P_{in}");
h1_ele_fbrem_mAOD_barrel = bookH1withSumw2(iBooker,
"fbrem_mAOD_barrel",
"ele brem fraction for barrel, mode of GSF components",
100,
0.,
1.,
"P_{in} - P_{out} / P_{in}");
h1_ele_fbrem_mAOD_endcaps = bookH1withSumw2(iBooker,
"fbrem_mAOD_endcaps",
"ele brem franction for endcaps, mode of GSF components",
100,
0.,
1.,
"P_{in} - P_{out} / P_{in}");
// -- pflow over pT
h1_ele_chargedHadronRelativeIso_mAOD = bookH1withSumw2(iBooker,
"chargedHadronRelativeIso_mAOD",
"chargedHadronRelativeIso",
100,
0.0,
2.,
"chargedHadronRelativeIso",
"Events",
"ELE_LOGY E1 P");
h1_ele_chargedHadronRelativeIso_mAOD_barrel = bookH1withSumw2(iBooker,
"chargedHadronRelativeIso_mAOD_barrel",
"chargedHadronRelativeIso for barrel",
100,
0.0,
2.,
"chargedHadronRelativeIso_barrel",
"Events",
"ELE_LOGY E1 P");
h1_ele_chargedHadronRelativeIso_mAOD_endcaps = bookH1withSumw2(iBooker,
"chargedHadronRelativeIso_mAOD_endcaps",
"chargedHadronRelativeIso for endcaps",
100,
0.0,
2.,
"chargedHadronRelativeIso_endcaps",
"Events",
"ELE_LOGY E1 P");
h1_ele_neutralHadronRelativeIso_mAOD = bookH1withSumw2(iBooker,
"neutralHadronRelativeIso_mAOD",
"neutralHadronRelativeIso",
100,
0.0,
2.,
"neutralHadronRelativeIso",
"Events",
"ELE_LOGY E1 P");
h1_ele_neutralHadronRelativeIso_mAOD_barrel = bookH1withSumw2(iBooker,
"neutralHadronRelativeIso_mAOD_barrel",
"neutralHadronRelativeIso for barrel",
100,
0.0,
2.,
"neutralHadronRelativeIso_barrel",
"Events",
"ELE_LOGY E1 P");
h1_ele_neutralHadronRelativeIso_mAOD_endcaps = bookH1withSumw2(iBooker,
"neutralHadronRelativeIso_mAOD_endcaps",
"neutralHadronRelativeIso for endcaps",
100,
0.0,
2.,
"neutralHadronRelativeIso_endcaps",
"Events",
"ELE_LOGY E1 P");
h1_ele_photonRelativeIso_mAOD = bookH1withSumw2(iBooker,
"photonRelativeIso_mAOD",
"photonRelativeIso",
100,
0.0,
2.,
"photonRelativeIso",
"Events",
"ELE_LOGY E1 P");
h1_ele_photonRelativeIso_mAOD_barrel = bookH1withSumw2(iBooker,
"photonRelativeIso_mAOD_barrel",
"photonRelativeIso for barrel",
100,
0.0,
2.,
"photonRelativeIso_barrel",
"Events",
"ELE_LOGY E1 P");
h1_ele_photonRelativeIso_mAOD_endcaps = bookH1withSumw2(iBooker,
"photonRelativeIso_mAOD_endcaps",
"photonRelativeIso for endcaps",
100,
0.0,
2.,
"photonRelativeIso_endcaps",
"Events",
"ELE_LOGY E1 P");
// -- recomputed pflow over pT
h1_ele_chargedHadronRelativeIso_mAOD_recomp = bookH1withSumw2(iBooker,
"chargedHadronRelativeIso_mAOD_recomp",
"recomputed chargedHadronRelativeIso",
100,
0.0,
2.,
"chargedHadronRelativeIso",
"Events",
"ELE_LOGY E1 P");
h1_ele_neutralHadronRelativeIso_mAOD_recomp = bookH1withSumw2(iBooker,
"neutralHadronRelativeIso_mAOD_recomp",
"recomputed neutralHadronRelativeIso",
100,
0.0,
2.,
"neutralHadronRelativeIso",
"Events",
"ELE_LOGY E1 P");
h1_ele_photonRelativeIso_mAOD_recomp = bookH1withSumw2(iBooker,
"photonRelativeIso_mAOD_recomp",
"recomputed photonRelativeIso",
100,
0.0,
2.,
"photonRelativeIso",
"Events",
"ELE_LOGY E1 P");
}
void ElectronMcSignalValidatorMiniAOD::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
// get collections
edm::Handle<pat::ElectronCollection> electrons;
iEvent.getByToken(electronToken_, electrons);
edm::Handle<edm::View<reco::GenParticle> > genParticles;
iEvent.getByToken(mcTruthCollection_, genParticles);
//recomp
edm::Handle<edm::ValueMap<float> > pfSumChargedHadronPtTmp;
edm::Handle<edm::ValueMap<float> > pfSumNeutralHadronEtTmp;
edm::Handle<edm::ValueMap<float> > pfSumPhotonEtTmp; /**/
//recomp
iEvent.getByToken(pfSumChargedHadronPtTmp_, pfSumChargedHadronPtTmp);
iEvent.getByToken(pfSumNeutralHadronEtTmp_, pfSumNeutralHadronEtTmp);
iEvent.getByToken(pfSumPhotonEtTmp_, pfSumPhotonEtTmp); /**/
edm::LogInfo("ElectronMcSignalValidatorMiniAOD::analyze")
<< "Treating event " << iEvent.id() << " with " << electrons.product()->size() << " electrons";
h1_recEleNum->Fill((*electrons).size());
//===============================================
// all rec electrons
//===============================================
pat::Electron gsfElectron;
pat::ElectronCollection::const_iterator el1;
pat::ElectronCollection::const_iterator el2;
for (el1 = electrons->begin(); el1 != electrons->end(); el1++) {
for (el2 = el1 + 1; el2 != electrons->end(); el2++) {
math::XYZTLorentzVector p12 = el1->p4() + el2->p4();
float mee2 = p12.Dot(p12);
h1_ele_mee_all->Fill(sqrt(mee2));
if (el1->charge() * el2->charge() < 0.) {
h1_ele_mee_os->Fill(sqrt(mee2));
}
}
}
//===============================================
// charge mis-ID
//===============================================
int mcNum = 0, gamNum = 0, eleNum = 0;
// bool matchingID;//, matchingMotherID ;
bool matchingMotherID;
//===============================================
// association mc-reco
//===============================================
for (size_t i = 0; i < genParticles->size(); i++) {
/* // DEBUG LINES - KEEP IT !
std::cout << "\nevt ID = " << iEvent.id() ;
std::cout << ", mcIter position : " << i << std::endl;
std::cout << "pdgID : " << (*genParticles)[i].pdgId() << ", Pt : " << (*genParticles)[i].pt() ;
std::cout << ", eta : " << (*genParticles)[i].eta() << ", phi : " << (*genParticles)[i].phi() << std::endl;
// DEBUG LINES - KEEP IT ! */
// number of mc particles
mcNum++;
// counts photons
if ((*genParticles)[i].pdgId() == 22) {
gamNum++;
}
// select requested mother matching gen particle
// always include single particle with no mother
const Candidate* mother = (*genParticles)[i].mother(0);
matchingMotherID = false;
for (unsigned int ii = 0; ii < matchingMotherIDs_.size(); ii++) {
/* // DEBUG LINES - KEEP IT !
std::cout << "Matching : matchingMotherID[" << ii << "] : "<< matchingMotherIDs_[ii] << ", evt ID = " << iEvent.id() << ", mother : " << mother ;
if (mother != 0) {
std::cout << "mother : " << mother << ", mother pdgID : " << mother->pdgId() << std::endl ;
std::cout << "mother pdgID : " << mother->pdgId() << ", Pt : " << mother->pt() << ", eta : " << mother->eta() << ", phi : " << mother->phi() << std::endl;
}
else {
std::cout << std::endl;
}
// DEBUG LINES - KEEP IT ! */
if (mother == nullptr) {
matchingMotherID = true;
} else if (mother->pdgId() == matchingMotherIDs_[ii]) {
if (mother->numberOfDaughters() <= 2) {
matchingMotherID = true;
//std::cout << "evt ID = " << iEvent.id() ; // debug lines
//std::cout << " - nb of Daughters : " << mother->numberOfDaughters() << " - pdgId() : " << mother->pdgId() << std::endl; // debug lines
}
} // end of mother if test
/* // DEBUG LINES - KEEP IT !
if (mother != 0) {
std::cout << "mother : " << mother << ", mother pdgID : " << mother->pdgId() << std::endl ;
std::cout << "mother pdgID : " << mother->pdgId() << ", Pt : " << mother->pt() << ", eta : " << mother->eta() << ", phi : " << mother->phi() << std::endl;
}
// DEBUG LINES - KEEP IT ! */
} // end of for loop
if (!matchingMotherID) {
continue;
}
// electron preselection
if ((*genParticles)[i].pt() > maxPt_ || std::abs((*genParticles)[i].eta()) > maxAbsEta_) {
continue;
}
eleNum++;
// find best matched electron
bool okGsfFound = false;
bool passMiniAODSelection = true;
double gsfOkRatio = 999999.;
pat::Electron bestGsfElectron;
for (const pat::Electron& el : *electrons) {
double dphi = el.phi() - (*genParticles)[i].phi();
if (std::abs(dphi) > CLHEP::pi) {
dphi = dphi < 0 ? (CLHEP::twopi) + dphi : dphi - CLHEP::twopi;
}
double deltaR2 = (el.eta() - (*genParticles)[i].eta()) * (el.eta() - (*genParticles)[i].eta()) + dphi * dphi;
if (deltaR2 < deltaR2_) {
if ((((*genParticles)[i].pdgId() == 11) && (el.charge() < 0.)) ||
(((*genParticles)[i].pdgId() == -11) && (el.charge() > 0.))) {
double tmpGsfRatio = el.p() / (*genParticles)[i].p();
if (std::abs(tmpGsfRatio - 1) < std::abs(gsfOkRatio - 1)) {
gsfOkRatio = tmpGsfRatio;
bestGsfElectron = el;
PatElectronPtr elePtr(electrons, &el - &(*electrons)[0]);
pt_ = elePtr->pt();
sumChargedHadronPt_recomp = (*pfSumChargedHadronPtTmp)[elePtr];
relisoChargedHadronPt_recomp = sumChargedHadronPt_recomp / pt_;
sumNeutralHadronPt_recomp = (*pfSumNeutralHadronEtTmp)[elePtr];
relisoNeutralHadronPt_recomp = sumNeutralHadronPt_recomp / pt_;
sumPhotonPt_recomp = (*pfSumPhotonEtTmp)[elePtr];
relisoPhotonPt_recomp = sumPhotonPt_recomp / pt_;
okGsfFound = true;
// DEBUG LINES - KEEP IT !
// std::cout << "evt ID : " << iEvent.id() << " - Pt : " << bestGsfElectron.pt() << " - eta : " << bestGsfElectron.eta() << " - phi : " << bestGsfElectron.phi() << std::endl;
// DEBUG LINES - KEEP IT ! /**/
}
}
}
}
if (!okGsfFound)
continue;
//------------------------------------
// analysis when the mc track is found
//------------------------------------
passMiniAODSelection = bestGsfElectron.pt() >= 5.;
// electron related distributions
h1_ele_vertexPt->Fill(bestGsfElectron.pt());
h1_ele_vertexEta->Fill(bestGsfElectron.eta());
if ((bestGsfElectron.scSigmaIEtaIEta() == 0.) && (bestGsfElectron.fbrem() == 0.))
h1_ele_vertexPt_nocut->Fill(bestGsfElectron.pt());
// generated distributions for matched electrons
h2_ele_PoPtrueVsEta->Fill(bestGsfElectron.eta(), bestGsfElectron.p() / (*genParticles)[i].p());
if (passMiniAODSelection) { // Pt > 5.
h2_ele_sigmaIetaIetaVsPt->Fill(bestGsfElectron.pt(), bestGsfElectron.scSigmaIEtaIEta());
}
// supercluster related distributions
if (passMiniAODSelection) { // Pt > 5.
h1_scl_SigIEtaIEta_mAOD->Fill(bestGsfElectron.scSigmaIEtaIEta());
h1_ele_dEtaSc_propVtx_mAOD->Fill(bestGsfElectron.deltaEtaSuperClusterTrackAtVtx());
h1_ele_dPhiCl_propOut_mAOD->Fill(bestGsfElectron.deltaPhiSeedClusterTrackAtCalo());
if (bestGsfElectron.isEB()) {
h1_scl_SigIEtaIEta_mAOD_barrel->Fill(bestGsfElectron.scSigmaIEtaIEta());
h1_ele_dEtaSc_propVtx_mAOD_barrel->Fill(bestGsfElectron.deltaEtaSuperClusterTrackAtVtx());
h1_ele_dPhiCl_propOut_mAOD_barrel->Fill(bestGsfElectron.deltaPhiSeedClusterTrackAtCalo());
}
if (bestGsfElectron.isEE()) {
h1_scl_SigIEtaIEta_mAOD_endcaps->Fill(bestGsfElectron.scSigmaIEtaIEta());
h1_ele_dEtaSc_propVtx_mAOD_endcaps->Fill(bestGsfElectron.deltaEtaSuperClusterTrackAtVtx());
h1_ele_dPhiCl_propOut_mAOD_endcaps->Fill(bestGsfElectron.deltaPhiSeedClusterTrackAtCalo());
}
}
// track related distributions
h2_ele_foundHitsVsEta->Fill(bestGsfElectron.eta(), bestGsfElectron.gsfTrack()->numberOfValidHits());
if (passMiniAODSelection) { // Pt > 5.
h2_ele_foundHitsVsEta_mAOD->Fill(bestGsfElectron.eta(), bestGsfElectron.gsfTrack()->numberOfValidHits());
}
// match distributions
if (passMiniAODSelection) { // Pt > 5.
h1_ele_HoE_mAOD->Fill(bestGsfElectron.hcalOverEcal());
if (bestGsfElectron.isEB())
h1_ele_HoE_mAOD_barrel->Fill(bestGsfElectron.hcalOverEcal());
if (bestGsfElectron.isEE())
h1_ele_HoE_mAOD_endcaps->Fill(bestGsfElectron.hcalOverEcal());
}
// fbrem
// double fbrem_mode = bestGsfElectron.fbrem();
if (passMiniAODSelection) { // Pt > 5.
h1_ele_fbrem_mAOD->Fill(bestGsfElectron.fbrem());
if (bestGsfElectron.isEB())
h1_ele_fbrem_mAOD_barrel->Fill(bestGsfElectron.fbrem());
if (bestGsfElectron.isEE())
h1_ele_fbrem_mAOD_endcaps->Fill(bestGsfElectron.fbrem());
// -- pflow over pT
double one_over_pt = 1. / bestGsfElectron.pt();
h1_ele_chargedHadronRelativeIso_mAOD->Fill(bestGsfElectron.pfIsolationVariables().sumChargedHadronPt *
one_over_pt);
h1_ele_neutralHadronRelativeIso_mAOD->Fill(bestGsfElectron.pfIsolationVariables().sumNeutralHadronEt *
one_over_pt);
h1_ele_photonRelativeIso_mAOD->Fill(bestGsfElectron.pfIsolationVariables().sumPhotonEt * one_over_pt);
if (bestGsfElectron.isEB()) {
h1_ele_chargedHadronRelativeIso_mAOD_barrel->Fill(bestGsfElectron.pfIsolationVariables().sumChargedHadronPt *
one_over_pt);
h1_ele_neutralHadronRelativeIso_mAOD_barrel->Fill(bestGsfElectron.pfIsolationVariables().sumNeutralHadronEt *
one_over_pt);
h1_ele_photonRelativeIso_mAOD_barrel->Fill(bestGsfElectron.pfIsolationVariables().sumPhotonEt * one_over_pt);
}
if (bestGsfElectron.isEE()) {
h1_ele_chargedHadronRelativeIso_mAOD_endcaps->Fill(bestGsfElectron.pfIsolationVariables().sumChargedHadronPt *
one_over_pt);
h1_ele_neutralHadronRelativeIso_mAOD_endcaps->Fill(bestGsfElectron.pfIsolationVariables().sumNeutralHadronEt *
one_over_pt);
h1_ele_photonRelativeIso_mAOD_endcaps->Fill(bestGsfElectron.pfIsolationVariables().sumPhotonEt * one_over_pt);
}
// -- recomputed pflow over pT
h1_ele_chargedHadronRelativeIso_mAOD_recomp->Fill(relisoChargedHadronPt_recomp);
h1_ele_neutralHadronRelativeIso_mAOD_recomp->Fill(relisoNeutralHadronPt_recomp);
h1_ele_photonRelativeIso_mAOD_recomp->Fill(relisoPhotonPt_recomp); /**/
}
} // fin boucle size_t i
}
| 52.745042 | 193 | 0.452683 | [
"vector"
] |
9ee25e1b36fec8e07f29fc0b1d162cbe89758fc8 | 6,471 | cpp | C++ | SudokuSolver/SudokuAlgorithm/Segment.cpp | bvijay74/Puzzles | 05511707a6fa0f5b162c005f7c36c32d5c2d3044 | [
"Apache-2.0"
] | null | null | null | SudokuSolver/SudokuAlgorithm/Segment.cpp | bvijay74/Puzzles | 05511707a6fa0f5b162c005f7c36c32d5c2d3044 | [
"Apache-2.0"
] | null | null | null | SudokuSolver/SudokuAlgorithm/Segment.cpp | bvijay74/Puzzles | 05511707a6fa0f5b162c005f7c36c32d5c2d3044 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Vijayakumar Balakrishnan
//
// 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.
//
// Segment.cpp
// SudokuAlgorithm
//
#include "Segment.h"
using namespace std;
namespace SudokuAlgorithm {
// Intialize is called to prepare the segment for the solution
void Segment::Initialize() {
unsolved_nums_.clear();
// Add the numbers not present in the cells of the segment
// to the unsolved numbers list
for (UShort n=1; n<=NUM_BASE; n++) {
if (find_if(begin(cells_), end(cells_),
[n](const weak_ptr<Cell>& cell)
{ return n == cell.lock()->GetNumber();}) == end(cells_)) {
unsolved_nums_.push_back(n);
}
}
if (unsolved_nums_.empty()) {
filled_ = true;
}
}
// Count the candidate's marking in a segment
UShort Segment::GetCandidateCount(UShort num) const {
UShort count = 0;
for (auto cell : cells_) {
if (cell.lock()->GetMarking().IsMarked(num)) {
count++;
}
}
return count;
}
// Refer the cell in a segment
weak_ptr<Cell>& Segment::operator[] (UShort index) {
if (index >= cells_.size()) {
throw out_of_range("Segment[]");
}
return cells_[index];
}
// Update the solved number in the segment and its cell markings
void Segment::UpdateSolvedNumber(UShort number) {
auto itr = find(begin(unsolved_nums_), end(unsolved_nums_), number);
if (itr != end(unsolved_nums_)) {
unsolved_nums_.erase(itr);
}
if (unsolved_nums_.empty()) {
filled_ = true;
}
for (auto cell : cells_) {
if (cell.lock()->IsEmpty()) {
cell.lock()->GetMarking().Erase(number);
}
}
}
// Find if the number is solved in the given segment
bool Segment::FindNumber(UShort number) const {
return find_if(begin(cells_), end(cells_),
[number](const weak_ptr<Cell>& cell)
{ return number == cell.lock()->GetNumber(); }) != end(cells_);
}
// Solve visible pairs, triples, quads etc.,
bool Segment::SolveVisibleSubsets() {
auto solved = false;
for (UShort i=0; i<GRID_WIDTH; i++) {
auto cell = cells_[i].lock();
if (!cell->IsEmpty()) {
continue;
}
// Count the number of occurances of the same set of candidates
vector<UShort> target_indices;
UShort count = 1;
Marking subset = cell->GetMarking();
for (UShort j=i+1; j<GRID_WIDTH; j++) {
if (cells_[j].lock()->IsEmpty()) {
if (subset == cells_[j].lock()->GetMarking()) {
count++;
} else {
target_indices.push_back(j);
}
}
}
if (count > 1 && count == subset.GetCount()) {
// Set of candidate occurances match the number of candidates in the set
// So, the candiates in the set can be eliminated from other cells in the segment
for (auto ti : target_indices) {
Marking& marking = cells_[ti].lock()->GetMarking();
if (marking.Erase(subset)) {
solved = true;
}
}
}
if (solved) {
break;
}
}
return solved;
}
// Solve hidden pairs,triples, quads etc.,
bool Segment::SolveHiddenSubsets() {
bool solved = false;
vector<weak_ptr<Cell>> empty_cells;
for (UShort i=0; i<GRID_WIDTH; i++) {
auto cell = cells_[i].lock();
if (cell->IsEmpty()) {
empty_cells.push_back(cell);
}
}
Marking subset;
UShort least_marking = GRID_WIDTH + 1;
for (UShort n=1; n<=NUM_BASE; n++) {
UShort marking_count = 0;
for (auto cell : empty_cells) {
if (cell.lock()->GetMarking().IsMarked(n)) {
if (++marking_count > least_marking) {
break;
}
}
}
if (marking_count != 0) {
// The least marked candidates in the segment could probably form a hidden subset
if (marking_count == least_marking) {
subset.Mark(n);
}
if (marking_count < least_marking) {
least_marking = marking_count;
subset.EraseAll();
subset.Mark(n);
}
}
}
// Elimnate the candidates which are already locked pairs, triples etc.,
for (auto i=0; i<empty_cells.size()-1; i++) {
Marking m1 = empty_cells[i].lock()->GetMarking();
UShort count = 1;
for (auto j=i+1; j<empty_cells.size(); j++) {
Marking m2 = empty_cells[j].lock()->GetMarking();
if (m1 == m2) {
count++;
}
}
if (count > 1 && count == m1.GetCount()) {
subset.Erase(m1);
}
}
if (subset.GetCount() != 0) {
if (subset.GetCount() > least_marking) {
// The least occuring candidates could be distributed across cells and may not form hidden subset
// Find out if a set of candidates appear in multiple cells
for (auto i=0; i<empty_cells.size()-1; i++) {
Marking s1 = subset.MatchSubset(empty_cells[i].lock()->GetMarking());
if (s1.GetCount() < 2) {
continue;
}
UShort count = 1;
for (auto j=i+1; j<empty_cells.size(); j++) {
Marking s2 = subset.MatchSubset(empty_cells[j].lock()->GetMarking());
if (s1 == s2) {
count++;
}
}
if (count > 1 && count == s1.GetCount()) {
subset = s1;
break;
}
}
}
if (subset.GetCount() < empty_cells.size()) {
vector<UShort> subset_indices;
for (UShort i=0; i<GRID_WIDTH; i++) {
auto cell = cells_[i].lock();
if (cell->IsEmpty()) {
if (!subset.MatchSubset(cell->GetMarking()).IsEmpty()) {
subset_indices.push_back(i);
if (subset_indices.size() > subset.GetCount()) {
break;
}
}
}
}
// If the subset occurs in as many cells as the size of the subset,
// eliminate other candidates in those cells
if (subset_indices.size() == subset.GetCount()) {
for (auto index : subset_indices) {
Marking& marking = cells_[index].lock()->GetMarking();
if (marking != subset) {
marking.Intersect(subset);
solved = true;
}
}
}
}
}
return solved;
}
}
| 27.189076 | 101 | 0.597898 | [
"vector"
] |
9ee43c5c60b4703f64e7a2575ec15ba59b618052 | 5,887 | cc | C++ | lite/tests/kernels/lrn_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | null | null | null | lite/tests/kernels/lrn_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | null | null | null | lite/tests/kernels/lrn_compute_test.cc | hcj5206/Paddle-Lite | eed7a506cef5d2ba6a076a34e4f51d3b5f60cddd | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "lite/api/paddle_use_kernels.h"
#include "lite/api/paddle_use_ops.h"
#include "lite/core/arena/framework.h"
namespace paddle {
namespace lite {
/**
* @brief get sum of x^2 between channels [size elements]
*
* @tparam dtype
* @param input
* @param channel_id: the c-th channel within n-th graph.
* @param offset_within_channel: the pixel's offset within a channel.
* @param offset_num: the first address of n-th graph.
* @param c
* @param h
* @param w
* @param size
* @return dtype
*/
template <typename dtype>
dtype lrn_square(const dtype* input,
int channel_id,
int offset_within_channel,
int offset_num,
int c,
int h,
int w,
int size) {
int pre_pad = (size - 1) / 2;
dtype res = 0;
const dtype* src = input + offset_num;
// handle left channels with padding situation.
if (channel_id - pre_pad < 0) {
for (int i = 0; i <= channel_id; ++i) {
res += src[i * h * w + offset_within_channel] *
src[i * h * w + offset_within_channel];
}
}
// handle left channels.
if (channel_id - pre_pad >= 0) {
for (int i = channel_id - pre_pad; i <= channel_id; ++i) {
res += src[i * h * w + offset_within_channel] *
src[i * h * w + offset_within_channel];
}
}
// handle right channels.
if (channel_id + pre_pad < c) {
for (int i = channel_id + 1; i <= channel_id + pre_pad; ++i) {
res += src[i * h * w + offset_within_channel] *
src[i * h * w + offset_within_channel];
}
}
// handle right channels with padding situation.
if (channel_id + pre_pad >= c && channel_id + 1 < c) {
for (int i = channel_id + 1; i < c; ++i) {
res += src[i * h * w + offset_within_channel] *
src[i * h * w + offset_within_channel];
}
}
return res;
}
class LrnComputeTester : public arena::TestCase {
protected:
// common attributes for this op.
std::string input_ = "x";
std::string output_ = "out";
float alpha_ = 1.;
float beta_ = 0.75;
float k_ = 1.;
int local_size_ = 5;
DDim dims_{{2, 4, 3, 8}};
std::string norm_region_{"AcrossChannels"};
public:
LrnComputeTester(const Place& place,
const std::string& alias,
float alpha,
float beta,
float k,
int local_size,
std::string norm_region)
: TestCase(place, alias),
alpha_(alpha),
beta_(beta),
k_(k),
local_size_(local_size),
norm_region_(norm_region) {}
void RunBaseline(Scope* scope) override {
auto* out = scope->NewTensor(output_);
CHECK(out);
out->Resize(dims_);
auto* out_data = out->mutable_data<float>();
auto* x = scope->FindTensor(input_);
const auto* x_data = x->data<float>();
int N = dims_[0];
int C = dims_[1];
int H = dims_[2];
int W = dims_[3];
int offset_num = 0;
int offset_within_channel = 0;
int dst_id;
float square;
for (int n = 0; n < N; ++n) {
offset_num = n * C * H * W;
for (int c = 0; c < C; ++c) {
for (int h = 0; h < H; ++h) {
for (int w = 0; w < W; ++w) {
offset_within_channel = h * W + w;
dst_id = offset_num + c * H * W + offset_within_channel;
square = lrn_square<float>(x_data,
c,
offset_within_channel,
offset_num,
C,
H,
W,
local_size_);
out_data[dst_id] =
x_data[dst_id] * pow(k_ + alpha_ * square, -beta_);
}
}
}
}
}
void PrepareOpDesc(cpp::OpDesc* op_desc) {
op_desc->SetType("lrn");
op_desc->SetInput("X", {input_});
op_desc->SetOutput("Out", {output_});
op_desc->SetAttr("alpha", alpha_);
op_desc->SetAttr("beta", beta_);
op_desc->SetAttr("local_size", local_size_);
op_desc->SetAttr("k", k_);
op_desc->SetAttr("norm_region", norm_region_);
}
void PrepareData() override {
std::vector<float> data(dims_.production());
for (int i = 0; i < dims_.production(); i++) {
data[i] = i * 1.1;
}
SetCommonTensor(input_, dims_, data.data());
}
};
void test_lrn(Place place) {
for (float alpha : {0.9, 1., 1.1}) {
for (float beta : {0.5, 0.75, 1.}) {
for (float k : {0.9, 1., 1.1}) {
for (int local_size : {4, 5, 7}) {
for (std::string norm_region : {"AcrossChannels"}) {
std::unique_ptr<arena::TestCase> tester(new LrnComputeTester(
place, "def", alpha, beta, k, local_size, norm_region));
arena::Arena arena(std::move(tester), place, 2e-5);
arena.TestPrecision();
}
}
}
}
}
}
TEST(Lrn, precision) {
#ifdef LITE_WITH_X86
Place place(TARGET(kX86));
#endif
#ifdef LITE_WITH_ARM
Place place(TARGET(kARM));
test_lrn(place);
#endif
}
} // namespace lite
} // namespace paddle
| 28.57767 | 75 | 0.553253 | [
"vector"
] |
9ee4f6de5538a990588aa64253413abcea8ec9e6 | 7,939 | cpp | C++ | plugins/mesh/src/RenderMDIMesh.cpp | UniStuttgart-VISUS/implicit-topology | a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5 | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | plugins/mesh/src/RenderMDIMesh.cpp | UniStuttgart-VISUS/implicit-topology | a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5 | [
"BSD-3-Clause"
] | null | null | null | plugins/mesh/src/RenderMDIMesh.cpp | UniStuttgart-VISUS/implicit-topology | a7e0d5dd7253264e9feb2ae3d4dd44db5321d3e5 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* RenderMDIMesh.cpp
*
* Copyright (C) 2017 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include <array>
#include <random>
#include "RenderMDIMesh.h"
#include "mmcore/CoreInstance.h"
#include "vislib/graphics/gl/ShaderSource.h"
#include "mesh/MeshCalls.h"
using namespace megamol;
using namespace megamol::mesh;
RenderMDIMesh::RenderMDIMesh()
: Renderer3DModule_2()
, m_render_task_callerSlot("getRenderTaskData", "Connects the renderer with a render task data source")
, m_framebuffer_slot("Framebuffer", "Connects the renderer to an (optional) framebuffer render target from the calling module")
{
this->m_render_task_callerSlot.SetCompatibleCall<GPURenderTasksDataCallDescription>();
this->MakeSlotAvailable(&this->m_render_task_callerSlot);
this->m_framebuffer_slot.SetCompatibleCall<compositing::CallFramebufferGLDescription>();
this->MakeSlotAvailable(&this->m_framebuffer_slot);
}
RenderMDIMesh::~RenderMDIMesh()
{
this->Release();
}
bool RenderMDIMesh::create()
{
// generate debug render batch that doesn't rely on data call
/*
CallmeshRenderBatches::RenderBatchesData::ShaderPrgmData shader_prgm_data;
CallmeshRenderBatches::RenderBatchesData::MeshData mesh_data;
CallmeshRenderBatches::RenderBatchesData::DrawCommandData draw_command_data;
CallmeshRenderBatches::RenderBatchesData::MeshShaderParams obj_shader_params;
CallmeshRenderBatches::RenderBatchesData::MaterialShaderParams mtl_shader_params;
shader_prgm_data.raw_string = "meshDebug";
shader_prgm_data.char_cnt = 12;
mesh_data.vertex_data.byte_size = 3 * 6 * 4;
mesh_data.vertex_data.raw_data = new uint8_t[mesh_data.vertex_data.byte_size]; // 3 triangles * 6 float entries * bytesize
float* float_view = reinterpret_cast<float*>(mesh_data.vertex_data.raw_data);
float_view[0] = -0.5f;
float_view[1] = 0.0f;
float_view[2] = 0.0f;
float_view[3] = 0.0f;
float_view[4] = 0.0f;
float_view[5] = 1.0f;
float_view[6] = 0.5f;
float_view[7] = 0.0f;
float_view[8] = 0.0f;
float_view[9] = 0.0f;
float_view[10] = 0.0f;
float_view[11] = 1.0f;
float_view[12] = 0.0f;
float_view[13] = 1.0f;
float_view[14] = 0.0f;
float_view[15] = 0.0f;
float_view[16] = 0.0f;
float_view[17] = 1.0f;
mesh_data.index_data.index_type = GL_UNSIGNED_INT;
mesh_data.index_data.byte_size = 3 * 4;
mesh_data.index_data.raw_data = new uint8_t[3 * 4];
uint32_t* uint_view = reinterpret_cast<uint32_t*>(mesh_data.index_data.raw_data);
uint_view[0] = 0;
uint_view[1] = 1;
uint_view[2] = 2;
mesh_data.vertex_descriptor = VertexLayout(24, { VertexLayout::Attribute(GL_FLOAT,3,GL_FALSE,0),VertexLayout::Attribute(GL_FLOAT,3,GL_FALSE,12) });
std::mt19937 generator(4215);
std::uniform_real_distribution<float> distr(0.05, 0.1);
std::uniform_real_distribution<float> loc_distr(-0.9, 0.9);
draw_command_data.draw_cnt = 1000000;
draw_command_data.data = new CallmeshRenderBatches::RenderBatchesData::DrawCommandData::glowl::DrawElementsCommand[draw_command_data.draw_cnt];
obj_shader_params.byte_size = 16 * 4 * draw_command_data.draw_cnt;
obj_shader_params.raw_data = new uint8_t[obj_shader_params.byte_size];
for (int i = 0; i < draw_command_data.draw_cnt; ++i)
{
draw_command_data.data[i].cnt = 3;
draw_command_data.data[i].instance_cnt = 1;
draw_command_data.data[i].first_idx = 0;
draw_command_data.data[i].base_vertex = 0;
draw_command_data.data[i].base_instance = 0;
vislib::math::Matrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> object_transform;
GLfloat scale = distr(generator);
object_transform.SetAt(0, 0, scale);
object_transform.SetAt(1, 1, scale);
object_transform.SetAt(2, 2, scale);
object_transform.SetAt(0, 3, loc_distr(generator));
object_transform.SetAt(1, 3, loc_distr(generator));
object_transform.SetAt(2, 3, loc_distr(generator));
std::memcpy(obj_shader_params.raw_data + i*(16*4), object_transform.PeekComponents(), 16*4);
}
mtl_shader_params.elements_cnt = 0;
addRenderBatch(shader_prgm_data, mesh_data, draw_command_data, obj_shader_params, mtl_shader_params);
//TODO delete stuff again
*/
return true;
}
void RenderMDIMesh::release()
{
m_per_frame_data.reset();
}
bool RenderMDIMesh::GetExtents(core::view::CallRender3D_2& call) {
megamol::core::view::CallRender3D_2* cr = &call; // dynamic_cast<core::view::CallRender3D_2*>(&call);
if (cr == NULL)
return false;
CallGPURenderTaskData* rtc = this->m_render_task_callerSlot.CallAs<CallGPURenderTaskData>();
if (rtc == NULL)
return false;
auto meta_data = rtc->getMetaData();
//meta_data.m_frame_ID = static_cast<int>(cr->LastFrameTime());
//rtc->setMetaData(meta_data);
if (!(*rtc)(1))
return false;
meta_data = rtc->getMetaData();
cr->SetTimeFramesCount(meta_data.m_frame_cnt);
cr->AccessBoundingBoxes() = meta_data.m_bboxs;
return true;
}
bool RenderMDIMesh::Render(core::view::CallRender3D_2& call) {
megamol::core::view::CallRender3D_2* cr = &call; //dynamic_cast<core::view::CallRender3D_2*>(&call);
if (cr == NULL) return false;
// obtain camera information
core::view::Camera_2 cam(cr->GetCamera());
cam_type::snapshot_type snapshot;
cam_type::matrix_type view_tmp, proj_tmp;
cam.calc_matrices(snapshot, view_tmp, proj_tmp, core::thecam::snapshot_content::all);
glm::mat4 view_mx = view_tmp;
glm::mat4 proj_mx = proj_tmp;
CallGPURenderTaskData* task_call = this->m_render_task_callerSlot.CallAs<CallGPURenderTaskData>();
if (task_call == NULL)
return false;
if ((!(*task_call)(0)) )
return false;
//vislib::sys::Log::DefaultLog.WriteError("Hey listen!");
// set state
const auto depth_test = glIsEnabled(GL_DEPTH_TEST);
if (!depth_test) glEnable(GL_DEPTH_TEST);
const auto culling = glIsEnabled(GL_CULL_FACE);
if (culling) glDisable(GL_CULL_FACE);
// get tasks
auto gpu_render_tasks = task_call->getData();
// TODO yet another nullptr check for gpu render tasks
auto const& per_frame_buffers = gpu_render_tasks->getPerFrameBuffers();
for (auto const& buffer : per_frame_buffers)
{
std::get<0>(buffer)->bind(std::get<1>(buffer));
}
// loop through "registered" render batches
for (auto const& render_task : gpu_render_tasks->getRenderTasks())
{
render_task.shader_program->use();
// TODO introduce per frame "global" data buffer to store information like camera matrices?
render_task.shader_program->setUniform("view_mx", view_mx);
render_task.shader_program->setUniform("proj_mx", proj_mx);
render_task.per_draw_data->bind(0);
render_task.draw_commands->bind();
render_task.mesh->bindVertexArray();
glMultiDrawElementsIndirect(render_task.mesh->getPrimitiveType(),
render_task.mesh->getIndexType(),
(GLvoid*)0,
render_task.draw_cnt,
0);
//CallmeshRenderBatches::RenderBatchesData::DrawCommandData::glowl::DrawElementsCommand command_buffer;
//command_buffer.cnt = 3;
//command_buffer.instance_cnt = 1;
//command_buffer.first_idx = 0;
//command_buffer.base_vertex = 0;
//command_buffer.base_instance = 0;
//glowl::DrawElementsCommand command_buffer;
//command_buffer.cnt = 3;
//command_buffer.instance_cnt = 1;
//command_buffer.first_idx = 0;
//command_buffer.base_vertex = 0;
//command_buffer.base_instance = 0;
//
//glDrawElementsIndirect(render_batch.mesh->getPrimitiveType(),
// render_batch.mesh->getIndicesType(),
// &command_buffer);
//GLenum err = glGetError();
//std::cout << "Error: " << err << std::endl;
}
// Clear the way for his ancient majesty, the mighty immediate mode...
glUseProgram(0);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
// Restore state
if (!depth_test) glDisable(GL_DEPTH_TEST);
if (culling) glEnable(GL_CULL_FACE);
return true;
} | 31.133333 | 148 | 0.737372 | [
"mesh",
"render"
] |
9ee88f86cb119e9d2745c2f8ef02e05d42ddbc8a | 4,397 | cpp | C++ | benchmark_apps/elmerfem/post/src/fttext.cpp | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | elmerfem/post/src/fttext.cpp | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | null | null | null | elmerfem/post/src/fttext.cpp | jcmcmurry/pipelining | 8fface1a501b5050f58e7b902aacdcdde68e9648 | [
"MIT"
] | 2 | 2021-08-02T23:23:40.000Z | 2022-02-26T12:39:30.000Z | //-----------------------------------------------------------------------------------
// Filename: fttext.cpp
// Description: Provides FTGL text rendering functionality for ElmerPost
// Usage: fttext string [x y]
// ftfont font [size r g b]
// Compilation: export CFLAGS="-DHAVE_FTGL -I/usr/include/freetype2 -I/usr/include/FTGL"
// export CXXFLAGS="-DHAVE_FTGL -I/usr/include/freetype2 -I/usr/include/FTGL"
// export LIBS="-lfreetype -lftgl"
// Written by: Mikko Lyly
// Date: 15. Jan 2008
//-----------------------------------------------------------------------------------
#if defined(HAVE_CONFIG_H)
#include "../config.h"
#endif
#if defined(HAVE_FTGL_NEW) || defined(HAVE_FTGL_OLD)
#include <stdlib.h>
#include <stdio.h>
#include <GL/gl.h>
#include <tcl.h>
#if defined(WIN32) || defined(win32)
#include <windows.h>
#include "FTGL/FTGL.h"
#include "FTGL/FTGLPixmapFont.h"
#else
#if defined(HAVE_FTGL_NEW)
#include "FTGL/ftgl.h"
#else
#include "FTGL/FTGL.h"
#include "FTGL/FTGLPixmapFont.h"
#endif // HAVE_FTGL_NEW
#endif // WIN32 || win32
#define FTGLSTRLEN 4096
typedef struct {
double x, y;
int size;
double r, g, b;
int init_ok;
FTGLPixmapFont *Font;
char txt[FTGLSTRLEN];
char ttf[FTGLSTRLEN];
char current_ttf[FTGLSTRLEN];
char ttffile[FTGLSTRLEN];
} ftgl_t;
static ftgl_t ftgl;
extern "C" void (*user_hook_before_all)();
extern "C" void (*user_hook_after_all)();
static void FtInit() {
strcpy(ftgl.txt, "");
ftgl.x = -0.9;
ftgl.y = -0.9;
strcpy(ftgl.ttf, "FreeSans");
ftgl.size = 30;
ftgl.r = 1.0;
ftgl.g = 1.0;
ftgl.b = 1.0;
ftgl.init_ok = 1;
return;
}
extern "C" void FtRender() {
unsigned int r = strlen(ftgl.current_ttf);
unsigned int s = strlen(ftgl.ttf);
int t = strcmp(ftgl.ttf, ftgl.current_ttf);
if( (r!=s) || (t!=0) || ftgl.Font->Error() ) {
char *elmer_post_home = getenv("ELMER_POST_HOME");
fprintf(stdout, "fttext: getenv: ELMER_POST_HOME=%s\n",
elmer_post_home);
fflush(stdout);
#if defined(WIN32) || defined(win32)
sprintf(ftgl.ttffile, "%s\\fonts\\TrueType\\%s.ttf",
elmer_post_home, ftgl.ttf);
#else
sprintf(ftgl.ttffile, "%s/fonts/TrueType/%s.ttf",
elmer_post_home, ftgl.ttf);
#endif
fprintf(stdout, "fttext: load: %s\n", ftgl.ttffile);
fflush(stdout);
delete ftgl.Font;
ftgl.Font = new FTGLPixmapFont(ftgl.ttffile);
if(ftgl.Font->Error()) {
fprintf(stderr, "fttext: error: load font failed!\n");
fflush(stderr);
return;
}
memset(ftgl.current_ttf, 0, FTGLSTRLEN);
strncpy(ftgl.current_ttf, ftgl.ttf, strlen(ftgl.ttf));
}
if( ftgl.Font->Error() ) {
fprintf(stderr, "fttext: error: no font loaded!\n");
fflush(stderr);
return;
}
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glColor3f(ftgl.r, ftgl.g, ftgl.b);
glRasterPos3f(ftgl.x, ftgl.y, 0.0);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_1D);
ftgl.Font->FaceSize(ftgl.size);
ftgl.Font->Render(ftgl.txt);
glEnable(GL_TEXTURE_1D);
glEnable(GL_LIGHTING);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
return;
}
extern "C" int FtFont(ClientData cl, Tcl_Interp *interp,
int argc, char **argv) {
if(!ftgl.init_ok)
FtInit();
if(argc > 1)
strcpy( ftgl.ttf, argv[1] );
if(argc > 2)
ftgl.size = atoi(argv[2]);
if(argc > 3)
ftgl.r = atof(argv[3]);
if(argc > 4)
ftgl.g = atof(argv[4]);
if(argc > 5)
ftgl.b = atof(argv[5]);
Tcl_Eval(interp, "display");
return TCL_OK;
}
extern "C" int FtText(ClientData cl, Tcl_Interp *interp,
int argc, char **argv) {
if(!ftgl.init_ok)
FtInit();
strcpy(ftgl.txt, "");
ftgl.x = -0.9;
ftgl.y = -0.9;
if(argc > 1) {
// TCL uses internally UTF-8. We want
// text in system default for FTGL:
//---------------------------------------
Tcl_DString ds;
Tcl_DStringInit(&ds);
char *res = Tcl_UtfToExternalDString(NULL, argv[1], -1, &ds);
strcpy(ftgl.txt, res);
Tcl_DStringFree(&ds);
}
if(argc > 2)
ftgl.x = atof(argv[2]);
if(argc > 3)
ftgl.y = atof(argv[3]);
user_hook_after_all = FtRender;
Tcl_Eval(interp, "display");
return TCL_OK;
}
#endif // HAVE_FTGL_NEW || HAVE_FTGL_OLD
| 22.548718 | 90 | 0.603139 | [
"render"
] |
9eeb898bbee180d4899a7509edc945ed3696bd75 | 1,107 | cpp | C++ | generated-sources/cpp-pistache-server/mojang-api/model/SecurityAnswerId.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-pistache-server/mojang-api/model/SecurityAnswerId.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | generated-sources/cpp-pistache-server/mojang-api/model/SecurityAnswerId.cpp | AsyncMC/Mojang-API-Libs | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | [
"Apache-2.0"
] | null | null | null | /**
* Mojang API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* OpenAPI spec version: 2020-06-05
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "SecurityAnswerId.h"
namespace com {
namespace github {
namespace asyncmc {
namespace mojang {
namespace api {
namespace cpp {
namespace pistache {
namespace server {
namespace model {
SecurityAnswerId::SecurityAnswerId()
{
m_Id = 0;
}
SecurityAnswerId::~SecurityAnswerId()
{
}
void SecurityAnswerId::validate()
{
// TODO: implement validation
}
nlohmann::json SecurityAnswerId::toJson() const
{
nlohmann::json val = nlohmann::json::object();
val["id"] = m_Id;
return val;
}
void SecurityAnswerId::fromJson(const nlohmann::json& val)
{
setId(val.at("id"));
}
int32_t SecurityAnswerId::getId() const
{
return m_Id;
}
void SecurityAnswerId::setId(int32_t const value)
{
m_Id = value;
}
}
}
}
}
}
}
}
}
}
| 14.192308 | 108 | 0.688347 | [
"object",
"model"
] |
9ef3108806ecb66c48e79fde389b22e25250333f | 29,524 | cc | C++ | itensor/tensor/algs.cc | HappyFacade/ITensor | fd7c677a4d0cc255129f9a44e93589ce6200fe61 | [
"Apache-2.0"
] | 1 | 2021-12-14T10:09:04.000Z | 2021-12-14T10:09:04.000Z | itensor/tensor/algs.cc | HappyFacade/ITensor | fd7c677a4d0cc255129f9a44e93589ce6200fe61 | [
"Apache-2.0"
] | null | null | null | itensor/tensor/algs.cc | HappyFacade/ITensor | fd7c677a4d0cc255129f9a44e93589ce6200fe61 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <limits>
#include <stdexcept>
#include <tuple>
#include "itensor/tensor/lapack_wrap.h"
#include "itensor/tensor/algs.h"
#include "itensor/util/iterate.h"
#include "itensor/global.h"
using std::move;
using std::sqrt;
using std::tuple;
using std::make_tuple;
using std::tie;
namespace itensor {
namespace detail {
int
hermitianDiag(int N, Real *Udata, Real *ddata)
{
LAPACK_INT _N = N;
LAPACK_INT info = 0;
dsyev_wrapper('V','U',_N,Udata,ddata,info);
return info;
}
int
hermitianDiag(int N, Cplx *Udata,Real *ddata)
{
LAPACK_INT _N = N;
return zheev_wrapper(_N,Udata,ddata);
}
int
QR(int M, int N, int Rrows, Real *Qdata, Real *Rdata)
{
LAPACK_INT _M = M, _N = N, _Rrows = Rrows;
LAPACK_INT info = 0;
std::vector<LAPACK_REAL> tau(_N);
dgeqrf_wrapper(&_M, &_N, Qdata, &_M, tau.data(), &info);
for(LAPACK_INT i = 0; i < _Rrows; i++)
for(LAPACK_INT j = i; j < _N; j++)
{
Rdata[i + j*_Rrows] = Qdata[i+j*_M];
}
LAPACK_INT min = _M < _N ? _M : _N;
dorgqr_wrapper(&_M, &_Rrows, &min, Qdata, &_M, tau.data(), &info);
return info;
}
int
QR(int M, int N, int Rrows, Cplx *Qdata, Cplx *Rdata)
{
LAPACK_INT _M = M, _N = N, _Rrows = Rrows;
LAPACK_INT info = 0;
std::vector<LAPACK_COMPLEX> tau(N);
zgeqrf_wrapper(&_M, &_N, Qdata, &_M, tau.data(), &info);
for(LAPACK_INT i = 0; i < _Rrows; i++)
for(LAPACK_INT j = i; j < _N; j++)
{
Rdata[i + j*_Rrows] = Qdata[i+j*_M];
}
LAPACK_INT min = _M < _N ? _M : _N;
zungqr_wrapper(&_M, &_Rrows, &min, Qdata, &_M, tau.data(), &info);
return info;
}
int
SVD_gesdd(int M, int N, Cplx * Adata, Cplx * Udata, Real * Ddata, Cplx * Vdata)
{
LAPACK_INT _M = M, _N = N;
LAPACK_INT info = 0;
char S = 'S';
zgesdd_wrapper(&S, &_M, &_N, Adata, Ddata, Udata, Vdata, &info);
return info;
}
int
SVD_gesdd(int M, int N, Real * Adata, Real * Udata, Real * Ddata, Real * Vdata)
{
LAPACK_INT _M = M, _N = N;
LAPACK_INT info = 0;
char S = 'S';
dgesdd_wrapper(&S, &_M, &_N, Adata, Ddata, Udata, Vdata, &info);
return info;
}
int
SVD_gesvd(int M, int N, Cplx * Adata, Cplx * Udata, Real * Ddata, Cplx * Vdata)
{
LAPACK_INT _M = M, _N = N;
LAPACK_INT info = 0;
char S = 'S';
zgesvd_wrapper(&S, &_M, &_N, Adata, Ddata, Udata, Vdata, &info);
return info;
}
int
SVD_gesvd(int M, int N, Real * Adata, Real * Udata, Real * Ddata, Real * Vdata)
{
LAPACK_INT _M = M, _N = N;
LAPACK_INT info = 0;
char S = 'S';
dgesvd_wrapper(&S, &_M, &_N, Adata, Ddata, Udata, Vdata, &info);
return info;
}
} //namespace detail
//void
//diagHermitian(MatrixRefc const& Mre,
// MatrixRefc const& Mim,
// MatrixRef const& Ure,
// MatrixRef const& Uim,
// VectorRef const& d)
// {
// auto N = ncols(Mre);
// if(N != nrows(Mre))
// {
// printfln("Mre is %dx%d",nrows(Mre),ncols(Mre));
// throw std::runtime_error("diagHermitian: Input Matrix must be square");
// }
// if(N != nrows(Mim) || N != ncols(Mim))
// {
// printfln("Mim is %dx%d",nrows(Mim),ncols(Mim));
// throw std::runtime_error("diagHermitian: Input Matrix must be square, and real and imag part same size");
// }
//
//#ifdef DEBUG
// if(N < 1) throw std::runtime_error("diagHermitian: 0 dimensional matrix");
// if(!(nrows(Ure) == N && ncols(Ure) == N))
// throw std::runtime_error("diagHermitian: Ure should have same dims as M");
// if(!(nrows(Uim) == N && ncols(Uim) == N))
// throw std::runtime_error("diagHermitian: Uim should have same dims as M");
// if(d.size() != N)
// throw std::runtime_error("diagHermitian: d size should be linear size of M");
// if(!isContiguous(Ure))
// throw std::runtime_error("diagHermitian: Ure must be contiguous");
// if(!isContiguous(Uim))
// throw std::runtime_error("diagHermitian: Uim must be contiguous");
// if(!isContiguous(d))
// throw std::runtime_error("diagHermitian: d must be contiguous");
//#endif
//
// //Set Mc = -M so eigenvalues will be sorted from largest to smallest
// auto Mc = std::vector<Cplx>(N*N);
// if(isContiguous(Mre) && isContiguous(Mim))
// {
// copyNegElts(Mre.data(),Mim.data(),Mc);
// }
// else
// {
// copyNegElts(Mre.cbegin(),Mim.cbegin(),Mc);
// }
//
// auto info = zheev_wrapper(N,Mc.data(),d.data());
// if(info != 0)
// {
// throw std::runtime_error("Error condition in diagHermitian");
// }
//
// //Correct eigenvalue signs
// d *= -1;
//
// //Following code assumes Ure and Uim are contiguous
// auto ur = Ure.data();
// auto ui = Uim.data();
// for(auto& z : Mc)
// {
// (*ur) = realRef(z);
// (*ui) = imagRef(z);
// ++ur;
// ++ui;
// }
// }
//
//void
//diagHermitian(MatrixRefc const& Mre,
// MatrixRefc const& Mim,
// Matrix & Ure,
// Matrix & Uim,
// VectorRef const& d)
// {
// resize(Ure,nrows(Mre),ncols(Mre));
// resize(Uim,nrows(Mre),ncols(Mre));
// diagHermitian(Mre,Mim,makeRef(Ure),makeRef(Uim),d);
// }
//
//void
//diagHermitian(MatrixRefc const& Mre,
// MatrixRefc const& Mim,
// Matrix & Ure,
// Matrix & Uim,
// Vector & d)
// {
// resize(Ure,nrows(Mre),ncols(Mre));
// resize(Uim,nrows(Mre),ncols(Mre));
// resize(d,nrows(Mre));
// diagHermitian(Mre,Mim,makeRef(Ure),makeRef(Uim),makeRef(d));
// }
template<typename value_type>
void
diagGeneralRef(MatRefc<value_type> const& M,
MatrixRef const& Rr,
MatrixRef const& Ri,
MatrixRef const& Lr,
MatrixRef const& Li,
VectorRef const& dr,
VectorRef const& di)
{
auto N = ncols(M);
if(N < 1) throw std::runtime_error("diagGeneral: 0 dimensional matrix");
if(N != nrows(M))
{
printfln("M is %dx%d",nrows(M),ncols(M));
throw std::runtime_error("diagGeneral: Input Matrix must be square");
}
#ifdef DEBUG
if(!isContiguous(Rr))
throw std::runtime_error("diagGeneral: Rr must be contiguous");
if(!isContiguous(Ri))
throw std::runtime_error("diagGeneral: Ri must be contiguous");
if(Lr && !isContiguous(Lr))
throw std::runtime_error("diagGeneral: Lr must be contiguous");
if(Li && !isContiguous(Li))
throw std::runtime_error("diagGeneral: Li must be contiguous");
if(!isContiguous(dr))
throw std::runtime_error("diagGeneral: dr must be contiguous");
if(!isContiguous(di))
throw std::runtime_error("diagGeneral: di must be contiguous");
#endif
struct Diag
{
LAPACK_INT static
call(LAPACK_INT N, Real const* Mdata, Real *Ldata, Real *Rdata, Real *drdata, Real *didata)
{
auto cl = (Ldata==nullptr) ? 'N' : 'V';
return dgeev_wrapper(cl,'V',N,Mdata,drdata,didata,Ldata,Rdata);
}
LAPACK_INT static
call(LAPACK_INT N, Cplx const* Mdata, Cplx *Ldata, Cplx *Rdata, Real *drdata, Real *didata)
{
auto d = std::vector<Cplx>(N);
auto cl = (Ldata==nullptr) ? 'N' : 'V';
auto info = zgeev_wrapper(cl,'V',N,Mdata,d.data(),Ldata,Rdata);
for(size_t n = 0ul; n < d.size(); ++n)
{
*drdata = d[n].real();
*didata = d[n].imag();
++drdata;
++didata;
}
return info;
}
};
auto R = Mat<value_type>(N,N);
auto L = Mat<value_type>{};
if(Lr && Li) resize(L,N,N);
auto info = Diag::call(N,M.data(),L.data(),R.data(),dr.data(),di.data());
if(info != 0)
{
//println("M = \n",M);
throw std::runtime_error("Error condition in diagGeneral");
}
struct Unpack
{
void static
call(VectorRef di, MatrixRef Vr, MatrixRef Vi, MatrixRefc V)
{
//Unpack information in V
//back into actual eigenvectors
auto N = di.size();
decltype(N) n = 0;
while(n < N)
{
if(di(n) > 0)
{
//complex eigenvalue pair
column(Vr,n) &= column(V,n);
column(Vr,n+1) &= column(V,n);
column(Vi,n) &= column(V,n+1);
column(Vi,n+1) &= column(V,n+1);
column(Vi,n+1) *= -1;
n += 2;
}
else
{
column(Vr,n) &= column(V,n);
stdx::fill(column(Vi,n),0.);
n += 1;
}
}
}
void static
call(VectorRef di, MatrixRef Vr, MatrixRef Vi, CMatrixRefc V)
{
auto N = di.size();
for(decltype(N) c = 0; c < N; ++c)
for(decltype(N) r = 0; r < N; ++r)
{
Vr(r,c) = V(r,c).real();
Vi(r,c) = V(r,c).imag();
}
}
};
auto Rref = isTransposed(M) ? transpose(R) : makeRef(R);
Unpack::call(makeRef(di),makeRef(Rr),makeRef(Ri),Rref);
if(L)
{
auto Lref = isTransposed(M) ? transpose(L) : makeRef(L);
Unpack::call(makeRef(di),makeRef(Lr),makeRef(Li),Lref);
Error("Inverse step not fully implemented");
//for(auto n : range(N))
// {
// auto facr = column(Lr,n)*column(Rr,n)+column(Li,n)*column(Ri,n);
// auto faci = column(Lr,n)*column(Ri,n)-column(Li,n)*column(Rr,n);
// auto z = Cplx(facr,faci);
// printfln("z %d = %.4E",n,z);
// if(std::abs(z) <= 1E-16) Error("Ill conditioned or non-invertible matrix");
// z = 1./z;
// column(Lr,n) &= column(Lr,n)*z.real()+column(Li,n)*z.imag();
// column(Li,n) &= column(Lr,n)*z.imag()-column(Li,n)*z.real();
// }
}
}
template void
diagGeneralRef(MatRefc<Real> const& M,MatrixRef const& Rr,MatrixRef const& Ri,
MatrixRef const& Lr,MatrixRef const& Li,VectorRef const& dr,VectorRef const& di);
template void
diagGeneralRef(MatRefc<Cplx> const& M,MatrixRef const& Rr,MatrixRef const& Ri,
MatrixRef const& Lr,MatrixRef const& Li,VectorRef const& dr,VectorRef const& di);
//
// orthog
//
template<typename V>
void
orthog(MatRef<V> M,
size_t numpass)
{
auto nkeep = std::min(nrows(M), ncols(M));
auto dots = Vec<V>(nkeep);
for(auto i : range(nkeep))
{
//normalize column i
auto coli = column(M,i);
auto nrm = norm(coli);
if(nrm == 0.0)
{
randomize(coli);
nrm = norm(coli);
}
coli /= nrm;
if(i == 0) continue;
auto Mcols = columns(M,0,i);
auto dotsref = subVector(dots,0,i);
for(auto pass : range1(numpass))
{
// does dotsref &= dag(Mcols) * coli:
auto ccoli = conj(coli);
mult(Mcols,makeRef(ccoli),dotsref,true);
conjugate(dotsref);
// does coli -= Mcols * dotsref:
multSub(Mcols,dotsref,coli);
nrm = norm(coli);
if(nrm < 1E-3) --pass; //orthog is suspect
if(nrm < 1E-10) // What if a subspace was zero in all vectors?
{
randomize(coli);
nrm = norm(coli);
}
coli /= nrm;
}
}
}
template void orthog(MatRef<Real> M, size_t numpass);
template void orthog(MatRef<Cplx> M, size_t numpass);
//Real static
//sqr(Real x) { return x*x; }
//void
//orthog(MatrixRef Mr,
// MatrixRef Mi,
// size_t numpass)
// {
// auto nkeep = std::min(nrows(Mr), ncols(Mr));
// auto Dr = Vector(nkeep);
// auto Di = Vector(nkeep);
// auto cnorm = [](VectorRefc const& r,
// VectorRefc const& i)
// {
// return sqrt(sqr(norm(r))+sqr(norm(i)));
// };
// for(auto n : range(nkeep))
// {
// //normalize column n
// auto cr = column(Mr,n);
// auto ci = column(Mi,n);
// auto nrm = cnorm(cr,ci);
// if(nrm == 0.0)
// {
// randomize(cr);
// randomize(ci);
// nrm = cnorm(cr,ci);
// }
// cr /= nrm;
// ci /= nrm;
// if(n == 0) continue;
//
// auto mr = columns(Mr,0,n);
// auto mi = columns(Mi,0,n);
// auto dr = subVector(Dr,0,n);
// auto di = subVector(Di,0,n);
// for(auto pass : range1(numpass))
// {
// //// does dotsref &= transpose(Mcols) * coli:
// //mult(transpose(Mcols),coli,dotsref);
// dr &= transpose(mr)*cr+transpose(mi)*ci;
// di &= transpose(mr)*ci-transpose(mi)*cr;
// cr -= mr*dr-mi*di;
// ci -= mr*di+mi*dr;
//
// nrm = cnorm(cr,ci);
// if(nrm < 1E-3) --pass; //orthog is suspect
// if(nrm < 1E-10) // What if a subspace was zero in all vectors?
// {
// randomize(cr);
// randomize(ci);
// nrm = cnorm(cr,ci);
// }
// cr /= nrm;
// ci /= nrm;
// }
// }
// }
//
// SVD
//
//#define CHKSVD
void
checksvd(MatrixRefc const& A,
MatrixRefc const& U,
VectorRefc const& D,
MatrixRefc const& V)
{
Matrix Ach(U);
for(auto i : range1(D.size())) column(Ach,i) *= D(i);
Ach = Ach * transpose(V);
Ach -= A;
printfln("relative error with sqrt in low level svd is %.5E",norm(Ach)/norm(A));
}
tuple<bool,size_t> // == (done, start)
checkSVDDone(VectorRefc const& D,
Real thresh)
{
auto N = D.size();
if(N <= 1 || thresh <= 0)
{
//println("Got zero thresh");
return make_tuple(true,1);
}
auto D1t = D(0)*thresh;
size_t start = 1;
for(; start < N; ++start)
{
if(D(start) < D1t) break;
}
if(start >= (N-1))
return make_tuple(true,start);
return make_tuple(false,start);
}
template<typename T>
void
SVDRefImpl(MatRefc<T> const& M,
MatRef<T> const& U,
VectorRef const& D,
MatRef<T> const& V,
const Args & args)
{
auto Mr = nrows(M);
auto thresh = args.getReal("SVDThreshold",SVD_THRESH);
//Form 'density matrix' rho
Mat<T> rho, Mconj, tempV, R;
if(isCplx(M))
{
Mconj = conj(M);
rho = M * transpose(Mconj);
}
else
{
rho = M * transpose(M);
}
//Diagonalize rho: evals are squares of singular vals
diagHermitian(rho,U,D);
//Put result of Mt*U==(V*D) in V storage
if(isCplx(M)) mult(transpose(Mconj),U,V);
else mult(transpose(M),U,V);
QR(V, tempV, R, {"Complete=",false, "PositiveDiagonal=",true});
V &= std::move(tempV);
for(decltype(D.size()) i = 0; i < D.size(); ++i)
{
D(i) = std::real(R(i,i));
}
auto [done,start] = checkSVDDone(D,thresh);
if(done) return;
//
//Recursively SVD part of B
//for greater final accuracy
//
auto n = Mr-start;
//reuse rho's storage to avoid allocation
auto mv = move(rho);
reduceCols(mv,n);
auto u = columns(U,start,ncols(U));
auto v = columns(V,start,ncols(V));
//b should be close to diagonal
//but may not be perfect - fix it up below
mult(M,v,mv);
Mat<T> b;
if(isCplx(M)) b = conj(transpose(u))*mv;
else b = transpose(u)*mv;
auto d = subVector(D,start,Mr);
Mat<T> bu(n,n),
bv(n,n);
SVDRefImpl(makeRef(b),makeRef(bu),d,makeRef(bv),args);
//reuse mv's storage to avoid allocation
auto W = move(mv);
mult(u,bu,W);
u &= W;
auto X = v*bv;
v &= X;
}
template<typename T>
void
SVDRef(MatRefc<T> const& M,
MatRef<T> const& U,
VectorRef const& D,
MatRef<T> const& V,
const Args & args)
{
auto Mr = nrows(M), Mc = ncols(M);
if(Mr > Mc)
{
SVDRef(transpose(M),V,D,U,args);
conjugate(V);
conjugate(U);
}
else
{
#ifdef DEBUG
if(!(nrows(U)==Mr && ncols(U)==Mr))
throw std::runtime_error("SVD (ref version), wrong size of U");
if(!(nrows(V)==Mc && ncols(V)==Mr))
throw std::runtime_error("SVD (ref version), wrong size of V");
if(D.size()!=Mr)
throw std::runtime_error("SVD (ref version), wrong size of D");
#endif
auto svdMethod = args.getString("SVDMethod", "gesdd");
if(svdMethod=="ITensor")
{
SVDRefImpl(M,U,D,V,args);
}
else if(svdMethod == "gesdd" or svdMethod == "gesvd")
{
SVDRefLAPACK(M,U,D,V,args);
}
else
{
throw std::runtime_error("Unsupported SVD method: "+svdMethod);
}
}
#ifdef CHKSVD
checksvd(M,U,D,V);
#endif
}
template void SVDRef(MatRefc<Real> const&,MatRef<Real> const&, VectorRef const&, MatRef<Real> const&,const Args&);
template void SVDRef(MatRefc<Cplx> const&,MatRef<Cplx> const&, VectorRef const&, MatRef<Cplx> const&, const Args&);
//void
//SVDRef(MatrixRefc const& Mre,
// MatrixRefc const& Mim,
// MatrixRef const& Ure,
// MatrixRef const& Uim,
// VectorRef const& D,
// MatrixRef const& Vre,
// MatrixRef const& Vim,
// Real thresh)
// {
// auto Mr = nrows(Mre),
// Mc = ncols(Mim);
//
// if(Mr > Mc)
// {
// SVDRef(transpose(Mre),transpose(Mim),Vre,Vim,D,Ure,Uim,thresh);
// Uim *= -1;
// Vim *= -1;
// return;
// }
//
//#ifdef DEBUG
// if(!(nrows(Mim)==Mr && ncols(Mim)==Mc))
// throw std::runtime_error("SVD (ref version), Mim must have same dims as Mre");
// if(!(nrows(Ure)==Mr && ncols(Ure)==Mr))
// throw std::runtime_error("SVD (ref version), wrong size of Ure");
// if(!(nrows(Uim)==Mr && ncols(Uim)==Mr))
// throw std::runtime_error("SVD (ref version), wrong size of Uim");
// if(!(nrows(Vre)==Mc && ncols(Vre)==Mr))
// throw std::runtime_error("SVD (ref version), wrong size of Vre");
// if(!(nrows(Vim)==Mc && ncols(Vim)==Mr))
// throw std::runtime_error("SVD (ref version), wrong size of Vim");
// if(D.size()!=Mr)
// throw std::runtime_error("SVD (ref version), wrong size of D");
//#endif
//
// //Form 'density matrix' rho
// auto rhore = Mre*transpose(Mre) + Mim*transpose(Mim);
// auto rhoim = Mim*transpose(Mre) - Mre*transpose(Mim);
//
// //Diagonalize rho: evals are squares of singular vals
// diagHermitian(rhore,rhoim,Ure,Uim,D);
//
// for(auto& el : D)
// {
// if(el < 0) el = 0.;
// else el = std::sqrt(el);
// }
// size_t nlarge = 0;
// auto rthresh = D(0)*thresh;
// for(decltype(Mr) n = 0; n < Mr; ++n)
// {
// if(D(n) < rthresh)
// {
// nlarge = n;
// break;
// }
// }
//
// //Compute Mt*U = V*D
// Vre &= transpose(Mre)*Ure + transpose(Mim)*Uim;
// Vim &= transpose(Mre)*Uim - transpose(Mim)*Ure;
//
// for(decltype(nlarge) n = 0; n < nlarge; ++n)
// {
// column(Vre,n) /= D(n);
// column(Vim,n) /= D(n);
// }
// if(nlarge < Mr)
// {
// //Much more accurate than dividing
// //by smallest singular values
// auto Vcr = columns(Vre,nlarge,Mr);
// auto Vci = columns(Vim,nlarge,Mr);
// orthog(Vcr,Vci,2);
// }
//
// bool done = false;
// size_t start = 1;
// tie(done,start) = checkSVDDone(D,thresh);
// if(done) return;
//
// //
// //Recursively SVD part of B
// //for greater final accuracy
// //
// auto n = Mr-start;
//
// //{
// //println("Method 1");
// ////TEST VERSION - SLOW!
// //auto Tre = Mre*Vre - Mim*Vim;
// //auto Tim = Mre*Vim + Mim*Vre;
// //auto Bre = transpose(Ure)*Tre + transpose(Uim)*Tim;
// //auto Bim = transpose(Ure)*Tim - transpose(Uim)*Tre;
//
// //auto bre = Matrix{subMatrix(Bre,start,Mr,start,Mr)};
// //auto bim = Matrix{subMatrix(Bim,start,Mr,start,Mr)};
//
// //auto d = subVector(D,start,Mr);
// //Matrix ure(n,n),
// // uim(n,n),
// // vre(n,n),
// // vim(n,n);
// //SVDRef(bre,bim,ure,uim,d,vre,vim,thresh);
//
// //auto nure = columns(Ure,start,Mr);
// //auto nuim = columns(Uim,start,Mr);
// //auto tmpre = nure*ure - nuim*uim;
// //auto tmpim = nuim*ure + nure*uim;
// //nure &= tmpre;
// //nuim &= tmpim;
//
// //auto nvre = columns(Vre,start,Mr);
// //auto nvim = columns(Vim,start,Mr);
// //tmpre = nvre*vre - nvim*vim;
// //tmpim = nvim*vre + nvre*vim;
// //nvre &= tmpre;
// //nvim &= tmpim;
// //}
//
// //reuse storage of rho to hold mv=M*columns(V,start,Mr)
// auto mvre = move(rhore);
// auto mvim = move(rhoim);
// reduceCols(mvre,n);
// reduceCols(mvim,n);
//
// auto ure = columns(Ure,start,Mr);
// auto uim = columns(Uim,start,Mr);
// auto vre = columns(Vre,start,Mr);
// auto vim = columns(Vim,start,Mr);
//
// mvre = Mre*vre - Mim*vim;
// mvim = Mre*vim + Mim*vre;
//
// auto utre = transpose(ure);
// auto utim = transpose(uim);
//
// //b (=ut*M*v) should be close to diagonal
// //but may not be perfect - fix it up below
// auto bre = utre*mvre + utim*mvim;
// auto bim = utre*mvim - utim*mvre;
// auto d = subVector(D,start,Mr);
// Matrix bure(n,n),
// buim(n,n),
// bvre(n,n),
// bvim(n,n);
// SVDRef(bre,bim,bure,buim,d,bvre,bvim,thresh);
//
// auto Nure = ure*bure-uim*buim;
// auto Nuim = ure*buim+uim*bure;
// ure &= Nure;
// uim &= Nuim;
//
// auto Nvre = vre*bvre-vim*bvim;
// auto Nvim = vre*bvim+vim*bvre;
// vre &= Nvre;
// vim &= Nvim;
//
//#ifdef CHKSVD
// checksvd(M,U,D,V);
//#endif
//
// return;
// }
//
//void
//SVD(MatrixRefc const& Mre,
// MatrixRefc const& Mim,
// Matrix & Ure,
// Matrix & Uim,
// Vector & D,
// Matrix & Vre,
// Matrix & Vim,
// Real thresh)
// {
// auto Mr = nrows(Mre),
// Mc = ncols(Mim);
// auto nsv = std::min(Mr,Mc);
// resize(Ure,Mr,nsv);
// resize(Uim,Mr,nsv);
// resize(Vre,Mc,nsv);
// resize(Vim,Mc,nsv);
// resize(D,nsv);
// SVDRef(Mre,Mim,Ure,Uim,D,Vre,Vim,thresh);
// }
namespace exptH_detail {
int
expPade(MatRef<Real> const& F, int N, int ideg)
{
LAPACK_INT info = 0;
//
// Scaling: seek ns such that ||F/2^ns|| < 1/2
// and set scale = 1/2^ns
//
auto ns = dlange_wrapper('I',N,N,F.data());// infinite norm of the matrix to be exponentiated
#ifdef DEBUG
if(ns == 0) throw std::runtime_error("padeExp: null input matrix");
#endif
ns = std::max(0,(int)(std::log(ns)/log(2))+2);
Real scale = std::pow(2,-ns);
Real scale2 = scale*scale;
//
// Compute Pade coefficient
//
std::vector<Real> coef(ideg+1);
coef[0] = 1.0;
for(int k = 1; k <= ideg; ++k)
{
coef[k] = coef[k-1]*((double)(ideg+1-k)/(double)(k*(2*ideg+1-k)));
}
//
// H^2 = scale2*F*F
//
auto F2 = Mat<Real>(N,N);
gemm(F,F,makeRef(F2),scale2,0);
//
// Initialize P and Q
//
auto P = Mat<Real>(N,N);
auto Q = Mat<Real>(N,N);
for(auto j : range(N))
{
Q(j,j) = coef[ideg];
P(j,j) = coef[ideg-1];
}
//
// Horner evaluation of the irreducible fraction:
// Apply Horner rule
//
bool odd = true;
for(int k = ideg-1; k > 0; --k)
{
if(odd)
{
Q = Q*F2;
for(auto j : range(N))
{
Q(j,j) += coef[k-1];
}
}
else
{
P = P*F2;
for(auto j : range(N))
{
P(j,j) += coef[k-1];
}
}
odd = !odd;
}
//
// Horner evaluation of the irreducible fraction:
// Obtain (+/-)(I+2*(P\Q))
//
if(odd)
{
Q = scale*Q*F;
}
else
{
P = scale*P*F;
}
Q -= P;
info = dgesv_wrapper(N,N,Q.data(),P.data());
if(info != 0) return info;
P *= 2.0;
for(auto j : range(N))
{
P(j,j) += 1.0;
}
if(ns == 0 && odd)
{
P *= -1.0;
}
//
// Squaring: exp(F) = (exp(F))^(2^ns)
//
for(int k = 1; k <= ns; ++k)
{
P = P*P;
}
//auto pend = P.data()+P.size();
//auto f = Fdata;
//for(auto p = P.data(); p != pend; ++p,++f)
// {
// *f = *p;
// }
F &= P;//deep copy
return info;
}
int
expPade(MatRef<Cplx> const& F, int N, int ideg)
{
LAPACK_INT info = 0;
//
// Scaling: seek ns such that ||F/2^ns|| < 1/2
// and set scale = 1/2^ns
//
auto ns = zlange_wrapper('I',N,N,F.data());
#ifdef DEBUG
if(ns == 0) throw std::runtime_error("padeExp: null input matrix");
#endif
ns = std::max(0,(int)(std::log(ns)/log(2))+2);
Real scale = std::pow(2,-ns);
Real scale2 = scale*scale;
//
// Compute Pade coefficient
//
std::vector<Real> coef(ideg+1);
coef[0] = 1.0;
for(int k = 1; k <= ideg; ++k)
{
coef[k] = coef[k-1]*((double)(ideg+1-k)/(double)(k*(2*ideg+1-k)));
}
//
// H^2 = scale2*F*F
//
auto F2 = Mat<Cplx>(N,N);
gemm(F,F,makeRef(F2),scale2,0);
//
// Initialize P and Q
//
auto P = Mat<Cplx>(N,N);
auto Q = Mat<Cplx>(N,N);
for(auto j : range(N))
{
Q(j,j) = coef[ideg];
P(j,j) = coef[ideg-1];
}
//
// Horner evaluation of the irreducible fraction:
// Apply Horner rule
//
bool odd = true;
for(int k = ideg-1; k > 0; --k)
{
if(odd)
{
Q = Q*F2;
for(auto j : range(N))
{
Q(j,j) += coef[k-1];
}
}
else
{
P = P*F2;
for(auto j : range(N))
{
P(j,j) += coef[k-1];
}
}
odd = !odd;
}
//
// Horner evaluation of the irreducible fraction:
// Obtain (+/-)(I+2*(P\Q))
//
if(odd)
{
Q = scale*Q*F;
}
else
{
P = scale*P*F;
}
Q -= P;
info = zgesv_wrapper(N,N,Q.data(),P.data());
if(info != 0) return info;
P *= 2.0;
for(auto j : range(N))
{
P(j,j) += 1.0;
}
if(ns == 0 && odd)
{
P *= -1.0;
}
//
// Squaring: exp(F) = (exp(F))^(2^ns)
//
for(int k = 1; k <= ns; ++k)
{
P = P*P;
}
//auto pend = P.data()+P.size();
//auto f = Fdata;
//for(auto p = P.data(); p != pend; ++p,++f)
// {
// *f = *p;
// }
F &= P;//deep copy;
return info;
}
} //namespace exptH_detail
} //namespace itensor
| 27.905482 | 115 | 0.478052 | [
"vector"
] |
9ef33e1f24d333b39191993d023f4af6573cb4ad | 6,407 | hpp | C++ | src/uml/src_gen/uml/DestroyObjectAction.hpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | null | null | null | src/uml/src_gen/uml/DestroyObjectAction.hpp | MichaelBranz/MDE4CPP | 5b918850a37e9cee54f6c3b92f381b0458451724 | [
"MIT"
] | 1 | 2019-03-01T00:54:13.000Z | 2019-03-04T02:15:50.000Z | src/uml/src_gen/uml/DestroyObjectAction.hpp | vallesch/MDE4CPP | 7f8a01dd6642820913b2214d255bef2ea76be309 | [
"MIT"
] | null | null | null | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef UML_DESTROYOBJECTACTION_HPP
#define UML_DESTROYOBJECTACTION_HPP
#include <map>
#include <list>
#include <memory>
#include <string>
// forward declarations
template<class T, class ... U> class Subset;
class AnyObject;
typedef std::shared_ptr<AnyObject> Any;
//*********************************
// generated Includes
#include <map>
namespace persistence
{
namespace interfaces
{
class XLoadHandler; // used for Persistence
class XSaveHandler; // used for Persistence
}
}
namespace uml
{
class UmlFactory;
}
//Forward Declaration for used types
namespace uml
{
class Action;
}
namespace uml
{
class Activity;
}
namespace uml
{
class ActivityEdge;
}
namespace uml
{
class ActivityGroup;
}
namespace uml
{
class ActivityNode;
}
namespace uml
{
class ActivityPartition;
}
namespace uml
{
class Classifier;
}
namespace uml
{
class Comment;
}
namespace uml
{
class Constraint;
}
namespace uml
{
class Dependency;
}
namespace ecore
{
class EAnnotation;
}
namespace uml
{
class Element;
}
namespace uml
{
class ExceptionHandler;
}
namespace uml
{
class InputPin;
}
namespace uml
{
class InterruptibleActivityRegion;
}
namespace uml
{
class Namespace;
}
namespace uml
{
class OutputPin;
}
namespace uml
{
class RedefinableElement;
}
namespace uml
{
class StringExpression;
}
namespace uml
{
class StructuredActivityNode;
}
// base class includes
#include "uml/Action.hpp"
// enum includes
#include "uml/VisibilityKind.hpp"
//*********************************
namespace uml
{
/*!
A DestroyObjectAction is an Action that destroys objects.
<p>From package UML::Actions.</p> */
class DestroyObjectAction:virtual public Action
{
public:
DestroyObjectAction(const DestroyObjectAction &) {}
DestroyObjectAction& operator=(DestroyObjectAction const&) = delete;
protected:
DestroyObjectAction(){}
public:
virtual std::shared_ptr<ecore::EObject> copy() const = 0;
//destructor
virtual ~DestroyObjectAction() {}
//*********************************
// Operations
//*********************************
/*!
The multiplicity of the targe IinputPin is 1..1.
target.is(1,1) */
virtual bool multiplicity(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The target InputPin has no type.
target.type= null */
virtual bool no_type(Any diagnostics,std::map < Any, Any > context) = 0;
//*********************************
// Attributes Getter Setter
//*********************************
/*!
Specifies whether links in which the object participates are destroyed along with the object.
<p>From package UML::Actions.</p> */
virtual bool getIsDestroyLinks() const = 0;
/*!
Specifies whether links in which the object participates are destroyed along with the object.
<p>From package UML::Actions.</p> */
virtual void setIsDestroyLinks (bool _isDestroyLinks)= 0;
/*!
Specifies whether objects owned by the object (via composition) are destroyed along with the object.
<p>From package UML::Actions.</p> */
virtual bool getIsDestroyOwnedObjects() const = 0;
/*!
Specifies whether objects owned by the object (via composition) are destroyed along with the object.
<p>From package UML::Actions.</p> */
virtual void setIsDestroyOwnedObjects (bool _isDestroyOwnedObjects)= 0;
//*********************************
// Reference
//*********************************
/*!
The InputPin providing the object to be destroyed.
<p>From package UML::Actions.</p> */
virtual std::shared_ptr<uml::InputPin > getTarget() const = 0;
/*!
The InputPin providing the object to be destroyed.
<p>From package UML::Actions.</p> */
virtual void setTarget(std::shared_ptr<uml::InputPin> _target_target) = 0;
protected:
//*********************************
// Attribute Members
//*********************************
/*!
Specifies whether links in which the object participates are destroyed along with the object.
<p>From package UML::Actions.</p> */
bool m_isDestroyLinks = false;
/*!
Specifies whether objects owned by the object (via composition) are destroyed along with the object.
<p>From package UML::Actions.</p> */
bool m_isDestroyOwnedObjects = false;
//*********************************
// Reference Members
//*********************************
/*!
The InputPin providing the object to be destroyed.
<p>From package UML::Actions.</p> */
std::shared_ptr<uml::InputPin > m_target;
public:
//*********************************
// Union Getter
//*********************************
/*!
ActivityGroups containing the ActivityNode.
<p>From package UML::Activities.</p> */
virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;/*!
The ordered set of InputPins representing the inputs to the Action.
<p>From package UML::Actions.</p> */
virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;/*!
The Elements owned by this Element.
<p>From package UML::CommonStructure.</p> */
virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;/*!
The Element that owns this Element.
<p>From package UML::CommonStructure.</p> */
virtual std::weak_ptr<uml::Element > getOwner() const = 0;/*!
The RedefinableElement that is being redefined by this element.
<p>From package UML::Classification.</p> */
virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0;
virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;
//*********************************
// Persistence Functions
//*********************************
virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) = 0;
virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;
};
}
#endif /* end of include guard: UML_DESTROYOBJECTACTION_HPP */
| 22.719858 | 115 | 0.616357 | [
"object"
] |
9ef4135dc19bb6ab5a9900f47d1947757146be5d | 1,683 | cpp | C++ | src/Cubestein3D/Entity.cpp | DioMuller/cubestein3D | 5a358e1662287f72fdb8e3a10a664413f24a462e | [
"MIT"
] | null | null | null | src/Cubestein3D/Entity.cpp | DioMuller/cubestein3D | 5a358e1662287f72fdb8e3a10a664413f24a462e | [
"MIT"
] | null | null | null | src/Cubestein3D/Entity.cpp | DioMuller/cubestein3D | 5a358e1662287f72fdb8e3a10a664413f24a462e | [
"MIT"
] | null | null | null | #include "Entity.h"
#include "GameManager.h"
#include "Log.h"
////////////////////////////////////////
// Constructor / Destructor
////////////////////////////////////////
Entity::Entity()
{
behaviors = std::list<Behavior*>();
position = Vector();
rotation = Vector();
size = Vector(1, 1, 1);
}
Entity::~Entity()
{
}
////////////////////////////////////////
// Public Methods
////////////////////////////////////////
void Entity::Update(long delta)
{
for (Behavior* b : behaviors)
{
b->Update(delta);
}
}
void Entity::Render(long delta, Renderer* renderer)
{
}
Vector Entity::GetDirection()
{
Vector origin = Vector(0, 0, 1);
origin.rotateY(rotation.y);
return origin;
}
void Entity::Destroy()
{
GameManager::GetCurrentLevel()->RemoveEntity(this);
}
////////////////////////////////////////
// Behavior Methods
////////////////////////////////////////
void Entity::AddBehavior(Behavior* behavior)
{
behaviors.push_back(behavior);
}
void Entity::RemoveBehavior(Behavior* behavior)
{
behaviors.remove(behavior);
}
void Entity::ClearBehaviors()
{
Behavior* behavior;
while (behaviors.size() != 0)
{
behavior = *(behaviors.begin());
behaviors.pop_front();
delete behavior;
}
}
////////////////////////////////////////
// Collision Methods
////////////////////////////////////////
bool Entity::CheckCollision(Entity* other)
{
if (GetCollisionRect().Intersects(other->GetCollisionRect()) )
{
CollideWith(other);
other->CollideWith(this);
return true;
}
return false;
}
Rect Entity::GetCollisionRect()
{
return Rect(position.x - (size.x / 2), position.z - (size.z / 2), size.x, size.z);
}
void Entity::CollideWith(Entity* other)
{
} | 16.5 | 83 | 0.548425 | [
"render",
"vector"
] |
9ef6750a82480fd87eef965e6e6a314f133a69db | 40,174 | cc | C++ | modules/tools/visualizer/main_window.cc | zhulianhai/apollo | ab47e53dff2a9fe836ac69fdf783a654a0220802 | [
"Apache-2.0"
] | 7 | 2017-07-07T07:56:13.000Z | 2019-03-06T06:27:00.000Z | modules/tools/visualizer/main_window.cc | zhulianhai/apollo | ab47e53dff2a9fe836ac69fdf783a654a0220802 | [
"Apache-2.0"
] | null | null | null | modules/tools/visualizer/main_window.cc | zhulianhai/apollo | ab47e53dff2a9fe836ac69fdf783a654a0220802 | [
"Apache-2.0"
] | 2 | 2017-07-07T07:56:15.000Z | 2018-08-10T17:13:34.000Z | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
#include <QMessageBox>
#include <QPushButton>
#include <QSpinBox>
#include "modules/tools/visualizer/fixedaspectratiowidget.h"
#include "modules/tools/visualizer/grid.h"
#include "modules/tools/visualizer/main_window.h"
#include "modules/tools/visualizer/pointcloud.h"
#include "modules/tools/visualizer/radarpoints.h"
#include "modules/tools/visualizer/ui_main_window.h"
#include "modules/tools/visualizer/video_images_dialog.h"
namespace {
const char* globalTreeItemStyle = "margin-right:10px";
const char* aboutMessage =
"Cyber_Visualizer\n"
"\n"
"One Visualization Tool for Presenting Cyber Channel Data\n"
"\n"
"F5 Play | Pause\n"
"\n"
"Main View PointCloud view\n"
"All Views have right button Menu";
const char* licenseMessage =
"Copyright 2018 The Apollo Authors. All Rights Reserved.\n"
"\n"
"Licensed under the Apache License, Version 2.0 (the \"License\");\n"
"you may not use this file except in compliance with the License.\n"
"You may obtain a copy of the License at\n"
"\n"
"http://www.apache.org/licenses/LICENSE-2.0\n"
"\n"
"Unless required by applicable law or agreed to in writing, software\n"
"distributed under the License is distributed on an \"AS IS\" BASIS,\n"
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
"See the License for the specific language governing permissions and\n"
"limitations under the License.\n";
const char* pcTempObjGroupName = "pointcloud";
const char* pcVertexPath = ":/shaders/pointcloud.vert";
const char* pcFragPath = ":/shaders/grid_pointcloud.frag";
const char* gridVertexPath = ":/shaders/grid.vert";
const char* gridFragPath = ":/shaders/grid_pointcloud.frag";
const char* radarVertexPath = ":/shaders/radarpoints.vert";
const char* radarFragPath = ":/shaders/radarpoints.frag";
const std::string CompressedImageType("apollo.drivers.CompressedImage");
} // namespace
#define MEMBER_OFFSET(StructType, Member) \
(size_t)( \
reinterpret_cast<char*>(&(reinterpret_cast<StructType*>(1)->Member)) - \
1)
#define StructPtrByMemberPtr(MemberPtr, StructType, Member) \
reinterpret_cast<StructType*>(reinterpret_cast<char*>(MemberPtr) - \
MEMBER_OFFSET(StructType, Member))
struct MainWindow::VideoImgProxy {
FixedAspectRatioWidget video_image_viewer_;
QTreeWidgetItem root_item_;
QTreeWidgetItem channel_name_item_;
QTreeWidgetItem action_item_;
QComboBox channel_name_combobox_;
QPushButton action_item_button_;
QMutex reader_mutex_;
std::shared_ptr<Texture> dynamic_texture_;
bool isCompressedImage_;
union {
CyberChannReader<apollo::drivers::Image>* image_reader_;
CyberChannReader<apollo::drivers::CompressedImage>*
compressed_image_reader_;
};
VideoImgProxy()
: video_image_viewer_(),
root_item_(),
channel_name_item_(),
action_item_(),
channel_name_combobox_(),
action_item_button_(),
reader_mutex_(),
dynamic_texture_(),
isCompressedImage_(false),
image_reader_(nullptr) {}
void deleteReader(void) {
if (image_reader_) {
if (isCompressedImage_) {
delete compressed_image_reader_;
} else {
delete image_reader_;
}
image_reader_ = nullptr;
isCompressedImage_ = false;
}
}
void CloseChannel(void) {
if (isCompressedImage_) {
compressed_image_reader_->CloseChannel();
} else {
image_reader_->CloseChannel();
}
}
~VideoImgProxy(void) {
dynamic_texture_.reset();
deleteReader();
}
};
struct MainWindow::RadarData {
QTreeWidgetItem root_item_;
QTreeWidgetItem channel_name_item_;
QTreeWidgetItem action_item_;
QComboBox channel_name_combobox_;
QPushButton action_item_button_;
QCheckBox enable_checkBox_;
QMutex reader_mutex_;
CyberChannReader<apollo::drivers::RadarObstacles>* channel_reader_;
RadarData(void)
: root_item_(),
channel_name_item_(),
action_item_(),
channel_name_combobox_(),
action_item_button_(),
enable_checkBox_(),
reader_mutex_(),
channel_reader_(nullptr) {}
~RadarData(void) {
if (channel_reader_) {
delete channel_reader_;
channel_reader_ = nullptr;
}
}
};
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
ui_(new Ui::MainWindow),
msg_dialog_(new MessageDialog),
open_images_dialog_(nullptr),
grid_(nullptr),
enable_grid_checkBox_(nullptr),
grid_root_Item_(nullptr),
pointcloud_top_item_(nullptr),
pointcloud_comboBox_(new QComboBox),
pointcloud_button_(new QPushButton),
pointcloud_channel_Reader_(nullptr),
pointcloud_reader_mutex_(),
pointcloud_shader_(nullptr),
grid_shader_(nullptr),
radar_points_shader_(nullptr),
video_image_viewer_list_(),
closed_video_image_viewer_list_(),
radarData_list_(),
closed_radarData_list_(),
_channelName2TypeMap() {
ui_->setupUi(this);
ui_->videoImageGridLayout->setContentsMargins(2, 2, 2, 2);
ui_->videoImageWidget->setVisible(false);
ui_->mainToolBar->addAction(ui_->actionAddGrid);
ui_->mainToolBar->addAction(ui_->actionPointCloud);
ui_->mainToolBar->addSeparator();
ui_->mainToolBar->addAction(ui_->actionOpenImage);
ui_->mainToolBar->addAction(ui_->actionOpenImages);
ui_->mainToolBar->addAction(ui_->actionDelImage);
ui_->mainToolBar->addSeparator();
ui_->mainToolBar->addAction(ui_->actionPlay);
ui_->mainToolBar->addAction(ui_->actionPause);
pointcloud_reader_mutex_.lock();
{
QStringList tmp;
tmp << "ChannelNames"
<< " ";
all_channel_root_ = new QTreeWidgetItem(tmp);
ui_->treeWidget->addTopLevelItem(all_channel_root_);
}
connect(ui_->actionAbout, SIGNAL(triggered(bool)), this, SLOT(showMessage()));
connect(ui_->actionLicense, SIGNAL(triggered(bool)), this,
SLOT(showMessage()));
pointcloud_button_->setCheckable(true);
pointcloud_button_->setStyleSheet(globalTreeItemStyle);
pointcloud_comboBox_->setStyleSheet(globalTreeItemStyle);
connect(pointcloud_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayRenderableObject(bool)));
connect(pointcloud_comboBox_, SIGNAL(currentIndexChanged(int)), this,
SLOT(ChangePointCloudChannel()));
connect(ui_->treeWidget, SIGNAL(itemSelectionChanged()), this,
SLOT(UpdateActions()));
connect(ui_->treeWidget, SIGNAL(visibilityChanged(bool)), ui_->actionGlobal,
SLOT(setChecked(bool)));
connect(ui_->actionPlay, SIGNAL(triggered(bool)), this, SLOT(PlayPause()));
connect(ui_->actionPause, SIGNAL(triggered(bool)), this, SLOT(PlayPause()));
}
MainWindow::~MainWindow() {
for (VideoImgProxy* item : video_image_viewer_list_) {
item->reader_mutex_.unlock();
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
item->reader_mutex_.unlock();
}
for (RadarData* item : radarData_list_) {
item->reader_mutex_.unlock();
}
for (RadarData* item : closed_radarData_list_) {
item->reader_mutex_.unlock();
}
pointcloud_reader_mutex_.unlock();
if (pointcloud_channel_Reader_) {
delete pointcloud_channel_Reader_;
pointcloud_channel_Reader_ = nullptr;
}
for (VideoImgProxy* item : video_image_viewer_list_) {
delete item;
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
delete item;
}
for (RadarData* item : radarData_list_) {
delete item;
}
for (RadarData* item : closed_radarData_list_) {
delete item;
}
delete ui_;
delete msg_dialog_;
}
void MainWindow::calculateWH(void) {
int count = video_image_viewer_list_.count();
if (count > 0) {
QSize wh;
wh.setWidth(ui_->sceneWidget->width() - count * 2 + 2);
wh.setHeight(50);
wh.setWidth(wh.width() / count);
int index = 0;
for (VideoImgProxy* p : video_image_viewer_list_) {
p->video_image_viewer_.setMinimumSize(wh);
ui_->videoImageGridLayout->removeWidget(&p->video_image_viewer_);
ui_->videoImageGridLayout->addWidget(&p->video_image_viewer_, index / 3,
index % 3, 1, 1);
++index;
}
ui_->videoImageWidget->adjustSize();
}
}
MainWindow::VideoImgProxy* MainWindow::AddVideoImgViewer() {
std::shared_ptr<Texture> tex(new Texture);
if (tex == nullptr) {
return nullptr;
}
VideoImgProxy* ret = new VideoImgProxy();
if (ret) {
int index = video_image_viewer_list_.count();
ret->video_image_viewer_.set_index(index);
ret->video_image_viewer_.setStyleSheet("background-color:black;");
ret->video_image_viewer_.setVisible(false);
QString imgName = tr("Camera%1").arg(index);
ret->root_item_.setHidden(true);
ret->root_item_.setText(0, imgName);
ret->root_item_.setText(1, "");
ret->channel_name_item_.setText(0, "ChannelName");
ret->action_item_.setText(0, "Action");
ret->action_item_button_.setObjectName(tr("pushButton%1").arg(index));
ret->action_item_button_.setText("Play");
ret->action_item_button_.setCheckable(true);
ret->action_item_button_.setStyleSheet(globalTreeItemStyle);
ret->channel_name_combobox_.setObjectName(tr("comboBox%1").arg(index));
ret->channel_name_combobox_.setStyleSheet(globalTreeItemStyle);
ret->root_item_.addChild(&ret->channel_name_item_);
ret->root_item_.addChild(&ret->action_item_);
ret->dynamic_texture_ = tex;
ret->video_image_viewer_.SetupDynamicTexture(tex);
ret->video_image_viewer_.setSizePolicy(QSizePolicy::Preferred,
QSizePolicy::Preferred);
ret->video_image_viewer_.addAction(ui_->actionDelImage);
ret->reader_mutex_.lock();
}
return ret;
}
MainWindow::RadarData* MainWindow::createRadarData(void) {
RadarData* ret = new RadarData();
if (ret) {
int index = radarData_list_.count();
QString radarName = tr("Radar%1").arg(index);
ret->root_item_.setHidden(true);
ret->root_item_.setText(0, radarName);
ret->channel_name_item_.setText(0, "ChannelName");
ret->action_item_.setText(0, "Action");
ret->enable_checkBox_.setChecked(true);
ret->action_item_button_.setText("Play");
ret->action_item_button_.setCheckable(true);
ret->action_item_button_.setStyleSheet(globalTreeItemStyle);
ret->channel_name_combobox_.setObjectName(tr("comboBox%1").arg(index));
ret->channel_name_combobox_.setStyleSheet(globalTreeItemStyle);
ret->root_item_.addChild(&ret->channel_name_item_);
ret->root_item_.addChild(&ret->action_item_);
ret->reader_mutex_.lock();
}
return ret;
}
void MainWindow::EnableGrid(bool b) { grid_->set_is_renderable(b); }
void MainWindow::ActionAddGrid(void) {
if (grid_shader_ == nullptr) {
grid_shader_ = RenderableObject::CreateShaderProgram(tr(gridVertexPath),
tr(gridFragPath));
if (grid_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("grid", grid_shader_);
}
}
if (grid_root_Item_ == nullptr) {
QTreeWidgetItem* colorChild = nullptr;
QTreeWidgetItem* cellCountChild = nullptr;
QSpinBox* spinbox = nullptr;
grid_ = new Grid(6);
if (grid_ == nullptr) {
goto _ret1;
}
if (grid_shader_ == nullptr) {
goto _ret2;
}
enable_grid_checkBox_ = new QCheckBox(ui_->treeWidget);
if (enable_grid_checkBox_ == nullptr) {
goto _ret2;
}
grid_root_Item_ = new QTreeWidgetItem(ui_->treeWidget);
if (grid_root_Item_ == nullptr) {
goto _ret3;
}
colorChild = new QTreeWidgetItem(grid_root_Item_);
if (colorChild == nullptr) {
goto _ret4;
}
grid_root_Item_->addChild(colorChild);
colorChild->setText(0, "Color");
colorChild->setText(1, tr("%1;%2;%3")
.arg(grid_->red())
.arg(grid_->green())
.arg(grid_->blue()));
spinbox = new QSpinBox(ui_->treeWidget);
if (spinbox == nullptr) {
goto _ret5;
}
spinbox->setMinimum(1);
spinbox->setMaximum(100);
spinbox->setSingleStep(1);
spinbox->setValue(grid_->CellCount());
spinbox->setStyleSheet(globalTreeItemStyle);
cellCountChild = new QTreeWidgetItem(grid_root_Item_);
if (cellCountChild == nullptr) {
goto _ret6;
}
grid_root_Item_->addChild(cellCountChild);
cellCountChild->setText(0, "CellCount");
grid_->set_shader_program(grid_shader_);
if (!ui_->sceneWidget->AddPermanentRenderObj(grid_)) {
goto _ret7;
}
enable_grid_checkBox_->setText("Enable");
enable_grid_checkBox_->setChecked(true);
grid_root_Item_->setText(0, "Grid");
grid_root_Item_->setText(1, "");
ui_->treeWidget->addTopLevelItem(grid_root_Item_);
ui_->treeWidget->setItemWidget(grid_root_Item_, 1, enable_grid_checkBox_);
ui_->treeWidget->setItemWidget(cellCountChild, 1, spinbox);
connect(enable_grid_checkBox_, SIGNAL(clicked(bool)), this,
SLOT(EnableGrid(bool)));
connect(ui_->treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
this, SLOT(EditGridColor(QTreeWidgetItem*, int)));
connect(spinbox, SIGNAL(valueChanged(int)), this,
SLOT(ChangeGridCellCountBySize(int)));
return;
_ret7:
delete cellCountChild;
_ret6:
delete spinbox;
_ret5:
delete colorChild;
_ret4:
delete grid_root_Item_;
_ret3:
delete enable_grid_checkBox_;
_ret2:
delete grid_;
_ret1:
QMessageBox::warning(this, tr("Error"),
tr("There is no enough memory for creating Grid!!!"),
QMessageBox::Ok);
return;
}
}
void MainWindow::ChangeGridCellCountBySize(int v) {
grid_->Destroy();
grid_->set_shader_program(grid_shader_);
grid_->SetCellCount(v);
grid_->set_is_renderable(true);
}
void MainWindow::EditGridColor(QTreeWidgetItem* item, int column) {
if (column && item == grid_root_Item_->child(0)) {
QStringList rgb = item->text(1).split(';');
QColor color(rgb.at(0).toInt(), rgb.at(1).toInt(), rgb.at(2).toInt());
color = QColorDialog::getColor(color, nullptr, tr("set grid color"));
if (color.isValid()) {
QString str =
tr("%1;%2;%3").arg(color.red()).arg(color.green()).arg(color.blue());
item->setText(1, str);
grid_->set_grid_color(color);
}
}
}
void MainWindow::EnableRadarPoints(bool b) {
QCheckBox* obj = static_cast<QCheckBox*>(sender());
RadarData* r = StructPtrByMemberPtr(obj, RadarData, enable_checkBox_);
ui_->sceneWidget->setTempObjGroupEnabled(r->root_item_.text(0).toStdString(),
b);
}
void MainWindow::ActionOpenRadarChannel(void) {
if (radar_points_shader_ == nullptr) {
radar_points_shader_ = RenderableObject::CreateShaderProgram(
tr(radarVertexPath), tr(radarFragPath));
if (radar_points_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("radarpoints", radar_points_shader_);
} else {
QMessageBox::warning(
this, tr("NO Shader"),
tr("There is no suitable shader for Radar Points!!!"),
QMessageBox::Ok);
return;
}
}
RadarData* radarProxy;
if (closed_radarData_list_.empty()) {
radarProxy = createRadarData();
if (radarProxy == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!\nCannot add new "
"image or video channel!"),
QMessageBox::Ok);
return;
}
ui_->treeWidget->addTopLevelItem(&radarProxy->root_item_);
ui_->treeWidget->setItemWidget(&radarProxy->root_item_, 1,
&radarProxy->enable_checkBox_);
ui_->treeWidget->setItemWidget(&radarProxy->channel_name_item_, 1,
&radarProxy->channel_name_combobox_);
ui_->treeWidget->setItemWidget(&radarProxy->action_item_, 1,
&radarProxy->action_item_button_);
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
QTreeWidgetItem* child = all_channel_root_->child(i);
QString channel = child->text(0);
if (channel.contains("radar")) {
radarProxy->channel_name_combobox_.addItem(channel);
}
}
} else {
radarProxy = closed_radarData_list_.takeFirst();
}
connect(&radarProxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(openRadarChannel(bool)));
connect(&radarProxy->enable_checkBox_, SIGNAL(clicked(bool)), this,
SLOT(EnableRadarPoints(bool)));
connect(&radarProxy->channel_name_combobox_, SIGNAL(currentIndexChanged(int)),
this, SLOT(ChangeRadarChannel()));
radarData_list_.append(radarProxy);
radarProxy->root_item_.setHidden(false);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
}
void MainWindow::openRadarChannel(bool b) {
QPushButton* obj = static_cast<QPushButton*>(QObject::sender());
RadarData* theVideoImg =
StructPtrByMemberPtr(obj, RadarData, action_item_button_);
DoOpenRadarChannel(b, theVideoImg);
}
void MainWindow::DoOpenRadarChannel(bool b, RadarData* radarProxy) {
if (b) {
if (radarProxy->channel_name_combobox_.currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Settup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease select one!"),
QMessageBox::Ok);
radarProxy->action_item_button_.setChecked(false);
return;
}
if (!radarProxy->channel_reader_) {
radarProxy->channel_reader_ =
new CyberChannReader<apollo::drivers::RadarObstacles>();
if (!radarProxy->channel_reader_) {
QMessageBox::warning(this, tr("Create cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
return;
}
auto radarcallback =
[this, radarProxy](
const std::shared_ptr<apollo::drivers::RadarObstacles>& pdata) {
this->RadarRenderCallback(pdata, radarProxy);
};
std::string nodeName("Visualizer-");
nodeName.append(radarProxy->root_item_.text(0).toStdString());
if (!radarProxy->channel_reader_->InstallCallbackAndOpen(
radarcallback,
radarProxy->channel_name_combobox_.currentText().toStdString(),
nodeName)) {
QMessageBox::warning(
this, tr("Settup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
delete radarProxy->channel_reader_;
radarProxy->channel_reader_ = nullptr;
radarProxy->action_item_button_.setChecked(false);
return;
}
}
radarProxy->root_item_.setToolTip(
0, radarProxy->channel_name_combobox_.currentText());
radarProxy->action_item_button_.setText("Stop");
radarProxy->channel_name_combobox_.setEnabled(false);
radarProxy->reader_mutex_.unlock();
} else {
if (!radarProxy->channel_name_combobox_.isEnabled()) {
radarProxy->reader_mutex_.lock();
radarProxy->action_item_button_.setText("Play");
radarProxy->channel_name_combobox_.setEnabled(true);
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::RadarRenderCallback(
const std::shared_ptr<const apollo::drivers::RadarObstacles>& rawData,
RadarData* radar) {
radar->reader_mutex_.lock();
radar->reader_mutex_.unlock();
std::cout << "-------MainWindow::RadarRenderCallback()-------" << std::endl;
if (rawData != nullptr) {
RadarPoints* r = new RadarPoints(radar_points_shader_);
if (r) {
if (!r->FillData(rawData) ||
!ui_->sceneWidget->AddTempRenderableObj(
radar->root_item_.text(0).toStdString(), r)) {
delete r;
}
} else {
std::cerr << "cannot create RadarPoints Renderable Object" << std::endl;
}
}
}
void MainWindow::ActionOpenPointCloud(void) {
if (pointcloud_shader_ == nullptr) {
pointcloud_shader_ =
RenderableObject::CreateShaderProgram(tr(pcVertexPath), tr(pcFragPath));
if (pointcloud_shader_ != nullptr) {
ui_->sceneWidget->AddNewShaderProg("pointcloud", pointcloud_shader_);
} else {
QMessageBox::warning(this, tr("NO Shader"),
tr("There is no suitable shader for Pointcloud!!!"),
QMessageBox::Ok);
return;
}
}
if (pointcloud_top_item_ == nullptr) {
pointcloud_top_item_ = new QTreeWidgetItem(ui_->treeWidget);
if (pointcloud_top_item_ == nullptr) {
return;
}
pointcloud_top_item_->setText(0, "PointCloud2");
pointcloud_top_item_->setText(1, "");
QTreeWidgetItem* item = new QTreeWidgetItem(pointcloud_top_item_);
if (item == nullptr) {
QMessageBox::warning(this, tr("NO Enough Memory"),
tr("Cannot create tree item for channel name!!!"),
QMessageBox::Ok);
return;
}
item->setText(0, "ChannelName");
ui_->treeWidget->setItemWidget(item, 1, pointcloud_comboBox_);
item = new QTreeWidgetItem(pointcloud_top_item_);
if (item == nullptr) {
QMessageBox::warning(this, tr("NO Enough Memory"),
tr("Cannot create tree item for channel Action!!!"),
QMessageBox::Ok);
return;
}
item->setText(0, "Action");
pointcloud_button_->setText("Play");
ui_->treeWidget->setItemWidget(item, 1, pointcloud_button_);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
}
}
void MainWindow::ActionOpenImages(void) {
if (open_images_dialog_ == nullptr) {
open_images_dialog_ = new VideoImagesDialog(this);
if (open_images_dialog_ == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!"), QMessageBox::Ok);
return;
} else {
connect(open_images_dialog_, SIGNAL(accepted()), this,
SLOT(AddVideoImages()));
}
}
open_images_dialog_->show();
}
void MainWindow::AddVideoImages(void) {
int count = open_images_dialog_->count();
while (count) {
ActionOpenImage();
--count;
}
}
void MainWindow::ActionOpenImage(void) {
VideoImgProxy* videoImgProxy;
if (closed_video_image_viewer_list_.empty()) {
videoImgProxy = AddVideoImgViewer();
if (videoImgProxy == nullptr) {
QMessageBox::warning(this, tr("No Enough Memory"),
tr("There is no enough memory!!!\nCannot add new "
"image or video channel!"),
QMessageBox::Ok);
return;
}
videoImgProxy->video_image_viewer_.setParent(ui_->videoImageWidget);
ui_->treeWidget->addTopLevelItem(&videoImgProxy->root_item_);
ui_->treeWidget->setItemWidget(&videoImgProxy->channel_name_item_, 1,
&videoImgProxy->channel_name_combobox_);
ui_->treeWidget->setItemWidget(&videoImgProxy->action_item_, 1,
&videoImgProxy->action_item_button_);
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
QTreeWidgetItem* child = all_channel_root_->child(i);
QString channel = child->text(0);
if (channel.contains("camera")) {
videoImgProxy->channel_name_combobox_.addItem(channel);
}
}
} else {
videoImgProxy = closed_video_image_viewer_list_.takeFirst();
}
connect(&videoImgProxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayVideoImage(bool)));
connect(&videoImgProxy->channel_name_combobox_,
SIGNAL(currentIndexChanged(int)), this,
SLOT(ChangeVideoImgChannel()));
connect(&videoImgProxy->video_image_viewer_,
SIGNAL(focusOnThis(FixedAspectRatioWidget*)), this,
SLOT(SelectCurrentTreeItem(FixedAspectRatioWidget*)));
video_image_viewer_list_.append(videoImgProxy);
videoImgProxy->video_image_viewer_.setVisible(true);
calculateWH();
videoImgProxy->video_image_viewer_.StartOrStopUpdate(true);
videoImgProxy->root_item_.setHidden(false);
ui_->videoImageWidget->setVisible(true);
ui_->treeWidget->setVisible(true);
ui_->actionGlobal->setChecked(true);
repaint();
}
void MainWindow::ActionDelVideoImage(void) {
QTreeWidgetItem* topItem = ui_->treeWidget->currentItem();
VideoImgProxy* proxy =
StructPtrByMemberPtr(topItem, VideoImgProxy, root_item_);
DoDeleteVideoImg(proxy);
ui_->actionDelImage->setEnabled(false);
}
void MainWindow::CloseVideoImgViewer(bool b) {
if (!b) {
VideoImgViewer* dock = static_cast<VideoImgViewer*>(sender());
DoDeleteVideoImg(
StructPtrByMemberPtr(dock, VideoImgProxy, video_image_viewer_));
}
}
void MainWindow::DoDeleteVideoImg(VideoImgProxy* proxy) {
disconnect(&proxy->action_item_button_, SIGNAL(clicked(bool)), this,
SLOT(PlayVideoImage(bool)));
disconnect(&proxy->channel_name_combobox_, SIGNAL(currentIndexChanged(int)),
this, SLOT(ChangeVideoImgChannel()));
disconnect(&proxy->video_image_viewer_,
SIGNAL(focusOnThis(FixedAspectRatioWidget*)), this,
SLOT(SelectCurrentTreeItem(FixedAspectRatioWidget*)));
proxy->action_item_button_.setChecked(false);
DoPlayVideoImage(false, proxy);
proxy->video_image_viewer_.StartOrStopUpdate(false);
proxy->root_item_.setHidden(true);
proxy->video_image_viewer_.setVisible(false);
ui_->videoImageGridLayout->removeWidget(&proxy->video_image_viewer_);
video_image_viewer_list_.removeOne(proxy);
closed_video_image_viewer_list_.append(proxy);
if (video_image_viewer_list_.count()) {
calculateWH();
} else {
ui_->videoImageWidget->setVisible(false);
}
}
void MainWindow::UpdateActions(void) {
QTreeWidgetItem* item = ui_->treeWidget->currentItem();
ui_->actionDelImage->setEnabled(false);
if (item) {
if (!item->parent() && item != pointcloud_top_item_ &&
item != all_channel_root_ && item != grid_root_Item_) {
ui_->actionDelImage->setEnabled(true);
}
}
}
void MainWindow::PointCloudReaderCallback(
const std::shared_ptr<const apollo::drivers::PointCloud>& pdata) {
pointcloud_reader_mutex_.lock();
pointcloud_reader_mutex_.unlock();
PointCloud* pc = new PointCloud(pdata->point_size(), 4, pointcloud_shader_);
if (pc) {
if (!pc->FillData(pdata) ||
!ui_->sceneWidget->AddTempRenderableObj(pcTempObjGroupName, pc)) {
delete pc;
}
} else {
std::cerr << "-----Cannot create PointCloud----------" << std::endl;
}
}
void MainWindow::PlayRenderableObject(bool b) {
if (b) {
if (pointcloud_comboBox_->currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Settup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease Select it!"),
QMessageBox::Ok);
pointcloud_button_->setChecked(false);
return;
}
if (!pointcloud_channel_Reader_) {
pointcloud_channel_Reader_ =
new CyberChannReader<apollo::drivers::PointCloud>();
if (!pointcloud_channel_Reader_) {
QMessageBox::warning(this, tr("Create Cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
pointcloud_button_->setChecked(false);
return;
}
auto pointCallback =
[this](const std::shared_ptr<apollo::drivers::PointCloud>& pdata) {
this->PointCloudReaderCallback(pdata);
};
std::string nodeName("Visualizer-");
nodeName.append(pointcloud_top_item_->text(0).toStdString());
if (!pointcloud_channel_Reader_->InstallCallbackAndOpen(
pointCallback, pointcloud_comboBox_->currentText().toStdString(),
nodeName)) {
QMessageBox::warning(
this, tr("Settup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
delete pointcloud_channel_Reader_;
pointcloud_channel_Reader_ = nullptr;
pointcloud_button_->setChecked(false);
return;
}
}
ui_->sceneWidget->setToolTip(pointcloud_comboBox_->currentText());
pointcloud_top_item_->setToolTip(0, pointcloud_comboBox_->currentText());
pointcloud_comboBox_->setEnabled(false);
pointcloud_button_->setText(tr("Stop"));
pointcloud_reader_mutex_.unlock();
} else {
if (!pointcloud_comboBox_->isEnabled()) {
pointcloud_reader_mutex_.lock();
pointcloud_comboBox_->setEnabled(true);
pointcloud_button_->setText(tr("Show"));
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::Image>& imgData,
VideoImgProxy* theVideoImgProxy) {
theVideoImgProxy->reader_mutex_.lock();
if (theVideoImgProxy->dynamic_texture_ != nullptr && imgData != nullptr) {
if (theVideoImgProxy->dynamic_texture_->UpdateData(imgData)) {
theVideoImgProxy->video_image_viewer_.SetupDynamicTexture(
theVideoImgProxy->dynamic_texture_);
} else {
std::cerr << "--------Cannot update dynamic Texture Data--------"
<< std::endl;
}
} else {
std::cerr
<< "----Dynamic Texture is nullptr or apollo.drivers.Image is nullptr"
<< std::endl;
}
theVideoImgProxy->reader_mutex_.unlock();
}
void MainWindow::ImageReaderCallback(
const std::shared_ptr<const apollo::drivers::CompressedImage>& imgData,
VideoImgProxy* theVideoImgProxy) {
theVideoImgProxy->reader_mutex_.lock();
if (theVideoImgProxy->dynamic_texture_ != nullptr && imgData != nullptr) {
QImage img;
const std::string& data = imgData->data();
if (img.loadFromData(reinterpret_cast<const unsigned char*>(data.c_str()),
static_cast<int>(data.size()))) {
if (theVideoImgProxy->dynamic_texture_->UpdateData(img)) {
theVideoImgProxy->video_image_viewer_.SetupDynamicTexture(
theVideoImgProxy->dynamic_texture_);
} else {
std::cerr << "--------Cannot update dynamic Texture Data--------"
<< std::endl;
}
} else {
std::cerr
<< "-----------Cannot load compressed image from data with QImage"
<< std::endl;
}
} else {
std::cerr
<< "----Dynamic Texture is nullptr or apollo.drivers.Image is nullptr"
<< std::endl;
}
theVideoImgProxy->reader_mutex_.unlock();
}
void MainWindow::PlayVideoImage(bool b) {
QPushButton* obj = static_cast<QPushButton*>(QObject::sender());
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(obj, VideoImgProxy, action_item_button_);
DoPlayVideoImage(b, theVideoImg);
}
void MainWindow::DoPlayVideoImage(bool b, VideoImgProxy* theVideoImg) {
if (b) {
if (theVideoImg->channel_name_combobox_.currentText().isEmpty()) {
QMessageBox::warning(
this, tr("Settup Channel Name"),
tr("Channel Name cannot be empty!!!\nPlease select one!"),
QMessageBox::Ok);
theVideoImg->action_item_button_.setChecked(false);
return;
}
const std::string channelName =
theVideoImg->channel_name_combobox_.currentText().toStdString();
if (_channelName2TypeMap[channelName] == CompressedImageType)
theVideoImg->isCompressedImage_ = true;
if (!theVideoImg->image_reader_) {
if (theVideoImg->isCompressedImage_) {
theVideoImg->compressed_image_reader_ =
new CyberChannReader<apollo::drivers::CompressedImage>();
} else {
theVideoImg->image_reader_ =
new CyberChannReader<apollo::drivers::Image>();
}
if (!theVideoImg->image_reader_) {
QMessageBox::warning(this, tr("Create cyber Channel Reader"),
tr("There is no enough memory!!!\nCannot create "
"cyber channel reader!"),
QMessageBox::Ok);
return;
}
std::string nodeName("Visualizer-");
nodeName.append(theVideoImg->root_item_.text(0).toStdString());
bool ret = false;
if (theVideoImg->isCompressedImage_) {
auto videoCallback =
[this, theVideoImg](
const std::shared_ptr<apollo::drivers::CompressedImage>&
pdata) { this->ImageReaderCallback(pdata, theVideoImg); };
ret = theVideoImg->compressed_image_reader_->InstallCallbackAndOpen(
videoCallback, channelName, nodeName);
} else {
auto videoCallback =
[this, theVideoImg](
const std::shared_ptr<apollo::drivers::Image>& pdata) {
this->ImageReaderCallback(pdata, theVideoImg);
};
ret = theVideoImg->image_reader_->InstallCallbackAndOpen(
videoCallback, channelName, nodeName);
}
if (!ret) {
QMessageBox::warning(
this, tr("Settup Channel Callback"),
tr("Channel Callback cannot be installed!!!\nPlease check it!"),
QMessageBox::Ok);
theVideoImg->deleteReader();
theVideoImg->action_item_button_.setChecked(false);
return;
}
}
theVideoImg->root_item_.setToolTip(
0, theVideoImg->channel_name_combobox_.currentText());
theVideoImg->video_image_viewer_.setToolTip(
theVideoImg->channel_name_combobox_.currentText());
theVideoImg->action_item_button_.setText("Stop");
theVideoImg->channel_name_combobox_.setEnabled(false);
theVideoImg->reader_mutex_.unlock();
} else {
if (!theVideoImg->channel_name_combobox_.isEnabled()) {
theVideoImg->reader_mutex_.lock();
theVideoImg->action_item_button_.setText("Play");
theVideoImg->channel_name_combobox_.setEnabled(true);
}
}
ui_->treeWidget->setCurrentItem(nullptr);
ui_->treeWidget->clearFocus();
}
void MainWindow::ChangePointCloudChannel() {
if (pointcloud_channel_Reader_ != nullptr) {
pointcloud_channel_Reader_->CloseChannel();
std::string nodeName("Visualizer-");
nodeName.append(pointcloud_top_item_->text(0).toStdString());
pointcloud_channel_Reader_->OpenChannel(
pointcloud_comboBox_->currentText().toStdString(), nodeName);
}
}
void MainWindow::ChangeVideoImgChannel() {
QComboBox* obj = static_cast<QComboBox*>(QObject::sender());
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(obj, VideoImgProxy, channel_name_combobox_);
if (theVideoImg->image_reader_ != nullptr) {
theVideoImg->deleteReader();
}
}
void MainWindow::ChangeRadarChannel(void) {
QComboBox* obj = static_cast<QComboBox*>(QObject::sender());
RadarData* radar =
StructPtrByMemberPtr(obj, RadarData, channel_name_combobox_);
if (radar->channel_reader_ != nullptr) {
radar->channel_reader_->CloseChannel();
std::string nodeName("Visualizer-");
nodeName.append(radar->root_item_.text(0).toStdString());
radar->channel_reader_->OpenChannel(obj->currentText().toStdString(),
nodeName);
}
}
void MainWindow::SelectCurrentTreeItem(FixedAspectRatioWidget* dock) {
if (dock) {
VideoImgProxy* theVideoImg =
StructPtrByMemberPtr(dock, VideoImgProxy, video_image_viewer_);
theVideoImg->root_item_.setExpanded(true);
if (ui_->treeWidget->currentItem() == &theVideoImg->root_item_) {
ui_->actionDelImage->setEnabled(true);
} else {
ui_->treeWidget->setCurrentItem(&theVideoImg->root_item_);
}
ui_->treeWidget->setFocus();
}
}
void MainWindow::TopologyChanged(
const apollo::cyber::proto::ChangeMsg& changeMsg) {
if (apollo::cyber::proto::ChangeType::CHANGE_CHANNEL ==
changeMsg.change_type() &&
apollo::cyber::proto::RoleType::ROLE_WRITER == changeMsg.role_type() &&
apollo::cyber::proto::OperateType::OPT_JOIN == changeMsg.operate_type()) {
FindNewWriter(changeMsg.role_attr());
}
}
void MainWindow::FindNewWriter(
const apollo::cyber::proto::RoleAttributes& role) {
const std::string& channelName = role.channel_name();
if (_channelName2TypeMap.find(channelName) != _channelName2TypeMap.end()) {
return;
}
const std::string& msgTypeName = role.message_type();
_channelName2TypeMap[channelName] = msgTypeName;
QTreeWidgetItem* child = new QTreeWidgetItem();
if (child == nullptr) {
QMessageBox::warning(this, tr("Error"),
tr("No Enough for New Channel!!!\nPlease Select it!"),
QMessageBox::Ok);
return;
}
QString str(channelName.c_str());
child->setText(0, str);
child->setToolTip(0, str);
bool b = true;
for (int i = 0; i < all_channel_root_->childCount(); ++i) {
if (str < all_channel_root_->child(i)->text(0)) {
all_channel_root_->insertChild(i, child);
b = false;
}
}
if (b) {
all_channel_root_->addChild(child);
}
ui_->treeWidget->setRootIsDecorated(true);
if (str.contains("camera", Qt::CaseInsensitive)) {
for (VideoImgProxy* item : video_image_viewer_list_) {
item->channel_name_combobox_.addItem(str);
}
for (VideoImgProxy* item : closed_video_image_viewer_list_) {
item->channel_name_combobox_.addItem(str);
}
}
if (str.contains("pointcloud", Qt::CaseInsensitive)) {
pointcloud_comboBox_->addItem(str);
}
if (str.contains("radar", Qt::CaseInsensitive)) {
for (RadarData* item : radarData_list_) {
item->channel_name_combobox_.addItem(str);
}
for (RadarData* item : closed_radarData_list_) {
item->channel_name_combobox_.addItem(str);
}
}
}
void MainWindow::PlayPause(void) {
QObject* obj = QObject::sender();
bool b = true;
if (obj == ui_->actionPause) b = false;
if (pointcloud_top_item_) {
pointcloud_button_->setChecked(b);
PlayRenderableObject(b);
}
for (VideoImgProxy* p : video_image_viewer_list_) {
p->action_item_button_.setChecked(b);
DoPlayVideoImage(b, p);
}
for (RadarData* item : radarData_list_) {
item->action_item_button_.setChecked(b);
DoOpenRadarChannel(b, item);
}
}
void MainWindow::resizeEvent(QResizeEvent* event) {
QMainWindow::resizeEvent(event);
calculateWH();
}
void MainWindow::showMessage() {
QObject* obj = QObject::sender();
if (obj == ui_->actionAbout) {
msg_dialog_->setWindowTitle(tr("About"));
msg_dialog_->setMessage(aboutMessage);
goto showMsgLabel;
}
if (obj == ui_->actionLicense) {
msg_dialog_->setWindowTitle(tr("License"));
msg_dialog_->setMessage(licenseMessage);
showMsgLabel:
msg_dialog_->adjustSize();
msg_dialog_->show();
}
}
| 32.47696 | 80 | 0.660651 | [
"object"
] |
9ef93c4a6f7b48bb83a45b3ba1e672fb2e150b52 | 12,079 | cpp | C++ | MT/MT_Tracking/cv/MT_CalibrationDataFile.cpp | leonard-lab/MADTraC | f1830c377a075aa5ddff9342c4851d0715cdd6a4 | [
"MIT"
] | 5 | 2015-07-26T22:54:34.000Z | 2018-08-21T16:15:33.000Z | MT/MT_Tracking/cv/MT_CalibrationDataFile.cpp | leonard-lab/MADTraC | f1830c377a075aa5ddff9342c4851d0715cdd6a4 | [
"MIT"
] | null | null | null | MT/MT_Tracking/cv/MT_CalibrationDataFile.cpp | leonard-lab/MADTraC | f1830c377a075aa5ddff9342c4851d0715cdd6a4 | [
"MIT"
] | 1 | 2021-09-22T08:12:40.000Z | 2021-09-22T08:12:40.000Z | #include "MT_CalibrationDataFile.h"
#include <sstream>
#include <iomanip>
#include <time.h>
#include "MT/MT_Core/support/filesupport.h"
#include "MT/MT_Core/support/mathsupport.h"
static const std::string tag_line_start = "Camera calibration - ";
static const std::string tag_line_middle = " rows w/lengths [";
static const std::string tag_line_end = "] - created ";
static const unsigned int num_rows_expected = 9;
static const int row_lengths_expected[] = {-1, 2, 2, 1, 5, 3, 3, 3, 3};
static bool readAndValidateLine(FILE* f, int i, double* data)
{
std::vector<double> row_data = MT_ReadDoublesToEndOfLine(f);
if((int) row_data.size() != row_lengths_expected[i])
{
fprintf(stderr,
"MT_CalibrationDataFile read error: Row length mismatch [b, %d]\n",
i);
return false;
}
for(int j = 0; j < row_lengths_expected[i]; j++)
{
data[j] = row_data[j];
}
return true;
}
static bool validateAndRead(FILE* f, MT_CalibrationData* data)
{
std::string line1 = MT_TextToEndOfLine(f);
int r = line1.substr(0, tag_line_start.length()).compare(tag_line_start);
if(r != 0)
{
fprintf(stderr, "MT_CalibrationDataFile read error: Mismatch [a] in head of file\n");
return false;
}
line1 = line1.substr(tag_line_start.length());
std::stringstream ss;
ss.str(line1);
int num_rows;
std::string v;
ss >> num_rows;
if(num_rows != (int) num_rows_expected)
{
fprintf(stderr, "MT_CalibrationDataFile read error: Number of rows mismatch [a]\n");
return false;
}
int nr = ss.tellg();
line1 = line1.substr(nr);
r = line1.substr(0, tag_line_middle.length()).compare(tag_line_middle);
if(r != 0)
{
fprintf(stderr, "MT_CalibrationDataFile read error: Mismatch [b] in head of file\n");
return false;
}
line1 = line1.substr(tag_line_middle.length());
ss.str(line1);
for(int i = 0; i < num_rows; i++)
{
ss >> nr;
if(nr != row_lengths_expected[i])
{
fprintf(stderr,
"MT_CalibrationDataFile read error: Row length mismatch [a, %d]\n",
i);
return false;
}
}
data->info = line1.substr(((int) ss.tellg()) + 4); /* strip "] - " */
if(!readAndValidateLine(f, 1, data->f)){return false;};
if(!readAndValidateLine(f, 2, data->c)){return false;};
if(!readAndValidateLine(f, 3, &data->alpha)){return false;};
if(!readAndValidateLine(f, 4, data->k)){return false;};
if(!readAndValidateLine(f, 5, &(data->R[0]))){return false;};
if(!readAndValidateLine(f, 6, &(data->R[3]))){return false;};
if(!readAndValidateLine(f, 7, &(data->R[6]))){return false;};
if(!readAndValidateLine(f, 8, data->T)){return false;};
return true;
}
void MT_CopyCalibrationData(MT_CalibrationData* dest, const MT_CalibrationData& src)
{
dest->info = std::string(src.info);
memcpy(dest->f, src.f, 2*sizeof(double));
memcpy(dest->c, src.c, 2*sizeof(double));
dest->alpha = src.alpha;
memcpy(dest->k, src.k, 5*sizeof(double));
memcpy(dest->R, src.R, 9*sizeof(double));
memcpy(dest->T, src.T, 3*sizeof(double));
}
std::string MT_CalibrationDataToString(const MT_CalibrationData& calibData)
{
std::string result;
std::stringstream ss;
ss << "Camera calibration:\n\t" << calibData.info << std::endl;
ss << "\tFocal Parameters: " << calibData.f[0] << ", " << calibData.f[1] << std::endl;
ss << "\tPrincipal Point: " << calibData.c[0] << ", " << calibData.c[1] << std::endl;
ss << "\tSkew Coefficient: " << calibData.alpha << std::endl;
ss << "\tRadial Distortion Ceofficients: " <<
calibData.k[0] << ", " <<
calibData.k[1] << ", " <<
calibData.k[2] << ", " <<
calibData.k[3] << ", " <<
calibData.k[4] << ", " << std::endl;
ss << "\tRotation Matrix: \n\t [" <<
calibData.R[0] << " " <<
calibData.R[1] << " " <<
calibData.R[2] << "]\n\t [" <<
calibData.R[3] << " " <<
calibData.R[4] << " " <<
calibData.R[5] << "]\n\t [" <<
calibData.R[6] << " " <<
calibData.R[7] << " " <<
calibData.R[8] << "]\n";
ss << "\tTranslation: \n\t [" <<
calibData.T[0] << " " <<
calibData.T[0] << " " <<
calibData.T[0] << "]\n";
return ss.str();
}
static bool validateOpenCVCalibration(const CvMat* cameraMatrix,
const CvMat* distCoeffs,
const CvMat* rvec,
const CvMat* tvec,
const CvMat* R)
{
if(!cameraMatrix || !distCoeffs || !rvec || !tvec)
{
fprintf(stderr, "OpenCV Calibration Validation Error: NULL pointer\n");
return false;
}
if(cameraMatrix->rows != 3 || cameraMatrix->cols != 3)
{
fprintf(stderr,
"OpenCV Calibration Validation Error: Wrong camera matrix format\n");
return false;
}
if(!( (distCoeffs->rows == 5 && distCoeffs->cols == 1)
|| (distCoeffs->cols == 5 && distCoeffs->rows == 1)))
{
fprintf(stderr,
"OpenCV Calibration Validation Error: Wrong distortion coefficient format\n");
return false;
}
if(!( (rvec->rows == 3 && rvec->cols == 1)
|| (rvec->rows == 1 && rvec->cols == 3)))
{
fprintf(stderr,
"OpenCV Calibration Validation Error: Wrong rotation vector format\n");
return false;
}
if(!( (tvec->rows == 3 && tvec->cols == 1)
|| (tvec->rows == 1 && tvec->cols == 3)))
{
fprintf(stderr,
"OpenCV Calibration Validation Error: Wrong translation vector format\n");
return false;
}
if(R && (R->rows != 3 || R->cols != 3))
{
fprintf(stderr,
"OpenCV Calibration Validation Error: Wrong rotation matrix format\n");
return false;
}
return true;
}
bool MT_CalibrationDataToOpenCVCalibration(const MT_CalibrationData& calibData,
CvMat* cameraMatrix,
CvMat* distCoeffs,
CvMat* rvec,
CvMat* tvec,
CvMat* R)
{
if(!validateOpenCVCalibration(cameraMatrix, distCoeffs, rvec, tvec, R))
{
return false;
}
cvZero(cameraMatrix);
cvSetReal2D(cameraMatrix, 0, 0, calibData.f[0]);
cvSetReal2D(cameraMatrix, 1, 1, calibData.f[1]);
cvSetReal2D(cameraMatrix, 0, 2, calibData.c[0]);
cvSetReal2D(cameraMatrix, 1, 2, calibData.c[1]);
cvSetReal2D(cameraMatrix, 0, 1, calibData.alpha);
cvSetReal2D(cameraMatrix, 2, 2, 1.0);
cvSetReal1D(distCoeffs, 0, calibData.k[0]);
cvSetReal1D(distCoeffs, 1, calibData.k[1]);
cvSetReal1D(distCoeffs, 2, calibData.k[2]);
cvSetReal1D(distCoeffs, 3, calibData.k[3]);
cvSetReal1D(distCoeffs, 4, calibData.k[4]);
CvMat* Rt = cvCreateMat(3, 3, CV_32FC1);
cvSetReal2D(Rt, 0, 0, calibData.R[0]);
cvSetReal2D(Rt, 0, 1, calibData.R[1]);
cvSetReal2D(Rt, 0, 2, calibData.R[2]);
cvSetReal2D(Rt, 1, 0, calibData.R[3]);
cvSetReal2D(Rt, 1, 1, calibData.R[4]);
cvSetReal2D(Rt, 1, 2, calibData.R[5]);
cvSetReal2D(Rt, 2, 0, calibData.R[6]);
cvSetReal2D(Rt, 2, 1, calibData.R[7]);
cvSetReal2D(Rt, 2, 2, calibData.R[8]);
if(R)
{
cvCopy(Rt, R);
}
cvRodrigues2(Rt, rvec);
cvSetReal1D(tvec, 0, calibData.T[0]);
cvSetReal1D(tvec, 1, calibData.T[1]);
cvSetReal1D(tvec, 2, calibData.T[2]);
cvReleaseMat(&Rt);
return true;
}
bool MT_OpenCVCalibrationToCalibrationData(const CvMat* cameraMatrix,
const CvMat* distCoeffs,
const CvMat* rvec,
const CvMat* tvec,
MT_CalibrationData* calibData)
{
if(!validateOpenCVCalibration(cameraMatrix, distCoeffs, rvec, tvec, NULL))
{
return false;
}
if(!calibData)
{
return false;
}
calibData->f[0] = cvGetReal2D(cameraMatrix, 0, 0);
calibData->f[1] = cvGetReal2D(cameraMatrix, 1, 1);
calibData->c[0] = cvGetReal2D(cameraMatrix, 0, 2);
calibData->c[1] = cvGetReal2D(cameraMatrix, 1, 2);
calibData->alpha = cvGetReal2D(cameraMatrix, 0, 1);
calibData->k[0] = cvGetReal1D(distCoeffs, 0);
calibData->k[1] = cvGetReal1D(distCoeffs, 1);
calibData->k[2] = cvGetReal1D(distCoeffs, 2);
calibData->k[3] = cvGetReal1D(distCoeffs, 3);
calibData->k[4] = cvGetReal1D(distCoeffs, 4);
CvMat* Rt = cvCreateMat(3, 3, CV_32FC1);
cvRodrigues2(rvec, Rt);
calibData->R[0] = cvGetReal2D(Rt, 0, 0);
calibData->R[1] = cvGetReal2D(Rt, 0, 1);
calibData->R[2] = cvGetReal2D(Rt, 0, 2);
calibData->R[3] = cvGetReal2D(Rt, 1, 0);
calibData->R[4] = cvGetReal2D(Rt, 1, 1);
calibData->R[5] = cvGetReal2D(Rt, 1, 2);
calibData->R[6] = cvGetReal2D(Rt, 2, 0);
calibData->R[7] = cvGetReal2D(Rt, 2, 1);
calibData->R[8] = cvGetReal2D(Rt, 2, 2);
calibData->T[0] = cvGetReal1D(tvec, 0);
calibData->T[1] = cvGetReal1D(tvec, 1);
calibData->T[2] = cvGetReal1D(tvec, 2);
return true;
}
MT_CalibrationDataFile::MT_CalibrationDataFile(const char* filename,
MT_CalibrationLoadMode mode)
: m_bDidLoadOK(false),
m_Data(),
m_Mode(mode),
m_sFileName(filename)
{
if(mode == MT_CALIB_READ)
{
if(!MT_FileIsAvailable(filename, "r"))
{
fprintf(stderr, "MT_CalibrationDataFile Error: Could not load %s", filename);
return;
}
FILE* f = fopen(filename, "r");
m_bDidLoadOK = validateAndRead(f, &m_Data);
fclose(f);
}
else
{
if(!MT_FileIsAvailable(filename, "wa"))
{
fprintf(stderr, "MT_CalibrationDataFile Error: Could not load %s", filename);
return;
}
m_bDidLoadOK = true;
}
}
MT_CalibrationDataFile::~MT_CalibrationDataFile()
{
}
bool MT_CalibrationDataFile::didLoadOK() const
{
return m_bDidLoadOK;
}
bool MT_CalibrationDataFile::getCalibration(MT_CalibrationData* calibData)
{
if(!calibData || !m_bDidLoadOK || (m_Mode != MT_CALIB_READ))
{
return false;
}
MT_CopyCalibrationData(calibData, m_Data);
return true;
}
bool MT_CalibrationDataFile::writeCalibration(const MT_CalibrationData& calibData)
{
if(!m_bDidLoadOK || (m_Mode != MT_CALIB_WRITE))
{
return false;
}
MT_CopyCalibrationData(&m_Data, calibData);
std::ofstream f(m_sFileName.c_str());
f << tag_line_start << num_rows_expected << tag_line_middle;
for(unsigned int i = 0; i < num_rows_expected; i++)
{
f << " " << row_lengths_expected[i];
}
if(m_Data.info.length() == 0 || m_Data.info.compare("N/A") == 0)
{
time_t nowtime;
time(&nowtime);
f << tag_line_end << ctime(&nowtime); // already includes newline (?)
}
else
{
f << tag_line_end << m_Data.info << std::endl;
}
f << m_Data.f[0] << " " << m_Data.f[1] << std::endl;
f << m_Data.c[0] << " " << m_Data.c[1] << std::endl;
f << m_Data.alpha << std::endl;
f << m_Data.k[0] << " " << m_Data.k[1] << " " << m_Data.k[2] << " "
<< m_Data.k[3] << " " << m_Data.k[4] << std::endl;
f << m_Data.R[0] << " " << m_Data.R[1] << " " << m_Data.R[2] << std::endl;
f << m_Data.R[3] << " " << m_Data.R[4] << " " << m_Data.R[5] << std::endl;
f << m_Data.R[6] << " " << m_Data.R[7] << " " << m_Data.R[8] << std::endl;
f << m_Data.T[0] << " " << m_Data.T[1] << " " << m_Data.T[2] << std::endl;
f.close();
return true;
}
| 30.349246 | 95 | 0.556172 | [
"vector"
] |
9efbf76f02be22a67af37172619c48caa65627ff | 5,840 | cc | C++ | 3rdParty/rocksdb/6.27/utilities/options/options_util.cc | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 15 | 2018-12-16T13:11:33.000Z | 2021-12-08T10:38:08.000Z | 3rdParty/rocksdb/6.27/utilities/options/options_util.cc | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 26 | 2021-06-08T16:20:23.000Z | 2022-03-30T03:42:21.000Z | 3rdParty/rocksdb/6.27/utilities/options/options_util.cc | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | 26 | 2018-12-13T05:44:22.000Z | 2021-11-17T21:22:41.000Z | // 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).
#ifndef ROCKSDB_LITE
#include "rocksdb/utilities/options_util.h"
#include "file/filename.h"
#include "options/options_parser.h"
#include "rocksdb/convenience.h"
#include "rocksdb/options.h"
#include "table/block_based/block_based_table_factory.h"
namespace ROCKSDB_NAMESPACE {
Status LoadOptionsFromFile(const std::string& file_name, Env* env,
DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
bool ignore_unknown_options,
std::shared_ptr<Cache>* cache) {
ConfigOptions config_options;
config_options.ignore_unknown_options = ignore_unknown_options;
config_options.input_strings_escaped = true;
config_options.env = env;
return LoadOptionsFromFile(config_options, file_name, db_options, cf_descs,
cache);
}
Status LoadOptionsFromFile(const ConfigOptions& config_options,
const std::string& file_name, DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
std::shared_ptr<Cache>* cache) {
RocksDBOptionsParser parser;
const auto& fs = config_options.env->GetFileSystem();
Status s = parser.Parse(config_options, file_name, fs.get());
if (!s.ok()) {
return s;
}
*db_options = *parser.db_opt();
const std::vector<std::string>& cf_names = *parser.cf_names();
const std::vector<ColumnFamilyOptions>& cf_opts = *parser.cf_opts();
cf_descs->clear();
for (size_t i = 0; i < cf_opts.size(); ++i) {
cf_descs->push_back({cf_names[i], cf_opts[i]});
if (cache != nullptr) {
TableFactory* tf = cf_opts[i].table_factory.get();
if (tf != nullptr) {
auto* opts = tf->GetOptions<BlockBasedTableOptions>();
if (opts != nullptr) {
opts->block_cache = *cache;
}
}
}
}
return Status::OK();
}
Status GetLatestOptionsFileName(const std::string& dbpath,
Env* env, std::string* options_file_name) {
Status s;
std::string latest_file_name;
uint64_t latest_time_stamp = 0;
std::vector<std::string> file_names;
s = env->GetChildren(dbpath, &file_names);
if (s.IsNotFound()) {
return Status::NotFound(Status::kPathNotFound,
"No options files found in the DB directory.",
dbpath);
} else if (!s.ok()) {
return s;
}
for (auto& file_name : file_names) {
uint64_t time_stamp;
FileType type;
if (ParseFileName(file_name, &time_stamp, &type) && type == kOptionsFile) {
if (time_stamp > latest_time_stamp) {
latest_time_stamp = time_stamp;
latest_file_name = file_name;
}
}
}
if (latest_file_name.size() == 0) {
return Status::NotFound(Status::kPathNotFound,
"No options files found in the DB directory.",
dbpath);
}
*options_file_name = latest_file_name;
return Status::OK();
}
Status LoadLatestOptions(const std::string& dbpath, Env* env,
DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
bool ignore_unknown_options,
std::shared_ptr<Cache>* cache) {
ConfigOptions config_options;
config_options.ignore_unknown_options = ignore_unknown_options;
config_options.input_strings_escaped = true;
config_options.env = env;
return LoadLatestOptions(config_options, dbpath, db_options, cf_descs, cache);
}
Status LoadLatestOptions(const ConfigOptions& config_options,
const std::string& dbpath, DBOptions* db_options,
std::vector<ColumnFamilyDescriptor>* cf_descs,
std::shared_ptr<Cache>* cache) {
std::string options_file_name;
Status s =
GetLatestOptionsFileName(dbpath, config_options.env, &options_file_name);
if (!s.ok()) {
return s;
}
return LoadOptionsFromFile(config_options, dbpath + "/" + options_file_name,
db_options, cf_descs, cache);
}
Status CheckOptionsCompatibility(
const std::string& dbpath, Env* env, const DBOptions& db_options,
const std::vector<ColumnFamilyDescriptor>& cf_descs,
bool ignore_unknown_options) {
ConfigOptions config_options(db_options);
config_options.sanity_level = ConfigOptions::kSanityLevelLooselyCompatible;
config_options.ignore_unknown_options = ignore_unknown_options;
config_options.input_strings_escaped = true;
config_options.env = env;
return CheckOptionsCompatibility(config_options, dbpath, db_options,
cf_descs);
}
Status CheckOptionsCompatibility(
const ConfigOptions& config_options, const std::string& dbpath,
const DBOptions& db_options,
const std::vector<ColumnFamilyDescriptor>& cf_descs) {
std::string options_file_name;
Status s =
GetLatestOptionsFileName(dbpath, config_options.env, &options_file_name);
if (!s.ok()) {
return s;
}
std::vector<std::string> cf_names;
std::vector<ColumnFamilyOptions> cf_opts;
for (const auto& cf_desc : cf_descs) {
cf_names.push_back(cf_desc.name);
cf_opts.push_back(cf_desc.options);
}
const auto& fs = config_options.env->GetFileSystem();
return RocksDBOptionsParser::VerifyRocksDBOptionsFromFile(
config_options, db_options, cf_names, cf_opts,
dbpath + "/" + options_file_name, fs.get());
}
} // namespace ROCKSDB_NAMESPACE
#endif // !ROCKSDB_LITE
| 36.5 | 80 | 0.657705 | [
"vector"
] |
9efd3c4239773035a000d0ef12f25a788215ee28 | 750 | cpp | C++ | CrossPlatform/BottomLevelAccelerationStructure.cpp | simul/Platform | 5825b3ce8540c6996ba6ab59a55581e44c68e7ad | [
"MIT"
] | 5 | 2020-07-20T15:47:46.000Z | 2021-12-23T20:54:22.000Z | CrossPlatform/BottomLevelAccelerationStructure.cpp | simul/Platform | 5825b3ce8540c6996ba6ab59a55581e44c68e7ad | [
"MIT"
] | 1 | 2021-07-12T09:53:30.000Z | 2021-07-12T09:53:30.000Z | CrossPlatform/BottomLevelAccelerationStructure.cpp | simul/Platform | 5825b3ce8540c6996ba6ab59a55581e44c68e7ad | [
"MIT"
] | 3 | 2020-10-01T14:02:28.000Z | 2021-05-27T14:15:35.000Z | #include "BottomLevelAccelerationStructure.h"
using namespace simul;
using namespace crossplatform;
////////////////////////////////////
//BottomLevelAccelerationStructure//
////////////////////////////////////
BottomLevelAccelerationStructure::BottomLevelAccelerationStructure(crossplatform::RenderPlatform* r)
:BaseAccelerationStructure(r)
{
}
BottomLevelAccelerationStructure::~BottomLevelAccelerationStructure()
{
}
void BottomLevelAccelerationStructure::SetMesh(crossplatform::Mesh* mesh)
{
this->mesh = mesh;
geometryType = GeometryType::TRIANGLE_MESH;
}
void BottomLevelAccelerationStructure::SetAABB(crossplatform::StructuredBuffer<Raytracing_AABB>* aabbBuffer)
{
this->aabbBuffer = aabbBuffer;
geometryType = GeometryType::AABB;
} | 25.862069 | 108 | 0.749333 | [
"mesh"
] |
9effefedf049ec1f3b0eb54b115a84e8d814ca01 | 2,665 | cpp | C++ | sg/scene/lights/SunSky.cpp | ospray/ospray_studio | 1549ac72c7c561b4aafdea976189bbe95bd32ff2 | [
"Apache-2.0"
] | 52 | 2018-10-09T23:56:32.000Z | 2022-03-25T09:27:40.000Z | sg/scene/lights/SunSky.cpp | ospray/ospray_studio | 1549ac72c7c561b4aafdea976189bbe95bd32ff2 | [
"Apache-2.0"
] | 11 | 2018-11-19T18:51:47.000Z | 2022-03-28T14:03:57.000Z | sg/scene/lights/SunSky.cpp | ospray/ospray_studio | 1549ac72c7c561b4aafdea976189bbe95bd32ff2 | [
"Apache-2.0"
] | 8 | 2019-02-10T00:16:24.000Z | 2022-02-17T19:50:15.000Z | // Copyright 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "Light.h"
namespace ospray {
namespace sg {
struct OSPSG_INTERFACE SunSky : public Light
{
SunSky();
virtual ~SunSky() override = default;
protected:
void preCommit() override;
};
OSP_REGISTER_SG_NODE_NAME(SunSky, sunSky);
// Sunsky definitions //////////////////////////////////////////////////////
SunSky::SunSky() : Light("sunSky")
{
createChild(
"up", "vec3f", "zenith of sky in world-space", vec3f(0.f, 1.f, 0.f));
createChild("right",
"vec3f",
"right-pointing vector, such that up cross right = direction",
vec3f(0.f, 0.f, 1.f));
createChild("azimuth", "float", "sun's angular distance from North", 0.f);
createChild(
"elevation", "float", "sun's angle relative to the horizon", 90.f);
createChild("albedo", "float", "ground reflectance [0-1]", 0.18f);
createChild("turbidity",
"float",
"atmospheric turbidity due to particles [1-10]",
3.f);
createChild("direction",
"vec3f",
"main emission direction of the sun",
vec3f(0.f, 1.f, 0.f));
createChild("horizonExtension",
"float",
"extend sky dome by stretching the horizon,\n"
"fraction of the lower hemisphere to cover [0-1]",
0.01f);
child("intensityQuantity").setValue((uint8_t)OSP_INTENSITY_QUANTITY_RADIANCE);
// Set reasonable limits, this will set slider range
child("albedo").setMinMax(0.f, 1.f);
child("azimuth").setMinMax(-180.f, 180.f);
child("elevation").setMinMax(-90.f, 90.f);
child("turbidity").setMinMax(0.f, 10.f);
child("horizonExtension").setMinMax(0.f, 1.f);
child("direction").setReadOnly();
// SceneGraph internal
child("azimuth").setSGOnly();
child("elevation").setSGOnly();
child("right").setSGOnly();
}
void SunSky::preCommit()
{
const float azimuth = child("azimuth").valueAs<float>() * M_PI / 180.f;
const float elevation = child("elevation").valueAs<float>() * M_PI / 180.f;
vec3f up = child("up").valueAs<vec3f>();
vec3f dir = child("right").valueAs<vec3f>();
vec3f p1 = cross(up, dir);
LinearSpace3f r1 = LinearSpace3f::rotate(dir, -elevation);
vec3f p2 = r1 * p1;
LinearSpace3f r2 = LinearSpace3f::rotate(up, azimuth);
vec3f p3 = r2 * p2;
vec3f direction = p3;
if (!(std::isnan(direction.x) || std::isnan(direction.y)
|| std::isnan(direction.z))) {
// this overwrites the "direction" child parameters, making that UI element
// not directly useable...
auto &directionNode = child("direction");
directionNode.setValue(direction);
}
Light::preCommit();
}
} // namespace sg
} // namespace ospray
| 29.611111 | 80 | 0.643902 | [
"vector"
] |
7300feaffa4c2d9c667ed89f3b33e112c29ce40e | 1,246 | cpp | C++ | 1. Array/04. Largest area in histogram.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | 1. Array/04. Largest area in histogram.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | 1. Array/04. Largest area in histogram.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | //https://leetcode.com/problems/largest-rectangle-in-histogram/
vector<int>find_rightmin(vector<int>arr){
int n=arr.size();
vector<int>res(n);
stack<int>st;
for(int i=n-1;i>=0;i--){
while(!st.empty() && arr[st.top()]>=arr[i]){
st.pop();
}
res[i]=(st.empty())?n:st.top();
st.push(i);
}
return res;
}
vector<int>find_leftmin(vector<int>arr){
int n=arr.size();
vector<int>res(n);
stack<int>st;
for(int i=0;i<n;i++){
while(!st.empty() && arr[st.top()]>=arr[i]){
st.pop();
}
res[i]=(st.empty())?-1:st.top();
st.push(i);
}
return res;
}
int largestRectangleArea(vector<int>& arr) {
int maxHeight=0;
int n=arr.size();
//find left min and right min
vector<int>rightMin=find_rightmin(arr);
vector<int>leftMin=find_leftmin(arr);
for(int i=0;i<n;i++){
int width=((rightMin[i]-1)-(leftMin[i]+1))+1; //width= right-left+1
maxHeight=max(maxHeight, width*arr[i]);
}
return maxHeight;
} | 30.390244 | 80 | 0.463082 | [
"vector"
] |
73033bba2f5cd6dce30c8fbb62f824ae75811cb2 | 23,924 | cc | C++ | physics/tests/TestNudy0/GeantV/TestNudy0_GV.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | physics/tests/TestNudy0/GeantV/TestNudy0_GV.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | physics/tests/TestNudy0/GeantV/TestNudy0_GV.cc | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/**
* @brief TestNudy0: simple GeantV-Low energy neutron test using Nudy.
* @author Harphool Kumawat
* @date June 2018
*
* A simple test for Nudy package where low energy neutron (< 20MeV) data
* are processed from the ufor a given particle, target material,
* particle kinetic energy and secondary production threshold. EM processes, that has
* discrete part and assigned to the given particle in the given physics-list, are
* extracted from the physics-list and the integrated quantities are computed by calling
* EMProcess/EMModel interface methods. Quantites, that are available in tables (built
* at the physics initialisation), also extracted (i.e. interpolated) from these tables
* by using the corresponding interface methods. Note, that atomic cross sections are
* computed only for materials that has a single elemnt.
*
* Run ./TestNudy0_GV --help for more details!
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <getopt.h>
#include <err.h>
#include "Geant/Material.h"
#include "Geant/Element.h"
#include "Geant/MaterialCuts.h"
#include "Geant/Isotope.h"
// vecgeom includes
#include "volumes/LogicalVolume.h"
#include "volumes/Box.h"
#include "Geant/Region.h"
#include "Geant/PhysicsListManager.h"
#include "Geant/PhysicsList.h"
#include "Geant/PhysicsParameters.h"
// include the user defined physics list
#include "UserPhysicsList.h"
#include "Geant/PhysicsManagerPerParticle.h"
#include "Geant/PhysicsProcess.h"
#include "Geant/Particle.h"
#include "Geant/Electron.h"
#include "Geant/Positron.h"
#include "Geant/Gamma.h"
#include "Geant/Proton.h"
#include "Geant/Neutron.h"
#include "Geant/PionPlus.h"
#include "Geant/PionMinus.h"
#include "Geant/PionZero.h"
#include "Geant/KaonPlus.h"
#include "Geant/KaonMinus.h"
#include "Geant/KaonZero.h"
#include "Geant/KaonShort.h"
#include "Geant/KaonLong.h"
#include "Geant/HadronicProcess.h"
#include "Geant/HadronicFinalStateModel.h"
#include "Geant/HadronicFinalStateModelStore.h"
#include "Geant/TNudyEndfFile.h"
#include "Geant/TNudyEndfTape.h"
#include "Geant/TNudyEndfTab1.h"
#include "Geant/TNudyEndfTab2.h"
#include "Geant/TNudyEndfMat.h"
#include "Geant/TNudyENDF.h"
#include "Geant/TNudyEndfSigma.h"
#include "Geant/TNudyEndfRecoPoint.h"
#include "Geant/ElasticScatteringProcess.h"
#include "Geant/DiffuseElasticModel.h"
#include "Geant/GlauberGribovElasticXsc.h"
#include "Geant/TNudyEndfRecoPoint.h"
#include "Geant/NeutronNudyElasticModel.h"
#include "Geant/NeutronNudyInelasticModel.h"
#include "Geant/NeutronNudyFissionModel.h"
#include "Geant/NeutronNudyCaptureModel.h"
#include "Geant/NeutronNudyElasticXsec.h"
#include "Geant/NeutronNudyInelasticXsec.h"
#include "Geant/NeutronNudyFissionXsec.h"
#include "Geant/NeutronNudyCaptureXsec.h"
#include "Geant/LightTrack.h"
#include "Geant/PhysicsData.h"
// from geantV
#include "Geant/Typedefs.h"
#include "Geant/TaskData.h"
#include "Hist.h"
using geantphysics::Element;
using geantphysics::Isotope;
using geantphysics::Material;
using geantphysics::MaterialCuts; // this is just to print the table
using geantphysics::PhysicsList;
using geantphysics::PhysicsListManager;
using geantphysics::PhysicsParameters;
using geantphysics::PhysicsManagerPerParticle;
using geantphysics::PhysicsProcess;
using geantphysics::Electron;
using geantphysics::Gamma;
using geantphysics::Neutron;
using geantphysics::Particle;
using geantphysics::Positron;
using geantphysics::Proton;
using geantphysics::HadronicFinalStateModel;
using geantphysics::HadronicProcess;
using geantphysics::LightTrack;
using geantphysics::PhysicsData;
using userapplication::Hist;
//
// default values of the input parameters
static std::string particleName("n"); // primary particle is neutron
static std::string materialName("NIST_MAT_Pb"); // material is lead
static int Z = 82; // Charge number of the isotope
static int N = 208; // Total nucleons of the isotope
static int numHistBins1 = 50; // number of histogram bins between min/max values
static int numHistBins2 = 1000; // number of histogram bins between min/max values
static int numHistBins3 = 20; // number of histogram bins between min/max values
static int numSamples = 1.e+7; // number of required final state samples
static double primaryEnergy = 1E-3; // primary particle energy in [GeV]
static double prodCutValue = 1E-11; // by default in length and internal units i.e. [cm]
static bool isProdCutInLength = true; // is the production cut value given in length ?
double sampleDistribution(double numSamples, double primaryEnergy, const MaterialCuts *matCut, Isotope *isotope,
Particle *primParticle, HadronicFinalStateModel *nudyModel, Hist *h1, Hist *h2, Hist *h3);
static struct option options[] = {
{"particle-name (possible particle: n) - default: n", required_argument, 0, 'p'},
{"material-name (with a NIST_MAT_ prefix; see more in material doc.) - default: NIST_MAT_Pb",
required_argument, 0, 'm'},
{"number-of-samples (number of required final state samples) - default: 1.e+7", required_argument,
0, 'f'},
{"primary-energy (in internal energy units i.e. [GeV]) - default: 1E-3",
required_argument, 0, 'E'},
{"sampling target Z (proton number: z) - default: 82", required_argument, 0, 'z'},
{"sampling target A (Mass number (proton + neutron): A) - default: 208", required_argument, 0, 'a'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}};
void help();
//===========================================================================================//
int main(int argc, char *argv[])
{
//
// Get input parameters
while (true) {
int c, optidx = 0;
c = getopt_long(argc, argv, "p:m:E:f:c:z:a:", options, &optidx);
if (c == -1) break;
switch (c) {
case 0:
c = options[optidx].val;
/* fall through */
case 'p':
particleName = optarg;
break;
case 'm':
materialName = optarg;
break;
case 'E':
primaryEnergy = (double)strtof(optarg, NULL);
if (primaryEnergy <= 0) errx(1, "primary particle energy must be positive");
break;
case 'f':
numSamples = (double)strtof(optarg, NULL);
if (numSamples <= 0) errx(1, "number of final state samples must be positive");
break;
case 'c':
prodCutValue = (double)strtof(optarg, NULL);
if (prodCutValue <= 0) errx(1, "production cut value must be positive");
break;
case 'e':
isProdCutInLength = false;
break;
case 'z':
Z = (double)strtof(optarg, NULL);
if (Z <= 0) errx(1, "Proton no. must be positive");
break;
case 'a':
N = (double)strtof(optarg, NULL);
if (N <= 0) errx(1, "Mass no. must be positive");
break;
case 'h':
help();
return 0;
break;
default:
help();
errx(1, "unknown option %c", c);
}
}
//============================= User defined input data =====================================//
//
// Create target material: which is supposed to be a NIST Material
Material *matDetector = Material::NISTMaterial(materialName);
//
// Set particle (Electron,Positron,Gamma)
Particle *particle = nullptr;
if (particleName == "n") {
particle = Neutron::Definition();
} else {
std::cerr << " ***** ERROR: unknown particle name: " << particleName << std::endl;
help();
return 0;
}
//
// Set particle kinetic energy
double kineticEnergy = primaryEnergy;
double logKinE = Math::Log(primaryEnergy);
//============= Initialization i.e. building up and init the physics ========================//
//
// Create a dummy vecgeom::geometry with only one volume i.e. world; create a region and set production cuts
//
// create a vecgeom::LogicalVolume
vecgeom::UnplacedBox worldParams = vecgeom::UnplacedBox(1., 1., 1.);
vecgeom::LogicalVolume worldl(&worldParams);
// create one region and assigne to the logical volume
vecgeom::Region *aRegion = new vecgeom::Region("ARegion"); //,iscutinlength, gcut, emcut, epcut);
worldl.SetRegion(aRegion);
// set the material pointer in the world logical volume
worldl.SetMaterialPtr((void *)matDetector);
vecgeom::GeoManager::Instance().SetWorld(worldl.Place());
vecgeom::GeoManager::Instance().CloseGeometry();
// print the material table
// std::cerr<< Material::GetTheMaterialTable();
//
// Create all MaterialCuts
//
MaterialCuts::CreateAll();
// print all MaterialCuts
// std::cout<<MaterialCuts::GetTheMaterialCutsTable()<<std::endl;
//
// Set number of regions in the PhysicsListManager: during normal physics init., it is done
// automatically in the PhysicsProcessHandler::Initialize()
PhysicsListManager::Instance().SetNumberOfRegions(vecgeom::Region::GetNumberOfRegions());
//
// Create one user physics list.
//
// THIS IS VERY SIMILAR To Geant4 STYLE
// The same as above but if we have only one physics list and the active region vector is not provided then that one
// phyics list will be used in all regions
// this is what the user needs to do:
// 1. create the physics list
// create the ENDF based elastic model for elastic scattering
PhysicsList *thePhysicsList = new userapplication::UserPhysicsList("UserDefined-PhysicsList");
// The user can get the PhysicsParameters form the physics list and change default values:
// - unlike in case of usual simulation, now we request to compute the CSDA range table
thePhysicsList->GetPhysicsParameters()->SetIsComputeCSDARange(true);
// 2. register the physics list:
PhysicsListManager::Instance().RegisterPhysicsList(thePhysicsList);
// Build all registered physics lists: during normal physics init., it is done
// automatically in the PhysicsProcessHandler::Initialize()
PhysicsListManager::Instance().BuildPhysicsLists();
//===========================================================================================//
//======================== Getting the required information =================================//
//
// Now get the list of EM processes assigned to the particle and use them.
//
std::cout << std::endl << std::endl;
std::cout << " ================================================================================ \n"
<< " ================================ RESULTS ================================= \n"
<< " ================================================================================ \n";
// first get the MaterialCuts: we have only one
const MaterialCuts *matCut = MaterialCuts::GetMaterialCut(aRegion->GetIndex(), matDetector->GetIndex());
std::cout << " Material = " << matDetector->GetName() << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Particle = " << particle->GetName() << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Kinetic energy = " << kineticEnergy / geant::units::MeV << " [MeV] " << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Physics list = " << thePhysicsList->GetName() << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
//
// Get all processes, assigned to this partcile and active in the given region, that has discrete part.
PhysicsManagerPerParticle *thePhysManager = particle->GetPhysicsManagerPerParticlePerRegion(matCut->GetRegionIndex());
// check if the particle has any processes assined to (in the current region): if not than the thePhysManager =
// nullptr
size_t numPostStepCandidateProcesses = 0;
std::vector<PhysicsProcess *> thePostStepCandProcVect;
if (thePhysManager) {
thePostStepCandProcVect = thePhysManager->GetListPostStepCandidateProcesses();
numPostStepCandidateProcesses = thePostStepCandProcVect.size();
}
std::cout << " The particle has " << numPostStepCandidateProcesses << " processes with discrete part assinged to."
<< std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
// terminate if there is no any post-step candidate processes assigned to the particle in the given region.
if (!numPostStepCandidateProcesses) {
std::cout << " ================================================================================ " << std::endl
<< std::endl;
return 0;
}
double compTotalMacXsec = 0.0; // computed total macroscopic cross section i.e. summed up per-process mac. x-secs
double getTotalMacXsec = 0.0; // same but interpolated from the lambda table that is built at initialization
double compTotalAtomicXsec = 0.0; // computed total atomic cross section (only if material has 1 element)
std::vector<std::string> processNameVect; // process names
std::vector<double> compMacXsecPerProcessVect; // computed macroscopic cross sections per-process
std::vector<double> getMacXsecPerProcessVect; // same but interpolated from the lambda table that is built at init.
std::vector<double> compAtomicXsectionVect; // computed atomic cross sections (only if material has 1 element)
// TNudyEndfRecoPoint *recopoint = new TNudyEndfRecoPoint(0,rENDF);
bool isSingleElementMaterial = false;
if (matCut->GetMaterial()->GetNumberOfElements() == 1) {
isSingleElementMaterial = true;
}
for (size_t i = 0; i < thePostStepCandProcVect.size(); ++i) {
PhysicsProcess *proc = thePostStepCandProcVect[i];
processNameVect.push_back(proc->GetName());
compMacXsecPerProcessVect.push_back(
proc->ComputeMacroscopicXSection(matCut, kineticEnergy, particle, particle->GetPDGMass()));
compTotalMacXsec += compMacXsecPerProcessVect[i];
getMacXsecPerProcessVect.push_back(
proc->GetMacroscopicXSection(matCut, kineticEnergy, logKinE, particle->GetPDGMass()));
getTotalMacXsec += getMacXsecPerProcessVect[i];
if (isSingleElementMaterial) {
compAtomicXsectionVect.push_back(static_cast<HadronicProcess *>(proc)->GetAtomicCrossSection(
particle->GetInternalCode(), kineticEnergy, particle->GetPDGMass(),
(matCut->GetMaterial()->GetElementVector())[0], matDetector));
compTotalAtomicXsec += compAtomicXsectionVect[i];
}
}
processNameVect.push_back("total");
compMacXsecPerProcessVect.push_back(compTotalMacXsec);
getMacXsecPerProcessVect.push_back(getTotalMacXsec);
compAtomicXsectionVect.push_back(compTotalAtomicXsec);
std::cout << " process name :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
std::cout << std::setw(16) << std::right << processNameVect[i] << std::setw(10) << " ";
}
std::cout << std::endl;
std::cout << std::endl;
if (isSingleElementMaterial) {
std::cout << " cross section per atom :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
std::cout << std::setw(14) << std::scientific << std::right << compAtomicXsectionVect[i] / (geant::units::barn)
<< std::setw(14) << std::left << " [barn]";
}
std::cout << std::endl;
std::cout << std::endl;
}
std::cout << " compCrossSectionPerVolume :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
std::cout << std::setw(14) << std::scientific << std::right
<< compMacXsecPerProcessVect[i] / (1. / geant::units::cm) << std::setw(14) << std::left << " [1/cm]";
}
std::cout << std::endl;
std::cout << " cross section per volume :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
std::cout << std::setw(14) << std::scientific << std::right << getMacXsecPerProcessVect[i] / (1. / geant::units::cm)
<< std::setw(14) << std::left << " [1/cm]";
}
std::cout << std::endl;
double density = matCut->GetMaterial()->GetDensity() / (geant::units::g / geant::units::cm3); // density in [g/cm3]
std::cout << " cross section per mass :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
std::cout << std::setw(14) << std::scientific << std::right
<< getMacXsecPerProcessVect[i] / density / (1. / geant::units::cm) << std::setw(14) << std::left
<< " [cm2/g]";
}
std::cout << std::endl;
std::cout << std::endl;
std::cout << " mean free path (length) :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
double lambda = PhysicsProcess::GetAVeryLargeValue();
if (getMacXsecPerProcessVect[i] > 0.) {
lambda = 1. / getMacXsecPerProcessVect[i] / geant::units::cm;
}
std::cout << std::setw(14) << std::scientific << std::right << lambda << std::setw(14) << std::left
<< " [cm]";
}
std::cout << std::endl;
std::cout << " mean free path (g/cm2) :";
for (size_t i = 0; i < processNameVect.size(); ++i) {
double lambda = PhysicsProcess::GetAVeryLargeValue();
if (getMacXsecPerProcessVect[i] > 0.) {
lambda = getMacXsecPerProcessVect[i] / density / (1. / geant::units::cm);
lambda = 1. / lambda;
}
std::cout << std::setw(14) << std::scientific << std::right << lambda << std::setw(14) << std::left
<< " [g/cm2]";
}
std::cout << std::endl;
std::cout << std::endl;
std::cout << " ================================================================================ " << std::endl
<< std::endl;
// this portion is for the secondary parameters (angle and energy distribution)
double xMin = 0.0;
double xMax = 180.0; //
Hist *hisAng = new Hist(xMin, xMax, numHistBins1);
xMin = 0.0;
xMax = 150; //
Hist *hisEne = new Hist(xMin, xMax, numHistBins2);
xMin = 0.0;
xMax = 20; //
Hist *hisSec = new Hist(xMin, xMax, numHistBins3);
// one can test models one by one (keep only one active model and comment others)
// geantphysics::HadronicFinalStateModel *nudyModel = new geantphysics::NeutronNudyElasticModel();
// geantphysics::HadronicFinalStateModel *nudyModel = new geantphysics::NeutronNudyFissionModel();
geantphysics::HadronicFinalStateModel *nudyModel = new geantphysics::NeutronNudyInelasticModel();
Isotope *isotope = Isotope::GetIsotope(Z, N);
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Model name = " << nudyModel->GetName() << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Sampling is running for : " << numSamples << " neutrons" << std::endl;
// call sampling method
double timeInSec =
sampleDistribution(numSamples, kineticEnergy, matCut, isotope, particle, nudyModel, hisAng, hisEne, hisSec);
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
std::cout << " Time of sampling = " << timeInSec << " [s]" << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
// print out histogram to file: fileName
char fileName[512];
sprintf(fileName, "nudy_%s_ang", (isotope->GetName()).c_str());
FILE *f = fopen(fileName, "w");
double norm = 1. / numSamples;
Hist *histo = hisAng;
for (int i = 0; i < histo->GetNumBins(); ++i) {
fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm);
}
delete histo;
fclose(f);
sprintf(fileName, "nudy_%s_ene", (isotope->GetName()).c_str());
f = fopen(fileName, "w");
norm = 1. / numSamples;
histo = hisEne;
for (int i = 0; i < histo->GetNumBins(); ++i) {
fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm);
}
delete histo;
fclose(f);
sprintf(fileName, "nudy_%s_Sec", (isotope->GetName()).c_str());
f = fopen(fileName, "w");
norm = 1. / numSamples;
histo = hisSec;
for (int i = 0; i < histo->GetNumBins(); ++i) {
fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm);
}
delete histo;
fclose(f);
//
std::cout << " Histogram is written into files ................................................" << std::endl;
std::cout << " -------------------------------------------------------------------------------- " << std::endl;
// end
std::cout << " ================================================================================ " << std::endl
<< std::endl;
delete nudyModel;
return 0;
}
double sampleDistribution(double numSamples, double primaryEnergy, const MaterialCuts *matCut, Isotope *isotope,
Particle *particle, HadronicFinalStateModel *nudyModel, Hist *h1, Hist *h2, Hist *h3)
{
double ekin = primaryEnergy;
double dirx = 0.0; // direction
double diry = 0.0;
double dirz = 1.0;
int gvcode = particle->GetInternalCode(); // internal code of the primary particle i.e. n
double mass = particle->GetPDGMass();
// Set up a dummy geant::TaskData and its geantphysics::PhysicsData member: they are needed in the final state
// sampling
geant::TaskData *td = new geant::TaskData(1, 1);
PhysicsData *phd = new PhysicsData();
td->fPhysicsData = phd;
// Set up a the primary light track for brem.
LightTrack primaryLT;
// init time
clock_t start_time = clock();
for (long int i = 0; i < numSamples; ++i) {
// we will use members:
// fMaterialCutCoupleIndex <==> // current MaterialCuts index
// fKinE <==> fE-fMass // kinetic energy; will be set to the new kinetic energy
// fGVcode <==> fGVcode // internal particle code
primaryLT.SetMaterialCutCoupleIndex(matCut->GetIndex());
primaryLT.SetKinE(ekin);
primaryLT.SetGVcode(gvcode);
primaryLT.SetDirX(dirx);
primaryLT.SetDirY(diry);
primaryLT.SetDirZ(dirz);
primaryLT.SetMass(mass);
// clean the number of secondary tracks used (in PhysicsData)
td->fPhysicsData->ClearSecondaries();
//
// invoke the interaction
int numSecs = nudyModel->SampleFinalState(primaryLT, isotope, td);
if (numSecs > 0) {
LightTrack *secondaryLT = td->fPhysicsData->GetListOfSecondaries();
for (int iSec = 0; iSec != numSecs; ++iSec) {
h1->Fill(std::acos(secondaryLT[iSec].GetDirZ()) / geant::units::deg);
h2->Fill(secondaryLT[iSec].GetKinE() / geant::units::MeV);
}
} else {
h1->Fill(std::acos(primaryLT.GetDirZ()) / geant::units::deg);
h2->Fill(primaryLT.GetKinE() / geant::units::MeV);
}
h3->Fill(numSecs);
}
clock_t end_time = clock();
return (end_time - start_time) / (double(CLOCKS_PER_SEC));
}
void help()
{
std::cout << "\n " << std::setw(120) << std::setfill('=') << "" << std::setfill(' ') << std::endl;
std::cout << " TestNudy0 GeantV application for testing integrated physics quantities" << std::endl;
std::cout << " and sampling secondary angle and energy using a given user physics-list" << std::endl;
std::cout << "\n Usage: TestNudy0_GV [OPTIONS] \n" << std::endl;
for (int i = 0; options[i].name != NULL; i++) {
printf("\t-%c --%s\n", options[i].val, options[i].name);
}
std::cout << "\n " << std::setw(120) << std::setfill('=') << "" << std::setfill(' ') << std::endl;
}
| 43.577413 | 120 | 0.607967 | [
"geometry",
"vector",
"model"
] |
73051044526d033d1bd66c0b0d538ec5cf4813ce | 9,341 | cpp | C++ | Multicomb/Multicomb.cpp | ccdarabundit/chugins | c6f5457f40fc9898f1e9bc8632974981a32a77e6 | [
"MIT"
] | 79 | 2015-01-10T01:26:09.000Z | 2021-10-19T03:04:37.000Z | Multicomb/Multicomb.cpp | ccdarabundit/chugins | c6f5457f40fc9898f1e9bc8632974981a32a77e6 | [
"MIT"
] | 33 | 2015-03-31T02:38:36.000Z | 2021-07-20T19:12:57.000Z | Multicomb/Multicomb.cpp | ccdarabundit/chugins | c6f5457f40fc9898f1e9bc8632974981a32a77e6 | [
"MIT"
] | 41 | 2015-02-21T02:11:17.000Z | 2022-03-21T20:11:22.000Z | //-----------------------------------------------------------------------------
// Entaro ChucK Developer!
// This is a Chugin boilerplate, generated by chuginate!
//-----------------------------------------------------------------------------
// this should align with the correct versions of these ChucK files
#include "chuck_dl.h"
#include "chuck_def.h"
#include "ulib_math.h"
#include "Ocomb.h"
#define NCOMBS 5
#define DEF_MINFREQ 220
#define DEF_MAXFREQ 880
#define DEF_REVTIME 1
// general includes
#include <stdio.h>
#include <limits.h>
#ifdef _MSC_VER
static long random() { return rand(); }
static void srandom( unsigned s ) { srand( s ); }
#endif // _MSC_VER
CK_DLL_CTOR(multicomb_ctor);
CK_DLL_DTOR(multicomb_dtor);
CK_DLL_TICKF(multicomb_tickf);
CK_DLL_MFUN(multicomb_setNum);
CK_DLL_MFUN(multicomb_setMinfreq);
CK_DLL_MFUN(multicomb_setMaxfreq);
CK_DLL_MFUN(multicomb_setRange);
CK_DLL_MFUN(multicomb_setRevtime);
CK_DLL_MFUN(multicomb_getNum);
CK_DLL_MFUN(multicomb_getMinfreq);
CK_DLL_MFUN(multicomb_getMaxfreq);
CK_DLL_MFUN(multicomb_getRevtime);
t_CKINT multicomb_data_offset = 0;
// class definition for internal Chugin data
class Multicomb
{
public:
Multicomb( t_CKFLOAT fs)
{
_srate = fs;
_num = NCOMBS;
_minfreq = DEF_MINFREQ;
_maxfreq = DEF_MAXFREQ;
_revtime = DEF_REVTIME;
_spread = new float[_num];
_delsamps = new int[_num];
_comb = new Ocomb*[_num];
for (int i=0; i< _num; i++)
{
_spread[i] = (float) i / (float) (_num-1);
float cfreq = rand2f(_minfreq,_maxfreq);
float loopt = 1.0 / cfreq;
_delsamps[i] = (int) (loopt * _srate + 0.5);
_comb[i] = new Ocomb(_srate, loopt, _revtime);
if (_comb[i]->frequency() == 0.0)
printf("Multicomb error: comb delay allocation delay failed.\n");
}
}
~Multicomb()
{
delete [] _spread;
delete [] _delsamps;
for (int i=0; i<_num; i++)
{
delete _comb[i];
}
delete [] _comb;
}
void tickf( SAMPLE* in, SAMPLE* out, int nframes)
{
memset (out, 0, sizeof(SAMPLE)*nframes);
out[0] = out[1] = 0.0;
for (int i=0; i<_num; i++)
{
float sig = _comb[i]->next(in[0],_delsamps[i]);
out[0] += sig * _spread[i];
out[1] += sig * (1.0 - _spread[i]);
}
}
t_CKDUR setRevtime ( t_CKDUR p)
{
_revtime = (p/_srate);
for (int i=0; i<_num; i++)
_comb[i]->setReverbTime(_revtime);
return p;
}
void setRange ( t_CKFLOAT lo, t_CKFLOAT hi )
{
_minfreq = lo;
_maxfreq = hi;
for (int i=0; i< _num; i++)
{
float cfreq = rand2f(_minfreq,_maxfreq);
float loopt = 1.0 / cfreq;
_delsamps[i] = (int) (loopt * _srate + 0.5);
_comb[i] = new Ocomb(_srate, loopt, _revtime);
if (_comb[i]->frequency() == 0.0)
printf("Multicomb error: comb delay allocation delay failed.\n");
}
}
float setMinfreq ( t_CKFLOAT p )
{
_minfreq = p;
for (int i=0; i< _num; i++)
{
float cfreq = rand2f(_minfreq,_maxfreq);
float loopt = 1.0 / cfreq;
_delsamps[i] = (int) (loopt * _srate + 0.5);
_comb[i] = new Ocomb(_srate, loopt, _revtime);
if (_comb[i]->frequency() == 0.0)
printf("Multicomb error: comb delay allocation delay failed.\n");
}
return p;
}
float setMaxfreq ( t_CKFLOAT p )
{
_maxfreq = p;
for (int i=0; i< _num; i++)
{
float cfreq = rand2f(_minfreq,_maxfreq);
float loopt = 1.0 / cfreq;
_delsamps[i] = (int) (loopt * _srate + 0.5);
_comb[i] = new Ocomb(_srate, loopt, _revtime);
if (_comb[i]->frequency() == 0.0)
printf("Multicomb error: comb delay allocation delay failed.\n");
}
return p;
}
int setNum ( t_CKINT p )
{
delete [] _spread;
delete [] _delsamps;
for (int i=0; i<_num; i++)
{
delete _comb[i];
}
delete [] _comb;
if (p>0) _num = p;
_spread = new float[_num];
_delsamps = new int[_num];
_comb = new Ocomb*[_num];
for (int i=0; i< _num; i++)
{
_spread[i] = (float) i / (float) (_num-1);
float cfreq = rand2f(_minfreq,_maxfreq);
float loopt = 1.0 / cfreq;
_delsamps[i] = (int) (loopt * _srate + 0.5);
_comb[i] = new Ocomb(_srate, loopt, _revtime);
if (_comb[i]->frequency() == 0.0)
printf("Multicomb error: comb delay allocation delay failed.\n");
}
return _num;
}
int getNum() { return _num; }
float getMinfreq() { return _minfreq; }
float getMaxfreq() { return _maxfreq; }
t_CKDUR getRevtime() { return _revtime * _srate; }
private:
float rand2f (float min, float max)
{
return min + (max-min)*(::random()/(t_CKFLOAT)CK_RANDOM_MAX);
}
unsigned int _num;
float _srate;
Ocomb **_comb;
int *_delsamps;
float *_spread;
float _minfreq, _maxfreq;
float _revtime;
float m_param;
};
// query function: chuck calls this when loading the Chugin
// NOTE: developer will need to modify this function to
// add additional functions to this Chugin
CK_DLL_QUERY( Multicomb )
{
// hmm, don't change this...
QUERY->setname(QUERY, "Multicomb");
// begin the class definition
// can change the second argument to extend a different ChucK class
QUERY->begin_class(QUERY, "Multicomb", "UGen");
// register the constructor (probably no need to change)
QUERY->add_ctor(QUERY, multicomb_ctor);
// register the destructor (probably no need to change)
QUERY->add_dtor(QUERY, multicomb_dtor);
// for UGen's only: add tickf function
QUERY->add_ugen_funcf(QUERY, multicomb_tickf, NULL, 2, 2);
// NOTE: if this is to be a UGen with more than 1 channel,
// e.g., a multichannel UGen -- will need to use add_ugen_funcf()
// and declare a tickf function using CK_DLL_TICKF
QUERY->add_mfun(QUERY, multicomb_setNum, "int", "num");
QUERY->add_arg(QUERY, "int", "num");
QUERY->add_mfun(QUERY, multicomb_setMinfreq, "float", "minfreq");
QUERY->add_arg(QUERY, "float", "minfreq");
QUERY->add_mfun(QUERY, multicomb_setMaxfreq, "float", "maxfreq");
QUERY->add_arg(QUERY, "float", "maxfreq");
QUERY->add_mfun(QUERY, multicomb_setRange, "void", "set");
QUERY->add_arg(QUERY, "float", "minfreq");
QUERY->add_arg(QUERY, "float", "maxfreq");
QUERY->add_mfun(QUERY, multicomb_setRevtime, "dur", "revtime");
QUERY->add_arg(QUERY, "dur", "revtime");
// example of adding getter method
QUERY->add_mfun(QUERY, multicomb_getNum, "int", "num");
QUERY->add_mfun(QUERY, multicomb_getMinfreq, "float", "minfreq");
QUERY->add_mfun(QUERY, multicomb_getMaxfreq, "float", "maxfreq");
QUERY->add_mfun(QUERY, multicomb_getRevtime, "dur", "revtime");
// this reserves a variable in the ChucK internal class to store
// referene to the c++ class we defined above
multicomb_data_offset = QUERY->add_mvar(QUERY, "int", "@m_data", false);
// end the class definition
// IMPORTANT: this MUST be called!
QUERY->end_class(QUERY);
// wasn't that a breeze?
return TRUE;
}
// implementation for the constructor
CK_DLL_CTOR(multicomb_ctor)
{
// get the offset where we'll store our internal c++ class pointer
OBJ_MEMBER_INT(SELF, multicomb_data_offset) = 0;
// instantiate our internal c++ class representation
Multicomb * bcdata = new Multicomb(API->vm->get_srate(API, SHRED));
// store the pointer in the ChucK object member
OBJ_MEMBER_INT(SELF, multicomb_data_offset) = (t_CKINT) bcdata;
}
// implementation for the destructor
CK_DLL_DTOR(multicomb_dtor)
{
// get our c++ class pointer
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
// check it
if( bcdata )
{
// clean up
delete bcdata;
OBJ_MEMBER_INT(SELF, multicomb_data_offset) = 0;
bcdata = NULL;
}
}
CK_DLL_TICKF(multicomb_tickf)
{
Multicomb * c = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
if(c) c->tickf(in,out, nframes);
return TRUE;
}
CK_DLL_MFUN(multicomb_setNum)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_int = bcdata->setNum(GET_NEXT_INT(ARGS));
}
CK_DLL_MFUN(multicomb_setMinfreq)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_float = bcdata->setMinfreq(GET_NEXT_FLOAT(ARGS));
}
CK_DLL_MFUN(multicomb_setMaxfreq)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_float = bcdata->setMaxfreq(GET_NEXT_FLOAT(ARGS));
}
CK_DLL_MFUN(multicomb_setRange)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
float high = GET_NEXT_FLOAT(ARGS);
float low = GET_NEXT_FLOAT(ARGS);
bcdata->setRange(low,high);
}
CK_DLL_MFUN(multicomb_setRevtime)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_dur = bcdata->setRevtime(GET_NEXT_DUR(ARGS));
}
// Get methods
CK_DLL_MFUN(multicomb_getNum)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_int = bcdata->getNum();
}
CK_DLL_MFUN(multicomb_getMinfreq)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_float = bcdata->getMinfreq();
}
CK_DLL_MFUN(multicomb_getMaxfreq)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_float = bcdata->getMaxfreq();
}
CK_DLL_MFUN(multicomb_getRevtime)
{
Multicomb * bcdata = (Multicomb *) OBJ_MEMBER_INT(SELF, multicomb_data_offset);
RETURN->v_dur = bcdata->getRevtime();
}
| 27.233236 | 81 | 0.666738 | [
"object"
] |
730ca94fd70afc6550ef33170f9ce35c9b2d470f | 12,095 | hpp | C++ | Function.hpp | hxmhuang/OpenArray_Dev | 863866a6b7accf21fa253567b0e66143c7506cdf | [
"MIT"
] | 3 | 2020-09-08T05:01:56.000Z | 2020-11-23T13:11:25.000Z | Function.hpp | hxmhuang/OpenArray_Dev | 863866a6b7accf21fa253567b0e66143c7506cdf | [
"MIT"
] | null | null | null | Function.hpp | hxmhuang/OpenArray_Dev | 863866a6b7accf21fa253567b0e66143c7506cdf | [
"MIT"
] | 2 | 2019-08-16T08:32:30.000Z | 2020-02-10T08:44:04.000Z | /*
* Function.hpp
* some basic functions in OpenArray
*
=======================================================*/
#ifndef __FUNCTION_HPP__
#define __FUNCTION_HPP__
#include "common.hpp"
#include "Internal.hpp"
#include "ArrayPool.hpp"
#include "utils/utils.hpp"
namespace oa {
namespace funcs {
//create an array with const val
template <typename T>
ArrayPtr consts(MPI_Comm comm, const Shape& s, T val, int stencil_width = 1) {
int data_type = oa::utils::to_type<T>();
ArrayPtr ap = ArrayPool::global()->get(comm, s, stencil_width, data_type);
Box box = ap->get_local_box();
int size = box.size_with_stencil(stencil_width);
oa::internal::set_buffer_consts((T*)ap->get_buffer(), size, val);
return ap;
}
//create an array with const val
template <typename T>
ArrayPtr consts(MPI_Comm comm, const vector<int>& x, const vector<int>& y,
const vector<int>&z, T val, int stencil_width = 1) {
int data_type = oa::utils::to_type<T>();
ArrayPtr ap = ArrayPool::global()->get(comm, x, y, z, stencil_width, data_type);
Box box = ap->get_local_box();
int size = box.size_with_stencil(stencil_width);
oa::internal::set_buffer_consts((T*)ap->get_buffer(), size, val);
return ap;
}
// create a ones array
ArrayPtr ones(MPI_Comm comm, const Shape& s,
int stencil_width = 1, int data_type = DATA_INT);
// create a zeros array
ArrayPtr zeros(MPI_Comm comm, const Shape& s,
int stencil_width = 1, int data_type = DATA_INT);
// create a rand array
ArrayPtr rands(MPI_Comm comm, const Shape& s,
int stencil_width = 1, int data_type = DATA_INT);
// create a seqs array
ArrayPtr seqs(MPI_Comm comm, const Shape& s,
int stencil_width = 1, int data_type = DATA_INT);
ArrayPtr seqs(MPI_Comm comm, const vector<int> &x, const vector<int> &y,
const vector<int> &z, int stencil_width = 1, int data_type = DATA_INT);
// according to partiton pp, transfer src to A
// A = transfer(src, pp)
ArrayPtr transfer(const ArrayPtr &src, const PartitionPtr &pp);
template <typename T>
void local_sub(const ArrayPtr &ap, int x, int y, int z, T* val) {
Box b(x, x+1, y, y+1, z, z+1);
Box local_box = ap->get_local_box();
int sw = ap->get_stencil_width();
x -= local_box.xs();
y -= local_box.ys();
z -= local_box.zs();
switch(ap->get_data_type()) {
case DATA_INT:
*val = oa::internal::get_buffer_local_sub((int*)ap->get_buffer(),
local_box, x, y, z, sw);
break;
case DATA_FLOAT:
*val = oa::internal::get_buffer_local_sub((float*)ap->get_buffer(),
local_box, x, y, z, sw);
break;
case DATA_DOUBLE:
*val = oa::internal::get_buffer_local_sub((double*)ap->get_buffer(),
local_box, x, y, z, sw);
break;
}
}
template <typename T>
void set_local(const ArrayPtr &ap, int x, int y, int z, T val) {
Box b(x, x+1, y, y+1, z, z+1);
Box local_box = ap->get_local_box();
int sw = ap->get_stencil_width();
x -= local_box.xs();
y -= local_box.ys();
z -= local_box.zs();
switch(ap->get_data_type()) {
case DATA_INT:
oa::internal::set_buffer_local((int*)ap->get_buffer(),
local_box, x, y, z, (int)val, sw);
break;
case DATA_FLOAT:
oa::internal::set_buffer_local((float*)ap->get_buffer(),
local_box, x, y, z, (float)val, sw);
break;
case DATA_DOUBLE:
oa::internal::set_buffer_local((double*)ap->get_buffer(),
local_box, x, y, z, (double)val, sw);
break;
}
}
// get a sub Array based on Box b
ArrayPtr subarray(const ArrayPtr &ap, const Box &box);
void update_ghost(ArrayPtr ap);
/*
* update boundary, direction = -1, all dimension
* direction = 0, dimension x
* direction = 1, dimension y
* direction = 2, dimension z
*/
void update_ghost_start(ArrayPtr ap, vector<MPI_Request> &reqs, int direction = -1,
int3 lb = {{0,0,0}}, int3 rb = {{0,0,0}});
void update_ghost_end(vector<MPI_Request> &reqs);
void set_ghost_zeros(ArrayPtr ap);
void set_boundary_zeros(ArrayPtr &ap, int3 lb, int3 rb);
void set_boundary_zeros(ArrayPtr &ap, Box sub_box);
//inline int calc_id(int i, int j, int k, int3 S);
void calc_inside(ArrayPtr &ap, ArrayPtr &A, int3 lbound, int3 rbound);
void calc_outside(ArrayPtr &ap, ArrayPtr &B, int3 lbound, int3 rbound);
// convert a mpi array to sequential array
template<class T>
bool is_equal(const ArrayPtr& A, const arma::Cube<T>& B){
assert(A->get_data_type() == oa::utils::dtype<T>::type);
//std::cout<<"is_seqs : " << A->is_seqs() << std::endl;
if (!A->is_seqs()) return false;
int A_size = A->size();
// std::cout<<"A_size : "<<A_size;
// std::cout<<"B_size : "<<arma::size(B)[0]
// * arma::size(B)[1] * arma::size(B)[2];
if (arma::size(B)[0]
* arma::size(B)[1]
* arma::size(B)[2] != A_size) {
return false;
}
T* A_buf = (T*)A->get_buffer();
T* B_buf = (T*)B.memptr();
for(int i = 0; i < A_size; ++ i) {
if(abs(A_buf[i] - B_buf[i]) > 1E-6) {
std::cout<<A_buf[i]<<std::endl;
std::cout<<B_buf[i]<<std::endl;
return false;
}
}
return true;
}
template<class T>
bool is_equal(const ArrayPtr& A, T B){
if (!A->is_seqs_scalar()) return false;
T* A_buf = (T*)A->get_buffer();
return *A_buf == B;
}
template<class T>
bool is_equal(const ArrayPtr& A, T* B){
if (!A->is_seqs()) return false;
///:for t in [['DATA_INT', 'int'],['DATA_FLOAT','float'],['DATA_DOUBLE','double']]
if(A->get_data_type() == ${t[0]}$){
${t[1]}$* A_buf = (${t[1]}$*)A->get_buffer();
Shape s = A->buffer_shape();
const int sw = A->get_partition()->get_stencil_width();
int cnt = 0;
for(int k = sw; k < s[2] - sw; k++){
for(int j = sw; j < s[1] - sw; j++){
for(int i = sw; i < s[0] - sw; i++){
if(abs(int(A_buf[i + j * s[0] + k * s[0] * s[1]]) - int(B[cnt])) > 1E-6){
std::cout<<"compare: "
<<int(A_buf[i + j * s[0] + k * s[0] * s[1]])
<<" "
<<int(B[cnt])
<<std::endl;
return false;
}
cnt ++;
}
}
}
}
///:endfor
return true;
}
bool is_equal(const ArrayPtr& A, const ArrayPtr& B);
template<class T>
ArrayPtr get_seq_scalar(T val) {
return consts<T>(MPI_COMM_SELF,SCALAR_SHAPE, val, 0);
}
template<class T>
ArrayPtr get_seq_array(T* val, const Shape& s){
ArrayPtr a = consts<T>(MPI_COMM_SELF, s, 0, 0);
const int size = s[0] * s[1] * s[2];
oa::internal::copy_buffer((T*)a->get_buffer(), val, size);
return a;
}
// set sub(A) = B
void set(ArrayPtr& A, const Box& A_box, const ArrayPtr& B);
// set sub(A) = sub(B)
void set(ArrayPtr& A, const Box& box_a,
const ArrayPtr& B, const Box& box_b);
// set sub(A) = const
template<typename T>
void set_ref_const(ArrayPtr& A, const Box& A_box, T val) {
// sub(A)'s partition
vector<int> rsx, rsy, rsz;
PartitionPtr pp = A->get_partition();
Shape ps = pp->procs_shape();
pp->split_box_procs(A_box, rsx, rsy, rsz);
vector<int> x(ps[0], 0), y(ps[1], 0), z(ps[2], 0);
for (int i = 0; i < rsx.size(); i += 3)
x[rsx[i + 2]] = rsx[i + 1] - rsx[i];
for (int i = 0; i < rsy.size(); i += 3)
y[rsy[i + 2]] = rsy[i + 1] - rsy[i];
for (int i = 0; i < rsz.size(); i += 3)
z[rsz[i + 2]] = rsz[i + 1] - rsz[i];
int rk = pp->rank();
vector<int> procs_coord = pp->get_procs_3d(rk);
int idx = procs_coord[0] - rsx[2];
int idy = procs_coord[1] - rsy[2];
int idz = procs_coord[2] - rsz[2];
// check whether there is local data in process
if (x[procs_coord[0]] * y[procs_coord[1]] * z[procs_coord[2]] == 0) return ;
Box box = A->get_local_box();
Box sub_box(rsx[idx * 3], rsx[idx * 3 + 1],
rsy[idy * 3], rsy[idy * 3 + 1],
rsz[idz * 3], rsz[idz * 3 + 1]);
///:for i in ['int', 'float', 'double']
if (A->get_data_type() == DATA_${i.upper()}$) {
oa::internal::set_buffer_subarray_const<${i}$, T>(
(${i}$*) A->get_buffer(),
val,
box,
sub_box,
pp->get_stencil_width()
);
}
///:endfor
}
ArrayPtr l2g(ArrayPtr& lap);
ArrayPtr g2l(ArrayPtr& gap);
// sub(A) = B (MPI_COMM_SELF)
void set_l2g(ArrayPtr& A, const Box& A_box, ArrayPtr& B);
// local_A (MPI_COMM_SELF)= sub(global_B)
void set_g2l(ArrayPtr& local, const Box& sub_box, ArrayPtr& global);
void set_with_mask(ArrayPtr& A, const Box& sub_box, const ArrayPtr& B, const ArrayPtr& mask);
void set_with_mask(ArrayPtr& A, const ArrayPtr& B, const ArrayPtr& mask);
// rep arry_B = rep_A(arryA, 1, 2, 3)
ArrayPtr rep(ArrayPtr& A, int x, int y, int z);
//ArrayPtr create_local_array(const Shape& gs, DataType dt);
template<class T>
ArrayPtr create_local_array(const Shape& gs, T* buf){
int sw = Partition::get_default_stencil_width();
DataType dt = oa::utils::to_type<T>();
ArrayPtr ap = zeros(MPI_COMM_SELF, gs, sw, dt);
T* dst_buf = (T*)ap->get_buffer();
const int xs = 0;
const int xe = gs[0] + 2 * sw;
const int ys = 0;
const int ye = gs[1] + 2 * sw;
const int zs = 0;
const int ze = gs[2] + 2 * sw;
const int M = xe;
const int N = ye;
const int P = ze;
for(int k = zs + sw; k < ze - sw; k++){
for(int j = ys + sw; j < ye - sw; j++){
for(int i = xs + sw; i < xe - sw; i++){
dst_buf[i+j*M+k*M*N] =
buf[i-sw + (j-sw) * gs[0] + (k-sw)*gs[0]*gs[1]];
}
}
}
return ap;
}
template<class T>
void set(ArrayPtr& A, const Box& ref_box,
T* buf, Shape& buf_shape){
int num = buf_shape[0] * buf_shape[1] * buf_shape[2];
for(int i = 0; i < num; ++i){
std::cout<<" "<< buf[i] << " ";
}
assert(ref_box.shape() == buf_shape);
Box local_box = A->get_local_box();
Box local_ref_box = local_box.get_intersection(ref_box);
int3 offset_local =
local_ref_box.starts() - local_box.starts();
int x1 = offset_local[0];
int y1 = offset_local[1];
int z1 = offset_local[2];
int3 offset_ref =
local_ref_box.starts() - ref_box.starts();
int x2 = offset_ref[0];
int y2 = offset_ref[1];
int z2 = offset_ref[2];
Shape slr = local_ref_box.shape();
int M = slr[0];
int N = slr[1];
int P = slr[2];
Shape bs = A->buffer_shape();
const int sw = A->get_partition()->get_stencil_width();
void* dst_buf = A->get_buffer();
switch(A->get_data_type()){
///:for t in ['int', 'float', 'double']
case (DATA_${t.upper()}$):
for(int k = 0; k < P; ++k){
for(int j = 0; j < N; ++j){
for(int i = 0; i < M; ++i){
int idx1 = (i + sw + x1) +
(j + sw + y1) * bs[0] +
(k + sw + z1) * bs[0] * bs[1];
int idx2 = (i + x2) +
(j + y2) * buf_shape[0] +
(k + z2) * buf_shape[0] * buf_shape[1];
((${t}$*)dst_buf)[idx1] = buf[idx2];
}
}
}
break;
///:endfor
}
}
ArrayPtr make_psudo3d(const ArrayPtr& B);
}
}
#endif
| 30.465995 | 97 | 0.528483 | [
"shape",
"vector"
] |
730d107005e15a3ffe3a894edfa14b2c8080885b | 3,996 | hpp | C++ | bitmatrix/bitmatrix.hpp | xixicat/argmat-clpb | eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58 | [
"MIT"
] | 3 | 2016-01-09T21:48:21.000Z | 2018-12-28T05:52:14.000Z | bitmatrix/bitmatrix.hpp | xixicat/argmat-clpb | eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58 | [
"MIT"
] | null | null | null | bitmatrix/bitmatrix.hpp | xixicat/argmat-clpb | eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58 | [
"MIT"
] | null | null | null | #ifndef BIT_MATRIX_HPP
#define BIT_MATRIX_HPP
#include <assert.h>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <vector>
#include <iostream>
#include <boost/dynamic_bitset/dynamic_bitset.hpp>
#include "config/config.hpp"
#include "bitvector.hpp"
#include <utility>
namespace argumatrix { // argumatrix
using namespace std;
class bitmatrix{
public:
// constructors
bitmatrix(size_type num_size);
bitmatrix(size_type num_rows, size_type num_columns);
// copy constructor
bitmatrix(const bitmatrix& _bm);
bitmatrix(): m_nRow(0), m_nColumn(0) {} // default constructor
void show();
bitvector& operator[](size_type pos);
const bitvector& operator[](size_type pos) const { return m_bitData[pos]; }
//const bitvector& operator[](const size_type pos);
bitvector operator*(const bitvector& _bv);
bitmatrix operator*(const bitmatrix& _bm);
bitmatrix operator=(const bitmatrix& _bm);
// set the row bitvector of bitmatrix at pos with _bv
void setBitvector(const bitvector& _bv, size_type pos);
// get a copy of the row bitvector of bitmatrix at pos
bitvector getBitvector(size_type pos);
bitmatrix transpose() const;
size_type sizeR() const { return m_nRow; }
size_type sizeC() const { return m_nColumn; }
void push_back(bitvector& _bv);
/**
* Get the diagonal elements of a bitmatrix
* @return the bitvector of the diagonal elements
*/
bitvector diag();
private:
size_type m_nRow;
size_type m_nColumn;
std::vector< bitvector > m_bitData;
};
bitmatrix::bitmatrix(size_type num_rows, size_type num_columns )
:m_nRow(num_rows),
m_nColumn(num_columns)
{
m_bitData.resize(m_nRow);
for(size_type i=0; i < m_nRow; i++){
m_bitData[i].resize(m_nColumn, false);
}
}
bitmatrix::bitmatrix(size_type num_size)
:m_nRow(num_size),
m_nColumn(num_size)
{
m_bitData.resize(m_nRow);
for(size_type i=0; i < m_nRow; i++){
m_bitData[i].resize(m_nColumn, false);
}
}
bitmatrix::bitmatrix(const bitmatrix& _bm)
{
m_nRow = _bm.m_nRow;
m_nColumn = _bm.m_nColumn;
m_bitData = _bm.m_bitData;
}
void bitmatrix::show(){
for(size_type i=0; i<m_nRow; i++){
std::cout<< m_bitData[i] << std::endl;
}
}
bitvector& bitmatrix::operator[](size_type pos) {
return m_bitData[pos];
}
bitvector bitmatrix::operator*(const bitvector& _bv){
assert(_bv.size()==m_nColumn);
bitvector bv1(_bv.size());
for(size_type i=0; i<m_nColumn; i++){
bv1[i] = m_bitData[i]*_bv;
}
return bv1;
}
bitmatrix bitmatrix::transpose() const {
assert(m_nColumn>0);
assert(m_nRow>0);
bitmatrix bm(m_nColumn, m_nRow);
for(size_type i=0; i<m_nColumn; i++){
for(size_type j=0; j<m_nRow; j++){
bm[i][j] = m_bitData[j][i];
}
}
return bm;
}
bitmatrix bitmatrix::operator=(const bitmatrix& _bm){
m_nRow = _bm.m_nRow;
m_nColumn = _bm.m_nColumn;
m_bitData = _bm.m_bitData;
return *this;
}
bitmatrix bitmatrix::operator*(const bitmatrix& _bm_r){
assert( m_nColumn == _bm_r.m_nRow);
bitmatrix result_bm(m_nRow, _bm_r.m_nColumn);
bitmatrix _bm_r_t = _bm_r.transpose();
for(size_type i=0; i<m_nRow; i++){
for(size_type j=0; j<_bm_r_t.m_nRow; j++){
result_bm[i][j] = (m_bitData[i]*_bm_r_t.m_bitData[j]);
}
}
return result_bm;
}
void bitmatrix::setBitvector(const bitvector& _bv, size_type pos)
{
assert(pos >=0 && pos < m_nRow);
assert(m_nColumn == _bv.size());
m_bitData[pos] = _bv;
}
bitvector bitmatrix::getBitvector(size_type pos)
{
assert(pos >=0 && pos < m_nRow);
return m_bitData[pos];
}
void bitmatrix::push_back(bitvector& _bv)
{
// The _bv must none empty, i.e., _bv.size()>0
assert(!_bv.empty());
// if the bitmatrix is empty, _bv will be the first row of it
if (m_nRow == 0){
m_nColumn = _bv.size();
}
assert( _bv.size() == m_nColumn );
m_bitData.push_back(_bv);
++m_nRow;
}
bitvector bitmatrix::diag()
{
size_type _sz = min(m_nRow, m_nColumn);
bitvector _bv( _sz );
for (size_type i=0; i<_sz; i++)
_bv[i] = m_bitData[i][i];
return _bv;
}
} // namespace argumatrix
#endif
| 20.8125 | 76 | 0.69995 | [
"vector"
] |
7310f9b33654be21103ec67944894cb29adc63db | 4,162 | hpp | C++ | Tensile/Source/lib/include/Tensile/SingleSolutionLibrary.hpp | cgmb/Tensile | b0055f18fe76bcb1a9e5fd963b6b7f93aae85ee0 | [
"MIT"
] | 116 | 2017-06-29T08:52:55.000Z | 2022-03-25T03:01:43.000Z | Tensile/Source/lib/include/Tensile/SingleSolutionLibrary.hpp | cgmb/Tensile | b0055f18fe76bcb1a9e5fd963b6b7f93aae85ee0 | [
"MIT"
] | 431 | 2017-07-19T16:29:54.000Z | 2022-03-31T19:40:12.000Z | Tensile/Source/lib/include/Tensile/SingleSolutionLibrary.hpp | cgmb/Tensile | b0055f18fe76bcb1a9e5fd963b6b7f93aae85ee0 | [
"MIT"
] | 107 | 2017-10-14T01:38:41.000Z | 2022-03-07T08:49:09.000Z | /*******************************************************************************
*
* MIT License
*
* Copyright 2019-2020 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include <Tensile/Debug.hpp>
namespace Tensile
{
/**
* \ingroup SolutionLibrary
*
* Leaf of the tree. Represents a single `Solution` object. Can eliminate
* itself from consideration based on restrictions of that particular
* `Solution`.
*/
template <typename MyProblem, typename MySolution>
struct SingleSolutionLibrary : public SolutionLibrary<MyProblem, MySolution>
{
static std::string Type()
{
return "Single";
}
std::string type() const override
{
return Type();
}
std::string description() const override
{
std::string rv = type();
if(solution != nullptr)
{
rv += ": ";
rv += solution->name();
}
else
{
rv += " (nullptr)";
}
return rv;
}
std::shared_ptr<MySolution> solution;
SingleSolutionLibrary() = default;
SingleSolutionLibrary(std::shared_ptr<MySolution> s)
: solution(s)
{
}
virtual std::shared_ptr<MySolution> findBestSolution(MyProblem const& problem,
Hardware const& hardware,
double* fitness
= nullptr) const override
{
bool debug = Debug::Instance().printPredicateEvaluation();
if(solution)
{
if(debug)
{
solution->hardwarePredicate->debugEval(hardware, std::cout);
solution->problemPredicate->debugEval(problem, std::cout);
}
if((*solution->hardwarePredicate)(hardware)
&& (*solution->problemPredicate)(problem))
return solution;
}
else if(debug)
{
std::cout << " (empty library)";
}
return std::shared_ptr<MySolution>();
}
virtual SolutionSet<MySolution> findAllSolutions(MyProblem const& problem,
Hardware const& hardware) const override
{
auto result = this->findBestSolution(problem, hardware);
bool debug = Debug::Instance().printPredicateEvaluation();
if(debug)
{
if(result)
std::cout << " (match)";
else
std::cout << " (no match)";
}
if(result)
return SolutionSet<MySolution>({result});
return SolutionSet<MySolution>();
}
};
} // namespace Tensile
| 33.564516 | 98 | 0.528111 | [
"object"
] |
731656d6446cc50911f127a9847eb45c5fb7cd42 | 5,026 | cpp | C++ | src/maiken/mods.cpp | PhilipDeegan/mkn | 399dd01990e130c4deeb0c2800204836d3875ae9 | [
"BSD-3-Clause"
] | 3 | 2019-02-07T20:50:36.000Z | 2019-08-05T19:22:59.000Z | src/maiken/mods.cpp | mkn/mkn | a05b542497270def02200df6620804b89429259b | [
"BSD-3-Clause"
] | null | null | null | src/maiken/mods.cpp | mkn/mkn | a05b542497270def02200df6620804b89429259b | [
"BSD-3-Clause"
] | null | null | null | /**
Copyright (c) 2017, Philip Deegan.
All rights reserved.
Redistribution and use in source and binary forms, mod or modout
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 mod the
distribution.
* Neither the name of Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software modout specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "maiken.hpp"
#include "mkn/kul/bon.hpp"
void maiken::Application::modArgs(std::string const mod_str, std::vector<YAML::Node>& mod_nodes,
std::function<void(YAML::Node const&, const bool)> getIfMissing) {
if (mod_str.size()) {
mkn::kul::hash::set::String mods;
std::stringstream ss;
size_t lb = 0, rb = 0;
for (auto& c : mod_str) {
rb = c == '}' ? rb + 1 : rb;
lb = c == '{' ? lb + 1 : lb;
if ((c == ',' || c == ' ') && rb == lb) {
mods.insert(ss.str());
ss.str(std::string());
lb = rb = 0;
continue;
}
ss << c;
}
if (rb != lb) KEXIT(1, "Invalid -m - inconsistent {} brackets");
if (ss.str().size()) mods.insert(ss.str());
mod(mods, mod_nodes, getIfMissing);
}
}
void maiken::Application::mod(mkn::kul::hash::set::String& mods, std::vector<YAML::Node>& mod_nodes,
std::function<void(YAML::Node const&, const bool)> getIfMissing) {
for (auto mod : mods) {
mkn::kul::String::REPLACE_ALL(mod, mkn::kul::os::EOL(), "");
mkn::kul::String::TRIM(mod);
if (mod.empty()) continue;
mod_nodes.emplace_back();
auto& node = mod_nodes.back();
std::string local /*&*/, profiles, proj = mod, version /*#*/, scm, objs;
auto get_between = [&](auto& var, auto lbrak, auto rbrak) {
auto between = maiken::string::between_rm_str(proj, lbrak, rbrak);
if (between.found) proj = between.remaining, var = *between.found;
return !between.error;
};
if (!get_between(scm, "(", ")")) KEXIT(1, "Invalid -m - missing right ) bracket");
if (!node[STR_SCM]) node[STR_SCM] = scm;
if (!get_between(profiles, "[", "]")) KEXIT(1, "Invalid -m - missing right ] bracket");
mkn::kul::String::REPLACE_ALL(profiles, ",", " ");
if (!node[STR_PROFILE] && profiles.size()) node[STR_PROFILE] = profiles;
{
auto lbrak = proj.find("{"), rbrak = proj.rfind("}");
if (lbrak != std::string::npos) {
if (rbrak == std::string::npos) KEXIT(1, "Invalid -m - missing right } bracket");
objs = proj.substr(lbrak), proj = proj.substr(0, lbrak);
}
auto am = proj.find("&"), ha = proj.find("#");
if (proj == this->project().root()[STR_NAME].Scalar()) {
node[STR_LOCAL] = ".";
if (am != std::string::npos || ha != std::string::npos)
KEXIT(1,
"-m invalid, current project may not specify version or "
"location");
}
if (am != std::string::npos && ha != std::string::npos)
if (ha > am) KEXIT(1, "-m invalid, version must before location");
auto if_set = [&](auto s, auto& v, auto n) {
if (s != std::string::npos) v = proj.substr(s + 1), proj = proj.substr(0, s), n = v;
};
if_set(am, local, node[STR_LOCAL]);
if_set(ha, version, node[STR_VERSION]);
}
if (proj.empty() && local.empty() && scm.empty())
KEXIT(1, "-m invalid, project cannot be deduced");
if (!proj.empty()) {
if (scm.empty()) {
scm = proj;
node[STR_SCM] = scm;
}
proj = mkn::kul::String::SPLIT(proj, "/").back();
} else if (proj.empty() && !scm.empty()) {
proj = mkn::kul::String::SPLIT(scm, "/").back();
}
if (!proj.empty()) node[STR_NAME] = proj;
if (objs.size())
for (auto const n : mkn::kul::bon::from(objs))
for (auto const p : n) node[p.first] = p.second;
YAML::Emitter out;
out << node;
getIfMissing(node, 1);
}
}
| 38.96124 | 100 | 0.616793 | [
"vector"
] |
731a99650833c5dfb32bd0c91c119540ccfcbeed | 2,225 | cpp | C++ | BashuOJ-Code/4030.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/4030.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/4030.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
using namespace std;
const int MAXN=500005;
char a[MAXN],b[MAXN];
int prt[MAXN],ch[MAXN][30],len[MAXN],Max1[MAXN],Max2[MAXN],tong[MAXN],Top[MAXN];
int cnt,last,root,ans=-0x7fffffff;
inline int getint()
{
int num=0,bj=1;
char c=getchar();
while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar();
return num*bj;
}
inline int newnode(int val)
{
cnt++;
prt[cnt]=0;
len[cnt]=val;
memset(ch[cnt],0,sizeof(ch[cnt]));
return cnt;
}
void Insert(int x)
{
int p=last,now=newnode(len[last]+1);
last=now;//新建节点并更新last
for(;p&&!ch[p][x];p=prt[p])ch[p][x]=now;//给所有的存在节点添加新儿子now
if(!p)prt[now]=root;//此时的p为第一个节点,p为root直接加
else
{
int q=ch[p][x];
if(len[q]==len[p]+1)//p,q之间无中间点,q由p访问到
prt[now]=q;//对于now的prt,p与q点等效
else//p,q之间有中间点,不能直接访问到
{
int nq=newnode(len[p]+1);//建立一个q的等效节点nq
for(ri i=1;i<=26;i++)ch[nq][i]=ch[q][i];
prt[nq]=prt[q];
prt[now]=prt[q]=nq;//转移并更新q与nq之间的关系
for(;p&&ch[p][x]==q;p=prt[p])ch[p][x]=nq;//更新p与nq之间的关系
}
}
}
void Build(char *s)
{
last=root=newnode(0);
int n=strlen(s+1);
for(ri i=1;i<=n;i++)Insert(int(s[i]-96));
}
int match(char *s)
{
int n=strlen(s+1);
int ans=0,slen=0,p=root;
for(ri i=1;i<=n;i++)
{
int x=int(s[i]-96);
if(ch[p][x])p=ch[p][x],slen++;
else
{
while(p&&!ch[p][x])p=prt[p];
if(!p)slen=0,p=root;
else slen=len[p]+1,p=ch[p][x];
}
Max2[p]=max(Max2[p],slen);
}
return ans;
}
int main()
{
scanf("%s",a+1);
Build(a);
for(ri i=1;i<=cnt;i++)Max1[i]=len[i];
for(ri i=1;i<=cnt;i++)tong[len[i]]++;
for(ri i=1;i<=cnt;i++)tong[i]+=tong[i-1];
for(ri i=1;i<=cnt;i++)Top[tong[len[i]]--]=i;
//基数排序作为一种优秀的拓扑排序的方法,使得满足一个自底而上的更新顺序
while(~scanf("%s",b+1))
{
match(b);
for(ri i=cnt;i>=1;i--)
{
int x=Top[i];//取出拓扑序
if(Max2[x]<Max1[x])Max1[x]=Max2[x];//用Max1[]存储最终答案,有妙用
if(prt[x]&&Max2[prt[x]]<Max2[x])Max2[prt[x]]=Max2[x];//存在父亲,Max2[]并未存储答案且满足拓扑序,向上迭代
Max2[x]=0;//对Max2[]清零,为下一次排序做准备
}
}
for(ri i=1;i<=cnt;i++)ans=max(ans,Max1[i]);//所有点求最大值
printf("%d",ans);
return 0;
}
| 21.813725 | 86 | 0.599101 | [
"vector"
] |
731efb02239ea0c9734bcb24c1a32cd806c1dece | 29,978 | tpp | C++ | src/mafCore/mafTree.tpp | tartarini/MAF3 | f9614d36591754544b23e3a670980799254dfd2c | [
"Apache-2.0"
] | 1 | 2021-05-10T19:01:48.000Z | 2021-05-10T19:01:48.000Z | src/mafCore/mafTree.tpp | examyes/MAF3 | f9614d36591754544b23e3a670980799254dfd2c | [
"Apache-2.0"
] | null | null | null | src/mafCore/mafTree.tpp | examyes/MAF3 | f9614d36591754544b23e3a670980799254dfd2c | [
"Apache-2.0"
] | 1 | 2018-02-06T03:51:57.000Z | 2018-02-06T03:51:57.000Z | ////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004-2009
// License: BSD License, see ../docs/license.html
////////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <algorithm>
namespace mafCore
{
////////////////////////////////////////////////////////////////////////////////
// mafTreeNode
template<typename T>
class mafTreeNode
{
public:
master_iterator<mafTree<T>, mafTreeNode<T> > m_master;
T m_data;
mafTreeNode<T>* m_parent;
std::vector<mafTreeNode<T>*> m_children;
public:
mafTreeNode(const mafTree<T>* owner, const T& data = T()) :
m_master(owner,this), m_data(data), m_parent(0)
{
}
void change_owner(const mafTree<T>* owner)
{
m_master.change_owner(owner);
for (TYPENAME std::vector<mafTreeNode<T>*>::iterator i = m_children.begin(); i != m_children.end(); ++i)
(*i)->change_owner(owner);
}
~mafTreeNode(void)
{
m_parent = 0;
for (TYPENAME std::vector<mafTreeNode<T>*>::iterator i = m_children.begin(); i != m_children.end(); ++i)
delete *i;
}
};
template<typename T>
static mafTreeNode<T>* mafTree_copy(const mafTree<T>* new_owner, mafTreeNode<T>* root)
{
if (!root) return 0;
mafTreeNode<T>* new_tree = new mafTreeNode<T>(new_owner, root->m_data);
for (TYPENAME std::vector<mafTreeNode<T>*>::iterator i = root->m_children.begin(); i != root->m_children.end(); ++i)
{
mafTreeNode<T>* new_child = mafTree_copy(new_owner, *i);
new_tree->m_children.push_back(new_child);
new_child->m_parent = new_tree;
}
return new_tree;
}
template<typename T>
static unsigned mafTree_size(mafTreeNode<T>* root)
{
if (!root) return 0;
unsigned result = 1;
for (TYPENAME std::vector<mafTreeNode<T>*>::iterator i = root->m_children.begin(); i != root->m_children.end(); ++i)
result += mafTree_size(*i);
return result;
}
template<typename T>
static unsigned mafTree_depth(mafTreeNode<T>* root)
{
unsigned depth = 0;
for (mafTreeNode<T>* i = root; i; i = i->m_parent)
++depth;
return depth;
}
////////////////////////////////////////////////////////////////////////////////
// mafTreeIterator
// constructor to create a null iterator - you must assign a valid value to this iterator before using it
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>::mafTreeIterator(void)
{
}
// used to create an alias of an iterator
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>::mafTreeIterator(const mafSafeIterator<mafTree<T>, mafTreeNode<T> >& iterator) :
mafSafeIterator<mafTree<T>,mafTreeNode<T> >(iterator)
{
}
// constructor used by mafTree to create a non-null iterator
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>::mafTreeIterator(mafTreeNode<T>* node) :
mafSafeIterator<mafTree<T>,mafTreeNode<T> >(node->m_master)
{
}
// constructor used by mafTree to create an end iterator
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>::mafTreeIterator(const mafTree<T>* owner) :
mafSafeIterator<mafTree<T>,mafTreeNode<T> >(owner)
{
}
// destructor
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>::~mafTreeIterator(void)
{
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreeIterator<T,TRef,TPtr>::const_iterator mafTreeIterator<T,TRef,TPtr>::constify(void) const
{
return mafTreeIterator<T,const T&,const T*>(*this);
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreeIterator<T,TRef,TPtr>::iterator mafTreeIterator<T,TRef,TPtr>::deconstify(void) const
{
return mafTreeIterator<T,T&,T*>(*this);
}
template<typename T, typename TRef, typename TPtr>
bool mafTreeIterator<T,TRef,TPtr>::operator == (const TYPENAME mafTreeIterator<T,TRef,TPtr>::this_iterator& r) const
{
return this->equal(r);
}
template<typename T, typename TRef, typename TPtr>
bool mafTreeIterator<T,TRef,TPtr>::operator != (const TYPENAME mafTreeIterator<T,TRef,TPtr>::this_iterator& r) const
{
return !operator==(r);
}
template<typename T, typename TRef, typename TPtr>
bool mafTreeIterator<T,TRef,TPtr>::operator < (const TYPENAME mafTreeIterator<T,TRef,TPtr>::this_iterator& r) const
{
return compare(r) < 0;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreeIterator<T,TRef,TPtr>::reference mafTreeIterator<T,TRef,TPtr>::operator*(void) const
throw(mafNullDereference,mafEndDereference)
{
this->assert_valid();
return this->node()->m_data;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreeIterator<T,TRef,TPtr>::pointer mafTreeIterator<T,TRef,TPtr>::operator->(void) const
throw(mafNullDereference,mafEndDereference)
{
return &(operator*());
}
////////////////////////////////////////////////////////////////////////////////
// mafTreePrefixIterator
template<typename T, typename TRef, typename TPtr>
mafTreePrefixIterator<T,TRef,TPtr>::mafTreePrefixIterator(void)
{
}
template<typename T, typename TRef, typename TPtr>
mafTreePrefixIterator<T,TRef,TPtr>::~mafTreePrefixIterator(void)
{
}
template<typename T, typename TRef, typename TPtr>
mafTreePrefixIterator<T,TRef,TPtr>::mafTreePrefixIterator(const mafTreeIterator<T,TRef,TPtr>& i) :
m_iterator(i)
{
// this is initialised with the root node
// which is also the first node in prefix traversal order
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::null(void) const
{
return m_iterator.null();
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::end(void) const
{
return m_iterator.end();
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::valid(void) const
{
return m_iterator.valid();
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::const_iterator mafTreePrefixIterator<T,TRef,TPtr>::constify(void) const
{
return mafTreePrefixIterator<T,const T&,const T*>(m_iterator);
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::iterator mafTreePrefixIterator<T,TRef,TPtr>::deconstify(void) const
{
return mafTreePrefixIterator<T,T&,T*>(m_iterator);
}
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr> mafTreePrefixIterator<T,TRef,TPtr>::simplify(void) const
{
return m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::operator == (const TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator == r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::operator != (const TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator != r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePrefixIterator<T,TRef,TPtr>::operator < (const TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator < r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::this_iterator& mafTreePrefixIterator<T,TRef,TPtr>::operator ++ (void)
throw(mafNullDereference,mafEndDereference)
{
// pre-increment operator
// algorithm: if there are any children, visit child 0, otherwise, go to
// parent and deduce which child the start node was of that parent - if
// there are further children, go into the next one. Otherwise, go up the
// tree and test again for further children. Return null if there are no
// further nodes
m_iterator.assert_valid();
mafTreeNode<T>* old_node = m_iterator.node();
if (!old_node->m_children.empty())
{
// simply take the first child of this node
m_iterator.set(old_node->m_children[0]->m_master);
}
else
{
// this loop walks up the parent pointers
// either it will walk off the top and exit or a new node will be found and the loop will exit
for (;;)
{
// go up a level
mafTreeNode<T>* parent = old_node->m_parent;
if (!parent)
{
// we've walked off the top of the tree, so return end
m_iterator.set_end();
break;
}
else
{
// otherwise walk down the next child - if there is one
// find which index the old node was relative to this node
TYPENAME std::vector<mafTreeNode<T>*>::iterator found =
std::find(parent->m_children.begin(), parent->m_children.end(), old_node);
// if this was found, then see if there is another and if so return that
++found;
if (found != parent->m_children.end())
{
// visit the next child
m_iterator.set((*found)->m_master);
break;
}
else
{
// keep going up
old_node = parent;
}
}
}
}
return *this;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::this_iterator mafTreePrefixIterator<T,TRef,TPtr>::operator ++ (int)
throw(mafNullDereference,mafEndDereference)
{
// post-increment is defined in terms of the pre-increment
mafTreePrefixIterator<T,TRef,TPtr> result(*this);
++(*this);
return result;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::reference mafTreePrefixIterator<T,TRef,TPtr>::operator*(void) const
throw(mafNullDereference,mafEndDereference)
{
return m_iterator.operator*();
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePrefixIterator<T,TRef,TPtr>::pointer mafTreePrefixIterator<T,TRef,TPtr>::operator->(void) const
throw(mafNullDereference,mafEndDereference)
{
return m_iterator.operator->();
}
template<typename T, typename TRef, typename TPtr>
const mafTreeIterator<T,TRef,TPtr>& mafTreePrefixIterator<T,TRef,TPtr>::get_iterator(void) const
{
return m_iterator;
}
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>& mafTreePrefixIterator<T,TRef,TPtr>::get_iterator(void)
{
return m_iterator;
}
////////////////////////////////////////////////////////////////////////////////
// mafTreePostfixIterator
template<typename T, typename TRef, typename TPtr>
mafTreePostfixIterator<T,TRef,TPtr>::mafTreePostfixIterator(void)
{
}
template<typename T, typename TRef, typename TPtr>
mafTreePostfixIterator<T,TRef,TPtr>::~mafTreePostfixIterator(void)
{
}
template<typename T, typename TRef, typename TPtr>
mafTreePostfixIterator<T,TRef,TPtr>::mafTreePostfixIterator(const mafTreeIterator<T,TRef,TPtr>& i) :
m_iterator(i)
{
// this is initialised with the root node
// initially traverse to the first node to be visited
if (m_iterator.valid())
{
mafTreeNode<T>* node = m_iterator.node();
while (!node->m_children.empty())
node = node->m_children[0];
m_iterator.set(node->m_master);
}
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::null(void) const
{
return m_iterator.null();
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::end(void) const
{
return m_iterator.end();
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::valid(void) const
{
return m_iterator.valid();
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::const_iterator mafTreePostfixIterator<T,TRef,TPtr>::constify(void) const
{
return mafTreePostfixIterator<T,const T&,const T*>(m_iterator);
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::iterator mafTreePostfixIterator<T,TRef,TPtr>::deconstify(void) const
{
return mafTreePostfixIterator<T,T&,T*>(m_iterator);
}
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr> mafTreePostfixIterator<T,TRef,TPtr>::simplify(void) const
{
return m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::operator == (const TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator == r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::operator != (const TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator != r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
bool mafTreePostfixIterator<T,TRef,TPtr>::operator < (const TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::this_iterator& r) const
{
return m_iterator < r.m_iterator;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::this_iterator& mafTreePostfixIterator<T,TRef,TPtr>::operator ++ (void)
throw(mafNullDereference,mafEndDereference)
{
// pre-increment operator
// algorithm: this node has been visited, therefore all children must have
// already been visited. So go to parent. Return null if the parent is null.
// Otherwise deduce which child the start node was of that parent - if there
// are further children, go into the next one and then walk down any
// subsequent first-child pointers to the bottom. Otherwise, if there are no
// children then the parent node is the next in the traversal.
m_iterator.assert_valid();
// go up a level
mafTreeNode<T>* old_node = m_iterator.node();
mafTreeNode<T>* parent = old_node->m_parent;
if (!parent)
{
// we've walked off the top of the tree, so return end
m_iterator.set_end();
}
else
{
// otherwise find which index the old node was relative to this node
TYPENAME std::vector<mafTreeNode<T>*>::iterator found =
std::find(parent->m_children.begin(), parent->m_children.end(), old_node);
// if this was found, then see if there is another
++found;
if (found != parent->m_children.end())
{
// if so traverse to it and walk down the leftmost child pointers to the bottom of the new sub-tree
mafTreeNode<T>* new_node = *found;
while (!new_node->m_children.empty())
new_node = new_node->m_children[0];
m_iterator.set(new_node->m_master);
}
else
{
// the parent's children have all been visited - so the parent is visited
m_iterator.set(parent->m_master);
}
}
return *this;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::this_iterator mafTreePostfixIterator<T,TRef,TPtr>::operator ++ (int)
throw(mafNullDereference,mafEndDereference)
{
// post-increment is defined in terms of the pre-increment
mafTreePostfixIterator<T,TRef,TPtr> result(*this);
++(*this);
return result;
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::reference mafTreePostfixIterator<T,TRef,TPtr>::operator*(void) const
throw(mafNullDereference,mafEndDereference)
{
return m_iterator.operator*();
}
template<typename T, typename TRef, typename TPtr>
TYPENAME mafTreePostfixIterator<T,TRef,TPtr>::pointer mafTreePostfixIterator<T,TRef,TPtr>::operator->(void) const
throw(mafNullDereference,mafEndDereference)
{
return m_iterator.operator->();
}
template<typename T, typename TRef, typename TPtr>
const mafTreeIterator<T,TRef,TPtr>& mafTreePostfixIterator<T,TRef,TPtr>::get_iterator(void) const
{
return m_iterator;
}
template<typename T, typename TRef, typename TPtr>
mafTreeIterator<T,TRef,TPtr>& mafTreePostfixIterator<T,TRef,TPtr>::get_iterator(void)
{
return m_iterator;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// mafTree
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
template<typename T>
mafTree<T>::mafTree(void) : m_root(0)
{
}
template<typename T>
mafTree<T>::~mafTree(void)
{
if (m_root) delete m_root;
}
template<typename T>
mafTree<T>::mafTree(const mafTree<T>& r) : m_root(0)
{
*this = r;
}
template<typename T>
mafTree<T>& mafTree<T>::operator=(const mafTree<T>& r)
{
if (m_root) delete m_root;
m_root = mafTree_copy(this, r.m_root);
return *this;
}
template<typename T>
bool mafTree<T>::empty(void) const
{
return m_root == 0;
}
template<typename T>
unsigned mafTree<T>::size(void) const
{
return mafTree_size(m_root);
}
template<typename T>
unsigned mafTree<T>::size(const TYPENAME mafTree<T>::const_iterator& i) const
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return mafTree_size(i.node());
}
template<typename T>
unsigned mafTree<T>::size(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return mafTree_size(i.node());
}
template<typename T>
unsigned mafTree<T>::depth(const TYPENAME mafTree<T>::const_iterator& i) const
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return mafTree_depth(i.node());
}
template<typename T>
unsigned mafTree<T>::depth(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return mafTree_depth(i.node());
}
template<typename T>
TYPENAME mafTree<T>::const_iterator mafTree<T>::root(void) const
{
if (!m_root) return mafTreeIterator<T,const T&,const T*>(this);
return mafTreeIterator<T,const T&,const T*>(m_root);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::root(void)
{
if (!m_root) return mafTreeIterator<T,T&,T*>(this);
return mafTreeIterator<T,T&,T*>(m_root);
}
template<typename T>
unsigned mafTree<T>::children(const TYPENAME mafTree<T>::const_iterator& i) const
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return i.node()->m_children.size();
}
template<typename T>
unsigned mafTree<T>::children(const mafTreeIterator<T,T&,T*>& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
return i.node()->m_children.size();
}
template<typename T>
TYPENAME mafTree<T>::const_iterator mafTree<T>::child(const TYPENAME mafTree<T>::const_iterator& i, unsigned child) const
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
i.assert_valid(this);
if (child >= children(i)) throw std::out_of_range("mafCore::mafTree");
return mafTreeIterator<T,const T&,const T*>(i.node()->m_children[child]);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::child(const TYPENAME mafTree<T>::iterator& i, unsigned child)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
i.assert_valid(this);
if (child >= children(i)) throw std::out_of_range("mafCore::mafTree");
return mafTreeIterator<T,T&,T*>(i.node()->m_children[child]);
}
template<typename T>
TYPENAME mafTree<T>::const_iterator mafTree<T>::parent(const TYPENAME mafTree<T>::const_iterator& i) const
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
mafTreeNode<T>* parent = i.node()->m_parent;
if (!parent) return mafTreeIterator<T,const T&,const T*>(this);
return mafTreeIterator<T,const T&,const T*>(parent);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::parent(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
i.assert_valid(this);
mafTreeNode<T>* parent = i.node()->m_parent;
if (!parent) return mafTreeIterator<T,T&,T*>(this);
return mafTreeIterator<T,T&,T*>(parent);
}
template<typename T>
TYPENAME mafTree<T>::const_prefix_iterator mafTree<T>::prefix_begin(void) const
{
return mafTreePrefixIterator<T,const T&,const T*>(root());
}
template<typename T>
TYPENAME mafTree<T>::prefix_iterator mafTree<T>::prefix_begin(void)
{
return mafTreePrefixIterator<T,T&,T*>(root());
}
template<typename T>
TYPENAME mafTree<T>::const_prefix_iterator mafTree<T>::prefix_end(void) const
{
return mafTreePrefixIterator<T,const T&,const T*>(mafTreeIterator<T,const T&,const T*>(this));
}
template<typename T>
TYPENAME mafTree<T>::prefix_iterator mafTree<T>::prefix_end(void)
{
return mafTreePrefixIterator<T,T&,T*>(mafTreeIterator<T,T&,T*>(this));
}
template<typename T>
TYPENAME mafTree<T>::const_postfix_iterator mafTree<T>::postfix_begin(void) const
{
return mafTreePostfixIterator<T,const T&,const T*>(root());
}
template<typename T>
TYPENAME mafTree<T>::postfix_iterator mafTree<T>::postfix_begin(void)
{
return mafTreePostfixIterator<T,T&,T*>(root());
}
template<typename T>
TYPENAME mafTree<T>::const_postfix_iterator mafTree<T>::postfix_end(void) const
{
return mafTreePostfixIterator<T,const T&,const T*>(mafTreeIterator<T,const T&,const T*>(this));
}
template<typename T>
TYPENAME mafTree<T>::postfix_iterator mafTree<T>::postfix_end(void)
{
return mafTreePostfixIterator<T,T&,T*>(mafTreeIterator<T,T&,T*>(this));
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::insert(const T& data)
{
// insert a new node as the root
return insert(mafTreeIterator<T,T&,T*>(this), 0, data);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::insert(const TYPENAME mafTree<T>::iterator& i, unsigned offset, const T& data)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
// if i is the end iterator, this means insert a new root
if (i.end())
erase();
else
{
i.assert_valid(this);
if (offset > children(i)) throw std::out_of_range("mafCore::mafTree");
}
mafTreeNode<T>* new_node = new mafTreeNode<T>(this,data);
if (i.end())
{
m_root = new_node;
}
else
{
i.node()->m_children.insert(i.node()->m_children.begin()+offset,new_node);
new_node->m_parent = i.node();
}
return mafTreeIterator<T,T&,T*>(new_node);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::append(const TYPENAME mafTree<T>::iterator& i, const T& data)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
return insert(i, i.node()->m_children.size(), data);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::insert(const TYPENAME mafTree<T>::iterator& i, unsigned offset, const mafTree<T>& tree)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
// insert a whole tree as a child of i
i.assert_valid(this);
if (offset > children(i)) throw std::out_of_range("mafCore::mafTree");
mafTreeNode<T>* new_node = mafTree_copy(this, tree.m_root);
i.node()->m_children.insert(i.node()->m_children.begin()+offset,new_node);
new_node->m_parent = i.node();
return mafTreeIterator<T,T&,T*>(new_node);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::append(const TYPENAME mafTree<T>::iterator& i, const mafTree<T>& tree)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
return insert(i, children(i), tree);
}
template<typename T>
TYPENAME mafTree<T>::iterator mafTree<T>::push(const TYPENAME mafTree<T>::iterator& node, const T& data)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
// insert a new node to replace the existing node in the tree
// making the original node the child of the new node
// i.e. (node) becomes (new)->(node)
// afterwards, the iterator still points to the old node, now the child
// returns the iterator to the new node
node.assert_valid(this);
mafTreeNode<T>* new_node = new mafTreeNode<T>(this,data);
if (node.node() == m_root)
{
// pushing the root node
m_root = new_node;
new_node->m_parent = 0;
}
else
{
// pushing a sub-node
*(std::find(node.node()->m_parent->m_children.begin(), node.node()->m_parent->m_children.end(), node.node())) = new_node;
new_node->m_parent = node.node()->m_parent;
}
// link up the old node as the child of the new node
new_node->m_children.insert(new_node->m_children.begin(),node.node());
node.node()->m_parent = new_node;
return mafTreeIterator<T,T&,T*>(new_node);
}
template<typename T>
void mafTree<T>::pop(const TYPENAME mafTree<T>::iterator& parent, unsigned offset)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
// inverse of push
// removes the specified child of the parent node, adding its children to the parent node at the same offset
parent.assert_valid(this);
mafTreeNode<T>* node = parent.node();
if (offset >= node->m_children.size()) throw std::out_of_range("mafCore::mafTree");
// move the grandchildren first
mafTreeNode<T>* child = parent.node()->m_children[offset];
while (!child->m_children.empty())
{
// remove the last grandchild and insert into node just after the child to be removed
mafTreeNode<T>* grandchild = child->m_children[child->m_children.size()-1];
child->m_children.pop_back();
node->m_children.insert(node->m_children.begin()+offset+1, grandchild);
grandchild->m_parent = node;
}
// now remove the child
node->m_children.erase(node->m_children.begin()+offset);
delete child;
}
template<typename T>
void mafTree<T>::erase(void)
{
// erase the whole tree
erase(root());
}
template<typename T>
void mafTree<T>::erase(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
if (!i.end())
{
// erase this node and its subtree
// do this by erasing this child of its parent
// handle the case of erasing the root
i.assert_valid(this);
mafTreeNode<T>* node = i.node();
if (node == m_root)
{
delete m_root;
m_root = 0;
}
else
{
mafTreeNode<T>* parent = node->m_parent;
// impossible for parent to be null - should assert this
TYPENAME std::vector<mafTreeNode<T>*>::iterator found =
std::find(parent->m_children.begin(), parent->m_children.end(), node);
// impossible for find to fail - should assert this
parent->m_children.erase(found);
delete node;
}
}
}
template<typename T>
void mafTree<T>::erase(const TYPENAME mafTree<T>::iterator& i, unsigned offset)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
erase(child(i, offset));
}
template<typename T>
mafTree<T> mafTree<T>::subtree(void)
{
return subtree(root());
}
template<typename T>
mafTree<T> mafTree<T>::subtree(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
mafTree<T> result;
if (!i.end())
{
i.assert_valid(this);
result.m_root = mafTree_copy(&result, i.node());
}
return result;
}
template<typename T>
mafTree<T> mafTree<T>::subtree(const TYPENAME mafTree<T>::iterator& i, unsigned offset)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
return subtree(child(i, offset));
}
template<typename T>
mafTree<T> mafTree<T>::cut(void)
{
return cut(root());
}
template<typename T>
mafTree<T> mafTree<T>::cut(const TYPENAME mafTree<T>::iterator& i)
throw(mafWrongObject,mafNullDereference,mafEndDereference)
{
mafTree<T> result;
if (!i.end())
{
i.assert_valid(this);
mafTreeNode<T>* node = i.node();
if (node == m_root)
{
result.m_root = m_root;
m_root = 0;
}
else
{
mafTreeNode<T>* parent = node->m_parent;
// impossible for parent to be null - should assert this
TYPENAME std::vector<mafTreeNode<T>*>::iterator found =
std::find(parent->m_children.begin(), parent->m_children.end(), node);
// impossible for find to fail - should assert this
result.m_root = *found;
parent->m_children.erase(found);
}
if (result.m_root)
{
result.m_root->m_parent = 0;
result.m_root->change_owner(&result);
}
}
return result;
}
template<typename T>
mafTree<T> mafTree<T>::cut(const TYPENAME mafTree<T>::iterator& i, unsigned offset)
throw(mafWrongObject,mafNullDereference,mafEndDereference,std::out_of_range)
{
return cut(child(i, offset));
}
////////////////////////////////////////////////////////////////////////////////
} // end namespace mafCore
| 32.798687 | 132 | 0.66412 | [
"vector"
] |
7321926332dfa6e61a58352093fd20fe3bb4a2db | 15,729 | cpp | C++ | Engine/Source/Runtime/Engine/Private/VisualLogger/VisualLogger.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Private/VisualLogger/VisualLogger.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Engine/Private/VisualLogger/VisualLogger.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "EnginePrivate.h"
#include "VisualLogger/VisualLogger.h"
#include "VisualLogger/VisualLoggerBinaryFileDevice.h"
#if WITH_EDITOR
# include "Editor/UnrealEd/Public/EditorComponents.h"
# include "Editor/UnrealEd/Public/EditorReimportHandler.h"
# include "Editor/UnrealEd/Public/TexAlignTools.h"
# include "Editor/UnrealEd/Public/TickableEditorObject.h"
# include "UnrealEdClasses.h"
# include "Editor/UnrealEd/Public/Editor.h"
# include "Editor/UnrealEd/Public/EditorViewportClient.h"
#endif
#if ENABLE_VISUAL_LOG
DEFINE_STAT(STAT_VisualLog);
DEFINE_LOG_CATEGORY(LogVisual);
TMap<UObject*, TArray<TWeakObjectPtr<const UObject> > > FVisualLogger::RedirectionMap;
bool FVisualLogger::CheckVisualLogInputInternal(const class UObject* Object, const struct FLogCategoryBase& Category, ELogVerbosity::Type Verbosity, UWorld **World, FVisualLogEntry **CurrentEntry)
{
FVisualLogger& VisualLogger = FVisualLogger::Get();
if (!Object || (GEngine && GEngine->bDisableAILogging) || VisualLogger.IsRecording() == false || Object->HasAnyFlags(RF_ClassDefaultObject))
{
return false;
}
const FName CategoryName = Category.GetCategoryName();
if (VisualLogger.IsBlockedForAllCategories() && VisualLogger.IsWhiteListed(CategoryName) == false)
{
return false;
}
*World = GEngine->GetWorldFromContextObject(Object, false);
if (ensure(*World != nullptr) == false)
{
return false;
}
*CurrentEntry = VisualLogger.GetEntryToWrite(Object, (*World)->TimeSeconds);
if (*CurrentEntry == nullptr)
{
return false;
}
return true;
}
FVisualLogEntry* FVisualLogger::GetLastEntryForObject(const class UObject* Object)
{
UObject * LogOwner = FVisualLogger::FindRedirection(Object);
return CurrentEntryPerObject.Contains(LogOwner) ? &CurrentEntryPerObject[LogOwner] : nullptr;
}
FVisualLogEntry* FVisualLogger::GetEntryToWrite(const class UObject* Object, float TimeStamp, ECreateIfNeeded ShouldCreate)
{
FVisualLogEntry* CurrentEntry = nullptr;
UObject * LogOwner = FVisualLogger::FindRedirection(Object);
if (LogOwner == nullptr || (LogOwner != Object && CurrentEntryPerObject.Contains(LogOwner) == false))
{
return nullptr;
}
bool InitializeNewEntry = false;
TWeakObjectPtr<UWorld> World = GetWorld(Object);
if (CurrentEntryPerObject.Contains(LogOwner))
{
CurrentEntry = &CurrentEntryPerObject[LogOwner];
InitializeNewEntry = TimeStamp > CurrentEntry->TimeStamp && ShouldCreate == ECreateIfNeeded::Create;
if (World.IsValid())
{
World->GetTimerManager().ClearTimer(VisualLoggerCleanupTimerHandle);
for (auto& CurrentPair : CurrentEntryPerObject)
{
FVisualLogEntry* Entry = &CurrentPair.Value;
if (Entry->TimeStamp >= 0 && Entry->TimeStamp < TimeStamp)
{
for (auto* Device : OutputDevices)
{
Device->Serialize(CurrentPair.Key, ObjectToNameMap[CurrentPair.Key], ObjectToClassNameMap[CurrentPair.Key], *Entry);
}
Entry->Reset();
}
}
}
}
if (!CurrentEntry)
{
// It's first and only one usage of LogOwner as regular object to get names. We assume once that LogOwner is correct here and only here.
CurrentEntry = &CurrentEntryPerObject.Add(LogOwner);
ObjectToNameMap.Add(LogOwner, LogOwner->GetFName());
ObjectToClassNameMap.Add(LogOwner, *(LogOwner->GetClass()->GetName()));
ObjectToPointerMap.Add(LogOwner, LogOwner);
InitializeNewEntry = true;
}
if (InitializeNewEntry)
{
CurrentEntry->Reset();
CurrentEntry->TimeStamp = TimeStamp;
if (RedirectionMap.Contains(LogOwner))
{
if (ObjectToPointerMap.Contains(LogOwner) && ObjectToPointerMap[LogOwner].IsValid())
{
const class AActor* LogOwnerAsActor = Cast<class AActor>(LogOwner);
if (LogOwnerAsActor)
{
LogOwnerAsActor->GrabDebugSnapshot(CurrentEntry);
}
}
for (auto Child : RedirectionMap[LogOwner])
{
if (Child.IsValid())
{
const class AActor* ChildAsActor = Cast<class AActor>(Child.Get());
if (ChildAsActor)
{
ChildAsActor->GrabDebugSnapshot(CurrentEntry);
}
}
}
}
else
{
const class AActor* ObjectAsActor = Cast<class AActor>(Object);
if (ObjectAsActor)
{
CurrentEntry->Location = ObjectAsActor->GetActorLocation();
ObjectAsActor->GrabDebugSnapshot(CurrentEntry);
}
}
}
if (World.IsValid())
{
//set next tick timer to flush obsolete/old entries
World->GetTimerManager().SetTimer(VisualLoggerCleanupTimerHandle, FTimerDelegate::CreateLambda(
[this, World](){
for (auto& CurrentPair : CurrentEntryPerObject)
{
FVisualLogEntry* Entry = &CurrentPair.Value;
if (Entry->TimeStamp >= 0 && (!World.IsValid() || Entry->TimeStamp < World->GetTimeSeconds())) // CurrentEntry->TimeStamp == -1 means it's not initialized entry information
{
for (auto* Device : OutputDevices)
{
Device->Serialize(CurrentPair.Key, ObjectToNameMap[CurrentPair.Key], ObjectToClassNameMap[CurrentPair.Key], *Entry);
}
Entry->Reset();
}
}
}
), 0.1, false);
}
return CurrentEntry;
}
void FVisualLogger::Flush()
{
for (auto &CurrentEntry : CurrentEntryPerObject)
{
if (CurrentEntry.Value.TimeStamp >= 0)
{
for (auto* Device : OutputDevices)
{
Device->Serialize(CurrentEntry.Key, ObjectToNameMap[CurrentEntry.Key], ObjectToClassNameMap[CurrentEntry.Key], CurrentEntry.Value);
}
CurrentEntry.Value.Reset();
}
}
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event1, const FVisualLogEventBase& Event2, const FVisualLogEventBase& Event3, const FVisualLogEventBase& Event4, const FVisualLogEventBase& Event5, const FVisualLogEventBase& Event6)
{
EventLog(Object, EventTag1, Event1, Event2, Event3, Event4, Event5);
EventLog(Object, EventTag1, Event6);
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event1, const FVisualLogEventBase& Event2, const FVisualLogEventBase& Event3, const FVisualLogEventBase& Event4, const FVisualLogEventBase& Event5)
{
EventLog(Object, EventTag1, Event1, Event2, Event3, Event4);
EventLog(Object, EventTag1, Event5);
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event1, const FVisualLogEventBase& Event2, const FVisualLogEventBase& Event3, const FVisualLogEventBase& Event4)
{
EventLog(Object, EventTag1, Event1, Event2, Event3);
EventLog(Object, EventTag1, Event4);
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event1, const FVisualLogEventBase& Event2, const FVisualLogEventBase& Event3)
{
EventLog(Object, EventTag1, Event1, Event2);
EventLog(Object, EventTag1, Event3);
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event1, const FVisualLogEventBase& Event2)
{
EventLog(Object, EventTag1, Event1);
EventLog(Object, EventTag1, Event2);
}
void FVisualLogger::EventLog(const class UObject* LogOwner, const FVisualLogEventBase& Event1, const FName EventTag1, const FName EventTag2, const FName EventTag3, const FName EventTag4, const FName EventTag5, const FName EventTag6)
{
EventLog(LogOwner, EventTag1, Event1, EventTag2, EventTag3, EventTag4, EventTag5, EventTag6);
}
void FVisualLogger::EventLog(const class UObject* Object, const FName EventTag1, const FVisualLogEventBase& Event, const FName EventTag2, const FName EventTag3, const FName EventTag4, const FName EventTag5, const FName EventTag6)
{
SCOPE_CYCLE_COUNTER(STAT_VisualLog);
UWorld *World = nullptr;
FVisualLogEntry *CurrentEntry = nullptr;
const FLogCategory<ELogVerbosity::Log, ELogVerbosity::Log> Category(*Event.Name);
if (CheckVisualLogInputInternal(Object, Category, ELogVerbosity::Log, &World, &CurrentEntry) == false)
{
return;
}
int32 Index = CurrentEntry->Events.Find(FVisualLogEvent(Event));
if (Index != INDEX_NONE)
{
CurrentEntry->Events[Index].Counter++;
}
else
{
Index = CurrentEntry->AddEvent(Event);
}
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag1)++;
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag2)++;
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag3)++;
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag4)++;
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag5)++;
CurrentEntry->Events[Index].EventTags.FindOrAdd(EventTag6)++;
CurrentEntry->Events[Index].EventTags.Remove(NAME_None);
}
void FVisualLogger::NavigationDataDump(const class UObject* Object, const struct FLogCategoryBase& Category, ELogVerbosity::Type Verbosity, int32 UniqueLogId, const FBox& Box)
{
SCOPE_CYCLE_COUNTER(STAT_VisualLog);
UWorld *World = nullptr;
FVisualLogEntry *CurrentEntry = nullptr;
if (CheckVisualLogInputInternal(Object, Category, Verbosity, &World, &CurrentEntry) == false)
{
return;
}
const ANavigationData* MainNavData = World ? UNavigationSystem::GetNavigationSystem(World)->GetMainNavData(FNavigationSystem::ECreateIfEmpty::DontCreate) : nullptr;
const FNavDataGenerator* Generator = MainNavData ? MainNavData->GetGenerator() : nullptr;
if (Generator)
{
Generator->GrabDebugSnapshot(CurrentEntry, FMath::IsNearlyZero(Box.GetVolume()) ? MainNavData->GetBounds() : Box, Category, Verbosity);
}
}
FVisualLogger::FVisualLogger()
{
BlockAllCategories(false);
AddDevice(&FVisualLoggerBinaryFileDevice::Get());
SetIsRecording(GEngine ? !!GEngine->bEnableVisualLogRecordingOnStart : false);
SetIsRecordingOnServer(false);
if (FParse::Param(FCommandLine::Get(), TEXT("EnableAILogging")))
{
SetIsRecording(true);
SetIsRecordingToFile(true);
}
}
namespace
{
static UWorld* GetWorldForVisualLogger(const class UObject* Object)
{
UWorld* World = Object ? GEngine->GetWorldFromContextObject(Object, false) : nullptr;
#if WITH_EDITOR
UEditorEngine *EEngine = Cast<UEditorEngine>(GEngine);
if (GIsEditor && EEngine != nullptr && World == nullptr)
{
// lets use PlayWorld during PIE/Simulate and regular world from editor otherwise, to draw debug information
World = EEngine->PlayWorld != nullptr ? EEngine->PlayWorld : EEngine->GetEditorWorldContext().World();
}
#endif
if (!GIsEditor && World == nullptr)
{
World = GEngine->GetWorld();
}
return World;
}
}
UWorld* FVisualLogger::GetWorld(const class UObject* Object)
{
return GetWorldForVisualLogger(Object);
}
void FVisualLogger::Shutdown()
{
SetIsRecording(false);
SetIsRecordingToFile(false);
if (UseBinaryFileDevice)
{
RemoveDevice(&FVisualLoggerBinaryFileDevice::Get());
}
}
void FVisualLogger::Cleanup(bool bReleaseMemory)
{
const bool WasRecordingToFile = IsRecordingToFile();
if (WasRecordingToFile)
{
SetIsRecordingToFile(false);
}
for (FVisualLogDevice* Device : FVisualLogger::Get().OutputDevices)
{
Device->Cleanup(bReleaseMemory);
}
RedirectionMap.Reset();
LastUniqueIds.Reset();
CurrentEntryPerObject.Reset();
if (WasRecordingToFile)
{
SetIsRecordingToFile(true);
}
}
int32 FVisualLogger::GetUniqueId(float Timestamp)
{
return LastUniqueIds.FindOrAdd(Timestamp)++;
}
void FVisualLogger::Redirect(UObject* FromObject, UObject* ToObject)
{
if (FromObject == ToObject || FromObject == nullptr || ToObject == nullptr)
{
return;
}
UObject* OldRedirection = FindRedirection(FromObject);
UObject* NewRedirection = FindRedirection(ToObject);
if (OldRedirection != NewRedirection)
{
auto OldArray = RedirectionMap.Find(OldRedirection);
if (OldArray)
{
OldArray->RemoveSingleSwap(FromObject);
}
RedirectionMap.FindOrAdd(NewRedirection).AddUnique(FromObject);
UE_CVLOG(FromObject != nullptr, FromObject, LogVisual, Log, TEXT("Redirected '%s' to '%s'"), *FromObject->GetName(), *NewRedirection->GetName());
}
}
class UObject* FVisualLogger::FindRedirection(const UObject* Object)
{
if (RedirectionMap.Contains(Object) == false)
{
for (auto& Redirection : RedirectionMap)
{
if (Redirection.Value.Find(Object) != INDEX_NONE)
{
return FindRedirection(Redirection.Key);
}
}
}
return const_cast<class UObject*>(Object);
}
void FVisualLogger::SetIsRecording(bool InIsRecording)
{
if (InIsRecording == false && InIsRecording != !!bIsRecording && FParse::Param(FCommandLine::Get(), TEXT("LogNavOctree")))
{
FVisualLogger::NavigationDataDump(GetWorld(nullptr), LogNavigation, ELogVerbosity::Log, INDEX_NONE, FBox());
}
if (IsRecordingToFile())
{
SetIsRecordingToFile(false);
}
bIsRecording = InIsRecording;
};
void FVisualLogger::SetIsRecordingToFile(bool InIsRecording)
{
if (!bIsRecording && InIsRecording)
{
SetIsRecording(true);
}
UWorld* World = GEngine ? GEngine->GetWorld() : nullptr;
const FString BaseFileName = LogFileNameGetter.IsBound() ? LogFileNameGetter.Execute() : TEXT("VisualLog");
const FString MapName = World ? World->GetMapName() : TEXT("");
FString OutputFileName = FString::Printf(TEXT("%s_%s"), *BaseFileName, *MapName);
if (bIsRecordingToFile && !InIsRecording)
{
for (auto* Device : OutputDevices)
{
if (Device->HasFlags(EVisualLoggerDeviceFlags::CanSaveToFile))
{
Device->SetFileName(OutputFileName);
Device->StopRecordingToFile(World ? World->TimeSeconds : StartRecordingToFileTime);
}
}
}
else if (!bIsRecordingToFile && InIsRecording)
{
StartRecordingToFileTime = World ? World->TimeSeconds : 0;
for (auto* Device : OutputDevices)
{
if (Device->HasFlags(EVisualLoggerDeviceFlags::CanSaveToFile))
{
Device->StartRecordingToFile(StartRecordingToFileTime);
}
}
}
bIsRecordingToFile = InIsRecording;
}
bool FVisualLogger::IsCategoryLogged(const struct FLogCategoryBase& Category) const
{
if ((GEngine && GEngine->bDisableAILogging) || IsRecording() == false)
{
return false;
}
const FName CategoryName = Category.GetCategoryName();
if (IsBlockedForAllCategories() && IsWhiteListed(CategoryName) == false)
{
return false;
}
return true;
}
#endif //ENABLE_VISUAL_LOG
const FGuid EVisualLoggerVersion::GUID = FGuid(0xA4237A36, 0xCAEA41C9, 0x8FA218F8, 0x58681BF3);
FCustomVersionRegistration GVisualLoggerVersion(EVisualLoggerVersion::GUID, EVisualLoggerVersion::LatestVersion, TEXT("VisualLogger"));
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
#if WITH_EDITOR
#include "SlateBasics.h"
#endif
static class FLogVisualizerExec : private FSelfRegisteringExec
{
public:
/** Console commands, see embeded usage statement **/
virtual bool Exec(UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Ar) override
{
if (FParse::Command(&Cmd, TEXT("VISLOG")))
{
if (FModuleManager::Get().LoadModulePtr<IModuleInterface>("LogVisualizer") != nullptr)
{
#if ENABLE_VISUAL_LOG
FString Command = FParse::Token(Cmd, 0);
if (Command == TEXT("record"))
{
FVisualLogger::Get().SetIsRecording(true);
return true;
}
else if (Command == TEXT("stop"))
{
FVisualLogger::Get().SetIsRecording(false);
return true;
}
else if (Command == TEXT("disableallbut"))
{
FString Category = FParse::Token(Cmd, 1);
FVisualLogger::Get().BlockAllCategories(true);
FVisualLogger::Get().AddCategortyToWhiteList(*Category);
return true;
}
#if WITH_EDITOR
else
{
FGlobalTabmanager::Get()->InvokeTab(FName(TEXT("VisualLogger")));
return true;
}
#endif
#else
UE_LOG(LogVisual, Warning, TEXT("Unable to open LogVisualizer - logs are disabled"));
#endif
}
}
else if (FParse::Command(&Cmd, TEXT("LogNavOctree")))
{
FVisualLogger::NavigationDataDump(GetWorldForVisualLogger(nullptr), LogNavigation, ELogVerbosity::Log, INDEX_NONE, FBox());
}
return false;
}
} LogVisualizerExec;
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
| 30.07457 | 290 | 0.742132 | [
"object"
] |
73235d5dad111c673a5af0f01bbbed915ee9c7e0 | 18,396 | cpp | C++ | modules/volume/rendering/renderabletimevaryingvolume.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/volume/rendering/renderabletimevaryingvolume.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/volume/rendering/renderabletimevaryingvolume.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* 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 <modules/volume/rendering/renderabletimevaryingvolume.h>
#include <modules/volume/rendering/basicvolumeraycaster.h>
#include <modules/volume/rendering/volumeclipplanes.h>
#include <modules/volume/transferfunctionhandler.h>
#include <modules/volume/rawvolume.h>
#include <modules/volume/rawvolumereader.h>
#include <modules/volume/volumegridtype.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/raycastermanager.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/histogram.h>
#include <openspace/util/time.h>
#include <openspace/util/timemanager.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/opengl/texture.h>
namespace {
constexpr const char* _loggerCat = "RenderableTimeVaryingVolume";
} // namespace
namespace {
const char* KeyStepSize = "StepSize";
const char* KeyGridType = "GridType";
const char* KeyTransferFunction = "TransferFunction";
const char* KeySourceDirectory = "SourceDirectory";
const char* KeyClipPlanes = "ClipPlanes";
const char* KeySecondsBefore = "SecondsBefore";
const char* KeySecondsAfter = "SecondsAfter";
const float SecondsInOneDay = 60 * 60 * 24;
constexpr const float VolumeMaxOpacity = 500;
static const openspace::properties::Property::PropertyInfo StepSizeInfo = {
"stepSize",
"Step Size",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo GridTypeInfo = {
"gridType",
"Grid Type",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo SecondsBeforeInfo = {
"secondsBefore",
"Seconds before",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo SecondsAfterInfo = {
"secondsAfter",
"Seconds after",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo SourceDirectoryInfo = {
"sourceDirectory",
"Source Directory",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo TransferFunctionInfo = {
"transferFunctionPath",
"Transfer Function Path",
""
};
constexpr openspace::properties::Property::PropertyInfo TriggerTimeJumpInfo = {
"triggerTimeJump",
"Jump",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo JumpToTimestepInfo = {
"jumpToTimestep",
"Jump to timestep",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo CurrentTimeStepInfo = {
"currentTimestep",
"Current timestep",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo rNormalizationInfo = {
"rNormalization",
"Radius normalization",
"" // @TODO Missing documentation
};
constexpr openspace::properties::Property::PropertyInfo rUpperBoundInfo = {
"rUpperBound",
"Radius upper bound",
"" // @TODO Missing documentation
};
} // namespace
namespace openspace::volume {
documentation::Documentation RenderableTimeVaryingVolume::Documentation() {
using namespace documentation;
return {
"RenderableTimevaryingVolume",
"volume_renderable_timevaryingvolume",
{
{
KeySourceDirectory,
new StringVerifier,
Optional::No,
"Specifies the path to load timesteps from"
},
{
KeyTransferFunction,
new StringVerifier,
Optional::No,
"Specifies the transfer function file path"
},
{
KeySecondsBefore,
new DoubleVerifier,
Optional::Yes,
"Specifies the number of seconds to show the the first timestep before "
"its actual time. The default value is 0."
},
{
KeySecondsAfter,
new DoubleVerifier,
Optional::No,
"Specifies the number of seconds to show the the last timestep after its "
"actual time"
}
}
};
}
RenderableTimeVaryingVolume::RenderableTimeVaryingVolume(
const ghoul::Dictionary& dictionary)
: Renderable(dictionary)
, _gridType(GridTypeInfo, properties::OptionProperty::DisplayType::Dropdown)
, _stepSize(StepSizeInfo, 0.02f, 0.001f, 0.1f)
, _rNormalization(rNormalizationInfo, 0.f, 0.f, 2.f)
, _rUpperBound(rUpperBoundInfo, 1.f, 0.f, 2.f)
, _secondsBefore(SecondsBeforeInfo, 0.f, 0.01f, SecondsInOneDay)
, _secondsAfter(SecondsAfterInfo, 0.f, 0.01f, SecondsInOneDay)
, _sourceDirectory(SourceDirectoryInfo)
, _transferFunctionPath(TransferFunctionInfo)
, _triggerTimeJump(TriggerTimeJumpInfo)
, _jumpToTimestep(JumpToTimestepInfo, 0, 0, 256)
, _currentTimestep(CurrentTimeStepInfo, 0, 0, 256)
{
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"RenderableTimeVaryingVolume"
);
_sourceDirectory = absPath(dictionary.value<std::string>(KeySourceDirectory));
_transferFunctionPath = absPath(dictionary.value<std::string>(KeyTransferFunction));
_transferFunction = std::make_shared<openspace::TransferFunction>(
_transferFunctionPath,
[](const openspace::TransferFunction&) {}
);
_gridType.addOptions({
{ static_cast<int>(volume::VolumeGridType::Cartesian), "Cartesian grid" },
{ static_cast<int>(volume::VolumeGridType::Spherical), "Spherical grid" }
});
_gridType = static_cast<int>(volume::VolumeGridType::Cartesian);
if (dictionary.hasKeyAndValue<float>(KeyStepSize)) {
_stepSize = dictionary.value<float>(KeyStepSize);
}
if (dictionary.hasKeyAndValue<float>(KeySecondsBefore)) {
_secondsBefore = dictionary.value<float>(KeySecondsBefore);
}
_secondsAfter = dictionary.value<float>(KeySecondsAfter);
ghoul::Dictionary clipPlanesDictionary;
dictionary.getValue(KeyClipPlanes, clipPlanesDictionary);
_clipPlanes = std::make_shared<volume::VolumeClipPlanes>(clipPlanesDictionary);
_clipPlanes->setIdentifier("clipPlanes");
_clipPlanes->setGuiName("Clip Planes");
if (dictionary.hasKeyAndValue<std::string>(KeyGridType)) {
VolumeGridType gridType = volume::parseGridType(
dictionary.value<std::string>(KeyGridType)
);
_gridType = static_cast<std::underlying_type_t<VolumeGridType>>(gridType);
}
addProperty(_opacity);
}
RenderableTimeVaryingVolume::~RenderableTimeVaryingVolume() {}
void RenderableTimeVaryingVolume::initializeGL() {
using RawPath = ghoul::filesystem::Directory::RawPath;
ghoul::filesystem::Directory sequenceDir(_sourceDirectory, RawPath::Yes);
if (!FileSys.directoryExists(sequenceDir)) {
LERROR(fmt::format("Could not load sequence directory '{}'", sequenceDir.path()));
return;
}
using Recursive = ghoul::filesystem::Directory::Recursive;
using Sort = ghoul::filesystem::Directory::Sort;
std::vector<std::string> sequencePaths = sequenceDir.read(Recursive::Yes, Sort::No);
for (const std::string& path : sequencePaths) {
ghoul::filesystem::File currentFile(path);
std::string extension = currentFile.fileExtension();
if (extension == "dictionary") {
loadTimestepMetadata(path);
}
}
// TODO: defer loading of data to later (separate thread or at least not when loading)
for (std::pair<const double, Timestep>& p : _volumeTimesteps) {
Timestep& t = p.second;
std::string path = FileSys.pathByAppendingComponent(
_sourceDirectory, t.baseName
) + ".rawvolume";
RawVolumeReader<float> reader(path, t.metadata.dimensions);
t.rawVolume = reader.read();
float min = t.metadata.minValue;
float diff = t.metadata.maxValue - t.metadata.minValue;
float* data = t.rawVolume->data();
for (size_t i = 0; i < t.rawVolume->nCells(); ++i) {
data[i] = glm::clamp((data[i] - min) / diff, 0.f, 1.f);
}
t.histogram = std::make_shared<Histogram>(0.f, 1.f, 100);
for (size_t i = 0; i < t.rawVolume->nCells(); ++i) {
t.histogram->add(data[i]);
}
// TODO: handle normalization properly for different timesteps + transfer function
t.texture = std::make_shared<ghoul::opengl::Texture>(
t.metadata.dimensions,
ghoul::opengl::Texture::Format::Red,
GL_RED,
GL_FLOAT,
ghoul::opengl::Texture::FilterMode::Linear,
ghoul::opengl::Texture::WrappingMode::Clamp
);
t.texture->setPixelData(
reinterpret_cast<void*>(data),
ghoul::opengl::Texture::TakeOwnership::No
);
t.texture->uploadTexture();
}
_clipPlanes->initialize();
_raycaster = std::make_unique<volume::BasicVolumeRaycaster>(
nullptr,
_transferFunction,
_clipPlanes
);
_raycaster->initialize();
global::raycasterManager.attachRaycaster(*_raycaster.get());
onEnabledChange([&](bool enabled) {
if (enabled) {
global::raycasterManager.attachRaycaster(*_raycaster.get());
}
else {
global::raycasterManager.detachRaycaster(*_raycaster.get());
}
});
_triggerTimeJump.onChange([this] () { jumpToTimestep(_jumpToTimestep); });
_jumpToTimestep.onChange([this] () { jumpToTimestep(_jumpToTimestep); });
const int lastTimestep = !_volumeTimesteps.empty() ?
static_cast<int>(_volumeTimesteps.size() - 1) :
0;
_currentTimestep.setMaxValue(lastTimestep);
_jumpToTimestep.setMaxValue(lastTimestep);
addProperty(_stepSize);
addProperty(_transferFunctionPath);
addProperty(_sourceDirectory);
addPropertySubOwner(_clipPlanes.get());
addProperty(_triggerTimeJump);
addProperty(_jumpToTimestep);
addProperty(_currentTimestep);
addProperty(_rNormalization);
addProperty(_rUpperBound);
addProperty(_gridType);
_raycaster->setGridType(static_cast<VolumeGridType>(_gridType.value()));
_gridType.onChange([this] {
_raycaster->setGridType(static_cast<VolumeGridType>(_gridType.value()));
});
_transferFunctionPath.onChange([this] {
_transferFunction = std::make_shared<openspace::TransferFunction>(
_transferFunctionPath
);
_raycaster->setTransferFunction(_transferFunction);
});
}
void RenderableTimeVaryingVolume::loadTimestepMetadata(const std::string& path) {
RawVolumeMetadata metadata;
try {
ghoul::Dictionary dictionary = ghoul::lua::loadDictionaryFromFile(path);
metadata = RawVolumeMetadata::createFromDictionary(dictionary);
} catch (...) {
return;
}
Timestep t;
t.metadata = metadata;
t.baseName = ghoul::filesystem::File(path).baseName();
t.inRam = false;
t.onGpu = false;
_volumeTimesteps[t.metadata.time] = std::move(t);
}
RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimestep() {
if (_volumeTimesteps.empty()) {
return nullptr;
}
double currentTime = global::timeManager.time().j2000Seconds();
// Get the first item with time > currentTime
auto currentTimestepIt = _volumeTimesteps.upper_bound(currentTime);
if (currentTimestepIt == _volumeTimesteps.end()) {
// No such timestep was found: show last timestep if it is within the time margin.
Timestep* lastTimestep = &(_volumeTimesteps.rbegin()->second);
double threshold = lastTimestep->metadata.time +
static_cast<double>(_secondsAfter);
return currentTime < threshold ? lastTimestep : nullptr;
}
if (currentTimestepIt == _volumeTimesteps.begin()) {
// No such timestep was found: show first timestep if it is within the time margin
Timestep* firstTimestep = &(_volumeTimesteps.begin()->second);
double threshold = firstTimestep->metadata.time -
static_cast<double>(_secondsBefore);
return currentTime >= threshold ? firstTimestep : nullptr;
}
// Get the last item with time <= currentTime
currentTimestepIt--;
return &(currentTimestepIt->second);
}
int RenderableTimeVaryingVolume::timestepIndex(
const RenderableTimeVaryingVolume::Timestep* t) const
{
if (!t) {
return -1;
}
int index = 0;
for (const std::pair<const double, Timestep>& it : _volumeTimesteps) {
if (&(it.second) == t) {
return index;
}
++index;
}
return -1;
}
// @TODO Can this be turned into a const ref?
RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::timestepFromIndex(
int target)
{
if (target < 0) {
target = 0;
}
int index = 0;
for (std::pair<const double, Timestep>& it : _volumeTimesteps) {
if (index == target) {
return &(it.second);
}
++index;
}
return nullptr;
}
void RenderableTimeVaryingVolume::jumpToTimestep(int target) {
Timestep* t = timestepFromIndex(target);
if (t) {
global::timeManager.setTimeNextFrame(t->metadata.time);
}
}
void RenderableTimeVaryingVolume::update(const UpdateData&) {
_transferFunction->update();
if (_raycaster) {
Timestep* t = currentTimestep();
_currentTimestep = timestepIndex(t);
// Set scale and translation matrices:
// The original data cube is a unit cube centered in 0
// ie with lower bound from (-0.5, -0.5, -0.5) and upper bound (0.5, 0.5, 0.5)
if (t && t->texture) {
if (_raycaster->gridType() == volume::VolumeGridType::Cartesian) {
glm::dvec3 scale = t->metadata.upperDomainBound -
t->metadata.lowerDomainBound;
glm::dvec3 translation =
(t->metadata.lowerDomainBound + t->metadata.upperDomainBound) * 0.5f;
glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), translation);
glm::dmat4 scaleMatrix = glm::scale(glm::dmat4(1.0), scale);
modelTransform = modelTransform * scaleMatrix;
_raycaster->setModelTransform(glm::mat4(modelTransform));
} else {
// The diameter is two times the maximum radius.
// No translation: the sphere is always centered in (0, 0, 0)
_raycaster->setModelTransform(
glm::scale(
glm::dmat4(1.0),
glm::dvec3(2.0 * t->metadata.upperDomainBound[0])
)
);
}
_raycaster->setVolumeTexture(t->texture);
} else {
_raycaster->setVolumeTexture(nullptr);
}
_raycaster->setStepSize(_stepSize);
_raycaster->setOpacity(_opacity * VolumeMaxOpacity);
_raycaster->setRNormalization(_rNormalization);
_raycaster->setRUpperBound(_rUpperBound);
}
}
void RenderableTimeVaryingVolume::render(const RenderData& data, RendererTasks& tasks) {
if (_raycaster && _raycaster->volumeTexture()) {
tasks.raycasterTasks.push_back({ _raycaster.get(), data });
}
}
bool RenderableTimeVaryingVolume::isReady() const {
return true;
}
void RenderableTimeVaryingVolume::deinitializeGL() {
if (_raycaster) {
global::raycasterManager.detachRaycaster(*_raycaster.get());
_raycaster = nullptr;
}
}
} // namespace openspace::volume
| 37.314402 | 90 | 0.614264 | [
"render",
"vector"
] |
7324476c660bf4bd9f7914e7d1b855fbbe959952 | 14,434 | hpp | C++ | Source/AllProjects/CoreTech/CQCIR/CQCIR_DriverBase.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CoreTech/CQCIR/CQCIR_DriverBase.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CoreTech/CQCIR/CQCIR_DriverBase.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCIR_DriverBase.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 11/16/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file defines a base class for all of the server side IR device
// drivers. They all share a lot of common functionality, so it saves a
// lot of grunt work to factor it out.
//
// At this level we can manage the device model configuration related
// stuff, writes to the command invocation field, configuration loading,
// and the invocation of IR reciever actions, which is a good bit of the
// functionality, sometimes almost all of it for some derived drivers.
//
// The IR driver architecture makes a good bit of use of the 'back door'
// driver methods that allow the client side driver to talk to them outside
// of field interface. This guy also handles all the translation of data
// going back and forth (which is not typed data since these are generic
// methods) and even in cases where the derived class might need to handle
// the call, we handle the incoming method, translate the data, call a
// protected virtual that we define (and the derived class overrides) and
// then package up the return data if any.
//
// Processing reciever commands is done on a background thread. Derived
// classes call us to queue up incoming command strings. We put them on
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TBaseIRSrvDriver
// PREFIX: orbs
// ---------------------------------------------------------------------------
class CQCIREXPORT TBaseIRSrvDriver : public TCQCServerBase
{
public :
// -------------------------------------------------------------------
// COnstructors and destructor
// -------------------------------------------------------------------
TBaseIRSrvDriver(const TBaseIRSrvDriver&) = delete;
TBaseIRSrvDriver(TBaseIRSrvDriver&&) = delete;
~TBaseIRSrvDriver();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TBaseIRSrvDriver& operator=(const TBaseIRSrvDriver&) = delete;
TBaseIRSrvDriver& operator=(TBaseIRSrvDriver&&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bQueryData
(
const TString& strQType
, const TString& strDataName
, tCIDLib::TCard4& c4OutBytes
, THeapBuf& mbufToFill
) override;
tCIDLib::TBoolean bQueryData2
(
const TString& strQType
, tCIDLib::TCard4& c4IOBytes
, THeapBuf& mbufIO
) override;
tCIDLib::TBoolean bQueryTextVal
(
const TString& strQType
, const TString& strDataName
, TString& strToFill
) override;
tCIDLib::TBoolean bQueryVal
(
const TString& strValId
) override;
tCIDLib::TBoolean bSendData
(
const TString& strSendType
, TString& strDataName
, tCIDLib::TCard4& c4Bytes
, THeapBuf& mbufData
) override;
tCIDLib::TCard4 c4SendCmd
(
const TString& strCmdId
, const TString& strParms
) override;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TCh chSepChar() const;
const TIRBlasterCfg& irbcData() const;
const TIRReceiverCfg& irrcData() const;
protected :
// -------------------------------------------------------------------
// Hidden constructors and operators
// -------------------------------------------------------------------
TBaseIRSrvDriver
(
const TCQCDriverObjCfg& cqcdcToLoad
);
// -------------------------------------------------------------------
// Protected, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bWaitConfig
(
TThread& thrThis
) override;
tCQCKit::EDrvInitRes eInitializeImpl() override;
tCQCKit::ECommResults eStringFldValChanged
(
const TString& strName
, const tCIDLib::TCard4 c4FldId
, const TString& strNewValue
) override;
tCIDLib::TVoid TerminateImpl() override;
tCIDLib::TVoid VerboseModeChanged
(
const tCQCKit::EVerboseLvls eNewState
) override;
// -------------------------------------------------------------------
// Protected, virtual methods
// -------------------------------------------------------------------
// These are blaster specific
virtual tCIDLib::TBoolean bBlastTrainingMode() const;
virtual tCIDLib::TBoolean bCheckBlastTrainingData
(
tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill
);
virtual tCIDLib::TBoolean bCvtManualBlastData
(
const TString& strText
, tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill
, TString& strError
);
virtual tCIDLib::TBoolean bRecTrainingMode() const;
virtual tCIDLib::TCard4 c4ZoneCount() const;
virtual tCIDLib::TCard4 c4InvokeFldId() const;
virtual tCIDLib::TVoid ClearBlastTrainingData();
virtual tCIDLib::TVoid EnterBlastTrainingMode();
virtual tCIDLib::TVoid ExitBlastTrainingMode();
virtual tCIDLib::TVoid FormatBlastData
(
const TIRBlasterCmd& irbcFmt
, TString& strToFill
);
virtual tCIDLib::TVoid InvokeBlastCmd
(
const TString& strDevice
, const TString& strCmd
, const tCIDLib::TCard4 c4ZoneNum
);
virtual tCIDLib::TVoid SendBlasterData
(
const tCIDLib::TCard4 c4DataBytes
, const TMemBuf& mbufToSend
, const tCIDLib::TCard4 c4ZoneNum
, const tCIDLib::TCard4 c4RepeatCount
);
// These are receiver only
virtual tCIDLib::TBoolean bCheckRecTrainingData
(
TString& strKeyToFill
);
virtual tCIDLib::TVoid ClearRecTrainingData();
virtual tCIDLib::TVoid EnterRecTrainingMode();
virtual tCIDLib::TVoid ExitRecTrainingMode();
// These are common to blasters and receivers
virtual tCIDLib::TBoolean bResetConnection() = 0;
// -------------------------------------------------------------------
// Protected, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid ClearEventQ();
const TIRBlasterCmd& irbcFromName
(
const TString& strDevice
, const TString& strCmd
, tCIDLib::TCard4& c4RepeatCount
);
tCIDLib::TVoid QueueRecEvent
(
const TString& strEventName
);
tCIDLib::TVoid RegWithRebinder
(
const TOrbObjId& ooidSrvObject
, const TString& strNodePath
, const TString& strDescription
);
tCIDLib::TVoid SetKeySepChar
(
const tCIDLib::TCh chSepChar
);
tCIDLib::TVoid StartActionsThread();
tCIDLib::TVoid WaitForActions();
private :
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bFormatCmds
(
TString& strToFill
);
tCIDLib::TBoolean bIsRecKeyUsed
(
const TString& strKeyToCheck
, TString& strTitleToFill
);
tCIDLib::TBoolean bStoreRecTrainingData
(
const TCQCStdKeyedCmdSrc& csrcToStore
);
tCIDLib::TVoid DeleteAllEvents();
tCIDLib::TVoid DeleteRecEvent
(
const TString& strKeyToDelete
);
tCIDLib::TVoid LoadBlasterDevModel
(
const TString& strModelName
);
tCIDLib::TVoid QueryBlasterConfig
(
TVector<TIRBlasterDevModelInfo>& colList
, tCIDLib::TCard4& c4ZoneCountToFill
);
tCIDLib::TVoid QueryMappedRecEvents
(
TVector<TCQCStdKeyedCmdSrc>& colToFill
);
tCIDLib::TVoid StoreBlastConfig
(
const TIRBlasterPerData& perdToStore
);
tCIDLib::TVoid StoreRecCfg
(
const TIRReceiverCfg& irrcToStore
);
tCIDLib::TVoid ThrowUnknownId
(
const TString& strId
, const tCIDLib::TCh* const pszMethod
);
tCIDLib::TVoid UnloadBlasterDevModel
(
const TString& strModelName
);
// -------------------------------------------------------------------
// Private data members
//
// m_c4BlastCfgVerId
// The configuration repository version id for our blaster
// config data, if we have any.
//
// m_c4RecCfgVerId
// The configuration repository version id for our receiver
// config data, if we have any.
//
// m_chSepChar
// This defaults to a null character, but it can be set by derived
// classes. We'll use this to break incoming trigger strings into
// two parts. The part before the separator is the key to match
// with the actions. The part after is passed to the action as an
// action parameter for it to use as it wishes.
//
// m_colRecEventQ
// A queue into which receiver events are queued. The derived
// class calls us to queue them up, and our action thread pulls
// them off and processes them.
//
// m_enctNextRebindTime
// Used to periodically cycle the rebinder. We want to do it
// every five seconds, or thereabouts, since the rebinder
// is set up for that cycle time.
//
// m_eDevCaps
// The derived type gives us a set of capabilities flags in the
// ctor so that we know what he's capable of (and can pass that
// on to the client.)
//
// m_irbcData
// m_irrcData
// This is our runtime blaster and receiver config data.
//
// We don't persist the blaster data structure. We always go
// back to the data server at load time to get the files we
// need. So we run through this list and get the names of the
// device models out and put them into a temporary object and
// persist that. When we reload, we load up the temporary object
// and use it to load up the files and build this config data
// back up.
//
// The receiver data is just loaded and stored as is, and
// contains the list of mapped events we are to respond to.
//
// m_strRepoDescr
// The derived class gives us a short, human readable name for
// the blaster device, for display purposes. The client can ask
// for this for that reason.
//
// m_strRepoName
// The derived class gives us a repository name that we can
// use for loading IR models of his sort and whatnot.
//
// m_thrActions
// We need a thread that pulls actions out of the event queue
// and runs them, so that we can remain responsive to the other
// events coming in.
// -------------------------------------------------------------------
tCIDLib::TCard4 m_c4BlastCfgVerId;
tCIDLib::TCard4 m_c4RecCfgVerId;
tCIDLib::TCh m_chSepChar;
tCIDLib::TStringQ m_colRecEventQ;
tCIDLib::TEncodedTime m_enctNextRebindTime;
tCQCIR::EIRDevCaps m_eDevCaps;
TIRBlasterCfg m_irbcData;
TIRReceiverCfg m_irrcData;
TString m_strRepoDescr;
TString m_strRepoName;
TCQCIRActionsThread m_thrActions;
// -------------------------------------------------------------------
// Magic macros
// -------------------------------------------------------------------
RTTIDefs(TBaseIRSrvDriver,TCQCServerBase)
};
#pragma CIDLIB_POPPACK
| 34.864734 | 79 | 0.474712 | [
"object",
"model"
] |
73248e6cac0c5cffffac941e90d9aa6e6e65b38c | 6,588 | hpp | C++ | stapl_release/stapl/skeletons/functional/scatter.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/functional/scatter.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/functional/scatter.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_SKELETONS_FUNCTIONAL_SCATTER_HPP
#define STAPL_SKELETONS_FUNCTIONAL_SCATTER_HPP
#include <stapl/skeletons/utility/utility.hpp>
#include <stapl/algorithms/functional.hpp>
#include "reverse_binary_tree.hpp"
namespace stapl {
namespace skeletons {
namespace skeletons_impl {
namespace scatter_impl {
//////////////////////////////////////////////////////////////////////
/// @brief A scatter skeleton based on @c reverse_binary_tree is
/// a no-op. The filtering of the input to this operation is done
/// with the help of filters to reduce communication.
//////////////////////////////////////////////////////////////////////
template <typename T>
struct scatter_op
: public stapl::identity<std::vector<T>>
{
void set_position(std::size_t index, bool is_downedge) { }
};
//////////////////////////////////////////////////////////////////////
/// @brief Filters the inputs in scatter tree into two halves. If the
/// edge requesting the value from this filter is a downedge then
/// the upper half of the input is returned. If not, the lower-half is
/// returned
///
/// @tparam T the value type of the elements being scattered
//////////////////////////////////////////////////////////////////////
template <typename T>
struct scatter_filter
{
using result_type = std::vector<T>;
private:
bool m_is_downedge;
public:
scatter_filter(void)
: m_is_downedge(false)
{ }
void set_position(std::size_t, bool is_downedge)
{
m_is_downedge = is_downedge;
}
template <typename V>
result_type operator()(V&& v) const
{
std::size_t size = v.size();
// first we find the point we would like to divide it in half. If size
// is a power of two, then it is easy. If not we group the first
// 2 * size % nearest_pow_two elements in pairs of two. For example,
// for 6 elements we would have
// o o o o o o -> (o o) (o o) o o
std::size_t half = size / 2;
//if it is not power of two
if (size != 0 and (size & (size-1)) != 0) {
std::size_t nearest_pow_2 = 1;
std::size_t n = size;
while (n != 1) {
nearest_pow_2 <<= 1;
n >>= 1;
}
std::size_t r = size - nearest_pow_2;
half = 2 * r;
}
auto&& begin_it = v.begin();
auto&& end_it = v.end();
if (m_is_downedge) {
std::advance(begin_it, half);
}
else {
end_it = begin_it;
std::advance(end_it, half);
}
return result_type(begin_it, end_it);
}
bool operator==(scatter_filter const& other) const
{
return m_is_downedge == other.m_is_downedge;
}
void define_type(typer& t)
{
t.member(m_is_downedge);
}
};
} // namespace scatter_impl
//////////////////////////////////////////////////////////////////////
/// @brief This class abstracts the semantics of a scatter skeleton
/// by exposing only the necessary information in its representation.
/// A scatter skeleton is simply a reverse binary tree with an operation
/// which splits the input into two halves.
///
/// This abstraction not only makes the reconstruction of a scatter
/// skeleton easier, but also provides access to the underlying
/// operation of a broadcast skeleton. Furthermore, it reduces the
/// symbol size for a scatter skeleton, hence, reducing the
/// total compilation time.
///
/// @tparam T the type of elements to be scattered
/// @tparam Span the iteration space for elements to be scattered
/// @tparam Tag determines the type of scatter
///
/// @ingroup skeletonsFunctionalInternal
//////////////////////////////////////////////////////////////////////
template <typename T, typename Span, typename Tag>
struct scatter
: public decltype(
skeletons::reverse_binary_tree<
false, Tag, stapl::use_default, Span, false, true
>(scatter_impl::scatter_op<T>(),
scatter_impl::scatter_filter<T>())
)
{
using skeleton_tag_type = tags::scatter<Tag>;
using base_type = decltype(
skeletons::reverse_binary_tree<
false, Tag, stapl::use_default, Span, false, true
>(scatter_impl::scatter_op<T>(),
scatter_impl::scatter_filter<T>()));
scatter(void)
: base_type(
skeletons::reverse_binary_tree<
false, Tag, stapl::use_default, Span, false, true
>(scatter_impl::scatter_op<T>(),
scatter_impl::scatter_filter<T>())
)
{ }
scatter_impl::scatter_op<T>
get_op(void) const
{
return base_type::get_op();
}
scatter_impl::scatter_filter<T>
get_filter(void) const
{
return base_type::get_filter();
}
};
} // namespace skeletons_impl
namespace result_of {
template <typename T,
typename Tag,
typename Span>
using scatter = skeletons_impl::scatter<
T, Span,
stapl::default_type<Tag, tags::left_aligned>>;
} // namespace result_of
//////////////////////////////////////////////////////////////////////
/// @brief This sink skeleton assumes a default span for the created
/// skeleton
///
/// @tparam T the type of elements to be copied
/// @param skeleton the skeleton to read the input from
/// @param dest_skeleton a customized sink skeleton. By default this
/// is assumed to be a copy skeleton
/// @return a sink skeleton with a customized destination skeleton
///
/// @see copy
///
/// @ingroup skeletonsFunctional
//////////////////////////////////////////////////////////////////////
template <typename T,
typename Tag = stapl::use_default,
typename Span = stapl::use_default>
result_of::scatter<T, Tag, Span>
scatter(void)
{
static_assert(std::is_same<Tag, stapl::use_default>::value ||
std::is_same<Tag, tags::left_aligned>::value ||
std::is_same<Tag, tags::right_aligned>::value ||
std::is_same<Tag, tags::left_skewed>::value,
"The supported types of scatter are left_aligned, "
"right_aligned, and left_skewed");
return result_of::scatter<T, Tag, Span>();
}
} // namespace skeletons
} // namespace stapl
#endif // STAPL_SKELETONS_FUNCTIONAL_SCATTER_HPP
| 30.082192 | 74 | 0.601548 | [
"vector"
] |
7329c247854679f3dbc12620e75f0b7c02503a54 | 11,561 | cc | C++ | mace/benchmark/statistics.cc | lee-bin/mace | aca4c5e2a3496cca955d45460eb976fe765d6f14 | [
"Apache-2.0"
] | 1 | 2018-12-20T07:09:05.000Z | 2018-12-20T07:09:05.000Z | mace/benchmark/statistics.cc | 13266828291/mace | 021dbc5b40e3f1be7466eb72e37c11ac391166bf | [
"Apache-2.0"
] | null | null | null | mace/benchmark/statistics.cc | 13266828291/mace | 021dbc5b40e3f1be7466eb72e37c11ac391166bf | [
"Apache-2.0"
] | 1 | 2019-06-26T11:07:29.000Z | 2019-06-26T11:07:29.000Z | // Copyright 2018 Xiaomi, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <functional>
#include <set>
#include "mace/benchmark/statistics.h"
#include "mace/utils/logging.h"
#include "mace/utils/string_util.h"
namespace mace {
namespace benchmark {
namespace {
std::string MetricToString(const Metric metric) {
switch (metric) {
case NAME:
return "Name";
case RUN_ORDER:
return "Run Order";
case COMPUTATION_TIME:
return "Computation Time";
default:
return "";
}
}
std::string PaddingTypeToString(int padding_type) {
std::stringstream stream;
switch (padding_type) {
case 0: stream << "VALID"; break;
case 1: stream << "SAME"; break;
case 2: stream << "FULL"; break;
default: stream << padding_type; break;
}
return stream.str();
}
std::string ShapeToString(
const std::vector<std::vector<int64_t>> &output_shape) {
if (output_shape.empty()) {
return "";
}
std::stringstream stream;
stream << "[";
for (size_t i = 0; i < output_shape.size(); ++i) {
size_t dims_size = output_shape[i].size();
for (size_t j = 0; j < dims_size; ++j) {
stream << output_shape[i][j];
if (j != dims_size - 1) {
stream << ",";
}
}
if (i != output_shape.size() - 1) {
stream << ":";
}
}
stream << "]";
return stream.str();
}
template <typename T>
std::string VectorToString(const std::vector<T> &vec) {
if (vec.empty()) {
return "";
}
std::stringstream stream;
stream << "[";
for (size_t i = 0; i < vec.size(); ++i) {
stream << vec[i];
if (i != vec.size() - 1) {
stream << ",";
}
}
stream << "]";
return stream.str();
}
} // namespace
int64_t StatMACs(const std::string &op_type,
const std::vector<int64_t> &filter_shape,
const std::vector<int64_t> &output_shape) {
int64_t macs = 0;
if (op_type == "Conv2D" || op_type == "Deconv2D") {
macs = output_shape[0] * output_shape[1] * output_shape[2]
* output_shape[3]
* filter_shape[2] * filter_shape[3] * filter_shape[1];
} else if (op_type == "MatMul") {
macs = std::accumulate(output_shape.begin(),
output_shape.end(),
1,
std::multiplies<int64_t>())
* filter_shape.back();
} else if (op_type == "DepthwiseConv2d") {
macs = output_shape[0] * output_shape[1] * output_shape[2]
* output_shape[3] * filter_shape[0] * filter_shape[2] * filter_shape[3];
} else if (op_type == "DepthwiseDeconv2d") {
macs = output_shape[0] * output_shape[1] * output_shape[2]
* output_shape[3] * filter_shape[2] * filter_shape[3];
} else if (op_type == "FullyConnected") {
macs = output_shape[0] * std::accumulate(filter_shape.begin(),
filter_shape.end(),
1,
std::multiplies<int64_t>());
} else if (op_type == "BatchNorm") {
macs = std::accumulate(output_shape.begin(),
output_shape.end(),
1,
std::multiplies<int64_t>());
} else if (op_type == "ResizeBilinear" || op_type == "ResizeBicubic") {
macs = 3 * std::accumulate(output_shape.begin(),
output_shape.end(),
1,
std::multiplies<int64_t>());
}
return macs;
}
void OpStat::StatMetadata(const RunMetadata &meta_data) {
if (meta_data.op_stats.empty()) {
LOG(FATAL) << "Op metadata should not be empty";
}
int64_t order_idx = 0;
int64_t total_time = 0;
const int64_t first_op_start_time = meta_data.op_stats[0].stats.start_micros;
for (auto &op_stat : meta_data.op_stats) {
auto result = records_.emplace(op_stat.operator_name, Record());
Record *record = &(result.first->second);
if (result.second) {
record->name = op_stat.operator_name;
record->type = op_stat.type;
record->args = op_stat.args;
record->output_shape = op_stat.output_shape;
record->macs =
StatMACs(op_stat.type, op_stat.args.kernels, op_stat.output_shape[0]);
record->order = order_idx;
order_idx += 1;
}
record->start.UpdateTime(op_stat.stats.start_micros - first_op_start_time);
int64_t run_time = op_stat.stats.end_micros - op_stat.stats.start_micros;
record->rel_end.UpdateTime(run_time);
record->called_times += 1;
total_time += run_time;
}
total_time_.UpdateTime(total_time);
}
std::string OpStat::StatByMetric(const Metric metric,
const int top_limit) const {
if (records_.empty()) {
return "";
}
// sort
std::vector<Record> records;
for (auto &record : records_) {
records.push_back(record.second);
}
std::sort(records.begin(), records.end(),
[=](const Record &lhs, const Record &rhs) {
if (metric == RUN_ORDER) {
return lhs.order < rhs.order;
} else if (metric == NAME) {
return lhs.name.compare(rhs.name) < 0;
} else {
return lhs.rel_end.avg() > rhs.rel_end.avg();
}
});
// generate string
std::string title = "Sort by " + MetricToString(metric);
const std::vector<std::string> header = {
"Op Type", "Start", "First", "Avg(ms)", "%", "cdf%", "GMACPS",
"Stride", "Pad", "Filter Shape", "Output Shape", "Dilation", "name"
};
std::vector<std::vector<std::string>> data;
int count = std::min(top_limit, static_cast<int>(records.size()));
if (top_limit <= 0) count = static_cast<int>(records.size());
int64_t accumulate_time = 0;
for (int i = 0; i < count; ++i) {
Record &record = records[i];
accumulate_time += record.rel_end.sum();
std::vector<std::string> tuple;
tuple.push_back(record.type);
tuple.push_back(FloatToString(record.start.avg() / 1000.0f, 3));
tuple.push_back(FloatToString(record.rel_end.first() / 1000.0f, 3));
tuple.push_back(FloatToString(record.rel_end.avg() / 1000.0f, 3));
tuple.push_back(
FloatToString(record.rel_end.sum() * 100.f / total_time_.sum(), 3));
tuple.push_back(
FloatToString(accumulate_time * 100.f / total_time_.sum(), 3));
tuple.push_back(FloatToString(
record.macs < 1e-6 ? record.macs :
(record.macs * 1e-3) / record.rel_end.avg(), 3));
tuple.push_back(VectorToString<int>(record.args.strides));
if (record.args.padding_type != -1) {
tuple.push_back(PaddingTypeToString(record.args.padding_type));
} else {
tuple.push_back(VectorToString<int>(record.args.paddings));
}
tuple.push_back(VectorToString<int64_t>(record.args.kernels));
tuple.push_back(ShapeToString(record.output_shape));
tuple.push_back(VectorToString<int>(record.args.dilations));
tuple.push_back(record.name);
data.emplace_back(tuple);
}
return mace::string_util::StringFormatter::Table(title, header, data);
}
std::string OpStat::StatByOpType() const {
if (records_.empty()) {
return "";
}
const int64_t round = total_time_.round();
int64_t total_time = 0;
std::map<std::string, int64_t> type_time_map;
std::map<std::string, int64_t> type_macs_map;
std::map<std::string, int64_t> type_count_map;
std::map<std::string, int64_t> type_called_times_map;
std::set<std::string> op_types_set;
for (auto &record : records_) {
std::string op_type = record.second.type;
op_types_set.insert(op_type);
type_time_map[op_type] += record.second.rel_end.sum() / round;
type_macs_map[op_type] += record.second.macs;
total_time += record.second.rel_end.sum() / round;
type_count_map[op_type] += 1;
type_called_times_map[op_type] += record.second.called_times / round;
}
std::vector<std::string> op_types(op_types_set.begin(),
op_types_set.end());
std::sort(op_types.begin(), op_types.end(),
[&](const std::string &lhs, const std::string &rhs) {
return type_time_map[lhs] > type_time_map[rhs];
});
std::string title = "Stat by Op Type";
const std::vector<std::string> header = {
"Op Type", "Count", "Avg(ms)", "%", "cdf%", "MACs",
"GMACPS", "Called times"
};
float cdf = 0.0f;
std::vector<std::vector<std::string>> data;
for (auto type : op_types) {
const float avg_time = type_time_map[type] / 1000.0f;
const float percentage = type_time_map[type] * 100.0f / total_time;
cdf += percentage;
std::vector<std::string> tuple;
tuple.push_back(type);
tuple.push_back(IntToString(type_count_map[type]));
tuple.push_back(FloatToString(avg_time, 3));
tuple.push_back(FloatToString(percentage, 3));
tuple.push_back(FloatToString(cdf, 3));
tuple.push_back(IntToString(type_macs_map[type]));
tuple.push_back(FloatToString(
type_macs_map[type] < 1e-6 ? type_macs_map[type] :
(type_macs_map[type] * 1e-3) / type_time_map[type], 3));
tuple.push_back(IntToString(type_called_times_map[type]));
data.emplace_back(tuple);
}
return mace::string_util::StringFormatter::Table(title, header, data);
}
std::string OpStat::StatByMACs() const {
if (records_.empty()) {
return "";
}
const int64_t round = total_time_.round();
int64_t count = 0;
for (auto &record : records_) {
count += record.second.macs;
}
std::string title = "Stat by MACs(Multiply-Accumulation)";
const std::vector<std::string> header = {
"total", "round", "first(G/s)", "avg(G/s)", "std"
};
std::vector<std::vector<std::string>> data;
std::vector<std::string> tuple;
tuple.push_back(IntToString(count));
tuple.push_back(IntToString(round));
tuple.push_back(FloatToString((count * 1e-3) / total_time_.first(), 3));
tuple.push_back(FloatToString((count * 1e-3) / total_time_.avg(), 3));
tuple.push_back(FloatToString(total_time_.std_deviation(), 3));
data.emplace_back(tuple);
return mace::string_util::StringFormatter::Table(title, header, data);
}
std::string OpStat::Summary() const {
std::stringstream stream;
if (!records_.empty()) {
stream << total_time_.ToString("Summary of Ops' Stat") << std::endl;
}
stream << records_.size() << " ops total." << std::endl;
return stream.str();
}
void OpStat::PrintStat() const {
std::stringstream stream;
if (!records_.empty()) {
// op stat by run order
stream << StatByMetric(Metric::RUN_ORDER, 0) << std::endl;
// top-10 op stat by time
stream << StatByMetric(Metric::COMPUTATION_TIME, 10) << std::endl;
// op stat by op type
stream << StatByOpType() << std::endl;
}
// print MACs statistics
stream << StatByMACs();
// Print summary
stream << Summary();
for (std::string line; std::getline(stream, line);) {
LOG(INFO) << line;
}
}
} // namespace benchmark
} // namespace mace
| 33.126074 | 80 | 0.619929 | [
"shape",
"vector"
] |
732b765b8845c9001bc3381b9bc61d38accf3396 | 2,761 | hpp | C++ | chipsum/solver/bicg.hpp | ChipSum-Group/ChipSum | 010656f6bcb5d95ece615425172b0d5f83cbc485 | [
"MIT"
] | 1 | 2022-03-30T01:53:08.000Z | 2022-03-30T01:53:08.000Z | chipsum/solver/bicg.hpp | ChipSum-Group/ChipSum | 010656f6bcb5d95ece615425172b0d5f83cbc485 | [
"MIT"
] | 1 | 2022-03-28T02:33:00.000Z | 2022-03-28T02:33:00.000Z | chipsum/solver/bicg.hpp | ChipSum-Group/ChipSum | 010656f6bcb5d95ece615425172b0d5f83cbc485 | [
"MIT"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * *
* File: bicg.cpp
* Author: Yaojie Yu
* group: CDCS-HPC
* Time: 2022-06-07
* * * * * * * * * * * * * * * * * * * * * */
#include "../../ChipSum.hpp"
#include "../chipsum_macro.h"
namespace ChipSum {
namespace Solver {
CSVector bicg(CSR &A, CSVector &b, CSVector &x, CSFloat tol, int max_it)
{
// BiConjugate Gradient Method without preconditioning.
//
// input A REAL matrix
// x REAL initial guess vector
// b REAL right hand side vector
// tol REAL error tolerance
// max_it INTEGER maximum number of iterations
//
// output x REAL solution vector
CSFloat bnrm2 = b.Norm2();
if (bnrm2 == 0.0)
bnrm2 = 1.0;
CSVector r(x.GetSize());
A.SPMV(x, r);
b.AXPBY(r, 1.0, -1.0); // r = b - A*x
CSFloat error = r.Norm2() / bnrm2;
if (error < tol)
return x;
CSVector r_tld(x.GetSize());
r_tld.DeepCopy(r);
CSVector p(x.GetSize()), p_tld(x.GetSize());
CSVector z(x.GetSize()), z_tld(x.GetSize());
CSVector q(x.GetSize()), q_tld(x.GetSize());
CSFloat alpha, beta, rho, rho_1;
for (int i = 0; i < max_it; i++)
{
// z = M.inverse() *r; M is a precondtioner, here M is a identity matrix
// z_tld = M'.inverse() *r_tld; M is a precondtioner
z.DeepCopy(r);
z_tld.DeepCopy(r_tld);
rho = r.Dot(z_tld);
if (rho == 0.0)
break;
if (i > 0)
{
beta = rho / rho_1;
z.AXPBY(p, 1.0, beta); // p = z + beta * p;
z_tld.AXPBY(p_tld, 1.0, beta); // p_tld = z_tld + beta * p_tld;
}
else
{
p.DeepCopy(z); // p = z
p_tld.DeepCopy(z_tld); // p_tld = z_tld
}
A.SPMV(p, q); // q = A*p
A.SPMV(p_tld, q_tld); // q_tld = A'x, but here A is symmetry
alpha = rho / (p_tld.Dot(q));
p.AXPBY(x, alpha, 1.0); // x = x + alpha * p;
q.AXPBY(r, -alpha, 1.0); // r = r - alpha * Ap
q_tld.AXPBY(r_tld, -alpha, 1.0); // r_tld = r_tld - alpha * q_tld
error = r.Norm2() / bnrm2;
printf("+++++++++++++++++++++++++++++++++++++++++++\n");
printf("step # %d\n", i + 1);
printf("residual : %.7f\n", error);
if (error <= tol)
break;
CSVector r_temp(b.GetSize());
A.SPMV(x, r_temp); /* r_temp = A*x */
b.AXPBY(r_temp, 1.0, -1.0); /* r_temp = b-r_temp */
rho_1 = rho;
}
printf("+++++++++++++++++++++++++++++++++++++++++++\n");
return x;
}
} // End namespace Solver
} // End namespace ChipSum | 27.61 | 80 | 0.45527 | [
"vector"
] |
732cb99ef2284cfa6474c0d08bc6558d18cc696f | 6,932 | cpp | C++ | src/victim_thermal_detector_node.cpp | kuri-kustar/victim_localization | b5b0b8f2915d9805372a1d8c4809991b6d63c1b5 | [
"BSD-3-Clause"
] | 1 | 2020-03-29T08:00:24.000Z | 2020-03-29T08:00:24.000Z | src/victim_thermal_detector_node.cpp | kuri-kustar/victim_localization | b5b0b8f2915d9805372a1d8c4809991b6d63c1b5 | [
"BSD-3-Clause"
] | null | null | null | src/victim_thermal_detector_node.cpp | kuri-kustar/victim_localization | b5b0b8f2915d9805372a1d8c4809991b6d63c1b5 | [
"BSD-3-Clause"
] | 1 | 2020-03-29T08:00:24.000Z | 2020-03-29T08:00:24.000Z | #include "victim_localization/victim_thermal_detector_node.h"
victim_thermal_detector::victim_thermal_detector(ros::NodeHandle &nh_, ros::NodeHandle &pnh_)
{
ros::param::param<double>("~min_Dist_Between_Blobs", minDistBetweenBlobs_ , 40.0);
ros::param::param<double>("~thermal_min_Area_Victim", minAreaVictim_ , 40.0);
std::string Thermal_topic;
// XmlRpc::XmlRpcValue filters;
// std::cout << "Node Space... " << ros::this_node::getNamespace() << std::endl;
// pnh_.getParam("/thermalVictim/home/filter", filters);
// ROS_ASSERT(filters.getType() == XmlRpc::XmlRpcValue::TypeStruct);
// for(XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = filters.begin(); it != filters.end(); ++it) {
// ROS_INFO_STREAM("Found filter: " << (std::string)(it->first) << " ==> " << filters[it->first]);
// // Do stuff with filters:
// ROS_INFO_STREAM("filter_cascade_1: in: " << filters[it->first]["in"]);
// ROS_INFO_STREAM("filter_cascade_1: filter: first_applied_filter: config_for_filter_1: " << filters[it->first]["filter"]["first_applied_filter"][0]);
// }
XmlRpc::XmlRpcValue param;
nh_.getParam(ros::this_node::getName()+"/pc", param);
ROS_ASSERT(param.getType() == XmlRpc::XmlRpcValue::TypeStruct);
//XmlRpc::XmlRpcValue::ValueStruct::const_iterator it = param.begin();
std::cout << param.getType() << std::endl;
std::cout << param[std::to_string(0)]["pc1"] << std::endl;
// std::cout << param["topic3"]["pc2"] << std::endl;
//nh_.setParam("/COCOC",param["pc2"]);
// std::map<std::string,std::string> map_s;
// pnh_.getParam("my_string_map", map_s);
// std::cout << map_s[0]<< std::endl;
ros::param::param<std::string>("/thermalVictim/Thermal_topic",Thermal_topic,
"thermal_cam/image_raw");
image_transport::ImageTransport it(nh_);
image_transport::ImageTransport p_it(pnh_);
sub_image = it.subscribe(Thermal_topic, 1, &victim_thermal_detector::imageCallback,this);
std::cout << sub_image.getTopic() << std::endl;
pub_detection_ = it.advertise("image_detection1", 10);
}
victim_thermal_detector::~victim_thermal_detector(){}
void victim_thermal_detector::imageCallback(const sensor_msgs::ImageConstPtr& img){
cv_bridge::CvImageConstPtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvShare(img, sensor_msgs::image_encodings::MONO8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat img_proc(cv_ptr->image);
cv::Mat threshold_image;
cv::threshold(img_proc,threshold_image,250,255,cv::THRESH_BINARY);
//Perform blob detection
cv::SimpleBlobDetector::Params params;
params.filterByColor = true;
params.blobColor = 255;
params.minDistBetweenBlobs = minDistBetweenBlobs_;
params.filterByArea = true;
params.minArea = minAreaVictim_;
params.maxArea = threshold_image.rows * threshold_image.cols;
params.filterByCircularity = false;
params.filterByColor = false;
params.filterByConvexity = false;
params.filterByInertia = false;
cv::Ptr<cv::SimpleBlobDetector> blob_detector = cv::SimpleBlobDetector::create(params);
std::vector<cv::KeyPoint> keypoints;
blob_detector->detect(threshold_image,keypoints);
victim_loc.clear();
for(unsigned int i=0; i<keypoints.size();i++)
{
cv::KeyPoint k = keypoints.at(i);
std::cout << "blob found at (x,y)= " << k.pt.x << "," << k.pt.y << std::endl;
ROS_DEBUG("Heat blob found at image coord: (%f, %f)", k.pt.x , k.pt.y);
// ROS_DEBUG("Heat blob numer: %f", keypoints.size());
cv::Rect rect_image(0, 0, threshold_image.cols, threshold_image.rows);
cv::Rect rect_roi(k.pt.x - (k.size - 1)/2, k.pt.y - (k.size - 1)/2, k.size - 1, k.size - 1);
//See http://stackoverflow.com/questions/29120231/how-to-verify-if-rect-is-inside-cvmat-in-opencv
bool is_inside = (rect_roi & rect_image) == rect_roi;
if (!is_inside){
ROS_ERROR("ROI image would be partly outside image border, aborting further processing!");
continue;
}
const cv::Mat roi = threshold_image(rect_roi);
int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
cv::Mat hist;
cv::calcHist(&roi, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, true, false);
geometry_msgs::Point p;
p.x=k.pt.x;
p.y=k.pt.y;
victim_loc.push_back(p);
}
if (keypoints.size() == 0) {
std::cout << "No blob detected" << std::endl;
}
if(pub_detection_.getNumSubscribers() > 0){
//Create image with detection frames
int width = 3;
int height = 3;
IplImage ipl_img = img_proc;
//Display Keypoints
for(unsigned int i = 0; i < keypoints.size(); i++){
if (keypoints.at(i).size > 1){
//Write rectangle into image
width = (int)(keypoints.at(i).size );
height = (int)(keypoints.at(i).size );
for(int j = -width; j <= width;j++){
if ((keypoints.at(i).pt.x + j) >= 0 && (keypoints.at(i).pt.x + j) < ipl_img.width){
//Draw upper line
if ((keypoints.at(i).pt.y - height) >= 0){
cvSet2D(&ipl_img,(int)(keypoints.at(i).pt.y - height), (int)(keypoints.at(i).pt.x + j),cv::Scalar(0));
}
//Draw lower line
if ((keypoints.at(i).pt.y + height) < ipl_img.height){
cvSet2D(&ipl_img,(int)(keypoints.at(i).pt.y + height), (int)(keypoints.at(i).pt.x + j),cv::Scalar(0));
}
}
}
for(int k = -height; k <= height;k++){
if ((keypoints.at(i).pt.y + k) >= 0 && (keypoints.at(i).pt.y + k) < ipl_img.height){
//Draw left line
if ((keypoints.at(i).pt.x - width) >= 0){
cvSet2D(&ipl_img,(int)(keypoints.at(i).pt.y +k), (int)(keypoints.at(i).pt.x - width),cv::Scalar(0));
}
//Draw right line
if ((keypoints.at(i).pt.x + width) < ipl_img.width){
cvSet2D(&ipl_img,(int)(keypoints.at(i).pt.y +k), (int)(keypoints.at(i).pt.x + width),cv::Scalar(0));
}
}
}
}
}
cv_bridge::CvImage cvImg;
cvImg.image = img_proc;
cvImg.header = img->header;
cvImg.encoding = sensor_msgs::image_encodings::MONO8;
pub_detection_.publish(cvImg.toImageMsg());
}
}
std::vector<geometry_msgs::Point> victim_thermal_detector::GetDetectionResult(){
return victim_loc;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "Heat_detection");
ros::NodeHandle nh_;
ros::NodeHandle pnh_;
victim_thermal_detector *hd;
hd= new victim_thermal_detector(nh_, pnh_);
ros::spin();
return 0;
}
| 37.47027 | 155 | 0.605597 | [
"vector"
] |
732db274d47ef232142a96c61f25cb8771de83bb | 12,299 | cpp | C++ | mptrack/HTTP.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 335 | 2017-02-25T16:39:27.000Z | 2022-03-29T17:45:42.000Z | mptrack/HTTP.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 7 | 2018-02-05T18:22:38.000Z | 2022-02-15T19:35:24.000Z | mptrack/HTTP.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 69 | 2017-04-10T00:48:09.000Z | 2022-03-20T10:24:45.000Z | /*
* HTTP.cpp
* --------
* Purpose: Simple HTTP client interface.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "HTTP.h"
#include "mpt/system_error/system_error.hpp"
#include <WinInet.h>
#include "mpt/io/io.hpp"
#include "mpt/io/io_stdstream.hpp"
OPENMPT_NAMESPACE_BEGIN
URI ParseURI(mpt::ustring str)
{
URI uri;
std::size_t scheme_delim_pos = str.find(':');
if(scheme_delim_pos == mpt::ustring::npos)
{
throw bad_uri("no scheme delimiter");
}
if(scheme_delim_pos == 0)
{
throw bad_uri("no scheme");
}
uri.scheme = str.substr(0, scheme_delim_pos);
str = str.substr(scheme_delim_pos + 1);
if(str.substr(0, 2) == U_("//"))
{
str = str.substr(2);
std::size_t authority_delim_pos = str.find_first_of(U_("/?#"));
mpt::ustring authority = str.substr(0, authority_delim_pos);
std::size_t userinfo_delim_pos = authority.find(U_("@"));
if(userinfo_delim_pos != mpt::ustring::npos)
{
mpt::ustring userinfo = authority.substr(0, userinfo_delim_pos);
authority = authority.substr(userinfo_delim_pos + 1);
std::size_t username_delim_pos = userinfo.find(U_(":"));
uri.username = userinfo.substr(0, username_delim_pos);
if(username_delim_pos != mpt::ustring::npos)
{
uri.password = userinfo.substr(username_delim_pos + 1);
}
}
std::size_t beg_bracket_pos = authority.find(U_("["));
std::size_t end_bracket_pos = authority.find(U_("]"));
std::size_t port_delim_pos = authority.find_last_of(U_(":"));
if(beg_bracket_pos != mpt::ustring::npos && end_bracket_pos != mpt::ustring::npos)
{
if(port_delim_pos != mpt::ustring::npos && port_delim_pos > end_bracket_pos)
{
uri.host = authority.substr(0, port_delim_pos);
uri.port = authority.substr(port_delim_pos + 1);
} else
{
uri.host = authority;
}
} else
{
uri.host = authority.substr(0, port_delim_pos);
if(port_delim_pos != mpt::ustring::npos)
{
uri.port = authority.substr(port_delim_pos + 1);
}
}
if(authority_delim_pos != mpt::ustring::npos)
{
str = str.substr(authority_delim_pos);
} else
{
str = U_("");
}
}
std::size_t path_delim_pos = str.find_first_of(U_("?#"));
uri.path = str.substr(0, path_delim_pos);
if(path_delim_pos != mpt::ustring::npos)
{
str = str.substr(path_delim_pos);
std::size_t query_delim_pos = str.find(U_("#"));
if(query_delim_pos != mpt::ustring::npos)
{
if(query_delim_pos > 0)
{
uri.query = str.substr(1, query_delim_pos - 1);
uri.fragment = str.substr(query_delim_pos + 1);
} else
{
uri.fragment = str.substr(query_delim_pos + 1);
}
} else
{
uri.query = str.substr(1);
}
}
return uri;
}
namespace HTTP
{
exception::exception(const mpt::ustring &m)
: std::runtime_error(std::string("HTTP error: ") + mpt::ToCharset(mpt::CharsetException, m))
{
message = m;
}
mpt::ustring exception::GetMessage() const
{
return message;
}
class LastErrorException
: public exception
{
public:
LastErrorException()
: exception(mpt::windows::GetErrorMessage(GetLastError(), GetModuleHandle(TEXT("wininet.dll"))))
{
}
};
struct NativeHandle
{
HINTERNET native_handle;
NativeHandle(HINTERNET h)
: native_handle(h)
{
}
operator HINTERNET() const
{
return native_handle;
}
};
Handle::Handle()
: handle(std::make_unique<NativeHandle>(HINTERNET(NULL)))
{
}
Handle::operator bool() const
{
return handle->native_handle != HINTERNET(NULL);
}
bool Handle::operator!() const
{
return handle->native_handle == HINTERNET(NULL);
}
Handle::Handle(NativeHandle h)
: handle(std::make_unique<NativeHandle>(HINTERNET(NULL)))
{
handle->native_handle = h.native_handle;
}
Handle & Handle::operator=(NativeHandle h)
{
if(handle->native_handle)
{
InternetCloseHandle(handle->native_handle);
handle->native_handle = HINTERNET(NULL);
}
handle->native_handle = h.native_handle;
return *this;
}
Handle::operator NativeHandle ()
{
return *handle;
}
Handle::~Handle()
{
if(handle->native_handle)
{
InternetCloseHandle(handle->native_handle);
handle->native_handle = HINTERNET(NULL);
}
}
InternetSession::InternetSession(mpt::ustring userAgent)
{
internet = NativeHandle(InternetOpen(mpt::ToWin(userAgent).c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0));
if(!internet)
{
throw HTTP::LastErrorException();
}
}
InternetSession::operator NativeHandle ()
{
return internet;
}
static mpt::winstring Verb(Method method)
{
mpt::winstring result;
switch(method)
{
case Method::Get:
result = _T("GET");
break;
case Method::Head:
result = _T("HEAD");
break;
case Method::Post:
result = _T("POST");
break;
case Method::Put:
result = _T("PUT");
break;
case Method::Delete:
result = _T("DELETE");
break;
case Method::Trace:
result = _T("TRACE");
break;
case Method::Options:
result = _T("OPTIONS");
break;
case Method::Connect:
result = _T("CONNECT");
break;
case Method::Patch:
result = _T("PATCH");
break;
}
return result;
}
static bool IsCachable(Method method)
{
return method == Method::Get || method == Method::Head;
}
namespace
{
class AcceptMimeTypesWrapper
{
private:
std::vector<mpt::winstring> strings;
std::vector<LPCTSTR> array;
public:
AcceptMimeTypesWrapper(AcceptMimeTypes acceptMimeTypes)
{
for(const auto &mimeType : acceptMimeTypes)
{
strings.push_back(mpt::ToWin(mpt::Charset::ASCII, mimeType));
}
array.resize(strings.size() + 1);
for(std::size_t i = 0; i < strings.size(); ++i)
{
array[i] = strings[i].c_str();
}
array[strings.size()] = NULL;
}
operator LPCTSTR*()
{
return strings.empty() ? NULL : array.data();
}
};
}
void Request::progress(Progress progress, uint64 transferred, std::optional<uint64> expectedSize) const
{
if(progressCallback)
{
progressCallback(progress, transferred, expectedSize);
}
}
Result Request::operator()(InternetSession &internet) const
{
progress(Progress::Start, 0, std::nullopt);
Port actualPort = port;
if(actualPort == Port::Default)
{
actualPort = (protocol != Protocol::HTTP) ? Port::HTTPS : Port::HTTP;
}
Handle connection = NativeHandle(InternetConnect(
NativeHandle(internet),
mpt::ToWin(host).c_str(),
static_cast<uint16>(actualPort),
!username.empty() ? mpt::ToWin(username).c_str() : NULL,
!password.empty() ? mpt::ToWin(password).c_str() : NULL,
INTERNET_SERVICE_HTTP,
0,
0));
if(!connection)
{
throw HTTP::LastErrorException();
}
progress(Progress::ConnectionEstablished, 0, std::nullopt);
mpt::ustring queryPath = path;
if(!query.empty())
{
std::vector<mpt::ustring> arguments;
for(const auto &[key, value] : query)
{
if(!value.empty())
{
arguments.push_back(MPT_UFORMAT("{}={}")(key, value));
} else
{
arguments.push_back(MPT_UFORMAT("{}")(key));
}
}
queryPath += U_("?") + mpt::String::Combine(arguments, U_("&"));
}
Handle request = NativeHandle(HttpOpenRequest(
NativeHandle(connection),
Verb(method).c_str(),
mpt::ToWin(path).c_str(),
NULL,
!referrer.empty() ? mpt::ToWin(referrer).c_str() : NULL,
AcceptMimeTypesWrapper(acceptMimeTypes),
0
| ((protocol != Protocol::HTTP) ? INTERNET_FLAG_SECURE : 0)
| (IsCachable(method) ? 0 : INTERNET_FLAG_NO_CACHE_WRITE)
| ((flags & NoCache) ? (INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE) : 0)
| ((flags & AutoRedirect) ? 0 : INTERNET_FLAG_NO_AUTO_REDIRECT)
,
NULL));
if(!request)
{
throw HTTP::LastErrorException();
}
progress(Progress::RequestOpened, 0, std::nullopt);
{
std::string headersString;
if(!dataMimeType.empty())
{
headersString += MPT_AFORMAT("Content-type: {}\r\n")(dataMimeType);
}
if(!headers.empty())
{
for(const auto &[key, value] : headers)
{
headersString += MPT_AFORMAT("{}: {}\r\n")(key, value);
}
}
if(HttpSendRequest(
NativeHandle(request),
!headersString.empty() ? mpt::ToWin(mpt::Charset::ASCII, headersString).c_str() : NULL,
!headersString.empty() ? mpt::saturate_cast<DWORD>(mpt::ToWin(mpt::Charset::ASCII, headersString).length()) : 0,
!data.empty() ? (LPVOID)data.data() : NULL,
!data.empty() ? mpt::saturate_cast<DWORD>(data.size()) : 0)
== FALSE)
{
throw HTTP::LastErrorException();
}
}
progress(Progress::RequestSent, 0, std::nullopt);
Result result;
{
DWORD statusCode = 0;
DWORD length = sizeof(statusCode);
if(HttpQueryInfo(NativeHandle(request), HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &length, NULL) == FALSE)
{
throw HTTP::LastErrorException();
}
result.Status = statusCode;
}
progress(Progress::ResponseReceived, 0, std::nullopt);
DWORD contentLength = static_cast<DWORD>(-1);
{
DWORD length = sizeof(contentLength);
if(HttpQueryInfo(NativeHandle(request), HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &length, NULL) == FALSE)
{
contentLength = static_cast<DWORD>(-1);
}
}
uint64 transferred = 0;
if(contentLength != static_cast<DWORD>(-1))
{
result.ContentLength = contentLength;
}
std::optional<uint64> expectedSize = result.ContentLength;
progress(Progress::TransferBegin, transferred, expectedSize);
{
std::vector<std::byte> resultBuffer;
DWORD bytesRead = 0;
do
{
std::array<std::byte, mpt::IO::BUFFERSIZE_TINY> downloadBuffer;
DWORD availableSize = 0;
if(InternetQueryDataAvailable(NativeHandle(request), &availableSize, 0, NULL) == FALSE)
{
throw HTTP::LastErrorException();
}
availableSize = std::clamp(availableSize, DWORD(0), mpt::saturate_cast<DWORD>(mpt::IO::BUFFERSIZE_TINY));
if(InternetReadFile(NativeHandle(request), downloadBuffer.data(), availableSize, &bytesRead) == FALSE)
{
throw HTTP::LastErrorException();
}
if(outputStream)
{
if(!mpt::IO::WriteRaw(*outputStream, mpt::as_span(downloadBuffer).first(bytesRead)))
{
throw HTTP::exception(U_("Writing output file failed."));
}
} else
{
mpt::append(resultBuffer, downloadBuffer.data(), downloadBuffer.data() + bytesRead);
}
transferred += bytesRead;
progress(Progress::TransferRunning, transferred, expectedSize);
} while(bytesRead != 0);
result.Data = std::move(resultBuffer);
}
progress(Progress::TransferDone, transferred, expectedSize);
return result;
}
Request &Request::SetURI(const URI &uri)
{
if(uri.scheme == U_(""))
{
throw bad_uri("no scheme");
} else if(uri.scheme == U_("http"))
{
protocol = HTTP::Protocol::HTTP;
} else if(uri.scheme == U_("https"))
{
protocol = HTTP::Protocol::HTTPS;
} else
{
throw bad_uri("wrong scheme");
}
host = uri.host;
if(!uri.port.empty())
{
port = HTTP::Port(ConvertStrTo<uint16>(uri.port));
} else
{
port = HTTP::Port::Default;
}
username = uri.username;
password = uri.password;
if(uri.path.empty())
{
path = U_("/");
} else
{
path = uri.path;
}
query.clear();
auto keyvals = mpt::String::Split<mpt::ustring>(uri.query, U_("&"));
for(const auto &keyval : keyvals)
{
std::size_t delim_pos = keyval.find(U_("="));
mpt::ustring key = keyval.substr(0, delim_pos);
mpt::ustring val;
if(delim_pos != mpt::ustring::npos)
{
val = keyval.substr(delim_pos + 1);
}
query.push_back(std::make_pair(key, val));
}
// ignore fragment
return *this;
}
#if defined(MPT_BUILD_RETRO)
Request &Request::InsecureTLSDowngradeWindowsXP()
{
if(mpt::OS::Windows::IsOriginal() && mpt::OS::Windows::Version::Current().IsBefore(mpt::OS::Windows::Version::WinVista))
{
// TLS 1.0 is not enabled by default until IE7. Since WinInet won't let us override this setting, we cannot assume that HTTPS
// is going to work on older systems. Besides... Windows XP is already enough of a security risk by itself. :P
if(protocol == Protocol::HTTPS)
{
protocol = Protocol::HTTP;
}
if(port == Port::HTTPS)
{
port = Port::HTTP;
}
}
return *this;
}
#endif // MPT_BUILD_RETRO
Result SimpleGet(InternetSession &internet, Protocol protocol, const mpt::ustring &host, const mpt::ustring &path)
{
HTTP::Request request;
request.protocol = protocol;
request.host = host;
request.method = HTTP::Method::Get;
request.path = path;
return internet(request);
}
} // namespace HTTP
OPENMPT_NAMESPACE_END
| 23.651923 | 134 | 0.679974 | [
"vector"
] |
732ecb0d38bd439781473b4c7ad6f01f8af8d68a | 924 | cpp | C++ | src/Section1/Combination Lock/combo.cpp | hwchiu/USACO | e82ffa309b6f1b183faf8c10d7760f479f542f6a | [
"Apache-2.0"
] | null | null | null | src/Section1/Combination Lock/combo.cpp | hwchiu/USACO | e82ffa309b6f1b183faf8c10d7760f479f542f6a | [
"Apache-2.0"
] | null | null | null | src/Section1/Combination Lock/combo.cpp | hwchiu/USACO | e82ffa309b6f1b183faf8c10d7760f479f542f6a | [
"Apache-2.0"
] | null | null | null | /*
ID: hwchiu1
PROG: combo
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
using namespace std;
int main() {
ofstream fout ("combo.out");
ifstream fin ("combo.in");
int N;
int farmer[3],master[3];
set<vector<int> >used;
fin >> N;
fin >> farmer[0] >> farmer[1] >> farmer[2];
fin >> master[0] >> master[1] >> master[2];
for(int i=-2 ; i <= 2; ++i) {
for(int j=-2; j<= 2; ++j) {
for(int k=-2; k<=2; ++k){
vector<int> combination;
combination.push_back((i+farmer[0]+N)%N);
combination.push_back((j+farmer[1]+N)%N);
combination.push_back((k+farmer[2]+N)%N);
used.insert(combination);
combination.clear();
combination.push_back((i+master[0]+N)%N);
combination.push_back((j+master[1]+N)%N);
combination.push_back((k+master[2]+N)%N);
used.insert(combination);
}
}
}
fout << used.size()<<endl;
return 0;
}
| 22.536585 | 45 | 0.598485 | [
"vector"
] |
73357f46bb8899613b50922c99d0d9693b156d77 | 11,867 | hpp | C++ | src/Module/CRC/CRC.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/CRC/CRC.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/CRC/CRC.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | /*!
* \file
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef CRC_HPP_
#define CRC_HPP_
#include <string>
#include <vector>
#include <sstream>
#include "Tools/Exception/exception.hpp"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
namespace crc
{
namespace tsk
{
enum list { build, extract, check, SIZE };
}
namespace sck
{
namespace build { enum list { U_K1, U_K2, SIZE }; }
namespace extract { enum list { V_K1, V_K2, SIZE }; }
namespace check { enum list { V_K , SIZE }; }
}
}
/*!
* \class CRC
*
* \brief Adds/builds and checks a Cyclic Redundancy Check (CRC) for a set of information bits.
*
* \tparam B: type of the bits in the CRC.
*
* Please use CRC for inheritance (instead of CRC).
*/
template <typename B = int>
class CRC : public Module
{
protected:
const int K; /*!< Number of information bits (the CRC bits are not included in K) */
const int size;
public:
/*!
* \brief Constructor.
*
* \param K: number of information bits (the CRC bits are included in K).
* \param n_frames: number of frames to process in the CRC.
* \param name: CRC's name.
*/
CRC(const int K, const int size, const int n_frames = 1)
: Module(n_frames), K(K), size(size)
{
const std::string name = "CRC";
this->set_name(name);
this->set_short_name(name);
if (K <= 0)
{
std::stringstream message;
message << "'K' has to be greater than 0 ('K' = " << K << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
auto &p1 = this->create_task("build");
auto &p1s_U_K1 = this->template create_socket_in <B>(p1, "U_K1", this->K * this->n_frames);
auto &p1s_U_K2 = this->template create_socket_out<B>(p1, "U_K2", (this->K + this->size) * this->n_frames);
this->create_codelet(p1, [this, &p1s_U_K1, &p1s_U_K2]() -> int
{
this->build(static_cast<B*>(p1s_U_K1.get_dataptr()),
static_cast<B*>(p1s_U_K2.get_dataptr()));
return 0;
});
auto &p2 = this->create_task("extract");
auto &p2s_V_K1 = this->template create_socket_in <B>(p2, "V_K1", (this->K + this->size) * this->n_frames);
auto &p2s_V_K2 = this->template create_socket_out<B>(p2, "V_K2", this->K * this->n_frames);
this->create_codelet(p2, [this, &p2s_V_K1, &p2s_V_K2]() -> int
{
this->extract(static_cast<B*>(p2s_V_K1.get_dataptr()),
static_cast<B*>(p2s_V_K2.get_dataptr()));
return 0;
});
auto &p3 = this->create_task("check");
auto &p3s_V_K = this->template create_socket_in<B>(p3, "V_K", (this->K + this->size) * this->n_frames);
this->create_codelet(p3, [this, &p3s_V_K]() -> int
{
return this->check(static_cast<B*>(p3s_V_K.get_dataptr())) ? 1 : 0;
});
}
/*!
* \brief Destructor.
*/
virtual ~CRC()
{
}
int get_K() const
{
return this->K;
}
/*!
* \brief Gets the size of the CRC (the number of bits for the CRC signature).
*
* \return the size of the CRC.
*/
virtual int get_size()
{
return size;
}
/*!
* \brief Computes and adds the CRC in the vector of information bits (the CRC bits are often put at the end of the
* vector).
*
* \param U_K: a vector (size = K - CRC<B>::size()) containing the information bits, adds "CRC<B>::size()" bits in
* U_K.
*/
template <class A = std::allocator<B>>
void build(const std::vector<B,A>& U_K1, std::vector<B,A>& U_K2, const int frame_id = -1)
{
if (this->K * this->n_frames != (int)U_K1.size())
{
std::stringstream message;
message << "'U_K1.size()' has to be equal to 'K' * 'n_frames' ('U_K1.size()' = " << U_K1.size()
<< ", 'K' = " << this->K << ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if ((this->K + this->get_size()) * this->n_frames != (int)U_K2.size())
{
std::stringstream message;
message << "'U_K2.size()' has to be equal to ('K' + 'get_size()') * 'n_frames' ('U_K2.size()' = "
<< U_K2.size() << ", 'K' = " << this->K << ", 'get_size()' = " << this->get_size()
<< ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if (frame_id != -1 && frame_id >= this->n_frames)
{
std::stringstream message;
message << "'frame_id' has to be equal to '-1' or to be smaller than 'n_frames' ('frame_id' = "
<< frame_id << ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
this->build(U_K1.data(), U_K2.data(), frame_id);
}
virtual void build(const B *U_K1, B *U_K2, const int frame_id = -1)
{
const auto f_start = (frame_id < 0) ? 0 : frame_id % this->n_frames;
const auto f_stop = (frame_id < 0) ? this->n_frames : f_start +1;
for (auto f = f_start; f < f_stop; f++)
this->_build(U_K1 + f * this->K,
U_K2 + f * (this->K + this->get_size()),
f);
}
template <class A = std::allocator<B>>
void extract(const std::vector<B,A>& V_K1, std::vector<B,A>& V_K2, const int frame_id = -1)
{
if ((this->K + this->get_size()) * this->n_frames != (int)V_K1.size())
{
std::stringstream message;
message << "'V_K1.size()' has to be equal to ('K' + 'get_size()') * 'n_frames' ('V_K1.size()' = "
<< V_K1.size() << ", 'K' = " << this->K << ", 'get_size()' = " << this->get_size()
<< ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if (this->K * this->n_frames != (int)V_K2.size())
{
std::stringstream message;
message << "'V_K2.size()' has to be equal to 'K' * 'n_frames' ('V_K2.size()' = " << V_K2.size()
<< ", 'K' = " << this->K << ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if (frame_id != -1 && frame_id >= this->n_frames)
{
std::stringstream message;
message << "'frame_id' has to be equal to '-1' or to be smaller than 'n_frames' ('frame_id' = "
<< frame_id << ", 'n_frames' = " << this->n_frames << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
this->extract(V_K1.data(), V_K2.data(), frame_id);
}
virtual void extract(const B *V_K1, B *V_K2, const int frame_id = -1)
{
const auto f_start = (frame_id < 0) ? 0 : frame_id % this->n_frames;
const auto f_stop = (frame_id < 0) ? this->n_frames : f_start +1;
for (auto f = f_start; f < f_stop; f++)
this->_extract(V_K1 + f * (this->K + this->get_size()),
V_K2 + f * this->K,
f);
}
/*!
* \brief Checks if the CRC is verified or not.
*
* \param V_K: a vector containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
template <class A = std::allocator<B>>
bool check(const std::vector<B,A>& V_K, const int n_frames = -1, const int frame_id = -1)
{
if (n_frames <= 0 && n_frames != -1)
{
std::stringstream message;
message << "'n_frames' has to be greater than 0 or equal to -1 ('n_frames' = " << n_frames << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (frame_id != -1 && frame_id >= (n_frames ? n_frames : this->n_frames))
{
std::stringstream message;
message << "'frame_id' has to be equal to '-1' or to be smaller than 'n_frames' ('frame_id' = "
<< frame_id << ", 'n_frames' = " << (n_frames ? n_frames : this->n_frames) << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if ((this->K + (int)this->get_size()) * n_frames != (int)V_K.size() &&
(this->K + (int)this->get_size()) * this->n_frames != (int)V_K.size())
{
std::stringstream message;
message << "'V_K.size()' has to be equal to ('K' + 'size') * 'n_frames' ('V_K.size()' = " << V_K.size()
<< ", 'K' = " << this->K
<< ", 'n_frames' = " << (n_frames != -1 ? n_frames : this->n_frames) << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
return this->check(V_K.data(), n_frames, frame_id);
}
virtual bool check(const B *V_K, const int n_frames = -1, const int frame_id = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
const auto f_start = (frame_id < 0) ? 0 : frame_id % real_n_frames;
const auto f_stop = (frame_id < 0) ? real_n_frames : f_start +1;
auto f = f_start;
while (f < f_stop && this->_check(V_K + f * (this->K + this->get_size()), f))
f++;
return f == f_stop;
}
/*!
* \brief Checks if the CRC is verified or not (works on packed bits).
*
* \param V_K: a vector of packed bits containing information bits plus the CRC bits.
* \param n_frames: you should not use this parameter unless you know what you are doing, this parameter
* redefine the number of frames to check specifically in this method.
*
* \return true if the CRC is verified, false otherwise.
*/
template <class A = std::allocator<B>>
bool check_packed(const std::vector<B,A>& V_K, const int n_frames = -1, const int frame_id = -1)
{
if (n_frames <= 0 && n_frames != -1)
{
std::stringstream message;
message << "'n_frames' has to be greater than 0 or equal to -1 ('n_frames' = " << n_frames << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
if (frame_id != -1 && frame_id >= (n_frames ? n_frames : this->n_frames))
{
std::stringstream message;
message << "'frame_id' has to be equal to '-1' or to be smaller than 'n_frames' ('frame_id' = "
<< frame_id << ", 'n_frames' = " << (n_frames ? n_frames : this->n_frames) << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
if ((this->K + (int)this->get_size()) * n_frames != (int)V_K.size() &&
(this->K + (int)this->get_size()) * this->n_frames != (int)V_K.size())
{
std::stringstream message;
message << "'V_K.size()' has to be equal to ('K' + 'size') * 'n_frames' ('V_K.size()' = " << V_K.size()
<< ", 'K' = " << this->K
<< ", 'n_frames' = " << (n_frames != -1 ? n_frames : this->n_frames) << ").";
throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
}
return this->check_packed(V_K.data(), n_frames, frame_id);
}
bool check_packed(const B *V_K, const int n_frames = -1, const int frame_id = -1)
{
const int real_n_frames = (n_frames != -1) ? n_frames : this->n_frames;
const auto f_start = (frame_id < 0) ? 0 : frame_id % real_n_frames;
const auto f_stop = (frame_id < 0) ? real_n_frames : f_start +1;
auto f = f_start;
while (f < f_stop && this->_check_packed(V_K + f * (this->K + this->get_size()), f))
f++;
return f == f_stop;
}
protected:
virtual void _build(const B *U_K1, B *U_K2, const int frame_id)
{
throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}
virtual void _extract(const B *V_K1, B *V_K2, const int frame_id)
{
throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}
virtual bool _check(const B *V_K, const int frame_id)
{
throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
return false;
}
virtual bool _check_packed(const B *V_K, const int frame_id)
{
throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
return false;
}
};
}
}
#endif
| 33.522599 | 116 | 0.60605 | [
"vector"
] |
73391f3651ef20f67ceb31e0d15555c5cebe512f | 1,030 | cpp | C++ | LeetCode/Design Compressed String Iterator/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | LeetCode/Design Compressed String Iterator/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | LeetCode/Design Compressed String Iterator/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | class StringIterator {
public:
StringIterator(string compressedString) {
this->compressedString = compressedString;
this->index = this->count = 0;
this->curr = ' ';
}
char next() {
if (count == 0) {
if (index >= compressedString.size()) {
return ' ';
}
curr = compressedString[index++];
while (index < compressedString.size() && compressedString[index] >= '0' && compressedString[index] <= '9') {
count = (count * 10) + (compressedString[index++] - '0');
}
}
count--;
return curr;
}
bool hasNext() {
return index < compressedString.size() || count != 0;
}
private:
string compressedString;
char curr;
int count, index;
};
/**
* Your StringIterator object will be instantiated and called as such:
* StringIterator* obj = new StringIterator(compressedString);
* char param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/ | 27.105263 | 121 | 0.548544 | [
"object"
] |
733ab75323716c58e082cca5a40baa262f2179ff | 6,371 | cpp | C++ | libs/hana/test/detail/preprocessor.cpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 918 | 2016-12-22T02:53:08.000Z | 2022-03-22T06:21:35.000Z | libs/hana/test/detail/preprocessor.cpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 203 | 2016-12-27T12:09:03.000Z | 2022-03-30T20:46:55.000Z | libs/hana/test/detail/preprocessor.cpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 122 | 2016-12-22T17:38:09.000Z | 2022-02-22T14:25:49.000Z | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/assert.hpp>
#include <boost/hana/detail/preprocessor.hpp>
#include <string>
#include <vector>
//////////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_CONCAT
//////////////////////////////////////////////////////////////////////////////
static_assert(BOOST_HANA_PP_CONCAT(1, 2) == 12, "");
//////////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_NARG
//////////////////////////////////////////////////////////////////////////////
static_assert(BOOST_HANA_PP_NARG(x) == 1, "");
static_assert(BOOST_HANA_PP_NARG(x, x) == 2, "");
static_assert(BOOST_HANA_PP_NARG(x, x, x) == 3, "");
static_assert(BOOST_HANA_PP_NARG(x, x, x, x) == 4, "");
static_assert(BOOST_HANA_PP_NARG(
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x) == 60, "");
static_assert(BOOST_HANA_PP_NARG(
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x) == 61, "");
static_assert(BOOST_HANA_PP_NARG(
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x) == 62, "");
static_assert(BOOST_HANA_PP_NARG(
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x) == 63, "");
static_assert(BOOST_HANA_PP_NARG(
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x, x, x, x, x, x, x,
x, x, x, x) == 64, "");
//////////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_BACK
//////////////////////////////////////////////////////////////////////////////
static_assert(BOOST_HANA_PP_BACK(0) == 0, "");
static_assert(BOOST_HANA_PP_BACK(0, 1) == 1, "");
static_assert(BOOST_HANA_PP_BACK(0, 1, 2) == 2, "");
static_assert(BOOST_HANA_PP_BACK(0, 1, 2, 3) == 3, "");
static_assert(BOOST_HANA_PP_BACK(0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18) == 18, "");
static_assert(BOOST_HANA_PP_BACK(0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18, 19) == 19, "");
//////////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_FRONT
//////////////////////////////////////////////////////////////////////////////
static_assert(BOOST_HANA_PP_FRONT(0) == 0, "");
static_assert(BOOST_HANA_PP_FRONT(0, 1) == 0, "");
static_assert(BOOST_HANA_PP_FRONT(0, 1, 2) == 0, "");
static_assert(BOOST_HANA_PP_FRONT(0, 1, 2, 3) == 0, "");
static_assert(BOOST_HANA_PP_FRONT(0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18) == 0, "");
static_assert(BOOST_HANA_PP_FRONT(0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18, 19) == 0, "");
int main() {
using Vector = std::vector<int>;
//////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_STRINGIZE
//////////////////////////////////////////////////////////////////////////
{
constexpr char const* xyz = BOOST_HANA_PP_STRINGIZE(xyz);
BOOST_HANA_RUNTIME_CHECK(std::string{xyz} == "xyz");
}{
constexpr char const* xyz = BOOST_HANA_PP_STRINGIZE(foo{bar, baz});
BOOST_HANA_RUNTIME_CHECK(std::string{xyz} == "foo{bar, baz}");
}{
constexpr char const* xyz = BOOST_HANA_PP_STRINGIZE(foo, bar, baz);
BOOST_HANA_RUNTIME_CHECK(std::string{xyz} == "foo, bar, baz");
}
//////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_DROP_BACK
//////////////////////////////////////////////////////////////////////////
{
Vector args = {BOOST_HANA_PP_DROP_BACK(0)};
BOOST_HANA_RUNTIME_CHECK(args.empty());
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(0, 1)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{0});
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(0, 1, 2)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{0, 1});
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(0, 1, 2, 3)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{0, 1, 2});
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(0, 1, 2, 3, 4)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{0, 1, 2, 3});
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(
0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18
)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{
0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16});
}{
Vector args = {BOOST_HANA_PP_DROP_BACK(
0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18, 19
)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{
0, 1, 2, 3, 4, 5, 6, 6, 8, 9,
10, 11, 12, 13, 14, 15, 16, 16, 18});
}
//////////////////////////////////////////////////////////////////////////
// BOOST_HANA_PP_DROP_FRONT
//////////////////////////////////////////////////////////////////////////
{
Vector args = {BOOST_HANA_PP_DROP_FRONT(0, 1)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{1});
}{
Vector args = {BOOST_HANA_PP_DROP_FRONT(0, 1, 2)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{1, 2});
}{
Vector args = {BOOST_HANA_PP_DROP_FRONT(0, 1, 2, 3)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{1, 2, 3});
}{
Vector args = {BOOST_HANA_PP_DROP_FRONT(0, 1, 2, 3, 4)};
BOOST_HANA_RUNTIME_CHECK(args == Vector{1, 2, 3, 4});
}
}
| 37.698225 | 84 | 0.433527 | [
"vector"
] |
733cbcfcb85a6182ef8a44e31801ab9feaf9496b | 8,180 | hpp | C++ | include/TGUI/Variant.hpp | Kvaz1r/TGUI | 16a1102e4c8c9de4d7cf1bb56cdea93a7a747eb0 | [
"Zlib"
] | null | null | null | include/TGUI/Variant.hpp | Kvaz1r/TGUI | 16a1102e4c8c9de4d7cf1bb56cdea93a7a747eb0 | [
"Zlib"
] | null | null | null | include/TGUI/Variant.hpp | Kvaz1r/TGUI | 16a1102e4c8c9de4d7cf1bb56cdea93a7a747eb0 | [
"Zlib"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus' Graphical User Interface
// Copyright (C) 2012-2020 Bruno Van de Velde (vdv_b@tgui.eu)
//
// 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.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef TGUI_VARIANT_HPP
#define TGUI_VARIANT_HPP
#if TGUI_COMPILED_WITH_CPP_VER >= 17
#include <variant>
#else
#include <TGUI/Any.hpp>
#include <TGUI/Exception.hpp>
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
/*
#if TGUI_COMPILED_WITH_CPP_VER < 17
namespace priv
{
template<typename... NoTypesLeft>
struct IndexInEmulatedVariantHelper
{
static std::size_t findIndex(const Any&, std::size_t)
{
// We should never pass here, it means that the Any object didn't hold anything.
throw tgui::Exception("tgui::Variant::index() called on uninitialized variant!");
}
static int getByIndex(const Any& any, std::size_t wantedIndex, std::size_t index)
{
throw tgui::Exception("tgui::Variant::get() called with too high index!");
}
};
template<typename FirstType, typename... OtherTypes>
struct IndexInEmulatedVariantHelper<FirstType, OtherTypes...>
{
static std::size_t findIndex(const Any& any, std::size_t index)
{
if (any.is<FirstType>())
return index;
else
return IndexInEmulatedVariantHelper<OtherTypes...>::findIndex(any, index + 1);
}
static decltype(auto) getByIndex(const Any& any, std::size_t wantedIndex, std::size_t index)
{
if (index == wantedIndex)
return any.as<FirstType>();
else
return IndexInEmulatedVariantHelper<OtherTypes...>::getByIndex(any, wantedIndex, index + 1);
}
};
}
#endif
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/// @brief Wrapper around std::variant which will fall back to a custom Any class in c++14 mode
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if TGUI_COMPILED_WITH_CPP_VER >= 17
template <typename... Types>
#else
template <typename FirstType, typename... OtherTypes>
#endif
class Variant
{
public:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Default constructor
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Variant() :
#if TGUI_COMPILED_WITH_CPP_VER >= 17
m_variant{}
#else
m_any{FirstType{}}
#endif
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Construct the variant with an initial value
///
/// @param value Value to store in the variant
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
Variant(const T& value) :
#if TGUI_COMPILED_WITH_CPP_VER >= 17
m_variant{value}
#else
m_any{value}
#endif
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Retrieve the value in the variant
///
/// @return Stored value
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
T& get()
{
#if TGUI_COMPILED_WITH_CPP_VER >= 17
return std::get<T>(m_variant);
#else
return m_any.as<T>();
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Retrieve the value in the variant
///
/// @return Stored value
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename T>
const T& get() const
{
#if TGUI_COMPILED_WITH_CPP_VER >= 17
return std::get<T>(m_variant);
#else
return m_any.as<T>();
#endif
}
/*
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Retrieve the value in the variant
///
/// @return Stored value
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <std::size_t Index>
auto& get()
{
#if TGUI_COMPILED_WITH_CPP_VER >= 17
return std::get<Index>(m_variant);
#else
return priv::IndexInEmulatedVariantHelper<FirstType, OtherTypes...>::getByIndex(m_any, Index, 0);
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Retrieve the value in the variant
///
/// @return Stored value
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <std::size_t Index>
const auto& get() const
{
#if TGUI_COMPILED_WITH_CPP_VER >= 17
return std::get<Index>(m_variant);
#else
return priv::IndexInEmulatedVariantHelper<FirstType, OtherTypes...>::getByIndex(m_any, Index, 0);
#endif
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the index
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::size_t index() const
{
#if TGUI_COMPILED_WITH_CPP_VER >= 17
return m_variant.index();
#else
return priv::IndexInEmulatedVariantHelper<FirstType, OtherTypes...>::findIndex(m_any, 0);
#endif
}
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private:
#if TGUI_COMPILED_WITH_CPP_VER >= 17
std::variant<Types...> m_variant;
#else
Any m_any;
#endif
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif // TGUI_VARIANT_HPP
| 37.522936 | 129 | 0.389487 | [
"object"
] |
733e0add1350aee7bf150048995a24ca06007a36 | 968 | hpp | C++ | src/geometry/include/geometry/operations.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | src/geometry/include/geometry/operations.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | src/geometry/include/geometry/operations.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | #pragma once
#include "geometry/internals/util.hpp"
#include "geometry/matrix.hpp"
#include "geometry/point.hpp"
#include "geometry/vector.hpp"
namespace geometry {
template <class U, class V,
class = internals::enable_if_have_common_type_t<U, V>>
auto operator-(const Point<U>& lhs, const Point<V>& rhs)
{
return Vector<std::common_type_t<U, V>>{lhs.x - rhs.x, lhs.y - rhs.y};
}
template <class U, class V,
class = internals::enable_if_have_common_type_t<U, V>>
auto operator-(const Vector<U>& lhs, const Point<V>& rhs)
{
return Vector<std::common_type_t<U, V>>{lhs.x - rhs.x, lhs.y - rhs.y};
}
template <class U, class V,
class = internals::enable_if_have_common_type_t<U, V>>
auto operator*(const Matrix<U>& matrix, const Vector<V>& vector)
{
return Vector<std::common_type_t<U, V>>{
matrix(0, 0) * vector.x + matrix(0, 1) * vector.y,
matrix(1, 0) * vector.x + matrix(1, 1) * vector.y
};
}
} // namespace geometry
| 26.888889 | 74 | 0.670455 | [
"geometry",
"vector"
] |
73412cec48377b91005ed0283ae14a2d7b8e256e | 8,732 | cpp | C++ | src/ltevent.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | null | null | null | src/ltevent.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | null | null | null | src/ltevent.cpp | hemantasapkota/lotech | 46598a7c37dfd7cd424e2426564cc32533e1cfd6 | [
"curl"
] | null | null | null | /* Copyright (C) 2010-2013 Ian MacLarty. See Copyright Notice in lt.h. */
#include "lt.h"
LT_INIT_IMPL(ltevent)
LTEventHandler::LTEventHandler(int filter, LTfloat left, LTfloat bottom, LTfloat right, LTfloat top) {
bb = new LTEventHandlerBB();
bb->left = left;
bb->bottom = bottom;
bb->right = right;
bb->top = top;
LTEventHandler::filter = filter;
execution_pending = false;
cancelled = false;
}
LTEventHandler::LTEventHandler(int filter) {
bb = NULL;
LTEventHandler::filter = filter;
execution_pending = false;
cancelled = false;
}
LTEventHandler::~LTEventHandler() {
assert(!execution_pending);
if (bb != NULL) {
delete bb;
}
}
bool LTEventHandler::hit(LTEvent *e) {
//ltLog("hit test: %x, %x, %f, %f", e->event, filter, e->x, e->y);
if (bb != NULL
&& LT_EVENT_MATCH(e->event, LT_EVENT_POINTER_MOVE)
&& LT_EVENT_MATCH(filter, LT_EVENT_POINTER_ENTER)
// prev position outside
&& (e->prev_x < bb->left || e->prev_x > bb->right || e->prev_y < bb->bottom || e->prev_y > bb->top)
// new position inside
&& (e->x >= bb->left && e->x <= bb->right && e->y >= bb->bottom && e->y <= bb->top))
{
e->event |= LT_EVENT_POINTER_ENTER;
return ((filter & e->event) == filter);
} else if (bb != NULL
&& LT_EVENT_MATCH(e->event, LT_EVENT_POINTER_MOVE)
&& LT_EVENT_MATCH(filter, LT_EVENT_POINTER_EXIT)
// new position outside
&& (e->x < bb->left || e->x > bb->right || e->y < bb->bottom || e->y > bb->top)
// prev position inside
&& (e->prev_x >= bb->left && e->prev_x <= bb->right && e->prev_y >= bb->bottom && e->prev_y <= bb->top))
{
e->event |= LT_EVENT_POINTER_EXIT;
return ((filter & e->event) == filter);
} else {
return (LT_EVENT_MATCH(e->event, filter) &&
( bb == NULL || (e->x >= bb->left && e->x <= bb->right && e->y >= bb->bottom && e->y <= bb->top) ));
}
}
LTSceneNode *lt_exclusive_receiver = NULL;
struct LTEventVisitor : LTSceneNodeVisitor {
LTEvent *event;
bool events_allowed;
LTSceneNode *exclusive_node;
std::list<LTEvent*> events_to_execute;
LTEventVisitor(LTEvent *e) {
event = e;
exclusive_node = lt_exclusive_receiver;
events_allowed = (exclusive_node == NULL);
}
virtual void visit(LTSceneNode *node) {
if (node->action_speed == 0.0f) {
// Ignore paused nodes and their children.
return;
}
bool prev_allowed = events_allowed;
if (exclusive_node != NULL && node == exclusive_node) {
events_allowed = true;
}
bool consumed = false;
if (events_allowed) {
if (node->event_handlers != NULL) {
std::list<LTEventHandler*>::iterator it;
for (it = node->event_handlers->begin(); it != node->event_handlers->end(); it++) {
LTEventHandler *handler = *it;
int e = event->event;
if (handler->hit(event)) {
LTEvent *event_with_handler = new LTEvent(event);
event_with_handler->node = node;
event_with_handler->handler = handler;
events_to_execute.push_back(event_with_handler);
handler->execution_pending = true;
consumed = true;
}
event->event = e; // call to hit() may alter event
}
}
}
if (!consumed) {
LTfloat old_x = 0, old_y = 0, old_prev_x = 0, old_prev_y = 0;
if (LT_EVENT_MATCH(event->event, LT_EVENT_POINTER)) {
old_x = event->x;
old_y = event->y;
old_prev_x = event->prev_x;
old_prev_y = event->prev_y;
if (!node->inverse_transform(&event->prev_x, &event->prev_y)) {
return;
}
if (!node->inverse_transform(&event->x, &event->y)) {
return;
}
}
node->visit_children(this, true);
if (LT_EVENT_MATCH(event->event, LT_EVENT_POINTER)) {
event->x = old_x;
event->y = old_y;
event->prev_x = old_prev_x;
event->prev_y = old_prev_y;
}
}
events_allowed = prev_allowed;
}
};
void ltPropagateEvent(LTSceneNode *node, LTEvent *event) {
LTEventVisitor v(event);
v.visit(node);
std::list<LTEvent*>::iterator it;
std::set<LTEventHandler *> cancelled_handlers;
bool consumed = false;
for (it = v.events_to_execute.begin(); it != v.events_to_execute.end(); it++) {
LTEvent *e = *it;
LTEventHandler *h = e->handler;
if (h->cancelled) {
cancelled_handlers.insert(h);
} else if (h->execution_pending) {
if (!consumed) {
consumed = h->consume(e->node, e);
}
h->execution_pending = false;
}
delete e;
}
std::set<LTEventHandler *>::iterator cit;
for (cit = cancelled_handlers.begin(); cit != cancelled_handlers.end(); cit++) {
delete *cit;
}
}
LT_REGISTER_TYPE(LTEvent, "lt.Event", "lt.Object")
LT_REGISTER_FIELD_FLOAT(LTEvent, x)
LT_REGISTER_FIELD_FLOAT(LTEvent, y)
LT_REGISTER_FIELD_FLOAT(LTEvent, orig_x)
LT_REGISTER_FIELD_FLOAT(LTEvent, orig_y)
LT_REGISTER_FIELD_INT(LTEvent, button)
LT_REGISTER_FIELD_INT_AS(LTEvent, touch_id, "touch")
static const LTEnumConstant key_enum_vals[] = {
{"unknown", LT_KEY_UNKNOWN},
{"0", LT_KEY_0},
{"1", LT_KEY_1},
{"2", LT_KEY_2},
{"3", LT_KEY_3},
{"4", LT_KEY_4},
{"5", LT_KEY_5},
{"6", LT_KEY_6},
{"7", LT_KEY_7},
{"8", LT_KEY_8},
{"9", LT_KEY_9},
{"a", LT_KEY_a},
{"b", LT_KEY_b},
{"c", LT_KEY_c},
{"d", LT_KEY_d},
{"e", LT_KEY_e},
{"f", LT_KEY_f},
{"g", LT_KEY_g},
{"h", LT_KEY_h},
{"i", LT_KEY_i},
{"j", LT_KEY_j},
{"k", LT_KEY_k},
{"l", LT_KEY_l},
{"m", LT_KEY_m},
{"n", LT_KEY_n},
{"o", LT_KEY_o},
{"p", LT_KEY_p},
{"q", LT_KEY_q},
{"r", LT_KEY_r},
{"s", LT_KEY_s},
{"t", LT_KEY_t},
{"u", LT_KEY_u},
{"v", LT_KEY_v},
{"w", LT_KEY_w},
{"x", LT_KEY_x},
{"y", LT_KEY_y},
{"z", LT_KEY_z},
{"A", LT_KEY_A},
{"B", LT_KEY_B},
{"C", LT_KEY_C},
{"D", LT_KEY_D},
{"E", LT_KEY_E},
{"F", LT_KEY_F},
{"G", LT_KEY_G},
{"H", LT_KEY_H},
{"I", LT_KEY_I},
{"J", LT_KEY_J},
{"K", LT_KEY_K},
{"L", LT_KEY_L},
{"M", LT_KEY_M},
{"N", LT_KEY_N},
{"O", LT_KEY_O},
{"P", LT_KEY_P},
{"Q", LT_KEY_Q},
{"R", LT_KEY_R},
{"S", LT_KEY_S},
{"T", LT_KEY_T},
{"U", LT_KEY_U},
{"V", LT_KEY_V},
{"W", LT_KEY_W},
{"X", LT_KEY_X},
{"Y", LT_KEY_Y},
{"Z", LT_KEY_Z},
{"space", LT_KEY_SPACE},
{"tab", LT_KEY_TAB},
{"enter", LT_KEY_ENTER},
{"up", LT_KEY_UP},
{"down", LT_KEY_DOWN},
{"left", LT_KEY_LEFT},
{"right", LT_KEY_RIGHT},
{"[", LT_KEY_LEFT_BRACKET},
{"]", LT_KEY_RIGHT_BRACKET},
{"\\", LT_KEY_BACKSLASH},
{";", LT_KEY_SEMI_COLON},
{"'", LT_KEY_APOS},
{",", LT_KEY_COMMA},
{".", LT_KEY_PERIOD},
{"/", LT_KEY_SLASH},
{"+", LT_KEY_PLUS},
{"-", LT_KEY_MINUS},
{"`", LT_KEY_TICK},
{"del", LT_KEY_DEL},
{"esc", LT_KEY_ESC},
{"back", LT_KEY_BACK},
{"~", LT_KEY_TILDE},
{"!", LT_KEY_EXCLAMATION},
{"@", LT_KEY_ATRATE},
{"#", LT_KEY_HASH},
{"$", LT_KEY_DOLLAR},
{"%", LT_KEY_PERCENT},
{"^", LT_KEY_CARET},
{"&", LT_KEY_AMPERSAND},
{"*", LT_KEY_ASTERISK},
{"(", LT_KEY_LEFT_ROUND_BRACKET},
{")", LT_KEY_RIGHT_ROUND_BRACKET},
{"_", LT_KEY_UNDERSCORE},
{"=", LT_KEY_EQUALS},
{"{", LT_KEY_LEFT_CURLY},
{"}", LT_KEY_RIGHT_CURLY},
{":", LT_KEY_COLON},
{"\"", LT_KEY_QUOTES},
{"<", LT_KEY_LEFT_ANGLE},
{">", LT_KEY_RIGHT_ANGLE},
{"?", LT_KEY_QUESTION},
{"|", LT_KEY_PIPE},
{"F1", LT_KEY_F1},
{NULL, 0}};
LT_REGISTER_FIELD_ENUM(LTEvent, key, LTKey, key_enum_vals)
static const LTEnumConstant event_enum_vals[] = {
{"touch_down", LT_EVENT_TOUCH_DOWN},
{"touch_up", LT_EVENT_TOUCH_UP},
{"touch_move", LT_EVENT_TOUCH_MOVE},
{"mouse_down", LT_EVENT_MOUSE_DOWN},
{"mouse_up", LT_EVENT_MOUSE_UP},
{"mouse_move", LT_EVENT_MOUSE_MOVE},
{"key_down", LT_EVENT_KEY_DOWN},
{"key_up", LT_EVENT_KEY_UP},
{NULL, 0}};
LT_REGISTER_FIELD_ENUM(LTEvent, event, int, event_enum_vals)
| 30.746479 | 112 | 0.539968 | [
"object"
] |
73447765043b92b799371dd47c981e0812dd2dfa | 35,845 | cpp | C++ | cell_based/src/population/AbstractCellPopulation.cpp | Mathematics-in-Oncology/ComputationalColonicCrypts | a407ae6c37acc878cd1548590c71bc1f87bc5c06 | [
"Unlicense"
] | 1 | 2021-01-25T12:21:40.000Z | 2021-01-25T12:21:40.000Z | cell_based/src/population/AbstractCellPopulation.cpp | Mathematics-in-Oncology/ComputationalColonicCrypts | a407ae6c37acc878cd1548590c71bc1f87bc5c06 | [
"Unlicense"
] | null | null | null | cell_based/src/population/AbstractCellPopulation.cpp | Mathematics-in-Oncology/ComputationalColonicCrypts | a407ae6c37acc878cd1548590c71bc1f87bc5c06 | [
"Unlicense"
] | 1 | 2021-01-25T12:21:56.000Z | 2021-01-25T12:21:56.000Z | /*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/bind.hpp>
#include <algorithm>
#include <functional>
#include "AbstractCellPopulation.hpp"
#include "AbstractPhaseBasedCellCycleModel.hpp"
#include "SmartPointers.hpp"
#include "CellAncestor.hpp"
#include "ApoptoticCellProperty.hpp"
// Cell writers
#include "BoundaryNodeWriter.hpp"
#include "CellProliferativeTypesWriter.hpp"
// Cell population writers
#include "CellMutationStatesCountWriter.hpp"
#include "CellProliferativePhasesCountWriter.hpp"
#include "CellProliferativeTypesCountWriter.hpp"
#include "NodeLocationWriter.hpp"
// These #includes are needed for SetDefaultCellMutationStateAndProliferativeTypeOrdering()
#include "WildTypeCellMutationState.hpp"
#include "ApcOneHitCellMutationState.hpp"
#include "ApcTwoHitCellMutationState.hpp"
#include "BetaCateninOneHitCellMutationState.hpp"
#include "BetaCateninTwoHitCellMutationState.hpp"
#include "MMRTwoHitCellMutationState.hpp"
#include "MMR_ApcOneHitCellMutationState.hpp"
#include "MMR_ApcTwoHitCellMutationState.hpp"
#include "MMR_BCOneHitCellMutationState.hpp"
#include "MMR_BCTwoHitCellMutationState.hpp"
#include "MMR_BCOneHit_ApcOneHitCellMutationState.hpp"
#include "BCOneHit_ApcOneHitCellMutationState.hpp"
#include "ApcLOHCellMutationState.hpp"
#include "BCOneHit_ApcLOHCellMutationState.hpp"
#include "MMR_ApcLOHCellMutationState.hpp"
#include "MMR_BCOneHit_ApcLOHCellMutationState.hpp"
#include "BCLOHApcOneHitCellMutationState.hpp"
#include "BCLOHMMRTwoHitCellMutationState.hpp"
#include "BCLOHMMR_ApcOneHitCellMutationState.hpp"
#include "BCLOHApcLOHCellMutationState.hpp"
#include "BCLOHMMR_ApcLOHCellMutationState.hpp"
#include "BCLOHCellMutationState.hpp"
//added mutations
#include "DefaultCellProliferativeType.hpp"
#include "StemCellProliferativeType.hpp"
#include "TransitCellProliferativeType.hpp"
#include "DifferentiatedCellProliferativeType.hpp"
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::AbstractCellPopulation( AbstractMesh<ELEMENT_DIM, SPACE_DIM>& rMesh,
std::vector<CellPtr>& rCells,
const std::vector<unsigned> locationIndices)
: mrMesh(rMesh),
mCells(rCells.begin(), rCells.end()),
mCentroid(zero_vector<double>(SPACE_DIM)),
mpCellPropertyRegistry(CellPropertyRegistry::Instance()->TakeOwnership()),
mOutputResultsForChasteVisualizer(true)
{
/*
* To avoid double-counting problems, clear the passed-in cells vector.
* We force a reallocation of memory so that subsequent usage of the
* vector is more likely to give an error.
*/
std::vector<CellPtr>().swap(rCells);
// There must be a one-one correspondence between cells and location indices
if (!locationIndices.empty())
{
if (mCells.size() != locationIndices.size())
{
EXCEPTION("There is not a one-one correspondence between cells and location indices");
}
}
// Set up the map between location indices and cells
mLocationCellMap.clear();
mCellLocationMap.clear();
std::list<CellPtr>::iterator it = mCells.begin();
for (unsigned i=0; it != mCells.end(); ++it, ++i)
{
// Give each cell a pointer to the property registry (we have taken ownership in this constructor)
(*it)->rGetCellPropertyCollection().SetCellPropertyRegistry(mpCellPropertyRegistry.get());
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::AbstractCellPopulation(AbstractMesh<ELEMENT_DIM, SPACE_DIM>& rMesh)
: mrMesh(rMesh)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::~AbstractCellPopulation()
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::InitialiseCells()
{
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter=this->Begin();
cell_iter!=this->End();
++cell_iter)
{
cell_iter->InitialiseCellCycleModel();
cell_iter->InitialiseSrnModel();
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetDataOnAllCells(const std::string& rDataName, double dataValue)
{
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter=this->Begin();
cell_iter!=this->End();
++cell_iter)
{
cell_iter->GetCellData()->SetItem(rDataName, dataValue);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
AbstractMesh<ELEMENT_DIM, SPACE_DIM>& AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::rGetMesh()
{
return mrMesh;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::list<CellPtr>& AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::rGetCells()
{
return mCells;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetNumRealCells()
{
unsigned counter = 0;
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter=this->Begin();
cell_iter!=this->End();
++cell_iter)
{
counter++;
}
return counter;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetNumAllCells()
{
return mCells.size();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetCellAncestorsToLocationIndices()
{
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter=this->Begin(); cell_iter!=this->End(); ++cell_iter)
{
MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor, (mCellLocationMap[(*cell_iter).get()]));
cell_iter->SetAncestor(p_cell_ancestor);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::set<unsigned> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellAncestors()
{
std::set<unsigned> remaining_ancestors;
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter=this->Begin(); cell_iter!=this->End(); ++cell_iter)
{
remaining_ancestors.insert(cell_iter->GetAncestor());
}
return remaining_ancestors;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::vector<unsigned> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellMutationStateCount()
{
std::vector<unsigned> mutation_state_count;
const std::vector<boost::shared_ptr<AbstractCellProperty> >& r_cell_properties
= mpCellPropertyRegistry->rGetAllCellProperties();
// Calculate mutation states count
for (unsigned i=0; i<r_cell_properties.size(); i++)
{
if (r_cell_properties[i]->IsSubType<AbstractCellMutationState>())
{
mutation_state_count.push_back(r_cell_properties[i]->GetCellCount());
}
}
// Reduce results onto all processes
if (PetscTools::IsParallel())
{
// Make sure the vector on each process has the same size
unsigned local_size = mutation_state_count.size();
unsigned global_size;
MPI_Allreduce(&local_size, &global_size, 1, MPI_UNSIGNED, MPI_MAX, PetscTools::GetWorld());
assert(local_size == global_size);
std::vector<unsigned> mutation_counts(global_size);
MPI_Allreduce(&mutation_state_count[0], &mutation_counts[0], mutation_counts.size(), MPI_UNSIGNED, MPI_SUM, PetscTools::GetWorld());
mutation_state_count = mutation_counts;
}
return mutation_state_count;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::vector<unsigned> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellProliferativeTypeCount()
{
std::vector<unsigned> proliferative_type_count;
const std::vector<boost::shared_ptr<AbstractCellProperty> >& r_cell_properties
= mpCellPropertyRegistry->rGetAllCellProperties();
// Calculate proliferative types count
for (unsigned i=0; i<r_cell_properties.size(); i++)
{
if (r_cell_properties[i]->IsSubType<AbstractCellProliferativeType>())
{
proliferative_type_count.push_back(r_cell_properties[i]->GetCellCount());
}
}
// Reduce results onto all processes
if (PetscTools::IsParallel())
{
// Make sure the vector on each process has the same size
unsigned local_size = proliferative_type_count.size();
unsigned global_size;
MPI_Allreduce(&local_size, &global_size, 1, MPI_UNSIGNED, MPI_MAX, PetscTools::GetWorld());
assert(local_size == global_size);
std::vector<unsigned> total_types_counts(global_size);
MPI_Allreduce(&proliferative_type_count[0], &total_types_counts[0], total_types_counts.size(), MPI_UNSIGNED, MPI_SUM, PetscTools::GetWorld());
proliferative_type_count = total_types_counts;
}
return proliferative_type_count;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::vector<unsigned> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellCyclePhaseCount()
{
std::vector<unsigned> cell_cycle_phase_count(5);
for (unsigned i=0; i<5; i++)
{
cell_cycle_phase_count[i] = 0;
}
/*
* Note that in parallel with a poor partition a process could end up with zero cells
* in which case the calculation should be skipped since `this->Begin()` is not defined.
*/
if (GetNumAllCells() > 0u)
{
if (dynamic_cast<AbstractPhaseBasedCellCycleModel*>((*(this->Begin()))->GetCellCycleModel()) == nullptr)
{
EXCEPTION("You are trying to record the cell cycle phase of cells with a non phase based cell cycle model.");
}
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
switch (static_cast<AbstractPhaseBasedCellCycleModel*>((*cell_iter)->GetCellCycleModel())->GetCurrentCellCyclePhase())
{
case G_ZERO_PHASE:
cell_cycle_phase_count[0]++;
break;
case G_ONE_PHASE:
cell_cycle_phase_count[1]++;
break;
case S_PHASE:
cell_cycle_phase_count[2]++;
break;
case G_TWO_PHASE:
cell_cycle_phase_count[3]++;
break;
case M_PHASE:
cell_cycle_phase_count[4]++;
break;
default:
NEVER_REACHED;
}
}
}
// Reduce results onto all processes
if (PetscTools::IsParallel())
{
std::vector<unsigned> phase_counts(cell_cycle_phase_count.size(), 0u);
MPI_Allreduce(&cell_cycle_phase_count[0], &phase_counts[0], phase_counts.size(), MPI_UNSIGNED, MPI_SUM, PetscTools::GetWorld());
cell_cycle_phase_count = phase_counts;
}
return cell_cycle_phase_count;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
CellPtr AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellUsingLocationIndex(unsigned index)
{
// Get the set of pointers to cells corresponding to this location index
std::set<CellPtr> cells = mLocationCellMap[index];
// If there is only one cell attached return the cell. Note currently only one cell per index.
if (cells.size() == 1)
{
return *(cells.begin());
}
if (cells.empty())
{
EXCEPTION("Location index input argument does not correspond to a Cell");
}
else
{
EXCEPTION("Multiple cells are attached to a single location index.");
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::set<CellPtr> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellsUsingLocationIndex(unsigned index)
{
// Return the set of pointers to cells corresponding to this location index, note the set may be empty.
return mLocationCellMap[index];
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsCellAttachedToLocationIndex(unsigned index)
{
// Get the set of pointers to cells corresponding to this location index
std::set<CellPtr> cells = mLocationCellMap[index];
// Return whether there is a cell attached to the location index
return !(cells.empty());
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::WriteDataToVisualizerSetupFile(out_stream& pVizSetupFile)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetCellUsingLocationIndex(unsigned index, CellPtr pCell)
{
// Clear the maps
mLocationCellMap[index].clear();
mCellLocationMap.erase(pCell.get());
// Replace with new cell
mLocationCellMap[index].insert(pCell);
// Do other half of the map
mCellLocationMap[pCell.get()] = index;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::AddCellUsingLocationIndex(unsigned index, CellPtr pCell)
{
mLocationCellMap[index].insert(pCell);
mCellLocationMap[pCell.get()] = index;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::RemoveCellUsingLocationIndex(unsigned index, CellPtr pCell)
{
std::set<CellPtr>::iterator cell_iter = mLocationCellMap[index].find(pCell);
if (cell_iter == mLocationCellMap[index].end())
{
EXCEPTION("Tried to remove a cell which is not attached to the given location index");
}
else
{
mLocationCellMap[index].erase(cell_iter);
mCellLocationMap.erase(pCell.get());
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::MoveCellInLocationMap(CellPtr pCell, unsigned old_index, unsigned new_index)
{
// Remove the cell from its current location
RemoveCellUsingLocationIndex(old_index, pCell);
// Add it to the new location
AddCellUsingLocationIndex(new_index, pCell);
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetLocationIndexUsingCell(CellPtr pCell)
{
// Check the cell is in the map
assert(this->mCellLocationMap.find(pCell.get()) != this->mCellLocationMap.end());
return mCellLocationMap[pCell.get()];
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
boost::shared_ptr<CellPropertyRegistry> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCellPropertyRegistry()
{
return mpCellPropertyRegistry;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> // added mutations
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetDefaultCellMutationStateAndProliferativeTypeOrdering()
{
boost::shared_ptr<CellPropertyRegistry> p_registry = GetCellPropertyRegistry();
if (!p_registry->HasOrderingBeenSpecified())
{
std::vector<boost::shared_ptr<AbstractCellProperty> > mutations_and_proliferative_types;
mutations_and_proliferative_types.push_back(p_registry->Get<WildTypeCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<ApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<ApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<ApcTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BetaCateninOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BetaCateninTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRApcTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRBCOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRBCTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRBCOneHitApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<MMRBCOneHitApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHMMRTwoHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHMMRApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHMMRApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCOneHitApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCOneHitApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHApcOneHitCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHApcLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<BCLOHCellMutationState>());
mutations_and_proliferative_types.push_back(p_registry->Get<StemCellProliferativeType>());
mutations_and_proliferative_types.push_back(p_registry->Get<TransitCellProliferativeType>());
mutations_and_proliferative_types.push_back(p_registry->Get<DifferentiatedCellProliferativeType>());
// Parallel process with no cells won't have the default property, so add it in
mutations_and_proliferative_types.push_back(p_registry->Get<DefaultCellProliferativeType>());
p_registry->SpecifyOrdering(mutations_and_proliferative_types);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetNumMMRCells()
{
std::vector<unsigned> mutation_state_count;
const std::vector<boost::shared_ptr<AbstractCellProperty> >& r_cell_properties
= mpCellPropertyRegistry->rGetAllCellProperties();
// Calculate mutation states count
for (unsigned i=0; i<r_cell_properties.size(); i++)
{
if (r_cell_properties[i]->IsSubType<AbstractCellMutationState>())
{
mutation_state_count.push_back(r_cell_properties[i]->GetCellCount());
}
}
// Reduce results onto all processes
if (PetscTools::IsParallel())
{
// Make sure the vector on each process has the same size
unsigned local_size = mutation_state_count.size();
unsigned global_size;
MPI_Allreduce(&local_size, &global_size, 1, MPI_UNSIGNED, MPI_MAX, PetscTools::GetWorld());
assert(local_size == global_size);
std::vector<unsigned> mutation_counts(global_size);
MPI_Allreduce(&mutation_state_count[0], &mutation_counts[0], mutation_counts.size(), MPI_UNSIGNED, MPI_SUM, PetscTools::GetWorld());
mutation_state_count = mutation_counts;
}
unsigned MMR_state_count = 0;
for (unsigned i=6; i<17; i++)
{
MMR_state_count += mutation_state_count[i];
}
return MMR_state_count;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double, SPACE_DIM> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetCentroidOfCellPopulation()
{
mCentroid = zero_vector<double>(SPACE_DIM);
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
mCentroid += GetLocationOfCellCentre(*cell_iter);
}
mCentroid /= this->GetNumRealCells();
return mCentroid;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::UpdateCellProcessLocation()
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::CloseRoundRobinWritersFiles()
{
typedef AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> cell_writer_t;
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->CloseFile();
}
typedef AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> pop_writer_t;
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->CloseFile();
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::CloseWritersFiles()
{
typedef AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> cell_writer_t;
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->CloseFile();
}
typedef AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> pop_writer_t;
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->CloseFile();
}
#ifdef CHASTE_VTK
*mpVtkMetaFile << " </Collection>\n";
*mpVtkMetaFile << "</VTKFile>\n";
mpVtkMetaFile->close();
#endif //CHASTE_VTK
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::OpenWritersFiles(OutputFileHandler& rOutputFileHandler)
{
#ifdef CHASTE_VTK
mpVtkMetaFile = rOutputFileHandler.OpenOutputFile("results.pvd");
*mpVtkMetaFile << "<?xml version=\"1.0\"?>\n";
*mpVtkMetaFile << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"LittleEndian\" compressor=\"vtkZLibDataCompressor\">\n";
*mpVtkMetaFile << " <Collection>\n";
#endif //CHASTE_VTK
if (mOutputResultsForChasteVisualizer)
{
if (!HasWriter<NodeLocationWriter>())
{
AddPopulationWriter<NodeLocationWriter>();
}
if (!HasWriter<BoundaryNodeWriter>())
{
AddPopulationWriter<BoundaryNodeWriter>();
}
if (!HasWriter<CellProliferativeTypesWriter>())
{
AddCellWriter<CellProliferativeTypesWriter>();
}
}
// Open output files for any cell writers
typedef AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> cell_writer_t;
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->OpenOutputFile(rOutputFileHandler);
}
// Open output files and write headers for any population writers
typedef AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> pop_writer_t;
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->OpenOutputFile(rOutputFileHandler);
p_pop_writer->WriteHeader(this);
}
// Open output files and write headers for any population count writers
typedef AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM> count_writer_t;
BOOST_FOREACH(boost::shared_ptr<count_writer_t> p_count_writer, mCellPopulationCountWriters)
{
p_count_writer->OpenOutputFile(rOutputFileHandler);
p_count_writer->WriteHeader(this);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::OpenRoundRobinWritersFilesForAppend(OutputFileHandler& rOutputFileHandler)
{
typedef AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> cell_writer_t;
typedef AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> pop_writer_t;
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->OpenOutputFileForAppend(rOutputFileHandler);
}
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->OpenOutputFileForAppend(rOutputFileHandler);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::WriteResultsToFiles(const std::string& rDirectory)
{
typedef AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> cell_writer_t;
typedef AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> pop_writer_t;
OutputFileHandler output_file_handler(rDirectory, false);
if (!(mCellWriters.empty() && mCellPopulationWriters.empty() && mCellPopulationCountWriters.empty()))
{
// An ordering must be specified for cell mutation states and cell proliferative types
SetDefaultCellMutationStateAndProliferativeTypeOrdering();
PetscTools::BeginRoundRobin();
{
OpenRoundRobinWritersFilesForAppend(output_file_handler);
// The master process writes time stamps
if (PetscTools::AmMaster())
{
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->WriteTimeStamp();
}
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->WriteTimeStamp();
}
}
for (typename std::vector<boost::shared_ptr<AbstractCellPopulationWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator pop_writer_iter = mCellPopulationWriters.begin();
pop_writer_iter != mCellPopulationWriters.end();
++pop_writer_iter)
{
AcceptPopulationWriter(*pop_writer_iter);
}
AcceptCellWritersAcrossPopulation();
// The top-most process adds a newline
if (PetscTools::AmTopMost())
{
BOOST_FOREACH(boost::shared_ptr<cell_writer_t> p_cell_writer, mCellWriters)
{
p_cell_writer->WriteNewline();
}
BOOST_FOREACH(boost::shared_ptr<pop_writer_t> p_pop_writer, mCellPopulationWriters)
{
p_pop_writer->WriteNewline();
}
}
CloseRoundRobinWritersFiles();
}
PetscTools::EndRoundRobin();
// Outside the round robin, deal with population count writers
typedef AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM> count_writer_t;
if (PetscTools::AmMaster())
{
// Open mCellPopulationCountWriters in append mode for writing, and write time stamps
BOOST_FOREACH(boost::shared_ptr<count_writer_t> p_count_writer, mCellPopulationCountWriters)
{
p_count_writer->OpenOutputFileForAppend(output_file_handler);
p_count_writer->WriteTimeStamp();
}
}
for (typename std::vector<boost::shared_ptr<AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator count_writer_iter = mCellPopulationCountWriters.begin();
count_writer_iter != mCellPopulationCountWriters.end();
++count_writer_iter)
{
AcceptPopulationCountWriter(*count_writer_iter);
}
if (PetscTools::AmMaster())
{
// Add a newline and close any output files
BOOST_FOREACH(boost::shared_ptr<count_writer_t> p_count_writer, mCellPopulationCountWriters)
{
p_count_writer->WriteNewline();
p_count_writer->CloseFile();
}
}
}
// VTK can only be written in 2 or 3 dimensions
if (SPACE_DIM > 1)
{
WriteVtkResultsToFile(rDirectory);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::AcceptCellWritersAcrossPopulation()
{
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
for (typename std::vector<boost::shared_ptr<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> > >::iterator cell_writer_iter = mCellWriters.begin();
cell_writer_iter != mCellWriters.end();
++cell_writer_iter)
{
AcceptCellWriter(*cell_writer_iter, *cell_iter);
}
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::OutputCellPopulationInfo(out_stream& rParamsFile)
{
std::string cell_population_type = GetIdentifier();
*rParamsFile << "\t<" << cell_population_type << ">\n";
OutputCellPopulationParameters(rParamsFile);
*rParamsFile << "\t</" << cell_population_type << ">\n";
*rParamsFile << "\n";
*rParamsFile << "\t<CellCycleModels>\n";
/**
* Loop over cells and generate a set of cell-cycle model classes
* that are present in the population.
*
* \todo this currently ignores different parameter regimes (#1453)
*/
std::set<std::string> unique_cell_cycle_models;
std::vector<CellPtr> first_cell_with_unique_CCM;
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
std::string identifier = cell_iter->GetCellCycleModel()->GetIdentifier();
if (unique_cell_cycle_models.count(identifier) == 0)
{
unique_cell_cycle_models.insert(identifier);
first_cell_with_unique_CCM.push_back((*cell_iter));
}
}
// Loop over unique cell-cycle models
for (unsigned i=0; i<first_cell_with_unique_CCM.size(); i++)
{
// Output cell-cycle model details
first_cell_with_unique_CCM[i]->GetCellCycleModel()->OutputCellCycleModelInfo(rParamsFile);
}
*rParamsFile << "\t</CellCycleModels>\n";
*rParamsFile << "\n";
*rParamsFile << "\t<SrnModels>\n";
/**
* Loop over cells and generate a set of SRN model classes
* that are present in the population.
*
* \todo this currently ignores different parameter regimes (#1453)
*/
std::set<std::string> unique_srn_models;
std::vector<CellPtr> first_cell_with_unique_SRN;
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
std::string identifier = cell_iter->GetSrnModel()->GetIdentifier();
if (unique_srn_models.count(identifier) == 0)
{
unique_srn_models.insert(identifier);
first_cell_with_unique_SRN.push_back((*cell_iter));
}
}
// Loop over unique SRN models
for (unsigned i=0; i<first_cell_with_unique_SRN.size(); i++)
{
// Output SRN model details
first_cell_with_unique_SRN[i]->GetSrnModel()->OutputSrnModelInfo(rParamsFile);
}
*rParamsFile << "\t</SrnModels>\n";
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::OutputCellPopulationParameters(out_stream& rParamsFile)
{
*rParamsFile << "\t\t<OutputResultsForChasteVisualizer>" << mOutputResultsForChasteVisualizer << "</OutputResultsForChasteVisualizer>\n";
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SimulationSetupHook(AbstractCellBasedSimulation<ELEMENT_DIM, SPACE_DIM>* pSimulation)
{
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetOutputResultsForChasteVisualizer()
{
return mOutputResultsForChasteVisualizer;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::SetOutputResultsForChasteVisualizer(bool outputResultsForChasteVisualizer)
{
mOutputResultsForChasteVisualizer = outputResultsForChasteVisualizer;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsRoomToDivide(CellPtr pCell)
{
return true;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
c_vector<double,SPACE_DIM> AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::GetSizeOfCellPopulation()
{
// Compute the centre of mass of the cell population
c_vector<double,SPACE_DIM> centre = GetCentroidOfCellPopulation();
// Loop over cells and find the maximum distance from the centre of mass in each dimension
c_vector<double,SPACE_DIM> max_distance_from_centre = zero_vector<double>(SPACE_DIM);
for (typename AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::Iterator cell_iter = this->Begin();
cell_iter != this->End();
++cell_iter)
{
c_vector<double,SPACE_DIM> cell_location = GetLocationOfCellCentre(*cell_iter);
// Note that we define this vector before setting it as otherwise the profiling build will break (see #2367)
c_vector<double,SPACE_DIM> displacement;
displacement = centre - cell_location;
for (unsigned i=0; i<SPACE_DIM; i++)
{
if (displacement[i] > max_distance_from_centre[i])
{
max_distance_from_centre[i] = displacement[i];
}
}
}
return max_distance_from_centre;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::pair<unsigned,unsigned> AbstractCellPopulation<ELEMENT_DIM,SPACE_DIM>::CreateOrderedPair(unsigned index1, unsigned index2)
{
assert(index1 != index2);
std::pair<unsigned, unsigned> ordered_pair;
if (index1 < index2)
{
ordered_pair.first = index1;
ordered_pair.second = index2;
}
else
{
ordered_pair.first = index2;
ordered_pair.second = index1;
}
return ordered_pair;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
bool AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>::IsPdeNodeAssociatedWithNonApoptoticCell(unsigned pdeNodeIndex)
{
bool non_apoptotic_cell_present = false;
if (IsCellAttachedToLocationIndex(pdeNodeIndex))
{
non_apoptotic_cell_present = !(GetCellUsingLocationIndex(pdeNodeIndex)->template HasCellProperty<ApoptoticCellProperty>());
}
return non_apoptotic_cell_present;
}
// Explicit instantiation
template class AbstractCellPopulation<1,1>;
template class AbstractCellPopulation<1,2>;
template class AbstractCellPopulation<2,2>;
template class AbstractCellPopulation<1,3>;
template class AbstractCellPopulation<2,3>;
template class AbstractCellPopulation<3,3>;
| 38.79329 | 180 | 0.725708 | [
"vector",
"model"
] |
73453492bfe65344a5706d6c4ad8122c8239ff52 | 7,681 | cpp | C++ | src/QR-Code-generator/QrSegment.cpp | Aifolin/motif-gui | 96911f334c0cecb907cfb41c0cf3b9029a480039 | [
"BSD-3-Clause"
] | null | null | null | src/QR-Code-generator/QrSegment.cpp | Aifolin/motif-gui | 96911f334c0cecb907cfb41c0cf3b9029a480039 | [
"BSD-3-Clause"
] | null | null | null | src/QR-Code-generator/QrSegment.cpp | Aifolin/motif-gui | 96911f334c0cecb907cfb41c0cf3b9029a480039 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2014-2019, The Motif Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
* QR Code generator library (C++)
*
* Copyright (c) 2016 Project Nayuki
* https://www.nayuki.io/page/qr-code-generator-library
*
* (MIT License)
* 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 <cstddef>
#include "BitBuffer.hpp"
#include "QrSegment.hpp"
qrcodegen::QrSegment::Mode::Mode(int mode, int cc0, int cc1, int cc2) :
modeBits(mode) {
numBitsCharCount[0] = cc0;
numBitsCharCount[1] = cc1;
numBitsCharCount[2] = cc2;
}
int qrcodegen::QrSegment::Mode::numCharCountBits(int ver) const {
if ( 1 <= ver && ver <= 9) return numBitsCharCount[0];
else if (10 <= ver && ver <= 26) return numBitsCharCount[1];
else if (27 <= ver && ver <= 40) return numBitsCharCount[2];
else throw "Version number out of range";
}
const qrcodegen::QrSegment::Mode qrcodegen::QrSegment::Mode::NUMERIC (0x1, 10, 12, 14);
const qrcodegen::QrSegment::Mode qrcodegen::QrSegment::Mode::ALPHANUMERIC(0x2, 9, 11, 13);
const qrcodegen::QrSegment::Mode qrcodegen::QrSegment::Mode::BYTE (0x4, 8, 16, 16);
const qrcodegen::QrSegment::Mode qrcodegen::QrSegment::Mode::KANJI (0x8, 8, 10, 12);
qrcodegen::QrSegment qrcodegen::QrSegment::makeBytes(const std::vector<uint8_t> &data) {
return QrSegment(Mode::BYTE, data.size(), data, data.size() * 8);
}
qrcodegen::QrSegment qrcodegen::QrSegment::makeNumeric(const char *digits) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *digits != '\0'; digits++, charCount++) {
char c = *digits;
if (c < '0' || c > '9')
throw "String contains non-numeric characters";
accumData = accumData * 10 + (c - '0');
accumCount++;
if (accumCount == 3) {
bb.appendBits(accumData, 10);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 or 2 digits remaining
bb.appendBits(accumData, accumCount * 3 + 1);
return QrSegment(Mode::NUMERIC, charCount, bb.getBytes(), bb.getBitLength());
}
qrcodegen::QrSegment qrcodegen::QrSegment::makeAlphanumeric(const char *text) {
BitBuffer bb;
int accumData = 0;
int accumCount = 0;
int charCount = 0;
for (; *text != '\0'; text++, charCount++) {
char c = *text;
if (c < ' ' || c > 'Z')
throw "String contains unencodable characters in alphanumeric mode";
accumData = accumData * 45 + ALPHANUMERIC_ENCODING_TABLE[c - ' '];
accumCount++;
if (accumCount == 2) {
bb.appendBits(accumData, 11);
accumData = 0;
accumCount = 0;
}
}
if (accumCount > 0) // 1 character remaining
bb.appendBits(accumData, 6);
return QrSegment(Mode::ALPHANUMERIC, charCount, bb.getBytes(), bb.getBitLength());
}
std::vector<qrcodegen::QrSegment> qrcodegen::QrSegment::makeSegments(const char *text) {
// Select the most efficient segment encoding automatically
std::vector<QrSegment> result;
if (*text == '\0'); // Leave the vector empty
else if (QrSegment::isNumeric(text))
result.push_back(QrSegment::makeNumeric(text));
else if (QrSegment::isAlphanumeric(text))
result.push_back(QrSegment::makeAlphanumeric(text));
else {
std::vector<uint8_t> bytes;
for (; *text != '\0'; text++)
bytes.push_back(static_cast<uint8_t>(*text));
result.push_back(QrSegment::makeBytes(bytes));
}
return result;
}
qrcodegen::QrSegment::QrSegment(const Mode &md, int numCh, const std::vector<uint8_t> &b, int bitLen) :
mode(md),
numChars(numCh),
data(b),
bitLength(bitLen) {
if (numCh < 0 || bitLen < 0 || b.size() != static_cast<unsigned int>((bitLen + 7) / 8))
throw "Invalid value";
}
int qrcodegen::QrSegment::getTotalBits(const std::vector<QrSegment> &segs, int version) {
if (version < 1 || version > 40)
throw "Version number out of range";
int result = 0;
for (size_t i = 0; i < segs.size(); i++) {
const QrSegment &seg(segs.at(i));
int ccbits = seg.mode.numCharCountBits(version);
// Fail if segment length value doesn't fit in the length field's bit-width
if (seg.numChars >= (1 << ccbits))
return -1;
result += 4 + ccbits + seg.bitLength;
}
return result;
}
bool qrcodegen::QrSegment::isAlphanumeric(const char *text) {
for (; *text != '\0'; text++) {
char c = *text;
if (c < ' ' || c > 'Z' || ALPHANUMERIC_ENCODING_TABLE[c - ' '] == -1)
return false;
}
return true;
}
bool qrcodegen::QrSegment::isNumeric(const char *text) {
for (; *text != '\0'; text++) {
char c = *text;
if (c < '0' || c > '9')
return false;
}
return true;
}
const int8_t qrcodegen::QrSegment::ALPHANUMERIC_ENCODING_TABLE[59] = {
// SP, !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, @, // ASCII codes 32 to 64
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, -1, // Array indices 0 to 32
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, // Array indices 33 to 58
// A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, // ASCII codes 65 to 90
};
| 38.024752 | 161 | 0.672438 | [
"vector"
] |
7347f28ff9bacead8593ddbfa42a7f625761ae67 | 8,607 | cpp | C++ | tools/skqp/jni/org_skia_skqp_SkQPRunner.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/skqp/jni/org_skia_skqp_SkQPRunner.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | tools/skqp/jni/org_skia_skqp_SkQPRunner.cpp | ndsol/subskia | 9a8f6e5ffc6676281a4389aa1503ba6c4352eaca | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <mutex>
#include <vector>
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include "gm_runner.h"
#include "gm_knowledge.h"
#include "skqp_asset_manager.h"
#include "SkStream.h"
////////////////////////////////////////////////////////////////////////////////
extern "C" {
JNIEXPORT void JNICALL Java_org_skia_skqp_SkQP_nInit(JNIEnv*, jobject, jobject, jstring);
JNIEXPORT jfloat JNICALL Java_org_skia_skqp_SkQP_nExecuteGM(JNIEnv*, jobject, jint, jint);
JNIEXPORT jobjectArray JNICALL Java_org_skia_skqp_SkQP_nExecuteUnitTest(JNIEnv*, jobject,
jint);
JNIEXPORT void JNICALL Java_org_skia_skqp_SkQP_nMakeReport(JNIEnv*, jobject);
} // extern "C"
////////////////////////////////////////////////////////////////////////////////
namespace {
struct AndroidAssetManager : public skqp::AssetManager {
AAssetManager* fMgr = nullptr;
std::unique_ptr<SkStreamAsset> open(const char* path) override {
struct AAStrm : public SkStreamAsset {
AAssetManager* fMgr;
std::string fPath;
AAsset* fAsset;
AAStrm(AAssetManager* m, std::string p, AAsset* a)
: fMgr(m), fPath(std::move(p)), fAsset(a) {}
~AAStrm() override { AAsset_close(fAsset); }
size_t read(void* buffer, size_t size) override {
size_t r = SkTMin(size, SkToSizeT(AAsset_getRemainingLength(fAsset)));
if (buffer) {
return SkToSizeT(AAsset_read(fAsset, buffer, r));
} else {
this->move(SkTo<long>(r));
return r;
}
}
size_t getLength() const override { return SkToSizeT(AAsset_getLength(fAsset)); }
size_t peek(void* buffer, size_t size) const override {
size_t r = const_cast<AAStrm*>(this)->read(buffer, size);
const_cast<AAStrm*>(this)->move(-(long)r);
return r;
}
bool isAtEnd() const override { return 0 == AAsset_getRemainingLength(fAsset); }
bool rewind() override { return this->seek(0); }
size_t getPosition() const override {
return SkToSizeT(AAsset_seek(fAsset, 0, SEEK_CUR));
}
bool seek(size_t position) override {
return -1 != AAsset_seek(fAsset, SkTo<off_t>(position), SEEK_SET);
}
bool move(long offset) override {
return -1 != AAsset_seek(fAsset, SkTo<off_t>(offset), SEEK_CUR);
}
SkStreamAsset* onDuplicate() const override {
AAsset* dupAsset = AndroidAssetManager::OpenAsset(fMgr, fPath.c_str());
return dupAsset ? new AAStrm(fMgr, fPath, dupAsset) : nullptr;
}
SkStreamAsset* onFork() const override {
SkStreamAsset* dup = this->onDuplicate();
if (dup) { (void)dup->seek(this->getPosition()); }
return dup;
}
};
AAsset* asset = AndroidAssetManager::OpenAsset(fMgr, path);
return asset ? std::unique_ptr<SkStreamAsset>(new AAStrm(fMgr, std::string(path), asset))
: nullptr;
}
static AAsset* OpenAsset(AAssetManager* mgr, const char* path) {
std::string fullPath = std::string("gmkb/") + path;
return mgr ? AAssetManager_open(mgr, fullPath.c_str(), AASSET_MODE_STREAMING) : nullptr;
}
};
}
static void set_string_array_element(JNIEnv* env, jobjectArray a, const char* s, unsigned i) {
jstring jstr = env->NewStringUTF(s);
env->SetObjectArrayElement(a, (jsize)i, jstr);
env->DeleteLocalRef(jstr);
}
#define jassert(env, cond) do { if (!(cond)) { \
(env)->ThrowNew((env)->FindClass("java/lang/Exception"), \
__FILE__ ": assert(" #cond ") failed."); } } while (0)
////////////////////////////////////////////////////////////////////////////////
static std::mutex gMutex;
static std::vector<gm_runner::SkiaBackend> gBackends;
static std::vector<gm_runner::GMFactory> gGMs;
static std::vector<gm_runner::UnitTest> gUnitTests;
static AndroidAssetManager gAssetManager;
static std::string gReportDirectory;
static jclass gStringClass = nullptr;
////////////////////////////////////////////////////////////////////////////////
template <typename T, typename F>
jobjectArray to_java_string_array(JNIEnv* env,
const std::vector<T>& array,
F toString) {
jobjectArray jarray = env->NewObjectArray((jint)array.size(), gStringClass, nullptr);
for (unsigned i = 0; i < array.size(); ++i) {
set_string_array_element(env, jarray, std::string(toString(array[i])).c_str(), i);
}
return jarray;
}
void Java_org_skia_skqp_SkQP_nInit(JNIEnv* env, jobject object, jobject assetManager,
jstring dataDir) {
jclass clazz = env->GetObjectClass(object);
jassert(env, assetManager);
gm_runner::InitSkia();
std::lock_guard<std::mutex> lock(gMutex);
gAssetManager.fMgr = AAssetManager_fromJava(env, assetManager);
jassert(env, gAssetManager.fMgr);
const char* dataDirString = env->GetStringUTFChars(dataDir, nullptr);
gReportDirectory = std::string(dataDirString) + "/skqp_report";
env->ReleaseStringUTFChars(dataDir, dataDirString);
gBackends = gm_runner::GetSupportedBackends();
gGMs = gm_runner::GetGMFactories(&gAssetManager);
gUnitTests = gm_runner::GetUnitTests();
gStringClass = env->FindClass("java/lang/String");
constexpr char stringArrayType[] = "[Ljava/lang/String;";
env->SetObjectField(object, env->GetFieldID(clazz, "mBackends", stringArrayType),
to_java_string_array(env, gBackends, gm_runner::GetBackendName));
env->SetObjectField(object, env->GetFieldID(clazz, "mUnitTests", stringArrayType),
to_java_string_array(env, gUnitTests, gm_runner::GetUnitTestName));
env->SetObjectField(object, env->GetFieldID(clazz, "mGMs", stringArrayType),
to_java_string_array(env, gGMs, gm_runner::GetGMName));
}
jfloat Java_org_skia_skqp_SkQP_nExecuteGM(JNIEnv* env,
jobject object,
jint gmIndex,
jint backendIndex) {
jassert(env, gmIndex < (jint)gGMs.size());
jassert(env, backendIndex < (jint)gBackends.size());
gm_runner::GMFactory gm;
gm_runner::SkiaBackend backend;
std::string reportDirectoryPath;
{
std::lock_guard<std::mutex> lock(gMutex);
backend = gBackends[backendIndex];
gm = gGMs[gmIndex];
reportDirectoryPath = gReportDirectory;
}
float result;
gm_runner::Error error;
std::tie(result, error) = gm_runner::EvaluateGM(backend, gm, &gAssetManager,
reportDirectoryPath.c_str());
if (error != gm_runner::Error::None) {
(void)env->ThrowNew(env->FindClass("org/skia/skqp/SkQPException"),
gm_runner::GetErrorString(error));
}
return result;
}
jobjectArray Java_org_skia_skqp_SkQP_nExecuteUnitTest(JNIEnv* env,
jobject object,
jint index) {
jassert(env, index < (jint)gUnitTests.size());
gm_runner::UnitTest test;
{
std::lock_guard<std::mutex> lock(gMutex);
test = gUnitTests[index];
}
std::vector<std::string> errors = gm_runner::ExecuteTest(test);
if (errors.size() == 0) {
return nullptr;
}
jobjectArray array = env->NewObjectArray(errors.size(), gStringClass, nullptr);
for (unsigned i = 0; i < errors.size(); ++i) {
set_string_array_element(env, array, errors[i].c_str(), i);
}
return (jobjectArray)env->NewGlobalRef(array);
}
void Java_org_skia_skqp_SkQP_nMakeReport(JNIEnv*, jobject) {
std::string reportDirectoryPath;
{
std::lock_guard<std::mutex> lock(gMutex);
reportDirectoryPath = gReportDirectory;
}
(void)gmkb::MakeReport(reportDirectoryPath.c_str());
}
////////////////////////////////////////////////////////////////////////////////
| 41.57971 | 97 | 0.580109 | [
"object",
"vector"
] |
735783a844d2eabac3b71b0455f8838e543b66a8 | 6,138 | inl | C++ | paddle/pten/core/dense_tensor.inl | ShiningZhang/Paddle | 94ab14a28aef0a1f96975b0ce80f788cf10daacb | [
"Apache-2.0"
] | 1 | 2022-02-20T09:01:02.000Z | 2022-02-20T09:01:02.000Z | paddle/pten/core/dense_tensor.inl | heiziiiii/Paddle | c6950ab2573aece1fa0728aef1446bd8b0b8c1a0 | [
"Apache-2.0"
] | null | null | null | paddle/pten/core/dense_tensor.inl | heiziiiii/Paddle | c6950ab2573aece1fa0728aef1446bd8b0b8c1a0 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/* --------------------------- */
/* From framework::Tensor */
/* --------------------------- */
/* The following members & interfaces were copied from framework::Tensor,
so as to facilitate the unification of different Tensors
Will be adjusted/removed/moved in the near future
*/
public:
/* Temporarily put InplaceVersion inside DenseTensor.
Will move to AutogradMeta as soon as we switch to Eager Dygraph.
*/
class InplaceVersion {
public:
bool IsUnique() const { return inplace_version_ == 0; }
void Bump() { ++inplace_version_; }
uint32_t CurrentVersion() const { return inplace_version_; }
void SetInplaceVersionToZero() { inplace_version_ = 0; }
private:
uint32_t inplace_version_{0};
};
/* @jim19930609: Remove dependency on protobuf after Tensor Unification.
*/
explicit DenseTensor(paddle::experimental::DataType dtype);
/// \brief Use existing storage space to create dense tensor. This interface
/// can be used to deliberately create an uninitialized dense tensor.
/// \param storage The existing storage.
/// \param meta The meta data of dense tensor.
DenseTensor(intrusive_ptr<Storage> storage, const DenseTensorMeta& meta);
/// \brief Use existing storage space to create dense tensor. This interface
/// can be used to deliberately create an uninitialized dense tensor.
/// \param storage The existing storage.
/// \param meta The meta data of dense tensor.
DenseTensor(intrusive_ptr<Storage> storage, DenseTensorMeta&& meta);
inline bool IsInitialized() const { return holder_ != nullptr; }
template <typename T>
T* mutable_data(const paddle::platform::Place& place,
size_t requested_size = 0);
template <typename T>
T* mutable_data(const DDim& dims,
const paddle::platform::Place& place,
size_t requested_size = 0);
void* mutable_data(const paddle::platform::Place& place,
paddle::experimental::DataType type,
size_t requested_size = 0);
void* mutable_data(const paddle::platform::Place& place,
size_t requested_size = 0);
void* mutable_data(const paddle::platform::Place& place,
paddle::experimental::DataType type,
const pten::Stream& stream);
/* @jim19930609: Remove dependency on protobuf after Tensor Unification.
*/
paddle::experimental::DataType type() const;
// memory size returns the holding memory size in byte.
size_t memory_size() const;
void check_memory_size() const;
void set_layout(const paddle::framework::DataLayout layout);
void clear() {
holder_.reset();
meta_.offset = 0;
}
void ShareBufferWith(const DenseTensor& tensor);
void ShareDataTypeWith(const DenseTensor& tensor) {
meta_.dtype = tensor.meta().dtype;
}
bool IsSharedBufferWith(const DenseTensor& src) const {
return holder_ && holder_ == src.Holder();
}
const std::shared_ptr<pten::Allocation>& Holder() const { return holder_; }
void set_offset(size_t offset) { meta_.offset = offset; }
size_t offset() const { return meta_.offset; }
std::shared_ptr<pten::Allocation> MoveMemoryHolder() {
return std::move(holder_);
}
void ResetHolder(const std::shared_ptr<pten::Allocation>& holder);
void ResetHolderWithType(const std::shared_ptr<pten::Allocation>& holder,
paddle::experimental::DataType type);
void set_type(paddle::experimental::DataType type);
InplaceVersion& InplaceVersionCounter() {
return *inplace_version_counter_;
}
/*! The internal of two tensors share the same memory block. */
DenseTensor& ShareDataWith(const DenseTensor& src);
/*! The internal of two tensors share the same inplace version counter. */
DenseTensor& ShareInplaceVersionCounterWith(const DenseTensor& src);
DenseTensor Slice(int64_t begin_idx, int64_t end_idx) const;
std::vector<DenseTensor> Split(int64_t split_size, int64_t axis) const;
std::vector<DenseTensor> Chunk(int64_t chunks, int64_t axis) const;
protected:
std::shared_ptr<InplaceVersion> inplace_version_counter_{std::make_shared<InplaceVersion>()};
/* @jim19930609: This is a hack
In general, it is badly designed to fuse MKLDNN-specific objects into a
generic Tensor.
We temporarily leave them here to unblock Tensor Unification progress.
In the final state, we should come up with a MKLDNN_Tensor and move the
following codes there.
*/
#ifdef PADDLE_WITH_MKLDNN
public:
inline dnnl::memory::format_tag format() const { return format_; }
inline void set_format(const dnnl::memory::format_tag format) {
format_ = format;
}
protected:
/**
* @brief the detail format of memory block which have layout as kMKLDNN
*
* @note MKLDNN lib support various memory format like nchw, nhwc, nChw8C,
* nChw16c, etc. For a MKLDNN memory block, layout will be set as
* DataLayout::kMKLDNN meanwhile detail memory format will be kept in
* this field.
*/
dnnl::memory::format_tag format_ = dnnl::memory::format_tag::undef;
#endif
/* ------------------------------ */
/* From framework::LoDTensor */
/* ------------------------------ */
/* The following members & interfaces were copied from framework::Tensor,
so as to facilitate the unification of different Tensors
Will be adjusted/removed/moved in the near future
*/
public:
explicit DenseTensor(const LoD& lod);
void set_lod(const LoD& lod);
LoD* mutable_lod();
/*
* Get the start offset and end offset of an element from LoD.
*/
std::pair<size_t, size_t> lod_element(size_t level, size_t elem) const;
size_t NumLevels() const;
size_t NumElements(size_t level = 0) const;
| 32.47619 | 93 | 0.721733 | [
"vector"
] |
735bfda6d8faf81165f95660c096c5ba19b1a9ab | 19,460 | cpp | C++ | gdal-1.11.0/alg/gdalmediancut.cpp | tilemapjp/gdal_mobile | f2bea3b017bb09c71f72c8e953a808f51e115c90 | [
"MIT"
] | 1 | 2015-07-04T20:09:20.000Z | 2015-07-04T20:09:20.000Z | gdal-1.11.0/alg/gdalmediancut.cpp | tilemapjp/gdal_mobile | f2bea3b017bb09c71f72c8e953a808f51e115c90 | [
"MIT"
] | null | null | null | gdal-1.11.0/alg/gdalmediancut.cpp | tilemapjp/gdal_mobile | f2bea3b017bb09c71f72c8e953a808f51e115c90 | [
"MIT"
] | null | null | null | /******************************************************************************
* $Id: gdalmediancut.cpp 27044 2014-03-16 23:41:27Z rouault $
*
* Project: CIETMap Phase 2
* Purpose: Use median cut algorithm to generate an near-optimal PCT for a
* given RGB image. Implemented as function GDALComputeMedianCutPCT.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2001, Frank Warmerdam
* Copyright (c) 2007-2010, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************
*
* This code was based on the tiffmedian.c code from libtiff (www.libtiff.org)
* which was based on a paper by Paul Heckbert:
*
* "Color Image Quantization for Frame Buffer Display", Paul
* Heckbert, SIGGRAPH proceedings, 1982, pp. 297-307.
*
*/
#include "gdal_priv.h"
#include "gdal_alg.h"
CPL_CVSID("$Id: gdalmediancut.cpp 27044 2014-03-16 23:41:27Z rouault $");
#define MAX_CMAP_SIZE 256
#define COLOR_DEPTH 8
#define MAX_COLOR 256
#define GMC_B_DEPTH 5 /* # bits/pixel to use */
#define GMC_B_LEN (1L<<GMC_B_DEPTH)
#define COLOR_SHIFT (COLOR_DEPTH-GMC_B_DEPTH)
typedef struct colorbox {
struct colorbox *next, *prev;
int rmin, rmax;
int gmin, gmax;
int bmin, bmax;
int total;
} Colorbox;
static void splitbox(Colorbox* ptr, int (*histogram)[GMC_B_LEN][GMC_B_LEN],
Colorbox **pfreeboxes, Colorbox **pusedboxes);
static void shrinkbox(Colorbox* box, int (*histogram)[GMC_B_LEN][GMC_B_LEN]);
static Colorbox* largest_box(Colorbox *usedboxes);
/************************************************************************/
/* GDALComputeMedianCutPCT() */
/************************************************************************/
/**
* Compute optimal PCT for RGB image.
*
* This function implements a median cut algorithm to compute an "optimal"
* pseudocolor table for representing an input RGB image. This PCT could
* then be used with GDALDitherRGB2PCT() to convert a 24bit RGB image into
* an eightbit pseudo-colored image.
*
* This code was based on the tiffmedian.c code from libtiff (www.libtiff.org)
* which was based on a paper by Paul Heckbert:
*
* \verbatim
* "Color Image Quantization for Frame Buffer Display", Paul
* Heckbert, SIGGRAPH proceedings, 1982, pp. 297-307.
* \endverbatim
*
* The red, green and blue input bands do not necessarily need to come
* from the same file, but they must be the same width and height. They will
* be clipped to 8bit during reading, so non-eight bit bands are generally
* inappropriate.
*
* @param hRed Red input band.
* @param hGreen Green input band.
* @param hBlue Blue input band.
* @param pfnIncludePixel function used to test which pixels should be included
* in the analysis. At this time this argument is ignored and all pixels are
* utilized. This should normally be NULL.
* @param nColors the desired number of colors to be returned (2-256).
* @param hColorTable the colors will be returned in this color table object.
* @param pfnProgress callback for reporting algorithm progress matching the
* GDALProgressFunc() semantics. May be NULL.
* @param pProgressArg callback argument passed to pfnProgress.
*
* @return returns CE_None on success or CE_Failure if an error occurs.
*/
extern "C" int CPL_STDCALL
GDALComputeMedianCutPCT( GDALRasterBandH hRed,
GDALRasterBandH hGreen,
GDALRasterBandH hBlue,
int (*pfnIncludePixel)(int,int,void*),
int nColors,
GDALColorTableH hColorTable,
GDALProgressFunc pfnProgress,
void * pProgressArg )
{
VALIDATE_POINTER1( hRed, "GDALComputeMedianCutPCT", CE_Failure );
VALIDATE_POINTER1( hGreen, "GDALComputeMedianCutPCT", CE_Failure );
VALIDATE_POINTER1( hBlue, "GDALComputeMedianCutPCT", CE_Failure );
int nXSize, nYSize;
CPLErr err = CE_None;
/* -------------------------------------------------------------------- */
/* Validate parameters. */
/* -------------------------------------------------------------------- */
nXSize = GDALGetRasterBandXSize( hRed );
nYSize = GDALGetRasterBandYSize( hRed );
if( GDALGetRasterBandXSize( hGreen ) != nXSize
|| GDALGetRasterBandYSize( hGreen ) != nYSize
|| GDALGetRasterBandXSize( hBlue ) != nXSize
|| GDALGetRasterBandYSize( hBlue ) != nYSize )
{
CPLError( CE_Failure, CPLE_IllegalArg,
"Green or blue band doesn't match size of red band.\n" );
return CE_Failure;
}
if( pfnIncludePixel != NULL )
{
CPLError( CE_Failure, CPLE_IllegalArg,
"GDALComputeMedianCutPCT() doesn't currently support "
" pfnIncludePixel function." );
return CE_Failure;
}
if ( nColors <= 0 )
{
CPLError( CE_Failure, CPLE_IllegalArg,
"GDALComputeMedianCutPCT() : nColors must be strictly greater than 1." );
return CE_Failure;
}
if ( nColors > 256 )
{
CPLError( CE_Failure, CPLE_IllegalArg,
"GDALComputeMedianCutPCT() : nColors must be lesser than or equal to 256." );
return CE_Failure;
}
if( pfnProgress == NULL )
pfnProgress = GDALDummyProgress;
/* ==================================================================== */
/* STEP 1: crate empty boxes. */
/* ==================================================================== */
int i;
Colorbox *box_list, *ptr;
int (*histogram)[GMC_B_LEN][GMC_B_LEN];
Colorbox *freeboxes;
Colorbox *usedboxes;
histogram = (int (*)[GMC_B_LEN][GMC_B_LEN])
CPLCalloc(GMC_B_LEN * GMC_B_LEN * GMC_B_LEN,sizeof(int));
usedboxes = NULL;
box_list = freeboxes = (Colorbox *)CPLMalloc(nColors*sizeof (Colorbox));
freeboxes[0].next = &freeboxes[1];
freeboxes[0].prev = NULL;
for (i = 1; i < nColors-1; ++i) {
freeboxes[i].next = &freeboxes[i+1];
freeboxes[i].prev = &freeboxes[i-1];
}
freeboxes[nColors-1].next = NULL;
freeboxes[nColors-1].prev = &freeboxes[nColors-2];
/* ==================================================================== */
/* Build histogram. */
/* ==================================================================== */
GByte *pabyRedLine, *pabyGreenLine, *pabyBlueLine;
int iLine, iPixel;
/* -------------------------------------------------------------------- */
/* Initialize the box datastructures. */
/* -------------------------------------------------------------------- */
ptr = freeboxes;
freeboxes = ptr->next;
if (freeboxes)
freeboxes->prev = NULL;
ptr->next = usedboxes;
usedboxes = ptr;
if (ptr->next)
ptr->next->prev = ptr;
ptr->rmin = ptr->gmin = ptr->bmin = 999;
ptr->rmax = ptr->gmax = ptr->bmax = -1;
ptr->total = nXSize * nYSize;
/* -------------------------------------------------------------------- */
/* Collect histogram. */
/* -------------------------------------------------------------------- */
pabyRedLine = (GByte *) VSIMalloc(nXSize);
pabyGreenLine = (GByte *) VSIMalloc(nXSize);
pabyBlueLine = (GByte *) VSIMalloc(nXSize);
if (pabyRedLine == NULL ||
pabyGreenLine == NULL ||
pabyBlueLine == NULL)
{
CPLError( CE_Failure, CPLE_OutOfMemory,
"VSIMalloc(): Out of memory in GDALComputeMedianCutPCT" );
err = CE_Failure;
goto end_and_cleanup;
}
for( iLine = 0; iLine < nYSize; iLine++ )
{
if( !pfnProgress( iLine / (double) nYSize,
"Generating Histogram", pProgressArg ) )
{
CPLError( CE_Failure, CPLE_UserInterrupt, "User Terminated" );
err = CE_Failure;
goto end_and_cleanup;
}
GDALRasterIO( hRed, GF_Read, 0, iLine, nXSize, 1,
pabyRedLine, nXSize, 1, GDT_Byte, 0, 0 );
GDALRasterIO( hGreen, GF_Read, 0, iLine, nXSize, 1,
pabyGreenLine, nXSize, 1, GDT_Byte, 0, 0 );
GDALRasterIO( hBlue, GF_Read, 0, iLine, nXSize, 1,
pabyBlueLine, nXSize, 1, GDT_Byte, 0, 0 );
for( iPixel = 0; iPixel < nXSize; iPixel++ )
{
int nRed, nGreen, nBlue;
nRed = pabyRedLine[iPixel] >> COLOR_SHIFT;
nGreen = pabyGreenLine[iPixel] >> COLOR_SHIFT;
nBlue = pabyBlueLine[iPixel] >> COLOR_SHIFT;
ptr->rmin = MIN(ptr->rmin, nRed);
ptr->gmin = MIN(ptr->gmin, nGreen);
ptr->bmin = MIN(ptr->bmin, nBlue);
ptr->rmax = MAX(ptr->rmax, nRed);
ptr->gmax = MAX(ptr->gmax, nGreen);
ptr->bmax = MAX(ptr->bmax, nBlue);
histogram[nRed][nGreen][nBlue]++;
}
}
if( !pfnProgress( 1.0, "Generating Histogram", pProgressArg ) )
{
CPLError( CE_Failure, CPLE_UserInterrupt, "User Terminated" );
err = CE_Failure;
goto end_and_cleanup;
}
/* ==================================================================== */
/* STEP 3: continually subdivide boxes until no more free */
/* boxes remain or until all colors assigned. */
/* ==================================================================== */
while (freeboxes != NULL) {
ptr = largest_box(usedboxes);
if (ptr != NULL)
splitbox(ptr, histogram, &freeboxes, &usedboxes);
else
freeboxes = NULL;
}
/* ==================================================================== */
/* STEP 4: assign colors to all boxes */
/* ==================================================================== */
for (i = 0, ptr = usedboxes; ptr != NULL; ++i, ptr = ptr->next)
{
GDALColorEntry sEntry;
sEntry.c1 = (GByte) (((ptr->rmin + ptr->rmax) << COLOR_SHIFT) / 2);
sEntry.c2 = (GByte) (((ptr->gmin + ptr->gmax) << COLOR_SHIFT) / 2);
sEntry.c3 = (GByte) (((ptr->bmin + ptr->bmax) << COLOR_SHIFT) / 2);
sEntry.c4 = 255;
GDALSetColorEntry( hColorTable, i, &sEntry );
}
end_and_cleanup:
CPLFree( pabyRedLine );
CPLFree( pabyGreenLine );
CPLFree( pabyBlueLine );
/* We're done with the boxes now */
CPLFree(box_list);
freeboxes = usedboxes = NULL;
CPLFree( histogram );
return err;
}
/************************************************************************/
/* largest_box() */
/************************************************************************/
static Colorbox *
largest_box(Colorbox *usedboxes)
{
Colorbox *p, *b;
int size;
b = NULL;
size = -1;
for (p = usedboxes; p != NULL; p = p->next)
if ((p->rmax > p->rmin || p->gmax > p->gmin ||
p->bmax > p->bmin) && p->total > size)
size = (b = p)->total;
return (b);
}
/************************************************************************/
/* splitbox() */
/************************************************************************/
static void
splitbox(Colorbox* ptr, int (*histogram)[GMC_B_LEN][GMC_B_LEN],
Colorbox **pfreeboxes, Colorbox **pusedboxes)
{
int hist2[GMC_B_LEN];
int first=0, last=0;
Colorbox *new_cb;
int *iptr, *histp;
int i, j;
int ir,ig,ib;
int sum, sum1, sum2;
enum { RED, GREEN, BLUE } axis;
/*
* See which axis is the largest, do a histogram along that
* axis. Split at median point. Contract both new boxes to
* fit points and return
*/
i = ptr->rmax - ptr->rmin;
if (i >= ptr->gmax - ptr->gmin && i >= ptr->bmax - ptr->bmin)
axis = RED;
else if (ptr->gmax - ptr->gmin >= ptr->bmax - ptr->bmin)
axis = GREEN;
else
axis = BLUE;
/* get histogram along longest axis */
switch (axis) {
case RED:
histp = &hist2[ptr->rmin];
for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
*histp = 0;
for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
iptr = &histogram[ir][ig][ptr->bmin];
for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
*histp += *iptr++;
}
histp++;
}
first = ptr->rmin;
last = ptr->rmax;
break;
case GREEN:
histp = &hist2[ptr->gmin];
for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
*histp = 0;
for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
iptr = &histogram[ir][ig][ptr->bmin];
for (ib = ptr->bmin; ib <= ptr->bmax; ++ib)
*histp += *iptr++;
}
histp++;
}
first = ptr->gmin;
last = ptr->gmax;
break;
case BLUE:
histp = &hist2[ptr->bmin];
for (ib = ptr->bmin; ib <= ptr->bmax; ++ib) {
*histp = 0;
for (ir = ptr->rmin; ir <= ptr->rmax; ++ir) {
iptr = &histogram[ir][ptr->gmin][ib];
for (ig = ptr->gmin; ig <= ptr->gmax; ++ig) {
*histp += *iptr;
iptr += GMC_B_LEN;
}
}
histp++;
}
first = ptr->bmin;
last = ptr->bmax;
break;
}
/* find median point */
sum2 = ptr->total / 2;
histp = &hist2[first];
sum = 0;
for (i = first; i <= last && (sum += *histp++) < sum2; ++i)
;
if (i == first)
i++;
/* Create new box, re-allocate points */
new_cb = *pfreeboxes;
*pfreeboxes = new_cb->next;
if (*pfreeboxes)
(*pfreeboxes)->prev = NULL;
if (*pusedboxes)
(*pusedboxes)->prev = new_cb;
new_cb->next = *pusedboxes;
*pusedboxes = new_cb;
histp = &hist2[first];
for (sum1 = 0, j = first; j < i; j++)
sum1 += *histp++;
for (sum2 = 0, j = i; j <= last; j++)
sum2 += *histp++;
new_cb->total = sum1;
ptr->total = sum2;
new_cb->rmin = ptr->rmin;
new_cb->rmax = ptr->rmax;
new_cb->gmin = ptr->gmin;
new_cb->gmax = ptr->gmax;
new_cb->bmin = ptr->bmin;
new_cb->bmax = ptr->bmax;
switch (axis) {
case RED:
new_cb->rmax = i-1;
ptr->rmin = i;
break;
case GREEN:
new_cb->gmax = i-1;
ptr->gmin = i;
break;
case BLUE:
new_cb->bmax = i-1;
ptr->bmin = i;
break;
}
shrinkbox(new_cb, histogram);
shrinkbox(ptr, histogram);
}
/************************************************************************/
/* shrinkbox() */
/************************************************************************/
static void
shrinkbox(Colorbox* box, int (*histogram)[GMC_B_LEN][GMC_B_LEN])
{
int *histp, ir, ig, ib;
if (box->rmax > box->rmin) {
for (ir = box->rmin; ir <= box->rmax; ++ir)
for (ig = box->gmin; ig <= box->gmax; ++ig) {
histp = &histogram[ir][ig][box->bmin];
for (ib = box->bmin; ib <= box->bmax; ++ib)
if (*histp++ != 0) {
box->rmin = ir;
goto have_rmin;
}
}
have_rmin:
if (box->rmax > box->rmin)
for (ir = box->rmax; ir >= box->rmin; --ir)
for (ig = box->gmin; ig <= box->gmax; ++ig) {
histp = &histogram[ir][ig][box->bmin];
ib = box->bmin;
for (; ib <= box->bmax; ++ib)
if (*histp++ != 0) {
box->rmax = ir;
goto have_rmax;
}
}
}
have_rmax:
if (box->gmax > box->gmin) {
for (ig = box->gmin; ig <= box->gmax; ++ig)
for (ir = box->rmin; ir <= box->rmax; ++ir) {
histp = &histogram[ir][ig][box->bmin];
for (ib = box->bmin; ib <= box->bmax; ++ib)
if (*histp++ != 0) {
box->gmin = ig;
goto have_gmin;
}
}
have_gmin:
if (box->gmax > box->gmin)
for (ig = box->gmax; ig >= box->gmin; --ig)
for (ir = box->rmin; ir <= box->rmax; ++ir) {
histp = &histogram[ir][ig][box->bmin];
ib = box->bmin;
for (; ib <= box->bmax; ++ib)
if (*histp++ != 0) {
box->gmax = ig;
goto have_gmax;
}
}
}
have_gmax:
if (box->bmax > box->bmin) {
for (ib = box->bmin; ib <= box->bmax; ++ib)
for (ir = box->rmin; ir <= box->rmax; ++ir) {
histp = &histogram[ir][box->gmin][ib];
for (ig = box->gmin; ig <= box->gmax; ++ig) {
if (*histp != 0) {
box->bmin = ib;
goto have_bmin;
}
histp += GMC_B_LEN;
}
}
have_bmin:
if (box->bmax > box->bmin)
for (ib = box->bmax; ib >= box->bmin; --ib)
for (ir = box->rmin; ir <= box->rmax; ++ir) {
histp = &histogram[ir][box->gmin][ib];
ig = box->gmin;
for (; ig <= box->gmax; ++ig) {
if (*histp != 0) {
box->bmax = ib;
goto have_bmax;
}
histp += GMC_B_LEN;
}
}
}
have_bmax:
;
}
| 35.641026 | 95 | 0.474974 | [
"object"
] |
735ca4fc9883ca723b8c19cee1ce03d9aaaf3e17 | 470 | cpp | C++ | 107. Binary Tree Level Order Traversal II.cpp | rajeev-ranjan-au6/Leetcode_Cpp | f64cd98ab96ec110f1c21393f418acf7d88473e8 | [
"MIT"
] | 3 | 2020-12-30T00:29:59.000Z | 2021-01-24T22:43:04.000Z | 107.Binary Tree Level Order Traversal II/answer.cpp | ReZeroS/LeetCode | 807ae800437e0b6224bd4672f28007388625437b | [
"MIT"
] | null | null | null | 107.Binary Tree Level Order Traversal II/answer.cpp | ReZeroS/LeetCode | 807ae800437e0b6224bd4672f28007388625437b | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>>v;
dfs(root, v, 0);
reverse(v.begin(), v.end());
return v;
}
void dfs(TreeNode* root, vector<vector<int>>& v, int level){
if(!root) return;
if(level == v.size()) v.push_back({});
v[level].push_back(root->val);
dfs(root->left, v, level + 1);
dfs(root->right, v, level + 1);
}
};
| 26.111111 | 64 | 0.525532 | [
"vector"
] |
735fbfce4c85c0a2b7747b305e37556cf4ba5c61 | 1,279 | hpp | C++ | Gabor.hpp | miaoever/x-face | ffd86c4de51449fdf46f311ddb23950c58e42854 | [
"FSFAP"
] | null | null | null | Gabor.hpp | miaoever/x-face | ffd86c4de51449fdf46f311ddb23950c58e42854 | [
"FSFAP"
] | null | null | null | Gabor.hpp | miaoever/x-face | ffd86c4de51449fdf46f311ddb23950c58e42854 | [
"FSFAP"
] | null | null | null | //
// Gabor.h
// LGBP
//
// Created by miaoever on 4/23/14.
// Copyright (c) 2014 miaoever. All rights reserved.
//
#ifndef __LGBP__Gabor__
#define __LGBP__Gabor__
#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
using namespace cv;
class GaborFR
{
public:
GaborFR();
static Mat getImagGaborKernel(Size ksize, double sigma, double theta,
double nu,double gamma=1, int ktype= CV_32F);
static Mat getRealGaborKernel( Size ksize, double sigma, double theta,
double nu,double gamma=1, int ktype= CV_32F);
static Mat getPhase(Mat &real,Mat &imag);
static Mat getMagnitude(Mat &real,Mat &imag);
static void getFilterRealImagPart(Mat& src,Mat& real,Mat& imag,Mat &outReal,Mat &outImag);
static Mat getFilterRealPart(Mat& src,Mat& real);
static Mat getFilterImagPart(Mat& src,Mat& imag);
static void gaborFilter(Mat image, int kernelSize, vector<Mat>& GMP);
void Init(Size ksize=Size(19,19), double sigma=2*CV_PI,
double gamma=1, int ktype=CV_32FC1);
private:
vector<Mat> gaborRealKernels;
vector<Mat> gaborImagKernels;
bool isInited;
};
#endif /* defined(__LGBP__Gabor__) */
| 31.975 | 91 | 0.691947 | [
"vector"
] |
73607e28e2689ac3eacc13abd7df04842f652fdc | 624 | cpp | C++ | src/ct_common/common/seed_constraint.cpp | xxyzzzq/ct_common | d28dd4362e97dff67fe68c512d6160be285bb05d | [
"MIT"
] | 2 | 2019-03-25T04:13:38.000Z | 2021-06-09T05:59:36.000Z | src/ct_common/common/seed_constraint.cpp | xxyzzzq/ct_common | d28dd4362e97dff67fe68c512d6160be285bb05d | [
"MIT"
] | null | null | null | src/ct_common/common/seed_constraint.cpp | xxyzzzq/ct_common | d28dd4362e97dff67fe68c512d6160be285bb05d | [
"MIT"
] | 1 | 2015-06-15T09:13:22.000Z | 2015-06-15T09:13:22.000Z | // Copyright 2016 ct_common authors. See LICENSE file for details.
#include "ct_common/common/seed_constraint.h"
namespace ct_common {
Seed_Constraint::Seed_Constraint() = default;
Seed_Constraint::Seed_Constraint(const Seed_Constraint& from) = default;
Seed_Constraint& Seed_Constraint::operator=(
const Seed_Constraint& right) = default;
Seed_Constraint::~Seed_Constraint() = default;
optional<bool> Seed_Constraint::IsMatch(
const Assignment& assignment,
const std::vector<std::shared_ptr<ParamSpec> >& paramspecs) {
return constraint_->Evaluate(paramspecs, assignment);
}
} // namespace ct_common
| 27.130435 | 72 | 0.772436 | [
"vector"
] |
7366b67bae647ce1f14427bd78070aaa50a325fc | 17,140 | cpp | C++ | llvm/lib/Transforms/Scaffold/Reverse.cpp | yipenghuang0302/ScaffCC | 4d7bfa034cfaea4e8346396c6198cdd3e271d272 | [
"BSD-2-Clause"
] | 158 | 2016-07-21T10:45:05.000Z | 2022-03-25T00:56:20.000Z | llvm/lib/Transforms/Scaffold/Reverse.cpp | yipenghuang0302/ScaffCC | 4d7bfa034cfaea4e8346396c6198cdd3e271d272 | [
"BSD-2-Clause"
] | 35 | 2016-07-25T01:23:07.000Z | 2021-09-27T16:05:50.000Z | llvm/lib/Transforms/Scaffold/Reverse.cpp | yipenghuang0302/ScaffCC | 4d7bfa034cfaea4e8346396c6198cdd3e271d272 | [
"BSD-2-Clause"
] | 62 | 2016-08-29T17:28:11.000Z | 2021-12-29T17:55:58.000Z | //===------------------------------ Reverse.cpp ---------------------------===//
//
// This file implements the Scaffold Pass of reversing functions. In the
// initial stage of the compiler, we search all of the IR
// code for functions beginning with "_reverse_". For any of these functions,
// we see which function they are meant to reverse; either an intrinsic
// function, or a user-defined function. For intrinsic functions, we already
// know their inverses. Otherwise, we can reverse user-defined functions
// with an "Instruction Visitor," an llvm construct which allows us to
// manipulate each individual instruction. Using this visitor, we place the
// inverse of each original instruction in reverse of the original order
// of the instructions.
//
// For reasons inherent to the uncertainty of quantum computation, this
// functionality is often crucial for optimal use of memory, specifically
// for automatic garbage-collection.
//
// This file was created by Scaffold Compiler Working Group
//
//===---------------------------------------------------------------------===//
//
#include <map>
#include "llvm/IR/ValueMap.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/IR/ValueSymbolTable.h"
using namespace llvm;
namespace {
// We need to use a ModulePass in order to insert new
// Functions into the target code
class FunctionReverse : public ModulePass {
public:
static char ID;
// Prefix of functions that should be replaced with the reverse
// of the function with the prefix dropped
static const std::string REVERSE_PREFIX;
FunctionReverse() : ModulePass(ID) {}
// an InstVisitor is an LLVM construct which allows to manipulate
// each instruction in our function
struct InsertReverseFunctionsVisitor :
public InstVisitor<InsertReverseFunctionsVisitor> {
// The reversed function implementations will be Functions
// in M's FunctionList
Module *M;
// We need to know the inverse of every intrinsic function
// before reversing any functions
ValueMap<Function *, Function *> IntrinsicInverses;
// The constructor is called once per module (in runOnModule)
InsertReverseFunctionsVisitor(Module *module) : M(module) {
// This table maps each intrinsic function to its inverse
std::vector<std::vector<Type*> > onePerm;
std::vector<std::vector<Type*> > twoPerms;
std::vector<std::vector<Type*> > threePerms;
//std::vector<ArrayRef<Type*> > prepTys;
//std::vector<ArrayRef<Type*> > RTys;
std::vector<Type*> v;
//errs() << "About to get type pointers\n";
Type *aa = Type::getInt8Ty(M->getContext());
Type *qq = Type::getInt16Ty(M->getContext());
// Type *dd = Type::getDoubleTy(M->getContext());
// Type *ii = Type::getInt32Ty(M->getContext());
/*
v.push_back(aa);
v.push_back(dd);
RTys.push_back(makeArrayRef(v));
v.pop_back();
v.pop_back();
v.push_back(qq);
v.push_back(dd);
RTys.push_back(makeArrayRef(v));
v.push_back(aa);
v.push_back(ii);
prepTys.push_back(makeArrayRef(v));
v.pop_back();
v.pop_back();
v.push_back(qq);
v.push_back(ii);
prepTys.push_back(makeArrayRef(v));
*/
//errs() << "About to make onePerm\n";
v.push_back(aa);
onePerm.push_back(v);//a
v.pop_back();
v.push_back(qq);
onePerm.push_back(v);//q
v.pop_back();
//errs() << "About to make twoPerms\n";
v.push_back(aa);
v.push_back(aa);
twoPerms.push_back(v);//aa
v.pop_back();
v.push_back(qq);
twoPerms.push_back(v);//aq
v.pop_back();
v.pop_back();
v.push_back(qq);
v.push_back(aa);
twoPerms.push_back(v);//qa
v.pop_back();
v.push_back(qq);
twoPerms.push_back(v);//qq
//errs() << "About to do threePerms\n";
v.push_back(qq);
threePerms.push_back(v);//qqq
v.pop_back();
v.push_back(aa);
threePerms.push_back(v);//qqa
v.pop_back();
v.pop_back();
v.push_back(aa);
v.push_back(aa);
threePerms.push_back(v);//qaa
v.pop_back();
v.push_back(qq);
threePerms.push_back(v);//qaq
v.pop_back();
v.pop_back();
v.pop_back();
v.push_back(aa);
v.push_back(qq);
v.push_back(qq);
threePerms.push_back(v);//aqq
v.pop_back();
v.push_back(aa);
threePerms.push_back(v);//aqa
v.pop_back();
v.pop_back();
v.push_back(aa);
v.push_back(aa);
threePerms.push_back(v);//aaa
v.pop_back();
v.push_back(qq);
threePerms.push_back(v);//aaq
for(int i=0; i<2; i++){
llvm::ArrayRef<Type*> ar = llvm::makeArrayRef(onePerm[i]);
//errs() << "doing one perm getDeclaration for " << i;
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::H, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::H, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::MeasX, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::MeasX, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::MeasZ, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::MeasZ, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::PrepX, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::PrepX, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::PrepZ, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::PrepZ, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Rx, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Rx, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Ry, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Ry, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Rz, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Rz, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::S, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Sdag, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Sdag, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::S, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::T, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Tdag, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Tdag, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::T, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::X, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::X, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Y, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Y, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Z, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Z, ar);
}
//errs() << "2perms getDeclaration\n";
for(int i=0; i<4; i++){
llvm::ArrayRef<Type*> ar = llvm::makeArrayRef(twoPerms[i]);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::CNOT, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::CNOT, ar);
}
//errs() << "3perms getDeclaration\n";
for(int i=0; i<8; i++){
llvm::ArrayRef<Type*> ar = llvm::makeArrayRef(threePerms[i]);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Toffoli, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Toffoli, ar);
IntrinsicInverses[Intrinsic::getDeclaration
(M, Intrinsic::Fredkin, ar)] = Intrinsic::getDeclaration
(M, Intrinsic::Fredkin, ar);
}
//errs() << "store_cbit getDeclaration\n";
IntrinsicInverses[M->getFunction("store_cbit")]
= M->getFunction("store_cbit");
}
// Returns a pointer to the inverse of the specified
// function and creates it if it doesn't exist yet
Function *GetOrCreateInverseFunction(Function *Func) {
if (IntrinsicInverses.count(Func)) {
return IntrinsicInverses[Func];
}
const std::string ReverseFuncName =
Func->getName().str() + "_Reverse";
Function *ReverseFunc = M->getFunction(ReverseFuncName);
// If it doesn't exist yet, create it
if (!ReverseFunc) {
ValueMap<const Value*, WeakTrackingVH> VMap;
ReverseFunc = CloneFunction
(Func, VMap/*, false ModuleLevelChanges */);
ReverseFunc->setName(ReverseFuncName);
BasicBlock &BB = ReverseFunc->front();
// Finds all of the call instructions
// in the cloned reverse function
std::vector<CallInst *> V;
BasicBlock::iterator It;
BasicBlock::iterator E = BB.end();
CallInst *CI;
for (It = BB.begin(); It != E; It++) {
if ( (CI = dyn_cast<CallInst>(&*It)) ) {
V.push_back(CI);
}
/*else if ( (RI = dyn_cast<ReturnInst>(&*It)) ) {
RI->removeFromParent();
}*/
}
// Iterates backwards through the list of call
// instructions, inverts the functions call by the
// instructions and moves them to the end of the
// reversed function
std::vector<CallInst *>::reverse_iterator I;
Function *Inverse;
std::vector<CallInst *>::reverse_iterator F = V.rend();
Instruction *term = BB.getTerminator();
for (I = V.rbegin(); I != F; I++) {
Inverse = GetOrCreateInverseFunction(
(*I)->getCalledFunction());
(*I)->setCalledFunction(Inverse);
(*I)->removeFromParent();
(*I)->insertBefore(term);
}
}
return ReverseFunc;
} // GetOrCreateInverseFunction()
// Gets called very time the target LLVM IR code
// has a function call
// Overrides visitCallInst in the InstVisitor class
void visitCallInst(CallInst &I) {
// Get the current function
Function *CF = I.getCalledFunction();
if (CF->getName().startswith(REVERSE_PREFIX)) {
// Stores the number of times a reverse function is
// prefixed with '_reverse_'; If this number is odd, it
// it will be replaced by the function's reverse
// otherwiseit will be replaced by the function itself
int numReverses = 0;
StringRef ForwardFunctionName = CF->getName();
while(ForwardFunctionName.startswith(REVERSE_PREFIX)){
ForwardFunctionName = ForwardFunctionName.drop_front
(REVERSE_PREFIX.size());
++numReverses;
}
Function *ForwardFunction;
// The Toffoli function is special becuase it has
// been rewritten to have a different function name
if (ForwardFunctionName == "Toffoli")
ForwardFunction = M->getFunction("ToffoliImpl");
else
ForwardFunction = M->getFunction(ForwardFunctionName);
// If the function name was not found in the current
// module we can search for it in the intrinsics by
// prepending "llvm." to it
if (ForwardFunction == NULL) {
std::string typeString = "";
size_t args = CF->getFunctionType()->getNumParams();
for(size_t i = 0;i<args;i++){
typeString += ".i16";
}
const std::string IntrinsicForwardFunctionName
= "llvm." + ForwardFunctionName.str() + typeString;
ForwardFunction = M->getFunction
(IntrinsicForwardFunctionName);
}
// If no function exists for the base after the
// _reverse_, print an error message
if (ForwardFunction == NULL) {
errs() <<
"Error: Could not invert non-existent function "
<< ForwardFunctionName << "\n";
}
// If a function exists, but different arguments are
// supplied to the call site than the type of the
// function, print an error message
else if (CF->getFunctionType() != ForwardFunction->
getFunctionType()) {
errs() << "Warning: reversed function " << CF->getName()
<< " did not match type of foward function "
<< ForwardFunctionName << "\n";
}
Function *ReplacementFunction = numReverses % 2 == 1 ?
GetOrCreateInverseFunction(ForwardFunction)
: ForwardFunction;
// Now that we have the replacement function, this
// performs the insertion into the target code
const FunctionType *FuncType = ReplacementFunction
->getFunctionType();
std::vector<Value*> Args(FuncType->getNumParams());
unsigned i;
for (i=0; i<FuncType->getNumParams(); i++) {
Args[i] = I.getArgOperand(i);
}
CallInst::Create(ReplacementFunction,
ArrayRef<Value*>(Args), "", &I);
I.eraseFromParent();
}
} // visitCallInst()
}; // struct InsertReverseFunctionsVisitor
virtual bool runOnModule(Module &M) {
InsertReverseFunctionsVisitor IRFV(&M);
IRFV.visit(M);
return true;
} // runOnModule()
}; // struct FunctionReverse
} // namespace
char FunctionReverse::ID = 0;
const std::string FunctionReverse::REVERSE_PREFIX = "_reverse_";
static RegisterPass<FunctionReverse> X("FunctionReverse",
"Function Reverser", false, false);
| 43.392405 | 80 | 0.495508 | [
"vector"
] |
7367e212975abeb60a1dcd2cf88e0e234101ed97 | 2,033 | cpp | C++ | dynamic_vino_lib/src/models/person_reidentification_model.cpp | ConnorChristie/ros_openvino_toolkit | f319108bb506630d041e6db74ea3025472fbf7e9 | [
"Apache-2.0"
] | null | null | null | dynamic_vino_lib/src/models/person_reidentification_model.cpp | ConnorChristie/ros_openvino_toolkit | f319108bb506630d041e6db74ea3025472fbf7e9 | [
"Apache-2.0"
] | null | null | null | dynamic_vino_lib/src/models/person_reidentification_model.cpp | ConnorChristie/ros_openvino_toolkit | f319108bb506630d041e6db74ea3025472fbf7e9 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @brief a header file with declaration of PersonReidentificationModel class
* @file person_reidentification_model.cpp
*/
#include <string>
#include "dynamic_vino_lib/models/person_reidentification_model.h"
#include "dynamic_vino_lib/slog.h"
// Validated Object Detection Network
Models::PersonReidentificationModel::PersonReidentificationModel(
const std::string & model_loc, int input_num, int output_num, int max_batch_size)
: BaseModel(model_loc, input_num, output_num, max_batch_size) {}
void Models::PersonReidentificationModel::setLayerProperty(
InferenceEngine::CNNNetReader::Ptr net_reader)
{
// set input property
InferenceEngine::InputsDataMap input_info_map(
net_reader->getNetwork().getInputsInfo());
InferenceEngine::InputInfo::Ptr input_info = input_info_map.begin()->second;
input_info->setPrecision(InferenceEngine::Precision::U8);
input_info->getInputData()->setLayout(InferenceEngine::Layout::NCHW);
// set output property
InferenceEngine::OutputsDataMap output_info_map(
net_reader->getNetwork().getOutputsInfo());
// set input and output layer name
input_ = input_info_map.begin()->first;
output_ = output_info_map.begin()->first;
}
void Models::PersonReidentificationModel::checkLayerProperty(
const InferenceEngine::CNNNetReader::Ptr & net_reader) {}
const std::string Models::PersonReidentificationModel::getModelName() const
{
return "Person Reidentification";
}
| 39.862745 | 83 | 0.776685 | [
"object"
] |
736b0e75f5869cb4f2cf37b95f494c0bb135f710 | 17,374 | cpp | C++ | Source/EvalDll/CNTKEval.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | 1 | 2019-04-14T20:17:55.000Z | 2019-04-14T20:17:55.000Z | Source/EvalDll/CNTKEval.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | null | null | null | Source/EvalDll/CNTKEval.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | 1 | 2018-12-29T20:52:30.000Z | 2018-12-29T20:52:30.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
// CNTKEval.cpp : Defines the exported functions for the CNTK DLL.
//
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
#include <math.h>
#define EVAL_EXPORTS // creating the exports here
#include "Eval.h"
#include "Actions.h"
#include "CNTKEval.h"
#include "CPUMatrix.h" // for SetNumThreads()
#include "SimpleOutputWriter.h"
#include "NDLNetworkBuilder.h"
#ifdef LEAKDETECT
#include <vld.h> // leak detection
#endif
#include "BestGpu.h"
#include "InputAndParamNodes.h"
#include "latticearchive.h"
#include <limits>
#include "RecurrentNodes.h"
namespace Microsoft { namespace MSR { namespace CNTK {
template <typename ElemType>
void CNTKEvalBase<ElemType>::Init(const std::string& config)
{
m_config.Parse(config);
size_t nThreads = m_config("numCPUThreads", "1");
CPUMatrix<ElemType>::SetNumThreads(nThreads);
Globals::SetShareNodeValueMatrices(m_config(L"shareNodeValueMatrices", true));
}
// CreateNetwork - create a network based on the network description
// networkDescription - network description
template <typename ElemType>
void CNTKEvalBase<ElemType>::CreateNetwork(const std::string& networkDescription)
{
ConfigParameters config;
config.Parse(networkDescription);
std::vector<wstring> outputNodeNames;
this->m_net = GetModelFromConfig<ConfigParameters, ElemType>(config, L"outputNodeNames", outputNodeNames);
if (this->m_net == nullptr)
{
LogicError("Unable to construct network from description");
}
}
// Destroy - cleanup and remove this class
// NOTE: this destroys the object, and it can't be used past this point
template <typename ElemType>
void CNTKEvalBase<ElemType>::Destroy()
{
// cleanup everything
this->m_net.reset();
}
// ----------------------------------------------------------------------------
// Basic interface
// ----------------------------------------------------------------------------
template <typename ElemType>
void EVAL_API GetEval(IEvaluateModel<ElemType>** peval)
{
*peval = new CNTKEval<ElemType>();
}
extern "C" EVAL_API void GetEvalF(IEvaluateModel<float>** peval)
{
GetEval(peval);
}
extern "C" EVAL_API void GetEvalD(IEvaluateModel<double>** peval)
{
GetEval(peval);
}
// GetNodeDimensions - Get the node dimensions of the specified nodes
// dimensions - map from name of node to dimension of the node, will be appended to for Input/Output scenarios
// nodeGroup - type of node we are requesting (input/output/specified)
// NOTE: when nodeGroup==specified the dimensions map is expected to be populated with the string names of the nodes requested, dimensions will be modified return the current value.
template <typename ElemType>
void CNTKEval<ElemType>::GetNodeDimensions(std::map<std::wstring, size_t>& dimensions, NodeGroup nodeGroup)
{
// On Linux with gcc 4.8.4, it is required to add "this->" when referencing m_net, which is the protected member of the base class with templates,
// in order to make the name correctly resolved by the compiler.
if (this->m_net == NULL)
{
for (auto iter = dimensions.begin(); iter != dimensions.end(); iter++)
iter->second = 0;
return;
}
const auto& outputNodes = this->m_net->OutputNodes();
switch (nodeGroup)
{
case nodeInput:
{
if (outputNodes.size() == 0)
{
LogicError("No Output nodes found: Cannot determine Input node dimensions due to lack of Output nodes.\n(are 'outputNodeNames' and/or 'OutputNodes' properly defined in the configuration file?)");
}
auto& nodes = this->m_net->InputNodes(outputNodes[0]);
for (auto& node : nodes)
{
std::wstring name = node->NodeName();
size_t size = node->GetSampleMatrixNumRows();
dimensions[name] = size;
}
break;
}
case nodeOutput:
{
const auto& nodes = outputNodes;
for (auto& node : nodes)
{
std::wstring name = node->NodeName();
size_t size = node->GetSampleMatrixNumRows();
dimensions[name] = size;
}
break;
}
case nodeSpecified:
for (auto iter = dimensions.begin(); iter != dimensions.end(); iter++)
{
auto node = this->m_net->GetNodeFromName(iter->first);
iter->second = node->GetSampleMatrixNumRows();
}
break;
}
}
// StartEvaluateMinibatchLoop - Prepare network for Evaluate() calls.
// outputNodeName - name of node that will be evaluated
template <typename ElemType>
void CNTKEval<ElemType>::StartEvaluateMinibatchLoop(const std::wstring& outputNodeName)
{
this->m_net->StartEvaluateMinibatchLoop(this->m_net->GetNodeFromName(outputNodeName));
}
// Evaluate - Evalute using the model with the given inputs and outputs
// inputs - map from node name to input vector
// outputs - map from node name to output vector, outputs vectors need to be preallocated by caller, sizing will happen during evaluation
template <typename ElemType>
void CNTKEval<ElemType>::Evaluate(std::map<std::wstring, std::vector<ElemType>*>& inputs, std::map<std::wstring, std::vector<ElemType>*>& outputs)
{
size_t minibatchSize = this->m_config(L"minibatchSize", (size_t) 10240);
size_t rightSplice = this->m_config(L"rightSplice", (size_t) 0);
// get the evaluation names from the output string
vector<wstring> outNodeNames;
ConfigParameters config;
// config["deviceId"] = to_string(this->m_net->GetDeviceId());
config["rightSplice"] = to_string(rightSplice);
// create the reader if necessary
if (m_reader == nullptr)
{
m_reader = new EvalReader<ElemType>(config);
}
// now set the data in the reader
GetNodeDimensions(m_dimensions, nodeInput);
m_reader->SetData(&inputs, &m_dimensions);
m_reader->SetBoundary(m_start);
// create the writer if necessary
if (m_writer == nullptr)
{
m_writer = new EvalWriter<ElemType>(config);
}
// now set the data in the writer
GetNodeDimensions(m_dimensions, nodeOutput);
m_writer->SetData(&outputs, &m_dimensions);
// call the evaluator
SimpleOutputWriter<ElemType> eval(this->m_net);
eval.WriteOutput(*m_reader, minibatchSize, *m_writer, outNodeNames);
}
// Evaluate - Evalute using the model with the given inputs and outputs
// outputs - map from node name to output vector, outputs vectors need to be preallocated by caller, sizing will happen during evaluation
template <typename ElemType>
void CNTKEval<ElemType>::Evaluate(std::map<std::wstring, std::vector<ElemType>*>& outputs)
{
// get the evaluation names from the output string
vector<wstring> outNodeNames;
ConfigParameters config;
// create the writer if necessary
if (m_writer == nullptr)
{
m_writer = new EvalWriter<ElemType>(config);
}
// now set the data in the writer
GetNodeDimensions(m_dimensions, nodeOutput);
m_writer->SetData(&outputs, &m_dimensions);
// call the evaluator
SimpleOutputWriter<ElemType> eval(this->m_net);
eval.WriteOutput(*m_writer, outNodeNames);
}
template <typename ElemType>
void CNTKEval<ElemType>::Destroy()
{
CNTKEvalBase<ElemType>::Destroy();
delete m_reader;
delete m_writer;
delete this;
}
// instantiate all the combinations we expect to be used
template class CNTKEval<double>;
template class CNTKEval<float>;
// ----------------------------------------------------------------------------
// Extended interface
// ----------------------------------------------------------------------------
template<typename ElemType>
VariableLayout CNTKEvalExtended<ElemType>::ToVariableLayout(const ComputationNodeBasePtr n)
{
auto matrix = dynamic_pointer_cast<Matrix<ElemType>>(n->ValuePtr());
return VariableLayout
{
/* name */ n->GetName(),
/* type */ sizeof(ElemType) == sizeof(float) ? VariableLayout::Float32 : VariableLayout::Float64,
/* storage */ matrix ? matrix->GetMatrixType() == MatrixType::DENSE ? VariableLayout::Dense :
matrix->GetMatrixType() == MatrixType::SPARSE ? VariableLayout::Sparse :
VariableLayout::Undetermined :
VariableLayout::Undetermined,
/* dimension */ n->GetSampleLayout().GetNumElements()
};
}
template<typename ElemType>
void CNTKEvalExtended<ElemType>::StartForwardEvaluation(const std::vector<wstring>& outputNodeNames)
{
m_scopedNetworkOperationMode = make_shared<ScopedNetworkOperationMode>(this->m_net, NetworkOperationMode::inferring);
m_outputNodes = this->m_net->OutputNodesByName(outputNodeNames);
m_inputNodes = this->m_net->InputNodesForOutputs(outputNodeNames);
// allocate memory for forward computation
this->m_net->AllocateAllMatrices({}, m_outputNodes, nullptr);
this->m_net->StartEvaluateMinibatchLoop(m_outputNodes);
m_inputMatrices = DataReaderHelpers::RetrieveInputMatrices(m_inputNodes);
for (const auto& node : m_outputNodes)
{
shared_ptr<Matrix<ElemType>> outputMatrix = dynamic_pointer_cast<Matrix<ElemType>>(node->ValuePtr());
if (outputMatrix->GetMatrixType() != MatrixType::DENSE)
RuntimeError("Sparse outputs are not supported by this API.");
}
m_started = true;
}
template<typename ElemType>
VariableSchema CNTKEvalExtended<ElemType>::GetOutputSchema() const
{
VariableSchema schema;
auto& nodes = m_started ? m_outputNodes : this->m_net->OutputNodes();
for (const auto& n : nodes)
{
schema.push_back(ToVariableLayout(n));
}
return schema;
}
template<typename ElemType>
VariableSchema CNTKEvalExtended<ElemType>::GetInputSchema() const
{
VariableSchema inputLayouts;
auto nodes = m_inputNodes;
if (nodes.size() == 0)
{
// Default to all nodes
nodes = this->m_net->InputNodesForOutputs({});
}
for (const auto& n : nodes)
{
inputLayouts.push_back(ToVariableLayout(n));
}
return inputLayouts;
}
template<typename ElemType>
template<template<typename> class ValueContainer>
void CNTKEvalExtended<ElemType>::ForwardPassT(const std::vector<ValueBuffer<ElemType, ValueContainer> >& inputs, std::vector<ValueBuffer<ElemType, ValueContainer> >& outputs, bool resetRNN)
{
if (!m_started)
RuntimeError("ForwardPass() called before StartForwardEvaluation()");
if (inputs.size() != (size_t)std::distance(m_inputMatrices.begin(), m_inputMatrices.end()))
RuntimeError("Expected %d inputs, but got %d.", (int)std::distance(m_inputMatrices.begin(), m_inputMatrices.end()), (int)inputs.size());
if (outputs.size() != m_outputNodes.size())
RuntimeError("Expected %d outputs, but got %d.", (int)m_outputNodes.size(), (int)outputs.size());
size_t i = 0;
for (auto& inputNode : m_inputNodes)
{
// const cast: The matrix class takes this over without copying and could theoretically change the contents,
// though it doesn't in this case.
auto& buffer = const_cast<ValueBuffer<ElemType, ValueContainer>&>(inputs[i]);
auto matrix = dynamic_pointer_cast<Matrix<ElemType>>(inputNode->ValuePtr());
auto type = matrix->GetMatrixType();
size_t numRows = inputNode->GetSampleLayout().GetNumElements();
if (buffer.m_buffer.data() == nullptr)
RuntimeError("Input %ls: Buffer is not allocated.", m_inputNodes[i]->GetName().c_str());
if (type == MatrixType::DENSE)
{
if (buffer.m_buffer.size() % numRows != 0)
RuntimeError("Input %ls: Expected input data to be a multiple of %" PRIu64 ", but it is %" PRIu64 ".",
m_inputNodes[i]->GetName().c_str(), numRows, buffer.m_buffer.size());
if (buffer.m_buffer.size() == 0)
RuntimeError("Input %ls: Expected at least one element.", m_inputNodes[i]->GetName().c_str());
}
else if (type == MatrixType::SPARSE)
{
if (buffer.m_colIndices.data() == nullptr)
RuntimeError("Input %ls: Due to sparse input format, expected colIndices array, but was nullptr.", m_inputNodes[i]->GetName().c_str());
if (buffer.m_indices.data() == nullptr)
RuntimeError("Input %ls: Due to sparse input format, expected Indices array, but was nullptr.", m_inputNodes[i]->GetName().c_str());
if (buffer.m_colIndices.size() < 2)
RuntimeError("Input %ls: Expected at least one element (2 entries in colIndices array).", m_inputNodes[i]->GetName().c_str());
if (buffer.m_colIndices[0] != 0)
RuntimeError("Input %ls: First element of column indices must be 0", m_inputNodes[i]->GetName().c_str());
if (buffer.m_colIndices[buffer.m_colIndices.size() - 1] != buffer.m_indices.size())
RuntimeError("Input %ls: Last element of column indices must be equal to the size of indices (%ld), but was %d",
m_inputNodes[i]->GetName().c_str(), buffer.m_indices.size(),
buffer.m_colIndices[buffer.m_colIndices.size() - 1]);
}
int numCols = type == MatrixType::DENSE ? buffer.m_buffer.size() / numRows : buffer.m_colIndices.size() - 1;
if (numCols < 1)
RuntimeError("Input: the number of column must be greater than or equal to 1.");
inputNode->GetMBLayout()->Init(1, numCols);
// SentinelValueIndicatingUnspecifedSequenceBeginIdx is used to specify the lower bound of look-back step of recurrent nodes
inputNode->GetMBLayout()->AddSequence(0, 0, resetRNN ? 0 : SentinelValueIndicatingUnspecifedSequenceBeginIdx, numCols);
if (type == MatrixType::DENSE)
matrix->SetValue(numRows, numCols, matrix->GetDeviceId(), buffer.m_buffer.data(), matrixFlagNormal);
else if (type == MatrixType::SPARSE)
{
// In the sparse case the m_data layout is identical to CUDA's CSC layout
// (see http://docs.nvidia.com/cuda/cusparse/#compressed-sparse-column-format-csc).
matrix->SetMatrixFromCSCFormat(buffer.m_colIndices.data(), buffer.m_indices.data(), buffer.m_buffer.data(),
buffer.m_buffer.size(), numRows, numCols);
}
++i;
}
ComputationNetwork::BumpEvalTimeStamp(m_inputNodes);
this->m_net->ForwardProp(m_outputNodes);
for (size_t i2 = 0; i2 < m_outputNodes.size(); ++i2)
{
auto node = m_outputNodes[i2];
shared_ptr<Matrix<ElemType>> outputMatrix = dynamic_pointer_cast<Matrix<ElemType>>(node->ValuePtr());
auto pMBLayout = node->GetMBLayout();
if (!pMBLayout)
{
pMBLayout = make_shared<MBLayout>();
pMBLayout->InitAsFrameMode(1); // treat this as if we have one single sample
}
const auto& seq = pMBLayout->GetAllSequences();
if (seq.size() != 1)
RuntimeError("Only 1 output sequence supported by this API");
ValueContainer<ElemType>& vec = outputs[i2].m_buffer;
size_t numElements = outputMatrix->GetNumElements();
if (vec.capacity() < numElements)
{
// Bad luck - we can't reallocate memory of an external object at this point.
RuntimeError("Not enough space in output buffer for output '%ls'.", node->GetName().c_str());
}
vec.resize(numElements);
ElemType* data = const_cast<ElemType*>(vec.data());
outputMatrix->CopyToArray(data, numElements);
}
}
template<typename ElemType>
void CNTKEvalExtended<ElemType>::ForwardPass(const Values<ElemType>& inputs, Values<ElemType>& outputs)
{
ForwardPassT(inputs, outputs, true);
}
template<typename ElemType>
void CNTKEvalExtended<ElemType>::ForwardPass(const Values<ElemType>& inputs, Values<ElemType>& outputs, bool resetRNN)
{
ForwardPassT(inputs, outputs, resetRNN);
}
template<typename ElemType>
void CNTKEvalExtended<ElemType>::ForwardPass(const ValueRefs<ElemType>& inputs, ValueRefs<ElemType>& outputs)
{
ForwardPassT(inputs, outputs, true);
}
template<typename ElemType>
void CNTKEvalExtended<ElemType>::ForwardPass(const ValueRefs<ElemType>& inputs, ValueRefs<ElemType>& outputs, bool resetRNN)
{
ForwardPassT(inputs, outputs, resetRNN);
}
template <typename ElemType>
void CNTKEvalExtended<ElemType>::Destroy()
{
// Since m_scopeNetworkOperationMode has a reference to m_net, it has to be released first.
m_scopedNetworkOperationMode.reset();
CNTKEvalBase<ElemType>::Destroy();
delete this;
}
template <typename ElemType>
void EVAL_API GetEvalExtended(IEvaluateModelExtended<ElemType>** peval)
{
*peval = new CNTKEvalExtended<ElemType>();
}
extern "C" EVAL_API void GetEvalExtendedF(IEvaluateModelExtended<float>** peval)
{
GetEvalExtended(peval);
}
extern "C" EVAL_API void GetEvalExtendedD(IEvaluateModelExtended<double>** peval)
{
GetEvalExtended(peval);
}
template class CNTKEvalExtended<double>;
template class CNTKEvalExtended<float>;
} } }
| 37.687636 | 207 | 0.665535 | [
"object",
"vector",
"model"
] |
736c80f74fe628d97f6435b87b8fbf000e8f1b5d | 18,507 | cpp | C++ | passes/DecoupleCompute/DecoupleCompute.cpp | PrincetonUniversity/GraphAttack | 2bb80fc54d2e83293abe40c506ae745259e1cd14 | [
"BSD-2-Clause"
] | 1 | 2021-09-28T07:00:01.000Z | 2021-09-28T07:00:01.000Z | passes/DecoupleCompute/DecoupleCompute.cpp | PrincetonUniversity/GraphAttack | 2bb80fc54d2e83293abe40c506ae745259e1cd14 | [
"BSD-2-Clause"
] | null | null | null | passes/DecoupleCompute/DecoupleCompute.cpp | PrincetonUniversity/GraphAttack | 2bb80fc54d2e83293abe40c506ae745259e1cd14 | [
"BSD-2-Clause"
] | 1 | 2021-09-28T07:00:08.000Z | 2021-09-28T07:00:08.000Z | #include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <chrono>
#include <thread>
#include <algorithm>
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/InstIterator.h"
using namespace std;
using namespace llvm;
namespace {
#include "../DecoupleCommon/Decouple.h"
std::map<std::string, int> unsupported_load_types;
int LOADS = 0;
int STORES = 0;
int NON_DEC_STORES = 0;
int INT_LABEL = 0;
Function *dec_open_consumer;
Function *dec_close_consumer;
Function *dec_consume32;
Function *dec_consume64;
Function *compute_consume_i8;
Function *compute_consume_i32;
Function *compute_consume_i64;
Function *compute_consume_ptr;
Function *compute_consume_cmp;
Function *compute_consume_float;
Function *compute_consume_double;
Function *compute_produce_i8;
Function *compute_produce_i32;
Function *compute_produce_i64;
Function *compute_produce_ptr;
Function *compute_produce_float;
Function *compute_produce_double;
Function *compute_consume__Znwm;
Function *compute_consume__Znam;
vector<Instruction *> to_erase;
void populate_functions(Module &M) {
dec_open_consumer = (Function *) M.getOrInsertFunction("dec_open_consumer",
FunctionType::get(Type::getInt32Ty(M.getContext()),
Type::getInt64Ty(M.getContext()))).getCallee();
dec_close_consumer = (Function *) M.getOrInsertFunction("dec_close_consumer",
FunctionType::get(Type::getInt32Ty(M.getContext()),
Type::getInt64Ty(M.getContext()))).getCallee();
dec_consume32 = (Function *) M.getOrInsertFunction("dec_consume32",
FunctionType::get(Type::getInt32Ty(M.getContext()),
Type::getInt64Ty(M.getContext()))).getCallee();
dec_consume64 = (Function *) M.getOrInsertFunction("dec_consume64",
FunctionType::get(Type::getInt64Ty(M.getContext()),
Type::getInt64Ty(M.getContext()))).getCallee();
// ********************************
// Functions below will be removed
// ********************************
compute_consume_i8 = (Function *) M.getOrInsertFunction("desc_compute_consume_i8",
FunctionType::get(Type::getInt8Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume_i32 = (Function *) M.getOrInsertFunction("desc_compute_consume_i32",
FunctionType::get(Type::getInt32Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume_i64 = (Function *) M.getOrInsertFunction("desc_compute_consume_i64",
FunctionType::get(Type::getInt64Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
// using *i8 and will cast later
compute_consume_ptr = (Function *) M.getOrInsertFunction("desc_compute_consume_ptr",
FunctionType::get(Type::getInt8PtrTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume_float = (Function *) M.getOrInsertFunction("desc_compute_consume_float",
FunctionType::get(Type::getFloatTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume_double = (Function *) M.getOrInsertFunction("desc_compute_consume_double",
FunctionType::get(Type::getDoubleTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_produce_i8 = (Function *) M.getOrInsertFunction("desc_compute_produce_i8",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getInt8Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_produce_i32 = (Function *) M.getOrInsertFunction("desc_compute_produce_i32",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getInt32Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_produce_i64 = (Function *) M.getOrInsertFunction("desc_compute_produce_i64",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getInt64Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
// using *i8 and will cast later
compute_produce_ptr = (Function *) M.getOrInsertFunction("desc_compute_produce_ptr",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getInt8PtrTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_produce_float = (Function *) M.getOrInsertFunction("desc_compute_produce_float",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getFloatTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_produce_double = (Function *) M.getOrInsertFunction("desc_compute_produce_double",
FunctionType::get(Type::getVoidTy(M.getContext()),
Type::getDoubleTy(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume_cmp = (Function *) M.getOrInsertFunction("desc_compute_consume_cmp",
FunctionType::get(Type::getInt8Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume__Znwm = (Function *) M.getOrInsertFunction("desc_compute_consume__Znwm",
FunctionType::get(Type::getInt8PtrTy(M.getContext()),
Type::getInt64Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
compute_consume__Znam = (Function *) M.getOrInsertFunction("desc_compute_consume__Znam",
FunctionType::get(Type::getInt8PtrTy(M.getContext()),
Type::getInt64Ty(M.getContext()),
Type::getInt32Ty(M.getContext()))).getCallee();
}
Function *get_non_ptr_consume(Instruction *I) {
if (I->getType()->isIntegerTy(8)) {
return compute_consume_i8;
}
else if (I->getType()->isIntegerTy(32)) {
return compute_consume_i32;
}
else if (I->getType()->isIntegerTy(64)) {
return compute_consume_i64;
}
else if (I->getType()->isFloatTy()) {
return compute_consume_float;
}
else if (I->getType()->isDoubleTy()) {
return compute_consume_double;
}
else {
errs() << "[Error: unsupported non-pointer type]\n";
errs() << *I << "\n";
errs() << *(I->getType()) << "\n";
assert(0);
}
}
void instrument_load(Module &M, Instruction *I) {
LOADS++;
Instruction *Intr;
Value *Intr2;
IRBuilder<> Builder(I);
if (non_ptr_load(I)) {
Function *compute_consume_non_ptr_func = get_non_ptr_consume(I);
Intr = Builder.CreateCall(compute_consume_non_ptr_func, {ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
I->replaceAllUsesWith(Intr);
to_erase.push_back(I);
INT_LABEL++;
}
else if (ptr_load(I)) {
Intr = Builder.CreateCall(compute_consume_ptr, {ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
Intr2 = Builder.CreatePointerCast(Intr, I->getType());
I->replaceAllUsesWith(Intr2);
to_erase.push_back(I);
INT_LABEL++;
}
else {
std::string type_str;
llvm::raw_string_ostream rso(type_str);
I->getType()->print(rso);
auto my_str = rso.str();
if (unsupported_load_types.find(my_str) == unsupported_load_types.end()) {
unsupported_load_types[my_str] = 0;
}
unsupported_load_types[my_str]++;
//errs() << "[Warning: Could not find a type for the load instruction]\n";
//errs() << *I << "\n";
//errs() << *(I->getType()) << "\n";
//assert(0);
}
}
Function *get_non_ptr_produce(StoreInst *stI) {
Value *I = stI->getValueOperand();
if (I->getType()->isIntegerTy(8)) {
return compute_produce_i8;
}
else if (I->getType()->isIntegerTy(32)) {
return compute_produce_i32;
}
else if (I->getType()->isIntegerTy(64)) {
return compute_produce_i64;
}
else if (I->getType()->isFloatTy()) {
return compute_produce_float;
}
else if (I->getType()->isDoubleTy()) {
return compute_produce_double;
}
else {
errs() << "[Error: unsupported non-pointer type]\n";
errs() << *I << "\n";
errs() << *(I->getType()) << "\n";
assert(0);
}
}
void instrument_store(Module &M, StoreInst *I) {
STORES++;
Instruction *Intr;
Value *Intr2;
IRBuilder<> Builder(I);
if (non_ptr_store(I)) {
Function *compute_produce_non_ptr_func = get_non_ptr_produce(I);
Intr = Builder.CreateCall(compute_produce_non_ptr_func, {I->getValueOperand(), ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
to_erase.push_back(I);
INT_LABEL++;
}
else if (ptr_store(I)) {
// This gets really nasty. Just going to have supply take care of pointer stores.
if (safe_ptr_store_common(I->getValueOperand())) {
Intr2 = Builder.CreatePointerCast(I->getValueOperand(), Type::getInt8PtrTy(M.getContext()));
Intr = Builder.CreateCall(compute_produce_ptr,{Intr2, ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
INT_LABEL++;
}
else {
NON_DEC_STORES++;
}
//Intr2 = Builder.CreatePointerCast(I->getValueOperand(), Type::getInt8PtrTy(M.getContext()));
//Intr = Builder.CreateCall(compute_produce_ptr,{Intr2});
to_erase.push_back(I);
}
else {
std::string type_str;
llvm::raw_string_ostream rso(type_str);
I->getType()->print(rso);
auto my_str = rso.str();
if (unsupported_load_types.find(my_str) == unsupported_load_types.end()) {
unsupported_load_types[my_str] = 0;
}
unsupported_load_types[my_str]++;
//to_erase.push_back(I);
}
}
bool try_instrument_function(Module &M, CallInst *I) {
if (I->getCalledFunction() == NULL) {
return false;
}
if (I->getCalledFunction()->getName().str() == "_Znwm") {
IRBuilder<> Builder(I);
//errs() << *I << "\n\n";
//errs() << *I->getOperand(0) << "\n\n";
Instruction *Intr = Builder.CreateCall(
compute_consume__Znwm,
{I->getOperand(0),
ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
INT_LABEL++;
I->replaceAllUsesWith(Intr);
to_erase.push_back(I);
return true;
}
if (I->getCalledFunction()->getName().str() == "_Znam") {
IRBuilder<> Builder(I);
Instruction *Intr = Builder.CreateCall(
compute_consume__Znam,
{I->getOperand(0),
ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
INT_LABEL++;
I->replaceAllUsesWith(Intr);
to_erase.push_back(I);
return true;
}
return false;
}
std::set<std::string> to_print;
void try_delete_mem_functions(Module &M, CallInst *I) {
/*if (I->getType()->isVoidTy()) {
//errs() << *(I->getType()) << "\n";
to_erase.push_back(I);
}*/
// Annoying indirect function calls
if (I->getCalledFunction() == NULL) {
return;
}
if (to_print.find(I->getCalledFunction()->getName().str()) == to_print.end()) {
to_print.insert(I->getCalledFunction()->getName().str());
//errs() << *I << "\n";
}
if (I->getCalledFunction()->getName().str().find("llvm.memcpy") != std::string::npos) {
to_erase.push_back(I);
return;
}
else if (I->getCalledFunction()->getName().str().find("llvm.memset") != std::string::npos) {
to_erase.push_back(I);
return;
}
else if (I->getCalledFunction()->getName().str().find("llvm.memmove") != std::string::npos) {
to_erase.push_back(I);
return;
}
else if (I->getCalledFunction()->getName().str().find("__assert_fail") != std::string::npos) {
to_erase.push_back(I);
return;
}
//else if (I->getCalledFunction()->getName().str().find("NRT_Free") != std::string::npos) {
// to_erase.push_back(I);
// return;
//}
else if (I->getCalledFunction()->getName().str().find("_ZN") != std::string::npos ||
I->getCalledFunction()->getName().str().find("_Zd") != std::string::npos ||
I->getCalledFunction()->getName().str().find("_ZS") != std::string::npos)
{
if (I->getType()->isVoidTy()) {
to_erase.push_back(I);
return;
}
else if (I->getNumUses() == 0) {
to_erase.push_back(I);
return;
}
//
//errs() << I->getNumUses() << "\n";
}
//errs() << *I << "\n";
}
void deal_with_cmp(Module &M, ICmpInst *I) {
Value *V1 = I->getOperand(0);
Value *V2 = I->getOperand(1);
if (V1->getType()->isPointerTy() || V2->getType()->isPointerTy()) {
IRBuilder<> Builder(I);
Value * Intr = Builder.CreateCall(compute_consume_cmp, {ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
Value * V = Builder.CreateIntCast(Intr, Type::getInt1Ty(M.getContext()), true);
I->replaceAllUsesWith(V);
to_erase.push_back(I);
INT_LABEL++;
}
return;
}
void check_rmw(Module &M, CallInst *ci) {
IRBuilder<> Builder(ci);
Instruction* Intr;
if (ci->getCalledFunction()->getName().str().find("dec_atomic_fetch_add_float") != std::string::npos) {
Intr = Builder.CreateCall(compute_consume_float, {ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
INT_LABEL++;
ci->replaceAllUsesWith(Intr);
to_erase.push_back(ci);
} else if (isRMW(ci)) {
Intr = Builder.CreateCall(compute_consume_i32, {ConstantInt::get(Type::getInt32Ty(M.getContext()),INT_LABEL)});
INT_LABEL++;
ci->replaceAllUsesWith(Intr);
to_erase.push_back(ci);
}
}
void instrument_compute(Module &M, Function &f) {
for (inst_iterator iI = inst_begin(&f), iE = inst_end(&f); iI != iE; ++iI) {
if (isa<LoadInst>(*iI)) {
instrument_load(M, (&(*iI)));
}
else if (isa<ExtractValueInst>(*iI)) {
if (is_decoupled_value(&(*iI))) {
ExtractValueInst *tmp = dyn_cast<ExtractValueInst>(&(*iI));
instrument_load(M,(&(*iI)));
}
}
else if (isa<StoreInst>(*iI)) {
instrument_store(M, dyn_cast<StoreInst>(&(*iI)));
}
else if (isa<CallInst>(*iI)) {
CallInst *tmp = dyn_cast<CallInst>(&(*iI));
//For an RMW we need to change this to a consume
check_rmw(M, dyn_cast<CallInst>(&(*iI)));
if (!try_instrument_function(M, dyn_cast<CallInst>(&(*iI)))) {
try_delete_mem_functions(M, dyn_cast<CallInst>(&(*iI)));
}
}
else if (isa<ICmpInst>(*iI)) {
deal_with_cmp(M, dyn_cast<ICmpInst>(&(*iI)));
}
}
for (int i = 0; i < to_erase.size(); i++) {
to_erase[i]->eraseFromParent();
}
to_erase.clear();
}
bool can_delete_inst(Value *val) {
if (isa<CallInst>(*val)) {
CallInst * ci = dyn_cast<CallInst>(&(*val));
if (ci->getCalledFunction()->getName().str().find("desc_compute") != std::string::npos) {
return false;
}
}
return true;
}
void delete_uses(Value *val, bool base) {
if (!can_delete_inst(val)) {
errs() << "Cannot slice supply exclusive accesses from supply!\n";
errs() << "Instruction: " << val << "\n";
assert(0);
}
for (auto use_iter : val->users()) {
if (isa<Instruction>(*use_iter)) {
Instruction *I = dyn_cast<Instruction>(&(*use_iter));
// Can't erase termintors :(
if (I->isTerminator()) {
errs() << "Terminator: " << "\n";
errs() << *I << "\n\n";
}
delete_uses(I, false);
}
}
if (isa<Instruction>(*val)) {
Instruction *I = dyn_cast<Instruction>(&(*val));
if (std::count(to_erase.begin(), to_erase.end(), I) == 0) {
to_erase.push_back(I);
}
}
}
void remove_supply_exclusive_load(Module &M, Function &f) {
for (inst_iterator iI = inst_begin(&f), iE = inst_end(&f); iI != iE; ++iI) {
if (isa<CallInst>(*iI)) {
CallInst * ci = dyn_cast<CallInst>(&(*iI));
if (ci->getCalledFunction()->getName().str().find("supply_exclusive_load") != std::string::npos) {
delete_uses(ci, true);
}
}
}
for (int i = 0; i < to_erase.size(); i++) {
to_erase[i]->eraseFromParent();
}
to_erase.clear();
}
void remove_supply_exclusive_store(Module &M, Function &f) {
for (inst_iterator iI = inst_begin(&f), iE = inst_end(&f); iI != iE; ++iI) {
if (isa<CallInst>(*iI)) {
CallInst * ci = dyn_cast<CallInst>(&(*iI));
if (ci->getCalledFunction()->getName().str().find("supply_exclusive_store") != std::string::npos) {
to_erase.push_back(ci);
}
}
}
for (int i = 0; i < to_erase.size(); i++) {
to_erase[i]->eraseFromParent();
}
to_erase.clear();
}
struct DecoupleComputePass : public ModulePass {
static char ID;
DecoupleComputePass() : ModulePass(ID) {}
virtual bool runOnModule(Module &M) {
errs() << "[Decouple Compute Pass Begin]\n";
populate_functions(M);
populate_functions_common(M);
for (Module::iterator fI = M.begin(), fE = M.end(); fI != fE; ++fI) {
if (isComputeKernelFunction(*fI)) {
errs() << "[Found Kernel]\n";
errs() << "[" << fI->getName().str() << "]\n";
instrument_compute(M, *fI);
remove_supply_exclusive_load(M, *fI);
remove_supply_exclusive_store(M, *fI);
}
}
errs() << "[Unsupported memory access types]\n";
for ( const auto &myPair : unsupported_load_types) {
errs() << myPair.first << " : " << myPair.second << "\n";
}
errs() << "[STORES: " << STORES << "]\n";
errs() << "[NON_DEC_STORES: " << NON_DEC_STORES << "]\n";
errs() << "[LOADS: " << LOADS << "]\n";
errs() << "[Decouple Compute Pass Finished]\n";
return true;
}
};
}
char DecoupleComputePass::ID = 0;
static RegisterPass<DecoupleComputePass> X("decouplecompute", "Decouple Compute Pass", false, false);
| 32.298429 | 148 | 0.613011 | [
"vector"
] |
73728906b768dd62848983681728b4824224fc28 | 1,573 | cpp | C++ | src/io/SpectrumCollectionFactory.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | src/io/SpectrumCollectionFactory.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | src/io/SpectrumCollectionFactory.cpp | johnhalloran321/crux-toolkit | 329390c63a4ec8ab4add22d847732dfa2e7f74ca | [
"Apache-2.0"
] | null | null | null | /**
* \file SpectrumCollectionFactory.cpp
* AUTHOR: Barbara Frewen
* CREATE DATE: 14 June 2011
* \brief Return a SpectrumCollection object of the appropriate
* derived class.
*/
#include "parameter.h"
#include "SpectrumCollectionFactory.h"
#include "MSToolkitSpectrumCollection.h"
#include "PWIZSpectrumCollection.h"
#include "SpectrumRecordSpectrumCollection.h"
#include "util/FileUtils.h"
#include "util/Params.h"
/**
* Instantiates a SpectrumCollection based on the extension of the
* given file and the use-mstoolkit and msgf options.
*/
Crux::SpectrumCollection* SpectrumCollectionFactory::create(const string& filename) {
if (!FileUtils::Exists(filename)) {
carp(CARP_FATAL, "The file %s does not exist. \n", filename.c_str());
}
if (FileUtils::IsDir(filename)) {
carp(CARP_FATAL, "Path %s is a directory. \n Please enter a spectrum filename\
(.ms2, .mgf, or .mzXML)", filename.c_str());
}
if (SpectrumRecordSpectrumCollection::IsSpectrumRecordFile(filename)) {
return new SpectrumRecordSpectrumCollection(filename);
}
string parser = Params::GetString("spectrum-parser");
if (parser == "pwiz") {
carp(CARP_DEBUG, "Using protewizard to parse spectra");
return new PWIZSpectrumCollection(filename);
} else if (parser == "mstoolkit") {
carp(CARP_DEBUG, "Using mstoolkit to parse spectra");
return new MSToolkitSpectrumCollection(filename);
}
carp(CARP_FATAL, "Unknown spectrum parser type");
return(NULL); // Avoid compiler warning.
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 2
* End:
*/
| 30.25 | 85 | 0.723458 | [
"object"
] |
73754704dfd46728d4e2c6fd3ccf87486bdf7895 | 1,236 | cpp | C++ | src/projects/scripts/compress_bed.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | 3 | 2020-11-14T14:41:55.000Z | 2020-12-12T07:05:51.000Z | src/projects/scripts/compress_bed.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | 1 | 2022-02-01T11:16:31.000Z | 2022-02-01T18:56:55.000Z | src/projects/scripts/compress_bed.cpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | null | null | null | #include <common/verify.hpp>
#include <sequences/seqio.hpp>
#include <common/cl_parser.hpp>
int main(int argc, char **argv) {
CLParser parser({"dimer-compress=1000000000,1000000000,1", "contigs=", "bed="}, {}, {},"");
parser.parseCL(argc, argv);
StringContig::homopolymer_compressing = true;
StringContig::SetDimerParameters(parser.getValue("dimer-compress"));
std::ifstream is;
is.open(parser.getValue("bed"));
io::Library contigs_lib = {std::experimental::filesystem::path(parser.getValue("contigs"))};
io::SeqReader reader(contigs_lib);
std::unordered_map<std::string, std::string> contigs;
for(StringContig s : reader) {
contigs.emplace(s.id, std::move(s.seq));
}
std::string line;
while(getline(is,line)) {
std::vector<std::string> s = split(line);
if(s.size() != 3)
break;
size_t start = std::stoull(s[1]);
size_t end = std::stoull(s[2]);
std::string &seq = contigs[s[0]];
start = StringContig(seq.substr(0, start), "c1").makeContig().size();
end = StringContig(seq.substr(0, end), "c2").makeContig().size();
std::cout << s[0] << "\t" << start << "\t" << end << "\n";
}
is.close();
}
| 37.454545 | 96 | 0.604369 | [
"vector"
] |
73768bcdc8af31bc2668c44c9c0d81552a991548 | 1,343 | hpp | C++ | include/learn/environment/bullet/BasicBulletEnvironment.hpp | thomas-gale/learn | a83759d13db1087d2c13fcc7bf967f327de538ed | [
"MIT"
] | 1 | 2020-11-13T22:15:29.000Z | 2020-11-13T22:15:29.000Z | include/learn/environment/bullet/BasicBulletEnvironment.hpp | thomas-gale/learn | a83759d13db1087d2c13fcc7bf967f327de538ed | [
"MIT"
] | 1 | 2020-06-22T08:12:46.000Z | 2020-06-22T08:14:02.000Z | include/learn/environment/bullet/BasicBulletEnvironment.hpp | thomas-gale/learn | a83759d13db1087d2c13fcc7bf967f327de538ed | [
"MIT"
] | null | null | null | #ifndef LEARN_ENV_BULLET_BASICBULLETENVIRONMENT_H_
#define LEARN_ENV_BULLET_BASICBULLETENVIRONMENT_H_
#include "learn/environment/gym/Environment.hpp"
#include "learn/environment/gym/Space.hpp"
#include "learn/environment/gym/State.hpp"
namespace learn {
namespace environment {
namespace bullet {
class BasicBulletEnvironment : public gym::Environment {
public:
BasicBulletEnvironment();
std::shared_ptr<gym::Space> actionSpace() const override;
std::shared_ptr<gym::Space> observationSpace() const override;
// On reset, the environment emmits a shared pointer for learning agents to
// grab.
std::shared_ptr<gym::State> reset() override;
// On step, the agent updates it's internal state and emits a shared pointer
// again (this may be inefficient)
std::shared_ptr<gym::State> step(const std::vector<float>& action,
bool render) override;
void monitorStart(const std::string& directory, bool force,
bool resume) override;
void monitorStop() override;
private:
std::shared_ptr<gym::Space> actionSpace_;
std::shared_ptr<gym::Space> observationSpace_;
std::shared_ptr<gym::State> state_;
};
} // namespace bullet
} // namespace environment
} // namespace learn
#endif // LEARN_ENV_BULLET_BASICBULLETENVIRONMENT_H_ | 32.756098 | 80 | 0.717051 | [
"render",
"vector"
] |
737773a3c01cf41915c54cea12e50a9a017b4336 | 3,116 | cpp | C++ | main/myexe/src/Camera.cpp | BJPerez/OpenGL-Tuto | 254454ebd8903ca876ef1422116f839e209a0a09 | [
"MIT"
] | null | null | null | main/myexe/src/Camera.cpp | BJPerez/OpenGL-Tuto | 254454ebd8903ca876ef1422116f839e209a0a09 | [
"MIT"
] | null | null | null | main/myexe/src/Camera.cpp | BJPerez/OpenGL-Tuto | 254454ebd8903ca876ef1422116f839e209a0a09 | [
"MIT"
] | null | null | null | #include "../include/Camera.hpp"
Camera::Camera(const glm::vec3 position, const glm::vec3 up, const float yaw, const float pitch)
: m_Position(position)
, m_Front(FRONT_DEFAULT)
, m_WorldUp(up)
, m_Yaw (yaw)
, m_Pitch (pitch)
, m_MovementSpeed(SPEED_DEFAULT)
, m_MouseSensitivity(SENSITIVITY_DEFAULT)
, m_Zoom(ZOOM_DEFAULT)
{
UpdateCameraVectors();
}
Camera::Camera(const float posX, const float posY, const float posZ, const float upX, const float upY, const float upZ,
const float yaw, const float pitch)
: m_Position(glm::vec3(posX, posY, posZ))
, m_Front(FRONT_DEFAULT)
, m_WorldUp(glm::vec3(upX, upY, upZ))
, m_Yaw(yaw)
, m_Pitch(pitch)
, m_MovementSpeed(SPEED_DEFAULT)
, m_MouseSensitivity(SENSITIVITY_DEFAULT)
, m_Zoom(ZOOM_DEFAULT)
{
UpdateCameraVectors();
}
float Camera::GetZoom() const
{
return m_Zoom;
}
glm::mat4 Camera::GetViewMatrix() const
{
return glm::lookAt(m_Position, m_Position + m_Front, m_Up);
}
void Camera::ProcessKeyboard(const Camera_Movement& direction, const float deltaTime)
{
const float velocity = m_MovementSpeed * deltaTime;
switch (direction)
{
case Camera_Movement::FORWARD:
{
m_Position += m_Front * velocity;
break;
}
case Camera_Movement::BACKWARD:
{
m_Position -= m_Front * velocity;
break;
}
case Camera_Movement::LEFT:
{
m_Position -= m_Right * velocity;
break;
}
case Camera_Movement::RIGHT:
{
m_Position += m_Right * velocity;
break;
}
}
}
void Camera::ProcessMouseMovement(const float xoffset, const float yoffset, const GLboolean constrainPitch)
{
m_Yaw += (xoffset * m_MouseSensitivity);
m_Yaw = glm::mod(m_Yaw, 360.0f);
m_Pitch += (yoffset * m_MouseSensitivity);
// make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (m_Pitch > 89.0f) m_Pitch = 89.0f;
if (m_Pitch < -89.0f) m_Pitch = -89.0f;
}
// update Front, Right and Up Vectors using the updated Euler angles
UpdateCameraVectors();
}
void Camera::ProcessMouseScroll(const float yoffset)
{
m_Zoom -= yoffset;
if (m_Zoom < 1.0f)
{
m_Zoom = 1.0f;
}
if (m_Zoom > 45.0f)
{
m_Zoom = 45.0f;
}
}
void Camera::UpdateCameraVectors()
{
// calculate the new Front vector
glm::vec3 front;
front.x = cos(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));
front.y = sin(glm::radians(m_Pitch));
front.z = sin(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));
m_Front = glm::normalize(front);
// also re-calculate the Right and Up vector
m_Right = glm::normalize(glm::cross( m_Front, m_WorldUp)); // normalize the vectors, because their length gets closer to 0 the more
// you look up or down which results in slower movement.
m_Up = glm::normalize(glm::cross(m_Right, m_Front));
} | 28.327273 | 135 | 0.620988 | [
"vector"
] |
7379d71312ab6ce4871df5af31b0928127675d6d | 26,641 | cpp | C++ | libs/math/test/test_beta_dist.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/math/test/test_beta_dist.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | libs/math/test/test_beta_dist.cpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | null | null | null | // test_beta_dist.cpp
// Copyright John Maddock 2006.
// Copyright Paul A. Bristow 2007, 2009, 2010.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
// Basic sanity tests for the beta Distribution.
// http://members.aol.com/iandjmsmith/BETAEX.HTM beta distribution calculator
// Appreas to be a 64-bit calculator showing 17 decimal digit (last is noisy).
// Similar to mathCAD?
// http://www.nuhertz.com/statmat/distributions.html#Beta
// Pretty graphs and explanations for most distributions.
// http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp
// provided 40 decimal digits accuracy incomplete beta aka beta regularized == cdf
// http://www.ausvet.com.au/pprev/content.php?page=PPscript
// mode 0.75 5/95% 0.9 alpha 7.39 beta 3.13
// http://www.epi.ucdavis.edu/diagnostictests/betabuster.html
// Beta Buster also calculates alpha and beta from mode & percentile estimates.
// This is NOT (yet) implemented.
#ifdef _MSC_VER
# pragma warning(disable: 4127) // conditional expression is constant.
# pragma warning (disable : 4996) // POSIX name for this item is deprecated
# pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'arg' was previously defined as a type
# pragma warning (disable : 4180) // qualifier applied to function type has no meaning; ignored
#endif
#include <boost/math/concepts/real_concept.hpp> // for real_concept
using ::boost::math::concepts::real_concept;
#include <boost/math/distributions/beta.hpp> // for beta_distribution
using boost::math::beta_distribution;
using boost::math::beta;
#include <boost/test/test_exec_monitor.hpp> // for test_main
#include <boost/test/floating_point_comparison.hpp> // for BOOST_CHECK_CLOSE_FRACTION
#include <iostream>
using std::cout;
using std::endl;
#include <limits>
using std::numeric_limits;
template <class RealType>
void test_spot(
RealType a, // alpha a
RealType b, // beta b
RealType x, // Probability
RealType P, // CDF of beta(a, b)
RealType Q, // Complement of CDF
RealType tol) // Test tolerance.
{
boost::math::beta_distribution<RealType> abeta(a, b);
BOOST_CHECK_CLOSE_FRACTION(cdf(abeta, x), P, tol);
if((P < 0.99) && (Q < 0.99))
{ // We can only check this if P is not too close to 1,
// so that we can guarantee that Q is free of error,
// (and similarly for Q)
BOOST_CHECK_CLOSE_FRACTION(
cdf(complement(abeta, x)), Q, tol);
if(x != 0)
{
BOOST_CHECK_CLOSE_FRACTION(
quantile(abeta, P), x, tol);
}
else
{
// Just check quantile is very small:
if((std::numeric_limits<RealType>::max_exponent <= std::numeric_limits<double>::max_exponent)
&& (boost::is_floating_point<RealType>::value))
{
// Limit where this is checked: if exponent range is very large we may
// run out of iterations in our root finding algorithm.
BOOST_CHECK(quantile(abeta, P) < boost::math::tools::epsilon<RealType>() * 10);
}
} // if k
if(x != 0)
{
BOOST_CHECK_CLOSE_FRACTION(quantile(complement(abeta, Q)), x, tol);
}
else
{ // Just check quantile is very small:
if((std::numeric_limits<RealType>::max_exponent <= std::numeric_limits<double>::max_exponent) && (boost::is_floating_point<RealType>::value))
{ // Limit where this is checked: if exponent range is very large we may
// run out of iterations in our root finding algorithm.
BOOST_CHECK(quantile(complement(abeta, Q)) < boost::math::tools::epsilon<RealType>() * 10);
}
} // if x
// Estimate alpha & beta from mean and variance:
BOOST_CHECK_CLOSE_FRACTION(
beta_distribution<RealType>::find_alpha(mean(abeta), variance(abeta)),
abeta.alpha(), tol);
BOOST_CHECK_CLOSE_FRACTION(
beta_distribution<RealType>::find_beta(mean(abeta), variance(abeta)),
abeta.beta(), tol);
// Estimate sample alpha and beta from others:
BOOST_CHECK_CLOSE_FRACTION(
beta_distribution<RealType>::find_alpha(abeta.beta(), x, P),
abeta.alpha(), tol);
BOOST_CHECK_CLOSE_FRACTION(
beta_distribution<RealType>::find_beta(abeta.alpha(), x, P),
abeta.beta(), tol);
} // if((P < 0.99) && (Q < 0.99)
} // template <class RealType> void test_spot
template <class RealType> // Any floating-point type RealType.
void test_spots(RealType)
{
// Basic sanity checks with 'known good' values.
// MathCAD test data is to double precision only,
// so set tolerance to 100 eps expressed as a fraction, or
// 100 eps of type double expressed as a fraction,
// whichever is the larger.
RealType tolerance = (std::max)
(boost::math::tools::epsilon<RealType>(),
static_cast<RealType>(std::numeric_limits<double>::epsilon())); // 0 if real_concept.
cout << "Boost::math::tools::epsilon = " << boost::math::tools::epsilon<RealType>() <<endl;
cout << "std::numeric_limits::epsilon = " << std::numeric_limits<RealType>::epsilon() <<endl;
cout << "epsilon = " << tolerance;
tolerance *= 100000; // Note: NO * 100 because is fraction, NOT %.
cout << ", Tolerance = " << tolerance * 100 << "%." << endl;
// RealType teneps = boost::math::tools::epsilon<RealType>() * 10;
// Sources of spot test values:
// MathCAD defines dbeta(x, s1, s2) pdf, s1 == alpha, s2 = beta, x = x in Wolfram
// pbeta(x, s1, s2) cdf and qbeta(x, s1, s2) inverse of cdf
// returns pr(X ,= x) when random variable X
// has the beta distribution with parameters s1)alpha) and s2(beta).
// s1 > 0 and s2 >0 and 0 < x < 1 (but allows x == 0! and x == 1!)
// dbeta(0,1,1) = 0
// dbeta(0.5,1,1) = 1
using boost::math::beta_distribution;
using ::boost::math::cdf;
using ::boost::math::pdf;
// Tests that should throw:
BOOST_CHECK_THROW(mode(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1))), std::domain_error);
// mode is undefined, and throws domain_error!
// BOOST_CHECK_THROW(median(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1))), std::domain_error);
// median is undefined, and throws domain_error!
// But now median IS provided via derived accessor as quantile(half).
BOOST_CHECK_THROW( // For various bad arguments.
pdf(
beta_distribution<RealType>(static_cast<RealType>(-1), static_cast<RealType>(1)), // bad alpha < 0.
static_cast<RealType>(1)), std::domain_error);
BOOST_CHECK_THROW(
pdf(
beta_distribution<RealType>(static_cast<RealType>(0), static_cast<RealType>(1)), // bad alpha == 0.
static_cast<RealType>(1)), std::domain_error);
BOOST_CHECK_THROW(
pdf(
beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(0)), // bad beta == 0.
static_cast<RealType>(1)), std::domain_error);
BOOST_CHECK_THROW(
pdf(
beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(-1)), // bad beta < 0.
static_cast<RealType>(1)), std::domain_error);
BOOST_CHECK_THROW(
pdf(
beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)), // bad x < 0.
static_cast<RealType>(-1)), std::domain_error);
BOOST_CHECK_THROW(
pdf(
beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)), // bad x > 1.
static_cast<RealType>(999)), std::domain_error);
// Some exact pdf values.
BOOST_CHECK_EQUAL( // a = b = 1 is uniform distribution.
pdf(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)),
static_cast<RealType>(1)), // x
static_cast<RealType>(1));
BOOST_CHECK_EQUAL(
pdf(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)),
static_cast<RealType>(0)), // x
static_cast<RealType>(1));
BOOST_CHECK_CLOSE_FRACTION(
pdf(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)),
static_cast<RealType>(0.5)), // x
static_cast<RealType>(1),
tolerance);
BOOST_CHECK_EQUAL(
beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)).alpha(),
static_cast<RealType>(1) ); //
BOOST_CHECK_EQUAL(
mean(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1))),
static_cast<RealType>(0.5) ); // Exact one half.
BOOST_CHECK_CLOSE_FRACTION(
pdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.5)), // x
static_cast<RealType>(1.5), // Exactly 3/2
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
pdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.5)), // x
static_cast<RealType>(1.5), // Exactly 3/2
tolerance);
// CDF
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.1)), // x
static_cast<RealType>(0.02800000000000000000000000000000000000000L), // Seems exact.
// http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp?name=BetaRegularized&ptype=0&z=0.1&a=2&b=2&digits=40
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.0001)), // x
static_cast<RealType>(2.999800000000000000000000000000000000000e-8L),
// http://members.aol.com/iandjmsmith/BETAEX.HTM 2.9998000000004
// http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp?name=BetaRegularized&ptype=0&z=0.0001&a=2&b=2&digits=40
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
pdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.0001)), // x
static_cast<RealType>(0.0005999400000000004L), // http://members.aol.com/iandjmsmith/BETAEX.HTM
// Slightly higher tolerance for real concept:
(std::numeric_limits<RealType>::is_specialized ? 1 : 10) * tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.9999)), // x
static_cast<RealType>(0.999999970002L), // http://members.aol.com/iandjmsmith/BETAEX.HTM
// Wolfram 0.9999999700020000000000000000000000000000
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(2)),
static_cast<RealType>(0.9)), // x
static_cast<RealType>(0.9961174629530394895796514664963063381217L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.1)), // x
static_cast<RealType>(0.2048327646991334516491978475505189480977L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.9)), // x
static_cast<RealType>(0.7951672353008665483508021524494810519023L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
quantile(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.7951672353008665483508021524494810519023L)), // x
static_cast<RealType>(0.9),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.6)), // x
static_cast<RealType>(0.5640942168489749316118742861695149357858L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
quantile(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.5640942168489749316118742861695149357858L)), // x
static_cast<RealType>(0.6),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.5)),
static_cast<RealType>(0.6)), // x
static_cast<RealType>(0.1778078083562213736802876784474931812329L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
quantile(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(0.5)),
static_cast<RealType>(0.1778078083562213736802876784474931812329L)), // x
static_cast<RealType>(0.6),
// Wolfram
tolerance); // gives
BOOST_CHECK_CLOSE_FRACTION(
cdf(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)),
static_cast<RealType>(0.1)), // x
static_cast<RealType>(0.1), // 0.1000000000000000000000000000000000000000
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
quantile(beta_distribution<RealType>(static_cast<RealType>(1), static_cast<RealType>(1)),
static_cast<RealType>(0.1)), // x
static_cast<RealType>(0.1), // 0.1000000000000000000000000000000000000000
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(complement(beta_distribution<RealType>(static_cast<RealType>(0.5), static_cast<RealType>(0.5)),
static_cast<RealType>(0.1))), // complement of x
static_cast<RealType>(0.7951672353008665483508021524494810519023L),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
quantile(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.0280000000000000000000000000000000000L)), // x
static_cast<RealType>(0.1),
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
cdf(complement(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.1))), // x
static_cast<RealType>(0.9720000000000000000000000000000000000000L), // Exact.
// Wolfram
tolerance);
BOOST_CHECK_CLOSE_FRACTION(
pdf(beta_distribution<RealType>(static_cast<RealType>(2), static_cast<RealType>(2)),
static_cast<RealType>(0.9999)), // x
static_cast<RealType>(0.0005999399999999344L), // http://members.aol.com/iandjmsmith/BETAEX.HTM
tolerance*10); // Note loss of precision calculating 1-p test value.
//void test_spot(
// RealType a, // alpha a
// RealType b, // beta b
// RealType x, // Probability
// RealType P, // CDF of beta(a, b)
// RealType Q, // Complement of CDF
// RealType tol) // Test tolerance.
// These test quantiles and complements, and parameter estimates as well.
// Spot values using, for example:
// http://functions.wolfram.com/webMathematica/FunctionEvaluation.jsp?name=BetaRegularized&ptype=0&z=0.1&a=0.5&b=3&digits=40
test_spot(
static_cast<RealType>(1), // alpha a
static_cast<RealType>(1), // beta b
static_cast<RealType>(0.1), // Probability p
static_cast<RealType>(0.1), // Probability of result (CDF of beta), P
static_cast<RealType>(0.9), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.1), // Probability p
static_cast<RealType>(0.0280000000000000000000000000000000000L), // Probability of result (CDF of beta), P
static_cast<RealType>(1 - 0.0280000000000000000000000000000000000L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.5), // Probability p
static_cast<RealType>(0.5), // Probability of result (CDF of beta), P
static_cast<RealType>(0.5), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.9), // Probability p
static_cast<RealType>(0.972000000000000), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.972000000000000), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.01), // Probability p
static_cast<RealType>(0.0002980000000000000000000000000000000000000L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.0002980000000000000000000000000000000000000L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.001), // Probability p
static_cast<RealType>(2.998000000000000000000000000000000000000E-6L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-2.998000000000000000000000000000000000000E-6L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.0001), // Probability p
static_cast<RealType>(2.999800000000000000000000000000000000000E-8L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-2.999800000000000000000000000000000000000E-8L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(2), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.99), // Probability p
static_cast<RealType>(0.9997020000000000000000000000000000000000L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.9997020000000000000000000000000000000000L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(0.5), // alpha a
static_cast<RealType>(2), // beta b
static_cast<RealType>(0.5), // Probability p
static_cast<RealType>(0.8838834764831844055010554526310612991060L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.8838834764831844055010554526310612991060L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(0.5), // alpha a
static_cast<RealType>(3.), // beta b
static_cast<RealType>(0.7), // Probability p
static_cast<RealType>(0.9903963064097119299191611355232156905687L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.9903963064097119299191611355232156905687L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
test_spot(
static_cast<RealType>(0.5), // alpha a
static_cast<RealType>(3.), // beta b
static_cast<RealType>(0.1), // Probability p
static_cast<RealType>(0.5545844446520295253493059553548880128511L), // Probability of result (CDF of beta), P
static_cast<RealType>(1-0.5545844446520295253493059553548880128511L), // Complement of CDF Q = 1 - P
tolerance); // Test tolerance.
} // template <class RealType>void test_spots(RealType)
int test_main(int, char* [])
{
BOOST_MATH_CONTROL_FP;
// Check that can generate beta distribution using one convenience methods:
beta_distribution<> mybeta11(1., 1.); // Using default RealType double.
// but that
// boost::math::beta mybeta1(1., 1.); // Using typedef fails.
// error C2039: 'beta' : is not a member of 'boost::math'
// Basic sanity-check spot values.
// Some simple checks using double only.
BOOST_CHECK_EQUAL(mybeta11.alpha(), 1); //
BOOST_CHECK_EQUAL(mybeta11.beta(), 1);
BOOST_CHECK_EQUAL(mean(mybeta11), 0.5); // 1 / (1 + 1) = 1/2 exactly
BOOST_CHECK_THROW(mode(mybeta11), std::domain_error);
beta_distribution<> mybeta22(2., 2.); // pdf is dome shape.
BOOST_CHECK_EQUAL(mode(mybeta22), 0.5); // 2-1 / (2+2-2) = 1/2 exactly.
beta_distribution<> mybetaH2(0.5, 2.); //
beta_distribution<> mybetaH3(0.5, 3.); //
// Check a few values using double.
BOOST_CHECK_EQUAL(pdf(mybeta11, 1), 1); // is uniform unity over 0 to 1,
BOOST_CHECK_EQUAL(pdf(mybeta11, 0), 1); // including zero and unity.
// Although these next three have an exact result, internally they're
// *not* treated as special cases, and may be out by a couple of eps:
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta11, 0.5), 1.0, 5*std::numeric_limits<double>::epsilon());
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta11, 0.0001), 1.0, 5*std::numeric_limits<double>::epsilon());
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta11, 0.9999), 1.0, 5*std::numeric_limits<double>::epsilon());
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta11, 0.1), 0.1, 2 * std::numeric_limits<double>::epsilon());
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta11, 0.5), 0.5, 2 * std::numeric_limits<double>::epsilon());
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta11, 0.9), 0.9, 2 * std::numeric_limits<double>::epsilon());
BOOST_CHECK_EQUAL(cdf(mybeta11, 1), 1.); // Exact unity expected.
double tol = std::numeric_limits<double>::epsilon() * 10;
BOOST_CHECK_EQUAL(pdf(mybeta22, 1), 0); // is dome shape.
BOOST_CHECK_EQUAL(pdf(mybeta22, 0), 0);
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta22, 0.5), 1.5, tol); // top of dome, expect exactly 3/2.
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta22, 0.0001), 5.9994000000000E-4, tol);
BOOST_CHECK_CLOSE_FRACTION(pdf(mybeta22, 0.9999), 5.9994000000000E-4, tol*50);
BOOST_CHECK_EQUAL(cdf(mybeta22, 0.), 0); // cdf is a curved line from 0 to 1.
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.1), 0.028000000000000, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.5), 0.5, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.9), 0.972000000000000, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.0001), 2.999800000000000000000000000000000000000E-8, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.001), 2.998000000000000000000000000000000000000E-6, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.01), 0.0002980000000000000000000000000000000000000, tol);
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.1), 0.02800000000000000000000000000000000000000, tol); // exact
BOOST_CHECK_CLOSE_FRACTION(cdf(mybeta22, 0.99), 0.9997020000000000000000000000000000000000, tol);
BOOST_CHECK_EQUAL(cdf(mybeta22, 1), 1.); // Exact unity expected.
// Complement
BOOST_CHECK_CLOSE_FRACTION(cdf(complement(mybeta22, 0.9)), 0.028000000000000, tol);
// quantile.
BOOST_CHECK_CLOSE_FRACTION(quantile(mybeta22, 0.028), 0.1, tol);
BOOST_CHECK_CLOSE_FRACTION(quantile(complement(mybeta22, 1 - 0.028)), 0.1, tol);
BOOST_CHECK_EQUAL(kurtosis(mybeta11), 3+ kurtosis_excess(mybeta11)); // Check kurtosis_excess = kurtosis - 3;
BOOST_CHECK_CLOSE_FRACTION(variance(mybeta22), 0.05, tol);
BOOST_CHECK_CLOSE_FRACTION(mean(mybeta22), 0.5, tol);
BOOST_CHECK_CLOSE_FRACTION(mode(mybeta22), 0.5, tol);
BOOST_CHECK_CLOSE_FRACTION(median(mybeta22), 0.5, sqrt(tol)); // Theoretical maximum accuracy using Brent is sqrt(epsilon).
BOOST_CHECK_CLOSE_FRACTION(skewness(mybeta22), 0.0, tol);
BOOST_CHECK_CLOSE_FRACTION(kurtosis_excess(mybeta22), -144.0 / 168, tol);
BOOST_CHECK_CLOSE_FRACTION(skewness(beta_distribution<>(3, 5)), 0.30983866769659335081434123198259, tol);
BOOST_CHECK_CLOSE_FRACTION(beta_distribution<double>::find_alpha(mean(mybeta22), variance(mybeta22)), mybeta22.alpha(), tol); // mean, variance, probability.
BOOST_CHECK_CLOSE_FRACTION(beta_distribution<double>::find_beta(mean(mybeta22), variance(mybeta22)), mybeta22.beta(), tol);// mean, variance, probability.
BOOST_CHECK_CLOSE_FRACTION(mybeta22.find_alpha(mybeta22.beta(), 0.8, cdf(mybeta22, 0.8)), mybeta22.alpha(), tol);
BOOST_CHECK_CLOSE_FRACTION(mybeta22.find_beta(mybeta22.alpha(), 0.8, cdf(mybeta22, 0.8)), mybeta22.beta(), tol);
beta_distribution<real_concept> rcbeta22(2, 2); // Using RealType real_concept.
cout << "numeric_limits<real_concept>::is_specialized " << numeric_limits<real_concept>::is_specialized << endl;
cout << "numeric_limits<real_concept>::digits " << numeric_limits<real_concept>::digits << endl;
cout << "numeric_limits<real_concept>::digits10 " << numeric_limits<real_concept>::digits10 << endl;
cout << "numeric_limits<real_concept>::epsilon " << numeric_limits<real_concept>::epsilon() << endl;
// (Parameter value, arbitrarily zero, only communicates the floating point type).
test_spots(0.0F); // Test float.
test_spots(0.0); // Test double.
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
test_spots(0.0L); // Test long double.
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.
#endif
#endif
return 0;
} // int test_main(int, char* [])
/*
Output is:
-Autorun "i:\boost-06-05-03-1300\libs\math\test\Math_test\debug\test_beta_dist.exe"
Running 1 test case...
numeric_limits<real_concept>::is_specialized 0
numeric_limits<real_concept>::digits 0
numeric_limits<real_concept>::digits10 0
numeric_limits<real_concept>::epsilon 0
Boost::math::tools::epsilon = 1.19209e-007
std::numeric_limits::epsilon = 1.19209e-007
epsilon = 1.19209e-007, Tolerance = 0.0119209%.
Boost::math::tools::epsilon = 2.22045e-016
std::numeric_limits::epsilon = 2.22045e-016
epsilon = 2.22045e-016, Tolerance = 2.22045e-011%.
Boost::math::tools::epsilon = 2.22045e-016
std::numeric_limits::epsilon = 2.22045e-016
epsilon = 2.22045e-016, Tolerance = 2.22045e-011%.
Boost::math::tools::epsilon = 2.22045e-016
std::numeric_limits::epsilon = 0
epsilon = 2.22045e-016, Tolerance = 2.22045e-011%.
*** No errors detected
*/
| 45.696398 | 161 | 0.682745 | [
"shape"
] |
737a2930a3820f7f7a496bf573b5e387f75cca15 | 4,174 | hpp | C++ | far/headers.hpp | qlost/FarManager | f6a938157b306ef510bcf02ee404b78e1353e057 | [
"BSD-3-Clause"
] | 1 | 2019-03-09T03:13:22.000Z | 2019-03-09T03:13:22.000Z | far/headers.hpp | qlost/FarManager | f6a938157b306ef510bcf02ee404b78e1353e057 | [
"BSD-3-Clause"
] | null | null | null | far/headers.hpp | qlost/FarManager | f6a938157b306ef510bcf02ee404b78e1353e057 | [
"BSD-3-Clause"
] | null | null | null | #ifndef HEADERS_HPP_9A02D08B_02BB_4240_845F_36ED60ED2647
#define HEADERS_HPP_9A02D08B_02BB_4240_845F_36ED60ED2647
#pragma once
/*
headers.hpp
Стандартные заголовки
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#ifdef _MSC_VER
#if !defined __clang__ && _MSC_FULL_VER < 191627023
#error Visual C++ 2017 Update 9 (or higher) required
#endif
#endif //_MSC_VER
#ifdef __GNUC__
#define GCC_VER_(gcc_major,gcc_minor,gcc_patch) (100*(gcc_major) + 10*(gcc_minor) + (gcc_patch))
#define _GCC_VER GCC_VER_(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
#if !defined __clang__ && _GCC_VER < GCC_VER_(8,1,0)
#error gcc 8.1.0 (or higher) required
#endif
#endif
#ifdef __GNUC__
// Current implementation of wcschr etc. in gcc removes const from returned pointer. Issue has been opened since 2007.
// These semi-magical defines and appropriate overloads in cpp.hpp are intended to fix this madness.
// Force C version to return const
#define _CONST_RETURN const
// Disable broken inline overloads
#define __CORRECT_ISO_CPP_WCHAR_H_PROTO
#endif
#include "disable_warnings_in_std_begin.hpp"
//----------------------------------------------------------------------------
#include <algorithm>
#include <any>
#include <array>
#include <atomic>
#include <bitset>
#include <chrono>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <queue>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <optional>
#include <random>
#include <regex>
#include <set>
#include <shared_mutex>
#include <sstream>
#include <stack>
#include <string>
#include <string_view>
#include <thread>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <variant>
#include <vector>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <cwchar>
#include <cwctype>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <share.h>
//----------------------------------------------------------------------------
#include "disable_warnings_in_std_end.hpp"
#include "common/cpp.hpp"
using string = std::wstring;
using string_view = std::wstring_view;
inline namespace literals
{
using namespace std::literals;
}
static_assert(std::is_unsigned_v<char>);
static_assert(sizeof(wchar_t) == 2);
static_assert("𠜎"sv == "\xF0\xA0\x9C\x8E"sv);
namespace features
{
constexpr auto
mantis_698 = false,
mantis_2562 = false,
win10_curdir = false,
reserved = false;
}
// BUGBUG remove
#define PRECOMPILE_PLATFORM_HEADERS
#ifdef PRECOMPILE_PLATFORM_HEADERS
#include "platform.headers.hpp"
#endif
#endif // HEADERS_HPP_9A02D08B_02BB_4240_845F_36ED60ED2647
| 27.103896 | 118 | 0.749401 | [
"vector"
] |
737a9fda8c25c64ddbf5e59aad8b0957c63d0209 | 28,124 | cc | C++ | chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/metrics/histogram_samples.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/ui/passwords/passwords_model_delegate_mock.h"
#include "chrome/test/base/testing_profile.h"
#include "components/password_manager/core/browser/mock_password_store.h"
#include "components/password_manager/core/browser/password_form_metrics_recorder.h"
#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/password_manager/core/browser/password_manager_test_utils.h"
#include "components/password_manager/core/browser/statistics_table.h"
#include "components/password_manager/core/common/credential_manager_types.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/password_manager/core/common/password_manager_ui.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_source.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Return;
using ::testing::ReturnRef;
namespace {
constexpr ukm::SourceId kTestSourceId = 0x1234;
constexpr char kSiteOrigin[] = "http://example.com/login";
constexpr char kUsername[] = "Admin";
constexpr char kUsernameExisting[] = "User";
constexpr char kUsernameNew[] = "User585";
constexpr char kPassword[] = "AdminPass";
constexpr char kPasswordEdited[] = "asDfjkl;";
constexpr char kUIDismissalReasonGeneralMetric[] =
"PasswordManager.UIDismissalReason";
constexpr char kUIDismissalReasonSaveMetric[] =
"PasswordManager.SaveUIDismissalReason";
constexpr char kUIDismissalReasonUpdateMetric[] =
"PasswordManager.UpdateUIDismissalReason";
} // namespace
class SaveUpdateBubbleControllerTest : public ::testing::Test {
public:
SaveUpdateBubbleControllerTest() {
// If kEnablePasswordsAccountStorage is enabled, then
// SaveUpdateWithAccountStoreBubbleController is used instead of this class.
feature_list_.InitAndDisableFeature(
password_manager::features::kEnablePasswordsAccountStorage);
}
~SaveUpdateBubbleControllerTest() override = default;
void SetUp() override {
test_web_contents_ =
content::WebContentsTester::CreateTestWebContents(&profile_, nullptr);
mock_delegate_ =
std::make_unique<testing::NiceMock<PasswordsModelDelegateMock>>();
ON_CALL(*mock_delegate_, GetPasswordFormMetricsRecorder())
.WillByDefault(Return(nullptr));
PasswordStoreFactory::GetInstance()->SetTestingFactoryAndUse(
profile(),
base::BindRepeating(
&password_manager::BuildPasswordStore<
content::BrowserContext,
testing::StrictMock<password_manager::MockPasswordStore>>));
pending_password_.url = GURL(kSiteOrigin);
pending_password_.signon_realm = kSiteOrigin;
pending_password_.username_value = base::ASCIIToUTF16(kUsername);
pending_password_.password_value = base::ASCIIToUTF16(kPassword);
}
void TearDown() override {
// Reset the delegate first. It can happen if the user closes the tab.
mock_delegate_.reset();
controller_.reset();
}
PrefService* prefs() { return profile_.GetPrefs(); }
TestingProfile* profile() { return &profile_; }
password_manager::MockPasswordStore* GetStore() {
return static_cast<password_manager::MockPasswordStore*>(
PasswordStoreFactory::GetInstance()
->GetForProfile(profile(), ServiceAccessType::EXPLICIT_ACCESS)
.get());
}
PasswordsModelDelegateMock* delegate() { return mock_delegate_.get(); }
SaveUpdateBubbleController* controller() { return controller_.get(); }
password_manager::PasswordForm& pending_password() {
return pending_password_;
}
const password_manager::PasswordForm& pending_password() const {
return pending_password_;
}
void SetUpWithState(password_manager::ui::State state,
PasswordBubbleControllerBase::DisplayReason reason);
void PretendPasswordWaiting(
PasswordBubbleControllerBase::DisplayReason reason =
PasswordBubbleControllerBase::DisplayReason::kAutomatic);
void PretendUpdatePasswordWaiting();
void DestroyModelAndVerifyControllerExpectations();
void DestroyModelExpectReason(
password_manager::metrics_util::UIDismissalReason dismissal_reason);
static password_manager::InteractionsStats GetTestStats();
std::vector<std::unique_ptr<password_manager::PasswordForm>> GetCurrentForms()
const;
private:
base::test::ScopedFeatureList feature_list_;
content::BrowserTaskEnvironment task_environment_;
content::RenderViewHostTestEnabler rvh_enabler_;
TestingProfile profile_;
std::unique_ptr<content::WebContents> test_web_contents_;
std::unique_ptr<SaveUpdateBubbleController> controller_;
std::unique_ptr<PasswordsModelDelegateMock> mock_delegate_;
password_manager::PasswordForm pending_password_;
};
void SaveUpdateBubbleControllerTest::SetUpWithState(
password_manager::ui::State state,
PasswordBubbleControllerBase::DisplayReason reason) {
url::Origin origin = url::Origin::Create(GURL(kSiteOrigin));
EXPECT_CALL(*delegate(), GetOrigin()).WillOnce(Return(origin));
EXPECT_CALL(*delegate(), GetState()).WillRepeatedly(Return(state));
EXPECT_CALL(*delegate(), GetWebContents())
.WillRepeatedly(Return(test_web_contents_.get()));
controller_ = std::make_unique<SaveUpdateBubbleController>(
mock_delegate_->AsWeakPtr(), reason);
ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(delegate()));
EXPECT_CALL(*delegate(), GetWebContents())
.WillRepeatedly(Return(test_web_contents_.get()));
}
void SaveUpdateBubbleControllerTest::PretendPasswordWaiting(
PasswordBubbleControllerBase::DisplayReason reason) {
EXPECT_CALL(*delegate(), GetPendingPassword())
.WillOnce(ReturnRef(pending_password()));
password_manager::InteractionsStats stats = GetTestStats();
EXPECT_CALL(*delegate(), GetCurrentInteractionStats())
.WillOnce(Return(&stats));
std::vector<std::unique_ptr<password_manager::PasswordForm>> forms =
GetCurrentForms();
EXPECT_CALL(*delegate(), GetCurrentForms()).WillOnce(ReturnRef(forms));
SetUpWithState(password_manager::ui::PENDING_PASSWORD_STATE, reason);
}
void SaveUpdateBubbleControllerTest::PretendUpdatePasswordWaiting() {
EXPECT_CALL(*delegate(), GetPendingPassword())
.WillOnce(ReturnRef(pending_password()));
std::vector<std::unique_ptr<password_manager::PasswordForm>> forms =
GetCurrentForms();
auto current_form =
std::make_unique<password_manager::PasswordForm>(pending_password());
current_form->password_value = u"old_password";
forms.push_back(std::move(current_form));
EXPECT_CALL(*delegate(), GetCurrentForms()).WillOnce(ReturnRef(forms));
SetUpWithState(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE,
PasswordBubbleControllerBase::DisplayReason::kAutomatic);
}
void SaveUpdateBubbleControllerTest::
DestroyModelAndVerifyControllerExpectations() {
EXPECT_CALL(*delegate(), OnBubbleHidden());
controller_->OnBubbleClosing();
ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(delegate()));
controller_.reset();
}
void SaveUpdateBubbleControllerTest::DestroyModelExpectReason(
password_manager::metrics_util::UIDismissalReason dismissal_reason) {
base::HistogramTester histogram_tester;
password_manager::ui::State state = controller_->state();
std::string histogram(kUIDismissalReasonGeneralMetric);
if (state == password_manager::ui::PENDING_PASSWORD_STATE)
histogram = kUIDismissalReasonSaveMetric;
else if (state == password_manager::ui::PENDING_PASSWORD_UPDATE_STATE)
histogram = kUIDismissalReasonUpdateMetric;
DestroyModelAndVerifyControllerExpectations();
histogram_tester.ExpectUniqueSample(histogram, dismissal_reason, 1);
}
// static
password_manager::InteractionsStats
SaveUpdateBubbleControllerTest::GetTestStats() {
password_manager::InteractionsStats result;
result.origin_domain = GURL(kSiteOrigin).GetOrigin();
result.username_value = base::ASCIIToUTF16(kUsername);
result.dismissal_count = 5;
result.update_time = base::Time::FromTimeT(1);
return result;
}
std::vector<std::unique_ptr<password_manager::PasswordForm>>
SaveUpdateBubbleControllerTest::GetCurrentForms() const {
password_manager::PasswordForm form(pending_password());
form.username_value = base::ASCIIToUTF16(kUsernameExisting);
form.password_value = u"123456";
password_manager::PasswordForm preferred_form(pending_password());
preferred_form.username_value = u"preferred_username";
preferred_form.password_value = u"654321";
std::vector<std::unique_ptr<password_manager::PasswordForm>> forms;
forms.push_back(std::make_unique<password_manager::PasswordForm>(form));
forms.push_back(
std::make_unique<password_manager::PasswordForm>(preferred_form));
return forms;
}
// Tests that the controller reads the value of
// ArePasswordsRevealedWhenBubbleIsOpened() before invoking OnBubbleShown()
// since the latter resets the value returned by the former. (crbug.com/1049085)
TEST_F(SaveUpdateBubbleControllerTest,
ArePasswordsRevealedWhenBubbleIsOpenedBeforeOnBubbleShown) {
{
testing::InSequence s;
EXPECT_CALL(*delegate(), ArePasswordsRevealedWhenBubbleIsOpened());
EXPECT_CALL(*delegate(), OnBubbleShown());
}
PretendPasswordWaiting();
}
TEST_F(SaveUpdateBubbleControllerTest, CloseWithoutInteraction) {
PretendPasswordWaiting();
EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE,
controller()->state());
base::SimpleTestClock clock;
base::Time now = base::Time::Now();
clock.SetNow(now);
controller()->set_clock(&clock);
password_manager::InteractionsStats stats = GetTestStats();
stats.dismissal_count++;
stats.update_time = now;
EXPECT_CALL(*GetStore(), AddSiteStatsImpl(stats));
EXPECT_CALL(*delegate(), OnNoInteraction());
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
DestroyModelExpectReason(
password_manager::metrics_util::NO_DIRECT_INTERACTION);
}
TEST_F(SaveUpdateBubbleControllerTest, ClickSave) {
PretendPasswordWaiting();
EXPECT_TRUE(controller()->enable_editing());
EXPECT_FALSE(controller()->IsCurrentStateUpdate());
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), OnPasswordsRevealed()).Times(0);
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
EXPECT_CALL(*delegate(), OnNopeUpdateClicked()).Times(0);
controller()->OnSaveClicked();
DestroyModelExpectReason(password_manager::metrics_util::CLICKED_ACCEPT);
}
TEST_F(SaveUpdateBubbleControllerTest, ClickSaveInUpdateState) {
PretendUpdatePasswordWaiting();
// Edit username, now it's a new credential.
controller()->OnCredentialEdited(base::ASCIIToUTF16(kUsernameNew),
base::ASCIIToUTF16(kPasswordEdited));
EXPECT_FALSE(controller()->IsCurrentStateUpdate());
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(base::ASCIIToUTF16(kUsernameNew),
base::ASCIIToUTF16(kPasswordEdited)));
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
EXPECT_CALL(*delegate(), OnNopeUpdateClicked()).Times(0);
controller()->OnSaveClicked();
DestroyModelExpectReason(password_manager::metrics_util::CLICKED_ACCEPT);
}
TEST_F(SaveUpdateBubbleControllerTest, ClickNever) {
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
EXPECT_CALL(*delegate(), NeverSavePassword());
controller()->OnNeverForThisSiteClicked();
EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE,
controller()->state());
DestroyModelExpectReason(password_manager::metrics_util::CLICKED_NEVER);
}
TEST_F(SaveUpdateBubbleControllerTest, ClickUpdate) {
PretendUpdatePasswordWaiting();
EXPECT_TRUE(controller()->enable_editing());
EXPECT_TRUE(controller()->IsCurrentStateUpdate());
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), OnPasswordsRevealed()).Times(0);
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
EXPECT_CALL(*delegate(), OnNopeUpdateClicked()).Times(0);
controller()->OnSaveClicked();
DestroyModelExpectReason(password_manager::metrics_util::CLICKED_ACCEPT);
}
TEST_F(SaveUpdateBubbleControllerTest, ClickUpdateInSaveState) {
PretendPasswordWaiting();
// Edit username, now it's an existing credential.
controller()->OnCredentialEdited(base::ASCIIToUTF16(kUsernameExisting),
base::ASCIIToUTF16(kPasswordEdited));
EXPECT_TRUE(controller()->IsCurrentStateUpdate());
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(base::ASCIIToUTF16(kUsernameExisting),
base::ASCIIToUTF16(kPasswordEdited)));
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
EXPECT_CALL(*delegate(), OnNopeUpdateClicked()).Times(0);
controller()->OnSaveClicked();
DestroyModelExpectReason(password_manager::metrics_util::CLICKED_ACCEPT);
}
TEST_F(SaveUpdateBubbleControllerTest, GetInitialUsername_MatchedUsername) {
PretendUpdatePasswordWaiting();
EXPECT_EQ(base::UTF8ToUTF16(kUsername),
controller()->pending_password().username_value);
}
TEST_F(SaveUpdateBubbleControllerTest, EditCredential) {
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
const std::u16string kExpectedUsername = u"new_username";
const std::u16string kExpectedPassword = u"new_password";
controller()->OnCredentialEdited(kExpectedUsername, kExpectedPassword);
EXPECT_EQ(kExpectedUsername, controller()->pending_password().username_value);
EXPECT_EQ(kExpectedPassword, controller()->pending_password().password_value);
EXPECT_CALL(*delegate(), SavePassword(kExpectedUsername, kExpectedPassword));
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
controller()->OnSaveClicked();
DestroyModelAndVerifyControllerExpectations();
}
TEST_F(SaveUpdateBubbleControllerTest, SuppressSignInPromo) {
prefs()->SetBoolean(password_manager::prefs::kSignInPasswordPromoRevive,
true);
prefs()->SetBoolean(password_manager::prefs::kWasSignInPasswordPromoClicked,
true);
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
controller()->OnSaveClicked();
EXPECT_FALSE(controller()->ReplaceToShowPromotionIfNeeded());
DestroyModelAndVerifyControllerExpectations();
}
TEST_F(SaveUpdateBubbleControllerTest, SignInPromoOK) {
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
controller()->OnSaveClicked();
#if BUILDFLAG(IS_CHROMEOS_ASH)
EXPECT_FALSE(controller()->ReplaceToShowPromotionIfNeeded());
#else
EXPECT_TRUE(controller()->ReplaceToShowPromotionIfNeeded());
#endif
}
#if !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(SaveUpdateBubbleControllerTest, SignInPromoCancel) {
base::HistogramTester histogram_tester;
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
controller()->OnSaveClicked();
EXPECT_TRUE(controller()->ReplaceToShowPromotionIfNeeded());
DestroyModelAndVerifyControllerExpectations();
histogram_tester.ExpectUniqueSample(
kUIDismissalReasonSaveMetric,
password_manager::metrics_util::CLICKED_ACCEPT, 1);
}
TEST_F(SaveUpdateBubbleControllerTest, SignInPromoDismiss) {
base::HistogramTester histogram_tester;
PretendPasswordWaiting();
EXPECT_CALL(*GetStore(), RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(pending_password().username_value,
pending_password().password_value));
controller()->OnSaveClicked();
EXPECT_TRUE(controller()->ReplaceToShowPromotionIfNeeded());
DestroyModelAndVerifyControllerExpectations();
histogram_tester.ExpectUniqueSample(
kUIDismissalReasonSaveMetric,
password_manager::metrics_util::CLICKED_ACCEPT, 1);
EXPECT_FALSE(prefs()->GetBoolean(
password_manager::prefs::kWasSignInPasswordPromoClicked));
}
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
// Verify that URL keyed metrics are properly recorded.
TEST_F(SaveUpdateBubbleControllerTest, RecordUKMs) {
using BubbleDismissalReason =
password_manager::PasswordFormMetricsRecorder::BubbleDismissalReason;
using BubbleTrigger =
password_manager::PasswordFormMetricsRecorder::BubbleTrigger;
using password_manager::metrics_util::CredentialSourceType;
using UkmEntry = ukm::builders::PasswordForm;
// |credential_management_api| defines whether credentials originate from the
// credential management API.
for (const bool credential_management_api : {false, true}) {
// |update| defines whether this is an update or a save bubble.
for (const bool update : {false, true}) {
for (const auto interaction :
{BubbleDismissalReason::kAccepted, BubbleDismissalReason::kDeclined,
BubbleDismissalReason::kIgnored}) {
SCOPED_TRACE(testing::Message()
<< "update = " << update
<< ", interaction = " << static_cast<int64_t>(interaction)
<< ", credential management api ="
<< credential_management_api);
ukm::TestAutoSetUkmRecorder test_ukm_recorder;
{
// Setup metrics recorder
auto recorder = base::MakeRefCounted<
password_manager::PasswordFormMetricsRecorder>(
true /*is_main_frame_secure*/, kTestSourceId,
/*pref_service=*/nullptr);
// Exercise bubble.
ON_CALL(*delegate(), GetPasswordFormMetricsRecorder())
.WillByDefault(Return(recorder.get()));
ON_CALL(*delegate(), GetCredentialSource())
.WillByDefault(
Return(credential_management_api
? CredentialSourceType::kCredentialManagementAPI
: CredentialSourceType::kPasswordManager));
if (update)
PretendUpdatePasswordWaiting();
else
PretendPasswordWaiting();
if (interaction == BubbleDismissalReason::kAccepted) {
EXPECT_CALL(*GetStore(),
RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(),
SavePassword(pending_password().username_value,
pending_password().password_value));
controller()->OnSaveClicked();
} else if (interaction == BubbleDismissalReason::kDeclined &&
update) {
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
controller()->OnNopeUpdateClicked();
} else if (interaction == BubbleDismissalReason::kDeclined &&
!update) {
EXPECT_CALL(*GetStore(),
RemoveSiteStatsImpl(GURL(kSiteOrigin).GetOrigin()));
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
EXPECT_CALL(*delegate(), NeverSavePassword());
controller()->OnNeverForThisSiteClicked();
} else if (interaction == BubbleDismissalReason::kIgnored && update) {
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
} else if (interaction == BubbleDismissalReason::kIgnored &&
!update) {
EXPECT_CALL(*GetStore(), AddSiteStatsImpl(testing::_));
EXPECT_CALL(*delegate(), OnNoInteraction());
EXPECT_CALL(*delegate(), SavePassword(_, _)).Times(0);
EXPECT_CALL(*delegate(), NeverSavePassword()).Times(0);
} else {
NOTREACHED();
}
DestroyModelAndVerifyControllerExpectations();
}
ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(delegate()));
// Flush async calls on password store.
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(testing::Mock::VerifyAndClearExpectations(GetStore()));
// Verify metrics.
const auto& entries =
test_ukm_recorder.GetEntriesByName(UkmEntry::kEntryName);
EXPECT_EQ(1u, entries.size());
for (const auto* entry : entries) {
EXPECT_EQ(kTestSourceId, entry->source_id);
test_ukm_recorder.ExpectEntryMetric(
entry,
update ? UkmEntry::kUpdating_Prompt_ShownName
: UkmEntry::kSaving_Prompt_ShownName,
1);
test_ukm_recorder.ExpectEntryMetric(
entry,
update ? UkmEntry::kUpdating_Prompt_TriggerName
: UkmEntry::kSaving_Prompt_TriggerName,
static_cast<int64_t>(
credential_management_api
? BubbleTrigger::kCredentialManagementAPIAutomatic
: BubbleTrigger::kPasswordManagerSuggestionAutomatic));
test_ukm_recorder.ExpectEntryMetric(
entry,
update ? UkmEntry::kUpdating_Prompt_InteractionName
: UkmEntry::kSaving_Prompt_InteractionName,
static_cast<int64_t>(interaction));
}
}
}
}
}
class SaveUpdateBubbleControllerPasswordRevealingTest
: public SaveUpdateBubbleControllerTest,
public testing::WithParamInterface<
std::tuple<bool /*is manual fallback*/,
bool /*form has autofilled value*/,
bool /*does os support user authentication*/,
PasswordBubbleControllerBase::DisplayReason>> {};
TEST_P(SaveUpdateBubbleControllerPasswordRevealingTest,
EyeIcon_ReauthForPasswordsRevealing) {
bool is_manual_fallback_for_saving = std::get<0>(GetParam());
bool form_has_autofilled_value = std::get<1>(GetParam());
bool does_os_support_user_auth = std::get<2>(GetParam());
PasswordBubbleControllerBase::DisplayReason display_reason =
std::get<3>(GetParam());
// That state is impossible.
if (is_manual_fallback_for_saving &&
(display_reason ==
PasswordBubbleControllerBase::DisplayReason::kAutomatic))
SUCCEED();
SCOPED_TRACE(
testing::Message()
<< "is_manual_fallback_for_saving = " << is_manual_fallback_for_saving
<< " form_has_autofilled_value = " << form_has_autofilled_value
<< " display_reason = "
<< (display_reason ==
PasswordBubbleControllerBase::DisplayReason::kAutomatic
? "AUTOMATIC"
: "USER_ACTION"));
pending_password().form_has_autofilled_value = form_has_autofilled_value;
EXPECT_CALL(*delegate(), ArePasswordsRevealedWhenBubbleIsOpened())
.WillOnce(Return(false));
EXPECT_CALL(*delegate(), BubbleIsManualFallbackForSaving())
.WillRepeatedly(Return(is_manual_fallback_for_saving));
PretendPasswordWaiting(display_reason);
bool reauth_expected = form_has_autofilled_value;
if (!reauth_expected) {
reauth_expected =
!is_manual_fallback_for_saving &&
display_reason ==
PasswordBubbleControllerBase::DisplayReason::kUserAction;
}
EXPECT_EQ(reauth_expected,
controller()->password_revealing_requires_reauth());
// delegate()->AuthenticateUser() is called only when reauth is expected.
EXPECT_CALL(*delegate(), AuthenticateUser())
.Times(reauth_expected)
.WillOnce(Return(!does_os_support_user_auth));
if (reauth_expected) {
EXPECT_EQ(controller()->RevealPasswords(), !does_os_support_user_auth);
} else {
EXPECT_TRUE(controller()->RevealPasswords());
}
}
INSTANTIATE_TEST_SUITE_P(
SaveUpdateBubbleController,
SaveUpdateBubbleControllerPasswordRevealingTest,
testing::Combine(
testing::Bool(),
testing::Bool(),
testing::Bool(),
testing::Values(
PasswordBubbleControllerBase::DisplayReason::kAutomatic,
PasswordBubbleControllerBase::DisplayReason::kUserAction)));
TEST_F(SaveUpdateBubbleControllerTest, EyeIcon_BubbleReopenedAfterAuth) {
// Checks re-authentication is not needed if the bubble is opened right after
// successful authentication.
pending_password().form_has_autofilled_value = true;
// After successful authentication this value is set to true.
EXPECT_CALL(*delegate(), ArePasswordsRevealedWhenBubbleIsOpened())
.WillOnce(Return(true));
PretendPasswordWaiting(
PasswordBubbleControllerBase::DisplayReason::kUserAction);
EXPECT_FALSE(controller()->password_revealing_requires_reauth());
EXPECT_TRUE(controller()->RevealPasswords());
}
TEST_F(SaveUpdateBubbleControllerTest, PasswordsRevealedReported) {
PretendPasswordWaiting();
EXPECT_CALL(*delegate(), OnPasswordsRevealed());
EXPECT_TRUE(controller()->RevealPasswords());
}
TEST_F(SaveUpdateBubbleControllerTest, PasswordsRevealedReportedAfterReauth) {
// The bubble is opened after reauthentication and the passwords are revealed.
pending_password().form_has_autofilled_value = true;
// After successful authentication this value is set to true.
EXPECT_CALL(*delegate(), ArePasswordsRevealedWhenBubbleIsOpened())
.WillOnce(Return(true));
EXPECT_CALL(*delegate(), OnPasswordsRevealed());
PretendPasswordWaiting(
PasswordBubbleControllerBase::DisplayReason::kUserAction);
}
TEST_F(SaveUpdateBubbleControllerTest, DisableEditing) {
EXPECT_CALL(*delegate(), BubbleIsManualFallbackForSaving())
.WillRepeatedly(Return(false));
EXPECT_CALL(*delegate(), GetCredentialSource())
.WillOnce(Return(password_manager::metrics_util::CredentialSourceType::
kCredentialManagementAPI));
PretendPasswordWaiting();
EXPECT_FALSE(controller()->enable_editing());
}
| 42.419306 | 89 | 0.728915 | [
"vector"
] |
7380f875a443234ad7e4fa19ea00db15d2ef3944 | 759 | cpp | C++ | example/constant.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | example/constant.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | example/constant.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | /*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/assert.hpp>
#include <boost/hana/functor.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/tuple.hpp>
using namespace boost::hana;
int main() {
{
//! [value]
auto i = integral_constant<int, 3>; // notice no constexpr
static_assert(value<decltype(i)>() == 3, "");
static_assert(value(i) == 3, "value(i) is always a constant expression!");
//! [value]
}{
//! [value_of]
constexpr auto xs = tuple_c<int, 1, 2, 3, 4, 5>;
constexpr auto vs = transform(xs, value_of);
static_assert(vs == make<Tuple>(1, 2, 3, 4, 5), "");
//! [value_of]
}
}
| 21.083333 | 78 | 0.682477 | [
"transform"
] |
7383f8e045174c804a0f21162211f93e874f27ea | 1,547 | cpp | C++ | src/lib/rendering/2d/fluid.cpp | Fluci/GooBalls | 4b68084303e66af368fd6bbf94aaec0950c9c6e3 | [
"BSD-3-Clause"
] | null | null | null | src/lib/rendering/2d/fluid.cpp | Fluci/GooBalls | 4b68084303e66af368fd6bbf94aaec0950c9c6e3 | [
"BSD-3-Clause"
] | null | null | null | src/lib/rendering/2d/fluid.cpp | Fluci/GooBalls | 4b68084303e66af368fd6bbf94aaec0950c9c6e3 | [
"BSD-3-Clause"
] | null | null | null | #include "fluid.hpp"
namespace GooBalls {
namespace d2 {
namespace Render {
Fluid::Fluid() : m_particles_position(new Coordinates()){
// Empty
}
Fluid::Fluid(std::shared_ptr<Coordinates> ptr, std::shared_ptr<Coordinates> boundary) : m_particles_position(ptr), m_boundary_position(boundary){
// Empty
}
// Fluid
const Fluid::Coordinates& Fluid::particles_position() const {
assert(m_particles_position.get() != nullptr);
return *m_particles_position;
}
Fluid::Coordinates& Fluid::particles_position() {
assert(m_particles_position.get() != nullptr);
return *m_particles_position;
}
const Fluid::Colors& Fluid::particles_color() const {
return m_particles_color;
}
Fluid::Colors& Fluid::particles_color() {
return m_particles_color;
}
const Fluid::Radii& Fluid::particles_radius() const {
return m_particles_radius;
}
Fluid::Radii& Fluid::particles_radius() {
return m_particles_radius;
}
const Fluid::Coordinates& Fluid::boundary_position() const {
assert(m_boundary_position.get() != nullptr);
return *m_boundary_position;
}
Fluid::Coordinates& Fluid::boundary_position() {
assert(m_boundary_position.get() != nullptr);
return *m_boundary_position;
}
const Fluid::Colors& Fluid::boundary_color() const {
return m_boundary_color;
}
Fluid::Colors& Fluid::boundary_color() {
return m_boundary_color;
}
const Fluid::Radii& Fluid::boundary_radius() const {
return m_boundary_radius;
}
Fluid::Radii& Fluid::boundary_radius() {
return m_boundary_radius;
}
} // Render
} // d2
} // GooBalls
| 21.191781 | 146 | 0.735617 | [
"render"
] |
738879e96e77a04dcabb23e611622a08ff52a13f | 13,178 | cpp | C++ | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-08T19:54:51.000Z | 2021-08-08T19:54:51.000Z | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// include required headers
#include "AttachmentsPlugin.h"
#include <MCore/Source/LogManager.h>
#include "../../../../EMStudioSDK/Source/EMStudioManager.h"
#include <QLabel>
#include <QVBoxLayout>
namespace EMStudio
{
// constructor
AttachmentsPlugin::AttachmentsPlugin()
: EMStudio::DockWidgetPlugin()
{
mDialogStack = nullptr;
mSelectCallback = nullptr;
mUnselectCallback = nullptr;
mClearSelectionCallback = nullptr;
mAddAttachmentCallback = nullptr;
mAddDeformableAttachmentCallback = nullptr;
mRemoveAttachmentCallback = nullptr;
mClearAttachmentsCallback = nullptr;
mAdjustActorCallback = nullptr;
mAttachmentNodesWindow = nullptr;
}
// destructor
AttachmentsPlugin::~AttachmentsPlugin()
{
// unregister the command callbacks and get rid of the memory
GetCommandManager()->RemoveCommandCallback(mSelectCallback, false);
GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false);
GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false);
GetCommandManager()->RemoveCommandCallback(mAddAttachmentCallback, false);
GetCommandManager()->RemoveCommandCallback(mAddDeformableAttachmentCallback, false);
GetCommandManager()->RemoveCommandCallback(mRemoveAttachmentCallback, false);
GetCommandManager()->RemoveCommandCallback(mClearAttachmentsCallback, false);
GetCommandManager()->RemoveCommandCallback(mAdjustActorCallback, false);
delete mSelectCallback;
delete mUnselectCallback;
delete mClearSelectionCallback;
delete mAddAttachmentCallback;
delete mAddDeformableAttachmentCallback;
delete mRemoveAttachmentCallback;
delete mClearAttachmentsCallback;
delete mAdjustActorCallback;
}
// clone the log window
EMStudioPlugin* AttachmentsPlugin::Clone()
{
return new AttachmentsPlugin();
}
// init after the parent dock window has been created
bool AttachmentsPlugin::Init()
{
//LogInfo("Initializing attachments window.");
// create the dialog stack
assert(mDialogStack == nullptr);
mDialogStack = new MysticQt::DialogStack(mDock);
mDock->setWidget(mDialogStack);
// create the attachments window
mAttachmentsWindow = new AttachmentsWindow(mDialogStack);
mAttachmentsWindow->Init();
mDialogStack->Add(mAttachmentsWindow, "Selected Actor Instance", false, true, true, false);
// create the attachment hierarchy window
mAttachmentsHierarchyWindow = new AttachmentsHierarchyWindow(mDialogStack);
mAttachmentsHierarchyWindow->Init();
mDialogStack->Add(mAttachmentsHierarchyWindow, "Hierarchy", false, true, true, false);
// create the attachment nodes window
mAttachmentNodesWindow = new AttachmentNodesWindow(mDialogStack);
mDialogStack->Add(mAttachmentNodesWindow, "Attachment Nodes", false, true);
// create and register the command callbacks only (only execute this code once for all plugins)
mSelectCallback = new CommandSelectCallback(false);
mUnselectCallback = new CommandUnselectCallback(false);
mClearSelectionCallback = new CommandClearSelectionCallback(false);
mAddAttachmentCallback = new CommandAddAttachmentCallback(false);
mAddDeformableAttachmentCallback = new CommandAddDeformableAttachmentCallback(false);
mRemoveAttachmentCallback = new CommandRemoveAttachmentCallback(false);
mClearAttachmentsCallback = new CommandClearAttachmentsCallback(false);
mAdjustActorCallback = new CommandAdjustActorCallback(false);
mRemoveActorInstanceCallback = new CommandRemoveActorInstanceCallback(false);
GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback);
GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback);
GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback);
GetCommandManager()->RegisterCommandCallback("AddAttachment", mAddAttachmentCallback);
GetCommandManager()->RegisterCommandCallback("AddDeformableAttachment", mAddDeformableAttachmentCallback);
GetCommandManager()->RegisterCommandCallback("RemoveAttachment", mRemoveAttachmentCallback);
GetCommandManager()->RegisterCommandCallback("ClearAttachments", mClearAttachmentsCallback);
GetCommandManager()->RegisterCommandCallback("AdjustActor", mAdjustActorCallback);
GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", mRemoveActorInstanceCallback);
// reinit the dialog
ReInit();
// connect the window activation signal to refresh if reactivated
connect(mDock, &QDockWidget::visibilityChanged, this, &AttachmentsPlugin::WindowReInit);
return true;
}
// function to reinit the window
void AttachmentsPlugin::ReInit()
{
mAttachmentsWindow->ReInit();
mAttachmentsHierarchyWindow->ReInit();
// get the current actor
const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection();
EMotionFX::ActorInstance* actorInstance = selection.GetSingleActorInstance();
EMotionFX::Actor* actor = nullptr;
// disable controls if no actor instance is selected
if (actorInstance)
{
actor = actorInstance->GetActor();
}
// set the actor of the attachment nodes window
mAttachmentNodesWindow->SetActor(actor);
}
// reinit the window when it gets activated
void AttachmentsPlugin::WindowReInit(bool visible)
{
if (visible)
{
ReInit();
}
}
//-----------------------------------------------------------------------------------------
// Command callbacks
//-----------------------------------------------------------------------------------------
bool ReInitAttachmentsPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AttachmentsPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
AttachmentsPlugin* attachmentsPlugin = (AttachmentsPlugin*)plugin;
// is the plugin visible? only update it if it is visible
if (attachmentsPlugin->GetDockWidget()->visibleRegion().isEmpty() == false)
{
attachmentsPlugin->ReInit();
}
return true;
}
bool AttachmentSelectedAttachmentsPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AttachmentsPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
AttachmentsPlugin* attachmentsPlugin = (AttachmentsPlugin*)plugin;
// is the plugin visible? only update it if it is visible
if (attachmentsPlugin->GetDockWidget()->visibleRegion().isEmpty() == false)
{
AttachmentsWindow* attachmentsWindow = attachmentsPlugin->GetAttachmentsWindow();
if (attachmentsWindow->GetIsWaitingForAttachment())
{
attachmentsWindow->OnAttachmentSelected();
}
else
{
attachmentsPlugin->ReInit();
}
}
return true;
}
bool AttachmentsPlugin::CommandSelectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandSelectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandUnselectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandUnselectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandClearSelectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandClearSelectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return AttachmentSelectedAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandAddAttachmentCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandAddAttachmentCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandAddDeformableAttachmentCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandAddDeformableAttachmentCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandRemoveAttachmentCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandRemoveAttachmentCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandClearAttachmentsCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandClearAttachmentsCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandRemoveActorInstanceCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandRemoveActorInstanceCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitAttachmentsPlugin(); }
bool AttachmentsPlugin::CommandAdjustActorCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return ReInitAttachmentsPlugin();
}
bool AttachmentsPlugin::CommandAdjustActorCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false)
{
return true;
}
return ReInitAttachmentsPlugin();
}
} // namespace EMStudio
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/moc_AttachmentsPlugin.cpp>
| 45.441379 | 227 | 0.680832 | [
"3d"
] |
738c611d55646043b24f8ce2628efa7739dd8fca | 5,945 | cc | C++ | ash/login/ui/lock_screen.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/login/ui/lock_screen.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/login/ui/lock_screen.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 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 "ash/login/ui/lock_screen.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "ash/login/ui/lock_contents_view.h"
#include "ash/login/ui/lock_debug_view.h"
#include "ash/login/ui/login_data_dispatcher.h"
#include "ash/login/ui/login_detachable_base_model.h"
#include "ash/public/cpp/lock_screen_widget_factory.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/shelf/login_shelf_view.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/wallpaper/wallpaper_controller_impl.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "chromeos/constants/chromeos_switches.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/capture_controller.h"
namespace ash {
namespace {
// Global lock screen instance. There can only ever be on lock screen at a
// time.
LockScreen* instance_ = nullptr;
} // namespace
LockScreen::TestApi::TestApi(LockScreen* lock_screen)
: lock_screen_(lock_screen) {}
LockScreen::TestApi::~TestApi() = default;
LockContentsView* LockScreen::TestApi::contents_view() const {
return lock_screen_->contents_view_;
}
void LockScreen::TestApi::AddOnShownCallback(base::OnceClosure on_shown) {
if (lock_screen_->is_shown_) {
std::move(on_shown).Run();
return;
}
lock_screen_->on_shown_callbacks_.push_back(std::move(on_shown));
}
LockScreen::LockScreen(ScreenType type) : type_(type) {
tray_action_observer_.Add(Shell::Get()->tray_action());
saved_clipboard_ = ui::Clipboard::TakeForCurrentThread();
}
LockScreen::~LockScreen() {
widget_.reset();
ui::Clipboard::DestroyClipboardForCurrentThread();
if (saved_clipboard_)
ui::Clipboard::SetClipboardForCurrentThread(std::move(saved_clipboard_));
}
// static
LockScreen* LockScreen::Get() {
CHECK(instance_);
return instance_;
}
// static
void LockScreen::Show(ScreenType type) {
CHECK(!instance_);
// Capture should be released when locked.
::wm::CaptureController::Get()->SetCapture(nullptr);
instance_ = new LockScreen(type);
aura::Window* parent = nullptr;
if (Shell::HasInstance()) {
parent = Shell::GetContainer(Shell::GetPrimaryRootWindow(),
kShellWindowId_LockScreenContainer);
}
instance_->widget_ = CreateLockScreenWidget(parent);
instance_->widget_->SetBounds(
display::Screen::GetScreen()->GetPrimaryDisplay().bounds());
auto initial_note_action_state =
Shell::Get()->tray_action()->GetLockScreenNoteState();
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kShowLoginDevOverlay)) {
auto debug_view =
std::make_unique<LockDebugView>(initial_note_action_state, type);
instance_->contents_view_ = debug_view->lock();
instance_->widget_->SetContentsView(std::move(debug_view));
} else {
auto detachable_base_model = LoginDetachableBaseModel::Create(
Shell::Get()->detachable_base_handler());
instance_->contents_view_ =
instance_->widget_->SetContentsView(std::make_unique<LockContentsView>(
initial_note_action_state, type,
Shell::Get()->login_screen_controller()->data_dispatcher(),
std::move(detachable_base_model)));
}
// Postpone showing the screen after the animation of the first wallpaper
// completes, to make the transition smooth. The callback will be dispatched
// immediately if the animation is already complete (e.g. kLock).
Shell::Get()->wallpaper_controller()->AddFirstWallpaperAnimationEndCallback(
base::BindOnce(&LockScreen::ShowWidgetUponWallpaperReady),
instance_->widget_->GetNativeView());
}
// static
bool LockScreen::HasInstance() {
return !!instance_;
}
void LockScreen::Destroy() {
LoginScreenController::AuthenticationStage authentication_stage =
Shell::Get()->login_screen_controller()->authentication_stage();
base::debug::Alias(&authentication_stage);
if (Shell::Get()->login_screen_controller()->authentication_stage() !=
authentication_stage) {
LOG(FATAL) << "Unexpected authentication stage "
<< static_cast<int>(authentication_stage);
}
CHECK_EQ(instance_, this);
Shell::Get()->login_screen_controller()->data_dispatcher()->RemoveObserver(
Shelf::ForWindow(Shell::GetPrimaryRootWindow())
->shelf_widget()
->login_shelf_view());
delete instance_;
instance_ = nullptr;
}
void LockScreen::FocusNextUser() {
contents_view_->FocusNextUser();
}
void LockScreen::FocusPreviousUser() {
contents_view_->FocusPreviousUser();
}
void LockScreen::ShowParentAccessDialog() {
contents_view_->ShowParentAccessDialog();
}
void LockScreen::OnLockScreenNoteStateChanged(mojom::TrayActionState state) {
Shell::Get()
->login_screen_controller()
->data_dispatcher()
->SetLockScreenNoteState(state);
}
void LockScreen::OnSessionStateChanged(session_manager::SessionState state) {
if (type_ == ScreenType::kLogin &&
state == session_manager::SessionState::ACTIVE) {
Destroy();
}
}
void LockScreen::OnLockStateChanged(bool locked) {
if (type_ != ScreenType::kLock)
return;
if (!locked)
Destroy();
}
void LockScreen::OnChromeTerminating() {
Destroy();
}
// static
void LockScreen::ShowWidgetUponWallpaperReady() {
// |instance_| may already be destroyed in tests.
if (!instance_ || instance_->is_shown_)
return;
instance_->is_shown_ = true;
instance_->widget_->Show();
std::vector<base::OnceClosure> on_shown_callbacks;
swap(instance_->on_shown_callbacks_, on_shown_callbacks);
for (auto& callback : on_shown_callbacks)
std::move(callback).Run();
}
} // namespace ash
| 30.177665 | 79 | 0.72582 | [
"vector"
] |
738dce79336bb3d1bab57e559331e9c67a9a62fb | 324 | hpp | C++ | ListAnimals.hpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | ListAnimals.hpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | ListAnimals.hpp | wolframtheta/cell | 71c14c391c00b2a125621a5134b5440a48c39d98 | [
"MIT"
] | null | null | null | #ifndef LISTANIMALS_HPP
#define LISTANIMALS_HPP
#include "Animal.hpp"
class ListAnimals {
public:
ListAnimals();
void addAnimal(Animal animal);
vector<Animal> getListAnimals();
Animal getAnimalByID(string ID);
Animal getAnimal(int i);
void print();
int size();
vector<Animal> listAnimals;
private:
};
#endif
| 12.96 | 33 | 0.737654 | [
"vector"
] |
7390af9c05ab0a59673e91df449913974f24ff72 | 1,037 | cpp | C++ | src/liquid/tags/capture.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | 4 | 2018-02-01T04:46:37.000Z | 2021-01-13T18:20:38.000Z | src/liquid/tags/capture.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | null | null | null | src/liquid/tags/capture.cpp | kainjow/Jeqyll | 3a234a345087c5d3366b1eda98d3ed92d3888101 | [
"MIT"
] | 3 | 2017-03-27T19:12:56.000Z | 2021-03-23T04:24:51.000Z | #include "capture.hpp"
#include "parser.hpp"
#include "context.hpp"
#include "template.hpp"
Liquid::CaptureTag::CaptureTag(const Context& context, const StringRef& tagName, const StringRef& markup)
: BlockTag(context, tagName, markup)
{
Parser parser(markup);
to_ = parser.consume(Token::Type::Id);
(void)parser.consume(Token::Type::EndOfString);
}
Liquid::String Liquid::CaptureTag::render(Context& context)
{
const String output = BlockTag::render(context);
context.data().insert(to_.toString(), output);
return "";
}
#ifdef TESTS
#include "tests.hpp"
TEST_CASE("Liquid::Capture") {
SECTION("Capture") {
CHECK_TEMPLATE_RESULT("{% capture my_variable %}I am being captured.{% endcapture %}{{ my_variable }}", "I am being captured.");
CHECK_TEMPLATE_DATA_RESULT(
"{{ var2 }}{% capture var2 %}{{ var }} foo {% endcapture %}{{ var2 }}{{ var2 }}",
"content foo content foo ",
(Liquid::Data::Hash{{"var", "content"}})
);
}
}
#endif
| 25.925 | 136 | 0.633558 | [
"render"
] |
739a7e523f4c3b3a175179e384e21fc9026a6d21 | 2,268 | cpp | C++ | src/app/CreateGlobalMatchPairs.cpp | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | src/app/CreateGlobalMatchPairs.cpp | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | src/app/CreateGlobalMatchPairs.cpp | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <math.h>
#include <string>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]) {
string keyList = argv[1];
string resultPath = argv[2];
string numListsStr = argv[3];
int numLists = atoi( numListsStr.c_str() );
ifstream keyListFile( keyList.c_str() );
if(!keyListFile.is_open()) {
cout << "\n COuld not open key list file" ;
return -1;
}
vector<int> numFeatures;
string line;
while(getline( keyListFile, line)) {
ifstream keyFile(line.c_str());
if(!keyFile.is_open()) {
cout << "\nCould not open file";
return -1;
}
getline(keyFile, line);
istringstream str(line);
int nFeat;
str >> nFeat;
numFeatures.push_back(nFeat);
keyFile.close();
}
int numImages = numFeatures.size();
int numPairs = numImages*(numImages-1)/2;
int numPairsPerList = floor(numPairs/numLists);
int currList = 0;
vector< pair<int, int> > pairs;
for(int i=0; i < numFeatures.size(); i++) {
for(int j=0; j < i; j++) {
if( numFeatures[i] < numFeatures[j] ) {
pairs.push_back(make_pair(i, j));
} else {
pairs.push_back(make_pair(j, i));
}
}
}
sort( pairs.begin(), pairs.end());
cout << "\nWriting lists " << numLists;
for(int i=0; i < numLists; i++) {
char filename[1000];
sprintf(filename,"%s/initial-pairs-%d.txt",resultPath.c_str(),i);
ofstream pairsOut( filename, std::ofstream::out );
if( !pairsOut.is_open() ) {
cout << "\nError opening pairs output file!";
}
int start = i*numPairsPerList;
int end = (i+1)*numPairsPerList;
if(i == numLists - 1) {
end = numPairs;
}
// cout << endl << i << " " << numLists << " " << start << " " << end << " " << numPairs << endl;
for(int j = start; j < end; j++) {
pairsOut << pairs[j].first << " " << pairs[j].second << "\n";
}
pairsOut.close();
}
return 0;
}
| 27 | 104 | 0.526896 | [
"vector"
] |
739cc45a4eced5aaaf400991f631332afcc1ef91 | 8,998 | cpp | C++ | src/lib/geogram/voronoi/generic_RVD_polygon.cpp | jdumas/geogram-1 | fd696441132d3d1dcab9ec4a02d12786255e354f | [
"BSD-3-Clause"
] | 348 | 2022-02-23T15:58:43.000Z | 2022-03-31T06:38:32.000Z | src/lib/geogram/voronoi/generic_RVD_polygon.cpp | jdumas/geogram-1 | fd696441132d3d1dcab9ec4a02d12786255e354f | [
"BSD-3-Clause"
] | 4 | 2022-02-28T02:30:40.000Z | 2022-03-11T12:32:32.000Z | src/lib/geogram/voronoi/generic_RVD_polygon.cpp | jdumas/geogram-1 | fd696441132d3d1dcab9ec4a02d12786255e354f | [
"BSD-3-Clause"
] | 22 | 2022-02-23T15:45:06.000Z | 2022-03-25T20:25:29.000Z | /*
* Copyright (c) 2012-2014, Bruno Levy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ALICE Project-Team nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* Bruno.Levy@inria.fr
* http://www.loria.fr/~levy
*
* ALICE Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
*/
#include <geogram/voronoi/generic_RVD_polygon.h>
#include <geogram/numerics/predicates.h>
#include <algorithm>
namespace GEOGen {
void Polygon::initialize_from_mesh_facet(
const Mesh* mesh, index_t facet, bool symbolic,
const GEO::Attribute<double>& vertex_weight
) {
clear();
if(symbolic) {
// Copy facet
for(index_t c = mesh->facets.corners_begin(facet);
c < mesh->facets.corners_end(facet); c++
) {
index_t v = mesh->facet_corners.vertex(c);
index_t adjacent_facet = mesh->facet_corners.adjacent_facet(c);
Vertex* vx = add_vertex(
Vertex(
mesh->vertices.point_ptr(v),
vertex_weight.is_bound() ? vertex_weight[v] : 1.0,
signed_index_t(adjacent_facet)
)
);
vx->sym().set_boundary_vertex(v);
}
// Initialize symbolic information
for(index_t i1 = 0; i1 < nb_vertices(); i1++) {
index_t i2 = next_vertex(i1);
Vertex& v1 = vertex(i1);
Vertex& v2 = vertex(i2);
// Note: Here we compute v2.sym()
// and we do not touch v1.sym()
v2.sym().add_boundary_facet(facet);
if(v1.adjacent_facet() >= 0) {
v2.sym().add_boundary_facet(
index_t(v1.adjacent_facet())
);
} else {
// "Virtual" boundary facet:
// indicates edge (i1,i2 = i1 \oplus 1)
// We no longer need them, except for
// indicating vertex sym. type.
v2.sym().add_boundary_facet(
mesh->facets.nb() + i1
);
}
// Note: we continue to compute v2.sym()
// and we do not touch v1.sym() (it looks
// like a copy-paste bug but it is correct !)
if(v2.adjacent_facet() >= 0) {
v2.sym().add_boundary_facet(
index_t(v2.adjacent_facet())
);
} else {
// "Virtual" boundary facet:
// indicates edge (i1,i2 = i1 \oplus 1)
// We no longer need them, except for
// indicating vertex sym. type.
v2.sym().add_boundary_facet(
mesh->facets.nb() + i2
);
}
}
#ifdef GEO_DEBUG
// Sanity check: make sure that the facet is not
// adjacent to the same facet twice.
index_t n = mesh->facets.nb_vertices(facet);
signed_index_t* adj = (signed_index_t*) alloca(
sizeof(signed_index_t) * n
);
GEO::Memory::clear(adj, sizeof(signed_index_t) * n);
index_t i = 0;
for(index_t c = mesh->facets.corners_begin(facet);
c < mesh->facets.corners_end(facet); ++c
) {
adj[i] = signed_index_t(mesh->facet_corners.adjacent_facet(c));
++i;
}
std::sort(adj, adj + n);
for(i = 0; i < n - 1; ++i) {
// If this assertion fails, then the mesh probably has a degree2 vertex
// (use remove_degree2_vertices() in mesh_preprocessing.h)
geo_debug_assert(
adj[i] == -1 || adj[i] != adj[i + 1]
);
}
#endif
} else {
// We are not in symbolic mode,
// we just gather the vertices, weights and adjacencies.
for(index_t c = mesh->facets.corners_begin(facet);
c < mesh->facets.corners_end(facet); c++
) {
index_t v = mesh->facet_corners.vertex(c);
index_t adjacent_facet = mesh->facet_corners.adjacent_facet(c);
add_vertex(
Vertex(
mesh->vertices.point_ptr(v),
vertex_weight.is_bound() ? vertex_weight[v] : 1.0,
signed_index_t(adjacent_facet)
)
);
}
}
}
Sign Polygon::side_exact(
const Mesh* mesh, const Delaunay* delaunay,
const Vertex& q, const double* pi, const double* pj, coord_index_t dim
) {
switch(q.sym().nb_boundary_facets()) {
case 0:
// All the points that we manipulate are supposed to
// belong to the restricted Voronoi diagram, therefore
// they belong to the surface, and are at least on one
// facet of the surface.
geo_assert_not_reached;
case 1:
{
// The point q is the intersection between
// a facet (f0,f1,f2) of the surface and two
// bisectors [pi b0] and [pi b1].
index_t b0 = q.sym().bisector(0);
index_t b1 = q.sym().bisector(1);
index_t f = q.sym().boundary_facet(0);
index_t if0 = mesh->facets.vertex(f,0);
index_t if1 = mesh->facets.vertex(f,1);
index_t if2 = mesh->facets.vertex(f,2);
const double* f0 = mesh->vertices.point_ptr(if0);
const double* f1 = mesh->vertices.point_ptr(if1);
const double* f2 = mesh->vertices.point_ptr(if2);
return GEO::PCK::side3_SOS(
pi, delaunay->vertex_ptr(b0), delaunay->vertex_ptr(b1), pj,
f0, f1, f2, dim
);
}
case 2:
{
// The point q is the intersection between
// two facets of the surface (i.e. an edge [e0 e1])
// and one bisector [pi b0].
// i.e. it's a vertex of the surface.
index_t b0 = q.sym().bisector(0);
index_t e0, e1;
q.sym().get_boundary_edge(e0, e1);
return GEO::PCK::side2_SOS(
pi, delaunay->vertex_ptr(b0), pj,
mesh->vertices.point_ptr(e0),
mesh->vertices.point_ptr(e1), dim
);
}
case 3:
{
// The point q is the intersection between
// three facets of the surface
// (i.e. a vertex v0 of the surface).
index_t v0 = q.sym().get_boundary_vertex();
return GEO::PCK::side1_SOS(
pi, pj, mesh->vertices.point_ptr(v0), dim
);
}
}
geo_assert_not_reached;
}
}
| 39.991111 | 87 | 0.522338 | [
"mesh"
] |
739ffa54cabe0581a97eb3c532bed406e5e2609b | 3,078 | cpp | C++ | examples/logistic_regression.cpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | 1 | 2019-01-23T02:10:10.000Z | 2019-01-23T02:10:10.000Z | examples/logistic_regression.cpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | examples/logistic_regression.cpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 Husky Team
//
// 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.
//
// Parameters
//
// alpha
// type: double
// info: (a.k.a learning rate)
// The step size of gradient descent. You may use 0.01 if not sure .
//
// train
// type: string
// info: The path of training data in hadoop
//
// test
// type: string
// info: The path of testing data in hadoop
//
// n_iter
// type: int
// info: (a.k.a number of epoch)
// How many time the entire training data will be went through
//
// Configuration example:
// train:/datasets/classification/a9
// test:/datasets/classification/a9t
// n_iter:50
// alpha:0.5
#include <string>
#include <vector>
#include "core/engine.hpp"
#include "lib/ml/data_loader.hpp"
#include "lib/ml/fgd.hpp"
#include "lib/ml/logistic_regression.hpp"
using husky::lib::ml::SparseFeatureLabel;
using husky::lib::ml::ParameterBucket;
void logistic_regression() {
auto & train_set = husky::ObjListFactory::create_objlist<SparseFeatureLabel>("train_set");
auto & test_set = husky::ObjListFactory::create_objlist<SparseFeatureLabel>("test_set");
// load data
husky::lib::ml::DataLoader<SparseFeatureLabel> data_loader(husky::lib::ml::kLIBSVMFormat);
data_loader.load_info(husky::Context::get_param("train"), train_set);
data_loader.load_info(husky::Context::get_param("test"), test_set);
int num_features = data_loader.get_num_feature();
double alpha = std::stod(husky::Context::get_param("alpha"));
int num_iter = std::stoi(husky::Context::get_param("n_iter"));
// initialize logistic regression model
husky::lib::ml::LogisticRegression<SparseFeatureLabel, ParameterBucket<double>> lr(num_features);
lr.report_per_round = true; // report training error per round
// train the model
lr.train<husky::lib::ml::FGD<SparseFeatureLabel, ParameterBucket<double>>>(train_set, num_iter, alpha);
// estimate generalization error
double test_error = lr.avg_error(test_set);
if (husky::Context::get_global_tid() == 0) {
// lr.present_param();
// validation
husky::base::log_msg("Error on testing set: " + std::to_string(test_error));
}
}
int main(int argc, char** argv) {
std::vector<std::string> args;
args.push_back("hdfs_namenode");
args.push_back("hdfs_namenode_port");
args.push_back("train");
args.push_back("test");
args.push_back("n_iter");
args.push_back("alpha");
if (husky::init_with_args(argc, argv, args)) {
husky::run_job(logistic_regression);
return 0;
}
return 1;
}
| 32.4 | 107 | 0.69883 | [
"vector",
"model"
] |
73a01dbdf8a405bc33e15f046b0fb2bc523ec861 | 3,906 | cpp | C++ | src/ui/ui.cpp | Toxe/video-trimmer | 09f00d7a09eeae8a3910a5ec63bfd966b411aef0 | [
"MIT"
] | null | null | null | src/ui/ui.cpp | Toxe/video-trimmer | 09f00d7a09eeae8a3910a5ec63bfd966b411aef0 | [
"MIT"
] | null | null | null | src/ui/ui.cpp | Toxe/video-trimmer | 09f00d7a09eeae8a3910a5ec63bfd966b411aef0 | [
"MIT"
] | null | null | null | #include "ui.h"
#include <fmt/core.h>
#include "colors.h"
#include "event_handler/event_handler.h"
const float left_pane_width = 500.0f;
const float additional_info_pane_height = 400.0f;
const float playback_controls_pane_height = 100.0f;
const float trim_controls_pane_height = 150.0f;
void UI::render()
{
render_main_window();
render_help_window();
// ImGui::ShowMetricsWindow();
}
void UI::render_main_window()
{
ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f));
ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize);
ImGui::Begin(main_window_title_, nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoBackground);
setup_left_pane(left_pane_width);
ImGui::SameLine();
setup_right_pane();
ImGui::End();
}
void UI::render_help_window()
{
if (show_help_) {
ImGui::SetNextWindowPos(ImVec2(20 + 20 + main_window_size_.x, 20), ImGuiCond_FirstUseEver);
ImGui::Begin(help_window_title_, &show_help_, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
ImGui::TextColored(UserInterface::Colors::light_blue, " F1");
ImGui::SameLine();
ImGui::Text("show/hide help");
ImGui::TextColored(UserInterface::Colors::light_blue, " ESC");
ImGui::SameLine();
ImGui::Text("quit");
if (ImGui::Button("Close"))
event_handler_->handle_event(Event::ToggleHelp);
ImGui::End();
}
}
void UI::help(const std::string& text)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered()) {
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(text.c_str());
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
void UI::setup_left_pane(const float pane_width)
{
ImGui::BeginChild("left pane", ImVec2(pane_width, 0), false, ImGuiWindowFlags_None);
const float files_pane_height = ImGui::GetWindowSize().y - additional_info_pane_height - ImGui::GetStyle().ItemSpacing.y;
setup_files_view(files_pane_height);
setup_additional_info_view(additional_info_pane_height);
ImGui::EndChild();
}
void UI::setup_right_pane()
{
ImGui::BeginChild("right pane", ImVec2(0, 0), false, ImGuiWindowFlags_None);
const float video_pane_height = ImGui::GetWindowSize().y - playback_controls_pane_height - trim_controls_pane_height - 2.0f * ImGui::GetStyle().ItemSpacing.y;
setup_video_view(video_pane_height);
setup_playback_controls_pane(playback_controls_pane_height);
setup_trim_controls_pane(trim_controls_pane_height);
ImGui::EndChild();
}
void UI::setup_files_view(const float pane_height)
{
ImGui::BeginChild("files", ImVec2(0, pane_height), true, ImGuiWindowFlags_None);
ImGui::EndChild();
}
void UI::setup_additional_info_view(const float pane_height)
{
ImGui::BeginChild("additional info", ImVec2(0, pane_height), true, ImGuiWindowFlags_None);
ImGui::EndChild();
}
void UI::setup_video_view(const float pane_height)
{
ImGui::BeginChild("video", ImVec2(0, pane_height), false, ImGuiWindowFlags_None);
video_view_position_ = ImGui::GetCursorScreenPos();
video_view_size_ = ImGui::GetWindowSize();
ImGui::EndChild();
}
void UI::setup_playback_controls_pane(const float pane_height)
{
ImGui::BeginChild("playback controls", ImVec2(0, pane_height), true, ImGuiWindowFlags_None);
ImGui::EndChild();
}
void UI::setup_trim_controls_pane(const float pane_height)
{
ImGui::BeginChild("trim controls", ImVec2(0, pane_height), true, ImGuiWindowFlags_None);
ImGui::EndChild();
}
ImagePosition UI::video_view_position() const
{
return {static_cast<int>(video_view_position_.x), static_cast<int>(video_view_position_.y)};
}
ImageSize UI::video_view_size() const
{
return {static_cast<int>(video_view_size_.x), static_cast<int>(video_view_size_.y)};
}
| 28.510949 | 162 | 0.718382 | [
"render"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.