hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count 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 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d323d783baec2c138768d7e519d4e7556b8201c | 5,302 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #include "ag_AguilaGuiTest.h"
// External headers.
#include <boost/filesystem.hpp>
// Project headers.
#include "dal_Exception.h"
// Module headers.
#include "ag_Aguila.h"
#include "ag_Viewer.h"
/*!
\file
This file contains the implementation of the AguilaGuiTest class.
*/
namespace ag {
//------------------------------------------------------------------------------
// DEFINITION OF STATIC AGUILAGUITEST MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF AGUILAGUITEST MEMBERS
//------------------------------------------------------------------------------
//! ctor
AguilaGuiTest::AguilaGuiTest()
:
// Cursor Window
// CursorView
// Data source table
d_nrVisualisationsPerCursorDialog(3),
// Map window
// Map
// Legend view
// Map view
d_nrVisualisationsPerMapWindow(4),
// Plot window
// Plot
// Legend view
// Plot view
d_nrVisualisationsPerTimePlotWindow(4),
d_nrVisualisationsPerAnimationDialog(1)
{
}
void AguilaGuiTest::initTestCase()
{
}
void AguilaGuiTest::cleanupTestCase()
{
}
void AguilaGuiTest::init()
{
}
void AguilaGuiTest::cleanup()
{
// Viewer::resetInstance();
}
void AguilaGuiTest::testNotExisting(
std::string const& name)
{
int argc = 2;
char const* argv[2] = { "aguila", name.c_str() };
QVERIFY(!boost::filesystem::exists(name));
Aguila aguila(argc, const_cast<char**>(argv));
bool rightExceptionCaught;
try {
rightExceptionCaught = false;
aguila.setup();
}
catch(dal::Exception const& exception) {
rightExceptionCaught = true;
QCOMPARE(exception.message(),
std::string("Data source " + name + ":\ncannot be opened"));
}
catch(...) {
}
QVERIFY(rightExceptionCaught);
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), static_cast<size_t>(0));
QVERIFY(!boost::filesystem::exists(name));
/// Viewer::resetInstance();
}
void AguilaGuiTest::testNotExisting()
{
testNotExisting("DoesNotExist.map");
testNotExisting("DoesNotExist");
}
void AguilaGuiTest::testRasterMinMaxEqual()
{
int argc = 2;
char const* argv[2] = { "aguila",
"MinMaxEqual.map" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), static_cast<size_t>(
/* d_nrVisualisationsPerCursorDialog + */
d_nrVisualisationsPerMapWindow));
}
void AguilaGuiTest::testDataset1()
{
{
int argc = 2;
char const* argv[2] = { "aguila",
"dataset1/aap/scalar_10" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
d_nrVisualisationsPerMapWindow));
}
{
int argc = 4;
char const* argv[4] = { "aguila",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"scalar_10" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
3 * d_nrVisualisationsPerMapWindow));
}
{
int argc = 6;
char const* argv[6] = { "aguila",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"--timesteps", "[1, 30]",
"scalar" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
3 * d_nrVisualisationsPerMapWindow // +
/* d_nrVisualisationsPerAnimationDialog */));
}
{
int argc = 8;
char const* argv[8] = { "aguila",
"--multi", "2x2",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"--timesteps", "[1, 30]",
"scalar" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
// MultiMap window
// MultiMap
// Legend view
// MultiMap view
// 4 * Map view
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */ 8 // +
/* d_nrVisualisationsPerAnimationDialog */));
}
}
void AguilaGuiTest::testMultipleViews()
{
// {
// int argc = 7;
// char const* argv[7] = { "aguila",
// "--timesteps", "[1, 250]",
// "--timeGraph", "dem",
// "--mapView", "dem"};
// Aguila aguila(argc, const_cast<char**>(argv));
// aguila.setup();
// Viewer const& viewer(aguila.viewer());
// // MultiMap window
// // MultiMap
// // Legend view
// // MultiMap view
// // 4 * Map view
// QCOMPARE(viewer.nrVisualisations(), size_t(
// d_nrVisualisationsPerCursorDialog +
// d_nrVisualisationsPerAnimationDialog +
// d_nrVisualisationsPerTimePlotWindow +
// d_nrVisualisationsPerMapWindow));
// }
}
} // namespace ag
| 22.277311 | 80 | 0.577707 |
3d35c3c9a7b42ea5e888bed29e718ccd70f36423 | 7,306 | hpp | C++ | include/argot/prov/switch_/detail/generate_switch_provision.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 49 | 2018-05-09T23:17:45.000Z | 2021-07-21T10:05:19.000Z | include/argot/prov/switch_/detail/generate_switch_provision.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | null | null | null | include/argot/prov/switch_/detail/generate_switch_provision.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 2 | 2019-08-04T03:51:36.000Z | 2020-12-28T06:53:29.000Z | /*==============================================================================
Copyright (c) 2017, 2018 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
#define ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
#ifndef ARGOT_PREPROCESSING_MODE
#include <argot/concepts/switch_body_default.hpp>
#include <argot/detail/unreachable.hpp>
#include <argot/detail/forward.hpp>
#include <argot/gen/is_modeled.hpp>
#include <argot/prov/switch_/detail/config.hpp>
#include <argot/prov/switch_/detail/switch_impl_fwd.hpp>
#include <argot/prov/switch_/detail/switch_provision_base.hpp>
#include <argot/prov/switch_/detail/switch_provision_fwd.hpp>
#include <argot/switch_traits/argument_list_kinds_of_body_destructive.hpp>
#include <argot/switch_traits/argument_list_kinds_of_body_persistent.hpp>
#include <argot/switch_traits/case_value_for_type_at.hpp>
#include <argot/switch_traits/destructive_provide_case.hpp>
#include <argot/switch_traits/destructive_provide_default.hpp>
#include <argot/switch_traits/num_cases.hpp>
#include <argot/switch_traits/persistent_provide_case.hpp>
#include <argot/switch_traits/persistent_provide_default.hpp>
#include <argot/unreachable_function.hpp>
#include <boost/preprocessor/arithmetic/dec.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <cstddef>
namespace argot::prov::switch_detail {
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID
////////////////////////////////////////////////////////////////////////////////
// Begin generation of switch_provision specializations... //
////////////////////////////////////////////////////////////////////////////////
#define BOOST_PP_ITERATION_PARAMS_1 \
( 3, ( 1, ARGOT_MAX_PREPROCESSED_SWITCH_CASES \
, <argot/prov/switch_/detail/generation/switch_generation.hpp> \
) \
)
#include BOOST_PP_ITERATE()
////////////////////////////////////////////////////////////////////////////////
// End generation of switch_provision specializations. //
////////////////////////////////////////////////////////////////////////////////
// This default definition handles situations where there are more cases than
// can fit in a single, preprocessed switch-statement. An instantation
// represents either the first or an intermediate link in a chain of
// switch-statements whose maximum number of cases is
// ARGOT_MAX_PREPROCESSED_SWITCH_CASES.
template< std::size_t NumRemainingCases, provision_kind Kind >
struct switch_provision
: switch_provision_base< Kind >
{
using base_t = switch_provision_base< Kind >;
template< class T >
using with_qualifiers_t = typename base_t::template with_qualifiers_t< T >;
template< auto V >
using provide_case_t = typename base_t::template provide_case_t< V >;
using provide_default_t = typename base_t::provide_default_t;
template< class Body, class ValueType >
using argument_list_kinds_of_body_t
= typename base_t
::template argument_list_kinds_of_body_t< Body, ValueType >;
/* TODO(mattcalabrese) Constrain*/
template< class ValueType, class... Bodies, class Receiver >
static constexpr decltype( auto ) run
( with_qualifiers_t
< prov::switch_detail::switch_impl< ValueType, Bodies... > > self
, Receiver&& receiver
)
{
using body_t
= typename prov::switch_detail::switch_impl< ValueType, Bodies... >
::body_t;
using qualified_body_t = with_qualifiers_t< body_t >;
std::size_t constexpr index_offset
= switch_traits::num_cases_v< body_t > - NumRemainingCases;
switch( self.value )
{
////////////////////////////////////////////////////////////////////////////////
// Begin generation of cases... //
////////////////////////////////////////////////////////////////////////////////
#define BOOST_PP_ITERATION_PARAMS_1 \
( 3, ( 0, ARGOT_MAX_PREPROCESSED_SWITCH_CASES - 1 \
, <argot/prov/switch_/detail/generation/case_generation.hpp> \
) \
)
#include BOOST_PP_ITERATE()
////////////////////////////////////////////////////////////////////////////////
// End generation of cases. //
////////////////////////////////////////////////////////////////////////////////
default:
return switch_provision
< NumRemainingCases - ARGOT_MAX_PREPROCESSED_SWITCH_CASES, Kind >::run
( static_cast
< with_qualifiers_t
< prov::switch_detail::switch_impl< ValueType, Bodies... > >
>( self )
, static_cast< Receiver&& >( receiver )
);
}
}
};
#endif // ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID
} // namespace (argot::prov::switch_detail)
#else // Otherwise, we are generating the preprocessed forms as files...
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 1, 2 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 3
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 3, 4 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 5
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 5, 8 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 9
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 9, 16 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 17
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 17, 32 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 33
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 33, 64 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 65
#error User requested preprocessing for switches with more than 64 cases.
#endif
#undef ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE
#endif // End of preprocessing mode checks
#endif // ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
| 40.142857 | 85 | 0.656584 |
3d36745f5a28918e6248895cf2c1fea18e67768a | 3,807 | hpp | C++ | ext/lexertl/lexertl/partition/equivset.hpp | thangduong/tokenex | fbc124caf248aaf83b8fb5e293b38398da7b1d6a | [
"MIT"
] | null | null | null | ext/lexertl/lexertl/partition/equivset.hpp | thangduong/tokenex | fbc124caf248aaf83b8fb5e293b38398da7b1d6a | [
"MIT"
] | null | null | null | ext/lexertl/lexertl/partition/equivset.hpp | thangduong/tokenex | fbc124caf248aaf83b8fb5e293b38398da7b1d6a | [
"MIT"
] | null | null | null | // equivset.hpp
// Copyright (c) 2005-2017 Ben Hanson (http://www.benhanson.net/)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file licence_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LEXERTL_EQUIVSET_HPP
#define LEXERTL_EQUIVSET_HPP
#include <algorithm>
#include "../parser/tree/node.hpp"
#include <set>
namespace lexertl
{
namespace detail
{
template<typename id_type>
struct basic_equivset
{
typedef std::set<id_type> index_set;
typedef std::vector<id_type> index_vector;
// Not owner of nodes:
typedef basic_node<id_type> node;
typedef std::vector<node *> node_vector;
index_vector _index_vector;
id_type _id;
bool _greedy;
node_vector _followpos;
basic_equivset() :
_index_vector(),
_id(0),
_greedy(true),
_followpos()
{
}
basic_equivset(const index_set &index_set_, const id_type id_,
const bool greedy_, const node_vector &followpos_) :
_index_vector(index_set_.begin(), index_set_.end()),
_id(id_),
_greedy(greedy_),
_followpos(followpos_)
{
}
bool empty() const
{
return _index_vector.empty() && _followpos.empty();
}
void intersect(basic_equivset &rhs_, basic_equivset &overlap_)
{
intersect_indexes(rhs_._index_vector, overlap_._index_vector);
if (!overlap_._index_vector.empty())
{
// Note that the LHS takes priority in order to
// respect rule ordering priority in the lex spec.
overlap_._id = _id;
overlap_._greedy = _greedy;
overlap_._followpos = _followpos;
typename node_vector::const_iterator overlap_begin_ =
overlap_._followpos.begin();
typename node_vector::const_iterator overlap_end_ =
overlap_._followpos.end();
typename node_vector::const_iterator rhs_iter_ =
rhs_._followpos.begin();
typename node_vector::const_iterator rhs_end_ =
rhs_._followpos.end();
for (; rhs_iter_ != rhs_end_; ++rhs_iter_)
{
node *node_ = *rhs_iter_;
if (std::find(overlap_begin_, overlap_end_, node_) ==
overlap_end_)
{
overlap_._followpos.push_back(node_);
overlap_begin_ = overlap_._followpos.begin();
overlap_end_ = overlap_._followpos.end();
}
}
if (_index_vector.empty())
{
_followpos.clear();
}
if (rhs_._index_vector.empty())
{
rhs_._followpos.clear();
}
}
}
private:
void intersect_indexes(index_vector &rhs_, index_vector &overlap_)
{
typename index_vector::iterator iter_ = _index_vector.begin();
typename index_vector::iterator end_ = _index_vector.end();
typename index_vector::iterator rhs_iter_ = rhs_.begin();
typename index_vector::iterator rhs_end_ = rhs_.end();
while (iter_ != end_ && rhs_iter_ != rhs_end_)
{
const id_type index_ = *iter_;
const id_type rhs_index_ = *rhs_iter_;
if (index_ < rhs_index_)
{
++iter_;
}
else if (index_ > rhs_index_)
{
++rhs_iter_;
}
else
{
overlap_.push_back(index_);
iter_ = _index_vector.erase(iter_);
end_ = _index_vector.end();
rhs_iter_ = rhs_.erase(rhs_iter_);
rhs_end_ = rhs_.end();
}
}
}
};
}
}
#endif
| 28.2 | 79 | 0.567113 |
3d39874c86d5a8d0607dff20b27d0641b0a681ce | 1,847 | cpp | C++ | mapping/src/mapperLazyTimesteps.cpp | xaedes/GNSS-Shadowing | a748e3063fb76272005b6430a844a53644cca9b0 | [
"MIT"
] | 29 | 2017-10-13T12:14:13.000Z | 2022-02-25T16:39:05.000Z | mapping/src/mapperLazyTimesteps.cpp | xaedes/GNSS-Shadowing | a748e3063fb76272005b6430a844a53644cca9b0 | [
"MIT"
] | null | null | null | mapping/src/mapperLazyTimesteps.cpp | xaedes/GNSS-Shadowing | a748e3063fb76272005b6430a844a53644cca9b0 | [
"MIT"
] | 8 | 2018-04-21T14:52:26.000Z | 2022-02-14T13:51:10.000Z |
#include "mapping/mapperLazyTimesteps.h"
#include <iostream>
namespace gnssShadowing {
namespace mapping {
MapperLazyTimesteps::MapperLazyTimesteps(world::World& world, MapProperties mapProperties, double startTimeUnixTimeSeconds, double timePerStep, double minimumSatelliteElevation)
: m_world(world)
, m_mapProperties(mapProperties)
, m_minimumSatelliteElevation(minimumSatelliteElevation)
, m_startTimeUnixTimeSeconds(startTimeUnixTimeSeconds)
, m_timePerStep(timePerStep)
{}
double MapperLazyTimesteps::getTime(int timeStep)
{
return m_startTimeUnixTimeSeconds + m_timePerStep*timeStep;
}
DOPMap& MapperLazyTimesteps::getDOPMap(int timeStep)
{
if (m_mappers.count(timeStep) && m_mappers[timeStep].get())
{
return m_mappers[timeStep]->m_dopMap;
}
else
{
return computeDOPMap(timeStep);
}
}
OccupancyMap& MapperLazyTimesteps::getOccupancyMap(int timeStep)
{
if (m_mappers.count(timeStep) && m_mappers[timeStep].get())
{
return m_mappers[timeStep]->m_occupancyMap;
}
else
{
computeDOPMap(timeStep);
return m_mappers[timeStep]->m_occupancyMap;
}
}
void MapperLazyTimesteps::clear()
{
m_mappers.clear();
}
DOPMap& MapperLazyTimesteps::computeDOPMap(int timeStep)
{
// std::cout << __PRETTY_FUNCTION__ << " timeStep " << timeStep << std::endl;
double now = getTime(timeStep);
m_mappers[timeStep].reset(new Mapper(m_world, m_mapProperties, m_minimumSatelliteElevation));
m_mappers[timeStep]->computeDOPMap(now);
return m_mappers[timeStep]->m_dopMap;
}
} // namespace mapping
} // namespace gnssShadowing
| 27.567164 | 181 | 0.651326 |
3d3bb9d6ec3066e7ae8aa645808da6c09ff82951 | 678 | cpp | C++ | simple_model_loader/src/main.cpp | JacobNeal/gl-projects | 4ea40797fde28602b9f787f0ec8005dcd164e054 | [
"MIT"
] | null | null | null | simple_model_loader/src/main.cpp | JacobNeal/gl-projects | 4ea40797fde28602b9f787f0ec8005dcd164e054 | [
"MIT"
] | null | null | null | simple_model_loader/src/main.cpp | JacobNeal/gl-projects | 4ea40797fde28602b9f787f0ec8005dcd164e054 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include "ModelLoader.hpp"
#include "Model.hpp"
#include "Window.hpp"
#include "Logger.hpp"
LOGGER_DECL
int main()
{
Window window("Simple Model Loader", 800, 640);
ModelLoader modelLoader;
Model * model = modelLoader.load("cube.MODEL");
while (!window.isDone())
{
window.beginDraw();
window.update();
window.draw(model);
window.endDraw();
}
// Clean up after the ModelLoader
delete model;
std::cout << LOGGER;
std::ofstream logFile("log.txt");
if (logFile.is_open())
{
logFile << LOGGER;
logFile.close();
}
return 0;
}
| 14.73913 | 51 | 0.589971 |
3d3ee1870119b322c1714c4886457ca06e699be7 | 1,010 | cpp | C++ | src/random/NormalDistribution.cpp | cuhkshenzhen/CUHKSZLib | 4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f | [
"MIT"
] | null | null | null | src/random/NormalDistribution.cpp | cuhkshenzhen/CUHKSZLib | 4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f | [
"MIT"
] | 29 | 2017-04-26T09:15:28.000Z | 2017-05-21T15:50:37.000Z | src/random/NormalDistribution.cpp | cuhkshenzhen/CUHKSZLib | 4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f | [
"MIT"
] | 7 | 2017-04-26T09:32:39.000Z | 2021-11-03T02:00:07.000Z | #include "random/NormalDistribution.h"
#include <cmath>
#include "utils/error.h"
namespace cuhksz {
void NormalDistribution::init(double mean, double stddev) {
if (stddev <= 0) {
error("Invalid parameter `stddev` for NormalDistribution");
}
mean_ = mean;
stddev_ = stddev;
}
double NormalDistribution::next() {
// Marsaglia polar method
// (https://en.wikipedia.org/wiki/Marsaglia_polar_method)
if (hasSpare) {
hasSpare = false;
return spareResult * stddev_ + mean_;
}
double u;
double v;
double sum;
do {
u = randomGenerator->nextDouble(-1, 1);
v = randomGenerator->nextDouble(-1, 1);
sum = u * u + v * v;
// disable gcc's warning for comparing with 0.0
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
} while (sum == 0.0 || sum > 1);
#pragma GCC diagnostic pop
double result = std::sqrt(-2 * std::log(sum) / sum);
spareResult = v * result;
hasSpare = true;
return u * result * stddev_ + mean_;
}
} // namespace cuhksz
| 24.634146 | 63 | 0.664356 |
3d3ff38fa83b28d3310c62eecfd311f8e5a1c197 | 8,097 | cc | C++ | tests/types/traits/logical.cc | evanacox/freestanding-rt | 44cb68d86654f07fe82c0a44a139f90ed5730ac3 | [
"BSD-3-Clause"
] | null | null | null | tests/types/traits/logical.cc | evanacox/freestanding-rt | 44cb68d86654f07fe82c0a44a139f90ed5730ac3 | [
"BSD-3-Clause"
] | null | null | null | tests/types/traits/logical.cc | evanacox/freestanding-rt | 44cb68d86654f07fe82c0a44a139f90ed5730ac3 | [
"BSD-3-Clause"
] | null | null | null | //======---------------------------------------------------------------======//
// //
// Copyright 2021-2022 Evan Cox <evanacox00@gmail.com>. All rights reserved. //
// //
// Use of this source code is governed by a BSD-style license that can be //
// found in the LICENSE.txt file at the root of this project, or at the //
// following link: https://opensource.org/licenses/BSD-3-Clause //
// //
//======---------------------------------------------------------------======//
#include "frt/types/concepts.h"
#include "frt/types/traits.h"
#include "gtest/gtest.h"
/*
* Note: Most of this test is adapted from the libc++ test suite, therefore it is
* also under the LLVM copyright. See the license header below for details:
*/
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
namespace {
struct True {
static constexpr bool value = true;
};
struct False {
static constexpr bool value = false;
};
TEST(FrtTypesTraits, Conjunction) {
static_assert(frt::traits::ConjunctionTrait<>::value);
static_assert(frt::traits::ConjunctionTrait<std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type>::value);
static_assert(frt::traits::conjunction<>);
static_assert(frt::traits::conjunction<std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type>);
static_assert(frt::traits::ConjunctionTrait<std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type>::value);
static_assert(frt::traits::conjunction<std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type>);
static_assert(frt::traits::ConjunctionTrait<std::true_type, std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::conjunction<std::true_type, std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type, std::false_type>);
static_assert(frt::traits::ConjunctionTrait<True>::value);
static_assert(!frt::traits::ConjunctionTrait<False>::value);
static_assert(frt::traits::conjunction<True>);
static_assert(!frt::traits::conjunction<False>);
}
TEST(FrtTypesTraits, Disjunction) {
static_assert(!frt::traits::DisjunctionTrait<>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type>::value);
static_assert(!frt::traits::disjunction<>);
static_assert(frt::traits::disjunction<std::true_type>);
static_assert(!frt::traits::disjunction<std::false_type>);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type, std::false_type>::value);
static_assert(frt::traits::disjunction<std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type>);
static_assert(!frt::traits::disjunction<std::false_type, std::false_type>);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::false_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::disjunction<std::true_type, std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type, std::true_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::false_type, std::false_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::true_type, std::false_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type, std::false_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type, std::false_type>);
static_assert(!frt::traits::disjunction<std::false_type, std::false_type, std::false_type>);
static_assert(frt::traits::DisjunctionTrait<True>::value);
static_assert(!frt::traits::DisjunctionTrait<False>::value);
static_assert(frt::traits::disjunction<True>);
static_assert(!frt::traits::disjunction<False>);
}
TEST(FrtTypesTraits, Negation) {
static_assert(!frt::traits::NegationTrait<std::true_type>::value);
static_assert(frt::traits::NegationTrait<std::false_type>::value);
static_assert(!frt::traits::negation<std::true_type>);
static_assert(frt::traits::negation<std::false_type>);
static_assert(!frt::traits::NegationTrait<True>::value);
static_assert(frt::traits::NegationTrait<False>::value);
static_assert(!frt::traits::negation<True>);
static_assert(frt::traits::negation<False>);
static_assert(frt::traits::NegationTrait<std::negation<std::true_type>>::value);
static_assert(!frt::traits::NegationTrait<std::negation<std::false_type>>::value);
}
} // namespace | 57.835714 | 108 | 0.682845 |
3d406ccf27012fa7f5b609ec3291bada72ac6268 | 140 | hpp | C++ | template-bot/src/utils.hpp | bmstu-iu8-cpp-sem-1/homework-telegram-bot | 138f6611e4ca08b9a5c4dde76c54af1cefe6504c | [
"MIT"
] | 2 | 2021-03-09T08:12:28.000Z | 2022-02-21T18:10:36.000Z | template-bot/src/utils.hpp | sjuda/telegram-bot | 11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d | [
"MIT"
] | null | null | null | template-bot/src/utils.hpp | sjuda/telegram-bot | 11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <boost/locale.hpp>
namespace Utils
{
std::string fromLocale(const std::string& localeStr);
}
| 12.727273 | 57 | 0.714286 |
3d420cd5393eba0250fc200d6e0304cc05ed703d | 3,343 | cpp | C++ | Code/System/Resource/ResourceLoader.cpp | JuanluMorales/KRG | f3a11de469586a4ef0db835af4bc4589e6b70779 | [
"MIT"
] | 419 | 2022-01-27T19:37:43.000Z | 2022-03-31T06:14:22.000Z | Code/System/Resource/ResourceLoader.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-01-28T20:35:33.000Z | 2022-03-13T17:42:52.000Z | Code/System/Resource/ResourceLoader.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 20 | 2022-01-27T20:41:02.000Z | 2022-03-26T16:16:57.000Z | #include "ResourceLoader.h"
#include "ResourceHeader.h"
#include "System/Core/Serialization/BinaryArchive.h"
#include "System/Core/Logging/Log.h"
//-------------------------------------------------------------------------
namespace KRG::Resource
{
bool ResourceLoader::Load( ResourceID const& resourceID, TVector<Byte>& rawData, ResourceRecord* pResourceRecord ) const
{
Serialization::BinaryMemoryArchive archive( Serialization::Mode::Read, rawData );
if ( archive.IsValid() )
{
// Read resource header
Resource::ResourceHeader header;
archive >> header;
// Set all install dependencies
pResourceRecord->m_installDependencyResourceIDs.reserve( header.m_installDependencies.size() );
for ( auto const& depResourceID : header.m_installDependencies )
{
pResourceRecord->m_installDependencyResourceIDs.push_back( depResourceID );
}
// Perform resource load
if ( !LoadInternal( resourceID, pResourceRecord, archive ) )
{
KRG_LOG_ERROR( "Resource", "Resource loader failed to load resource: %s", resourceID.c_str() );
return false;
}
// Loaders must always set a valid resource data ptr, even if the resource internally is invalid
// This is enforced to prevent leaks from occurring when a loader allocates a resource, then tries to
// load it unsuccessfully and then forgets to release the allocated data.
KRG_ASSERT( pResourceRecord->GetResourceData() != nullptr );
return true;
}
else
{
KRG_LOG_ERROR( "Resource", "Failed to read binary resource data (%s)", resourceID.c_str() );
return false;
}
}
InstallResult ResourceLoader::Install( ResourceID const& resourceID, ResourceRecord* pResourceRecord, InstallDependencyList const& installDependencies ) const
{
KRG_ASSERT( pResourceRecord != nullptr );
pResourceRecord->m_pResource->m_resourceID = resourceID;
return InstallResult::Succeeded;
}
InstallResult ResourceLoader::UpdateInstall( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
// This function should never be called directly!!
// If your resource requires multi-frame installation, you need to override this function in your loader and return InstallResult::InProgress from the install function!
KRG_UNREACHABLE_CODE();
return InstallResult::Succeeded;
}
void ResourceLoader::Unload( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
KRG_ASSERT( pResourceRecord != nullptr );
KRG_ASSERT( pResourceRecord->IsUnloading() || pResourceRecord->HasLoadingFailed() );
UnloadInternal( resourceID, pResourceRecord );
pResourceRecord->m_installDependencyResourceIDs.clear();
}
void ResourceLoader::UnloadInternal( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
IResource* pData = pResourceRecord->GetResourceData();
KRG::Delete( pData );
pResourceRecord->SetResourceData( nullptr );
}
} | 44.573333 | 177 | 0.638648 |
3d447cbeece9cbf1aa1dc04cf5ba3f18bd7e77fd | 2,937 | cc | C++ | moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | 1 | 2020-05-11T18:36:25.000Z | 2020-05-11T18:36:25.000Z | moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014-2016 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 <iostream>
#include "image_writer.h"
// This was automatically generated by /Volumes/Android/inde-dev//art/tools/generate-operator-out.py --- do not edit!
namespace art {
std::ostream& operator<<(std::ostream& os, const ImageWriter::Bin& rhs) {
switch (rhs) {
case ImageWriter::kBinString: os << "BinString"; break;
case ImageWriter::kBinRegular: os << "BinRegular"; break;
case ImageWriter::kBinClassInitializedFinalStatics: os << "BinClassInitializedFinalStatics"; break;
case ImageWriter::kBinClassInitialized: os << "BinClassInitialized"; break;
case ImageWriter::kBinClassVerified: os << "BinClassVerified"; break;
case ImageWriter::kBinArtField: os << "BinArtField"; break;
case ImageWriter::kBinArtMethodClean: os << "BinArtMethodClean"; break;
case ImageWriter::kBinArtMethodDirty: os << "BinArtMethodDirty"; break;
case ImageWriter::kBinDexCacheArray: os << "BinDexCacheArray"; break;
case ImageWriter::kBinSize: os << "BinSize"; break;
default: os << "ImageWriter::Bin[" << static_cast<int>(rhs) << "]"; break;
}
return os;
}
} // namespace art
// This was automatically generated by /Volumes/Android/inde-dev//art/tools/generate-operator-out.py --- do not edit!
namespace art {
std::ostream& operator<<(std::ostream& os, const ImageWriter::NativeObjectRelocationType& rhs) {
switch (rhs) {
case ImageWriter::kNativeObjectRelocationTypeArtField: os << "NativeObjectRelocationTypeArtField"; break;
case ImageWriter::kNativeObjectRelocationTypeArtFieldArray: os << "NativeObjectRelocationTypeArtFieldArray"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodClean: os << "NativeObjectRelocationTypeArtMethodClean"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodArrayClean: os << "NativeObjectRelocationTypeArtMethodArrayClean"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodDirty: os << "NativeObjectRelocationTypeArtMethodDirty"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodArrayDirty: os << "NativeObjectRelocationTypeArtMethodArrayDirty"; break;
case ImageWriter::kNativeObjectRelocationTypeDexCacheArray: os << "NativeObjectRelocationTypeDexCacheArray"; break;
default: os << "ImageWriter::NativeObjectRelocationType[" << static_cast<int>(rhs) << "]"; break;
}
return os;
}
} // namespace art
| 49.779661 | 131 | 0.765066 |
3d4aedc2125a1985f141e06caed48c4ba3c24f50 | 1,991 | hpp | C++ | aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 2,690 | 2015-01-07T03:50:23.000Z | 2022-03-31T20:27:01.000Z | aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 481 | 2015-01-27T10:21:00.000Z | 2022-03-31T14:02:41.000Z | aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 1,091 | 2015-01-26T21:21:13.000Z | 2022-03-30T01:55:33.000Z | /**
* @file sbm_gtest.hpp
* @author Paul Furgale <paul.furgale@gmail.com>
* @date Wed Jan 11 09:29:57 2012
*
* @brief Helper functions for unit testing SBM
*
*
*/
#ifndef _SBM_GTEST_H_
#define _SBM_GTEST_H_
namespace sparse_block_matrix {
template<typename MATRIX1_TYPE, typename MATRIX2_TYPE, typename T>
void expectNear(const MATRIX1_TYPE & A, const MATRIX2_TYPE & B, T tolerance, std::string const & message = "")
{
// These assert statements will return from this function but not from the base unit test.
ASSERT_EQ(A.rows(),B.rows()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
ASSERT_EQ(A.cols(),B.cols()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
for(int r = 0; r < A.rows(); r++)
{
for(int c = 0; c < A.cols(); c++)
{
ASSERT_NEAR(A(r,c),B(r,c),tolerance) << message << "\nTolerance comparison failed at (" << r << "," << c << ")"
<< "\nMatrix A:\n" << A << "\nand matrix B\n" << B;
}
}
}
template<typename MATRIX1_TYPE, typename MATRIX2_TYPE>
void expectEqual(const MATRIX1_TYPE & A, const MATRIX2_TYPE & B, std::string const & message = "")
{
// These assert statements will return from this function but not from the base unit test.
ASSERT_EQ(B.rows(),A.rows()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
ASSERT_EQ(B.cols(),A.cols()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
for(int r = 0; r < A.rows(); r++)
{
for(int c = 0; c < A.cols(); c++)
{
ASSERT_EQ(B(r,c),A(r,c)) << message << "\nEquality comparison failed at (" << r << "," << c << ")"
<< "\nMatrix A:\n" << A << "\nand matrix B\n" << B;
}
}
}
} // namespace sbm
#endif /* _SBM_GTEST_H_ */
| 36.87037 | 126 | 0.550979 |
3d4c6a768bef0b77475e30aa4f9b42aff74bbba1 | 444 | cpp | C++ | codeforces/1108B.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | codeforces/1108B.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | codeforces/1108B.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
#define le 130
using namespace std;
int n[le];
map<int, int> mp;
int main(){
//freopen("input.txt", "r", stdin);
int len, mx = -INT_MAX, mx1 = -INT_MAX;
scanf("%d", &len);
for(int i = 0; i < len; i++){
scanf("%d", &n[i]);
mx = max(mx, n[i]);
}
for(int i = 0; i < len; i++){
mp[n[i]]++;
if(mx % n[i] != 0 || mp[n[i]] > 1) mx1 = max(mx1, n[i]);
}
printf("%d %d\n", mx, mx1);
return 0;
}
| 21.142857 | 60 | 0.481982 |
3d4cbc776bb8b6c4f70872c069f5e89785342846 | 620 | cpp | C++ | c++11/understanding-cpp11/chapter7/7-3-13.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | c++11/understanding-cpp11/chapter7/7-3-13.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | c++11/understanding-cpp11/chapter7/7-3-13.cpp | cuiwm/choe_lib | 6992c7bf551e7d6d633399b21b028e6873d5e6e8 | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
using namespace std;
vector<int> nums;
vector<int> largeNums;
const int ubound = 10;
inline void LargeNumsFunc(int i){
if (i > ubound)
largeNums.push_back(i);
}
void Above() {
// 传统的for循环
for (auto itr = nums.begin(); itr != nums.end(); ++itr) {
if (*itr >= ubound)
largeNums.push_back(*itr);
}
// 使用函数指针
for_each(nums.begin(), nums.end(), LargeNumsFunc);
// 使用lambda函数和算法for_each
for_each(nums.begin(), nums.end(), [=](int i){
if (i > ubound)
largeNums.push_back(i);
});
}
| 19.375 | 61 | 0.562903 |
3d4cc3e641a6d66de21abeea0c2035956e900a7d | 5,612 | cpp | C++ | FBConsole.cpp | StereoRocker/fbconsole | a0ad55525f1c6a0a048147f8d5317a081fe372f0 | [
"BSD-3-Clause"
] | null | null | null | FBConsole.cpp | StereoRocker/fbconsole | a0ad55525f1c6a0a048147f8d5317a081fe372f0 | [
"BSD-3-Clause"
] | null | null | null | FBConsole.cpp | StereoRocker/fbconsole | a0ad55525f1c6a0a048147f8d5317a081fe372f0 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Dominic Houghton. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Framebuffer console driver, using the I_Framebuffer interface
#include "FBConsole.hpp"
template <class T>
FBConsole<T>::FBConsole(I_Framebuffer<T>* framebuffer, uint8_t* font, uint8_t scale)
{
// These will hold the display's actual dimensions while initialising
uint16_t display_width, display_height;
// Set the constants within the class
_FRAMEBUFFER = framebuffer;
_FONT = font;
_SCALE = scale;
// Calculate the console width and height, store them within the class
_FRAMEBUFFER->get_dimensions(&display_width, &display_height);
_WIDTH = display_width / (8 * _SCALE);
_HEIGHT = display_height / (8 * _SCALE);
/* Create a buffer of pixels, large enough to hold a single character.
* The put_char function will use this array, so as to maintain a consistent
* memory footprint.
*
* Scaling the font to be larger will increase the memory footprint
* exponentially.
*/
_CHARBUF = new T[(8 * _SCALE) * (8 * _SCALE)];
// Set sane defaults for the runtime variables
console_background = _FRAMEBUFFER->get_color(0x00,0x00,0x00); // Black
console_foreground = _FRAMEBUFFER->get_color(0xFF,0xFF,0xFF); // White
console_x = 0;
console_y = 0;
}
template <class T>
void FBConsole<T>::put_char(char c)
{
// Determine the character to draw
uint16_t charindex = 0;
bool drawchar = true;
int count;
// Handle special-case characters, or calculate the font index
switch (c)
{
case '\n': // Line feed, handled unix-style
drawchar = false;
console_x = 0;
console_y++;
break;
case '\r': // Carriage return
drawchar = false;
console_x = 0;
break;
case '\t': // Tab
count = _TABSTOP - ((console_x) % _TABSTOP);
for (int i = 0; i < count; i++)
put_char(' ');
drawchar = false;
break;
case '\b': // Backspace
if (console_x > 0)
console_x--;
drawchar = false;
break;
// If character is none of the special cases above
default:
// Test if the character is mapped in the font
if (c >= 0x20 || c <= 0x7E)
charindex = (c - 0x20);
else
charindex = 95; // font[95] contains the "invalid" glyph
break;
}
// Fill the character buffer
// Iterate through the character data
if (drawchar) {
T* color;
for (int cy = 0; cy < 8; cy++)
{
for (int cx = 0; cx < 8; cx++)
{
// Test the bit
if ( ((_FONT[(charindex * 8) + cy] << cx) & 0x80) == 0x80 )
color = &console_foreground;
else
color = &console_background;
// Plot the color in the character buffer
for (int by = 0; by < _SCALE; by++)
{
for (int bx = 0; bx < _SCALE; bx++)
{
//_CHARBUF[((cy + by) * 8 * _SCALE) + (cx * _SCALE) + bx] = *color;
//_CHARBUF[(cy * 8 * _SCALE) + (cx * _SCALE) + bx] = *color;
_CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = *color;
}
}
}
}
// Plot the character buffer
uint16_t dx, dy;
dx = (console_x * 8 * _SCALE);
dy = (console_y * 8 * _SCALE);
_FRAMEBUFFER->plot_block(dx, dy,
dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1,
_CHARBUF, (8 * _SCALE) * (8 * _SCALE));
// Increase console_x
console_x++;
}
// Test console_x, increment console_y if necessary
if (console_x >= _WIDTH)
{
console_x = 0;
console_y++;
}
// Test console_y, call scroll_vertical if necessary
if (console_y >= _HEIGHT)
{
_FRAMEBUFFER->scroll_vertical(8 * _SCALE);
// If scroll_vertical was called, decrement console_y and clear the row
console_y--;
// Set character with only background
for (int cy = 0; cy < 8; cy++)
{
for (int cx = 0; cx < 8; cx++)
{
// Plot the color in the character buffer
for (int by = 0; by < _SCALE; by++)
{
for (int bx = 0; bx < _SCALE; bx++)
{
_CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = console_background;
}
}
}
}
// Clear the row with the background color
int dy = (console_y * 8 * _SCALE);
int dx;
for (int x = 0; x < _WIDTH; x++)
{
dx = (x * 8 * _SCALE);
_FRAMEBUFFER->plot_block(dx, dy,
dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1,
_CHARBUF, (8 * _SCALE) * (8 * _SCALE));
}
}
}
template <class T>
void FBConsole<T>::put_string(const char* str)
{
int i = 0;
for (i = 0; str[i] != 0; i++)
put_char(str[i]);
}
template class FBConsole<uint8_t>;
template class FBConsole<uint16_t>;
template class FBConsole<uint32_t>; | 30.335135 | 115 | 0.50392 |
3d4ce5463fc1e90aa8c6ff5511f4d0f941e7304c | 4,819 | cpp | C++ | librtt/Display/Rtt_ClosedPath.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | librtt/Display/Rtt_ClosedPath.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | librtt/Display/Rtt_ClosedPath.cpp | pouwelsjochem/corona | 86ffe9002e42721b4bb2c386024111d995e7b27c | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#include "Display/Rtt_ClosedPath.h"
#include "Display/Rtt_DisplayTypes.h"
#include "Rtt_Matrix.h"
#include "Rtt_LuaUserdataProxy.h"
#include "Display/Rtt_VertexCache.h"
#include "Display/Rtt_DisplayObject.h"
#include "Display/Rtt_Paint.h"
#include "Display/Rtt_Shader.h"
#include "Renderer/Rtt_Program.h"
#include "Renderer/Rtt_Geometry_Renderer.h"
// ----------------------------------------------------------------------------
namespace Rtt
{
// ----------------------------------------------------------------------------
ClosedPath::ClosedPath( Rtt_Allocator* pAllocator )
: fObserver( NULL ),
fAdapter( NULL ),
fProxy( NULL ),
fFill( NULL ),
fProperties( 0 ),
fDirtyFlags( kDefault )
{
}
ClosedPath::~ClosedPath()
{
if ( fProxy )
{
GetObserver()->QueueRelease( fProxy ); // Release native ref to Lua-side proxy
fProxy->DetachUserdata(); // Notify proxy that object is invalid
}
Rtt_DELETE( fFill );
}
void
ClosedPath::Update( RenderData& data, const Matrix& srcToDstSpace )
{
if ( HasFill() && ! fFill->IsValid(Paint::kTextureTransformFlag) )
{
Invalidate( kFillSourceTexture );
}
}
void
ClosedPath::UpdateGeometry( Geometry& dst, const VertexCache& src, const Matrix& srcToDstSpace, U32 flags, Array<U16> *indices )
{
if ( 0 == flags ) { return; }
const ArrayVertex2& vertices = src.Vertices();
const ArrayVertex2& texVertices = src.TexVertices();
U32 numVertices = vertices.Length();
U32 numIndices = indices==NULL?0:indices->Length();
if ( dst.GetVerticesAllocated() < numVertices || dst.GetIndicesAllocated() < numIndices)
{
dst.Resize( numVertices, numIndices, false );
}
Geometry::Vertex *dstVertices = dst.GetVertexData();
bool updateVertices = ( flags & kVerticesMask );
bool updateTexture = ( flags & kTexVerticesMask );
Rtt_ASSERT( ! updateTexture || ( vertices.Length() == texVertices.Length() ) );
for ( U32 i = 0, iMax = vertices.Length(); i < iMax; i++ )
{
Rtt_ASSERT( i < dst.GetVerticesAllocated() );
Geometry::Vertex& dst = dstVertices[i];
if ( updateVertices )
{
Vertex2 v = vertices[i];
srcToDstSpace.Apply( v );
dst.x = v.x;
dst.y = v.y;
dst.z = 0.f;
}
if ( updateTexture )
{
dst.u = texVertices[i].x;
dst.v = texVertices[i].y;
dst.q = 1.f;
}
}
dst.SetVerticesUsed( numVertices );
if(flags & kIndicesMask)
{
if(indices)
{
const U16* indicesData = indices->ReadAccess();
U16* dstData = dst.GetIndexData();
numIndices = indices->Length();
for (U32 i=0; i<numIndices; i++)
{
dstData[i] = indicesData[i];
}
dst.Invalidate();
}
dst.SetIndicesUsed(numIndices);
}
}
void
ClosedPath::Translate( Real dx, Real dy )
{
if ( HasFill() )
{
fFill->Translate( dx, dy );
}
}
bool
ClosedPath::SetSelfBounds( Real width, Real height )
{
return false;
}
void
ClosedPath::UpdatePaint( RenderData& data )
{
if ( HasFill() )
{
fFill->UpdatePaint( data );
}
}
void
ClosedPath::UpdateColor( RenderData& data, U8 objectAlpha )
{
if ( HasFill() )
{
fFill->UpdateColor( data, objectAlpha );
}
}
void
ClosedPath::SetFill( Paint* newValue )
{
if ( IsProperty( kIsFillLocked ) )
{
// Caller expects receiver to own this, so we delete it
// b/c the fill is locked. Otherwise it will leak.
Rtt_DELETE( newValue );
return;
}
if ( fFill != newValue )
{
if ( ! fFill )
{
// If fill was NULL, then we need to ensure
// source vertices are generated
Invalidate( kFillSource | kFillSourceTexture );
}
Rtt_DELETE( fFill );
fFill = newValue;
if ( newValue )
{
newValue->SetObserver( GetObserver() );
}
}
}
void
ClosedPath::SwapFill( ClosedPath& rhs )
{
Paint* paint = rhs.fFill;
rhs.fFill = fFill;
fFill = paint;
if ( fFill )
{
fFill->SetObserver( GetObserver() );
}
if ( rhs.fFill )
{
rhs.fFill->SetObserver( rhs.GetObserver() );
}
Invalidate( kFillSource );
}
bool
ClosedPath::IsFillVisible() const
{
bool result = false;
if ( HasFill() )
{
result = ( fFill->GetRGBA().a > Rtt_REAL_0 );
}
return result;
}
void
ClosedPath::PushProxy( lua_State *L ) const
{
if ( ! fProxy )
{
fProxy = LuaUserdataProxy::New( L, const_cast< Self * >( this ) );
fProxy->SetAdapter( GetAdapter() );
}
fProxy->Push( L );
}
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
| 19.913223 | 128 | 0.599709 |
3d4d428b5518f3ebfb7a75e47af0c31a1f7b8b90 | 271 | cpp | C++ | tester-webserv/CppTester/src/Utility/close_pipe.cpp | aprilmayjune135/42_web_server | 46bc46dd6a0008119842e3848d4fe57fcd84526b | [
"MIT"
] | 2 | 2022-01-04T13:07:46.000Z | 2022-01-04T13:08:50.000Z | tester-webserv/CppTester/src/Utility/close_pipe.cpp | aprilmayjune135/web-server | 46bc46dd6a0008119842e3848d4fe57fcd84526b | [
"MIT"
] | 3 | 2021-09-27T08:35:34.000Z | 2021-11-25T09:49:52.000Z | tester-webserv/CppTester/src/Utility/close_pipe.cpp | aprilmayjune135/web-server | 46bc46dd6a0008119842e3848d4fe57fcd84526b | [
"MIT"
] | 2 | 2021-11-17T20:26:55.000Z | 2021-12-22T21:54:24.000Z | #include "utility.hpp"
#include "macros.hpp"
#include <unistd.h>
#include <stdio.h>
namespace util
{
void closeFd(int fd)
{
if (close(fd) == -1)
{
syscallError(_FUNC_ERR("close"));
}
}
void closePipe(int* fds)
{
closeFd(fds[0]);
closeFd(fds[1]);
}
}
| 12.318182 | 36 | 0.612546 |
3d5308430ff86e27b6bdd8de09fc22daa0968ff1 | 460 | cpp | C++ | src/util/bip32.cpp | ligui2003/BCEX | 2f34c68fce7215d36c5520e46fe83321a6df4408 | [
"Apache-2.0"
] | 4 | 2020-05-02T08:07:37.000Z | 2021-07-09T03:17:00.000Z | src/util/bip32.cpp | ligui2003/BCEX | 2f34c68fce7215d36c5520e46fe83321a6df4408 | [
"Apache-2.0"
] | null | null | null | src/util/bip32.cpp | ligui2003/BCEX | 2f34c68fce7215d36c5520e46fe83321a6df4408 | [
"Apache-2.0"
] | 3 | 2019-07-01T18:40:12.000Z | 2021-07-09T03:17:01.000Z | // Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <sstream>
#include <stdio.h>
#include "util/tinyformat.h"
#include "util/bip32.h"
#include "util/strencodings.h"
bool ParseHDKeypath(const std::string& keypath_str,std::vector<uint32_t>& keypath)
{
std::stringstream ss(keypath_str);
return true;
}
| 24.210526 | 82 | 0.743478 |
3d5811c0d2006ec2c33ae0fdf33af47b00862d3d | 752 | cpp | C++ | halfacookie.cpp | nemo201/Kattis | 887711eece263965a4529048011847f7a2749fec | [
"MIT"
] | null | null | null | halfacookie.cpp | nemo201/Kattis | 887711eece263965a4529048011847f7a2749fec | [
"MIT"
] | null | null | null | halfacookie.cpp | nemo201/Kattis | 887711eece263965a4529048011847f7a2749fec | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
int main() {
cout << fixed << setprecision(4);
double r, x, y;
while(cin >> r >> x >> y){
if(sqrt(x * x + y * y) >= r){
cout << "miss" << endl;
} else {
double h = r - sqrt(x * x + y * y);
double area = r * r * 3.141592653589793238462643383;
double seg_area = r * r * acos((r - h) / r) - (r - h) * sqrt((2 * r * h - h * h));
cout << area - seg_area << " " << seg_area << endl;
}
}
}
| 30.08 | 94 | 0.482713 |
3d59a072f742b1c1ae7225767f5ef46ae0edec0c | 1,088 | cpp | C++ | Tree Algorithms/Distance Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T12:30:13.000Z | 2022-02-12T13:59:20.000Z | Tree Algorithms/Distance Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | 2 | 2022-02-12T11:09:41.000Z | 2022-02-12T11:55:49.000Z | Tree Algorithms/Distance Queries.cpp | DecSP/cses-downloader | 12a8f37665a33f6f790bd2c355f84dea8a0e332c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adjList;
int up[(int)(2e5+1.5)][20] {};
vector<int>tin,tout,d;
int n,q,timer;
void dfs(int curr,int pre){
tin[curr]=timer++;
up[curr][0]=pre;
for (int i=1;i<20;++i){
up[curr][i]=up[up[curr][i-1]][i-1];
}
for (int &v:adjList[curr]){
if (v==pre) continue;
d[v]=d[curr]+1;
dfs(v,curr);
}
tout[curr]=timer++;
}
bool is_ancestor(int par,int child){
return tin[par]<=tin[child]&&tout[par]>=tout[child];
}
int lca(int n1,int n2){
if (is_ancestor(n1,n2)) return n1;
if (is_ancestor(n2,n1)) return n2;
for (int i=19;i>=0;--i){
if (!is_ancestor(up[n1][i],n2)) n1=up[n1][i];
}
return up[n1][0];
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
cin>>n>>q;
adjList.assign(n,vector<int>());
tin.assign(n,-1);
tout.assign(n,-1);
d.assign(n,-1);
d[0]=0;
timer=0;
for (int i=1;i<n;++i){
int a,b;cin>>a>>b;--a;--b;
adjList[a].push_back(b);
adjList[b].push_back(a);
}
dfs(0,0);
for (int i=0;i<q;++i){
int a,b;
cin>>a>>b;--a;--b;
cout<<d[a]+d[b]-2*d[lca(a,b)]<<'\n';
}
return 0;
} | 19.087719 | 53 | 0.579963 |
3d5b8c15d444b1fe8d4086f4a81a95f4f38fec7f | 1,718 | cpp | C++ | plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 39 | 2015-01-26T16:18:43.000Z | 2021-12-20T23:36:41.000Z | plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 1,248 | 2019-02-21T19:32:09.000Z | 2022-03-29T16:50:04.000Z | plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp | anastasia143/qreal | 9bd224b41e569c9c50ab88848a5746a010c65ad7 | [
"Apache-2.0"
] | 58 | 2015-03-03T12:57:28.000Z | 2020-05-09T15:54:42.000Z | /* Copyright 2007-2015 QReal Research Group
*
* 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 "kitBase/blocksBase/common/getButtonCodeBlock.h"
#include <utils/abstractTimer.h>
#include <kitBase/robotModel/robotParts/button.h>
#include <kitBase/robotModel/robotModelUtils.h>
using namespace kitBase::blocksBase::common;
using namespace kitBase::robotModel;
GetButtonCodeBlock::GetButtonCodeBlock(RobotModelInterface &robotModel)
: WaitBlock(robotModel)
{
}
void GetButtonCodeBlock::run()
{
mButtons.clear();
for (const PortInfo &port : mRobotModel.availablePorts()) {
const robotParts::Button *button = RobotModelUtils::findDevice<robotParts::Button>(mRobotModel, port.name());
if (button) {
mButtons << button;
}
}
mActiveWaitingTimer->start();
}
void GetButtonCodeBlock::timerTimeout()
{
for (const robotParts::Button *button : mButtons) {
if (button->lastData()) {
returnCode(button->code());
return;
}
}
if (!boolProperty("Wait")) {
returnCode(-1);
}
}
DeviceInfo GetButtonCodeBlock::device() const
{
return DeviceInfo();
}
void GetButtonCodeBlock::returnCode(int code)
{
evalCode(stringProperty("Variable") + " = " + QString::number(code));
stop();
}
| 26.030303 | 111 | 0.735157 |
3d5e27cb374a8905ccf9b4d80607ae7935995314 | 2,235 | cpp | C++ | sdlpaint/rcolor.cpp | cbries/utilities | 86ce97d2c3e0d13b9beb0fc6ec79d31945c14461 | [
"MIT"
] | 1 | 2015-02-22T17:40:23.000Z | 2015-02-22T17:40:23.000Z | sdlpaint/rcolor.cpp | cbries/utilities | 86ce97d2c3e0d13b9beb0fc6ec79d31945c14461 | [
"MIT"
] | null | null | null | sdlpaint/rcolor.cpp | cbries/utilities | 86ce97d2c3e0d13b9beb0fc6ec79d31945c14461 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2007 Christian B. Ries
* License: MIT
* Website: https://github.com/cbries/utilities
*/
#include "rcolor.h"
RColor::RColor()
{
setType( COLOR );
}
RColor::RColor( const SDL_Surface * surface,
int xpos, int ypos,
int width, int height )
: RButton( surface, xpos, ypos, width, height )
{
setType( COLOR );
}
RColor::~RColor()
{
}
void RColor::draw()
{
SDL_Rect clip;
clip.x = x();
clip.y = y();
clip.w = width();
clip.h = height();
SDL_SetClipRect((SDL_Surface*)surface(), &clip);
if( _state == NOTACTIVE )
{
boxRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, _r, _g, _b, 255 );
rectangleRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 2, x_end(), y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 1, x_end(), y_end() - 1, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 0, x_end(), y_end() - 0, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 1, y() + 2, x_end() - 1, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 0, y() + 2, x_end() - 0, y_end() - 2, 0, 0, 0, 255 );
}
if( _state == ACTIVE )
{
boxRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, _r, _g, _b, 255 );
rectangleRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 0, x_end() - 3, y() + 0, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 1, x_end() - 3, y() + 1, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 2, x_end() - 3, y() + 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 0, y(), x() + 0, y_end() - 3, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 1, y(), x() + 1, y_end() - 3, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y(), x() + 2, y_end() - 3, 0, 0, 0, 255 );
}
SDL_UpdateRect((SDL_Surface*)surface(), x(), y(), width(), height() );
}
| 33.358209 | 102 | 0.536913 |
3d5fbc8152f3d044e3385f2629cd0cc7640b2fc8 | 110 | hpp | C++ | include/lib_B/lib_B.hpp | dep-heaven/lib_B | c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd | [
"MIT"
] | null | null | null | include/lib_B/lib_B.hpp | dep-heaven/lib_B | c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd | [
"MIT"
] | null | null | null | include/lib_B/lib_B.hpp | dep-heaven/lib_B | c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd | [
"MIT"
] | null | null | null | #ifndef LIB_B_HPP
#define LIB_B_HPP
namespace lib_B {
int fn_b();
} // namespace lib_B
#endif // LIB_B_HPP | 11 | 20 | 0.718182 |
87d1f145000427ebc429b437c62dd6992a6a9d1e | 2,299 | cpp | C++ | src/_cxx11/_semaphore.cpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | 11 | 2015-10-06T21:00:30.000Z | 2021-07-27T05:54:44.000Z | src/_cxx11/_semaphore.cpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | null | null | null | src/_cxx11/_semaphore.cpp | ombre5733/weos | 2c3edef042fa80baa7c8fb968ba3104b7119cf2d | [
"BSD-2-Clause"
] | 1 | 2015-10-03T03:51:28.000Z | 2015-10-03T03:51:28.000Z | /*******************************************************************************
WEOS - Wrapper for embedded operating systems
Copyright (c) 2013-2016, Manuel Freiberger
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "_semaphore.hpp"
WEOS_BEGIN_NAMESPACE
semaphore::~semaphore()
{
}
void semaphore::post()
{
std::lock_guard<std::mutex> lock(m_mutex);
m_mutex.lock();
++m_value;
m_mutex.unlock();
m_conditionVariable.notify_one();
}
void semaphore::wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_conditionVariable.wait(lock, [this] { return m_value != 0; });
--m_value;
}
bool semaphore::try_wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_value > 0)
{
--m_value;
return true;
}
else
{
return false;
}
}
semaphore::value_type semaphore::value() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_value;
}
WEOS_END_NAMESPACE
| 30.653333 | 80 | 0.680731 |
87d364317e653c45917da8b33c7adfcf1e21c6ab | 10,868 | cpp | C++ | cobs/construction/compact_index.cpp | karasikov/cobs | 63ba36f042c59e14f721018e68e36e20a8bf4936 | [
"MIT"
] | null | null | null | cobs/construction/compact_index.cpp | karasikov/cobs | 63ba36f042c59e14f721018e68e36e20a8bf4936 | [
"MIT"
] | null | null | null | cobs/construction/compact_index.cpp | karasikov/cobs | 63ba36f042c59e14f721018e68e36e20a8bf4936 | [
"MIT"
] | null | null | null | /*******************************************************************************
* cobs/construction/compact_index.cpp
*
* Copyright (c) 2018 Florian Gauger
*
* All rights reserved. Published under the MIT License in the LICENSE file.
******************************************************************************/
#include <cobs/construction/classic_index.hpp>
#include <cobs/construction/compact_index.hpp>
#include <cobs/file/classic_index_header.hpp>
#include <cobs/file/compact_index_header.hpp>
#include <cobs/file/kmer_buffer_header.hpp>
#include <cobs/util/calc_signature_size.hpp>
#include <cobs/util/file.hpp>
#include <iomanip>
#include <tlx/die.hpp>
#include <tlx/math/div_ceil.hpp>
#include <tlx/math/round_to_power_of_two.hpp>
#include <tlx/math/round_up.hpp>
#include <tlx/string/format_iec_units.hpp>
namespace cobs {
bool combine_classic_index(const fs::path& in_dir, const fs::path& out_dir,
size_t mem_bytes, size_t num_threads) {
bool all_combined = true;
fs::path result_file;
for (fs::directory_iterator it(in_dir), end; it != end; it++) {
if (fs::is_directory(it->path())) {
bool this_combined = classic_combine(
in_dir / it->path().filename(),
out_dir / it->path().filename(),
result_file,
mem_bytes, num_threads);
if (!this_combined)
all_combined = false;
}
}
if (!gopt_keep_temporary) {
fs::remove(in_dir);
}
return all_combined;
}
void compact_combine_into_compact(
const fs::path& in_dir, const fs::path& out_file,
uint64_t page_size, uint64_t memory)
{
std::vector<fs::path> paths;
fs::recursive_directory_iterator it(in_dir), end;
std::copy_if(it, end, std::back_inserter(paths), [](const auto& p) {
return file_has_header<ClassicIndexHeader>(p);
});
std::sort(paths.begin(), paths.end());
unsigned term_size = 0;
uint8_t canonicalize = 0;
std::vector<CompactIndexHeader::parameter> parameters;
std::vector<std::string> file_names;
LOG1 << "Combine Compact Index from " << paths.size() << " Classic Indices";
for (size_t i = 0; i < paths.size(); i++) {
auto h = deserialize_header<ClassicIndexHeader>(paths[i]);
parameters.push_back({ h.signature_size(), h.num_hashes() });
file_names.insert(file_names.end(),
h.file_names().begin(), h.file_names().end());
if (term_size == 0) {
term_size = h.term_size();
canonicalize = h.canonicalize();
}
die_unequal(term_size, h.term_size());
die_unequal(canonicalize, h.canonicalize());
LOG1 << i << ": " << h.row_bits() << " documents "
<< tlx::format_iec_units(fs::file_size(paths[i])) << 'B'
<< " row_size " << h.row_size()
<< " : " << paths[i].string();
if (i < paths.size() - 1) {
die_unless(h.row_size() == page_size);
}
else {
die_unless(h.row_size() <= page_size);
}
}
Timer t;
CompactIndexHeader h(term_size, canonicalize, parameters,
file_names, page_size);
std::ofstream ofs;
serialize_header(ofs, out_file, h);
for (const auto& p : paths) {
std::ifstream ifs;
uint64_t row_size =
deserialize_header<ClassicIndexHeader>(ifs, p).row_size();
if (row_size == page_size) {
// row_size is page_size -> direct copy
t.active("copy");
ofs << ifs.rdbuf();
t.stop();
}
else {
// row_size needs to be padded to page_size
size_t batch_size = memory / 2 / page_size;
uint64_t data_size = get_stream_size(ifs);
batch_size = std::min(
batch_size, tlx::div_ceil(data_size, page_size));
sLOG0 << "batch_size" << batch_size;
std::vector<char> buffer(batch_size* page_size);
die_unless(data_size % row_size == 0);
while (data_size > 0) {
t.active("read");
size_t this_batch = std::min(batch_size, data_size / row_size);
ifs.read(buffer.data(), this_batch * row_size);
die_unequal(this_batch * row_size,
static_cast<size_t>(ifs.gcount()));
data_size -= this_batch * row_size;
t.active("expand");
// expand each row_size to page_size, start at the back
for (size_t b = this_batch; b != 0; ) {
--b;
std::copy_backward(
buffer.begin() + b * row_size,
buffer.begin() + (b + 1) * row_size,
buffer.begin() + b * page_size + row_size);
std::fill(
buffer.begin() + b * page_size + row_size,
buffer.begin() + (b + 1) * page_size,
0);
}
t.active("write");
ofs.write(buffer.data(), this_batch * page_size);
t.stop();
}
}
ifs.close();
if (!gopt_keep_temporary) {
fs::remove(p);
fs::remove(p.parent_path());
}
}
if (!gopt_keep_temporary) {
fs::remove(in_dir);
}
t.print("compact_combine_into_compact()");
}
void compact_construct(const fs::path& in_dir, const fs::path& index_file,
const fs::path& tmp_path,
CompactIndexParameters params) {
size_t iteration = 1;
// read file list, sort by size
DocumentList doc_list(in_dir);
doc_list.sort_by_size();
if (params.page_size == 0) {
params.page_size = tlx::round_up_to_power_of_two(
static_cast<size_t>(std::sqrt(doc_list.size() / 8)));
params.page_size = std::max<uint64_t>(params.page_size, 8);
params.page_size = std::min<uint64_t>(params.page_size, 4096);
}
size_t num_pages = tlx::div_ceil(doc_list.size(), 8 * params.page_size);
size_t num_threads = params.num_threads;
if (num_threads > num_pages) {
// use div_floor() instead
num_threads = doc_list.size() / (8 * params.page_size);
}
if (num_threads == 0) num_threads = 1;
LOG1 << "Compact Index Parameters:\n"
<< " term_size: " << params.term_size << '\n'
<< " number of documents: " << doc_list.size() << '\n'
<< " num_hashes: " << params.num_hashes << '\n'
<< " false_positive_rate: " << params.false_positive_rate << '\n'
<< " page_size: " << params.page_size << " bytes"
<< " = " << params.page_size * 8 << " documents" << '\n'
<< " num_pages: " << num_pages << '\n'
<< " mem_bytes: " << params.mem_bytes
<< " = " << tlx::format_iec_units(params.mem_bytes) << 'B' << '\n'
<< " num_threads: " << num_threads;
size_t total_size = 0;
doc_list.process_batches(
8 * params.page_size,
[&](size_t /* batch_num */, const std::vector<DocumentEntry>& files,
fs::path /* out_file */) {
size_t max_doc_size = 0;
for (const DocumentEntry& de : files) {
max_doc_size = std::max(
max_doc_size, de.num_terms(params.term_size));
}
size_t signature_size = calc_signature_size(
max_doc_size, params.num_hashes, params.false_positive_rate);
total_size += params.page_size * signature_size;
});
LOG1 << " total_size: " << tlx::format_iec_units(total_size) << 'B';
// process batches and create classic indexes for each batch
doc_list.process_batches_parallel(
8 * params.page_size, num_threads,
[&](size_t batch_num, const std::vector<DocumentEntry>& files,
fs::path /* out_file */) {
size_t max_doc_size = 0;
for (const DocumentEntry& de : files) {
max_doc_size = std::max(
max_doc_size, de.num_terms(params.term_size));
}
size_t signature_size = calc_signature_size(
max_doc_size, params.num_hashes, params.false_positive_rate);
size_t docsize_roundup = tlx::round_up(files.size(), 8);
if (max_doc_size == 0)
return;
ClassicIndexParameters classic_params;
classic_params.term_size = params.term_size;
classic_params.canonicalize = params.canonicalize;
classic_params.num_hashes = params.num_hashes;
classic_params.false_positive_rate = params.false_positive_rate;
classic_params.signature_size = signature_size;
classic_params.mem_bytes = params.mem_bytes / num_threads;
classic_params.num_threads =
tlx::div_ceil(params.num_threads, num_threads);
classic_params.log_prefix
= "[" + pad_index(batch_num, 2)
+ "/" + pad_index(num_pages, 2) + "] ";
LOG1 << "Classic Sub-Index Parameters: "
<< classic_params.log_prefix << '\n'
<< " number of documents: " << files.size() << '\n'
<< " maximum document size: " << max_doc_size << '\n'
<< " signature_size: " << signature_size << '\n'
<< " sub-index size: "
<< (docsize_roundup / 8 * signature_size) << " = "
<< tlx::format_iec_units(docsize_roundup / 8 * signature_size)
<< '\n'
<< " mem_bytes: " << classic_params.mem_bytes << '\n'
<< " num_threads: " << classic_params.num_threads;
DocumentList batch_list(files);
fs::path classic_dir = tmp_path / pad_index(iteration);
classic_construct_from_documents(
batch_list, classic_dir / pad_index(batch_num), classic_params);
});
// combine classic indexes
while (!combine_classic_index(tmp_path / pad_index(iteration),
tmp_path / pad_index(iteration + 1),
params.mem_bytes, params.num_threads)) {
iteration++;
}
// combine classic indexes into one compact index
compact_combine_into_compact(
tmp_path / pad_index(iteration + 1),
index_file,
params.page_size, params.mem_bytes);
// cleanup: this will fail if not _all_ temporary files are removed
if (!gopt_keep_temporary) {
fs::remove(tmp_path);
}
}
} // namespace cobs
/******************************************************************************/
| 36.592593 | 80 | 0.544442 |
87d7b5b251da24ca870ee9f024016db0aed12c78 | 42,165 | cpp | C++ | MatlabToolbox/external/tinyXml/tinyxml2_wrap.cpp | sigurdal/AutoActive-Matlab-toolbox | 2fad294d62f91ff192eb2d7c6980bc41cffef0f9 | [
"Apache-2.0"
] | 1 | 2020-07-03T10:19:48.000Z | 2020-07-03T10:19:48.000Z | MatlabToolbox/external/tinyXml/tinyxml2_wrap.cpp | SINTEF/AutoActive-core | 3e2cb7bbbae8c6b5f812cf85795d3daf738f4633 | [
"Apache-2.0"
] | null | null | null | MatlabToolbox/external/tinyXml/tinyxml2_wrap.cpp | SINTEF/AutoActive-core | 3e2cb7bbbae8c6b5f812cf85795d3daf738f4633 | [
"Apache-2.0"
] | 1 | 2022-03-29T11:10:39.000Z | 2022-03-29T11:10:39.000Z | /*
* XML serializing/deserializing of MATLAB arrays
* author: Ladislav Dobrovsky (dobrovsky@fme.vutbr.cz, ladislav.dobrovsky@gmail.com)
*
* last change: 2015-03-17
*
*
* 2015-02-28 Peter van den Biggelaar Handle structure similar to xml_load from Matlab Central
* 2015-03-05 Ladislav Dobrovsky Function handles load/save (str2func, func2str)
* 2015-03-05 Peter van den Biggelaar Support N-dimension arrays
* 2015-03-06 Peter van den Biggelaar Support complex doubles and sparse matrices
* 2015-03-07 Peter van den Biggelaar updated tinyxml2.h from version 0.9.4 to version 2.2.0 and add tinyxml2.cpp from https://github.com/leethomason/tinyxml2
* 2015-03-08 Peter van den Biggelaar 0.9.0: Support int64 and uint64 classes
* 2015-03-11 Peter van den Biggelaar 0.9.1: Support Inf and NaN
* 2015-03-13 Peter van den Biggelaar 0.9.2: Add MsgId's; put comment after header;
* Print Inf and NaN on Unix similar as Windows
* 2015-03-18 Peter van den Biggelaar 0.10.0: Fix roundtrip issue with empty cell and struct elements
* Allow 'on' and 'off' for OPTIONS
* Allow name input for root element
* 2015-03-28 Peter van den Biggelaar 0.10.1: Build with version 3.0.0 of tinyxml2.cpp from https://github.com/leethomason/tinyxml2
* Include function name when returning version number
* 2015-04-03 Ladislav Dobrovsky 1.0.0: Refactoring
* [DISABLED, not working] base64 coding of binary data (optional)
*/
#define MEXFUNCNAME "tinyxml2_wrap"
#define TIXML2_WRAP_MAJOR_VERSION "1"
#define TIXML2_WRAP_MINOR_VERSION "0"
#define TIXML2_WRAP_PATCH_VERSION "0"
#include "tinyxml2.h"
/*
* uncomment to fix next compilation error on 32bit Windows:
* error C2371: 'char16_t' : redefinition; different basic types
*/
// #ifdef _CHAR16T
// #define CHAR16_T
// #endif
#include <mex.h>
#include <string>
#include <sstream>
#include <iostream>
#include <math.h> // fabs
/*#include <b64/encode.h>
#include <b64/decode.h>
*/
/*
* Assume 32 bit addressing for old Matlab
* See MEX option "compatibleArrayDims" for MEX in Matlab >= 7.7.
*/
#ifndef MWSIZE_MAX
typedef int mwSize;
typedef int mwIndex;
#endif
// format modifier for scanning and printing size_t
#ifdef _WIN64
#define PR_SIZET "ll"
#else
#define PR_SIZET "l"
#endif
#ifdef _WIN32
#define strcasecmp(x,y) _stricmp((x),(y))
#endif
using namespace tinyxml2;
using namespace std;
#define MSGID_INPUT MEXFUNCNAME ":InputFail"
#define MSGID_READ MEXFUNCNAME ":ReadFail"
#define MSGID_WRITE MEXFUNCNAME ":WriteFail"
#define MSGID_CLASSID MEXFUNCNAME ":ClassIdFail"
#define MSGID_CALLMATLAB MEXFUNCNAME ":CallMatlabFail"
#define MSGID_DEVEL MEXFUNCNAME ":RuntimeError_Devel"
#include "exportoptions.h"
#include "misc_utils.h"
XMLNode * addAny(XMLNode *parent, const mxArray *data_MA, const char *nodeName, ExportOptions& options);
mxArray * extractAny(const XMLElement *element);
template<typename T>
XMLNode * add(XMLNode *parent, T const * const data, const mxArray *data_MA, mxClassID classID, const char *nodeName, ExportOptions &options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(data_MA);
const mwSize *dims = mxGetDimensions(data_MA);
size_t numel = mxGetNumberOfElements(data_MA);
if(numel!=1 && options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
{
element->SetAttribute("type", mxGetClassName(data_MA));
}
/*if(options.encodeBase64)
{
element->SetAttribute("encoding", "base64");
}*/
const char *frmStr = Utils::getFormatingString(classID, mxGetClassName(data_MA), options.singleFloatingFormat, options.doubleFloatingFormat);
if(numel)
{
/*if(options.encodeBase64)
{
stringstream ssIn, ssOut;
ssIn.write(reinterpret_cast<const char*>(data), sizeof(T)*numel);
options.encode64(ssIn, ssOut);
element->InsertFirstChild( doc->NewText(ssOut.str().c_str()) );
}
else*/
{
string str;
static char format[256];
sprintf(format, "%s ", frmStr);
static char tmpS[1024];
for(mwSize i=0; i<numel; i++)
{
// fill tmpS with data[i] including NaN and Inf support
if(classID==mxDOUBLE_CLASS || classID==mxSINGLE_CLASS)
{
double value = (double)data[i]; // cast to double
if(!mxIsFinite(value))
{
if(mxIsNaN(value))
sprintf(tmpS, "NaN ");
else if(mxIsInf(value))
{
if(value>0)
sprintf(tmpS, "Inf ");
else
sprintf(tmpS, "-Inf ");
}
}
else
sprintf(tmpS, format, data[i]);
}
else
sprintf(tmpS, format, data[i]);
if(i+1==numel && *tmpS)
// remove end space from last element
*(tmpS+strlen(tmpS)-1) = '\0';
str += tmpS;
}
// [NOTE]: although Linux supports printing NaN and Inf, the above
// code is a factor 3 faster than using Linux sprintf. (PvdB)
element->InsertFirstChild( doc->NewText(str.c_str()) );
}
}
else
{ // empty
element->InsertFirstChild( doc->NewText("") );
}
return element;
}
XMLNode * addStruct(XMLNode *parent, const mxArray *aStruct, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(aStruct);
const mwSize *dims = mxGetDimensions(aStruct);
size_t numel = mxGetNumberOfElements(aStruct);
if(numel!=1 && options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
{
element->SetAttribute("type", mxGetClassName(aStruct));
}
if(numel==0)
return element; // nothing to do here...
int nFields = mxGetNumberOfFields(aStruct);
XMLElement *fieldElement=0;
for(unsigned idx=0; idx < numel; idx++) // loop over indexes
{
for(int fN = 0; fN < nFields; fN++) // loop over fields
{
const char *fieldName = mxGetFieldNameByNumber(aStruct, fN);
mxArray *field = mxGetField(aStruct, idx, fieldName);
if(field)
{
fieldElement = addAny(element, field, fieldName, options)->ToElement();
if(options.storeIndexes)
fieldElement->SetAttribute("idx", idx+1);
}
}
}
return element;
}
XMLNode * addCell(XMLNode *parent, const mxArray *aCell, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(aCell);
const mwSize *dims = mxGetDimensions(aCell);
size_t numel = mxGetNumberOfElements(aCell);
if(numel!=1 && options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
{
element->SetAttribute("type", mxGetClassName(aCell));
}
if(numel==0)
return element; // nothing to do here...
XMLElement *cellElement=0;
for(unsigned idx=0; idx < numel; idx++)
{
mxArray *cellValue = mxGetCell(aCell, idx);
if(cellValue)
{
cellElement = addAny(element, cellValue, "item", options)->ToElement();
if(options.storeIndexes)
cellElement->SetAttribute("idx", idx+1);
}
}
return element;
}
XMLNode *addChar(XMLNode *parent, char const * const data, const mxArray * aString, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(aString);
const mwSize *dims = mxGetDimensions(aString);
if(options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
{
element->SetAttribute("type", mxGetClassName(aString));
}
char *stringCopy = mxArrayToString(aString);
//printf("string len = %u ; m = %u, n = %u; content=\"%c\"\n", len, (unsigned)mxGetM(aString), (unsigned)mxGetN(aString), data[0]/*string(data, len).c_str()*/);
element->InsertFirstChild( doc->NewText( stringCopy ) );
mxFree(stringCopy);
return element;
}
XMLNode *addFunctionHandle(XMLNode *parent, const mxArray *fHandle, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
if(options.storeClass)
{
element->SetAttribute("type", mxGetClassName(fHandle));
}
else
{
mexWarnMsgIdAndTxt(MSGID_WRITE, "function handle being saved without class specification, will become a string!\n");
}
mxArray *lhs[1];
mxArray *rhs[1] = {const_cast<mxArray*>(fHandle)};
if(mexCallMATLAB(1, lhs, 1, rhs, "func2str") != 0)
mexWarnMsgIdAndTxt(MSGID_CALLMATLAB, "converting function handle to string failed\n");
char *stringCopy=mxArrayToString(lhs[0]);
element->InsertFirstChild( doc->NewText( stringCopy ) );
mxFree(stringCopy);
return element;
}
XMLNode * addComplex(XMLNode *parent, const mxArray *aComplex, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(aComplex);
const mwSize *dims = mxGetDimensions(aComplex);
size_t numel = mxGetNumberOfElements(aComplex);
if(numel!=1 && options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
element->SetAttribute("type", "complex");
else
mexWarnMsgIdAndTxt(MSGID_WRITE, "complex being saved without class specification, will become a cell array with two elements!\n");
mxArray *theMatrix = mxDuplicateArray(aComplex);
void *pr = mxGetData(theMatrix);
void *pi = mxGetImagData(theMatrix);
// add real part; temporary set imag data to NULL
mxSetImagData(theMatrix, NULL);
XMLElement * realElement = addAny(element, theMatrix, "item", options)->ToElement();
if(options.storeIndexes)
realElement->SetAttribute("idx", 1);
// add imaginary part; temporary set real data point to imag data
mxSetData(theMatrix, pi);
XMLElement * imagElement = addAny(element, theMatrix, "item", options)->ToElement();
if(options.storeIndexes)
imagElement->SetAttribute("idx", 2);
// restore original pointers to real and imag data and safely destroy
mxSetData(theMatrix, pr);
mxSetImagData(theMatrix, pi);
mxDestroyArray(theMatrix);
return element;
}
XMLNode * addSparse(XMLNode *parent, const mxArray *aSparse, const char *nodeName, ExportOptions& options)
{
XMLDocument *doc = parent->GetDocument();
XMLElement *element = doc->NewElement(nodeName);
parent->InsertEndChild( element );
mwSize ndim = mxGetNumberOfDimensions(aSparse);
const mwSize *dims = mxGetDimensions(aSparse);
if(options.storeSize)
{
char * sizeStr = Utils::createSizeStr(ndim, dims);
element->SetAttribute("size", sizeStr);
mxFree(sizeStr);
}
if(options.storeClass)
element->SetAttribute("type", "sparse");
else
mexWarnMsgIdAndTxt(MSGID_WRITE, " sparse being saved without class specification, will become a cell array with three elements!\n");
// determine indexes of nonzero values
mxArray * plhs[3];
mxArray * prhs[1] = {const_cast<mxArray*>(aSparse)};
if(mexCallMATLAB(3, plhs, 1, prhs, "find") != 0)
mexErrMsgIdAndTxt(MSGID_CALLMATLAB, "determine indexes of sparse failed");
mxArray * aRows = plhs[0];
mxArray * aColumns = plhs[1];
mxArray * aValues = plhs[2];
XMLElement * doubleElement = 0;
// add row indexes
doubleElement = addAny(element, aRows, "item", options)->ToElement();
if(options.storeIndexes)
doubleElement->SetAttribute("idx", 1);
// add column indexes
doubleElement = addAny(element, aColumns, "item", options)->ToElement();
if(options.storeIndexes)
doubleElement->SetAttribute("idx", 2);
// add values
doubleElement = addAny(element, aValues, "item", options)->ToElement();
if(options.storeIndexes)
doubleElement->SetAttribute("idx", 3);
return element;
}
XMLNode * addAny(XMLNode *parent, const mxArray *data_MA, const char *nodeName, ExportOptions& options)
{
void const * const data=mxGetData(data_MA);
mxClassID classID = mxGetClassID(data_MA);
if(mxIsSparse(data_MA)) // check for sparse first, because sparse can also be complex
return addSparse(parent, data_MA, nodeName, options);
if(mxIsComplex(data_MA))
return addComplex(parent, data_MA, nodeName, options);
switch(classID)
{
case mxCELL_CLASS: return addCell(parent, data_MA, nodeName, options);
case mxSTRUCT_CLASS: return addStruct(parent, data_MA, nodeName, options);
case mxLOGICAL_CLASS: return add(parent, (mxLogical*)data, data_MA, classID, nodeName, options);
case mxDOUBLE_CLASS: return add(parent, (double*)data, data_MA, classID, nodeName, options);
case mxSINGLE_CLASS: return add(parent, (float*)data, data_MA, classID, nodeName, options);
case mxINT8_CLASS: return add(parent, (signed char*)data, data_MA, classID, nodeName, options);
case mxUINT8_CLASS: return add(parent, (unsigned char*)data, data_MA, classID, nodeName, options);
case mxINT16_CLASS: return add(parent, (short*)data, data_MA, classID, nodeName, options);
case mxUINT16_CLASS: return add(parent, (unsigned short*)data, data_MA, classID, nodeName, options);
case mxINT32_CLASS: return add(parent, (int*)data, data_MA, classID, nodeName, options);
case mxUINT32_CLASS: return add(parent, (unsigned int*)data, data_MA, classID, nodeName, options);
case mxINT64_CLASS: return add(parent, (long long*)data, data_MA, classID, nodeName, options);
case mxUINT64_CLASS: return add(parent, (unsigned long long*)data, data_MA, classID, nodeName, options);
case mxCHAR_CLASS: return addChar(parent, (const char * const)data, data_MA, nodeName, options);
case mxFUNCTION_CLASS: return addFunctionHandle(parent, data_MA, nodeName, options);
default:
{
mexErrMsgIdAndTxt(MSGID_CLASSID, "unsupported class to save in xml format: %s\n", mxGetClassName(data_MA));
}
}
return NULL;
}
// string
mxArray *extractChar(const XMLElement *element)
{
mxArray *aString = mxCreateString(element->GetText());
const char *sizeAttribute=element->Attribute( "size" );
if(sizeAttribute && element->GetText())
{
mwSize ndim=0;
size_t numel=0;
mwSize *dims = Utils::getDimensions(sizeAttribute, &ndim, &numel);
size_t len = mxGetNumberOfElements(aString);
// reshape into specified size
// note: character arrays may look a bit weird in the xml-file
// because strings are stored column-wise. This functionality
// is equivalent with xml_save/xml_load
#ifdef _WIN64
// TODO: Windows 64 bit has a problem with the if statement
// Adding next dummy mexPrintf here helps!!!
mexPrintf("");
#endif
if ( len != numel )
{
// mexPrintf("len=%lu numel=%lu s=%s\n", (size_t)len, (size_t)numel, element->GetText());
mexErrMsgIdAndTxt(MSGID_READ, "number of characters does not match specified size");
}
mxSetDimensions(aString, dims, ndim);
mxFree(dims);
}
return aString;
}
// structures
// mxArray *mxCreateStructMatrix(mwSize m, mwSize n, int nfields, const char **fieldnames);
mxArray *extractStruct(const XMLElement *element)
{
mwSize ndim=0;
size_t numel=0;
const char *sizeAttribute=element->Attribute( "size" );
mwSize *dims = Utils::getDimensions(sizeAttribute, &ndim, &numel);
if(!sizeAttribute)
{
// determine size by counting children and checking "idx" attribute
numel=0;
const XMLElement *structElement = element->FirstChildElement();
while(structElement)
{
unsigned idx=(unsigned)numel+1;
structElement->QueryUnsignedAttribute("idx", &idx); // if attribute does not exists it will not change value of idx
numel=idx;
structElement = structElement->NextSiblingElement();
}
dims[0] = 1; // 1 row
dims[1] = (mwSize)numel; // numel columns
}
mxArray *theStruct = mxCreateStructArray(ndim, dims, 0, 0);
mxFree(dims);
if(!theStruct)
mexErrMsgIdAndTxt(MSGID_READ, "creating structure array failed.");
if(numel)
{
unsigned *idx = NULL;
unsigned max_idx = 1;
const XMLElement *structElement=element->FirstChildElement();
while(structElement)
{
const char *name = structElement->Value();
if(!name)
name="NO_NAME_STRUCT_FIELD";
// add fieldname or increment idx for existing fieldname
int fieldNumber = mxGetFieldNumber(theStruct, name);
if(fieldNumber<0)
{ // field does not exist; add field and initialize idx for this field
fieldNumber=mxAddField(theStruct, name);
if(fieldNumber<0)
mexErrMsgIdAndTxt(MSGID_READ, "can't add field");
// (re)allocate space for tracking indexes for each field
idx = (unsigned *)mxRealloc(idx, sizeof(unsigned)*(fieldNumber+1));
idx[fieldNumber] = 1;
}
else
{ // fieldname already exists
// increment idx of this field
idx[fieldNumber]++;
// keep track of maximum idx
if(idx[fieldNumber]>max_idx)
max_idx = idx[fieldNumber];
}
// get value of "idx" attribute. idx will be unchanged when attribute is not defined
structElement->QueryUnsignedAttribute("idx", &(idx[fieldNumber]));
if(idx[fieldNumber]>numel)
mexErrMsgIdAndTxt(MSGID_READ, "element idx > struct length");
// set field value
mxArray *fieldValue = extractAny(structElement);
if(fieldValue)
mxSetFieldByNumber(theStruct, idx[fieldNumber]-1, fieldNumber, fieldValue);
else
mexWarnMsgIdAndTxt(MSGID_READ, "struct field %s (idx %d) is corrupted\n", name, idx[fieldNumber]);
structElement = structElement->NextSiblingElement();
}
if(max_idx<numel && !sizeAttribute)
{
// remove extra columns
mxSetN(theStruct, max_idx);
}
mxFree(idx);
}
return theStruct;
}
// cells
mxArray *extractCell(const XMLElement *element)
{
mwSize ndim=0;
size_t numel=0;
const char *sizeAttribute=element->Attribute( "size" );
mwSize *dims = Utils::getDimensions(sizeAttribute, &ndim, &numel);
// count cells
if(!sizeAttribute)
{
unsigned len2=0;
const XMLElement *cellElement = element->FirstChildElement("item");
while(cellElement)
{
unsigned idx=len2+1; // idx range: 1...N
cellElement->QueryUnsignedAttribute("idx", &idx);
len2++;
if(idx>len2+1)
len2=idx;
cellElement = cellElement->NextSiblingElement("item");
}
if(numel != len2)
{
ndim = 2;
dims[0] = 1;
dims[1] = len2;
numel = len2;
if(sizeAttribute)
mexWarnMsgIdAndTxt(MSGID_READ, "cell array size specified, but the actual count differs\n");
}
}
mxArray *theCell = mxCreateCellArray(ndim, dims);
mxFree(dims);
if(numel)
{
unsigned naturalOrder=0; // used if idx is not specified
const XMLElement *cellElement = element->FirstChildElement("item");
while(cellElement)
{
unsigned idx=naturalOrder+1; // idx range: 1...N
cellElement->QueryUnsignedAttribute("idx", &idx);
if(idx>numel)
mexErrMsgIdAndTxt(MSGID_READ, "element idx > cell length");
mxArray *cellValue = extractAny(cellElement);
if(cellValue)
mxSetCell(theCell, idx-1, cellValue);
else
mexWarnMsgIdAndTxt(MSGID_READ, "cell (idx %d) is corrupted\n", idx);
cellElement = cellElement->NextSiblingElement("item");
naturalOrder++;
}
}
return theCell;
}
template <typename T>
mxArray *extract(const XMLElement *element, mxClassID classID)
{
mwSize ndim=0;
size_t numel=0;
const char *sizeAttribute=element->Attribute( "size" );
mwSize *dims = Utils::getDimensions(sizeAttribute, &ndim, &numel);
if(!sizeAttribute)
{
// count words to determine number of values
const char *p = element->GetText();
numel = 0;
while(*p)
{
while(*p && isspace(*p)) p++; // find next non-space
if(*p) // at begin of word
numel++;
while(*p && !isspace(*p)) p++; // find next space
}
dims[0] = 1; // return row vector
dims[1] = numel;
}
mxArray *theMatrix = mxCreateNumericArray(ndim, dims, classID, mxREAL);
mxFree(dims);
if(numel)
{
T *data = (T*)mxGetData(theMatrix);
stringstream ss(element->GetText());
for(mwIndex idx=0; idx<numel; idx++)
{
if(classID == mxINT8_CLASS || classID == mxUINT8_CLASS)
{ // code path for 8bit integer number (char)
int value;
ss >> value; // string stream would extract ASCII value of a character, not whole number
data[idx] = (T)(value);
}
else
{
ss >> data[idx];
}
if(!ss.good())
{ // something went wrong
if(ss.eof() && idx+1!=numel)
{
mexWarnMsgIdAndTxt(MSGID_READ, "specified size is larger than available number of data elements eof=%d, badbit=%d\n", (int)ss.eof(), (int)ss.bad());
break;
}
if(ss.fail())
{ // check for NaN and Inf with optional sign
ss.clear();
bool negSign = false;
if(ss.unget()) // backup one character because sign may have been read succesfully
{
// check for sign character
char c;
ss.get(c);
negSign = (c=='-');
}
else
{
// backup may fail when stream starts with "nan" or "inf"
ss.clear();
}
// read 3 character and check if it is "nan" or "inf"
char buf[4];
if(ss.get(buf,4))
{
if (!strcasecmp(buf,"nan"))
{
data[idx] = (T)mxGetNaN();
}
else if (!strcasecmp(buf,"inf"))
{
if(negSign)
data[idx] = (T)(-mxGetInf());
else
data[idx] = (T)mxGetInf();
}
else
{ // other string than "nan" or "inf"
mexWarnMsgIdAndTxt(MSGID_READ, "stringstream invalid number\n");
break;
}
}
else
{ // reading 3 characters failed --> invalid number
mexWarnMsgIdAndTxt(MSGID_READ, "stringstream invalid number\n");
break;
}
}
if(ss.bad())
{
mexWarnMsgIdAndTxt(MSGID_READ, "stringstream error eof=%d, badbit=%d\n", (int)ss.eof(), (int)ss.bad());
break;
}
}
}
#ifndef _WIN32
// TODO: eofbit is not set when last character is read with ss.get on Windows
if(!ss.eof())
mexWarnMsgIdAndTxt(MSGID_READ, "stringstream has more data elements available than specified in size.\n");
#endif
}
return theMatrix;
}
// function handle
mxArray *extractFunctionHandle(const XMLElement *element)
{
mxArray *lhs[1], *rhs[1]={mxCreateString(element->GetText())};
if(mexCallMATLAB(1, lhs, 1, rhs, "str2func") !=0 )
mexWarnMsgIdAndTxt(MSGID_CALLMATLAB, "converting string to function handle failed\n");
return lhs[0];
}
// complex
mxArray *extractComplex(const XMLElement *element)
{
// read 2 child elements with real and imag values
mxArray *aRealValue;
mxArray *aImagValue;
const XMLElement *complexElement = element->FirstChildElement("item");
if(complexElement)
{
aRealValue = extractAny(complexElement);
complexElement = complexElement->NextSiblingElement("item");
}
else // create empty Matrix
aRealValue = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
if(complexElement)
{
aImagValue = extractAny(complexElement);
complexElement = complexElement->NextSiblingElement("item");
}
else // create empty Matrix
aImagValue = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
if(complexElement)
mexWarnMsgIdAndTxt(MSGID_READ, "extra elements in complex type ignored");
// check types
if(!mxIsNumeric(aRealValue))
mexErrMsgIdAndTxt(MSGID_READ, "real data of sparse must be numeric");
if(!mxIsNumeric(aImagValue))
mexErrMsgIdAndTxt(MSGID_READ, "imaginary data of sparse must be numeric");
mwSize ndim = mxGetNumberOfDimensions(aRealValue);
const mwSize *dims = mxGetDimensions(aRealValue);
size_t numel = mxGetNumberOfElements(aRealValue);
// check sizes
if(numel!=mxGetNumberOfElements(aImagValue))
mexErrMsgIdAndTxt(MSGID_READ, "number of elements in real and imaginary part is different");
if(mxGetClassID(aRealValue)!=mxGetClassID(aImagValue))
mexErrMsgIdAndTxt(MSGID_READ, "real and imaginary part must be of the same class");
mxArray * aComplex = mxCreateNumericArray(ndim, dims, mxGetClassID(aRealValue), mxCOMPLEX);
// copy pointers to the data
mxFree(mxGetPr(aComplex));
mxSetPr(aComplex, mxGetPr(aRealValue));
mxSetPr(aRealValue, NULL);
mxDestroyArray(aRealValue);
mxFree(mxGetPi(aComplex));
mxSetPi(aComplex, mxGetPr(aImagValue));
mxSetPr(aImagValue, NULL);
mxDestroyArray(aImagValue);
return aComplex;
}
// sparse
mxArray *extractSparse(const XMLElement *element)
{
mwSize ndim=0;
size_t numel=0;
const char *sizeAttribute=element->Attribute( "size" );
mwSize *dims = Utils::getDimensions(sizeAttribute, &ndim, &numel);
if(ndim>2)
mexErrMsgIdAndTxt(MSGID_READ, "Only 2-D supported for sparse");
// read 3 child elements with rows, colums, and values
mxArray *aRows;
mxArray *aColumns;
mxArray *aValues;
const XMLElement *sparseElement = element->FirstChildElement("item");
if(sparseElement)
{
aRows = extractAny(sparseElement);
sparseElement = sparseElement->NextSiblingElement("item");
}
else // create empty Matrix
aRows = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
if(sparseElement)
{
aColumns = extractAny(sparseElement);
sparseElement = sparseElement->NextSiblingElement("item");
}
else // create empty Matrix
aColumns = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
if(sparseElement)
{
aValues = extractAny(sparseElement);
sparseElement = sparseElement->NextSiblingElement("item");
}
else // create empty Matrix
aValues = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
if(sparseElement)
mexWarnMsgIdAndTxt(MSGID_READ, "extra elements in sparse type ignored");
// check types
if(mxGetClassID(aRows) != mxDOUBLE_CLASS)
mexErrMsgIdAndTxt(MSGID_READ, "row indexes for sparse must be of type double");
if(mxGetClassID(aColumns) != mxDOUBLE_CLASS)
mexErrMsgIdAndTxt(MSGID_READ, "columns indexes for sparse must be of type double");
if(mxGetClassID(aValues) != mxDOUBLE_CLASS)
mexErrMsgIdAndTxt(MSGID_READ, "values for sparse must be of type double");
// check sizes
numel = mxGetNumberOfElements(aRows);
if(numel!=mxGetNumberOfElements(aColumns))
mexErrMsgIdAndTxt(MSGID_READ, "number of colomn indexes does not match number of row indexes");
if(numel!=mxGetNumberOfElements(aValues))
mexErrMsgIdAndTxt(MSGID_READ, "number of values does not match number of row indexes");
bool isComplex = mxIsComplex(aValues);
mxComplexity ComplexFlag = mxREAL;
if(isComplex)
ComplexFlag = mxCOMPLEX;
mwSize m = dims[0];
mwSize n = dims[1];
mxArray * aSparse = mxCreateSparse(m, n, (mwSize)numel, ComplexFlag);
if(numel)
{
// copy data
double * row = mxGetPr(aRows);
double * col = mxGetPr(aColumns);
double * pr = mxGetPr(aValues);
double * pi = NULL;
double * sr = mxGetPr(aSparse);
double * si = NULL;
mwIndex * irs = mxGetIr(aSparse);
mwIndex * jcs = mxGetJc(aSparse);
if(isComplex)
{
pi = mxGetPi(aValues);
si = mxGetPi(aSparse);
}
// fill sparse array
mwIndex k=0;
for(mwIndex j=0; j<n; j++)
{
jcs[j] = k;
while((mwIndex)(col[k])-1==j)
{
sr[k] = pr[k];
if(isComplex)
si[k] = pi[k];
irs[k] = (mwIndex)(row[k])-1;
k++;
}
}
jcs[n] = k;
/*
for(mwIndex j=0; j<numel; j++)
printf("irs[%d]=%d\n",j,irs[j]);
for(mwIndex j=0; j<numel; j++)
printf("sr[%d]=%e\n",j,sr[j]);
if(isComplex)
for(mwIndex j=0; j<numel; j++)
printf("si[%d]=%e\n",j,si[j]);
for(mwIndex j=0; j<=n; j++)
printf("jcs[%d]=%d\n",j,jcs[j]);
*/
}
// cleanup
mxDestroyArray(aRows);
mxDestroyArray(aColumns);
mxDestroyArray(aValues);
return aSparse;
}
mxArray *extractAny(const XMLElement *element)
{
const char* classStr = element->Attribute("type");
if(!classStr)
{
// have children elements -> struct or cell
if(element->FirstChildElement())
{
// we need at least 2 consequtive 'item' elements to consider the element a cell array
const XMLElement *itemElement=element->FirstChildElement("item");
if(itemElement && itemElement->NextSiblingElement("item"))
classStr="cell";
else
// otherwise it's a struct
classStr="struct";
}
else // or else it's considered a string
classStr="char";
}
else if(strcmp(classStr,"complex")==0)
return extractComplex(element);
else if(strcmp(classStr,"sparse")==0)
return extractSparse(element);
mxClassID classID = Utils::getClassByName(classStr);
switch(classID)
{
case mxCELL_CLASS: return extractCell(element);
case mxSTRUCT_CLASS: return extractStruct(element);
case mxLOGICAL_CLASS: return extract<mxLogical>(element, classID);
case mxDOUBLE_CLASS: return extract<double>(element, classID);
case mxSINGLE_CLASS: return extract<float>(element, classID);
case mxINT8_CLASS: return extract<signed char>(element, classID);
case mxUINT8_CLASS: return extract<unsigned char>(element, classID);
case mxINT16_CLASS: return extract<short>(element, classID);
case mxUINT16_CLASS: return extract<unsigned short>(element, classID);
case mxINT32_CLASS: return extract<int>(element, classID);
case mxUINT32_CLASS: return extract<unsigned int>(element, classID);
case mxINT64_CLASS: return extract<long long>(element, classID);
case mxUINT64_CLASS: return extract<unsigned long long>(element, classID);
case mxCHAR_CLASS: return extractChar(element);
case mxFUNCTION_CLASS: return extractFunctionHandle(element);
default:
{
mexErrMsgIdAndTxt(MSGID_CLASSID, "unrecognized or unsupported class: %s", classStr);
}
}
return NULL;
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
if(nlhs>1)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many output arguments\n");
if(nrhs<1)
mexErrMsgIdAndTxt(MSGID_INPUT, "Not enough input arguments: " MEXFUNCNAME "(mode, ...)\n");
const mxArray *mode_MA = prhs[0];
if(!mxIsChar(mode_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "mode must be a string\n");
char * modeString = mxArrayToString(mode_MA);
if(!modeString)
mexErrMsgIdAndTxt(MSGID_INPUT, "mode string error\n");
if(!strcmp(modeString, "save"))
{
if(nlhs>0)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many output arguments\n");
if(nrhs<3)
mexErrMsgIdAndTxt(MSGID_INPUT, "Not enough input arguments: " MEXFUNCNAME "('save', filename, data, ...)\n");
if(nrhs>5)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many input arguments\n");
const mxArray *filename_MA = prhs[1];
if(!mxIsChar(filename_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "filename must be a string\n");
char * filename = mxArrayToString(filename_MA);
if(!filename)
mexErrMsgIdAndTxt(MSGID_INPUT, "filename string error\n");
const mxArray *data_MA = prhs[2];
ExportOptions options(nrhs>=4 ? prhs[3] : NULL); // if the fourth argument is present - pass it, else NULL
XMLDocument doc;
doc.InsertEndChild( doc.NewDeclaration() );
doc.InsertEndChild( doc.NewComment( "Written using " MEXFUNCNAME " version " TIXML2_WRAP_MAJOR_VERSION "." TIXML2_WRAP_MINOR_VERSION));
// get root name
if(nrhs>=5)
{
const mxArray *name_MA = prhs[4];
if(!mxIsChar(name_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "name must be a string\n");
char * rootName = mxArrayToString(name_MA);
addAny(&doc, data_MA, rootName, options);
mxFree(rootName);
}
else
{
// default "root" name
addAny(&doc, data_MA, "root", options);
}
doc.SaveFile(filename);
mxFree(filename);
}
else if(!strcmp(modeString, "load"))
{
if(nrhs<2)
mexErrMsgIdAndTxt(MSGID_INPUT, "Not enough input arguments: " MEXFUNCNAME "('load', filename)\n");
if(nrhs>2)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many input arguments\n");
const mxArray *filename_MA = prhs[1];
if(!mxIsChar(filename_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "filename must be a string\n");
char * filename = mxArrayToString(filename_MA);
if(!filename)
mexErrMsgIdAndTxt(MSGID_INPUT, "filename string error\n");
XMLDocument doc;
if (doc.LoadFile(filename) != XML_NO_ERROR)
{
mexErrMsgIdAndTxt(MSGID_READ, "failed reading file \"%s\" ; %s", doc.GetErrorStr1(), doc.GetErrorStr2());
}
const XMLElement *root = doc.FirstChildElement();
if(!root && nlhs==0)
mexWarnMsgIdAndTxt(MSGID_READ, "no XML elements found in %s\n", filename);
plhs[0] = extractAny(root);
mxFree(filename);
}
else if(!strcmp(modeString, "format"))
{
if(nrhs<2)
mexErrMsgIdAndTxt(MSGID_INPUT, "Not enough input arguments: " MEXFUNCNAME "('format', data, ...)\n");
if(nrhs>4)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many input arguments\n");
const mxArray *data_MA = prhs[1];
ExportOptions options(nrhs>=3 ? prhs[2] : NULL); // if the fourth argument is present - pass it, else NULL
XMLDocument doc;
doc.InsertEndChild( doc.NewDeclaration() );
doc.InsertEndChild( doc.NewComment( "Created using " MEXFUNCNAME " version " TIXML2_WRAP_MAJOR_VERSION "." TIXML2_WRAP_MINOR_VERSION));
// get root name
if(nrhs>=4)
{
const mxArray *name_MA = prhs[3];
if(!mxIsChar(name_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "name must be a string\n");
char * rootName = mxArrayToString(name_MA);
addAny(&doc, data_MA, rootName, options);
mxFree(rootName);
}
else
{
// default "root" name
addAny(&doc, data_MA, "root", options);
}
XMLPrinter printer;
doc.Print( &printer );
const char *xmlString = printer.CStr();
plhs[0] = mxCreateString(xmlString);
}
else if(!strcmp(modeString, "parse"))
{
if(nrhs<2)
mexErrMsgIdAndTxt(MSGID_INPUT, "Not enough input arguments: " MEXFUNCNAME "('parse', XMLstring)\n");
if(nrhs>2)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many input arguments\n");
const mxArray *XMLstring_MA = prhs[1];
if(!mxIsChar(XMLstring_MA))
mexErrMsgIdAndTxt(MSGID_INPUT, "XMLstring must be a string\n");
char * XMLstring = mxArrayToString(XMLstring_MA);
if(!XMLstring)
mexErrMsgIdAndTxt(MSGID_INPUT, "XMLstring error\n");
XMLDocument doc;
if (doc.Parse(XMLstring) != XML_NO_ERROR)
{
mexErrMsgIdAndTxt(MSGID_READ, "failed parsing XMLstring \"%s\" ; %s", doc.GetErrorStr1(), doc.GetErrorStr2());
}
const XMLElement *root = doc.FirstChildElement();
if(!root && nlhs==0)
mexWarnMsgIdAndTxt(MSGID_READ, "no XML elements found in XMLstring\n");
plhs[0] = extractAny(root);
mxFree(XMLstring);
}
else if(!strcmp(modeString, "version"))
{
if(nrhs>1)
mexErrMsgIdAndTxt(MSGID_INPUT, "Too many input arguments\n");
plhs[0] = mxCreateString(MEXFUNCNAME ": " TIXML2_WRAP_MAJOR_VERSION "." TIXML2_WRAP_MINOR_VERSION "." TIXML2_WRAP_PATCH_VERSION);
}
else
mexErrMsgIdAndTxt(MSGID_INPUT, "unknown mode: %s\n", modeString);
mxFree(modeString);
}
| 34.675164 | 168 | 0.579106 |
87dd82ed0539a26de1a25c25eeb2fc8dda035205 | 892 | hh | C++ | dune/xt/common/python.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | dune/xt/common/python.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | dune/xt/common/python.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2019)
// René Fritze (2018 - 2020)
// Tobias Leibner (2020)
//
// Created by r_milk01 on 4/25/18.
#ifndef DUNE_XT_COMMON_PYTHON_HH
#define DUNE_XT_COMMON_PYTHON_HH
#include <functional>
#include <dune/pybindxi/pybind11.h>
namespace Dune::XT::Common::bindings {
void guarded_bind(const std::function<void()>& registrar);
} // namespace Dune::XT::Common::bindings
#endif // DUNE_XT_COMMON_PYTHON_HH
| 29.733333 | 95 | 0.719731 |
87dda1ed26f9e38adf47580171f95e67e0d5d7d0 | 24,417 | cpp | C++ | src/dialman.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 9 | 2020-04-01T04:15:22.000Z | 2021-09-26T21:03:47.000Z | src/dialman.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | 17 | 2020-04-02T19:38:40.000Z | 2020-04-12T05:47:08.000Z | src/dialman.cpp | taviso/mpgravity | f6a2a7a02014b19047e44db76ae551bd689c16ac | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/* SOURCE CONTROL VERSIONS */
/*---------------------------------------------------------------------------*/
/* */
/* Version Date Time Author / Comment (optional) */
/* */
/* $Log: dialman.cpp,v $
/* Revision 1.1 2010/07/21 17:14:56 richard_wood
/* Initial checkin of V3.0.0 source code and other resources.
/* Initial code builds V3.0.0 RC1
/*
/* Revision 1.2 2009/08/25 20:04:25 richard_wood
/* Updates for 2.9.9
/*
/* Revision 1.1 2009/06/09 13:21:28 richard_wood
/* *** empty log message ***
/*
/* Revision 1.2 2008/09/19 14:51:21 richard_wood
/* Updated for VS 2005
/*
/* */
/*****************************************************************************/
/**********************************************************************************
Copyright (c) 2003, Albert M. Choy
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 Microplanet, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************/
// TDialupManager - class for managing a dialup connection for Gravity
#include "stdafx.h"
#include "mplib.h"
#include "globals.h"
#include "server.h"
#include "dialman.h"
#include "critsect.h"
#include "fileutil.h"
#include "resource.h"
#include "genutil.h" // GetOS
#include "timemb.h" // TimeMsgBox_MessageBox
#include "servcp.h" // TServerCountedPtr
#include "raserror.h" // ERROR_NO_CONNECTION
#include "rasdlg.h" // TRasDialDlg our timer redial dlg
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
TDialupManager dialMgr; // a global
P_RASSTATUSFUNC gpfnStatus = 0;
// prototypes;
static UINT GetRasConnStateStringID( RASCONNSTATE rasconn );
static HWND hWaitDlg;
static HWND ghWndOutput = 0; // set within Connect
static UINT gmsgOutput = 0; // set within Connect
BOOL postSuccess ()
{
PostMessage (ghWndOutput, gmsgOutput, 0, 0);
return TRUE;
}
BOOL postFailure (DWORD dwError)
{
// stuff error code into wParam
PostMessage (ghWndOutput, gmsgOutput, (WPARAM) dwError, 0);
return TRUE;
}
// prototype
void WINAPI ras_process_event (UINT uMsg,
RASCONNSTATE rasconnstate,
DWORD dwError);
/////////////////////////////////////////////////////////////////////////////
// TDialupManager ctor - Construct a dialup manager for Gravity
/////////////////////////////////////////////////////////////////////////////
TDialupManager::TDialupManager()
{
m_fRasInstalled = FALSE;
m_hConnection = 0;
m_fWeCreated = FALSE;
m_fCancelled = FALSE;
m_ePseudoState = kNotConnected;
m_byRedials = 0;
m_hCriticalSection = &m_CriticalSection;
m_fAskedQuestionAlready = false;
InitializeCriticalSection (m_hCriticalSection);
}
/////////////////////////////////////////////////////////////////////////////
// loads RAS dll
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Initialize ()
{
m_fRasInstalled = m_rasLib.Initialize ();
return m_fRasInstalled;
}
/////////////////////////////////////////////////////////////////////////////
// TDialupManager dtor
/////////////////////////////////////////////////////////////////////////////
TDialupManager::~TDialupManager ()
{
DeleteCriticalSection (m_hCriticalSection);
}
/////////////////////////////////////////////////////////////////////////////
// ShowRasError - Show a RAS error to the user.
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::ShowRasError (bool fDuringInit, DWORD errorNum)
{
CString strIntro;
if (fDuringInit)
strIntro.LoadString (IDS_ERR_DIALUP_EST);
else
strIntro.LoadString (IDS_ERR_DIALUP_TERM);
TCHAR errorBuff[512];
CString errorString;
if (0 != m_rasLib.RasGetErrorString (errorNum,
errorBuff, sizeof (errorBuff)))
errorBuff[0] = 0;
errorString.Format ("%s - %s.", (LPCTSTR)strIntro, errorBuff);
NewsMessageBox (TGlobalDef::kMainWnd, errorString, MB_OK | MB_ICONEXCLAMATION);
}
/////////////////////////////////////////////////////////////////////////////
// Connect - Take the steps to create a dialup networking connection.
//
// Notes: 1) If ForceConnect is FALSE, then we just return true,
// since we assume that the connection has been established.
// 2) If PromptBeforeConnecting is set, we prompt before
// attempting to make the dialup connection.
// 3) If UseExistingConnection, we check to see if the
// DUN connection exists by enumerating over the current
// connections, and if found, using it. Otherwise
// we proceed to build a connection.
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Connect (P_RASSTATUSFUNC pStatusFunc, HWND hWnd, UINT msg)
{
ghWndOutput = hWnd;
gmsgOutput = msg;
m_fAskedQuestionAlready = false;
TServerCountedPtr cpNewsServer; // smart pointer
// act dumb
if (!m_fRasInstalled)
{
return postSuccess ();
}
if (!IsActiveServer())
throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError));
// don't let more than one person Try to connect at once...
if (TDialupManager::kConnecting == m_ePseudoState)
{
//TRACE0("we are connecting already...\n");
return FALSE;
}
// if we're already connected, just return TRUE
const CString & strDialupName = cpNewsServer->GetConnectionName();
HRASCONN hFound = 0;
if (FindConnectionByName (kFindOurs, strDialupName, hFound))
{
//TRACE0("we are Already connected...\n");
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hFound;
m_ePseudoState = kConnected;
return postSuccess ();
}
if (!cpNewsServer->GetForceConnection() && !cpNewsServer->GetForceDisconnect ())
{
// we're not responsible for any RAS work. or this is a LAN connection
return postSuccess ();
}
BOOL fRet;
// if we're not told to force a connection, then we just
// tell whoever is calling us the connection has been
// established
if (!cpNewsServer->GetForceConnection())
{
TEnterCSection ds(m_hCriticalSection);
FindConnectionByName(kFindAny, "", m_hConnection);
return postSuccess ();
}
if (strDialupName.IsEmpty())
{
// "You have not selected a dialup connection to use."
NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_NOCONNECTION, MB_OK | MB_ICONSTOP);
return TRUE;
}
if (cpNewsServer->GetUseExistingConnection())
{
// iterate over the existing connections and use
// the existing one if one is there...
HRASCONN hRasConn;
if (FindConnectionByName (kFindOurs, strDialupName, hRasConn))
{
//TRACE0("Found an existing connection\n");
// we found the connection that the user specified, so
// we set that we connected and return TRUE to the user...
{
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hRasConn;
}
return postSuccess ();
}
}
LPCTSTR pszConnectionName = strDialupName;
if (cpNewsServer->GetPromptBeforeConnecting())
{
CString connectionPrompt;
AfxFormatString1 (connectionPrompt, IDS_DIALUP_CONNECT1, pszConnectionName);
// "Connect to %s now?"
if (IDNO == NewsMessageBox(TGlobalDef::kMainWnd,
connectionPrompt,
MB_YESNO | MB_ICONQUESTION))
{
return FALSE;
}
}
// get to the nitty gritty
gpfnStatus = pStatusFunc;
fRet = MakeConnection (pszConnectionName);
return fRet;
}
/////////////////////////////////////////////////////////////////////////////
// Disconnect - Handle disconnecting from the dialup connection we may
// or may not have started. This is controlled by two variables
// that can be set in the server - ForceDisconnect and
// DisconnectIfWeOpened. The method will also show a prompt
// if PromptBeforeDisconnecting is set at the server.
//
// fAutoDisconnect - indicates that Gravity is disconnecting automatically.
// Don't let the MessageBoxes halt the shutdown
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Disconnect(BOOL fAutoDisconnect)
{
DWORD dwRC;
TServerCountedPtr cpNewsServer; // smart pointer
//TRACE ("%s : %d, thread ID : %d\n", __FILE__, __LINE__, AfxGetThread ());
if (FALSE == m_fRasInstalled)
return TRUE;
if (!IsActiveServer ())
throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError));
if (!cpNewsServer->GetForceDisconnect())
{
// reset to clean state
set_vars_init ();
return TRUE;
}
// if they only want us to disconnect sessions we created, then return
if (cpNewsServer->GetDisconnectIfWeOpened ())
{
if (!m_fWeCreated)
{
// reset to clean state
set_vars_init ();
return TRUE;
}
}
if (kConnecting == m_ePseudoState)
{
// amc - it's valid to Try to abort a RAS session that is
// connecting. Proceed
}
else if (0 == m_hConnection)
{
set_vars_init ();
return TRUE;
}
try
{
// keep from asking the disconnect Question more than once.
// this is weird since you might get asked 3 times:
// 1) disconnect
// 2) mainfrm OnClose
// 3) ExitInstance
if (m_fAskedQuestionAlready)
{
set_vars_init ();
return FALSE;
}
if (cpNewsServer->GetPromptBeforeDisconnecting() && !m_fAskedQuestionAlready)
{
int nMsgRet;
CString promptString;
AfxFormatString1(promptString, IDS_DIALUP_ASKDISCONNECT1,
cpNewsServer->GetConnectionName ());
UINT uBoxFlags = MB_YESNO | MB_ICONQUESTION;
if (fAutoDisconnect)
{
// Timeout after 60 seconds - return IDTIMEOUT
nMsgRet = NewsMessageBoxTimeout (60, NULL, promptString, uBoxFlags);
}
else
nMsgRet = NewsMessageBox(TGlobalDef::kMainWnd, promptString, uBoxFlags);
m_fAskedQuestionAlready = true;
if (IDNO == nMsgRet)
{
set_vars_init ();
return FALSE;
}
}
}
catch(...)
{
LINE_TRACE();
throw;
}
// go ahead and close the connection....
try
{
// 2-26-98. Even if the server has dropped us,
// (FindConnectionByName==FALSE)
// call ras hangup on the m_hConnection handle. It seems to
// help ras come back to a clean initial state.
if (kConnecting == m_ePseudoState)
m_fCancelled = TRUE;
{
TEnterCSection cs(m_hCriticalSection);
dwRC = 0;
ASSERT(m_hConnection);
//TRACE0("In Disconnect() - call RasHangUp\n");
if (m_hConnection)
{
dwRC = m_rasLib.RasHangUp (m_hConnection);
}
if (0 == dwRC)
{
// wait for handle to become invalid
wait_after_hangup (m_hConnection);
// set vars to indicate cancelled
set_vars_init ();
return TRUE;
}
}
// deal with error
set_vars_init ();
// it's silly to say "Can't hang up - connection was dropped"
if (ERROR_NO_CONNECTION != dwRC)
{
ShowRasError (false, dwRC);
}
return FALSE;
}
catch(...)
{
LINE_TRACE();
throw;
}
}
// -------------------------------------------------------------------------
// set_vars_init -- reset variables to a clean state
void TDialupManager::set_vars_init()
{
TEnterCSection cs(m_hCriticalSection);
m_fWeCreated = FALSE;
m_fCancelled = FALSE;
m_hConnection = NULL;
m_ePseudoState = kNotConnected;
}
//-------------------------------------------------------------------------
// called from the dialog box
void WINAPI ras_process_event (UINT uMsg,
RASCONNSTATE rasconnstate,
DWORD dwError)
{
// wait for 1 of three cases
// dwError is not zero - An Error occurred
// RASCS_Connected -
// someone called RasHangup
if (dwError)
{
//TRACE("callback - (error) %d, %u\n", (int)rasconnstate, dwError);
// clear status line
if (gpfnStatus)
gpfnStatus ( -1 );
// both cases need to set flags to failure values
dialMgr.processEventsResult (false);
dialMgr.hangup_nowait ();
// special handling for ERROR_LINE_BUSY, pass error up, so upper layer can redial
if (ERROR_LINE_BUSY == dwError ||
ERROR_VOICE_ANSWER == dwError)
{
postFailure (dwError);
return ;
}
if (ERROR_USER_DISCONNECTION == dwError)
{
// user interrupted dialing themselves, so they don't need to see the error msg.
}
else
dialMgr.ShowRasError (true, dwError);
return;
}
if (gpfnStatus)
gpfnStatus ( GetRasConnStateStringID(rasconnstate) );
if (RASCS_DONE & rasconnstate)
{
dialMgr.processEventsResult (true); // success
postSuccess ();
}
}
/////////////////////////////////////////////////////////////////////////////
// TDialupManager::GetDialupState
//
// Returns: ECheckConnect[kNotConnected, kConnected,
// kConnecting, kNotInstalled]
//
/////////////////////////////////////////////////////////////////////////////
TDialupManager::ECheckConnect TDialupManager::GetDialupState ()
{
if (FALSE == m_fRasInstalled)
return kNotInstalled;
// don't use FindConnectionByName, use the pseudo var
return m_ePseudoState;
}
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::MakeConnection (LPCTSTR pConnName)
{
if (RUNNING_ON_WINNT == GetOS())
{
m_ePseudoState = kConnecting;
RASDIALDLG DlgInfo;
ZeroMemory (&DlgInfo, sizeof(DlgInfo));
DlgInfo.dwSize = sizeof(DlgInfo);
DlgInfo.hwndOwner = ghWndOutput;
// returns 0 for ERROR or if the user Canceled
BOOL fRet = m_rasLib.RasNTDialDlg (NULL, // phonebook
pConnName, // phbook entry
NULL, // override phone number
&DlgInfo);
if (fRet)
{
TEnterCSection cs(m_hCriticalSection);
FindConnectionByName (kFindOurs, pConnName, m_hConnection);
m_ePseudoState = kConnected;
m_fWeCreated = TRUE;
return postSuccess ();
}
else
{
m_ePseudoState = kNotConnected;
if (ERROR_LINE_BUSY == DlgInfo.dwError)
postFailure (DlgInfo.dwError);
return FALSE;
}
}
RASDIALPARAMS rasParms;
DWORD dwRC;
m_fCancelled = FALSE;
// get the dial parameters from the registry...
if (FALSE == get_dial_parms ( pConnName, &rasParms ))
return FALSE;
HRASCONN hConnection = NULL;
m_ePseudoState = kConnecting;
m_fWeCreated = TRUE;
RASDIALEXTENSIONS extensions;
ZeroMemory (&extensions, sizeof (extensions));
extensions.dwSize = sizeof (extensions);
extensions.dwfOptions |= RDEOPT_PausedStates;
// dialog processes events via ras_process_event (in this module)
dwRC = m_rasLib.RasDial (
&extensions, // RASDIALEXTENSIONS - we don't use them
NULL, // use the default phonebook
&rasParms, // parameters for RAS dialer
(DWORD) 0 , // treat next param as type RasDialFunc
ras_process_event, // pass in our function ptr
&hConnection);
if (dwRC)
{
if (true)
{
TEnterCSection cs(m_hCriticalSection);
hangup_and_wait ( hConnection );
m_hConnection = NULL;
}
if (m_fCancelled)
{
m_fCancelled = FALSE; // reset to clean state
}
else
ShowRasError (true, dwRC);
m_ePseudoState = kNotConnected;
m_fWeCreated = FALSE;
return FALSE;
}
else
{
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hConnection;
}
return TRUE;
}
DWORD TDialupManager::RasCreatePhonebookEntry(HWND hwnd, LPTSTR pPhoneBook)
{
return m_rasLib.RasCreatePhonebookEntry(hwnd, pPhoneBook);
}
DWORD TDialupManager::RasEditPhonebookEntry(HWND hwnd, LPTSTR pPhoneBook, LPTSTR entry)
{
return m_rasLib.RasEditPhonebookEntry(hwnd, pPhoneBook, entry);
}
DWORD TDialupManager::RasEnumEntries(LPTSTR r1, LPTSTR pPhoneBook, LPRASENTRYNAME pEntry,
LPDWORD lpcb, LPDWORD lpcEntries)
{
return m_rasLib.RasEnumEntries(r1, pPhoneBook, pEntry, lpcb, lpcEntries);
}
DWORD
TDialupManager::RasGetEntryDialParams(LPTSTR pPhoneBook,
LPRASDIALPARAMS pDialParams,
LPBOOL pfPassword)
{
return m_rasLib.RasGetEntryDialParams(pPhoneBook, pDialParams, pfPassword);
}
DWORD
TDialupManager::RasSetEntryDialParams(LPTSTR pBook,
LPRASDIALPARAMS pDP,
BOOL fRemovePwd)
{
return m_rasLib.RasSetEntryDialParams(pBook, pDP, fRemovePwd);
}
//-------------------------------------------------------------------------
void TDialupManager::wait_after_hangup (HRASCONN hConnection)
{
RASCONNSTATUS rasStatus;
DWORD dwRC;
CTime start = CTime::GetCurrentTime();
do
{
ZeroMemory (&rasStatus, sizeof(rasStatus));
rasStatus.dwSize = sizeof(rasStatus);
dwRC = m_rasLib.RasGetConnectStatus (hConnection, &rasStatus);
if (ERROR_INVALID_HANDLE == dwRC)
break;
Sleep (0);
} while ((CTime::GetCurrentTime() - start).GetSeconds() < 15);
}
//-------------------------------------------------------------------------
BOOL TDialupManager::get_dial_parms (LPCTSTR pConnName,
RASDIALPARAMS* prasParms)
{
BOOL fPassword = FALSE;
DWORD dwRC;
ZeroMemory (prasParms, sizeof(RASDIALPARAMS));
prasParms->dwSize = sizeof(RASDIALPARAMS);
if (sizeof(*prasParms) != sizeof(RASDIALPARAMS))
AfxThrowMemoryException();
_tcscpy(prasParms->szEntryName, pConnName);
dwRC = m_rasLib.RasGetEntryDialParams(
NULL, // use default phonebook
prasParms, // pointer to parameters
&fPassword); // was password returned?
if (0 != dwRC)
{
// "Error retrieving dialup networking parameters."
NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_ERRGETDIALPARAMS, MB_OK | MB_ICONSTOP);
return FALSE;
}
return TRUE;
}
// ------------------------------------------------------------------------
// PURPOSE: get the index to the corresponding string
//
// PARAMETERS:
// rasconn - ras connection state
//
// RETURNS:
// index into stringtable.
static UINT GetRasConnStateStringID( RASCONNSTATE rasconn )
{
switch( rasconn )
{
case RASCS_OpenPort:
return IDS_OPENPORT;
case RASCS_PortOpened:
return IDS_PORTOPENED;
case RASCS_ConnectDevice:
return IDS_CONNECTDEVICE;
case RASCS_DeviceConnected:
return IDS_DEVICECONNECTED;
case RASCS_AllDevicesConnected:
return IDS_ALLDEVICESCONNECTED;
case RASCS_Authenticate:
return IDS_AUTHENTICATE;
case RASCS_AuthNotify:
return IDS_AUTHNOTIFY;
case RASCS_AuthRetry:
return IDS_AUTHRETRY;
case RASCS_AuthCallback:
return IDS_AUTHCALLBACK;
case RASCS_AuthChangePassword:
return IDS_AUTHCHANGEPASSWORD;
case RASCS_AuthProject:
return IDS_AUTHPROJECT;
case RASCS_AuthLinkSpeed:
return IDS_AUTHLINKSPEED;
case RASCS_AuthAck:
return IDS_AUTHACK;
case RASCS_ReAuthenticate:
return IDS_REAUTHENTICATE;
case RASCS_Authenticated:
return IDS_AUTHENTICATED;
case RASCS_PrepareForCallback:
return IDS_PREPAREFORCALLBACK;
case RASCS_WaitForModemReset:
return IDS_WAITFORMODEMRESET;
case RASCS_WaitForCallback:
return IDS_WAITFORCALLBACK;
case RASCS_StartAuthentication:
return IDS_STARTAUTH;
case RASCS_CallbackComplete:
return IDS_CALLBACK_COMPLETE;
case RASCS_LogonNetwork:
return IDS_LOGON_NETWORK;
case RASCS_SubEntryConnected:
return IDS_SUBENTRYCONNECTED;
case RASCS_Interactive:
return IDS_INTERACTIVE;
case RASCS_RetryAuthentication:
return IDS_RETRYAUTHENTICATION;
case RASCS_CallbackSetByCaller:
return IDS_CALLBACKSETBYCALLER;
case RASCS_PasswordExpired:
return IDS_PASSWORDEXPIRED;
case RASCS_Connected:
return IDS_CONNECTED;
case RASCS_Disconnected:
return IDS_DISCONNECTED;
default:
return IDS_RAS_UNDEFINED_ERROR;
}
}
//-------------------------------------------------------------------------
void TDialupManager::hangup_and_wait (HRASCONN hConnection)
{
if (hConnection)
{
m_rasLib.RasHangUp ( hConnection );
wait_after_hangup ( hConnection );
}
}
/////////////////////////////////////////////////////////////////////////////
// FindConnectionByName - Locate a connection (in the set of current
// connections) by name
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::FindConnectionByName(
EFindConn eFind,
const CString & dialupName,
HRASCONN & hConnection)
{
RASCONN connections[10]; // assume there are not more than 10 ras conns
DWORD cbSize;
DWORD numConnections;
DWORD dwRC;
cbSize = sizeof (connections);
connections[0].dwSize = sizeof (RASCONN);
dwRC = m_rasLib.RasEnumConnections (connections,
&cbSize,
&numConnections);
if (0 == dwRC)
{
for (int i = 0; i < int(numConnections); i++)
{
if (eFind == kFindOurs)
{
if (dialupName.CompareNoCase(connections[i].szEntryName) == 0)
{
hConnection = connections[i].hrasconn;
return TRUE;
}
}
else // kFindAny
{
hConnection = connections[i].hrasconn;
return TRUE;
}
}
}
hConnection = NULL;
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::processEventsResult (bool fSuccess)
{
if (fSuccess)
{
m_ePseudoState = kConnected ;
m_byRedials = 0;
}
else
{
m_ePseudoState = kNotConnected;
}
}
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::hangup_nowait ()
{
TEnterCSection cs(m_hCriticalSection);
if (m_hConnection)
{
// we are not hanging up a Valid connection, more like freeing the
// memory for this handle
// come here if we get a busy signal
m_rasLib.RasHangUp (m_hConnection);
m_hConnection = 0;
}
}
// returns true to redial
bool TDialupManager::incrementRedialCount (bool fResetToZero)
{
BYTE n = m_byRedials + 1;
if (n > 4 || fResetToZero)
{
// over the limit
m_byRedials = 0;
return false;
}
else
{
m_byRedials = n;
return true;
}
}
// ------------------------------------------------------------------------
// Returns true for "ok to redial"
bool TDialupManager::ShowRedialDlg (CWnd * pAnchor)
{
TRasDialDlg sDlg(pAnchor);
sDlg.DoModal();
return sDlg.getAnswer();
}
| 27.009956 | 91 | 0.60507 |
87ddf5a2e5a3747713708066b0d4f8f8c710746c | 3,835 | cpp | C++ | VGP242/06_HelloTexturing/GameState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | VGP242/06_HelloTexturing/GameState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | VGP242/06_HelloTexturing/GameState.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | #include "GameState.h"
using namespace JimmyGod::Input;
using namespace JimmyGod::Graphics;
using namespace JimmyGod::Math;
void GameState::Initialize()
{
GraphicsSystem::Get()->SetClearColor(Colors::Black);
mCamera.SetPosition({ 0.0f,0.0f,-5.0f });
mCamera.SetDirection({ 0.0f,0.0f,1.0f });
/* Homework
Update helloTexturing to use a MeshPX data to draw a texture mapped cubes
You will need to add Sampler and Texture classes provided
You will need to use DoTexturing fx shaders
Add a new class called Graphics::MeshBuilder with the following functions
namespace JimmyGod::Graphics
{
class MeshBuilder
{
static MeshPX CreatePlanePX();
static MeshPX CreateCylinderPX();
static MeshPX CreateSpherePX(float radius, int ringhs = 16, int slices = 16);
}
This will allow you to create a mesh easily by doing:
auto mesh = MeshBuilder::CreateSpherePX(...);
Add HelloEarth to test a texture mapped sphere using Earth texture
a plane:
for(int y=0; y< height; ++y)
for(int x=0; x<width; ++x)
mMesh.push_back({x,y,0.0f}...);
a cylinder:
for(int y=0; y< height; ++y)
for(int theta=0; theta<TwoPi; theta += ...)
mMesh.push_back({sin(theta),y,cos(theta)}...);
a sphere:
for(int phi=0; phi< Pi; phi += ...)
for(int theta=0; theta<TwoPi; theta += ...)
mMesh.push_back({sin(theta) * r,phi,cos(theta) *r}...);
}*/
auto Mesh = MeshBuilder::CreateCubePX();
auto Plane = MeshBuilder::CreatePlanePX(2,2);
auto Cylinder = MeshBuilder::CreateCylinderPX(36, 36);
auto Sphere = MeshBuilder::CreateSpherePX(10);
mMeshBuffer.Initialize(Plane);
mConstantBuffer.Initialize(sizeof(Matrix4));
mSampler.Initialize(Sampler::Filter::Point, Sampler::AddressMode::Clamp);
mTexture.Initialize("../../Assets/Textures/SimYoung.jpg");
// Compile and create vertex shader
mVertexShader.Initialize("../../Assets/Shaders/DoTexturing.fx",VertexPX::Format);
// Compile and create pixel shader
mPixelShader.Initialize("../../Assets/Shaders/DoTexturing.fx");
}
void GameState::Terminate()
{
mVertexShader.Terminate();
mPixelShader.Terminate();
mMeshBuffer.Terminate();
mConstantBuffer.Terminate();
mTexture.Terminate();
mSampler.Terminate();
}
void GameState::Update(float deltaTime)
{
const float kMoveSpeed = 7.5f;
const float kTurnSpeed = 0.5f;
auto inputSystem = InputSystem::Get();
if (inputSystem->IsKeyDown(KeyCode::W))
{
mCamera.Walk(kMoveSpeed*deltaTime);
}
if (inputSystem->IsKeyDown(KeyCode::S))
{
mCamera.Walk(-kMoveSpeed * deltaTime);
}
mCamera.Yaw(inputSystem->GetMouseMoveX() * kTurnSpeed * deltaTime);
mCamera.Pitch(inputSystem->GetMouseMoveY() * kTurnSpeed * deltaTime);
if (inputSystem->IsKeyDown(KeyCode::A))
{
mRotation += deltaTime;
}
if (inputSystem->IsKeyDown(KeyCode::D))
{
mRotation -= deltaTime;
}
}
void GameState::Render()
{
auto matView = mCamera.GetViewMatrix();
auto matProj = mCamera.GetPerspectiveMatrix();
mVertexShader.Bind();
mPixelShader.Bind();
mConstantBuffer.BindVS(0);
mSampler.BindPS();
mTexture.BindPS();
for (int i = 0; i < 2; i++)
{
auto matWorld1 = Matrix4::RotationY(mRotation.y);
//auto matWorld2 = Matrix4::RotationX(mRotation.x- static_cast<float>(i));
//auto matWorld3 = Matrix4::RotationZ(mRotation.z+ static_cast<float>(i));
auto matTranslation = Matrix4::Identity;// Matrix4::Translation(Vector3(static_cast<float>(i), static_cast<float>(i), static_cast<float>(0)));
auto matScl = Matrix4::Scaling(static_cast<float>(i) * 0.25f);
auto matWVP = Transpose(matScl*matTranslation*matWorld1 * matView * matProj);
mConstantBuffer.Update(&matWVP);
mMeshBuffer.Draw();
}
/*context->Draw(mVertices.size(), 0);*/ // This is for when we don't have an index buffer
} | 30.19685 | 145 | 0.690743 |
87e0ec19e6f60dc42bcc6fa3a417c0796aee134d | 1,187 | hpp | C++ | include/codegen/include/GlobalNamespace/BeatmapEventData.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/BeatmapEventData.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/BeatmapEventData.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: BeatmapEventType
#include "GlobalNamespace/BeatmapEventType.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: BeatmapEventData
class BeatmapEventData : public ::Il2CppObject {
public:
// public readonly BeatmapEventType type
// Offset: 0x10
GlobalNamespace::BeatmapEventType type;
// public readonly System.Single time
// Offset: 0x14
float time;
// public readonly System.Int32 value
// Offset: 0x18
int value;
// public System.Void .ctor(System.Single time, BeatmapEventType type, System.Int32 value)
// Offset: 0xB8D16C
static BeatmapEventData* New_ctor(float time, GlobalNamespace::BeatmapEventType type, int value);
}; // BeatmapEventData
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEventData*, "", "BeatmapEventData");
#pragma pack(pop)
| 35.969697 | 101 | 0.699242 |
87e24f9b179db7cf817f62262a028bed3a77134d | 3,987 | hpp | C++ | src/main/cpp/USSL/BasicArithmatic.hpp | Crtl-F5/F5RC-Kernel | 145cf9f7a34463226e68112033f56e0d121425e3 | [
"MIT"
] | 1 | 2018-08-12T03:50:19.000Z | 2018-08-12T03:50:19.000Z | src/main/cpp/USSL/BasicArithmatic.hpp | Crtl-F5/F5RC-Kernel | 145cf9f7a34463226e68112033f56e0d121425e3 | [
"MIT"
] | null | null | null | src/main/cpp/USSL/BasicArithmatic.hpp | Crtl-F5/F5RC-Kernel | 145cf9f7a34463226e68112033f56e0d121425e3 | [
"MIT"
] | null | null | null | #pragma once
#include <ProgramType.hpp>
namespace USSL
{
inline void ADD(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b + args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s + args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i + args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l + args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f + args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d + args[2].data.d; break;
}
}
inline void SUB((ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b - args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s - args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i - args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l - args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f - args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d - args[2].data.d; break;
}
}
inline void MUL(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b * args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s * args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i * args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l * args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f * args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d * args[2].data.d; break;
}
}
inline void DIV(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b / args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s / args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i / args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l / args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f / args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d / args[2].data.d; break;
}
}
inline void MOD(ProgramType* args, unsigned char* memory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b % args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s % args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i % args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l % args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f % args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d % args[2].data.d; break;
}
}
} | 56.957143 | 114 | 0.563582 |
87e7683708abea0b9a5cf4c0ecbae75ffdf6184e | 1,582 | cpp | C++ | acmicpc/16235.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/16235.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/16235.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
#define MAX 11
const int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
const int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int n, m, k, x, y, z;
int map[MAX][MAX], nou[MAX][MAX], new_tree[MAX][MAX];
bool visit[MAX][MAX];
vector<int> tree[MAX][MAX];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j) {
cin >> map[i][j];
nou[i][j] = 5;
}
}
for (int i=0; i<m; ++i) {
cin >> x >> y >> z;
tree[x-1][y-1].push_back(z);
}
while (k--) {
memset(new_tree, 0, sizeof(new_tree));
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j) {
sort(tree[i][j].begin(), tree[i][j].end());
vector<int> t;
int dead = 0;
for (int s=0; s<tree[i][j].size(); ++s) {
int cur = tree[i][j][s];
if (cur <= nou[i][j]) {
t.push_back(cur+1);
nou[i][j] -= cur;
if ((cur+1) % 5 != 0)
continue;
for (int p=0; p<8; ++p) {
int nx = i + dx[p];
int ny = j + dy[p];
if (nx < 0 || ny < 0 || nx >= n || ny >= n)
continue;
new_tree[nx][ny] += 1;
}
} else {
dead += cur/2;
}
}
nou[i][j] += (dead + map[i][j]);
tree[i][j] = t;
}
}
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
for (int k=0; k<new_tree[i][j]; ++k)
tree[i][j].push_back(1);
}
int ans = 0;
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
ans += tree[i][j].size();
cout << ans << '\n';
return 0;
}
| 19.530864 | 53 | 0.453224 |
87e9cd99ee6892015e96a6141a5649aad854bde2 | 1,580 | cpp | C++ | libnativeipc/src/ConnectionFactory.cpp | stream-labs/twitch-native-ipc | 81154497fcf55288c51cb5c93e95014ec4f0644d | [
"MIT"
] | 8 | 2020-10-12T21:44:47.000Z | 2021-07-29T16:58:41.000Z | libnativeipc/src/ConnectionFactory.cpp | ConnectionMaster/twitch-native-ipc | 81154497fcf55288c51cb5c93e95014ec4f0644d | [
"MIT"
] | 1 | 2021-08-28T03:11:34.000Z | 2021-08-28T03:11:34.000Z | libnativeipc/src/ConnectionFactory.cpp | ConnectionMaster/twitch-native-ipc | 81154497fcf55288c51cb5c93e95014ec4f0644d | [
"MIT"
] | 3 | 2020-10-02T17:34:57.000Z | 2021-08-28T03:11:23.000Z | // Copyright Twitch Interactive, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
#include "ClientConnection.h"
#include "ConnectionFactoryPrivate.h"
#include "Pipe-ClientTransport.h"
#include "Pipe-ServerTransport.h"
#include "TCP-ClientTransport.h"
#include "TCP-ServerTransport.h"
#include "ServerConnection.h"
#include "ServerConnectionSingle.h"
using namespace Twitch::IPC;
namespace {
std::string pipeNameForEndpoint(const std::string &endpoint)
{
#ifdef _WIN32
return R"(\\.\pipe\)" + endpoint;
#else
return "/tmp/" + endpoint;
#endif
}
} // namespace
namespace Twitch::IPC::ConnectionFactory {
NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newServerConnection(const std::string &endpoint, bool allowMultiuserAccess)
{
return std::unique_ptr<IConnection>(std::make_unique<ServerConnectionSingle>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), allowMultiuserAccess));
}
NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newClientConnection(
const std::string &endpoint)
{
return std::unique_ptr<IConnection>(std::make_unique<ClientConnection>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint)));
}
NATIVEIPC_LIBSPEC std::unique_ptr<IServerConnection> newMulticonnectServerConnection(const std::string &endpoint, bool allowMultiuserAccess)
{
return std::unique_ptr<IServerConnection>(std::make_unique<ServerConnection>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), false, allowMultiuserAccess));
}
} // namespace Twitch::IPC::ConnectionFactory
| 32.244898 | 140 | 0.772152 |
87eeb246a6f0325edcc78761210938ddb9930ff2 | 516 | cc | C++ | ChiTech/ChiMesh/Region/chi_region.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 7 | 2019-09-10T12:16:08.000Z | 2021-05-06T16:01:59.000Z | ChiTech/ChiMesh/Region/chi_region.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 72 | 2019-09-04T15:00:25.000Z | 2021-12-02T20:47:29.000Z | ChiTech/ChiMesh/Region/chi_region.cc | Jrgriss2/chi-tech | db75df761d5f25ca4b79ee19d36f886ef240c2b5 | [
"MIT"
] | 41 | 2019-09-02T15:33:31.000Z | 2022-02-10T13:26:49.000Z | #include "chi_region.h"
#include "chi_log.h"
extern ChiLog& chi_log;
//###################################################################
/** Obtains the latest created grid from the region.*/
chi_mesh::MeshContinuumPtr chi_mesh::Region::GetGrid()
{
if (this->volume_mesh_continua.empty())
{
chi_log.Log(LOG_ALLERROR)
<< "Region: Grid retrieval failed. Verify that volume mesher"
" has executed for this region.";
exit(EXIT_FAILURE);
} else
return volume_mesh_continua.back();
} | 25.8 | 69 | 0.602713 |
87eed6ecbee0098d46274cc62d47f0f864ad77bf | 18,482 | cpp | C++ | mainwindow.cpp | Chady00/Three-Rocks-Game | 40e803e329080bc4f759599bd8561ed65914247f | [
"MIT"
] | null | null | null | mainwindow.cpp | Chady00/Three-Rocks-Game | 40e803e329080bc4f759599bd8561ed65914247f | [
"MIT"
] | null | null | null | mainwindow.cpp | Chady00/Three-Rocks-Game | 40e803e329080bc4f759599bd8561ed65914247f | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QPlainTextEdit>
#include<QLabel>
#include<QColor>
#include <QApplication>
#include <QProcess>
#include<QTime>
#include<QString>
#include<QThread>
#include<QtDebug>
#include<QMessageBox>
////////////////////////////////////////////////
int counter_L=0;
int counter_R=0;
int temp=20;
int blink_flag=0;
////////////////////////////////////////////////
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//DISPLAYING background
this->centralWidget()->setStyleSheet(
"background-image:url(\"D:/imager.jpg\"); background-position: center;" );
// ui->label->setText("Engine Stole");
ui->label->hide();
timer = new QTimer(this);
blinktimer= new QTimer(this);
connect(blinktimer,SIGNAL(timeout()),this,SLOT(blink()));
connect(timer,SIGNAL(timeout()),this,SLOT(myfunction()));
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::myfunction()
{
Engine_turn();
timer->stop();
enable_buttons();
}
void MainWindow::blink()
{ blink_flag++;
if(ui->label->isHidden())
ui->label->show();
else
ui->label->hide();
if(blink_flag==4){
ui->label->hide();
blinktimer->stop();
blink_flag=0;
}
}
void MainWindow::enable_buttons(){
ui->one_zero->setEnabled(true);
ui->one_one->setEnabled(true);
ui->one_two->setEnabled(true);
ui->two_one->setEnabled(true);
ui->two_zero->setEnabled(true);
ui->three_zero->setEnabled(true);
ui->zero_one->setEnabled(true);
ui->zero_two->setEnabled(true);
ui->zero_three->setEnabled(true);
}
void MainWindow::disable_buttons(){
ui->one_zero->setDisabled(true);
ui->one_one->setDisabled(true);
ui->one_two->setDisabled(true);
ui->two_one->setDisabled(true);
ui->two_zero->setDisabled(true);
ui->three_zero->setDisabled(true);
ui->zero_one->setDisabled(true);
ui->zero_two->setDisabled(true);
ui->zero_three->setDisabled(true);
}
////////////////////////////////////////////////
void MainWindow::check(){
if(counter_L>=10){//check for 1 remaining
ui->one_zero->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->one_zero->setDisabled(true);
//disable 1,2 and 1,1
ui->one_one->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->one_one->setDisabled(true);
ui->one_two->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->one_two->setDisabled(true);
}
if(counter_L>=9){//check for 2 remaining
ui->two_zero->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->two_zero->setDisabled(true);
//disable 2,1
ui->two_one->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->two_one->setDisabled(true);
}
if(counter_L>=8){//check for 3 remaining
ui->three_zero->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->three_zero->setDisabled(true);
}
//////////////////////...........................////////////////////
if(counter_R>=10){//check for 1 remaining
ui->zero_one->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->zero_one->setDisabled(true);
//disable 1,1 and 2,1
ui->one_one->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->one_one->setDisabled(true);
ui->two_one->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->two_one->setDisabled(true);
}
if(counter_R>=9){//check for 2 remaining
ui->zero_two->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->zero_two->setDisabled(true);
// disabe 1,2
ui->one_two->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->one_two->setDisabled(true);
}
if(counter_R>=8){//check for 3 remaining
ui->zero_three->setStyleSheet("QPushButton { color :#C5C4C4; }");
ui->zero_three->setDisabled(true);
}
if(temp==0){
QMessageBox::information(this,tr("YOU'VE MADE IT"),tr("You Win! You picked the last balls"));
}
}
void MainWindow:: clear_one_right(){
counter_R++;
temp--;
if(ui->rock_1R){
delete ui->rock_1R;
ui->rock_1R=nullptr;
}
else if(ui->rock_2R){
delete ui->rock_2R;
ui->rock_2R=nullptr;
}
else if(ui->rock_3R){
delete ui->rock_3R;
ui->rock_3R=nullptr;
}
else if(ui->rock_4R){
delete ui->rock_4R;
ui->rock_4R=nullptr;
}
else if(ui->rock_5R){
delete ui->rock_5R;
ui->rock_5R=nullptr;
}
else if(ui->rock_6R){
delete ui->rock_6R;
ui->rock_6R=nullptr;
}
else if(ui->rock_7R){
delete ui->rock_7R;
ui->rock_7R=nullptr;
}
else if(ui->rock_8R){
delete ui->rock_8R;
ui->rock_8R=nullptr;
}
else if(ui->rock_9R){
delete ui->rock_9R;
ui->rock_9R=nullptr;
}
else if(ui->rock_10R){
delete ui->rock_10R;
ui->rock_10R=nullptr;
}
}
void MainWindow::clear_two_right(){
counter_R+=2;
temp-=2;
if(ui->rock_1R){
delete ui->rock_1R;
delete ui->rock_2R;
ui->rock_1R=nullptr;
ui->rock_2R=nullptr;
}
else if(ui->rock_2R){
delete ui->rock_2R;
delete ui->rock_3R;
ui->rock_2R=nullptr;
ui->rock_3R=nullptr;
}
else if(ui->rock_3R){
delete ui->rock_3R;
delete ui->rock_4R;
ui->rock_3R=nullptr;
ui->rock_4R=nullptr;
}
else if(ui->rock_4R){
delete ui->rock_4R;
delete ui->rock_5R;
ui->rock_4R=nullptr;
ui->rock_5R=nullptr;
}
else if(ui->rock_5R){
delete ui->rock_5R;
delete ui->rock_6R;
ui->rock_5R=nullptr;
ui->rock_6R=nullptr;
}
else if(ui->rock_6R){
delete ui->rock_6R;
delete ui->rock_7R;
ui->rock_6R=nullptr;
ui->rock_7R=nullptr;
}
else if(ui->rock_7R){
delete ui->rock_7R;
delete ui->rock_8R;
ui->rock_7R=nullptr;
ui->rock_8R=nullptr;
}
else if(ui->rock_8R){
delete ui->rock_8R;
delete ui->rock_9R;
ui->rock_8R=nullptr;
ui->rock_9R=nullptr;
}
else if(ui->rock_9R){
delete ui->rock_9R;
delete ui->rock_10R;
ui->rock_9R=nullptr;
ui->rock_10R=nullptr;
}
}
void MainWindow::clear_three_right(){
counter_R+=3;
temp-=3;
if(ui->rock_1R){
delete ui->rock_1R;
delete ui->rock_2R;
delete ui->rock_3R;
ui->rock_1R=nullptr;
ui->rock_2R=nullptr;
ui->rock_3R=nullptr;
}
else if(ui->rock_2R){
delete ui->rock_2R;
delete ui->rock_3R;
delete ui->rock_4R;
ui->rock_2R=nullptr;
ui->rock_3R=nullptr;
ui->rock_4R=nullptr;
}
else if(ui->rock_3R){
delete ui->rock_3R;
delete ui->rock_4R;
delete ui->rock_5R;
ui->rock_3R=nullptr;
ui->rock_4R=nullptr;
ui->rock_5R=nullptr;
}
else if(ui->rock_4R){
delete ui->rock_4R;
delete ui->rock_5R;
delete ui->rock_6R;
ui->rock_4R=nullptr;
ui->rock_5R=nullptr;
ui->rock_6R=nullptr;
}
else if(ui->rock_5R){
delete ui->rock_5R;
delete ui->rock_6R;
delete ui->rock_7R;
ui->rock_5R=nullptr;
ui->rock_6R=nullptr;
ui->rock_7R=nullptr;
}
else if(ui->rock_6R){
delete ui->rock_6R;
delete ui->rock_7R;
delete ui->rock_8R;
ui->rock_6R=nullptr;
ui->rock_7R=nullptr;
ui->rock_8R=nullptr;
}
else if(ui->rock_7R){
delete ui->rock_7R;
delete ui->rock_8R;
delete ui->rock_9R;
ui->rock_7R=nullptr;
ui->rock_8R=nullptr;
ui->rock_9R=nullptr;
}
else if(ui->rock_8R){
delete ui->rock_8R;
delete ui->rock_9R;
delete ui->rock_10R;
ui->rock_8R=nullptr;
ui->rock_9R=nullptr;
ui->rock_10R=nullptr;
}
}
void MainWindow:: clear_one_left(){
counter_L++;
temp--;
if(ui->rock_1L){
delete ui->rock_1L;
ui->rock_1L=nullptr;
}
else if(ui->rock_2L){
delete ui->rock_2L;
ui->rock_2L=nullptr;
}
else if(ui->rock_3L){
delete ui->rock_3L;
ui->rock_3L=nullptr;
}
else if(ui->rock_4L){
delete ui->rock_4L;
ui->rock_4L=nullptr;
}
else if(ui->rock_5L){
delete ui->rock_5L;
ui->rock_5L=nullptr;
}
else if(ui->rock_6L){
delete ui->rock_6L;
ui->rock_6L=nullptr;
}
else if(ui->rock_7L){
delete ui->rock_7L;
ui->rock_7L=nullptr;
}
else if(ui->rock_8L){
delete ui->rock_8L;
ui->rock_8L=nullptr;
}
else if(ui->rock_9L){
delete ui->rock_9L;
ui->rock_9L=nullptr;
}
else if(ui->rock_10L){
delete ui->rock_10L;
ui->rock_10L=nullptr;
}
}
////////////////////////////////////////////////
void MainWindow:: clear_two_left(){
counter_L+=2;
temp-=2;
if(ui->rock_1L){
delete ui->rock_1L;
delete ui->rock_2L;
ui->rock_1L=nullptr;
ui->rock_2L=nullptr;
}
else if(ui->rock_2L){
delete ui->rock_2L;
delete ui->rock_3L;
ui->rock_2L=nullptr;
ui->rock_3L=nullptr;
}
else if(ui->rock_3L){
delete ui->rock_3L;
delete ui->rock_4L;
ui->rock_3L=nullptr;
ui->rock_4L=nullptr;
}
else if(ui->rock_4L){
delete ui->rock_4L;
delete ui->rock_5L;
ui->rock_4L=nullptr;
ui->rock_5L=nullptr;
}
else if(ui->rock_5L){
delete ui->rock_5L;
delete ui->rock_6L;
ui->rock_5L=nullptr;
ui->rock_6L=nullptr;
}
else if(ui->rock_6L){
delete ui->rock_6L;
delete ui->rock_7L;
ui->rock_6L=nullptr;
ui->rock_7L=nullptr;
}
else if(ui->rock_7L){
delete ui->rock_7L;
delete ui->rock_8L;
ui->rock_7L=nullptr;
ui->rock_8L=nullptr;
}
else if(ui->rock_8L){
delete ui->rock_8L;
delete ui->rock_9L;
ui->rock_8L=nullptr;
ui->rock_9L=nullptr;
}
else if(ui->rock_9L){
delete ui->rock_9L;
delete ui->rock_10L;
ui->rock_9L=nullptr;
ui->rock_10L=nullptr;
}
}
void MainWindow:: clear_three_left(){
temp-=3;
counter_L+=3;
if(ui->rock_1L){
delete ui->rock_1L;
delete ui->rock_2L;
delete ui->rock_3L;
ui->rock_1L=nullptr;
ui->rock_2L=nullptr;
ui->rock_3L=nullptr;
}
else if(ui->rock_2L){
delete ui->rock_2L;
delete ui->rock_3L;
delete ui->rock_4L;
ui->rock_2L=nullptr;
ui->rock_3L=nullptr;
ui->rock_4L=nullptr;
}
else if(ui->rock_3L){
delete ui->rock_3L;
delete ui->rock_4L;
delete ui->rock_5L;
ui->rock_3L=nullptr;
ui->rock_4L=nullptr;
ui->rock_5L=nullptr;
}
else if(ui->rock_4L){
delete ui->rock_4L;
delete ui->rock_5L;
delete ui->rock_6L;
ui->rock_4L=nullptr;
ui->rock_5L=nullptr;
ui->rock_6L=nullptr;
}
else if(ui->rock_5L){
delete ui->rock_5L;
delete ui->rock_6L;
delete ui->rock_7L;
ui->rock_5L=nullptr;
ui->rock_6L=nullptr;
ui->rock_7L=nullptr;
}
else if(ui->rock_6L){
delete ui->rock_6L;
delete ui->rock_7L;
delete ui->rock_8L;
ui->rock_6L=nullptr;
ui->rock_7L=nullptr;
ui->rock_8L=nullptr;
}
else if(ui->rock_7L){
delete ui->rock_7L;
delete ui->rock_8L;
delete ui->rock_9L;
ui->rock_7L=nullptr;
ui->rock_8L=nullptr;
ui->rock_9L=nullptr;
}
else if(ui->rock_8L){
delete ui->rock_8L;
delete ui->rock_9L;
delete ui->rock_10L;
ui->rock_8L=nullptr;
ui->rock_9L=nullptr;
ui->rock_10L=nullptr;
}
}
////////////////////////////////////////////////
void MainWindow::on_one_zero_clicked()
{// initially counter_L =10
// ui->label->setText("Engine Removed 1 Stone\n from the left");
clear_one_left();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_two_zero_clicked()
{
clear_two_left();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_three_zero_clicked()
{
clear_three_left();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_one_one_clicked()
{
clear_one_left();
clear_one_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_two_one_clicked()
{ clear_two_left();
clear_one_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_zero_one_clicked()
{
clear_one_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_zero_two_clicked()
{
clear_two_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_zero_three_clicked()
{
clear_three_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow::on_one_two_clicked()
{
clear_one_left();
clear_two_right();
check();
disable_buttons();
timer->start(2000);
blinktimer->start(500);
}
void MainWindow:: delay()
{
QTime dieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
void MainWindow::on_pushButton_clicked()
{//reset
qApp->quit();
QProcess::startDetached(qApp->arguments()[0], qApp->arguments());
}
void MainWindow::Engine_turn(){
//I want to make his turn at 16 ..1 12 ..8 ..4
//delay
if(temp==20){
clear_one_right(); // Now counter_L + counter_R=1;
}
else if(temp==18){
clear_one_right();
clear_one_left();
}
else if(temp==17){
clear_one_left();
}
else if(temp==16){// BAD
clear_two_right();
}
else if(temp==15){
clear_three_left();
}
else if(temp==14){
clear_two_right();
}
else if(temp==13){
clear_one_right();
}
else if(temp==12){ // BAD
clear_two_left();
}
else if(temp==11){
if(counter_R<=7){
clear_three_right();}
else {clear_three_left();}
}
else if(temp==10){
if(counter_R<=8){
clear_two_right();}
else {clear_two_left();}
}
else if(temp==9){
if(counter_L<=9){
clear_one_left();}
else {clear_one_right();}
}
else if(temp==8){// BAD
if(counter_R<=9){
clear_one_right();}
else{clear_one_left();}
}
else if(temp==7){
if(counter_L<=7){
clear_three_left();}
else {clear_three_right();}
}
else if(temp==6){
if(counter_R<=8){
clear_two_right();}
else if(counter_L<=8){
clear_two_left();}
else{clear_one_right();
clear_one_left();}
}
else if (temp==5){
if(counter_L<=9){
clear_one_left();}
else {clear_one_right();}
}
else if(temp==4){ //BAD
if(counter_R<=8){
clear_two_right();}
else if(counter_L<=8){
clear_two_left();}
else{clear_one_right();
clear_one_left();}
}
else if(temp==3){
if(counter_R<=9 && counter_L<=8){
clear_one_right();
clear_two_left();
}
else if(counter_R<=8 && counter_L<=9){
clear_one_left();
clear_two_right();
}
else if(counter_R<=7){
clear_three_right();
}
else {clear_three_left();}
QMessageBox::information(this,tr("GAME OVER"),tr("You lose! Engine picked the last 3 balls"));
}
else if (temp==2){
if(counter_R<=8){
clear_two_right();
}
else if(counter_L<=8){
clear_two_left();
}
if(counter_R<=9 && counter_L<=9){
clear_one_right();
clear_one_left();
}
else { qDebug()<<"I am waiting for engine";}
QMessageBox::information(this,tr("GAME OVER"),tr("You lose! Engine picked the last 2 balls"));
}
else if(temp==1){
if(counter_R<=9){
clear_one_right();}
else{clear_one_left();}
QMessageBox::information(this,tr("GAME OVER"),tr("You lose! Engine picked the last ball"));
}
if(temp>0)check();
}
| 25.111413 | 102 | 0.511092 |
87efcf503e4fdf4c4251b35612961e906b8b0b90 | 1,361 | cpp | C++ | TP/starters 12/maxpoint.cpp | ShyrenMore/DSA_Docs | 7d489326799886afd8d5f7ec7f4b88311e86e582 | [
"Unlicense"
] | null | null | null | TP/starters 12/maxpoint.cpp | ShyrenMore/DSA_Docs | 7d489326799886afd8d5f7ec7f4b88311e86e582 | [
"Unlicense"
] | null | null | null | TP/starters 12/maxpoint.cpp | ShyrenMore/DSA_Docs | 7d489326799886afd8d5f7ec7f4b88311e86e582 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define deb(x) cout << #x << ": " << x << endl;
#define deb2(x, y) cout << #x << ": " << x << " ~ " << #y << ": " << y << endl;
#define in(n, arr) \
for (int i = 0; i < n; i++) \
cin >> arr[i]
#define out(n, arr) \
for (int i = 0; i < n; i++) \
cout << arr[i]
#define lli long long int
#define here cout << "\nHERE\n"
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
using namespace std;
int main()
{
// /*
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// */
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
int A, B, C, X, Y, Z;
cin >> A >> B >> C >> X >> Y >> Z;
int ans = 0;
for (int take_a = 0; take_a <= 20; take_a++)
{
for (int take_b = 0; take_b <= 20; take_b++)
{
for (int take_c = 0; take_c <= 20; take_c++)
{
int time = take_a * A + take_b * B + take_c * C;
if (time <= 240)
{
ans = max(ans, take_a * X + take_b * Y + take_c * Z);
}
}
}
}
cout << ans << "\n";
}
return 0;
} | 24.745455 | 79 | 0.404849 |
87f309380c4edea79fa65041f91153ead7e3da12 | 6,775 | cpp | C++ | src/change.cpp | janreerink/CarND-Path-Planning-Project | ef9d3f19603cdde3096c5f4bd25ab4f1679c619a | [
"MIT"
] | null | null | null | src/change.cpp | janreerink/CarND-Path-Planning-Project | ef9d3f19603cdde3096c5f4bd25ab4f1679c619a | [
"MIT"
] | null | null | null | src/change.cpp | janreerink/CarND-Path-Planning-Project | ef9d3f19603cdde3096c5f4bd25ab4f1679c619a | [
"MIT"
] | null | null | null | #include <list>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
double consider_change(int lane, vector<vector<double>> sensor_fusion, double current_speed, double car_s, int prev_size, double same_lane_dist)
{
int rec_lane = lane;
std::list<int> potential_lanes;
vector<double> lane_0_speeds;
vector<double> lane_1_speeds;
vector<double> lane_2_speeds;
vector<double> min_speeds;
//for each car
cout<<"starting car loop \n";
for(int i = 0; i < sensor_fusion.size(); i++)
{
//log car loop
cout<<"car" << i+1 << "from " << sensor_fusion.size() << "\n";
float d = sensor_fusion[i][6];
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx*vx + vy *vy);
double check_car_s = sensor_fusion[i][5];
cout<<"check_car_s " << check_car_s << "\n";
cout<<"own_s " << car_s << "\n";
cout<<"check_car_d " << d << "\n";
// if vehicle is in front and not too far, add its speed to list of speeds for lanes
if( (check_car_s > car_s) && ((check_car_s - car_s) < 65) )
{
//cout<<"found car in front, going " << check_speed << "mph \n";
if( (d < 4) && (d >= 0) )
{
//cout<<"car is in left lane \n";
lane_0_speeds.push_back(check_speed);}
if( (d < 8) && (d >= 4) )
{
//cout<<"car is in center lane \n";
lane_1_speeds.push_back(check_speed);}
if( (d < 12) && (d >= 8) )
{
//cout<<"car is in right lane \n";
lane_2_speeds.push_back(check_speed);}
}
}
//find min speeds per lane; if no vehicles set to high number
double lane0m;
double lane1m;
double lane2m;
if (lane_0_speeds.size()>0)
{lane0m = *std::min_element(lane_0_speeds.begin(),lane_0_speeds.end());;}
else
{lane0m = 999;}
if (lane_1_speeds.size()>0)
{lane1m = *std::min_element(lane_1_speeds.begin(),lane_1_speeds.end());;}
else
{lane1m = 999;}
if (lane_2_speeds.size()>0)
{lane2m = *std::min_element(lane_2_speeds.begin(),lane_2_speeds.end());;}
else
{lane2m = 999;}
/* ddebug
cout<<"lane_0_speeds: \n";
for (auto const& c : lane_0_speeds)
std::cout << c << ' ';
cout<<"\n";
cout<<"lane_1_speeds: \n";
for (auto const& c : lane_1_speeds)
std::cout << c << ' ';
cout<<"\n";
cout<<"lane_2_speeds: \n";
for (auto const& c : lane_2_speeds)
std::cout << c << ' ';
cout<<"\n";
*/
min_speeds.push_back(lane0m);
min_speeds.push_back(lane1m);
min_speeds.push_back(lane2m);
cout<<"min speeds: \n";
/* debug
cout<<min_speeds";
for (auto const& c : min_speeds)
std::cout << c << ' ';
cout<<"\n";
*/
// compare speeds in adjacent lanes, set recommended lane in case minimum speed of vehicle in front is faster than in current lane
switch(lane)
{
case 0:
if (min_speeds[0] < min_speeds[1] + 0.5)
{cout<<"current speed in CL better than my LL, going center \n";
rec_lane = 1;}
else if (min_speeds[2] + 1.5 > min_speeds[0]) //if far lane significantly faster try to switch to center lane
{rec_lane = 1;}
break;
case 1:
/* debug
cout<<"entered switch case 1 \n";
cout<< "min_speeds0: " << min_speeds[0] << "\n";
cout<< "min_speeds1: " << min_speeds[1] << "\n";
cout<< "min_speeds2: " << min_speeds[2] << "\n";
cout<< "current_speed: " << current_speed << "\n";
*/
if ( (min_speeds[0] > min_speeds[1]+0.5) && (min_speeds[0] >= min_speeds[2])) //if both lanes clear prefer left, needs to be improved
{cout<<"current speed in LL better than my CL, going LL \n";
rec_lane = 0;}
if ( (min_speeds[2] > min_speeds[1]+0.5) && (min_speeds[0] < min_speeds[2]))
{cout<<"current speed in RL better than my CL, going RL \n";
rec_lane = 2;}
cout<<"result of switch: " << rec_lane << " \n";
break;
case 2:
if (min_speeds[lane] < min_speeds[1] + 0.5)
{
cout<<"current speed my RL slower, going CL \n";
rec_lane = 1;
}
else if (min_speeds[0] + 1.5 > min_speeds[2]) //if far lane significantly faster try to switch to center lane
{rec_lane = 1;}
break;
}
//test feasibility of recommended lane
if (rec_lane != lane)
{
/*
cout<<"ok, so you want me to switch to " << rec_lane << " \n";
*/
//for recommended lane, project s and compare to self
//cout<<"current own s " << car_s << " \n";
double car_s_x = car_s;
car_s_x += ((double)prev_size * 0.02 * current_speed); //extrapolate own s position
//cout<<"extra own s " << car_s_x << " \n";
// loop through vehicles
for(int i = 0; i < sensor_fusion.size(); i++)
{
float d = sensor_fusion[i][6];
// find vehicles in recommended lane
if(d < (2+4*rec_lane+2) && d > (2+4*rec_lane-2))
{
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx*vx + vy *vy);
double check_car_s = sensor_fusion[i][5];
//cout<<"current s of veh " << check_car_s << " \n";
double check_car_s_x = check_car_s;
check_car_s_x += ((double)prev_size * 0.02 * check_speed); //extrapolate veh s position
//cout<<"extra s of veh " << check_car_s_x << " \n";
double dist = car_s - check_car_s;
double dist_x = car_s_x - check_car_s_x;
cout<<" dist: " << dist << " \n";
cout<<" dist extrapolated: " << dist_x << " \n";
cout<<" dist same_lane: " << same_lane_dist << " \n";
// check if current distance, extrapolated distance to target lane or distance in own lane too small
if ( (dist_x > 0 && dist_x < 15 ) || (dist_x < 0 && dist_x > -15) || (std::abs(dist) < 15) || (same_lane_dist < 10) ) // car getting close in s-dimension
{
// not feasible, so stay in current lane
cout<<" not enough space to switch, staying here \n";
rec_lane = lane;
}
}
}
// return recommended lane
cout<<"recommended lane is " << rec_lane << " \n";
return rec_lane;
}
cout<<"recommend to stay in " << rec_lane << " \n";
return rec_lane;
}
bool find_lane_change(int lane, vector<vector<double>> sensor_fusion, int prev_size, double car_s)
{
/* find lane changers, if found return true
* currently also triggers if cars leave our lane, could be improved
*/
for(int i = 0; i < sensor_fusion.size(); i++)
{
float d = sensor_fusion[i][6];
double s = sensor_fusion[i][5];
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx*vx + vy *vy);
s += ((double)prev_size * 0.02 * check_speed); //extrapolate veh s position
if (car_s < s) //if car is in front
{
if( (lane == 0) && (d > 3) && (d<5))
{return true;}
if( (lane == 1) && ((d > 3) && (d<5)) || ( (d > 7) && (d<9) ))
{return true;}
if( (lane == 2) && (d > 7) && (d<9))
{return true;}
}
return false;
}
}
| 29.714912 | 161 | 0.601919 |
87f3b27586d6ffea1b2d3b216f9bea13a9ef1fad | 12,602 | cpp | C++ | game_server/test/misc_test.cpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | 5 | 2017-07-20T10:36:23.000Z | 2018-01-30T16:18:31.000Z | game_server/test/misc_test.cpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | null | null | null | game_server/test/misc_test.cpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | null | null | null | #include "misc_test.hpp"
#include <cstring>
#include <cstdio>
#include <cinttypes>
#include <constants.hpp>
using namespace std;
int fails = 0;
int tests = 0;
int math_tests()
{
fails = 0;
tests = 0;
// TODO tests go here
//test binary_to_num
string test1 = "1101";
string test2 = "00001101";
string test3 = "11000011010011111";
string test4 = "0000100110011010";
string test5 = "100110011010";
unsigned long test6 = 70;
unsigned long test7 = 63;
unsigned long test8 = 0;
unsigned long test9 = 7;
unsigned long test10 = 8;
string test11 = "000000111";
string test12 = "000000111111";
string test13 = "0010000";
string test14 = "000100000";
string test15 = "000100001";
string test16 = "Mihai";
string test17 = "journey";
string test18 = "persona";
string test19 = "car";
string test20 = "cat";
string test21 = "";
tests++;
if(13 != binary_to_num(test1)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(13 != binary_to_num(test2)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(99999 != binary_to_num(test3)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(2458 != binary_to_num(test4)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(2458 != binary_to_num(test5)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
//test num_to_binary
tests++;
if(!str_eq("01000110", num_to_binary(test6))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
string s = num_to_binary(test6);
printf("HERE:%s\n", s.c_str());
fails++;
}
tests++;
if(!str_eq("00111111", num_to_binary(test7))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00000000", num_to_binary(test8))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00000111", num_to_binary(test9))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00001000", num_to_binary(test10))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
//test encode_six_bits
tests++;
if(7 != encode_six_bits(test11, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(7 != encode_six_bits(test12, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(16 != encode_six_bits(test13, 1)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(32 != encode_six_bits(test14, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(33 != encode_six_bits(test15, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(!str_eq("TWloYWk=", encode_base64((unsigned char *) test16.c_str(), test16.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test16.c_str(), test16.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("am91cm5leQ==", encode_base64((unsigned char *) test17.c_str(), test17.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test17.c_str(), test17.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("cGVyc29uYQ==", encode_base64((unsigned char *) test18.c_str(), test18.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test18.c_str(), test18.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("Y2Fy", encode_base64((unsigned char *) test19.c_str(), test19.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test19.c_str(), test19.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("Y2F0", encode_base64((unsigned char *) test20.c_str(), test20.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test20.c_str(), test20.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("", encode_base64((unsigned char *) test21.c_str(), test21.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test21.c_str(), test21.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
//test encode_base64.
fprintf(stderr, "%d/%d tests passed - math\n", tests - fails, tests);
return fails;
}
int strings_tests()
{
fails = 0;
tests = 0;
// in tests
tests++;
if(!in(' ', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\f', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\n', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\r', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\t', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\v', STR_WHITE)){fails++; fprintf(stderr, "In failing\n");}
tests++;
if(in(' ', "")){fails++; fprintf(stderr, "In failing empty\n");}
tests++;
if(in(' ', "asdefaersdvkdjlvc")){fails++; fprintf(stderr, "In failing not\n");}
tests++;
if(!in('A', "AAAAAAAAAAAAAAAAAAAAA")){fails++; fprintf(stderr, "In failing many\n");}
tests++;
if(!in('A', "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWA")){fails++; fprintf(stderr, "In failing long\n");}
// skip_ws tests
tests++;
if(*(skip_ws(" qwe")) != 'q'){fails++; fprintf(stderr, "skipped ws failing\n");}
tests++;
if(*(skip_ws(" \n\n\n")) != (char)0){fails++; fprintf(stderr, "skipped ws failing around sentinel\n");}
tests++;
if(*(skip_ws("")) != (char)0){fails++; fprintf(stderr, "skipped ws failing for empty\n");}
tests++;
if(*(skip_ws("asd")) != 'a'){fails++; fprintf(stderr, "skipped ws when not required\n");}
// string_seek tests
tests++;
if(*(string_seek("asdqwerty", "asd")) != 'q'){fails++; fprintf(stderr, "mismatch at asd\n");}
tests++;
if(*(string_seek("key: MAGIC_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGIC\n");}
tests++;
if(*(string_seek("kkey: MAGICKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICKA\n");}
tests++;
if(*(string_seek("kkkkkkkkkkkkkey: MAGICA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICA\n");}
tests++;
if(*(string_seek("key: MADOKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MADOKA\n");}
tests++;
if(*(string_seek("kkey: MAGIKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at kkey\n");}
tests++;
if(*(string_seek("kkkkkkkkkkkkkey: AGICKA_KEY", "key:")) != 'A'){fails++; fprintf(stderr, "mismatch at AGICKA\n");}
tests++;
if(string_seek("qwertyuiop", "key") != NULL){fails++; fprintf(stderr, "mismatch at never\n");}
tests++;
if(string_seek("kekeroni macaroni.", "key") != NULL){fails++; fprintf(stderr, "mismatch at kek\n");}
tests++;
if(*(string_seek(" lorem ipsum", "lorem")) != 'i'){fails++; fprintf(stderr, "mismatch at lorem\n");}
tests++;
if(*(string_seek(" lorem ipsum", "lore")) != 'm'){fails++; fprintf(stderr, "mismatch at lore\n");}
tests++;
if(string_seek("", "key") != NULL){fails++; fprintf(stderr, "mismatch at null\n");}
// string_get_next_token tests
string tok;
tests++;
if((tok = string_get_next_token("qwert", "ert")).compare("qw")){fails++; fprintf(stderr, "mismatch token qwe1\n got \"%s\" expected qw\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("qwert", "tr")).compare("qwe")){fails++; fprintf(stderr, "mismatch token qwe2\n got \"%s\" expected qwe\n", tok.c_str());}
tests++;
if((tok = string_get_next_token(" ", STR_WHITE)).compare("")){fails++; fprintf(stderr, "mismatch token empty ws\n got \"%s\" expected nothing\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("asdqwe ", STR_WHITE)).compare("asdqwe")){fails++; fprintf(stderr, "mismatch token full ws\n got \"%s\" expected asdqwe\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("asdqwetyi", STR_WHITE)).compare("asdqwetyi")){fails++; fprintf(stderr, "mismatch token no separator\n got \"%s\" expected asdqwetyi\n", tok.c_str());}
tests++;
if((tok = string_get_next_token(STR_WHITE, "")).compare(STR_WHITE)){fails++; fprintf(stderr, "mismatch token null separator\n got \"%s\" expected whitespace\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("", "")).compare("")){fails++; fprintf(stderr, "mismatch token empty insanity\n got \"%s\" expected nothing\n", tok.c_str());}
// is_num tests
tests++;
if(!is_num("0")){fails++; fprintf(stderr, "0 not detected as numeric\n");}
tests++;
if(!is_num("-0")){fails++; fprintf(stderr, "-0 not detected as numeric\n");}
tests++;
if(!is_num("-12312312312312321321321321312")){fails++; fprintf(stderr, "-long not detected as numeric\n");}
tests++;
if(is_num("-----123")){fails++; fprintf(stderr, "multiple negation detected as numeric\n");}
tests++;
if(is_num(" ")){fails++; fprintf(stderr, "space detected as numeric\n");}
tests++;
if(is_num("-")){fails++; fprintf(stderr, "Just minus detected as numeric\n");}
tests++;
if(is_num("-asd123")){fails++; fprintf(stderr, "minus string detected as numeric\n");}
tests++;
if(is_num("asdqwe")){fails++; fprintf(stderr, "text detected as numeric\n");}
tests++;
if(!is_num("1asdqwe")){fails++; fprintf(stderr, "number prefix not detected as numeric\n");}
tests++;
if(!is_num("-4asdqwe")){fails++; fprintf(stderr, "negative number prefix not detected as numeric\n");}
// combination tests
tests++;
if((tok = string_get_next_token(string_seek("HTTP1/1 GET /\nws_key: asdqwemihai", "ws_key:"), STR_WHITE)).compare("asdqwemihai")){fails++; fprintf(stderr, "failed key detection\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "x=")
, " \n\t\f\r\v&")
.compare("1"))
{fails++; fprintf(stderr, "failed argument parsing for x(first)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "y=")
, " \n\t\f\r\v&")
.compare("2"))
{fails++; fprintf(stderr, "failed argument parsing for y(second)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "t=")
, " \n\t\f\r\v&")
.compare("3"))
{fails++; fprintf(stderr, "failed argument parsing for t(third)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "k=")
, " \n\t\f\r\v&")
.compare(""))
{fails++; fprintf(stderr, "failed argument parsing for t(third)\n");}
// null propagation testing
tests++;
if(in('U', NULL)){fails++; fprintf(stderr, "Null propagation failing for in\n");}
tests++;
if(skip_ws(NULL)){fails++; fprintf(stderr, "Null propagation failing for skip_ws\n");}
tests++;
if(string_seek(NULL, "qwe")){fails++; fprintf(stderr, "Null propagation failing for seek(origin)\n");}
tests++;
if(string_seek("qwe", NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(target)\n");}
tests++;
if(string_seek(NULL, NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(both)\n");}
tests++;
if(string_get_next_token(FIXED_STRING, NULL).compare(FIXED_STRING)){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should work\n");}
tests++;
if(string_get_next_token(NULL, FIXED_STRING).compare("")){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should fail\n");}
tests++;
if(is_num("")){fails++; fprintf(stderr, "empty detected as numeric\n");}
tests++;
if(is_num(NULL)){fails++; fprintf(stderr, "null detected as numeric\n");}
// results and finish
fprintf(stderr, "%d/%d tests passed - strings\n", tests - fails, tests);
return fails;
}
int main()
{
return math_tests() + strings_tests();
}
| 38.656442 | 187 | 0.610062 |
87f60818cf08ceae83d9cce078c75e5de85c125d | 33,887 | cpp | C++ | Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp | 499453466/Lua-Other | 43fd2b72405faf3f2074fd2a2706ef115d16faa6 | [
"Unlicense"
] | 2 | 2015-06-23T16:26:32.000Z | 2019-06-27T07:45:59.000Z | Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | null | null | null | Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | 3 | 2015-01-10T18:22:59.000Z | 2021-04-27T21:28:28.000Z | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2011 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*
*/
/*
English Worldstrings as of 08.16.2009
entry text
1 I would like to browse your goods.
2 I seek
3 mage
4 shaman
5 warrior
6 paladin
7 warlock
8 hunter
9 rogue
10 druid
11 priest
12 training
13 Train me in the ways of the beast.
14 Give me a ride.
15 I would like to make a bid.
16 Make this inn your home.
17 I would like to check my deposit box.
18 Bring me back to life.
19 How do I create a guild/arena team?
20 I want to create a guild crest.
21 I would like to go to the battleground.
22 I would like to reset my talents.
23 I wish to untrain my pet.
24 I understand, continue.
25 Yes, please do.
26 This instance is unavailable.
27 You must have The Burning Crusade Expansion to access this content.
28 Heroic mode unavailable for this instance.
29 You must be in a raid group to pass through here.
30 You do not have the required attunement to pass through here.
31 You must be at least level %u to pass through here.
32 You must be in a party to pass through here.
33 You must be level 70 to enter heroic mode.
34 -
35 You must have the item, `%s` to pass through here.
36 You must have the item, UNKNOWN to pass through here.
37 What can I teach you, $N?
38 Alterac Valley
39 Warsong Gulch
40 Arathi Basin
41 Arena 2v2
42 Arena 3v3
43 Arena 5v5
44 Eye of the Storm
45 Unknown Battleground
46 One minute until the battle for %s begins!
47 Thirty seconds until the battle for %s begins!
48 Fifteen seconds until the battle for %s begins!
49 The battle for %s has begun!
50 Arena
51 You have tried to join an invalid instance id.
52 Your queue on battleground instance id %u is no longer valid. Reason: Instance Deleted.
53 You cannot join this battleground as it has already ended.
54 Your queue on battleground instance %u is no longer valid, the instance no longer exists.
55 Sorry, raid groups joining battlegrounds are currently unsupported.
56 You must be the party leader to add a group to an arena.
57 You must be in a team to join rated arena.
58 You have too many players in your party to join this type of arena.
59 Sorry, some of your party members are not level 70.
60 One or more of your party members are already queued or inside a battleground.
61 One or more of your party members are not members of your team.
62 Welcome to
63 Horde
64 Alliance
65 [ |cff00ccffAttention|r ] Welcome! A new challenger (|cff00ff00{%d}|r - |cffff0000%s|r) has arrived and joined into |cffff0000%s|r,their force has already been increased.
66 This instance is scheduled to reset on
67 Auto loot passing is now %s
68 On
69 Off
70 Hey there, $N. How can I help you?
71 You are already in an arena team.
72 That name is already in use.
73 You already have an arena charter.
74 A guild with that name already exists.
75 You already have a guild charter.
76 Item not found.
77 Target is of the wrong faction.
78 Target player cannot sign your charter for one or more reasons.
79 You have already signed that charter.
80 You don't have the required amount of signatures to turn in this petition.
81 You must have Wrath of the Lich King Expansion to access this content.
82 Deathknight
*/
#include "StdAfx.h"
#include <git_version.h>
namespace worldstring
{
}
initialiseSingleton(ScriptMgr);
initialiseSingleton(HookInterface);
ScriptMgr::ScriptMgr()
{
}
ScriptMgr::~ScriptMgr()
{
}
struct ScriptingEngine_dl
{
Arcemu::DynLib* dl;
exp_script_register InitializeCall;
uint32 Type;
ScriptingEngine_dl()
{
dl = NULL;
InitializeCall = NULL;
Type = 0;
}
};
void ScriptMgr::LoadScripts()
{
if(HookInterface::getSingletonPtr() == NULL)
new HookInterface;
Log.Success("Server", "Loading External Script Libraries...");
std::string Path;
std::string FileMask;
Path = PREFIX;
Path += '/';
#ifdef WIN32
/*Path = Config.MainConfig.GetStringDefault( "Script", "BinaryLocation", "script_bin" );
Path += "\\";*/
FileMask = ".dll";
#else
#ifndef __APPLE__
FileMask = ".so";
#else
FileMask = ".dylib";
#endif
#endif
Arcemu::FindFilesResult findres;
std::vector< ScriptingEngine_dl > Engines;
Arcemu::FindFiles(Path.c_str(), FileMask.c_str(), findres);
uint32 count = 0;
while(findres.HasNext())
{
std::stringstream loadmessage;
std::string fname = Path + findres.GetNext();
Arcemu::DynLib* dl = new Arcemu::DynLib(fname.c_str());
loadmessage << " " << dl->GetName() << " : ";
if(!dl->Load())
{
loadmessage << "ERROR: Cannot open library.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
exp_get_version vcall = reinterpret_cast< exp_get_version >(dl->GetAddressForSymbol("_exp_get_version"));
exp_script_register rcall = reinterpret_cast< exp_script_register >(dl->GetAddressForSymbol("_exp_script_register"));
exp_get_script_type scall = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if((vcall == NULL) || (rcall == NULL) || (scall == NULL))
{
loadmessage << "ERROR: Cannot find version functions.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
const char *version = vcall();
uint32 stype = scall();
if( strcmp( version, BUILD_HASH_STR ) != 0 )
{
loadmessage << "ERROR: Version mismatch.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
loadmessage << ' ' << std::string( BUILD_HASH_STR ) << " : ";
if((stype & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
ScriptingEngine_dl se;
se.dl = dl;
se.InitializeCall = rcall;
se.Type = stype;
Engines.push_back(se);
loadmessage << "delayed load";
}
else
{
rcall(this);
dynamiclibs.push_back(dl);
loadmessage << "loaded";
}
LOG_BASIC(loadmessage.str().c_str());
count++;
}
}
}
}
if(count == 0)
{
LOG_ERROR(" No external scripts found! Server will continue to function with limited functionality.");
}
else
{
Log.Success("Server", "Loaded %u external libraries.", count);
Log.Success("Server", "Loading optional scripting engine(s)...");
for(std::vector< ScriptingEngine_dl >::iterator itr = Engines.begin(); itr != Engines.end(); ++itr)
{
itr->InitializeCall(this);
dynamiclibs.push_back(itr->dl);
}
Log.Success("Server", "Done loading scripting engine(s)...");
}
}
void ScriptMgr::UnloadScripts()
{
if(HookInterface::getSingletonPtr())
delete HookInterface::getSingletonPtr();
for(CustomGossipScripts::iterator itr = _customgossipscripts.begin(); itr != _customgossipscripts.end(); ++itr)
(*itr)->Destroy();
_customgossipscripts.clear();
for(QuestScripts::iterator itr = _questscripts.begin(); itr != _questscripts.end(); ++itr)
delete *itr;
_questscripts.clear();
UnloadScriptEngines();
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
delete *itr;
dynamiclibs.clear();
}
void ScriptMgr::DumpUnimplementedSpells()
{
std::ofstream of;
LOG_BASIC("Dumping IDs for spells with unimplemented dummy/script effect(s)");
uint32 count = 0;
of.open("unimplemented1.txt");
for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr)
{
SpellEntry* sp = *itr;
if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
continue;
HandleDummySpellMap::iterator sitr = _spells.find(sp->Id);
if(sitr != _spells.end())
continue;
HandleScriptEffectMap::iterator seitr = SpellScriptEffects.find(sp->Id);
if(seitr != SpellScriptEffects.end())
continue;
std::stringstream ss;
ss << sp->Id;
ss << std::endl;
of.write(ss.str().c_str(), ss.str().length());
count++;
}
of.close();
LOG_BASIC("Dumped %u IDs.", count);
LOG_BASIC("Dumping IDs for spells with unimplemented dummy aura effect.");
std::ofstream of2;
of2.open("unimplemented2.txt");
count = 0;
for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr)
{
SpellEntry* sp = *itr;
if(!sp->AppliesAura(SPELL_AURA_DUMMY))
continue;
HandleDummyAuraMap::iterator ditr = _auras.find(sp->Id);
if(ditr != _auras.end())
continue;
std::stringstream ss;
ss << sp->Id;
ss << std::endl;
of2.write(ss.str().c_str(), ss.str().length());
count++;
}
of2.close();
LOG_BASIC("Dumped %u IDs.", count);
}
void ScriptMgr::register_creature_script(uint32 entry, exp_create_creature_ai callback)
{
if(_creatures.find(entry) != _creatures.end())
LOG_ERROR("ScriptMgr is trying to register a script for Creature ID: %u even if there's already one for that Creature. Remove one of those scripts.", entry);
_creatures.insert(CreatureCreateMap::value_type(entry, callback));
}
void ScriptMgr::register_gameobject_script(uint32 entry, exp_create_gameobject_ai callback)
{
if(_gameobjects.find(entry) != _gameobjects.end())
LOG_ERROR("ScriptMgr is trying to register a script for GameObject ID: %u even if there's already one for that GameObject. Remove one of those scripts.", entry);
_gameobjects.insert(GameObjectCreateMap::value_type(entry, callback));
}
void ScriptMgr::register_dummy_aura(uint32 entry, exp_handle_dummy_aura callback)
{
if(_auras.find(entry) != _auras.end())
{
LOG_ERROR("ScriptMgr is trying to register a script for Aura ID: %u even if there's already one for that Aura. Remove one of those scripts.", entry);
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr is trying to register a dummy aura handler for Spell ID: %u which is invalid.", entry);
return;
}
if(!sp->AppliesAura(SPELL_AURA_DUMMY) && !sp->AppliesAura(SPELL_AURA_PERIODIC_TRIGGER_DUMMY))
LOG_ERROR("ScriptMgr has registered a dummy aura handler for Spell ID: %u ( %s ), but spell has no dummy aura!", entry, sp->Name);
_auras.insert(HandleDummyAuraMap::value_type(entry, callback));
}
void ScriptMgr::register_dummy_spell(uint32 entry, exp_handle_dummy_spell callback)
{
if(_spells.find(entry) != _spells.end())
{
LOG_ERROR("ScriptMgr is trying to register a script for Spell ID: %u even if there's already one for that Spell. Remove one of those scripts.", entry);
return;
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr is trying to register a dummy handler for Spell ID: %u which is invalid.", entry);
return;
}
if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
LOG_ERROR("ScriptMgr has registered a dummy handler for Spell ID: %u ( %s ), but spell has no dummy/script/send event effect!", entry, sp->Name);
_spells.insert(HandleDummySpellMap::value_type(entry, callback));
}
void ScriptMgr::register_gossip_script(uint32 entry, GossipScript* gs)
{
register_creature_gossip(entry, gs);
}
void ScriptMgr::register_go_gossip_script(uint32 entry, GossipScript* gs)
{
register_go_gossip(entry, gs);
}
void ScriptMgr::register_quest_script(uint32 entry, QuestScript* qs)
{
Quest* q = QuestStorage.LookupEntry(entry);
if(q != NULL)
{
if(q->pQuestScript != NULL)
LOG_ERROR("ScriptMgr is trying to register a script for Quest ID: %u even if there's already one for that Quest. Remove one of those scripts.", entry);
q->pQuestScript = qs;
}
_questscripts.insert(qs);
}
void ScriptMgr::register_instance_script(uint32 pMapId, exp_create_instance_ai pCallback)
{
if(mInstances.find(pMapId) != mInstances.end())
LOG_ERROR("ScriptMgr is trying to register a script for Instance ID: %u even if there's already one for that Instance. Remove one of those scripts.", pMapId);
mInstances.insert(InstanceCreateMap::value_type(pMapId, pCallback));
};
void ScriptMgr::register_creature_script(uint32* entries, exp_create_creature_ai callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_creature_script(entries[y], callback);
}
};
void ScriptMgr::register_gameobject_script(uint32* entries, exp_create_gameobject_ai callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_gameobject_script(entries[y], callback);
}
};
void ScriptMgr::register_dummy_aura(uint32* entries, exp_handle_dummy_aura callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_dummy_aura(entries[y], callback);
}
};
void ScriptMgr::register_dummy_spell(uint32* entries, exp_handle_dummy_spell callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_dummy_spell(entries[y], callback);
}
};
void ScriptMgr::register_script_effect(uint32* entries, exp_handle_script_effect callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_script_effect(entries[y], callback);
}
};
void ScriptMgr::register_script_effect(uint32 entry, exp_handle_script_effect callback)
{
HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(entry);
if(itr != SpellScriptEffects.end())
{
LOG_ERROR("ScriptMgr tried to register more than 1 script effect handlers for Spell %u", entry);
return;
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr tried to register a script effect handler for Spell %u, which is invalid.", entry);
return;
}
if(!sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
LOG_ERROR("ScriptMgr has registered a script effect handler for Spell ID: %u ( %s ), but spell has no scripted effect!", entry, sp->Name);
SpellScriptEffects.insert(std::pair< uint32, exp_handle_script_effect >(entry, callback));
}
CreatureAIScript* ScriptMgr::CreateAIScriptClassForEntry(Creature* pCreature)
{
CreatureCreateMap::iterator itr = _creatures.find(pCreature->GetEntry());
if(itr == _creatures.end())
return NULL;
exp_create_creature_ai function_ptr = itr->second;
return (function_ptr)(pCreature);
}
GameObjectAIScript* ScriptMgr::CreateAIScriptClassForGameObject(uint32 uEntryId, GameObject* pGameObject)
{
GameObjectCreateMap::iterator itr = _gameobjects.find(pGameObject->GetEntry());
if(itr == _gameobjects.end())
return NULL;
exp_create_gameobject_ai function_ptr = itr->second;
return (function_ptr)(pGameObject);
}
InstanceScript* ScriptMgr::CreateScriptClassForInstance(uint32 pMapId, MapMgr* pMapMgr)
{
InstanceCreateMap::iterator Iter = mInstances.find(pMapMgr->GetMapId());
if(Iter == mInstances.end())
return NULL;
exp_create_instance_ai function_ptr = Iter->second;
return (function_ptr)(pMapMgr);
};
bool ScriptMgr::CallScriptedDummySpell(uint32 uSpellId, uint32 i, Spell* pSpell)
{
HandleDummySpellMap::iterator itr = _spells.find(uSpellId);
if(itr == _spells.end())
return false;
exp_handle_dummy_spell function_ptr = itr->second;
return (function_ptr)(i, pSpell);
}
bool ScriptMgr::HandleScriptedSpellEffect(uint32 SpellId, uint32 i, Spell* s)
{
HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(SpellId);
if(itr == SpellScriptEffects.end())
return false;
exp_handle_script_effect ptr = itr->second;
return (ptr)(i, s);
}
bool ScriptMgr::CallScriptedDummyAura(uint32 uSpellId, uint32 i, Aura* pAura, bool apply)
{
HandleDummyAuraMap::iterator itr = _auras.find(uSpellId);
if(itr == _auras.end())
return false;
exp_handle_dummy_aura function_ptr = itr->second;
return (function_ptr)(i, pAura, apply);
}
bool ScriptMgr::CallScriptedItem(Item* pItem, Player* pPlayer)
{
Arcemu::Gossip::Script* script = this->get_item_gossip(pItem->GetEntry());
if(script != NULL)
{
script->OnHello(pItem, pPlayer);
return true;
}
return false;
}
void ScriptMgr::register_item_gossip_script(uint32 entry, GossipScript* gs)
{
register_item_gossip(entry, gs);
}
/* CreatureAI Stuff */
CreatureAIScript::CreatureAIScript(Creature* creature) : _unit(creature), linkedCreatureAI(NULL)
{
}
CreatureAIScript::~CreatureAIScript()
{
//notify our linked creature that we are being deleted.
if(linkedCreatureAI != NULL)
linkedCreatureAI->LinkedCreatureDeleted();
}
void CreatureAIScript::RegisterAIUpdateEvent(uint32 frequency)
{
//sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0,0);
sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
void CreatureAIScript::ModifyAIUpdateEvent(uint32 newfrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(_unit, EVENT_SCRIPT_UPDATE_EVENT, newfrequency);
}
void CreatureAIScript::RemoveAIUpdateEvent()
{
sEventMgr.RemoveEvents(_unit, EVENT_SCRIPT_UPDATE_EVENT);
}
void CreatureAIScript::LinkedCreatureDeleted()
{
linkedCreatureAI = NULL;
}
void CreatureAIScript::SetLinkedCreature(CreatureAIScript* creatureAI)
{
//notify our linked creature that we are not more linked
if(linkedCreatureAI != NULL)
linkedCreatureAI->LinkedCreatureDeleted();
//link to the new creature
linkedCreatureAI = creatureAI;
}
bool CreatureAIScript::IsAlive()
{
return _unit->isAlive();
}
/* GameObjectAI Stuff */
GameObjectAIScript::GameObjectAIScript(GameObject* goinstance) : _gameobject(goinstance)
{
}
void GameObjectAIScript::ModifyAIUpdateEvent(uint32 newfrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(_gameobject, EVENT_SCRIPT_UPDATE_EVENT, newfrequency);
}
void GameObjectAIScript::RemoveAIUpdateEvent()
{
sEventMgr.RemoveEvents(_gameobject, EVENT_SCRIPT_UPDATE_EVENT);
}
void GameObjectAIScript::RegisterAIUpdateEvent(uint32 frequency)
{
sEventMgr.AddEvent(_gameobject, &GameObject::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
/* InstanceAI Stuff */
InstanceScript::InstanceScript(MapMgr* pMapMgr) : mInstance(pMapMgr)
{
};
void InstanceScript::RegisterUpdateEvent(uint32 pFrequency)
{
sEventMgr.AddEvent(mInstance, &MapMgr::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, pFrequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
};
void InstanceScript::ModifyUpdateEvent(uint32 pNewFrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(mInstance, EVENT_SCRIPT_UPDATE_EVENT, pNewFrequency);
};
void InstanceScript::RemoveUpdateEvent()
{
sEventMgr.RemoveEvents(mInstance, EVENT_SCRIPT_UPDATE_EVENT);
};
/* Hook Stuff */
void ScriptMgr::register_hook(ServerHookEvents event, void* function_pointer)
{
ARCEMU_ASSERT(event < NUM_SERVER_HOOKS);
_hooks[event].insert(function_pointer);
}
bool ScriptMgr::has_creature_script(uint32 entry) const
{
return (_creatures.find(entry) != _creatures.end());
}
bool ScriptMgr::has_gameobject_script(uint32 entry) const
{
return (_gameobjects.find(entry) != _gameobjects.end());
}
bool ScriptMgr::has_dummy_aura_script(uint32 entry) const
{
return (_auras.find(entry) != _auras.end());
}
bool ScriptMgr::has_dummy_spell_script(uint32 entry) const
{
return (_spells.find(entry) != _spells.end());
}
bool ScriptMgr::has_script_effect(uint32 entry) const
{
return (SpellScriptEffects.find(entry) != SpellScriptEffects.end());
}
bool ScriptMgr::has_instance_script(uint32 id) const
{
return (mInstances.find(id) != mInstances.end());
}
bool ScriptMgr::has_hook(ServerHookEvents evt, void* ptr) const
{
return (_hooks[evt].size() != 0 && _hooks[evt].find(ptr) != _hooks[evt].end());
}
bool ScriptMgr::has_quest_script(uint32 entry) const
{
Quest* q = QuestStorage.LookupEntry(entry);
return (q == NULL || q->pQuestScript != NULL);
}
void ScriptMgr::register_creature_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = creaturegossip_.find(entry);
if(itr == creaturegossip_.end())
creaturegossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
bool ScriptMgr::has_creature_gossip(uint32 entry) const
{
return creaturegossip_.find(entry) != creaturegossip_.end();
}
Arcemu::Gossip::Script* ScriptMgr::get_creature_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = creaturegossip_.find(entry);
if(itr != creaturegossip_.end())
return itr->second;
return NULL;
}
void ScriptMgr::register_item_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = itemgossip_.find(entry);
if(itr == itemgossip_.end())
itemgossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
void ScriptMgr::register_go_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = gogossip_.find(entry);
if(itr == gogossip_.end())
gogossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
bool ScriptMgr::has_item_gossip(uint32 entry) const
{
return itemgossip_.find(entry) != itemgossip_.end();
}
bool ScriptMgr::has_go_gossip(uint32 entry) const
{
return gogossip_.find(entry) != gogossip_.end();
}
Arcemu::Gossip::Script* ScriptMgr::get_go_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = gogossip_.find(entry);
if(itr != gogossip_.end())
return itr->second;
return NULL;
}
Arcemu::Gossip::Script* ScriptMgr::get_item_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = itemgossip_.find(entry);
if(itr != itemgossip_.end())
return itr->second;
return NULL;
}
void ScriptMgr::ReloadScriptEngines()
{
//for all scripting engines that allow reloading, assuming there will be new scripting engines.
exp_get_script_type version_function;
exp_engine_reload engine_reloadfunc;
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
{
Arcemu::DynLib* dl = *itr;
version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if(version_function == NULL)
continue;
if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
engine_reloadfunc = reinterpret_cast< exp_engine_reload >(dl->GetAddressForSymbol("_export_engine_reload"));
if(engine_reloadfunc != NULL)
engine_reloadfunc();
}
}
}
void ScriptMgr::UnloadScriptEngines()
{
//for all scripting engines that allow unloading, assuming there will be new scripting engines.
exp_get_script_type version_function;
exp_engine_unload engine_unloadfunc;
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
{
Arcemu::DynLib* dl = *itr;
version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if(version_function == NULL)
continue;
if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
engine_unloadfunc = reinterpret_cast< exp_engine_unload >(dl->GetAddressForSymbol("_exp_engine_unload"));
if(engine_unloadfunc != NULL)
engine_unloadfunc();
}
}
}
//support for Gossip scripts added before r4106 changes
void GossipScript::OnHello(Object* pObject, Player* Plr)
{
GossipHello(pObject, Plr);
}
void GossipScript::OnSelectOption(Object* pObject, Player* Plr, uint32 Id, const char* EnteredCode)
{
uint32 IntId = Id;
if(Plr->CurrentGossipMenu != NULL)
{
GossipMenuItem item = Plr->CurrentGossipMenu->GetItem(Id);
IntId = item.IntId;
}
GossipSelectOption(pObject, Plr, Id , IntId, EnteredCode);
}
void GossipScript::OnEnd(Object* pObject, Player* Plr)
{
GossipEnd(pObject, Plr);
}
/* Hook Implementations */
bool HookInterface::OnNewCharacter(uint32 Race, uint32 Class, WorldSession* Session, const char* Name)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_NEW_CHARACTER];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnNewCharacter) * itr)(Race, Class, Session, Name);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnKillPlayer(Player* pPlayer, Player* pVictim)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_KILL_PLAYER];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnKillPlayer)*itr)(pPlayer, pVictim);
}
void HookInterface::OnFirstEnterWorld(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FIRST_ENTER_WORLD];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnFirstEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnCharacterCreate(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHARACTER_CREATE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOCharacterCreate)*itr)(pPlayer);
}
void HookInterface::OnEnterWorld(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_WORLD];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnGuildCreate(Player* pLeader, Guild* pGuild)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_CREATE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnGuildCreate)*itr)(pLeader, pGuild);
}
void HookInterface::OnGuildJoin(Player* pPlayer, Guild* pGuild)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_JOIN];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnGuildJoin)*itr)(pPlayer, pGuild);
}
void HookInterface::OnDeath(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DEATH];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnDeath)*itr)(pPlayer);
}
bool HookInterface::OnRepop(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_REPOP];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnRepop) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_EMOTE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEmote)*itr)(pPlayer, Emote, pUnit);
}
void HookInterface::OnEnterCombat(Player* pPlayer, Unit* pTarget)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_COMBAT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterCombat)*itr)(pPlayer, pTarget);
}
bool HookInterface::OnCastSpell(Player* pPlayer, SpellEntry* pSpell, Spell* spell)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CAST_SPELL];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnCastSpell) * itr)(pPlayer, pSpell, spell);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
bool HookInterface::OnLogoutRequest(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT_REQUEST];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnLogoutRequest) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnLogout(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnLogout)*itr)(pPlayer);
}
void HookInterface::OnQuestAccept(Player* pPlayer, Quest* pQuest, Object* pQuestGiver)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_ACCEPT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestAccept)*itr)(pPlayer, pQuest, pQuestGiver);
}
void HookInterface::OnZone(Player* pPlayer, uint32 zone, uint32 oldZone)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ZONE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnZone)*itr)(pPlayer, zone, oldZone);
}
bool HookInterface::OnChat(Player* pPlayer, uint32 type, uint32 lang, const char* message, const char* misc)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHAT];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnChat) * itr)(pPlayer, type, lang, message, misc);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnLoot(Player* pPlayer, Unit* pTarget, uint32 money, uint32 itemId)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOOT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnLoot)*itr)(pPlayer, pTarget, money, itemId);
}
void HookInterface::OnObjectLoot(Player* pPlayer, Object* pTarget, uint32 money, uint32 itemId)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_OBJECTLOOT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnObjectLoot)*itr)(pPlayer, pTarget, money, itemId);
}
void HookInterface::OnFullLogin(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FULL_LOGIN];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnQuestCancelled(Player* pPlayer, Quest* pQuest)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_CANCELLED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestCancel)*itr)(pPlayer, pQuest);
}
void HookInterface::OnQuestFinished(Player* pPlayer, Quest* pQuest, Object* pQuestGiver)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_FINISHED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestFinished)*itr)(pPlayer, pQuest, pQuestGiver);
}
void HookInterface::OnHonorableKill(Player* pPlayer, Player* pKilled)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_HONORABLE_KILL];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnHonorableKill)*itr)(pPlayer, pKilled);
}
void HookInterface::OnArenaFinish(Player* pPlayer, ArenaTeam* pTeam, bool victory, bool rated)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ARENA_FINISH];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnArenaFinish)*itr)(pPlayer, pTeam, victory, rated);
}
void HookInterface::OnAreaTrigger(Player* pPlayer, uint32 areaTrigger)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AREATRIGGER];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAreaTrigger)*itr)(pPlayer, areaTrigger);
}
void HookInterface::OnPostLevelUp(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_POST_LEVELUP];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnPostLevelUp)*itr)(pPlayer);
}
bool HookInterface::OnPreUnitDie(Unit* killer, Unit* victim)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_PRE_DIE];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnPreUnitDie) * itr)(killer, victim);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnAdvanceSkillLine(Player* pPlayer, uint32 skillLine, uint32 current)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ADVANCE_SKILLLINE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAdvanceSkillLine)*itr)(pPlayer, skillLine, current);
}
void HookInterface::OnDuelFinished(Player* Winner, Player* Looser)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DUEL_FINISHED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnDuelFinished)*itr)(Winner, Looser);
}
void HookInterface::OnAuraRemove(Aura* aura)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AURA_REMOVE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAuraRemove)*itr)(aura);
}
bool HookInterface::OnResurrect(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_RESURRECT];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnResurrect) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
} | 30.25625 | 174 | 0.741051 |
87ff0fe2e6931d5ab67336efe927a2c045ad694d | 1,584 | cpp | C++ | Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | null | null | null | Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | null | null | null | Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | null | null | null | /*
Code without Objects
Suppose you were writing a program to model several cars.
In your program, you want to keep track of each car's color and the distance the car has traveled,
and you want to be able to increment this distance and print out the car's properties.
You could write something like the code below to accomplish this:
*/
#include <iostream>
#include <string>
using std::string;
using std::cout;
int main()
{
// Variables to hold each car's color.
string car_1_color = "green";
string car_2_color = "red";
string car_3_color = "blue";
// Variables to hold each car's initial position.
int car_1_distance = 0;
int car_2_distance = 0;
int car_3_distance = 0;
// Increment car_1's position by 1.
car_1_distance++;
// Print out the position and color of each car.
cout << "The distance that the " << car_1_color << " car 1 has traveled is: " << car_1_distance << "\n";
cout << "The distance that the " << car_2_color << " car 2 has traveled is: " << car_2_distance << "\n";
cout << "The distance that the " << car_3_color << " car 3 has traveled is: " << car_3_distance << "\n";
}
/*
This works for the few cars that are defined in the program,
but if you wanted the program to keep track of many cars this would be cumbersome.
You would need to create a new variables for every car, and the code would quickly become cluttered.
One way to fix this would be to define a Car class with those variables as attributes,
along with a few class methods to increment the distance traveled and print out car data.
*/
| 36 | 108 | 0.705177 |
e2008f873e49dc817c7bbea2579cd98fb7e09b25 | 4,792 | cpp | C++ | sdh/crc.cpp | ipab-slmc/SDHLibrary-CPP | 0217d4edf82f34292750240bd7a3d9c63feb7e33 | [
"Apache-2.0"
] | 2 | 2021-11-12T09:28:45.000Z | 2021-12-22T09:09:31.000Z | sdh/crc.cpp | ipab-slmc/SDHLibrary-CPP | 0217d4edf82f34292750240bd7a3d9c63feb7e33 | [
"Apache-2.0"
] | null | null | null | sdh/crc.cpp | ipab-slmc/SDHLibrary-CPP | 0217d4edf82f34292750240bd7a3d9c63feb7e33 | [
"Apache-2.0"
] | 2 | 2019-05-02T20:03:29.000Z | 2019-06-24T14:50:42.000Z | //======================================================================
/*!
\file
\section sdhlibrary_cpp_crc_cpp_general General file information
\author Dirk Osswald
\date 2007-02-19
\brief
Implementation of class #SDH::cCRC_DSACON32m (actually only the static members all other is derived).
\section sdhlibrary_cpp_crc_cpp_copyright Copyright
- Copyright (c) 2008 SCHUNK GmbH & Co. KG
<HR>
\internal
\subsection sdhlibrary_cpp_crc_cpp_details SVN related, detailed file specific information:
$LastChangedBy: Osswald2 $
$LastChangedDate: 2008-10-08 10:48:38 +0200 (Mi, 08 Okt 2008) $
\par SVN file revision:
$Id: crc.cpp 3659 2008-10-08 08:48:38Z Osswald2 $
\subsection sdhlibrary_cpp_crc_cpp_changelog Changelog of this file:
\include crc.cpp.log
*/
//======================================================================
#include "sdhlibrary_settings.h"
//----------------------------------------------------------------------
// System Includes - include with <>
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Project Includes - include with ""
//----------------------------------------------------------------------
#include "crc.h"
USING_NAMESPACE_SDH
//----------------------------------------------------------------------
// Defines, enums, unions, structs,
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global variables
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Function implementation (function definitions)
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Class member definitions
//----------------------------------------------------------------------
tCRCValue const cCRC_DSACON32m::crc_table_dsacon32m[256] =
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
};
//======================================================================
/*
Here are some settings for the emacs/xemacs editor (and can be safely ignored):
(e.g. to explicitely set C++ mode for *.h header files)
Local Variables:
mode:C++
mode:ELSE
End:
*/
//======================================================================
| 42.785714 | 105 | 0.515442 |
e207034aa51177b9803721c97bffdf7abe9ae688 | 279 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace rend {
enum class WindShapeAnchorPointVert : uint32_t
{
AP_CENTER = 0,
AP_TOP = 1,
AP_BOTTOM = 2,
};
} // namespace rend
} // namespace RED4ext
| 16.411765 | 57 | 0.698925 |
e20737d3135a49e21df6882d87d3d9136988046b | 786 | hpp | C++ | source/gui/LogEntry.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | 1 | 2021-12-26T12:48:18.000Z | 2021-12-26T12:48:18.000Z | source/gui/LogEntry.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | null | null | null | source/gui/LogEntry.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | 1 | 2021-12-26T12:48:25.000Z | 2021-12-26T12:48:25.000Z | #pragma once
#include <VehicleID.hpp>
class LogEntry {
public:
std::string timestamp;
std::string source;
std::string text;
uint8_t color[3];
/**
* @brief Create a log entry.
* @param [in] timestamp The UTC second of the day.
* @param [in] source Source of the log message.
* @param [in] text Text of the log message.
* @param [in] r Red component for text color.
* @param [in] g Green component for text color.
* @param [in] b Blue component for text color.
*/
LogEntry(double timestamp, const VehicleID& source, std::string& text, uint8_t r, uint8_t g, uint8_t b);
/**
* @brief Delete the log entry.
*/
~LogEntry();
};
| 25.354839 | 112 | 0.554707 |
e208cd81c87125355ee128e641604a7199345678 | 1,545 | cpp | C++ | libpigpiodpp/test/pihardwaremanagerfactorytests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | null | null | null | libpigpiodpp/test/pihardwaremanagerfactorytests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | 14 | 2019-11-17T14:46:25.000Z | 2021-03-10T02:48:40.000Z | libpigpiodpp/test/pihardwaremanagerfactorytests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include "tendril/devices/i2cdevicedata.hpp"
#include "tendril/devices/pca9685.hpp"
#include "pigpiodpp/pihardwaremanagerfactory.hpp"
BOOST_AUTO_TEST_SUITE( PiHardwareManagerFactory )
BOOST_AUTO_TEST_CASE( Smoke )
{
Tendril::HardwareManagerData config;
auto hwm = PiGPIOdpp::GetHardwareManager(config);
BOOST_REQUIRE( hwm );
BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("0") );
BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("1") );
}
BOOST_AUTO_TEST_CASE( WithPCA9685 )
{
const std::string devName = "MyServoProvider";
auto some9685 = std::make_shared<
Tendril::Devices::I2CDeviceData<Tendril::Devices::PCA9685>>();
some9685->i2cCommsRequest.providerName = "1";
some9685->i2cCommsRequest.idOnProvider = "0x10";
some9685->name = devName;
some9685->settings["referenceClock"] = "25e6";
some9685->settings["pwmFrequency"] = "60";
Tendril::HardwareManagerData config;
config.devices.push_back(some9685);
auto hwm = PiGPIOdpp::GetHardwareManager(config);
BOOST_REQUIRE( hwm );
BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->pwmcProviderRegistrar.Retrieve( devName ) );
}
BOOST_AUTO_TEST_SUITE_END()
| 32.1875 | 66 | 0.756634 |
e20a1779c288f36bf771964a87d0f79255b286bb | 10,634 | cpp | C++ | Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp | Stalpaard/SensoHapt | 74c90f1f4b1a17bd94109bc6543a864006849c75 | [
"MIT"
] | null | null | null | Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp | Stalpaard/SensoHapt | 74c90f1f4b1a17bd94109bc6543a864006849c75 | [
"MIT"
] | null | null | null | Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp | Stalpaard/SensoHapt | 74c90f1f4b1a17bd94109bc6543a864006849c75 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
//OpenHaptics QuickHaptics - Depth and Feedback Buffer Example
//SensAble Technologies, Woburn, MA
//September 03, 2008
//Programmer: Hari Vasudevan
//////////////////////////////////////////////////////////////////////////////
#include <QHHeadersGLUT.h>//Include all necessary headers
void glutMenuFunction(int MenuID);
int main(int argc, char *argv[])
{
QHGLUT* DisplayObject = new QHGLUT(argc,argv);//create a display window
DeviceSpace* OmniSpace = new DeviceSpace;//get the default device
DisplayObject->tell(OmniSpace);//Tell QuickHaptics about it
TriMesh* Bunny = new TriMesh("Models/BunnyRep.ply");//Load the Bunny Models
Bunny->setName("Bunny");//give it a name
Bunny->setTranslation(0.25,-1.0,0.0);//Position the model
Bunny->setScale(10.0);//make the model 2 times as large
Bunny->setStiffness(0.5);
Bunny->setDamping(0.3);
Bunny->setFriction(0.3, 0.5);//Give the Bunny some friction on the surface
Bunny->setShapeColor(205.0/255.0,133.0/255.0,63.0/255.0);//Set a brown color for the bunny
DisplayObject->tell(Bunny);//Tell Quickhaptics about the bunny
TriMesh* WheelLowRes = new TriMesh("Models/wheel-lo.obj");//Load the low resolution Wheel model
WheelLowRes->setName("WheelLowRes");//give it a name
WheelLowRes->setScale(1/12.0);//This model is too big compared to the bunnt model.. So we have to scale it down
WheelLowRes->setStiffness(1.0);
WheelLowRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface
WheelLowRes->setShapeColor(0.65,0.65,0.65);//Give the Wheel a green color
DisplayObject->tell(WheelLowRes);//Tell Quickhaptics about the low resolution Wheel
TriMesh* WheelHighRes = new TriMesh("Models/wheel-hi.obj");//Load the High resolution Wheel model
WheelHighRes->setName("WheelHighRes");//give it a name
WheelHighRes->setScale(1/12.0);//Scale the Wheel model
WheelHighRes->setStiffness(1.0);
WheelHighRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface
WheelHighRes->setRenderModeDepth();//Set the rendering mode to Depth Buffer. This is because the High resolution mode contains more than 65536 vertices
WheelHighRes->setShapeColor(0.65,0.65,0.65);//Set the color of the shape to green
DisplayObject->tell(WheelHighRes);//Tell Quickhaptics about the WheelHighRes
Text* RenderModeMsg = new Text(30, "Render Mode: Feedback Buffer", 0.0, 0.95);//Set the message to be displayed on screen, with it's position in
//normalised coordinates. (0,0) is the lower left corner of the screen and (1,1) is the upper right corner.
RenderModeMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
RenderModeMsg->setName("RenderModemessage");//Give the message a name
DisplayObject->tell(RenderModeMsg);//Tell QuickHaptics about the text message
Text* ModelStatMsg = new Text(24, "Stanford Bunny: 35,947 vertices",0.0, 0.875);//Create a text message and position it.
ModelStatMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
ModelStatMsg->setName("ModelStatMessage");//Give the message a name
DisplayObject->tell(ModelStatMsg);//Tell QuickHaptics about the text message
Text* InstMsg = new Text(24, "Right click on screen to bring up the menu",0.0, 0.05);
InstMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
InstMsg->setName("ModelStatMessage");//Tell QuickHaptics about the text message
DisplayObject->tell(InstMsg);//Tell QuickHaptics about the text message
Cursor* OmniCursor = new Cursor("Models/pencil.3DS");//Declare a new cursor
OmniCursor->scaleCursor(0.002);//Scale the cursor because it is too large
TriMesh* ModelTriMeshPointer = OmniCursor->getTriMeshPointer();
ModelTriMeshPointer->setTexture("Models/pencil.JPG");
DisplayObject->tell(OmniCursor);//tell QuickHaptics about the cursor
//Make the The Hight and Low Res Wheels both haptically and graphically invisible
/////////////////////////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
/////////////////////////////////////////////////////////////////////////////////
//Create the GLUT menu
glutCreateMenu(glutMenuFunction);
//Add entries
glutAddMenuEntry("Stanford Bunny - Feedback Buffer", 0);
glutAddMenuEntry("Stanford Bunny - Depth Buffer", 1);
glutAddMenuEntry("Wheel Low Resolution - Feedback Buffer", 2);
glutAddMenuEntry("Wheel Low Resolution - Depth Buffer", 3);
glutAddMenuEntry("Wheel High Resolution - Depth Buffer", 4);
//Attach the menu to the right mouse button
glutAttachMenu(GLUT_RIGHT_BUTTON);
qhStart();//Set everything in motion
return 0;
}
void glutMenuFunction(int MenuID)
{
static TriMesh* BunnyPointer = TriMesh::searchTriMesh("Bunny");//Search for a Pointer to the model
static TriMesh* WheelLowRes = TriMesh::searchTriMesh("WheelLowRes");//Search for a Pointer to the model
static TriMesh* WheelHighRes = TriMesh::searchTriMesh("WheelHighRes");//Search for a Pointer to the model
static Text* RenderModeMsgPointer = Text::searchText("RenderModemessage");//Search for a Pointer to the Text
static Text* ModelStatMsgPointer = Text::searchText("ModelStatMessage");//Search for a Pointer to the Text
if(!(BunnyPointer && WheelLowRes && WheelHighRes && RenderModeMsgPointer && ModelStatMsgPointer))//If any of the models cannot be found then return
return;
//////////////////////////
//////////////////////////
if(MenuID == 0)//If the Bunny is clicked on
{
BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible
BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeFeedback();
WheelLowRes->setRenderModeFeedback();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Feedback Buffer");//For any other model change the message to feedback buffer
ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message
///////////////////////
///////////////////////
}
else if(MenuID == 1)//If the low resolution Wheel is clicked on
{
BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible
BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message
///////////////////////
///////////////////////
}
else if(MenuID == 2)//If the high resolution Wheel is clicked on
{
WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible
WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeFeedback();
WheelLowRes->setRenderModeFeedback();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Feedback Buffer");
ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices");
}
else if(MenuID == 3)
{
WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible;
WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices");
}
else if(MenuID == 4)
{
WheelHighRes->setHapticVisibility(true);//Make the High Res Wheel Haptically visible;
WheelHighRes->setGraphicVisibility(true);//Make the High Res Wheel Graphically visible;
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Wheel - High Resolution: 147,489 vertices");
}
}
| 43.227642 | 152 | 0.639552 |
e20eea4aa0e49a939e83748eb6704d8bf33e8e06 | 545 | cpp | C++ | 440. K-th Smallest in Lexicographical Order/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 440. K-th Smallest in Lexicographical Order/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 440. K-th Smallest in Lexicographical Order/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | /** 440. K-th Smallest in Lexicographical Order
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
**/
#include <iostream>
#include "../utils.h"
using namespace std;
class Solution {
public:
int findKthNumber(int n, int k) {
}
};
int main() {
Solution s;
return 0;
}
| 16.029412 | 110 | 0.638532 |
e2120377a58db75c38aa97ec4ec682b2383728db | 15,892 | cc | C++ | qbmove_manipulator/build/msgs/pos_current_echo_request.pb.cc | valeria-parnenzini/qbmove_manipulator | b51f5c1d8d091e1b3f84a257f6ea45977c00edd0 | [
"Apache-2.0"
] | 1 | 2020-10-28T12:44:44.000Z | 2020-10-28T12:44:44.000Z | qbmove_manipulator/build/msgs/pos_current_echo_request.pb.cc | valeria-parnenzini/qbmove_manipulator | b51f5c1d8d091e1b3f84a257f6ea45977c00edd0 | [
"Apache-2.0"
] | null | null | null | qbmove_manipulator/build/msgs/pos_current_echo_request.pb.cc | valeria-parnenzini/qbmove_manipulator | b51f5c1d8d091e1b3f84a257f6ea45977c00edd0 | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: pos_current_echo_request.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "pos_current_echo_request.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace pos_current_echo_creator_msgs {
namespace msgs {
namespace {
const ::google::protobuf::Descriptor* PosCurrentEchoRequest_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
PosCurrentEchoRequest_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_pos_5fcurrent_5fecho_5frequest_2eproto() {
protobuf_AddDesc_pos_5fcurrent_5fecho_5frequest_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"pos_current_echo_request.proto");
GOOGLE_CHECK(file != NULL);
PosCurrentEchoRequest_descriptor_ = file->message_type(0);
static const int PosCurrentEchoRequest_offsets_[5] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, pos_out_shaft_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, pos_mot_1_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, pos_mot_2_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, curr_mot_1_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, curr_mot_2_),
};
PosCurrentEchoRequest_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
PosCurrentEchoRequest_descriptor_,
PosCurrentEchoRequest::default_instance_,
PosCurrentEchoRequest_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PosCurrentEchoRequest, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(PosCurrentEchoRequest));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_pos_5fcurrent_5fecho_5frequest_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
PosCurrentEchoRequest_descriptor_, &PosCurrentEchoRequest::default_instance());
}
} // namespace
void protobuf_ShutdownFile_pos_5fcurrent_5fecho_5frequest_2eproto() {
delete PosCurrentEchoRequest::default_instance_;
delete PosCurrentEchoRequest_reflection_;
}
void protobuf_AddDesc_pos_5fcurrent_5fecho_5frequest_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\036pos_current_echo_request.proto\022\"pos_cu"
"rrent_echo_creator_msgs.msgs\"|\n\025PosCurre"
"ntEchoRequest\022\025\n\rpos_out_shaft\030\001 \002(\001\022\021\n\t"
"pos_mot_1\030\002 \002(\001\022\021\n\tpos_mot_2\030\003 \002(\001\022\022\n\ncu"
"rr_mot_1\030\004 \002(\001\022\022\n\ncurr_mot_2\030\005 \002(\001", 194);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"pos_current_echo_request.proto", &protobuf_RegisterTypes);
PosCurrentEchoRequest::default_instance_ = new PosCurrentEchoRequest();
PosCurrentEchoRequest::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_pos_5fcurrent_5fecho_5frequest_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_pos_5fcurrent_5fecho_5frequest_2eproto {
StaticDescriptorInitializer_pos_5fcurrent_5fecho_5frequest_2eproto() {
protobuf_AddDesc_pos_5fcurrent_5fecho_5frequest_2eproto();
}
} static_descriptor_initializer_pos_5fcurrent_5fecho_5frequest_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int PosCurrentEchoRequest::kPosOutShaftFieldNumber;
const int PosCurrentEchoRequest::kPosMot1FieldNumber;
const int PosCurrentEchoRequest::kPosMot2FieldNumber;
const int PosCurrentEchoRequest::kCurrMot1FieldNumber;
const int PosCurrentEchoRequest::kCurrMot2FieldNumber;
#endif // !_MSC_VER
PosCurrentEchoRequest::PosCurrentEchoRequest()
: ::google::protobuf::Message() {
SharedCtor();
}
void PosCurrentEchoRequest::InitAsDefaultInstance() {
}
PosCurrentEchoRequest::PosCurrentEchoRequest(const PosCurrentEchoRequest& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
}
void PosCurrentEchoRequest::SharedCtor() {
_cached_size_ = 0;
pos_out_shaft_ = 0;
pos_mot_1_ = 0;
pos_mot_2_ = 0;
curr_mot_1_ = 0;
curr_mot_2_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
PosCurrentEchoRequest::~PosCurrentEchoRequest() {
SharedDtor();
}
void PosCurrentEchoRequest::SharedDtor() {
if (this != default_instance_) {
}
}
void PosCurrentEchoRequest::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PosCurrentEchoRequest::descriptor() {
protobuf_AssignDescriptorsOnce();
return PosCurrentEchoRequest_descriptor_;
}
const PosCurrentEchoRequest& PosCurrentEchoRequest::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_pos_5fcurrent_5fecho_5frequest_2eproto();
return *default_instance_;
}
PosCurrentEchoRequest* PosCurrentEchoRequest::default_instance_ = NULL;
PosCurrentEchoRequest* PosCurrentEchoRequest::New() const {
return new PosCurrentEchoRequest;
}
void PosCurrentEchoRequest::Clear() {
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
pos_out_shaft_ = 0;
pos_mot_1_ = 0;
pos_mot_2_ = 0;
curr_mot_1_ = 0;
curr_mot_2_ = 0;
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool PosCurrentEchoRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required double pos_out_shaft = 1;
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &pos_out_shaft_)));
set_has_pos_out_shaft();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(17)) goto parse_pos_mot_1;
break;
}
// required double pos_mot_1 = 2;
case 2: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
parse_pos_mot_1:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &pos_mot_1_)));
set_has_pos_mot_1();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(25)) goto parse_pos_mot_2;
break;
}
// required double pos_mot_2 = 3;
case 3: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
parse_pos_mot_2:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &pos_mot_2_)));
set_has_pos_mot_2();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(33)) goto parse_curr_mot_1;
break;
}
// required double curr_mot_1 = 4;
case 4: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
parse_curr_mot_1:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &curr_mot_1_)));
set_has_curr_mot_1();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(41)) goto parse_curr_mot_2;
break;
}
// required double curr_mot_2 = 5;
case 5: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
parse_curr_mot_2:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &curr_mot_2_)));
set_has_curr_mot_2();
} else {
goto handle_uninterpreted;
}
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
return true;
#undef DO_
}
void PosCurrentEchoRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// required double pos_out_shaft = 1;
if (has_pos_out_shaft()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->pos_out_shaft(), output);
}
// required double pos_mot_1 = 2;
if (has_pos_mot_1()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->pos_mot_1(), output);
}
// required double pos_mot_2 = 3;
if (has_pos_mot_2()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->pos_mot_2(), output);
}
// required double curr_mot_1 = 4;
if (has_curr_mot_1()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(4, this->curr_mot_1(), output);
}
// required double curr_mot_2 = 5;
if (has_curr_mot_2()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->curr_mot_2(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
}
::google::protobuf::uint8* PosCurrentEchoRequest::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// required double pos_out_shaft = 1;
if (has_pos_out_shaft()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->pos_out_shaft(), target);
}
// required double pos_mot_1 = 2;
if (has_pos_mot_1()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->pos_mot_1(), target);
}
// required double pos_mot_2 = 3;
if (has_pos_mot_2()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->pos_mot_2(), target);
}
// required double curr_mot_1 = 4;
if (has_curr_mot_1()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(4, this->curr_mot_1(), target);
}
// required double curr_mot_2 = 5;
if (has_curr_mot_2()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->curr_mot_2(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
return target;
}
int PosCurrentEchoRequest::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required double pos_out_shaft = 1;
if (has_pos_out_shaft()) {
total_size += 1 + 8;
}
// required double pos_mot_1 = 2;
if (has_pos_mot_1()) {
total_size += 1 + 8;
}
// required double pos_mot_2 = 3;
if (has_pos_mot_2()) {
total_size += 1 + 8;
}
// required double curr_mot_1 = 4;
if (has_curr_mot_1()) {
total_size += 1 + 8;
}
// required double curr_mot_2 = 5;
if (has_curr_mot_2()) {
total_size += 1 + 8;
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PosCurrentEchoRequest::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const PosCurrentEchoRequest* source =
::google::protobuf::internal::dynamic_cast_if_available<const PosCurrentEchoRequest*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void PosCurrentEchoRequest::MergeFrom(const PosCurrentEchoRequest& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_pos_out_shaft()) {
set_pos_out_shaft(from.pos_out_shaft());
}
if (from.has_pos_mot_1()) {
set_pos_mot_1(from.pos_mot_1());
}
if (from.has_pos_mot_2()) {
set_pos_mot_2(from.pos_mot_2());
}
if (from.has_curr_mot_1()) {
set_curr_mot_1(from.curr_mot_1());
}
if (from.has_curr_mot_2()) {
set_curr_mot_2(from.curr_mot_2());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void PosCurrentEchoRequest::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PosCurrentEchoRequest::CopyFrom(const PosCurrentEchoRequest& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PosCurrentEchoRequest::IsInitialized() const {
if ((_has_bits_[0] & 0x0000001f) != 0x0000001f) return false;
return true;
}
void PosCurrentEchoRequest::Swap(PosCurrentEchoRequest* other) {
if (other != this) {
std::swap(pos_out_shaft_, other->pos_out_shaft_);
std::swap(pos_mot_1_, other->pos_mot_1_);
std::swap(pos_mot_2_, other->pos_mot_2_);
std::swap(curr_mot_1_, other->curr_mot_1_);
std::swap(curr_mot_2_, other->curr_mot_2_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata PosCurrentEchoRequest::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = PosCurrentEchoRequest_descriptor_;
metadata.reflection = PosCurrentEchoRequest_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace msgs
} // namespace pos_current_echo_creator_msgs
// @@protoc_insertion_point(global_scope)
| 33.812766 | 112 | 0.703499 |
e2149b5c91c3ba0cb374d5e5506b3b243b969ff1 | 1,709 | hpp | C++ | src/core/Math.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | 1 | 2021-11-12T08:42:43.000Z | 2021-11-12T08:42:43.000Z | src/core/Math.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | null | null | null | src/core/Math.hpp | bferan/lucent | b19163df12739ffc513110d927e92f98c0b54321 | [
"MIT"
] | null | null | null | #pragma once
#include <cmath>
#include "math.h"
namespace lucent
{
constexpr float kPi = 3.14159265358979323846;
constexpr float k2Pi = kPi * 2.0f;
constexpr float kHalfPi = kPi / 2.0f;
// Math wrapper functions:
inline float Sqrt(float x)
{
return std::sqrt(x);
}
inline float Sin(float radians)
{
return std::sin(radians);
}
inline float Asin(float x)
{
return std::asin(x);
}
inline float Cos(float radians)
{
return std::cos(radians);
}
inline float Acos(float x)
{
return std::acos(x);
}
inline float Tan(float radians)
{
return std::tan(radians);
}
inline float Atan(float x)
{
return std::atan(x);
}
inline float Atan2(float x, float y)
{
return std::atan2(x, y);
}
inline float Clamp(float value, float min, float max)
{
return value > min ? (value < max ? value : max) : min;
}
inline float Ceil(float value)
{
return std::ceil(value);
}
inline float Floor(float value)
{
return std::floor(value);
}
inline float Round(float value)
{
return Floor(value + 0.5f);
}
inline float Mod(float value, float by)
{
return std::fmod(value, by);
}
inline float Exp(float value)
{
return std::exp(value);
}
inline float Pow(float base, float exp)
{
return std::powf(base, exp);
}
inline float Abs(float x)
{
return std::abs(x);
}
inline float CopySign(float value, float sign)
{
return std::copysign(value, sign);
}
inline bool Approximately(float x, float y, float epsilon = FLT_EPSILON)
{
return Abs(x - y) <= epsilon;
}
inline float Log2(float x)
{
return std::log2(x);
}
template<typename T>
T Min(T a, T b)
{
return a < b ? a : b;
}
template<typename T>
T Max(T a, T b)
{
return a < b ? b : a;
}
} | 14.008197 | 72 | 0.647162 |
e216b026375f1dfdaeeb490f3eeb344d5e13abb4 | 1,052 | cpp | C++ | control/examples/pegel/main.cpp | devfix/b15f | 5a49a37e69cca99359a98e1ef29a83043afed5e5 | [
"MIT"
] | 1 | 2019-10-26T18:37:49.000Z | 2019-10-26T18:37:49.000Z | control/examples/pegel/main.cpp | devfix/b15f | 5a49a37e69cca99359a98e1ef29a83043afed5e5 | [
"MIT"
] | null | null | null | control/examples/pegel/main.cpp | devfix/b15f | 5a49a37e69cca99359a98e1ef29a83043afed5e5 | [
"MIT"
] | 1 | 2022-03-26T16:06:23.000Z | 2022-03-26T16:06:23.000Z | #include <iostream>
#include <cmath>
#include <b15f/b15f.h>
#include <b15f/plottyfile.h>
/*
* Inkrementiert DAC 0 von 0 bis 1023 und speichert zu jeder Ausgabe den Wert von ADC 0 in einem Puffer.
* Die Funktion ADC 0 abhängig von DAC 0 wird als Graph geplottet.
*/
const char PLOT_FILE[] = "plot.bin";
int main()
{
B15F& drv = B15F::getInstance();
PlottyFile pf;
uint16_t buf[1024];
const uint16_t count = 1024;
const uint16_t delta = 1;
const uint16_t start = 0;
pf.setUnitX("V");
pf.setUnitY("V");
pf.setUnitPara("V");
pf.setDescX("U_{OUT}");
pf.setDescY("U_{IN}");
pf.setDescPara("");
pf.setRefX(5);
pf.setRefY(5);
pf.setParaFirstCurve(0);
pf.setParaStepWidth(0);
const uint8_t curve = 0;
drv.analogSequence(0, &buf[0], 0, 1, nullptr, 0, start, delta, count);
for(uint16_t x = 0; x < count; x++)
{
std::cout << x << " - " << buf[x] << std::endl;
pf.addDot(Dot(x, buf[x], curve));
}
// speichern und plotty starten
pf.writeToFile(PLOT_FILE);
pf.startPlotty(PLOT_FILE);
}
| 21.04 | 104 | 0.635932 |
e21babaa579368d6960e67e4357583b0514be73d | 17,289 | cpp | C++ | engine/hltvclient.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/engine/hltvclient.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/engine/hltvclient.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //===== Copyright (c) Valve Corporation, All rights reserved. ======//
//
// hltvclient.cpp: implementation of the CHLTVClient class.
//
// $NoKeywords: $
//
//==================================================================//
#include <tier0/vprof.h>
#include "hltvclient.h"
#include "netmessages.h"
#include "hltvserver.h"
#include "framesnapshot.h"
#include "networkstringtable.h"
#include "dt_send_eng.h"
#include "GameEventManager.h"
#include "cmd.h"
#include "ihltvdirector.h"
#include "host.h"
#include "sv_steamauth.h"
#include "fmtstr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static ConVar tv_maxrate( "tv_maxrate", STRINGIFY( DEFAULT_RATE ), FCVAR_RELEASE, "Max GOTV spectator bandwidth rate allowed, 0 == unlimited" );
static ConVar tv_relaypassword( "tv_relaypassword", "", FCVAR_NOTIFY | FCVAR_PROTECTED | FCVAR_DONTRECORD | FCVAR_RELEASE, "GOTV password for relay proxies" );
static ConVar tv_chattimelimit( "tv_chattimelimit", "8", FCVAR_RELEASE, "Limits spectators to chat only every n seconds" );
static ConVar tv_chatgroupsize( "tv_chatgroupsize", "0", FCVAR_RELEASE, "Set the default chat group size" );
extern ConVar replay_debug;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHLTVClient::CHLTVClient(int slot, CBaseServer *pServer)
{
Clear();
m_nClientSlot = slot;
m_Server = pServer;
m_pHLTV = dynamic_cast<CHLTVServer*>(pServer);
Assert( g_pHltvServer[ m_pHLTV->GetInstanceIndex() ] == pServer );
m_nEntityIndex = slot < 0 ? slot : m_pHLTV->GetHLTVSlot() + 1;
m_nLastSendTick = 0;
m_fLastSendTime = 0.0f;
m_flLastChatTime = 0.0f;
m_bNoChat = false;
if ( tv_chatgroupsize.GetInt() > 0 )
{
Q_snprintf( m_szChatGroup, sizeof(m_szChatGroup), "group%d", slot%tv_chatgroupsize.GetInt() );
}
else
{
Q_strncpy( m_szChatGroup, "all", sizeof(m_szChatGroup) );
}
}
CHLTVClient::~CHLTVClient()
{
}
bool CHLTVClient::SendSignonData( void )
{
// check class table CRCs
if ( m_nSendtableCRC != SendTable_GetCRC() )
{
Disconnect( "Server uses different class tables" );
return false;
}
else
{
// use your class infos, CRC is correct
CSVCMsg_ClassInfo_t classmsg;
classmsg.set_create_on_client( true );
m_NetChannel->SendNetMsg( classmsg );
}
return CBaseClient::SendSignonData();
}
bool CHLTVClient::ProcessSignonStateMsg(int state, int spawncount)
{
if ( !CBaseClient::ProcessSignonStateMsg( state, spawncount ) )
return false;
if ( state == SIGNONSTATE_FULL )
{
// Send all the delayed avatar data to the fully connected client
if ( INetChannel *pMyNetChannel = GetNetChannel() )
{
FOR_EACH_MAP_FAST( m_pHLTV->m_mapPlayerAvatarData, iData )
{
pMyNetChannel->EnqueueVeryLargeAsyncTransfer( *m_pHLTV->m_mapPlayerAvatarData.Element( iData ) );
}
}
}
return true;
}
bool CHLTVClient::CLCMsg_ClientInfo( const CCLCMsg_ClientInfo& msg )
{
if ( !CBaseClient::CLCMsg_ClientInfo( msg ) )
return false;
return true;
}
bool CHLTVClient::CLCMsg_Move( const CCLCMsg_Move& msg )
{
// HLTV clients can't move
return true;
}
bool CHLTVClient::CLCMsg_ListenEvents( const CCLCMsg_ListenEvents& msg )
{
// HLTV clients can't subscribe to events, we just send them
return true;
}
bool CHLTVClient::CLCMsg_RespondCvarValue( const CCLCMsg_RespondCvarValue& msg )
{
return true;
}
bool CHLTVClient::CLCMsg_FileCRCCheck( const CCLCMsg_FileCRCCheck& msg )
{
return true;
}
bool CHLTVClient::CLCMsg_VoiceData(const CCLCMsg_VoiceData& msg)
{
// HLTV clients can't speak
return true;
}
void CHLTVClient::ConnectionClosing(const char *reason)
{
Disconnect ( (reason!=NULL)?reason:"Connection closing" );
}
void CHLTVClient::ConnectionCrashed(const char *reason)
{
Disconnect ( (reason!=NULL)?reason:"Connection lost" );
}
void CHLTVClient::PacketStart(int incoming_sequence, int outgoing_acknowledged)
{
// During connection, only respond if client sends a packet
m_bReceivedPacket = true;
}
void CHLTVClient::PacketEnd()
{
}
void CHLTVClient::FileRequested(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileRequested: %s.\n", fileName );
m_NetChannel->DenyFile( fileName, transferID, bIsReplayDemoFile );
}
void CHLTVClient::FileDenied(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileDenied: %s.\n", fileName );
}
void CHLTVClient::FileReceived( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileReceived: %s.\n", fileName );
}
void CHLTVClient::FileSent( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileSent: %s.\n", fileName );
}
CClientFrame *CHLTVClient::GetDeltaFrame( int nTick )
{
return m_pHLTV->GetDeltaFrame( nTick );
}
bool CHLTVClient::ExecuteStringCommand( const char *pCommandString )
{
// first let the baseclass handle it
if ( CBaseClient::ExecuteStringCommand( pCommandString ) )
return true;
if ( !pCommandString || !pCommandString[0] )
return true;
CCommand args;
if ( !args.Tokenize( pCommandString, kCommandSrcNetServer ) )
return true;
const char *cmd = args[ 0 ];
if ( !Q_stricmp( cmd, "spec_next" ) ||
!Q_stricmp( cmd, "spec_prev" ) ||
!Q_stricmp( cmd, "spec_mode" ) ||
!Q_stricmp( cmd, "spec_goto" ) ||
!Q_stricmp( cmd, "spec_lerpto" ) )
{
ClientPrintf("Camera settings can't be changed during a live broadcast.\n");
return true;
}
if ( !Q_stricmp( cmd, "say" ) && args.ArgC() > 1 )
{
// if tv_chattimelimit = 0, chat is turned off
if ( tv_chattimelimit.GetFloat() <= 0 )
return true;
if ( (m_flLastChatTime + tv_chattimelimit.GetFloat()) > net_time )
return true;
m_flLastChatTime = net_time;
// Check if chat is non-empty string
bool bValidText = false;
for ( char const *szChatMsg = args[1]; szChatMsg && *szChatMsg; ++ szChatMsg )
{
if ( !V_isspace( *szChatMsg ) )
{
bValidText = true;
break;
}
}
if ( !bValidText )
return true;
char chattext[128];
V_sprintf_safe( chattext, "%s : %s", GetClientName(), args[1] );
m_pHLTV->BroadcastLocalChat( chattext, m_szChatGroup );
return true;
}
else if ( !Q_strcmp( cmd, "tv_chatgroup" ) )
{
if ( args.ArgC() > 1 )
{
Q_strncpy( m_szChatGroup, args[1], sizeof(m_szChatGroup) );
}
else
{
ClientPrintf("Your current chat group is \"%s\"\n", m_szChatGroup );
}
return true;
}
else if ( !Q_strcmp( cmd, "status" ) )
{
int slots, proxies, clients;
char gd[MAX_OSPATH];
Q_FileBase( com_gamedir, gd, sizeof( gd ) );
if ( m_pHLTV->IsMasterProxy() )
{
ClientPrintf("GOTV Master \"%s\", delay %.0f\n",
m_pHLTV->GetName(), m_pHLTV->GetDirector()->GetDelay() );
}
else // if ( m_Server->IsRelayProxy() )
{
if ( m_pHLTV->GetRelayAddress() )
{
ClientPrintf("GOTV Relay \"%s\", connected.\n",
m_pHLTV->GetName() );
}
else
{
ClientPrintf("GOTV Relay \"%s\", not connect.\n", m_pHLTV->GetName() );
}
}
ClientPrintf("IP %s:%i, Online %s, Version %i (%s)\n",
net_local_adr.ToString( true ), m_pHLTV->GetUDPPort(),
COM_FormatSeconds( m_pHLTV->GetOnlineTime() ), build_number(),
#ifdef _WIN32
"Win32" );
#else
"Linux" );
#endif
ClientPrintf("Game Time %s, Mod \"%s\", Map \"%s\", Players %i\n", COM_FormatSeconds( m_pHLTV->GetTime() ),
gd, m_pHLTV->GetMapName(), m_pHLTV->GetNumPlayers() );
m_pHLTV->GetLocalStats( proxies, slots, clients );
ClientPrintf("Local Slots %i, Spectators %i, Proxies %i\n",
slots, clients-proxies, proxies );
m_pHLTV->GetGlobalStats( proxies, slots, clients);
ClientPrintf("Total Slots %i, Spectators %i, Proxies %i\n",
slots, clients-proxies, proxies);
m_pHLTV->GetExternalStats( slots, clients );
if ( slots > 0 )
{
if ( clients > 0 )
ClientPrintf( "Streaming spectators %i, linked to Steam %i\n", slots, clients );
else
ClientPrintf( "Streaming spectators %i\n", slots );
}
}
else
{
DevMsg( "CHLTVClient::ExecuteStringCommand: Unknown command %s.\n", pCommandString );
}
return true;
}
bool CHLTVClient::ShouldSendMessages( void )
{
if ( !IsActive() )
{
// during signon behave like normal client
return CBaseClient::ShouldSendMessages();
}
// HLTV clients use snapshot rate used by HLTV server, not given by HLTV client
// if the reliable message overflowed, drop the client
if ( m_NetChannel->IsOverflowed() )
{
m_NetChannel->Reset();
Disconnect( CFmtStr( "%s overflowed reliable buffer", m_Name ) );
return false;
}
// send a packet if server has a new tick we didn't already send
bool bSendMessage = ( m_nLastSendTick != m_Server->m_nTickCount );
// send a packet at least every 2 seconds
if ( !bSendMessage && (m_fLastSendTime + 2.0f) < net_time )
{
bSendMessage = true; // force sending a message even if server didn't update
}
if ( bSendMessage && !m_NetChannel->CanPacket() )
{
// we would like to send a message, but bandwidth isn't available yet
// in HLTV we don't send choke information, doesn't matter
bSendMessage = false;
}
return bSendMessage;
}
void CHLTVClient::SpawnPlayer( void )
{
// set view entity
CSVCMsg_SetView_t setView;
setView.set_entity_index( m_pHLTV->m_nViewEntity );
SendNetMsg( setView );
m_pHLTV->BroadcastLocalTitle( this );
m_flLastChatTime = net_time;
CBaseClient::SpawnPlayer();
}
void CHLTVClient::SetRate(int nRate, bool bForce )
{
if ( !bForce )
{
if ( m_bIsHLTV )
{
// allow higher bandwidth rates for HLTV proxies
nRate = clamp( nRate, MIN_RATE, MAX_RATE );
}
else if ( tv_maxrate.GetInt() > 0 )
{
// restrict rate for normal clients to hltv_maxrate
nRate = clamp( nRate, MIN_RATE, tv_maxrate.GetInt() );
}
}
CBaseClient::SetRate( nRate, bForce );
}
void CHLTVClient::SetUpdateRate( float fUpdateRate, bool bForce)
{
// for HLTV clients ignore update rate settings, speed is tv_snapshotrate
m_fSnapshotInterval = 1.0f / m_pHLTV->GetSnapshotRate();
}
bool CHLTVClient::NETMsg_SetConVar(const CNETMsg_SetConVar& msg)
{
if ( !CBaseClient::NETMsg_SetConVar( msg ) )
return false;
// if this is the first time we get user settings, check password etc
if ( GetSignonState() == SIGNONSTATE_CONNECTED )
{
// Note: the master client of HLTV server will replace the rate ConVars for us. It's necessary so that demo recorder can take those frames from the master client and write them with values already modified
m_bIsHLTV = m_ConVars->GetInt( "tv_relay", 0 ) != 0;
if ( m_bIsHLTV )
{
// The connecting client is a TV relay
// Check if this relay address is whitelisted by IP range mask and bypasses all checks
extern bool IsHltvRelayProxyWhitelisted( ns_address const &adr );
if ( IsHltvRelayProxyWhitelisted( m_NetChannel->GetRemoteAddress() ) )
{
Msg( "Accepted GOTV relay proxy from whitelisted IP address: %s\n", m_NetChannel->GetAddress() );
}
// if the connecting client is a TV relay, check the password
else if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetHltvRelayPassword(), CSteamID() ) )
{
Disconnect("Bad relay password");
return false;
}
}
else
{
// if client is a normal spectator, check if we can to forward him to other relays
if ( m_pHLTV->DispatchToRelay( this ) )
{
return false;
}
// if we are not dispatching the client to other relay and we are the master server then validate
// the number of non-proxy clients
extern ConVar tv_maxclients_relayreserved;
if ( tv_maxclients_relayreserved.GetInt() )
{
int numActualNonProxyAccounts = 0;
for (int i=0; i < m_pHLTV->GetClientCount(); i++ )
{
CBaseClient *pProxy = static_cast< CBaseClient * >( m_pHLTV->GetClient( i ) );
// check if this is a proxy
if ( !pProxy->IsConnected() || pProxy->IsHLTV() || (this == pProxy) )
continue;
++ numActualNonProxyAccounts;
}
if ( numActualNonProxyAccounts > m_pHLTV->GetMaxClients() - tv_maxclients_relayreserved.GetInt() )
{
this->Disconnect( "No GOTV relays available" );
return false;
}
}
// if client stays here, check the normal password
// additionally if the first variable is client accountid then use that to validate personalized password
CSteamID steamUserAccountID;
if ( Steam3Server().SteamGameServerUtils() &&
( msg.convars().cvars_size() > 1 ) &&
!Q_strcmp( NetMsgGetCVarUsingDictionary( msg.convars().cvars( 0 ) ), "accountid" ) )
steamUserAccountID = CSteamID( Q_atoi( msg.convars().cvars( 0 ).value().c_str() ), Steam3Server().SteamGameServerUtils()->GetConnectedUniverse(), k_EAccountTypeIndividual );
if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetPassword(), steamUserAccountID ) )
{
Disconnect("Bad spectator password");
return false;
}
// check if server is LAN only
if ( !m_pHLTV->CheckIPRestrictions( m_NetChannel->GetRemoteAddress(), PROTOCOL_HASHEDCDKEY ) )
{
Disconnect( "GOTV server is restricted to local spectators (class C).\n" );
return false;
}
}
}
return true;
}
void CHLTVClient::UpdateUserSettings()
{
// set voice loopback
m_bNoChat = m_ConVars->GetInt( "tv_nochat", 0 ) != 0;
CBaseClient::UpdateUserSettings();
}
bool CHLTVClient::SendSnapshot( CClientFrame * pFrame )
{
VPROF_BUDGET( "CHLTVClient::SendSnapshot", "HLTV" );
byte buf[NET_MAX_PAYLOAD];
bf_write msg( "CHLTVClient::SendSnapshot", buf, sizeof(buf) );
// if we send a full snapshot (no delta-compression) before, wait until client
// received and acknowledge that update. don't spam client with full updates
if ( m_pLastSnapshot == pFrame->GetSnapshot() )
{
// never send the same snapshot twice
m_NetChannel->Transmit();
return false;
}
if ( m_nForceWaitForTick > 0 )
{
// just continue transmitting reliable data
Assert( !m_bFakePlayer ); // Should never happen
m_NetChannel->Transmit();
return false;
}
CClientFrame *pDeltaFrame = GetDeltaFrame( m_nDeltaTick ); // NULL if delta_tick is not found
CHLTVFrame *pLastFrame = (CHLTVFrame*) GetDeltaFrame( m_nLastSendTick );
if ( pLastFrame )
{
// start first frame after last send
pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext;
}
// add all reliable messages between ]lastframe,currentframe]
// add all tempent & sound messages between ]lastframe,currentframe]
while ( pLastFrame && pLastFrame->tick_count <= pFrame->tick_count )
{
m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_RELIABLE], true );
if ( pDeltaFrame )
{
// if we send entities delta compressed, also send unreliable data
m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_UNRELIABLE], false );
m_NetChannel->SendData( pLastFrame->m_Messages[ HLTV_BUFFER_VOICE ], false ); // we separate voice, even though it's simply more unreliable data, because we don't send it in replay
}
pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext;
}
// now create client snapshot packet
// send tick time
CNETMsg_Tick_t tickmsg( pFrame->tick_count, host_frameendtime_computationduration, host_frametime_stddeviation, host_framestarttime_stddeviation );
tickmsg.WriteToBuffer( msg );
// Update shared client/server string tables. Must be done before sending entities
m_Server->m_StringTables->WriteUpdateMessage( NULL, GetMaxAckTickCount(), msg );
// TODO delta cache whole snapshots, not just packet entities. then use net_Align
// send entity update, delta compressed if deltaFrame != NULL
{
CSVCMsg_PacketEntities_t packetmsg;
m_Server->WriteDeltaEntities( this, pFrame, pDeltaFrame, packetmsg );
packetmsg.WriteToBuffer( msg );
}
// write message to packet and check for overflow
if ( msg.IsOverflowed() )
{
if ( !pDeltaFrame )
{
// if this is a reliable snapshot, drop the client
Disconnect( "ERROR! Reliable snapshot overflow." );
return false;
}
else
{
// unreliable snapshots may be dropped
ConMsg ("WARNING: msg overflowed for %s\n", m_Name);
msg.Reset();
}
}
// remember this snapshot
m_pLastSnapshot = pFrame->GetSnapshot();
m_nLastSendTick = pFrame->tick_count;
// Don't send the datagram to fakeplayers
if ( m_bFakePlayer )
{
m_nDeltaTick = pFrame->tick_count;
return true;
}
bool bSendOK;
// is this is a full entity update (no delta) ?
if ( !pDeltaFrame )
{
if ( replay_debug.GetInt() >= 10 )
Msg( "HLTV send full frame %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 );
// transmit snapshot as reliable data chunk
bSendOK = m_NetChannel->SendData( msg );
bSendOK = bSendOK && m_NetChannel->Transmit();
// remember this tickcount we send the reliable snapshot
// so we can continue sending other updates if this has been acknowledged
m_nForceWaitForTick = pFrame->tick_count;
}
else
{
if ( replay_debug.GetInt() >= 10 )
Msg( "HLTV send datagram %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 );
// just send it as unreliable snapshot
bSendOK = m_NetChannel->SendDatagram( &msg ) > 0;
}
if ( !bSendOK )
{
Disconnect( "ERROR! Couldn't send snapshot." );
return false;
}
return true;
}
| 28.066558 | 208 | 0.692116 |
e21c6fa48127900170983abd4d0f273513c10bf7 | 44,201 | cpp | C++ | deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp | siyuanpan/ajisai_render | 203d79235bf698c1a4a747be291c0f3050b213da | [
"MIT"
] | null | null | null | deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp | siyuanpan/ajisai_render | 203d79235bf698c1a4a747be291c0f3050b213da | [
"MIT"
] | null | null | null | deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp | siyuanpan/ajisai_render | 203d79235bf698c1a4a747be291c0f3050b213da | [
"MIT"
] | null | null | null | /*
Copyright 2021 Siyuan Pan <pansiyuan.cs@gmail.com>
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 <Ajisai/Core/BSDF.h>
#include <Ajisai/Core/Geometry.h>
#include <Ajisai/Integrators/Integrator.h>
#include <Ajisai/Integrators/BidirectionalPath.h>
#include <cstring>
// using Ajisai::Core::CameraSamplingRecord;
// using Ajisai::Core::Intersect;
// using Ajisai::Core::LightSamplingRecord;
// using Ajisai::Core::SurfaceInteraction;
// using Ajisai::Core::VisibilityTester;
using namespace Ajisai::Math;
using namespace Ajisai::Core;
namespace Ajisai::Integrators {
// template <typename T>
// class ScopedAssignment {
// T* target = nullptr;
// T backup;
// public:
// ScopedAssignment() : target(nullptr), backup(T()) {}
// ScopedAssignment(T* target, T value) : target(target) {
// if (target) {
// backup = *target;
// *target = value;
// }
// }
// ~ScopedAssignment() {
// if (target) *target = backup;
// }
// ScopedAssignment(ScopedAssignment&&) = delete;
// ScopedAssignment(const ScopedAssignment&) = delete;
// ScopedAssignment& operator=(const ScopedAssignment&) = delete;
// ScopedAssignment& operator=(ScopedAssignment&& other) noexcept {
// if (target) *target = backup;
// target = other.target;
// backup = other.backup;
// other.target = nullptr;
// return *this;
// }
// };
// struct EndpointInteraction : Intersect {
// using Intersect::Intersect;
// // Math::Vector3f p;
// union {
// const Core::Camera* camera;
// const Core::AreaLight* light;
// };
// EndpointInteraction() : light{nullptr} {}
// EndpointInteraction(const Core::Ray& ray)
// : Intersect(ray.Point(1)), light(nullptr) {}
// EndpointInteraction(const Core::Camera* camera, const Core::Ray& ray)
// : Intersect(ray.o), camera(camera) {}
// EndpointInteraction(const Core::AreaLight* light, const Core::Ray& ray)
// : Intersect(ray.o), light(light) {}
// // EndpointInteraction(const Core::Camera* camera, const Math::Vector3f& p)
// // : Intersect(p), camera(camera) {}
// EndpointInteraction(const Core::AreaLight* light, const Core::Ray& r,
// const Math::Vector3f& nl)
// : Intersect(r.o), light(light) {
// Ng = nl;
// }
// };
// enum class VertexType { Camera, Light, Surface };
// enum class TransportMode { Radiance, Importance };
// struct PathVertex {
// VertexType type;
// Math::Spectrum beta;
// union {
// EndpointInteraction ei;
// SurfaceInteraction si;
// };
// bool delta = false;
// float pdfFwd = 0, pdfRev = 0;
// PathVertex() : ei() {}
// PathVertex(VertexType type, const EndpointInteraction& ei,
// const Math::Spectrum& beta)
// : type(type), beta(beta), ei(ei) {}
// PathVertex(const SurfaceInteraction& si, const Math::Spectrum& beta)
// : type(VertexType::Surface), beta(beta), si(si) {}
// ~PathVertex() {}
// PathVertex(const PathVertex& v) { memcpy(this, &v, sizeof(PathVertex)); }
// PathVertex& operator=(const PathVertex& v) {
// memcpy(this, &v, sizeof(PathVertex));
// return *this;
// }
// const Intersect& GetInteraction() const {
// switch (type) {
// case VertexType::Surface:
// return si;
// default:
// return ei;
// }
// }
// const auto& p() const { return GetInteraction().p; }
// const auto& ng() const { return GetInteraction().Ng; }
// [[nodiscard]] Math::Vector3f Ns() const {
// if (type == VertexType::Surface) {
// return si.Ns;
// } else if (type == VertexType::Light || type == VertexType::Camera) {
// return ei.Ng;
// } else {
// return {};
// }
// }
// bool IsOnSurface() const { return ng() != Math::Vector3f{0.f}; }
// bool IsConnectible() const {
// switch (type) {
// case VertexType::Light:
// return true;
// case VertexType::Camera:
// return true;
// case VertexType::Surface:
// return !delta;
// }
// return false; // NOTREACHED
// }
// float PdfLightOrigin(const Core::Scene& scene, const PathVertex& next) {
// const Core::AreaLight* light = ei.light;
// if (!light) {
// return 0.0f;
// }
// auto w = next.p() - p();
// w = w.normalized();
// float pdfPos = 0, pdfDir = 0;
// light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir);
// return scene.PdfLight(light) * pdfPos;
// }
// Math::Spectrum Le(const PathVertex& next) const {
// switch (type) {
// case VertexType::Surface: {
// auto wo = (next.p() - p()).normalized();
// return si.Le(wo);
// }
// case VertexType::Light: {
// auto* light = ei.light;
// auto wo = (next.p() - p()).normalized();
// return light->Li(wo);
// }
// case VertexType::Camera:
// default:
// return Math::Spectrum{0.f};
// }
// }
// float Pdf(const Core::Scene& scene, const PathVertex* prev,
// const PathVertex& next) {
// if (type == VertexType::Light) {
// return PdfLight(scene, next);
// }
// auto wn = next.p() - p();
// if (Math::dot(wn, wn) == 0) return 0;
// wn = wn.normalized();
// Math::Vector3f wp;
// if (prev) {
// wp = prev->p() - p();
// if (Math::dot(wp, wp) == 0) return 0;
// wp = wp.normalized();
// } else {
// assert(type == VertexType::Camera);
// }
// float pdf = 0;
// if (type == VertexType::Surface) {
// auto wo = si.bsdf->toLocal(-wp);
// auto wi = si.bsdf->toLocal(wn);
// pdf = si.bsdf->EvaluatePdf(wo, wi);
// } else if (type == VertexType::Camera) {
// auto* camera = ei.camera;
// float _;
// camera->Pdf_We(ei.SpawnRay(wn), &_, &pdf);
// } else {
// std::exit(1);
// }
// return ConvertDensity(pdf, next);
// }
// float PdfLight(const Core::Scene& scene, const PathVertex& next) {
// const Core::AreaLight* light = ei.light;
// if (!light) {
// return 0;
// }
// auto w = next.p() - p();
// float invDist2 = 1 / Math::dot(w, w);
// w = w.normalized();
// float pdf;
// float pdfPos = 0, pdfDir = 0;
// light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir);
// pdf = pdfDir * invDist2;
// if (next.IsOnSurface()) {
// pdf *= std::abs(Math::dot(next.ng(), w));
// }
// return pdf;
// }
// Math::Spectrum f(const PathVertex& next) const {
// auto wi = (next.p() - p()).normalized();
// switch (type) {
// case VertexType::Surface: {
// return si.bsdf->Evaluate(si.wo, wi);
// }
// default:
// return {};
// }
// }
// float ConvertDensity(float pdf, const PathVertex& next) const {
// // Return solid angle density if _next_ is an infinite area light
// // if (next.IsInfiniteLight()) return pdf;
// auto w = next.p() - p();
// if (Math::dot(w, w) == 0) return 0;
// float invDist2 = 1 / Math::dot(w, w);
// w = w.normalized();
// if (next.IsOnSurface()) pdf *= std::abs(Math::dot(next.ng(), w));
// // pdf *= std::abs(Math::dot(next.ng(), w * std::sqrt(invDist2)));
// return pdf * invDist2;
// }
// static inline PathVertex CreateCamera(const Core::Camera* camera,
// const Core::Ray& ray,
// const Math::Spectrum& beta);
// static inline PathVertex CreateLight(const EndpointInteraction& ei,
// const Math::Spectrum& beta, float
// pdf);
// static inline PathVertex CreateSurface(const SurfaceInteraction& si,
// const Math::Spectrum& beta, float
// pdf, const PathVertex& prev);
// static inline PathVertex CreateLight(const Core::AreaLight* light,
// const Core::Ray& ray,
// const Math::Vector3f& N,
// const Math::Spectrum& Le, float pdf);
// static inline PathVertex CreateCamera(const Core::Camera* camera,
// const Math::Vector3f& p,
// const Math::Spectrum& beta);
// static Math::Spectrum G(const Core::Scene& scene, const PathVertex& v0,
// const PathVertex& v1) {
// auto d = v0.p() - v1.p();
// float g = 1 / Math::dot(d, d);
// // d *= std::sqrt(g);
// d = d.normalized();
// if (v0.IsOnSurface()) g *= std::abs(Math::dot(v0.Ns(), d));
// if (v1.IsOnSurface()) g *= std::abs(Math::dot(v1.Ns(), d));
// VisibilityTester vis(v0.GetInteraction(), v1.GetInteraction());
// return g * vis.Tr(scene);
// }
// };
// inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera,
// const Core::Ray& ray,
// const Math::Spectrum& beta) {
// return PathVertex(VertexType::Camera, EndpointInteraction(camera, ray),
// beta);
// }
// inline PathVertex PathVertex::CreateLight(const EndpointInteraction& ei,
// const Math::Spectrum& beta,
// float pdf) {
// PathVertex v(VertexType::Light, ei, beta);
// v.pdfFwd = pdf;
// return v;
// }
// inline PathVertex PathVertex::CreateSurface(const SurfaceInteraction& si,
// const Math::Spectrum& beta,
// float pdf, const PathVertex&
// prev) {
// PathVertex v(si, beta);
// v.pdfFwd = prev.ConvertDensity(pdf, v);
// return v;
// }
// inline PathVertex PathVertex::CreateLight(const Core::AreaLight* light,
// const Core::Ray& ray,
// const Math::Vector3f& N,
// const Math::Spectrum& Le, float
// pdf) {
// PathVertex v(VertexType::Light, EndpointInteraction(light, ray, N), Le);
// v.pdfFwd = pdf;
// return v;
// }
// inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera,
// const Math::Vector3f& p,
// const Math::Spectrum& beta) {
// return PathVertex(VertexType::Camera, EndpointInteraction(camera, p),
// beta);
// }
// class BDPTIntegrator : public Integrator {
// public:
// explicit BDPTIntegrator(PluginManager::AbstractManager& manager,
// const std::string plugin)
// : Integrator{manager, plugin} {}
// struct Vertex {
// Spectrum throughput;
// uint32_t length;
// SurfaceInteraction si;
// Vector3f inDir;
// float DVCM;
// float DVC;
// };
// struct PathState {
// Vector3f origin;
// Vector3f direction;
// Spectrum throughput;
// uint PathLength : 30;
// bool isFiniteLight : 1;
// bool SpecularPath : 1;
// float DVCM;
// float DVC;
// };
// size_t RandomWalk(const Core::Scene& scene, Core::Sampler& sampler,
// Core::Ray& ray, Math::Spectrum& beta, float pdf,
// size_t depth, TransportMode mode, PathVertex* path) const
// {
// using Core::BSDFSamplingRecord;
// using Core::BSDFType;
// if (depth == 0) return 0;
// int bounces = 0;
// float pdfFwd = pdf, pdfRev = 0.f;
// while (true) {
// Core::Intersection isect;
// bool foundIntersection = scene.Intersect(ray, &isect);
// if (beta.isBlack()) break;
// auto& vertex = path[bounces];
// auto& prev = path[bounces - 1];
// if (!foundIntersection) {
// // if (mode == TransportMode::Radiance) {
// // vertex =
// // PathVertex::CreateLight(EndpointInteraction(ray), beta,
// // pdfFwd);
// // ++bounces;
// // }
// break;
// }
// Core::Triangle triangle{};
// isect.mesh->GetTriangle(isect.triId, &triangle);
// auto p = ray.Point(isect.t);
// SurfaceInteraction si(-ray.d, p, triangle, isect);
// isect.mesh->GetMaterial()->ComputeScatteringFunction(&si);
// vertex = PathVertex::CreateSurface(si, beta, pdfFwd, prev);
// if (++bounces >= depth) break;
// Math::Vector3f wi, wo = si.wo;
// BSDFSamplingRecord bRec(si, sampler.Next2D());
// si.bsdf->Sample(bRec);
// if (bRec.pdf <= 0.f) break;
// pdfFwd = bRec.pdf;
// wi = si.bsdf->toWorld(bRec.wi);
// beta *= bRec.f * std::abs(Math::dot(wi, si.Ns)) / bRec.pdf;
// pdfRev = si.bsdf->EvaluatePdf(bRec.wi, bRec.wo);
// if (bRec.type & BSDFType::BSDF_SPECULAR) {
// vertex.delta = true;
// pdfFwd = pdfRev = 0.f;
// }
// ray = si.SpawnRay(wi);
// prev.pdfRev = vertex.ConvertDensity(pdfRev, prev);
// }
// return bounces;
// }
// size_t GenerateCameraSubpath(const Core::Scene& scene,
// const Core::Camera& camera,
// const Math::Vector2i& raster,
// Core::Sampler& sampler, size_t depth,
// PathVertex* path) const {
// if (depth == 0) return 0;
// // const float u =
// // (raster.x() + sampler.Next1D()) /
// camera.GetFilm()->Dimension().x();
// // const float v =
// // (raster.y() + sampler.Next1D()) /
// camera.GetFilm()->Dimension().y();
// // auto ray = camera.GenerateRay(u, v);
// auto ray = camera.GenerateRay(sampler.Next2D(), sampler.Next2D(),
// raster); auto beta = Math::Spectrum(1);
// float pdfPos, pdfDir;
// path[0] = PathVertex::CreateCamera(&camera, ray, beta);
// camera.Pdf_We(ray, &pdfPos, &pdfDir);
// if (pdfDir <= 0 || pdfPos <= 0) {
// return 0;
// }
// return RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1,
// TransportMode::Importance, path + 1) +
// 1;
// }
// size_t GenerateLightSubpath(const Core::Scene& scene, Core::Sampler&
// sampler,
// size_t depth, PathVertex* path) const {
// if (depth == 0) return 0;
// float lightPdf = 0.f;
// auto sampleLight = scene.SampleOneLight(sampler.Next1D(), &lightPdf);
// Core::Ray ray;
// Math::Vector3f nLight;
// float pdfPos, pdfDir;
// Math::Spectrum Le;
// sampleLight->Sample_Le(sampler.Next2D(), sampler.Next2D(), &ray, nLight,
// &pdfPos, &pdfDir, Le);
// if (lightPdf <= 0 || pdfPos <= 0 || pdfDir <= 0 || Le.isBlack()) {
// return 0;
// }
// path[0] = PathVertex::CreateLight(sampleLight, ray, nLight, Le,
// pdfPos * lightPdf);
// Math::Spectrum beta =
// Le * std::abs(Math::dot(nLight, ray.d)) / (lightPdf * pdfPos *
// pdfDir);
// return 1 + RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1,
// TransportMode::Radiance, path + 1);
// }
// template <int Power>
// float MisWeight(const Core::Scene& scene, Core::Sampler& sampler,
// PathVertex* cameraVertices, size_t t,
// PathVertex* lightVertices, size_t s,
// PathVertex& sampled) const {
// if (s + t == 2) return 1;
// auto remap0 = [](float x) -> float {
// return x != 0 ? std::pow(x, Power) : 1.0f;
// };
// (void)remap0;
// float sumRi = 0;
// // p_0 ... pt qs ... q_0
// auto* pt = t > 0 ? &cameraVertices[t - 1] : nullptr;
// auto* qs = s > 0 ? &lightVertices[s - 1] : nullptr;
// auto* ptMinus = t > 1 ? &cameraVertices[t - 2] : nullptr;
// auto* qsMinus = s > 1 ? &lightVertices[s - 2] : nullptr;
// ScopedAssignment<PathVertex> _a1;
// if (s == 1)
// _a1 = {qs, sampled};
// else if (t == 1)
// _a1 = {pt, sampled};
// // if (s == 1) {
// // printf("b %f\n", lightVertices[s - 1].pdfFwd);
// // }
// ScopedAssignment<bool> _a2, _a3;
// if (pt) _a2 = {&pt->delta, false};
// if (qs) _a3 = {&qs->delta, false};
// // now connect pt to qs
// // we need to compute pt->pdfRev
// // segfault ?
// ScopedAssignment<float> _a4;
// if (pt) {
// float pdfRev;
// if (s > 0) {
// pdfRev = qs->Pdf(scene, qsMinus, *pt);
// } else {
// pdfRev = pt->PdfLightOrigin(scene, *ptMinus);
// }
// // if (s != 0)
// // printf("before rev %f s %d pdfRev %f\n", pt->pdfRev, (int)s,
// pdfRev); _a4 = {&pt->pdfRev, pdfRev};
// }
// // if (pt) printf("after rev %f\n", pt->pdfRev);
// // now ptMinus->pdfRev
// ScopedAssignment<float> _a5;
// // if (ptMinus) printf("before rev %f\n", ptMinus->pdfRev);
// if (ptMinus) {
// float pdfRev;
// if (s > 0) {
// pdfRev = pt->Pdf(scene, qs, *ptMinus);
// } else {
// pdfRev = pt->PdfLight(scene, *ptMinus);
// }
// _a5 = {&ptMinus->pdfRev, pdfRev};
// }
// // if (ptMinus) printf("after rev %f\n", ptMinus->pdfRev);
// // now qs
// ScopedAssignment<float> _a6;
// if (qs) {
// _a6 = {&qs->pdfRev, pt->Pdf(scene, ptMinus, *qs)};
// }
// // printf("%f\n", sampled.pdfFwd);
// // now qsMinus
// ScopedAssignment<float> _a7;
// if (qsMinus) {
// _a7 = {&qsMinus->pdfRev, qs->Pdf(scene, pt, *qsMinus)};
// }
// float ri = 1;
// for (int i = (int)t - 1; i > 0; i--) {
// ri *= remap0(cameraVertices[i].pdfRev) /
// remap0(cameraVertices[i].pdfFwd); if (!cameraVertices[i].delta &&
// !cameraVertices[i - 1].delta) {
// sumRi += ri;
// }
// }
// ri = 1;
// for (int i = (int)s - 1; i >= 0; i--) {
// ri *= remap0(lightVertices[i].pdfRev) /
// remap0(lightVertices[i].pdfFwd); bool delta = i > 0 ? lightVertices[i -
// 1].delta
// : false /*lightVertices[i].IsDeltaLight()*/;
// if (!lightVertices[i].delta && !delta) {
// sumRi += ri;
// }
// }
// return 1.0 / (1.0 + sumRi);
// }
// Math::Spectrum ConnectPath(const Core::Scene& scene, Core::Sampler&
// sampler,
// PathVertex* cameraVertices, size_t t,
// PathVertex* lightVertices, size_t s,
// Math::Vector2f* pRaster) const {
// if (t > 1 && s != 0 && cameraVertices[t - 1].type == VertexType::Light)
// return Math::Spectrum(0.f);
// Math::Spectrum L(0.f);
// PathVertex sampled{};
// if (s == 0) {
// const PathVertex& pt = cameraVertices[t - 1];
// L = pt.Le(cameraVertices[t - 2]) * pt.beta;
// } else if (t == 1) {
// const PathVertex& qs = lightVertices[s - 1];
// auto camera = cameraVertices[0].ei.camera;
// if (qs.IsConnectible()) {
// VisibilityTester vis;
// CameraSamplingRecord cRec;
// camera->Sample_Wi(sampler.Next2D(), qs.GetInteraction(), &cRec,
// &vis); *pRaster = cRec.pos; if (cRec.pdf > 0 && !cRec.I.isBlack()) {
// // Initialize dynamically sampled vertex and _L_ for $t=1$ case
// sampled = PathVertex::CreateCamera(camera, vis.shadowRay,
// cRec.I / cRec.pdf);
// L = qs.beta * qs.f(sampled) * sampled.beta;
// if (qs.IsOnSurface()) L *= std::abs(Math::dot(cRec.wi, qs.Ns()));
// // Only check visibility after we know that the path would
// // make a non-zero contribution.
// if (!L.isBlack()) L *= vis.Tr(scene);
// }
// }
// } else if (s == 1) {
// // Sample a point on a light and connect it to the camera subpath
// const PathVertex& pt = cameraVertices[t - 1];
// auto& lightVertex = lightVertices[0];
// if (pt.IsConnectible()) {
// float lightPdf;
// VisibilityTester vis;
// LightSamplingRecord lRec;
// lightVertex.ei.light->Sample_Li(sampler.Next2D(),
// pt.GetInteraction(),
// lRec, vis);
// const Core::AreaLight* light = lightVertex.ei.light;
// if (lRec.pdf > 0 && !lRec.Li.isBlack()) {
// EndpointInteraction ei(light, vis.shadowRay);
// sampled = PathVertex::CreateLight(
// ei, lRec.Li / (scene.PdfLight(light) * lRec.pdf), 0);
// sampled.pdfFwd = sampled.PdfLightOrigin(scene, pt);
// L = pt.beta * pt.f(sampled) * sampled.beta;
// if (pt.IsOnSurface()) L *= std::abs(Math::dot(lRec.wi, pt.Ns()));
// // Only check visibility if the path would carry radiance.
// if (!L.isBlack()) L *= vis.Tr(scene);
// }
// }
// } else {
// // Handle all other bidirectional connection cases
// const PathVertex &qs = lightVertices[s - 1], &pt = cameraVertices[t -
// 1]; if (qs.IsConnectible() && pt.IsConnectible()) {
// L = qs.beta * qs.f(pt) * pt.f(qs) * pt.beta;
// // VLOG(2) << "General connect s: " << s << ", t: " << t << " qs: "
// <<
// // qs
// // << ", pt: " << pt
// // << ", qs.f(pt): " << qs.f(pt, TransportMode::Importance)
// // << ", pt.f(qs): " << pt.f(qs, TransportMode::Radiance)
// // << ", G: " << G(scene, sampler, qs, pt)
// // << ", dist^2: " << DistanceSquared(qs.p(), pt.p());
// if (!L.isBlack()) L *= PathVertex::G(scene, qs, pt);
// }
// }
// if (L.isBlack()) return {};
// float misWeight = 1.0f / (s + t);
// // if (s == 1) printf("t %d s %d\n", (int)t, (int)s);
// misWeight = MisWeight<1>(scene, sampler, cameraVertices, t,
// lightVertices,
// s, sampled);
// assert(misWeight >= 0);
// L *= misWeight;
// return L.removeNaN();
// }
template <int pow>
float MIS(float fVal) {
// Use power heuristic
return std::pow(fVal, pow);
}
BDPTIntegrator::PathState BDPTIntegrator::SampleLightSource(Scene* scene,
Sampler* sampler) {
PathState ret;
float lightPdf = 0.f;
auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf);
// printf("lightPdf %f\n", lightPdf);
Ray lightRay;
Vector3f nLight;
float posPdf, dirPdf;
sampleLight->Sample_Le(sampler->Next2D(), sampler->Next2D(), &lightRay,
nLight, &posPdf, &dirPdf, ret.throughput);
// printf(
// "ray.o (%f %f %f) ray.d (%f %f %f) nLight (%f %f %f) posPdf (%f) "
// "dirPdf(%f) E (%f %f %f)\n",
// lightRay.o[0], lightRay.o[1], lightRay.o[2], lightRay.d[0],
// lightRay.d[1], lightRay.d[2], nLight.x(), nLight.y(), nLight.z(),
// posPdf, dirPdf, ret.throughput[0], ret.throughput[1],
// ret.throughput[2]);
if ((posPdf * dirPdf) == 0.0f) return ret;
// dirPdf *= lightPdf;
// posPdf *= lightPdf;
// printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf,
// lightPdf, dirPdf * posPdf * lightPdf);
float emitPdf = dirPdf * posPdf * lightPdf;
ret.throughput /= emitPdf;
ret.isFiniteLight = sampleLight->isFinite();
ret.SpecularPath = true;
ret.PathLength = 1;
ret.direction = lightRay.d.normalized();
ret.origin = lightRay.o;
float emitCos = dot(nLight, lightRay.d);
ret.DVCM = MIS<pow>((posPdf * lightPdf) / emitPdf);
ret.DVC = sampleLight->isDelta()
? 0.f
: (sampleLight->isFinite()
? MIS<pow>(emitCos / (dirPdf * posPdf * lightPdf))
: MIS<pow>(1.f / (dirPdf * posPdf * lightPdf)));
// printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf,
// lightPdf, emitPdf);
// printf("E (%f %f %f), emitCos %f, DVCM %f DVC %f\n", ret.throughput[0],
// ret.throughput[1], ret.throughput[2], emitCos, ret.DVCM, ret.DVC);
return ret;
}
Spectrum BDPTIntegrator::ConnectToCamera(Scene* scene, Camera* camera,
Sampler* sampler,
SurfaceInteraction& si,
Vertex& lightVertex,
Vector2f& pRaster) {
Vector3f dirToCamera;
// Vector2f pRaster;
if (!camera->ToRaster(sampler->Next2D(), si, dirToCamera, pRaster)) return {};
float distToCamera = dirToCamera.length();
dirToCamera = dirToCamera.normalized();
// printf("(%f %f %f) (%f %f)\n", lightVertex.throughput[0],
// lightVertex.throughput[1], lightVertex.throughput[2], pRaster[0],
// pRaster[1]);
Spectrum f = si.bsdf->Evaluate(dirToCamera, lightVertex.inDir) *
std::abs(dot(lightVertex.inDir, si.Ns)) /
std::abs(dot(lightVertex.inDir, si.Ng));
// printf("(%f %f %f) (%f %f %f) %f %f (%f %f %f)\n", dirToCamera[0],
// dirToCamera[1], dirToCamera[2],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[0],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[1],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[2],
// std::abs(dot(lightVertex.inDir, si.Ns)),
// std::abs(dot(lightVertex.inDir, si.Ng)), f[0], f[1], f[2]);
if (f.isBlack()) return {};
// printf("(%f %f %f)\n", f[0], f[1], f[2]);
float pdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(lightVertex.inDir),
si.bsdf->toLocal(dirToCamera));
float revPdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(dirToCamera),
si.bsdf->toLocal(lightVertex.inDir));
// printf("%f %f\n", pdf, revPdf);
if (pdf == 0.f || revPdf == 0.f) return {};
float cosToCam = dot(si.Ng, dirToCamera);
CameraSamplingRecord cRec;
VisibilityTester tester;
camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester);
(void)tester;
// printf("%f\n", cRec.pdf);
float cameraPdfA =
cRec.pdf * std::abs(cosToCam) / (distToCamera * distToCamera);
// printf("%d\n", camera->GetPixelCount());
float WLight =
MIS<pow>(
cameraPdfA / camera->GetPixelCount() //(float)camera->GetPixelCount()
) *
(lightVertex.DVCM + lightVertex.DVC * MIS<pow>(revPdf));
float MISWeight = 1.f / (WLight + 1.f);
// printf("%f\n", MISWeight);
Spectrum contrib = MISWeight * lightVertex.throughput * f * cameraPdfA /
camera->GetPixelCount();
// (float)camera->GetPixelCount();
// printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]);
// printf("(%f %f %f) MISWeight %f f (%f %f %f) cameraPdfA %f A %f\n",
// lightVertex.throughput[0], lightVertex.throughput[1],
// lightVertex.throughput[2], MISWeight, f[0], f[1], f[2],
// cameraPdfA, camera->A());
Ray rayToCam =
Ray(si.p, dirToCamera, Ray::Eps(), distToCamera * (1.f - Ray::Eps()));
if (!contrib.isBlack() && !scene->Occlude(rayToCam)) {
// printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]);
return contrib;
}
return {};
}
int BDPTIntegrator::GenerateLightPath(Scene* scene, Sampler* sampler,
const int maxDepth, Vertex* lightVertices,
Camera* camera, int* vertexCount,
const int rrDepth,
const bool connectToCamera) {
if (maxDepth == 0) {
*vertexCount = 0;
return 0;
}
PathState lightPathState = SampleLightSource(scene, sampler);
if (lightPathState.throughput.isBlack()) return 0;
// printf("(%f %f %f) \n", lightPathState.throughput[0],
// lightPathState.throughput[1], lightPathState.throughput[2]);
if (lightPathState.PathLength >= maxDepth) {
*vertexCount = 0;
return lightPathState.PathLength;
}
*vertexCount = 0;
while (true) {
Ray pathRay(lightPathState.origin, lightPathState.direction);
// printf("(%f %f %f) (%f %f %f)\n", pathRay.o[0], pathRay.o[1],
// pathRay.o[2], pathRay.d[0], pathRay.d[1], pathRay.d[2]);
Intersection isect;
if (!scene->Intersect(pathRay, &isect)) {
return lightPathState.PathLength;
}
if (lightPathState.PathLength > 1 || lightPathState.isFiniteLight) {
// printf("1 %f %f\n", lightPathState.DVCM, isect.t);
lightPathState.DVCM *= MIS<pow>(isect.t * isect.t);
// printf("(%f) (%f)\n", (pathRay.Point(isect.t) - pathRay.o).length(),
// isect.t);
// printf("2 %f\n", lightPathState.DVCM);
}
float cosIn = std::abs(dot(isect.Ng, -pathRay.d));
lightPathState.DVCM /= MIS<pow>(cosIn);
lightPathState.DVC /= MIS<pow>(cosIn);
// printf("cosIn %f DVCM %f DVC %f\n", cosIn, lightPathState.DVCM,
// lightPathState.DVC);
Triangle triangle{};
isect.mesh->GetTriangle(isect.triId, &triangle);
auto p = pathRay.Point(isect.t);
SurfaceInteraction si(-pathRay.d, p, triangle, isect);
isect.mesh->GetMaterial()->ComputeScatteringFunction(
&si, Core::TransportMode::eRadiance);
BSDFSamplingRecord bRec(si, sampler->Next2D());
si.bsdf->Sample(bRec);
// if (bRec.pdf <= 0.f) break;
auto specular = bRec.type & BxDFType::BSDF_SPECULAR;
if (!specular) {
Vertex& lightVertex = lightVertices[(*vertexCount)++];
lightVertex.throughput = lightPathState.throughput;
lightVertex.length = lightPathState.PathLength + 1;
lightVertex.si = si;
lightVertex.inDir = -lightPathState.direction;
lightVertex.DVCM = lightPathState.DVCM;
lightVertex.DVC = lightPathState.DVC;
// printf("(%f %f %f) \n", lightVertex.throughput[0],
// lightVertex.throughput[1], lightVertex.throughput[2]);
// connect to camera
if (connectToCamera) {
Vector2f ptRaster;
Spectrum connectRadiance =
ConnectToCamera(scene, camera, sampler, si, lightVertex, ptRaster);
// if (connectRadiance.isBlack()) break;
// printf("(%f %f %f) (%f %f)\n", connectRadiance[0],
// connectRadiance[1],
// connectRadiance[2], ptRaster[0], ptRaster[1]);
camera->GetFilm()->AddSplat(connectRadiance, ptRaster);
}
}
if (++lightPathState.PathLength >= maxDepth) break;
// if (!SampleScattering()) break;
Spectrum f = bRec.f;
Vector3f wi = bRec.wi;
float scatteredPdf = bRec.pdf;
float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d));
if (f.isBlack() || scatteredPdf == 0.f) break;
// printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf);
if (!specular && rrDepth != -1 && lightPathState.PathLength > rrDepth) {
float q = std::min(0.95f, lightPathState.throughput.max());
if (sampler->Next1D() >= q) break;
lightPathState.throughput /= q;
}
lightPathState.origin = si.p;
lightPathState.direction = si.bsdf->toWorld(bRec.wi);
float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi)));
if (!specular) {
lightPathState.SpecularPath &= 0;
lightPathState.DVCM =
MIS<pow>(cosOut / scatteredPdf) *
(lightPathState.DVC * MIS<pow>(revPdf) + lightPathState.DVCM);
lightPathState.DVC = MIS<pow>(1.0f / scatteredPdf);
// printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC);
} else {
lightPathState.SpecularPath &= 1;
lightPathState.DVCM = 0.f;
lightPathState.DVC *= MIS<pow>(cosOut);
// printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC);
}
lightPathState.throughput *= f * cosOut / scatteredPdf;
// printf("(%f %f %f) \n", lightPathState.throughput[0],
// lightPathState.throughput[1], lightPathState.throughput[2]);
}
return lightPathState.PathLength;
}
// bool SampleScattering() const {}
void BDPTIntegrator::SampleCamera(Camera* camera, Ray& ray, Sampler* sampler,
PathState& initPathState) {
// CameraSamplingRecord cRec;
// VisibilityTester tester;
// SurfaceInteraction si;
// ray.d = ray.d.normalized();
// si.p = ray.Point(camera->GetFocusDistance());
// camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester);
// (void)tester;
// float cosAtCam = Math::Dot(pCamera->mDir, primRay.mDir);
// float rasterToCamDist = pCamera->GetImagePlaneDistance() / cosAtCam;
// float cameraPdfW = rasterToCamDist * rasterToCamDist / cosAtCam;
float virtualImagePlaneDistance = camera->GetImagePlaneDist();
float cosThetaCamera = dot(camera->GetDir(), ray.d.normalized());
float imagePointToCameraDistance = virtualImagePlaneDistance / cosThetaCamera;
float invSolidAngleMeasure =
imagePointToCameraDistance * imagePointToCameraDistance / cosThetaCamera;
float revCameraPdfW = (1.0f / invSolidAngleMeasure);
// printf("%f %f %f %f %f\n", virtualImagePlaneDistance, cosThetaCamera,
// imagePointToCameraDistance, invSolidAngleMeasure, revCameraPdfW);
initPathState.origin = ray.o;
initPathState.direction = ray.d.normalized();
initPathState.throughput = Spectrum{1.f};
initPathState.PathLength = 1;
initPathState.SpecularPath = true;
initPathState.DVC = 0.f;
initPathState.DVCM = MIS<pow>(revCameraPdfW * camera->GetPixelCount());
// initPathState.DVCM = MIS<pow>( // camera->GetPixelCount()
// camera->A() / cRec.pdf);
// printf("%d %f %f\n", camera->GetPixelCount(), cRec.pdf,
// initPathState.DVCM);
}
Spectrum BDPTIntegrator::HittingLightSource(Scene* scene, Ray& ray,
Intersection& isect,
AreaLight* light,
PathState& cameraPathState) {
float pickPdf = scene->PdfLight(light);
float emitPdfW, directPdfA;
Spectrum emittedRadiance =
light->Emit(-ray.d, isect.Ng, &emitPdfW, &directPdfA);
// printf("(%f %f %f) %f %f\n", emittedRadiance[0], emittedRadiance[1],
// emittedRadiance[2], emitPdfW, directPdfA);
if (emittedRadiance.isBlack()) return {};
// printf("%d\n", cameraPathState.PathLength);
if (cameraPathState.PathLength == 2) {
return emittedRadiance;
}
directPdfA *= pickPdf;
emitPdfW *= pickPdf;
float WCamera = MIS<pow>(directPdfA) * cameraPathState.DVCM +
MIS<pow>(emitPdfW) * cameraPathState.DVC;
float MISWeight = 1.0f / (1.0f + WCamera);
// printf("%f %f %f %f %f\n", directPdfA, emitPdfW, cameraPathState.DVCM,
// cameraPathState.DVC, WCamera);
return MISWeight * emittedRadiance;
}
Spectrum BDPTIntegrator::ConnectToLight(const Scene* scene, Ray& pathRay,
const SurfaceInteraction& si,
Sampler* sampler,
PathState& cameraPathState) {
// Sample light source and get radiance
float lightPdf = 0.f;
auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf);
const Vector3f& pos = si.p;
Vector3f vIn;
VisibilityTester visibility;
float lightPdfW;
float cosAtLight;
float emitPdfW;
Spectrum radiance =
sampleLight->Illuminate(si, sampler->Next2D(), vIn, visibility,
&lightPdfW, &cosAtLight, &emitPdfW);
// printf("(%f %f %f) %f %f %f\n", radiance[0], radiance[1], radiance[2],
// lightPdfW, cosAtLight, emitPdfW);
if (radiance.isBlack() || lightPdfW == 0.0f) {
return {};
}
Vector3f vOut = -pathRay.d;
Spectrum bsdfFac = si.bsdf->Evaluate(vOut, vIn);
if (bsdfFac.isBlack()) {
return {};
}
float bsdfPdfW = si.bsdf->EvaluatePdf(vOut, vIn);
if (bsdfPdfW == 0.f) return {};
if (sampleLight->isDelta()) bsdfPdfW = 0.f;
float bsdfRevPdfW = si.bsdf->EvaluatePdf(vIn, vOut);
float WLight = MIS<pow>(bsdfPdfW / (lightPdfW * lightPdf));
// printf("%f\n", WLight);
float cosToLight = std::abs(Math::dot(si.Ns, vIn));
float WCamera =
MIS<pow>(emitPdfW * cosToLight / (lightPdfW * cosAtLight)) *
(cameraPathState.DVCM + cameraPathState.DVC * MIS<pow>(bsdfRevPdfW));
// printf("%f\n", WCamera);
float fMISWeight = 1.0f / (WLight + 1.0f + WCamera);
Spectrum contribution =
(fMISWeight * cosToLight / (lightPdfW * lightPdf)) * bsdfFac * radiance;
if (contribution.isBlack() || !visibility.visible(*scene)) {
return {};
}
// printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]);
return contribution;
}
Spectrum BDPTIntegrator::ConnectVertex(Scene* scene, SurfaceInteraction& si,
const Vertex& lightVertex,
PathState& cameraState) {
const Vector3f& cameraPos = si.p;
auto dirToLight = lightVertex.si.p - cameraPos;
float distToLightSqr = dot(dirToLight, dirToLight);
float distToLight = dirToLight.length();
auto vOutCam = -cameraState.direction;
Spectrum cameraBsdfFac = si.bsdf->Evaluate(vOutCam, dirToLight);
float cosAtCam = dot(si.Ns, dirToLight);
auto cameraDirPdfW = si.bsdf->EvaluatePdf(vOutCam, dirToLight);
float cameraReversePdfW = si.bsdf->EvaluatePdf(dirToLight, vOutCam);
if (cameraBsdfFac.isBlack() || cameraDirPdfW == 0.0f ||
cameraReversePdfW == 0.0f)
return {};
Vector3f dirToCamera = -dirToLight;
Spectrum lightBsdfFac =
lightVertex.si.bsdf->Evaluate(lightVertex.inDir, dirToCamera);
float cosAtLight = Math::dot(lightVertex.si.Ns, dirToCamera);
float lightDirPdfW =
lightVertex.si.bsdf->EvaluatePdf(lightVertex.inDir, dirToCamera);
float lightRevPdfW =
lightVertex.si.bsdf->EvaluatePdf(dirToCamera, lightVertex.inDir);
if (lightBsdfFac.isBlack() || lightDirPdfW == 0.0f || lightRevPdfW == 0.0f)
return {};
// printf("%f %f %f %f\n", cameraDirPdfW, cameraReversePdfW, lightDirPdfW,
// lightRevPdfW);
float geometryTerm = cosAtLight * cosAtCam / distToLightSqr;
if (geometryTerm < 0.0f) {
return {};
}
// printf("%f\n", geometryTerm);
float cameraDirPdfA =
cameraDirPdfW * std::abs(cosAtLight) / (distToLight * distToLight);
float lightDirPdfA =
lightDirPdfW * std::abs(cosAtCam) / (distToLight * distToLight);
float WLight = MIS<pow>(cameraDirPdfA) *
(lightVertex.DVCM + lightVertex.DVC * MIS<pow>(lightRevPdfW));
float WCamera =
MIS<pow>(lightDirPdfA) *
(cameraState.DVCM + cameraState.DVC * MIS<pow>(cameraReversePdfW));
float fMISWeight = 1.0f / (WLight + 1.0f + WCamera);
// printf("%f %f %f\n", fMISWeight, WLight, WCamera);
Spectrum contribution =
(fMISWeight * geometryTerm) * lightBsdfFac * cameraBsdfFac;
Ray rayToLight =
Ray(cameraPos, dirToLight, Ray::Eps(), distToLight * (1.f - Ray::Eps()));
if (contribution.isBlack() || scene->Occlude(rayToLight)) {
// printf("%f %f %f\n", contribution[0], contribution[1],
// contribution[2]);
return {};
}
// printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]);
return contribution;
}
Math::Spectrum BDPTIntegrator::Li(Core::Scene* scene, Core::Camera* camera,
const Math::Vector2i& raster,
Core::Sampler* sampler) const {
Vertex* lightVertices = (Vertex*)calloc(maxDepth, sizeof(Vertex));
int numLightVertex;
int lightPathLen = GenerateLightPath(scene, sampler, maxDepth + 1,
lightVertices, camera, &numLightVertex);
const float u =
(raster.x() + sampler->Next1D()) / camera->GetFilm()->Dimension().x();
const float v =
(raster.y() + sampler->Next1D()) / camera->GetFilm()->Dimension().y();
// auto ray = camera->GenerateRay(u, v);
auto ray = camera->GenerateRay(sampler->Next2D(), sampler->Next2D(), raster);
PathState cameraPathState;
SampleCamera(camera, ray, sampler, cameraPathState);
Math::Spectrum L(0.f);
while (true) {
Ray pathRay(cameraPathState.origin, cameraPathState.direction);
Intersection isect;
if (!scene->Intersect(pathRay, &isect)) {
break;
}
float cosIn = std::abs(dot(isect.Ng, -pathRay.d));
cameraPathState.DVCM *= MIS<pow>(isect.t * isect.t);
cameraPathState.DVCM /= MIS<pow>(cosIn);
cameraPathState.DVC /= MIS<pow>(cosIn);
// printf("%f %f\n", cameraPathState.DVCM, cameraPathState.DVC);
if (isect.mesh->IsEmitter()) {
cameraPathState.PathLength++;
L += cameraPathState.throughput *
HittingLightSource(scene, pathRay, isect,
isect.mesh->GetLight(isect.triId).get(),
cameraPathState);
break;
}
if (++cameraPathState.PathLength >= maxDepth + 2) {
break;
}
Triangle triangle{};
isect.mesh->GetTriangle(isect.triId, &triangle);
auto p = pathRay.Point(isect.t);
SurfaceInteraction si(-pathRay.d, p, triangle, isect);
isect.mesh->GetMaterial()->ComputeScatteringFunction(
&si, Core::TransportMode::eImportance);
BSDFSamplingRecord bRec(si, sampler->Next2D());
si.bsdf->Sample(bRec);
if (bRec.pdf <= 0.f) break;
auto specular = bRec.type & BxDFType::BSDF_SPECULAR;
if (!specular) {
L += cameraPathState.throughput *
ConnectToLight(scene, pathRay, si, sampler, cameraPathState);
for (int i = 0; i < numLightVertex; i++) {
const Vertex& lightVertex = lightVertices[i];
if (lightVertex.length + cameraPathState.PathLength - 2 > maxDepth) {
break;
}
L += lightVertex.throughput * cameraPathState.throughput *
ConnectVertex(scene, si, lightVertex, cameraPathState);
}
}
Spectrum f = bRec.f;
Vector3f wi = bRec.wi;
float scatteredPdf = bRec.pdf;
float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d));
if (f.isBlack() || scatteredPdf == 0.f) break;
// printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf);
if (!specular && rrDepth != -1 && cameraPathState.PathLength > rrDepth) {
float q = std::min(0.95f, cameraPathState.throughput.max());
if (sampler->Next1D() >= q) break;
cameraPathState.throughput /= q;
}
cameraPathState.origin = si.p;
cameraPathState.direction = si.bsdf->toWorld(bRec.wi);
float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi)));
if (!specular) {
cameraPathState.SpecularPath &= 0;
cameraPathState.DVCM =
MIS<pow>(cosOut / scatteredPdf) *
(cameraPathState.DVC * MIS<pow>(revPdf) + cameraPathState.DVCM);
cameraPathState.DVC = MIS<pow>(1.0f / scatteredPdf);
} else {
cameraPathState.SpecularPath &= 1;
cameraPathState.DVCM = 0.f;
cameraPathState.DVC *= MIS<pow>(cosOut);
}
cameraPathState.throughput *= f * cosOut / scatteredPdf;
}
free((void*)lightVertices);
return L;
}
void BDPTIntegrator::Render(Core::Scene* scene, Core::Camera* camera,
Core::Sampler* sampler) const {}
// private:
// // int rrDepth = 5, maxDepth = 16;
// int rrDepth = 5, maxDepth = 16;
// // heuristic
// static constexpr int pow = 1;
// };
} // namespace Ajisai::Integrators
AJISAI_PLUGIN_REGISTER(BDPTIntegrator, Ajisai::Integrators::BDPTIntegrator,
"ajisai.integrators.Integrator/0.0.1") | 36.111928 | 80 | 0.573878 |
e21d279030ae945e07b298fba9765629f435c3ad | 13,800 | cpp | C++ | lib/Sema/DerivedConformanceVectorProtocol.cpp | eaplatanios/swift-language | be21761f8fb4fe8763dc4786b64819b827fad2f2 | [
"Apache-2.0"
] | 2 | 2020-04-30T06:02:35.000Z | 2020-10-16T12:25:28.000Z | lib/Sema/DerivedConformanceVectorProtocol.cpp | eaplatanios/swift-language | be21761f8fb4fe8763dc4786b64819b827fad2f2 | [
"Apache-2.0"
] | null | null | null | lib/Sema/DerivedConformanceVectorProtocol.cpp | eaplatanios/swift-language | be21761f8fb4fe8763dc4786b64819b827fad2f2 | [
"Apache-2.0"
] | 1 | 2021-09-12T16:22:05.000Z | 2021-09-12T16:22:05.000Z | //===--- DerivedConformanceVectorProtocol.cpp -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements explicit derivation of the VectorProtocol protocol for
// struct types.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "TypeChecker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "DerivedConformances.h"
using namespace swift;
// Return the protocol requirement with the specified name.
// TODO: Move function to shared place for use with other derived conformances.
static ValueDecl *getProtocolRequirement(ProtocolDecl *proto, Identifier name) {
auto lookup = proto->lookupDirect(name);
// Erase declarations that are not protocol requirements.
// This is important for removing default implementations of the same name.
llvm::erase_if(lookup, [](ValueDecl *v) {
return !isa<ProtocolDecl>(v->getDeclContext()) ||
!v->isProtocolRequirement();
});
assert(lookup.size() == 1 && "Ambiguous protocol requirement");
return lookup.front();
}
// Return true if given nominal type has a `let` stored with an initial value.
// TODO: Move function to shared place for use with other derived conformances.
static bool hasLetStoredPropertyWithInitialValue(NominalTypeDecl *nominal) {
return llvm::any_of(nominal->getStoredProperties(), [&](VarDecl *v) {
return v->isLet() && v->hasInitialValue();
});
}
// Return the `VectorSpaceScalar` associated type for the given `ValueDecl` if
// it conforms to `VectorProtocol` in the given context. Otherwise, return
// `nullptr`.
static Type getVectorProtocolVectorSpaceScalarAssocType(
VarDecl *varDecl, DeclContext *DC) {
auto &C = varDecl->getASTContext();
auto *vectorProto = C.getProtocol(KnownProtocolKind::VectorProtocol);
if (!varDecl->hasInterfaceType())
C.getLazyResolver()->resolveDeclSignature(varDecl);
if (!varDecl->hasInterfaceType())
return nullptr;
auto varType = DC->mapTypeIntoContext(varDecl->getValueInterfaceType());
auto conf = TypeChecker::conformsToProtocol(varType, vectorProto, DC, None);
if (!conf)
return nullptr;
return conf->getTypeWitnessByName(varType, C.Id_VectorSpaceScalar);
}
// Return the `VectorSpaceScalar` associated type for the given nominal type in
// the given context, or `nullptr` if `VectorSpaceScalar` cannot be derived.
static Type deriveVectorProtocol_VectorSpaceScalar(NominalTypeDecl *nominal,
DeclContext *DC) {
auto &C = DC->getASTContext();
// Nominal type must be a struct. (Zero stored properties is okay.)
if (!isa<StructDecl>(nominal))
return nullptr;
// If all stored properties conform to `VectorProtocol` and have the same
// `VectorSpaceScalar` associated type, return that `VectorSpaceScalar`
// associated type. Otherwise, the `VectorSpaceScalar` type cannot be derived.
Type sameScalarType;
for (auto member : nominal->getStoredProperties()) {
if (!member->hasInterfaceType())
C.getLazyResolver()->resolveDeclSignature(member);
if (!member->hasInterfaceType())
return nullptr;
auto scalarType = getVectorProtocolVectorSpaceScalarAssocType(member, DC);
// If stored property does not conform to `VectorProtocol`, return nullptr.
if (!scalarType)
return nullptr;
// If same `VectorSpaceScalar` type has not been set, set it for the first
// time.
if (!sameScalarType) {
sameScalarType = scalarType;
continue;
}
// If stored property `VectorSpaceScalar` types do not match, return
// nullptr.
if (!scalarType->isEqual(sameScalarType))
return nullptr;
}
return sameScalarType;
}
bool DerivedConformance::canDeriveVectorProtocol(NominalTypeDecl *nominal,
DeclContext *DC) {
// Must not have any `let` stored properties with an initial value.
// - This restriction may be lifted later with support for "true" memberwise
// initializers that initialize all stored properties, including initial
// value information.
if (hasLetStoredPropertyWithInitialValue(nominal))
return false;
// Must be able to derive `VectorSpaceScalar` associated type.
return bool(deriveVectorProtocol_VectorSpaceScalar(nominal, DC));
}
// Synthesize body for a `VectorProtocol` method requirement.
static std::pair<BraceStmt *, bool>
deriveBodyVectorProtocol_method(AbstractFunctionDecl *funcDecl,
Identifier methodName,
Identifier methodParamLabel) {
auto *parentDC = funcDecl->getParent();
auto *nominal = parentDC->getSelfNominalTypeDecl();
auto &C = nominal->getASTContext();
// Create memberwise initializer: `Nominal.init(...)`.
auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer();
assert(memberwiseInitDecl && "Memberwise initializer must exist");
auto *initDRE =
new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true);
initDRE->setFunctionRefKind(FunctionRefKind::SingleApply);
auto *nominalTypeExpr = TypeExpr::createForDecl(SourceLoc(), nominal,
funcDecl, /*Implicit*/ true);
auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr);
// Get method protocol requirement.
auto *vectorProto = C.getProtocol(KnownProtocolKind::VectorProtocol);
auto *methodReq = getProtocolRequirement(vectorProto, methodName);
// Get references to `self` and parameter declarations.
auto *selfDecl = funcDecl->getImplicitSelfDecl();
auto *selfDRE =
new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true);
auto *paramDecl = funcDecl->getParameters()->get(0);
auto *paramDRE =
new (C) DeclRefExpr(paramDecl, DeclNameLoc(), /*Implicit*/ true);
// Create call expression applying a member method to the parameter.
// Format: `<member>.method(<parameter>)`.
// Example: `x.scaled(by: scalar)`.
auto createMemberMethodCallExpr = [&](VarDecl *member) -> Expr * {
auto *module = nominal->getModuleContext();
auto memberType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
auto confRef = module->lookupConformance(memberType, vectorProto);
assert(confRef && "Member does not conform to `VectorNumeric`");
// Get member type's method, e.g. `Member.scaled(by:)`.
// Use protocol requirement declaration for the method by default: this
// will be dynamically dispatched.
ValueDecl *memberMethodDecl = methodReq;
// If conformance reference is concrete, then use concrete witness
// declaration for the operator.
if (confRef->isConcrete()) {
if (auto *concreteMemberMethodDecl =
confRef->getConcrete()->getWitnessDecl(methodReq))
memberMethodDecl = concreteMemberMethodDecl;
assert(memberMethodDecl);
}
assert(memberMethodDecl && "Member method declaration must exist");
auto memberMethodDRE =
new (C) DeclRefExpr(memberMethodDecl, DeclNameLoc(), /*Implicit*/ true);
memberMethodDRE->setFunctionRefKind(FunctionRefKind::SingleApply);
// Create reference to member method: `x.scaled(by:)`.
auto memberExpr =
new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(),
/*Implicit*/ true);
auto memberMethodExpr =
new (C) DotSyntaxCallExpr(memberMethodDRE, SourceLoc(), memberExpr);
// Create expression: `x.scaled(by: scalar)`.
return CallExpr::createImplicit(C, memberMethodExpr, {paramDRE},
{methodParamLabel});
};
// Create array of member method call expressions.
llvm::SmallVector<Expr *, 2> memberMethodCallExprs;
llvm::SmallVector<Identifier, 2> memberNames;
for (auto *member : nominal->getStoredProperties()) {
memberMethodCallExprs.push_back(createMemberMethodCallExpr(member));
memberNames.push_back(member->getName());
}
// Call memberwise initializer with member method call expressions.
auto *callExpr =
CallExpr::createImplicit(C, initExpr, memberMethodCallExprs, memberNames);
ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true);
auto *braceStmt =
BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true);
return std::pair<BraceStmt *, bool>(braceStmt, false);
}
// Synthesize function declaration for a `VectorProtocol` method requirement.
static ValueDecl *deriveVectorProtocol_method(
DerivedConformance &derived, Identifier methodBaseName,
Identifier argumentLabel, Identifier parameterName, Type parameterType,
Type returnType, AbstractFunctionDecl::BodySynthesizer bodySynthesizer) {
auto nominal = derived.Nominal;
auto &TC = derived.TC;
auto &C = derived.TC.Context;
auto parentDC = derived.getConformanceContext();
auto *param =
new (C) ParamDecl(VarDecl::Specifier::Default, SourceLoc(), SourceLoc(),
argumentLabel, SourceLoc(), parameterName, parentDC);
param->setInterfaceType(parameterType);
ParameterList *params = ParameterList::create(C, {param});
DeclName declName(C, methodBaseName, params);
auto funcDecl = FuncDecl::create(C, SourceLoc(), StaticSpellingKind::None,
SourceLoc(), declName, SourceLoc(),
/*Throws*/ false, SourceLoc(),
/*GenericParams*/ nullptr, params,
TypeLoc::withoutLoc(returnType), parentDC);
funcDecl->setImplicit();
funcDecl->setBodySynthesizer(bodySynthesizer.Fn, bodySynthesizer.Context);
if (auto env = parentDC->getGenericEnvironmentOfContext())
funcDecl->setGenericEnvironment(env);
funcDecl->computeType();
funcDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true);
funcDecl->setValidationToChecked();
derived.addMembersToConformanceContext({funcDecl});
C.addSynthesizedDecl(funcDecl);
// Returned nominal type must define a memberwise initializer.
// Add memberwise initializer if necessary.
if (!nominal->getEffectiveMemberwiseInitializer()) {
// The implicit memberwise constructor must be explicitly created so that
// it can called in `VectorProtocol` methods. Normally, the memberwise
// constructor is synthesized during SILGen, which is too late.
auto *initDecl = createImplicitConstructor(
TC, nominal, ImplicitConstructorKind::Memberwise);
nominal->addMember(initDecl);
C.addSynthesizedDecl(initDecl);
}
return funcDecl;
}
/// Synthesize a method declaration that has the following signture:
/// func {methodBaseName}(
/// {argumentLabel} {parameterName}: VectorSpaceScalar
/// ) -> Self
static ValueDecl *deriveVectorProtocol_unaryMethodOnScalar(
DerivedConformance &derived, Identifier methodBaseName,
Identifier argumentLabel, Identifier parameterName) {
auto &C = derived.TC.Context;
auto *nominal = derived.Nominal;
auto *parentDC = derived.getConformanceContext();
auto selfInterfaceType = parentDC->getDeclaredInterfaceType();
auto scalarType = deriveVectorProtocol_VectorSpaceScalar(nominal, parentDC)
->mapTypeOutOfContext();
auto bodySynthesizer = [](AbstractFunctionDecl *funcDecl,
void *ctx) -> std::pair<BraceStmt *, bool> {
auto methodNameAndLabel = reinterpret_cast<Identifier *>(ctx);
return deriveBodyVectorProtocol_method(
funcDecl, methodNameAndLabel[0], methodNameAndLabel[1]);
};
Identifier baseNameAndLabel[2] = {methodBaseName, argumentLabel};
return deriveVectorProtocol_method(
derived, methodBaseName, argumentLabel, parameterName, scalarType,
selfInterfaceType,
{bodySynthesizer, C.AllocateCopy(baseNameAndLabel).data()});
}
ValueDecl *DerivedConformance::deriveVectorProtocol(ValueDecl *requirement) {
// Diagnose conformances in disallowed contexts.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
auto &C = requirement->getASTContext();
if (requirement->getBaseName() == TC.Context.Id_scaled)
return deriveVectorProtocol_unaryMethodOnScalar(
*this, C.Id_scaled, C.Id_by, C.Id_scale);
if (requirement->getBaseName() == TC.Context.Id_adding)
return deriveVectorProtocol_unaryMethodOnScalar(
*this, C.Id_adding, Identifier(), C.Id_x);
if (requirement->getBaseName() == TC.Context.Id_subtracting)
return deriveVectorProtocol_unaryMethodOnScalar(
*this, C.Id_subtracting, Identifier(), C.Id_x);
TC.diagnose(requirement->getLoc(), diag::broken_vector_protocol_requirement);
return nullptr;
}
Type DerivedConformance::deriveVectorProtocol(AssociatedTypeDecl *requirement) {
// Diagnose conformances in disallowed contexts.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
if (requirement->getBaseName() == TC.Context.Id_VectorSpaceScalar)
return deriveVectorProtocol_VectorSpaceScalar(
Nominal, getConformanceContext());
TC.diagnose(requirement->getLoc(), diag::broken_vector_protocol_requirement);
return nullptr;
}
| 44.37299 | 80 | 0.706957 |
e2228f6754b8bbf31357a6f7086c29b17ac48b84 | 6,380 | hpp | C++ | libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp | MirayXS/Vapecord-ACNL-Plugin | 247eb270dfe849eda325cc0c6adc5498d51de3ef | [
"MIT"
] | null | null | null | #ifndef CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP
#define CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP
#include "CTRPluginFrameworkImpl/Graphics.hpp"
#include "CTRPluginFramework/Graphics/CustomIcon.hpp"
#include "CTRPluginFrameworkImpl/Graphics/TouchKey.hpp"
#include "CTRPluginFrameworkImpl/Graphics/TouchKeyString.hpp"
#include "CTRPluginFramework/Menu/Keyboard.hpp"
#include "CTRPluginFrameworkImpl/System.hpp"
#include "CTRPluginFramework/Sound.hpp"
#include <vector>
#include <string>
namespace CTRPluginFramework
{
enum Layout
{
QWERTY,
DECIMAL,
HEXADECIMAL
};
class Keyboard;
class KeyboardImpl
{
using CompareCallback = bool (*)(const void *, std::string&);
using ConvertCallback = void *(*)(std::string&, bool);
using OnEventCallback = void(*)(Keyboard&, KeyboardEvent&);
using FrameCallback = void (*)(Time);
using KeyIter = std::vector<TouchKey>::iterator;
using KeyStringIter = std::vector<TouchKeyString>::iterator;
public:
KeyboardImpl(const std::string &text = "");
explicit KeyboardImpl(Keyboard *kb, const std::string &text = "");
~KeyboardImpl(void);
void SetLayout(Layout layout);
void SetHexadecimal(bool isHex);
bool IsHexadecimal(void) const;
void SetMaxInput(u32 max);
void CanAbort(bool canAbort);
void CanChangeLayout(bool canChange);
std::string &GetInput(void);
std::string &GetMessage(void);
std::string &GetTitle(void);
void SetError(std::string &error);
void SetConvertCallback(ConvertCallback callback);
void SetCompareCallback(CompareCallback callback);
void OnKeyboardEvent(OnEventCallback callback);
static void OnNewFrame(FrameCallback callback);
void ChangeSelectedEntry(int entry);
int GetSelectedEntry() {return _manualKey;}
void ChangeEntrySound(int entry, SoundEngine::Event soundEvent);
void Populate(const std::vector<std::string>& input, bool resetScroll);
void Populate(const std::vector<CustomIcon>& input, bool resetScroll);
void Clear(void);
int Run(void);
void Close(void);
bool operator()(int &out);
bool DisplayTopScreen;
private:
friend class HexEditor;
friend class ARCodeEditor;
void _RenderTop(void);
void _RenderBottom(void);
void _ProcessEvent(Event &event);
void _UpdateScroll(float delta, bool ignoreTouch);
void _Update(float delta);
// Keyboard layout constructor
void _Qwerty(void);
void _QwertyLowCase(void);
void _QwertyUpCase(void);
void _QwertySymbols(void);
void _QwertyNintendo(void);
static void _DigitKeyboard(std::vector<TouchKey> &keys);
void _Decimal(void);
void _Hexadecimal(void);
void _ScrollUp(void);
void _ScrollDown(void);
void _UpdateScrollInfos(void);
bool _CheckKeys(void); //<- Return if input have changed
bool _CheckInput(void); //<- Call compare callback, return true if the input is valid
bool _CheckButtons(int &ret); //<- for string button
void _HandleManualKeyPress(Key key);
void _ClearKeyboardEvent();
void _ChangeManualKey(int newVal, bool playSound = true);
Keyboard *_owner{nullptr};
std::string _title;
std::string _text;
std::string _error;
std::string _userInput;
bool _canChangeLayout{false};
bool _canAbort{true};
bool _isOpen{false};
bool _askForExit{false};
bool _errorMessage{false};
bool _userAbort{false};
bool _isHex{true};
bool _mustRelease{false};
bool _useCaps{false};
bool _useSymbols{false};
bool _useNintendo{false};
float _offset{0.f};
u32 _max{0};
u8 _symbolsPage{0};
u8 _nintendoPage{0};
Layout _layout{HEXADECIMAL};
Clock _blinkingClock;
int _cursorPositionInString{0};
int _cursorPositionOnScreen{0};
bool _showCursor{true};
CompareCallback _compare{nullptr};
ConvertCallback _convert{nullptr};
OnEventCallback _onKeyboardEvent{nullptr};
static FrameCallback _onNewFrame;
KeyboardEvent _KeyboardEvent{};
std::vector<TouchKey> *_keys{nullptr};
static std::vector<TouchKey> _DecimalKeys;
static std::vector<TouchKey> _HexaDecimalKeys;
static std::vector<TouchKey> _QwertyKeys;
// Custom keyboard stuff
int _manualKey{0};
int _prevManualKey{-2};
bool _manualScrollUpdate{false};
bool _userSelectedKey{false};
bool _customKeyboard{false};
bool _displayScrollbar{false};
bool _isIconKeyboard{false};
int _currentPosition{0};
u32 _scrollbarSize{0};
u32 _scrollCursorSize{0};
float _scrollSize{0.f};
float _scrollPosition{0.f};
float _scrollPadding{0.f};
float _scrollJump{0.f};
float _inertialVelocity{0.f};
float _scrollStart{0.f};
float _scrollEnd{0.f};
IntVector _lastTouch;
Clock _touchTimer;
std::vector<TouchKeyString *> _strKeys;
};
}
#endif
| 38.902439 | 96 | 0.54185 |
e224e709d74a393c04acd3371847fe9ca1d0b0e3 | 704 | cpp | C++ | 152-maxProductSubarray.cpp | riasood02/leetcoding-problems | 568bb4e323acb57e274b87c07969a772f011259e | [
"Unlicense"
] | 5 | 2020-10-06T13:10:04.000Z | 2021-06-07T02:07:59.000Z | 152-maxProductSubarray.cpp | riasood02/leetcoding-problems | 568bb4e323acb57e274b87c07969a772f011259e | [
"Unlicense"
] | 5 | 2020-10-05T17:23:57.000Z | 2020-10-10T12:56:15.000Z | 152-maxProductSubarray.cpp | riasood02/leetcoding-problems | 568bb4e323acb57e274b87c07969a772f011259e | [
"Unlicense"
] | 43 | 2020-10-05T17:31:56.000Z | 2020-10-29T23:47:53.000Z | // https://leetcode.com/problems/maximum-product-subarray/
class Solution {
public:
int maxProduct(vector<int>& nums) {
int cur = INT_MIN;
vector<int> a(nums.size(),0);
vector<int> b(nums.size(),0);
a[0] = nums[0];
b[0] = nums[0];
int ma = a[0];
for(int i = 1 ;i<nums.size();i++){
if(nums[i]<0){
a[i] = max(nums[i],b[i-1]*nums[i]);
b[i] = min(nums[i],a[i-1]*nums[i]);
}
else{
a[i] = max(nums[i],a[i-1]*nums[i]);
b[i] = min(nums[i],b[i-1]*nums[i]);
}
ma = max(a[i],ma);
}
return ma;
}
}; | 27.076923 | 58 | 0.400568 |
e226f459cd362e116b198f580aba183789202887 | 653 | cc | C++ | autofuzz/lcms_fuzz.cc | Munyola/security-research-pocs | bbbd8ccf20999800a736070b379d5116731aa1f5 | [
"Apache-2.0"
] | 2 | 2020-09-18T04:59:08.000Z | 2020-12-28T18:59:36.000Z | autofuzz/lcms_fuzz.cc | Sicks3c/security-research-pocs | bbbd8ccf20999800a736070b379d5116731aa1f5 | [
"Apache-2.0"
] | null | null | null | autofuzz/lcms_fuzz.cc | Sicks3c/security-research-pocs | bbbd8ccf20999800a736070b379d5116731aa1f5 | [
"Apache-2.0"
] | 1 | 2021-06-08T17:12:24.000Z | 2021-06-08T17:12:24.000Z | #include <stdint.h>
#include <string>
#include "lcms2.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size < 2) {
return 0;
}
size_t mid = size / 2;
cmsHPROFILE hInProfile, hOutProfile;
cmsHTRANSFORM hTransform;
hInProfile = cmsOpenProfileFromMem(data, mid);
hOutProfile = cmsOpenProfileFromMem(data + mid, size - mid);
hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_8, hOutProfile,
TYPE_BGR_8, INTENT_PERCEPTUAL, 0);
cmsCloseProfile(hInProfile);
cmsCloseProfile(hOutProfile);
if (hTransform) {
cmsDeleteTransform(hTransform);
}
return 0;
}
| 24.185185 | 73 | 0.689127 |
e22cbd6c605e06532af43dbbde37760a540e4ad3 | 2,773 | hpp | C++ | src/cpp/basic_lot.hpp | plewis/phycas | 9f5a4d9b2342dab907d14a46eb91f92ad80a5605 | [
"MIT"
] | 3 | 2015-09-24T23:12:57.000Z | 2021-04-12T07:07:01.000Z | src/cpp/basic_lot.hpp | plewis/phycas | 9f5a4d9b2342dab907d14a46eb91f92ad80a5605 | [
"MIT"
] | null | null | null | src/cpp/basic_lot.hpp | plewis/phycas | 9f5a4d9b2342dab907d14a46eb91f92ad80a5605 | [
"MIT"
] | 1 | 2015-11-23T10:35:43.000Z | 2015-11-23T10:35:43.000Z | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\
| Phycas: Python software for phylogenetic analysis |
| Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with this program; if not, write to the Free Software Foundation, Inc., |
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#if ! defined(BASIC_LOT_HPP)
#define BASIC_LOT_HPP
#include <cmath>
#include <ctime>
#include <boost/shared_ptr.hpp>
namespace phycas
{
/*----------------------------------------------------------------------------------------------------------------------
| This class was called Lot because the noun lot is defined as "an object used in deciding something by chance"
| according to The New Merriam-Webster Dictionary.
*/
class Lot
{
public:
Lot();
Lot(unsigned);
~Lot();
// Accessors
unsigned GetSeed() const;
unsigned GetInitSeed() const;
// Modifiers
void UseClockToSeed();
void SetSeed(unsigned s);
// Utilities
unsigned MultinomialDraw(const double * probs, unsigned n, double totalProb=1.0);
unsigned SampleUInt(unsigned);
unsigned GetRandBits(unsigned nbits);
double Uniform();
double Normal();
bool Boolean();
private:
unsigned last_seed_setting;
unsigned curr_seed;
};
typedef boost::shared_ptr<Lot> LotShPtr;
inline bool Lot::Boolean()
{
return (Uniform() < 0.5);
}
inline double Lot::Normal()
{
double u = Uniform();
double x = sqrt(-2.0*log(u));
double v = Uniform();
double y = cos(2.0*3.141592653589793238846*v);
return x*y;
}
} // namespace phycas
#endif
| 33.011905 | 120 | 0.510999 |
e2338d870195e71b2e20868ca3757af7d5680636 | 5,493 | cpp | C++ | src/uavpc/Pose/PoseService.cpp | filipdutescu/uavpc | 050bd19b103f2cf7cdac9fd167d8965d0032c5ec | [
"Apache-2.0"
] | 2 | 2021-10-11T02:54:08.000Z | 2021-10-11T09:29:59.000Z | src/uavpc/Pose/PoseService.cpp | filipdutescu/uavpc | 050bd19b103f2cf7cdac9fd167d8965d0032c5ec | [
"Apache-2.0"
] | null | null | null | src/uavpc/Pose/PoseService.cpp | filipdutescu/uavpc | 050bd19b103f2cf7cdac9fd167d8965d0032c5ec | [
"Apache-2.0"
] | null | null | null | #include "uavpc/Pose/PoseService.hpp"
#include <ctime>
#include <iostream>
#include <stdexcept>
#include <string>
#include <opencv2/core/types.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <openpose/core/matrix.hpp>
#include <openpose/core/point.hpp>
#include <openpose/thread/enumClasses.hpp>
namespace uavpc::Pose
{
PoseService::PoseService() noexcept
: m_OpenPoseWrapper(op::ThreadManagerMode::Asynchronous),
m_ShouldRun(false),
m_WithRecognition(false),
m_SaveVideoStream(false)
{
}
PoseService::~PoseService()
{
if (m_ShouldRun)
{
while (!m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_ShouldRun = false;
m_RecognitionMutex.unlock();
while (!m_RecognitionThread.joinable())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
if (m_RecognitionThread.joinable())
{
m_RecognitionThread.join();
}
m_RecognitionMutex.unlock();
if (m_SaveVideoStream)
{
ToggleSaveVideoStream();
}
}
}
TDatumsSP PoseService::DetectPoseFromFrame(const cv::Mat &frame) noexcept
{
const auto rawImage = OP_CV2OPCONSTMAT(frame);
return m_OpenPoseWrapper.emplaceAndPop(rawImage);
}
void PoseService::DisplayFrameWithPose(const TDatumsSP &frame) noexcept
{
try
{
if (frame != nullptr && !frame->empty())
{
const auto image = OP_OP2CVCONSTMAT(frame->at(0U)->cvOutputData);
if (!image.empty())
{
cv::imshow("UAVPC", image);
}
}
}
catch (const std::exception &e)
{
std::cerr << "Could not display frame with pose: " << e.what();
}
}
void PoseService::ToggleRecognition() noexcept
{
m_WithRecognition = !m_WithRecognition;
}
void PoseService::ToggleSaveVideoStream() noexcept
{
m_SaveVideoStream = !m_SaveVideoStream;
if (m_ShouldRun)
{
if (m_SaveVideoStream)
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
constexpr auto format = "uavpc_%Y%m%d_%H%M%S.mp4";
constexpr auto bufferSize = 30U;
char buffer[bufferSize]{ '\0' };
std::strftime(buffer, bufferSize, format, std::localtime(nullptr));
m_PersistentVideoStream.open(
std::string(buffer), cv::VideoWriter::fourcc('M', 'P', '4', 'V'), -1, m_VideoStreamSize);
m_RecognitionMutex.unlock();
}
else
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_PersistentVideoStream.release();
m_RecognitionMutex.unlock();
}
}
}
void PoseService::StartDisplay(cv::VideoCapture &videoStream)
{
m_ShouldRun = true;
if (!videoStream.isOpened())
{
throw std::runtime_error("Video stream closed.");
}
m_RecognitionThread = std::thread(
[&]
{
auto width = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_WIDTH) / 2);
auto height = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_HEIGHT) / 2);
auto opWidth = (width / (16 * 3) + 1) * 16;
auto opHeight = (width / (16 * 3) + 1) * 16;
cv::Mat frame;
op::WrapperStructPose poseConfig{};
poseConfig.netInputSize = op::Point<int>(opWidth, opHeight);
poseConfig.poseModel = op::PoseModel::MPI_15_4;
m_OpenPoseWrapper.configure(poseConfig);
m_OpenPoseWrapper.start();
while (m_ShouldRun)
{
if (videoStream.read(frame))
{
if (!frame.empty())
{
cv::Mat resizedFrame;
cv::resize(frame, resizedFrame, cv::Size(width, height));
cv::Mat persistentFrame = resizedFrame;
if (m_WithRecognition)
{
auto processedFrame = DetectPoseFromFrame(resizedFrame);
DisplayFrameWithPose(processedFrame);
persistentFrame = OP_OP2CVCONSTMAT(processedFrame->at(0U)->cvOutputData);
}
else
{
cv::imshow("UAVPC", resizedFrame);
}
if (m_SaveVideoStream)
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_PersistentVideoStream.write(persistentFrame);
m_RecognitionMutex.unlock();
}
}
}
else
{
std::cout << "could not read frame" << std::endl;
}
cv::waitKey(1);
}
});
}
void PoseService::StopDisplay() noexcept
{
while (!m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_ShouldRun = false;
m_RecognitionMutex.unlock();
while (!m_RecognitionThread.joinable())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
if (m_RecognitionThread.joinable())
{
m_RecognitionThread.join();
}
m_RecognitionMutex.unlock();
m_OpenPoseWrapper.stop();
}
} // namespace uavpc::Pose
| 25.910377 | 101 | 0.57728 |
e23ab9f821e9f74c8baa4061e876516778c0842a | 422 | cpp | C++ | CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp | NicholsTyler/cse_335 | b8a46522c15a9881cb681ae94b4a5f737817b05e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "CppUnitTest.h"
#include "AnimChannelAngle.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Testing
{
TEST_CLASS(CAnimChannelAngleTest)
{
public:
TEST_METHOD(TestCAnimChannelAngleName)
{
CAnimChannelAngle channel;
channel.SetName(L"abcdexx");
Assert::AreEqual(std::wstring(L"abcdexx"), channel.GetName());
}
};
} | 16.230769 | 74 | 0.687204 |
e24129d77e249d87a686a143648196a9981f0b01 | 788 | cpp | C++ | SumNumber/SumNumber.cpp | Tupiet/Learncpp-tutorial | d9c382687d0f7f6dca4bd18c1c78d11368047726 | [
"MIT"
] | null | null | null | SumNumber/SumNumber.cpp | Tupiet/Learncpp-tutorial | d9c382687d0f7f6dca4bd18c1c78d11368047726 | [
"MIT"
] | null | null | null | SumNumber/SumNumber.cpp | Tupiet/Learncpp-tutorial | d9c382687d0f7f6dca4bd18c1c78d11368047726 | [
"MIT"
] | null | null | null |
// This app will, simply, sum two numbers that we'll input from the console. It's an easy program.
#include "sum.h" // Including the header with the math logic
#include "getInput.h" // Including the header with all the inputs
#include "utilities.h" // This includes some utilities that will made this easy to understarnd
#include <iostream> // For having std::cout and std::cin
#include <limits> // We need them for allowing the app to only close if the user press any key.
int main()
{
std::cout << "Bienvenido a SumNumber!\n" << "Somos la aplicacion perfecta si no sabes sumar.\n";
int x = intInput();
int y = intInput();
std::cout << "La suma de " << x << " y " << y << " es igual a " << sum(x, y);
askBeforeExiting();
return 0;
}
| 31.52 | 101 | 0.643401 |
e249cc60aa888d14c8688687992cf22d8f83ba50 | 1,069 | hpp | C++ | include/gclib/gc_delete.hpp | axilmar/gclib | 1d2707238b549d889a7c9b097d599a36e3841da4 | [
"Apache-2.0"
] | 2 | 2021-11-24T18:49:09.000Z | 2022-01-11T04:30:43.000Z | include/gclib/gc_delete.hpp | axilmar/gclib | 1d2707238b549d889a7c9b097d599a36e3841da4 | [
"Apache-2.0"
] | null | null | null | include/gclib/gc_delete.hpp | axilmar/gclib | 1d2707238b549d889a7c9b097d599a36e3841da4 | [
"Apache-2.0"
] | 1 | 2020-10-27T09:51:06.000Z | 2020-10-27T09:51:06.000Z | #ifndef GCLIB_GC_DELETE_HPP
#define GCLIB_GC_DELETE_HPP
#include "gc_new_array.hpp"
namespace gclib {
/**
* Deletes an object pointed to by the given pointer.
* @param p pointer to object to delete; can be null; if not null, then it should have a value returned by gc_new,
* otherwise the operation will have undefined results.
*/
template <class T> void gc_delete(const gc_ptr<T>& p) {
if (!p) {
return;
}
class delete_object {
public:
delete_object(void* obj)
: m_block(gc::object_to_block(obj))
{
gc::begin_remove(m_block);
m_block->vtable->finalize(m_block + 1, m_block->end());
}
~delete_object() {
gc::end_remove(m_block);
m_block->vtable->deallocate(m_block);
}
private:
gc::block* m_block;
};
const delete_object delete_object_var(p.get());
}
} //namespace gclib
#endif //GCLIB_GC_DELETE_HPP
| 22.270833 | 118 | 0.558466 |
e249ede58f2470a9c1f7e80dc03b41cb69fcfeb0 | 6,519 | cpp | C++ | src/VDBMapping.cpp | fzi-forschungszentrum-informatik/vdb_mapping | b15e5349309f82fc05d39152865d6eb43fe75215 | [
"Apache-2.0"
] | 12 | 2021-04-15T10:22:41.000Z | 2022-03-16T16:35:13.000Z | src/VDBMapping.cpp | fzi-forschungszentrum-informatik/vdb_mapping | b15e5349309f82fc05d39152865d6eb43fe75215 | [
"Apache-2.0"
] | 2 | 2021-12-06T18:13:43.000Z | 2022-03-25T11:05:07.000Z | src/VDBMapping.cpp | fzi-forschungszentrum-informatik/vdb_mapping | b15e5349309f82fc05d39152865d6eb43fe75215 | [
"Apache-2.0"
] | 2 | 2021-06-30T10:28:44.000Z | 2022-03-17T10:39:12.000Z | // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2021 FZI Forschungszentrum Informatik
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Marvin Große Besselmann grosse@fzi.de
* \date 2020-12-23
*
*/
//----------------------------------------------------------------------
#include <vdb_mapping/VDBMapping.h>
#include <iostream>
VDBMapping::VDBMapping(const double resolution)
: m_resolution(resolution)
, m_config_set(false)
{
// Initialize Grid
m_vdb_grid = createVDBMap(m_resolution);
}
void VDBMapping::resetMap()
{
m_vdb_grid->clear();
m_vdb_grid = createVDBMap(m_resolution);
}
VDBMapping::GridT::Ptr VDBMapping::createVDBMap(double resolution)
{
GridT::Ptr new_map = GridT::create(0.0);
new_map->setTransform(openvdb::math::Transform::createLinearTransform(m_resolution));
new_map->setGridClass(openvdb::GRID_LEVEL_SET);
return new_map;
}
bool VDBMapping::insertPointCloud(const PointCloudT::ConstPtr& cloud,
const Eigen::Matrix<double, 3, 1>& origin)
{
// Check if a valid configuration was loaded
if (!m_config_set)
{
std::cerr << "Map not properly configured. Did you call setConfig method?" << std::endl;
return false;
}
RayT ray;
DDAT dda;
// Ray origin in world coordinates
openvdb::Vec3d ray_origin_world(origin.x(), origin.y(), origin.z());
// Ray origin in index coordinates
const Vec3T ray_origin_index(m_vdb_grid->worldToIndex(ray_origin_world));
// Ray end point in world coordinates
openvdb::Vec3d ray_end_world;
// Direction the ray is point towards
openvdb::Vec3d ray_direction;
bool max_range_ray;
GridT::Accessor acc = m_vdb_grid->getAccessor();
// Creating a temporary grid in which the new data is casted. This way we prevent the computation
// of redundant probability updates in the actual map
GridT::Ptr temp_grid = GridT::create(0.0);
GridT::Accessor temp_acc = temp_grid->getAccessor();
openvdb::Vec3d x;
double ray_length;
// Raycasting of every point in the input cloud
for (const PointT& pt : *cloud)
{
max_range_ray = false;
ray_end_world = openvdb::Vec3d(pt.x, pt.y, pt.z);
if (m_max_range > 0.0 && (ray_end_world - ray_origin_world).length() > m_max_range)
{
ray_end_world = ray_origin_world + (ray_end_world - ray_origin_world).unit() * m_max_range;
max_range_ray = true;
}
ray_direction = m_vdb_grid->worldToIndex(ray_end_world - ray_origin_world);
ray.setEye(ray_origin_index);
ray.setDir(ray_direction);
dda.init(ray);
ray_length = ray_direction.length();
ray_direction.normalize();
// The signed distance is calculated for each DDA step to determine, when the endpoint is
// reached.
double signed_distance = 1;
while (signed_distance >= 0)
{
x = openvdb::Vec3d(dda.voxel().x(), dda.voxel().y(), dda.voxel().z()) - ray_origin_index;
// Signed distance in grid coordinates for faster processing(not scaled with the grid
// resolution!!!)
// The main idea of the dot product is to first get the center of the current voxel and then
// add half the ray direction to gain the outer boundary of this voxel
signed_distance =
ray_length - ray_direction.dot(x + 0.5 + ray_direction / 2.0);
if (signed_distance >= 0)
{
temp_acc.setActiveState(dda.voxel(), true);
dda.step();
}
else
{
// Set the last passed voxel as occupied if the ray wasn't longer than the maximum raycast
// range
if (!max_range_ray)
{
temp_acc.setValueOn(dda.voxel(), -1);
}
}
}
}
// Probability update lambda for free space grid elements
auto miss = [&prob_miss = m_logodds_miss,
&prob_thres_min = m_logodds_thres_min](float& voxel_value, bool& active) {
voxel_value += prob_miss;
if (voxel_value < prob_thres_min)
{
active = false;
}
};
// Probability update lambda for occupied grid elements
auto hit = [&prob_hit = m_logodds_hit, &prob_thres_max = m_logodds_thres_max](float& voxel_value,
bool& active) {
voxel_value += prob_hit;
if (voxel_value > prob_thres_max)
{
active = true;
}
};
// Integrating the data of the temporary grid into the map using the probability update functions
for (GridT::ValueOnCIter iter = temp_grid->cbeginValueOn(); iter; ++iter)
{
if (*iter == -1)
{
acc.modifyValueAndActiveState(iter.getCoord(), hit);
}
else
{
acc.modifyValueAndActiveState(iter.getCoord(), miss);
}
}
return true;
}
void VDBMapping::setConfig(const Config config)
{
// Sanity Check for input config
if (config.prob_miss > 0.5)
{
std::cerr << "Probability for a miss should be below 0.5 but is " << config.prob_miss
<< std::endl;
return;
}
if (config.prob_hit < 0.5)
{
std::cerr << "Probability for a hit should be above 0.5 but is " << config.prob_miss
<< std::endl;
return;
}
if (config.max_range < 0.0)
{
std::cerr << "Max range of " << config.max_range << " invalid. Range cannot be negative."
<< config.prob_miss << std::endl;
return;
}
m_max_range = config.max_range;
// Store probabilities as log odds
m_logodds_miss = log(config.prob_miss) - log(1 - config.prob_miss);
m_logodds_hit = log(config.prob_hit) - log(1 - config.prob_hit);
m_logodds_thres_min = log(config.prob_thres_min) - log(1 - config.prob_thres_min);
m_logodds_thres_max = log(config.prob_thres_max) - log(1 - config.prob_thres_max);
m_config_set = true;
}
| 32.432836 | 99 | 0.637828 |
f46d513866d62800e662f5381531cf2cd4b82e88 | 2,430 | cpp | C++ | control/groupsform.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | null | null | null | control/groupsform.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | 101 | 2017-03-11T19:09:46.000Z | 2017-09-04T17:37:55.000Z | control/groupsform.cpp | TheMrButcher/offline-mentor | 15c362710fc993b21ed2d23adfc98e797e2380db | [
"MIT"
] | 1 | 2018-03-13T03:47:15.000Z | 2018-03-13T03:47:15.000Z | #include "groupsform.h"
#include "ui_groupsform.h"
#include "group_utils.h"
#include "groupdialog.h"
GroupsForm::GroupsForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::GroupsForm)
{
ui->setupUi(this);
}
GroupsForm::~GroupsForm()
{
delete ui;
}
void GroupsForm::load()
{
ui->listWidget->clear();
ui->listWidget->selectionModel()->clear();
for (const auto& group : getGroups()) {
QListWidgetItem* item = new QListWidgetItem(group.name, ui->listWidget);
item->setData(Qt::UserRole, group.id);
}
}
void GroupsForm::onGroupsPathChanged()
{
loadGroups();
load();
emit groupCollectionChanged();
}
void GroupsForm::createGroup()
{
if (!groupDialog)
groupDialog = new GroupDialog(this);
groupDialog->init(Group::createGroup());
if (groupDialog->exec() == QDialog::Accepted) {
auto newGroup = groupDialog->result();
QListWidgetItem* item = new QListWidgetItem(newGroup.name, ui->listWidget);
item->setData(Qt::UserRole, newGroup.id);
addGroup(newGroup);
emit groupAdded(newGroup.id);
}
}
void GroupsForm::editGroupInRow(int row)
{
if (!groupDialog)
groupDialog = new GroupDialog(this);
auto item = ui->listWidget->item(row);
const auto& group = getGroup(item->data(Qt::UserRole).toUuid());
groupDialog->init(group);
if (groupDialog->exec() == QDialog::Accepted) {
auto newGroup = groupDialog->result();
item->setText(newGroup.name);
addGroup(newGroup);
emit groupCollectionChanged();
}
}
void GroupsForm::on_addButton_clicked()
{
createGroup();
}
void GroupsForm::on_editButton_clicked()
{
editGroupInRow(ui->listWidget->selectionModel()->selectedRows()[0].row());
}
void GroupsForm::on_removeButton_clicked()
{
int row = ui->listWidget->selectionModel()->selectedRows()[0].row();
auto item = ui->listWidget->item(row);
removeGroup(item->data(Qt::UserRole).toUuid());
delete item;
ui->listWidget->selectionModel()->clear();
emit groupCollectionChanged();
}
void GroupsForm::on_listWidget_doubleClicked(const QModelIndex &index)
{
editGroupInRow(index.row());
}
void GroupsForm::on_listWidget_itemSelectionChanged()
{
bool isRowSelected = ui->listWidget->selectionModel()->selectedRows().size() == 1;
ui->editButton->setEnabled(isRowSelected);
ui->removeButton->setEnabled(isRowSelected);
}
| 25.578947 | 86 | 0.671605 |
f46e2fffcd01d3db771283a05a6a14e9cb327b97 | 432 | cpp | C++ | ArkEngineTest/ArkEngineTest.cpp | gamedevboy/ArkEngine | 1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01 | [
"MIT"
] | null | null | null | ArkEngineTest/ArkEngineTest.cpp | gamedevboy/ArkEngine | 1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01 | [
"MIT"
] | null | null | null | ArkEngineTest/ArkEngineTest.cpp | gamedevboy/ArkEngine | 1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../ArkEngine/include/ArkEngine/AEModuleManager.h"
#include "../ArkEngine/include/ArkEngine/gfx/AEGFXDevice.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ArkEngineTest
{
TEST_CLASS(ArkEngineTest)
{
public:
TEST_METHOD(ModuleTest)
{
ArkEngine::GFX::AEGFXDevice device;
ArkEngine::AEModuleManager::Get()->Initialize();
}
};
} | 19.636364 | 62 | 0.743056 |
f472b7a520d86afbd6c1e38b9fa9230bfe2880da | 3,156 | cpp | C++ | day11/day11.cpp | throx/advent2020 | 071dee09e6bb2596c3f78c19f9c97d076798c8b3 | [
"Unlicense"
] | null | null | null | day11/day11.cpp | throx/advent2020 | 071dee09e6bb2596c3f78c19f9c97d076798c8b3 | [
"Unlicense"
] | null | null | null | day11/day11.cpp | throx/advent2020 | 071dee09e6bb2596c3f78c19f9c97d076798c8b3 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
int NumOcc(const vector<string>& seats, int x, int y)
{
int maxx = seats[0].length();
int maxy = seats.size();
int numocc = 0;
for (int x1 = max(0, x - 1); x1 < min(maxx, x + 2); ++x1) {
for (int y1 = max(0, y - 1); y1 < min(maxy, y + 2); ++y1) {
if (x != x1 || y != y1) {
if (seats[y1][x1] == '#') {
++numocc;
}
}
}
}
return numocc;
}
int NumOccSeen(const vector<string>& seats, int x, int y)
{
int maxx = seats[0].length();
int maxy = seats.size();
int numocc = 0;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
if (dx != 0 || dy != 0) {
int x1 = x + dx;
int y1 = y + dy;
while (x1 >= 0 && x1 < maxx && y1 >= 0 && y1 < maxy) {
if (seats[y1][x1] == '#') {
++numocc;
break;
}
else if (seats[y1][x1] == 'L') {
break;
}
x1 += dx;
y1 += dy;
}
}
}
}
return numocc;
}
void DoRound(vector<string>& seats, int maxocc = 4, int occfn(const vector<string>&, int, int) = NumOcc)
{
int maxx = seats[0].length();
int maxy = seats.size();
vector<string> newseats;
for (int y = 0; y < maxy; ++y) {
string s;
for (int x = 0; x < maxx; ++x) {
if (seats[y][x] != '.') {
int n = occfn(seats, x, y);
if (n == 0) {
s.push_back('#');
}
else if (n >= maxocc) {
s.push_back('L');
}
else {
s.push_back(seats[y][x]);
}
}
else {
s.push_back('.');
}
}
newseats.push_back(s);
}
seats = newseats;
}
void Dump(const vector<string>& seats)
{
for (auto v : seats) {
cout << v << endl;
}
cout << endl;
}
int Occupancy(const vector<string>& seats)
{
int occ = 0;
for (auto s : seats) {
for (auto c : s) {
if (c == '#') ++occ;
}
}
return occ;
}
int main()
{
vector<string> seats;
string s;
while (getline(cin, s)) {
seats.push_back(s);
}
auto base = seats;
vector<string> prev;
int rounds = 0;
while (prev != seats) {
prev = seats;
DoRound(seats);
++rounds;
//Dump(seats);
}
cout << "Rounds to stable = " << rounds - 1 << endl;
cout << "Occupancy = " << Occupancy(seats) << endl << endl;
seats = base;
rounds = 0;
while (prev != seats) {
prev = seats;
DoRound(seats, 5, NumOccSeen);
++rounds;
//Dump(seats);
}
cout << "Rounds to stable = " << rounds - 1 << endl;
cout << "Occupancy = " << Occupancy(seats) << endl;
}
| 21.616438 | 104 | 0.398289 |
f474d24b5559b63aa17cce38e93e1ffaff1cee97 | 2,098 | cpp | C++ | cpp/leetcode/RemoveComments.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/RemoveComments.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/RemoveComments.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 722 Remove Comments
//Solution written by Xuqiang Fang on 30 May, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
#include <regex>
using namespace std;
class Solution{
public:
vector<string> removeComments(vector<string>& source) {
/*
* only a few cases, double slash, block
*/
vector<string> ans;
bool in = false;
string b;
for(auto&s : source){
for(int j=0; j<s.length(); ++j){
if(in){
if(s[j] == '*' && j < s.length() - 1 && s[j+1] == '/'){
in = false;
j++;
}
}
else{
if(s[j] == '/' && j < s.length() - 1 && s[j+1] == '*'){
in = true;
j++;
}
else if(s[j] == '/' && j < s.length() - 1 && s[j+1] == '/'){
break;
}
else{
b.push_back(s[j]);
}
}
}
if(!in && b.length() > 0){
ans.push_back(b);
b = "";
}
}
return ans;
}
};
int main(){
Solution s;
vector<string> s1{"/*Test program */", "int main()", "{ ", " // variable declaration ", "aaa//a"};
vector<string> s2{"a/*comment", "line", "more_comment*/b"};
vector<string> s3{"/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"};
vector<string> ans = s.removeComments(s1);
for(auto& a : ans){
cout << a << endl;
}
ans = s.removeComments(s2);
for(auto& a : ans){
cout << a << endl;
}
ans = s.removeComments(s3);
for(auto& a : ans){
cout << a << endl;
}
return 0;
}
| 28.739726 | 203 | 0.408008 |
f4758d1ca2a898ed6dab41ffc92a79c178fe68b9 | 993 | hpp | C++ | Converter/include/converter.hpp | ref-humbold/CPlusPlus-Gtk | acd78ea9ec0fe94c5847b532a05a33b4ca23d898 | [
"MIT"
] | 1 | 2020-08-06T08:06:43.000Z | 2020-08-06T08:06:43.000Z | Converter/include/converter.hpp | ref-humbold/CPlusPlus-Gtk | acd78ea9ec0fe94c5847b532a05a33b4ca23d898 | [
"MIT"
] | null | null | null | Converter/include/converter.hpp | ref-humbold/CPlusPlus-Gtk | acd78ea9ec0fe94c5847b532a05a33b4ca23d898 | [
"MIT"
] | null | null | null | #ifndef CONVERTER_HPP_
#define CONVERTER_HPP_
#include <cstdlib>
#include <cmath>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <string>
#include <vector>
#include <numeric>
class converter_exception : public std::logic_error
{
public:
explicit converter_exception(const std::string & s) : std::logic_error(s)
{
}
};
class converter
{
private:
enum sign
{
minus,
plus,
nosign
};
public:
converter(int base_in, int base_out);
~converter() = default;
std::string convert(const std::string & number) const;
private:
sign get_sign(const std::string & number) const;
void validate_digits(sign sgn, const std::string & number) const;
long long int to_decimal(const std::string & number) const;
std::vector<int> to_base_out(long long int decimal) const;
std::string build_number(sign sgn, const std::vector<int> & number) const;
int base_in, base_out;
};
#endif
| 20.265306 | 78 | 0.683787 |
f47cb5a5ca81f778eccc1c89e0c3879162d31a72 | 1,921 | cpp | C++ | mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp | belieflong/media-dev-android | 6103cdce4725bc9ab1a8d5d085abbdab26a164dc | [
"Apache-2.0"
] | null | null | null | mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp | belieflong/media-dev-android | 6103cdce4725bc9ab1a8d5d085abbdab26a164dc | [
"Apache-2.0"
] | null | null | null | mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp | belieflong/media-dev-android | 6103cdce4725bc9ab1a8d5d085abbdab26a164dc | [
"Apache-2.0"
] | null | null | null | #include "mp3_encoder.h"
#define LOG_TAG "Mp3Encoder"
Mp3Encoder::Mp3Encoder() {
}
Mp3Encoder::~Mp3Encoder() {
}
int Mp3Encoder::Init(const char* pcmFilePath, const char *mp3FilePath, int sampleRate, int channels, int bitRate) {
int ret = -1;
pcmFile = fopen(pcmFilePath, "rb");
if(pcmFile) {
mp3File = fopen(mp3FilePath, "wb");
if(mp3File) {
lameClient = lame_init();
lame_set_in_samplerate(lameClient, sampleRate);
lame_set_out_samplerate(lameClient, sampleRate);
lame_set_num_channels(lameClient, channels);
lame_set_brate(lameClient, bitRate / 1000);
lame_init_params(lameClient);
ret = 0;
}
}
return ret;
}
void Mp3Encoder::Encode() {
int bufferSize = 1024 * 512; // 缓冲区的数据量大小 (512KB)
short* buffer = new short[bufferSize / 2]; //262144[bit] -> 256[Byte] (262144B -> 256KB)
short* leftBuffer = new short[bufferSize / 4];
short* rightBuffer = new short[bufferSize / 4];
uint8_t* mp3_buffer = new uint8_t[bufferSize];
int readBufferSize = 0;
LOGD("sizeof(short) = %zd", sizeof(short));
//将PCM数据读取到 buffer 中,一次性读 2*(bufferSize / 2)的数据量
while ((readBufferSize = fread(buffer, 2, bufferSize / 2, pcmFile)) > 0) {
for (int i = 0; i < readBufferSize; i++) {
// 读取到的长度 分割为两半:一半左声道、一半右声道,分别填充数据
if (i % 2 == 0) {
leftBuffer[i / 2] = buffer[i];
} else {
rightBuffer[i / 2] = buffer[i];
}
}
LOGD("readBufferSize = %d", readBufferSize); // 成功读取的元素总数 * size(short) = pcm的总字节数
//左声道数据、右声道数据、每个通道的样本数量、MP3buffer、buffer大小 ->返回每段数据 编码后的长度,写入文件
int wroteSize = lame_encode_buffer(lameClient, (short int *) leftBuffer, (short int *) rightBuffer, readBufferSize / 2, mp3_buffer, bufferSize);
fwrite(mp3_buffer, 1, wroteSize, mp3File);
}
delete[] buffer;
delete[] leftBuffer;
delete[] rightBuffer;
delete[] mp3_buffer;
}
void Mp3Encoder::Destory() {
if(pcmFile) {
fclose(pcmFile);
}
if(mp3File) {
fclose(mp3File);
lame_close(lameClient);
}
}
| 28.671642 | 146 | 0.68506 |
f47e2107c702f649175447aec68f6acf7eaff645 | 254 | hpp | C++ | pythran/pythonic/include/operator_/__itruediv__.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/operator_/__itruediv__.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/operator_/__itruediv__.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP
#define PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP
#include "pythonic/include/operator_/itruediv.hpp"
namespace pythonic
{
namespace operator_
{
USING_FUNCTOR(__itruediv__, itruediv);
}
}
#endif
| 15.875 | 50 | 0.807087 |
f47e9665cb2ddbe80c4ea6ef19e806cc109ec4d8 | 5,435 | cpp | C++ | LexRisLogic/src/MathStructures/Polygon.cpp | chanochambure/LexRisLogicHeaders | 00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6 | [
"MIT"
] | 2 | 2016-01-31T03:32:25.000Z | 2020-12-07T02:59:35.000Z | LexRisLogic/src/MathStructures/Polygon.cpp | chanochambure/LexRisLogicHeaders | 00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6 | [
"MIT"
] | null | null | null | LexRisLogic/src/MathStructures/Polygon.cpp | chanochambure/LexRisLogicHeaders | 00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6 | [
"MIT"
] | null | null | null | /* Polygon.cpp -- Polygon Math Structure Source - LexRis Logic Headers
Copyright (c) 2017-2018 LexRisLogic
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.
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 "../../include/LexRisLogic/MathStructures/Polygon.h"
namespace LL_MathStructure
{
bool Polygon::add_point(Point point)
{
if(point.get_dimension()==2)
{
_V_points.push_back(point);
return true;
}
return false;
}
bool Polygon::remove_point(unsigned int index)
{
if(index>=_V_points.size())
return false;
_V_points.erase(_V_points.begin()+index);
return true;
}
unsigned int Polygon::size()
{
return _V_points.size();
}
void Polygon::clear()
{
_V_points.clear();
}
bool Polygon::set_point(unsigned int index,Point new_point)
{
if(new_point.get_dimension()==2 and index<_V_points.size())
{
_V_points[index]=new_point;
return true;
}
return false;
}
const Point Polygon::operator [] (unsigned int index)
{
return _V_points[index];
}
bool LL_SHARED point_into_polygon(Polygon polygon,Point point)
{
if(point.get_dimension()==2 and polygon.size()>2)
{
float max_pos_x=polygon[0][0];
for(unsigned int i=1;i<polygon.size();++i)
{
if(polygon[i][0]>max_pos_x)
max_pos_x=polygon[i][0];
}
unsigned int count_intersection=0;
for(unsigned int i=0;i<polygon.size();++i)
{
unsigned int j=(i+1)%polygon.size();
LineSegment first_segment(2);
first_segment.set_ini_point(point);
first_segment.set_end_point(create_point(max_pos_x+1,point[1]));
LineSegment second_segment(2);
second_segment.set_ini_point(polygon[i]);
second_segment.set_end_point(polygon[j]);
count_intersection+=intersection_of_line_segments_in_two_dimensions(first_segment,second_segment);
}
return count_intersection%2;
}
return false;
}
bool LL_SHARED collision_of_polygons(Polygon first_polygon,Polygon second_polygon,std::list<Point>* points)
{
if(first_polygon.size()>2 and second_polygon.size()>2)
{
for(unsigned int i=0;i<first_polygon.size();++i)
{
unsigned int j=(i+1)%first_polygon.size();
for(unsigned int k=0;k<second_polygon.size();++k)
{
unsigned int l=(k+1)%second_polygon.size();
float intersection_x;
float intersection_y;
LineSegment first_segment(2);
first_segment.set_ini_point(first_polygon[i]);
first_segment.set_end_point(first_polygon[j]);
LineSegment second_segment(2);
second_segment.set_ini_point(second_polygon[k]);
second_segment.set_end_point(second_polygon[l]);
if(intersection_of_line_segments_in_two_dimensions(first_segment,second_segment,
&intersection_x,&intersection_y))
{
if(points)
{
bool insertion=true;
for(std::list<Point>::iterator m=points->begin();m!=points->end();++m)
{
if((*m)[0]==intersection_x and (*m)[1]==intersection_y)
{
insertion=false;
break;
}
}
if(insertion)
points->push_back(create_point(intersection_x,intersection_y));
}
else
return true;
}
}
}
if(points and points->size())
return true;
return (point_into_polygon(first_polygon,second_polygon[0]) or
point_into_polygon(second_polygon,first_polygon[0]));
}
return false;
}
}
| 39.384058 | 119 | 0.552714 |
f4858b21356f076b7544d53c05055b358c718911 | 3,229 | hpp | C++ | src/Zv8/V8Engine.hpp | indie-zen/zen-server | deb4485fe462d6c88eeeadb09c62e6024e06ff67 | [
"MIT"
] | null | null | null | src/Zv8/V8Engine.hpp | indie-zen/zen-server | deb4485fe462d6c88eeeadb09c62e6024e06ff67 | [
"MIT"
] | 8 | 2016-12-06T15:55:28.000Z | 2016-12-18T17:31:36.000Z | src/Zv8/V8Engine.hpp | indie-zen/zen-server | deb4485fe462d6c88eeeadb09c62e6024e06ff67 | [
"MIT"
] | null | null | null | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// V8 plugin for Zen Scripting
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include <Zen/Scripting/I_ScriptEngine.hpp>
#include <memory>
#include <v8.h>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Zv8 {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class V8Engine
: public Zen::Scripting::I_ScriptEngine
, public std::enable_shared_from_this<V8Engine>
{
/// @name I_ScriptEngine implementation
/// @{
public:
virtual void initialize(pConfiguration_type _pConfiguration = nullptr);
virtual Scripting::I_ObjectHeap& heap();
virtual bool executeScript(const std::string& _fileName);
virtual void executeMethod(boost::any& _object, boost::any& _method, std::vector<boost::any>& _parms);
virtual pScriptModule_type createScriptModule(const std::string& _moduleName, const std::string& _docString);
/// @}
/// @name V8Engine implementation
/// @{
public:
/// Implementation of managed_self_ref from Zen 1.x
std::shared_ptr<V8Engine> getSelfReference();
/// Execute a script that is embedded in a string
/// @param _source - String to execute
/// @param _name - Name of the string (usually the URI where the string
/// was loaded from)
/// @param _printResult - output the results of the script to std::cout
/// @param _reportExceptions - output an exception report if the script throws
/// an uncaught exception.
bool executeString(v8::Local<v8::String> _source, v8::Local<v8::Value> _name,
bool _printResult, bool _reportExecptions);
/// Read a file into a (maybe local) string
/// @todo Zen Server should not support direct file access; instead, all
/// source must be loaded from a container local segment of Zen Spaces.
/// This is only being supported as a temporary measure until Zen Spaces
/// integration is complete.
v8::MaybeLocal<v8::String> readFile(const std::string& _scriptName);
/// Report an exception
/// Output an exception to std::cout (maybe it should be std::cerr?)
void reportException(v8::TryCatch* _pTryCatch);
/// Convert a v8 string to a C string
const char* toCString(const v8::String::Utf8Value& value);
v8::Isolate* getIsolate();
/// @}
/// @name 'Structors
/// @{
public:
V8Engine();
virtual ~V8Engine();
/// @}
/// @name Member variables
/// @{
private:
v8::Platform* m_pPlatform;
v8::Isolate* m_pIsolate;
v8::Isolate::Scope* m_pGlobalScope;
v8::HandleScope* m_pHandleScope;
// v8::Global<v8::ObjectTemplate> m_global;
v8::Global<v8::Context> m_context;
/// @}
}; // class V8Engine
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Zv8
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 35.483516 | 113 | 0.549396 |
f498dc62d5bebae3e8bd7c1efbc82658400f67d4 | 2,051 | cpp | C++ | Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp | PavelSaltykov/Course1 | 68920c4a4679b6dd0e0b83cb8109d3c52d2cf076 | [
"Apache-2.0"
] | null | null | null | Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp | PavelSaltykov/Course1 | 68920c4a4679b6dd0e0b83cb8109d3c52d2cf076 | [
"Apache-2.0"
] | 2 | 2019-12-17T11:58:46.000Z | 2019-12-21T20:08:01.000Z | Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp | PavelSaltykov/Course1 | 68920c4a4679b6dd0e0b83cb8109d3c52d2cf076 | [
"Apache-2.0"
] | 1 | 2020-02-24T18:28:00.000Z | 2020-02-24T18:28:00.000Z | #include <stdio.h>
#include <string.h>
#include "list.h"
struct Entry
{
char *name = nullptr;
char *phone = nullptr;
Entry *next = nullptr;
};
struct List
{
int length = 0;
Entry *head = nullptr;
Entry *tail = nullptr;
};
List *createList()
{
return new List;
}
bool isEmpty(List *list)
{
return list->head == nullptr;
}
void addEntry(List *list, char *name, char *phone)
{
list->length++;
char *newName = new char[strlen(name) + 1];
char *newPhone = new char[strlen(phone) + 1];
strcpy(newName, name);
strcpy(newPhone, phone);
Entry *newEntry = new Entry {newName, newPhone, nullptr};
if (isEmpty(list))
{
list->head = newEntry;
list->tail = list->head;
return;
}
list->tail->next = newEntry;
list->tail = list->tail->next;
}
char *returnNameFromHead(List *list)
{
return list->head->name;
}
char *returnPhoneFromHead(List *list)
{
return list->head->phone;
}
int listLength(List *list)
{
return list->length;
}
void deleteHead(List *list)
{
if (isEmpty(list))
{
return;
}
list->length--;
Entry *temp = list->head->next;
delete list->head->name;
delete list->head->phone;
delete list->head;
list->head = temp;
}
bool checkSort(List *list, bool byName)
{
if (isEmpty(list))
{
return true;
}
Entry *current = list->head->next;
Entry *previous = list->head;
while (current != nullptr)
{
int comparison = 0;
if (byName)
{
comparison = strcmp(current->name, previous->name);
}
else
{
comparison = strcmp(current->phone, previous->phone);
}
if (comparison < 0)
{
return false;
}
previous = current;
current = current->next;
}
return true;
}
void printList(List *list)
{
if (isEmpty(list))
{
return;
}
Entry *current = list->head;
while (current != nullptr)
{
printf("%s - %s\n", current->name, current->phone);
current = current->next;
}
}
void deleteList(List *list)
{
while (!isEmpty(list))
{
Entry *temp = list->head->next;
delete list->head->name;
delete list->head->phone;
delete list->head;
list->head = temp;
}
delete list;
} | 15.537879 | 58 | 0.641151 |
f49da775121857bfc051cb595e70bbd9923d03ea | 3,588 | cpp | C++ | main.cpp | DennisZZH/CS263_Project_Garbage_Collector | 07e81c0eb532792cb3d1fd504b501bca67b5365d | [
"MIT"
] | null | null | null | main.cpp | DennisZZH/CS263_Project_Garbage_Collector | 07e81c0eb532792cb3d1fd504b501bca67b5365d | [
"MIT"
] | null | null | null | main.cpp | DennisZZH/CS263_Project_Garbage_Collector | 07e81c0eb532792cb3d1fd504b501bca67b5365d | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <sstream>
#include "frontend/lexer.h"
#include "frontend/parser.h"
#include "backend/codegen.h"
using namespace cs160::frontend;
using namespace cs160::backend;
void usage(char const* programName) {
std::cerr << "Usage: " << programName << " program.l2 [--gen-asm-only] output-file\n\n"
<< "This program compiles given L2 program. If the `--gen-asm-only` option is given, it will only generate the assembly code, otherwise it will also link the assembly code with the bootstrap code and GC code to produce an executable.";
}
// Option for generating assembly only
const std::string OnlyGenAsm{"--gen-asm-only"};
// C++ compiler. We use it as linker. GCC's C++ compier is usually named `g++` on most systems.
const std::string CPPCompiler{"g++"};
// Name of the assembler program. GNU assembler is usually named `as` on most systems.
const std::string Assembler{"as"};
int main(int argc, char* argv[]) {
std::string outputFileName;
bool link = true;
if (argc == 3) {
outputFileName = argv[2];
} else if (argc == 4 && OnlyGenAsm == argv[2]) {
outputFileName = argv[3];
link = false;
} else{
usage(argv[0]);
return 1;
}
std::ifstream programFile{argv[1]};
if (!programFile.is_open()) {
std::cerr << "'" << argv[1]
<< "' does not exist or is not a regular file.\n\n";
usage(argv[0]);
} // Read the file
std::string programText{std::istreambuf_iterator<char>(programFile),
std::istreambuf_iterator<char>()};
// Run the lexer
std::cout << "Lexing the input program '" << argv[1] << "'" << std::endl;
Lexer lexer;
auto tokens = lexer.tokenize(programText);
// Run the parser
std::cout << "Parsing the token stream" << std::endl;
Parser parser(tokens);
auto ast = parser.parse();
if (! ast) {
std::cerr << "Parse error: the parser produced an empty unique_ptr" << std::endl;
return 1;
}
// Run the code generator
std::cout << "Generating code" << std::endl;
CodeGen codeGen;
auto insns = codeGen.generateCode(*ast);
// Write out the assembly file
std::string asmFileName = link ? (outputFileName + ".asm") : outputFileName;
std::ofstream asmFile{asmFileName};
if (!asmFile.is_open()) {
std::cerr << "Failed to open the assembly file '" << asmFileName << "'" << std::endl;
return 1;
}
for (auto & line : insns) {
asmFile << line << "\n";
}
asmFile.close();
// Assemble and link to build an executable
if (link) {
// Assemble the object file
std::cout << "Calling the assembler on the assembly code to build\n";
std::ostringstream cmdLine;
cmdLine << Assembler << " --32 -g " << asmFileName << " -o " << outputFileName << ".o";
auto cmd = cmdLine.str();
std::cout << "Running assembler command: " << cmd << std::endl;
if (auto err = std::system(cmd.c_str())) {
std::cerr << "Assembler command exited with error code " << err << std::endl;
return 1;
}
// Link the object files
std::cout << "Linking the bootstrap code with L2 program object code\n";
// reset the command line
cmdLine = std::ostringstream{};
cmdLine << CPPCompiler << " -m32 build/bootstrap.o build/gc.o " << outputFileName << ".o -o " << outputFileName;
cmd = cmdLine.str();
std::cout << "Running linker command: " << cmd << std::endl;
// Run the linker
if (auto err = std::system(cmd.c_str())) {
std::cerr << "Linker exited with error code " << err << std::endl;
return 1;
}
}
return 0;
}
| 31.752212 | 247 | 0.625139 |
f4a5bfba34e14bc084fff11d5e9053a3bf5831ca | 3,815 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | // ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/CopyOp>
#include <osg/NodeVisitor>
#include <osg/Object>
#include <osgParticle/Emitter>
#include <osgParticle/Particle>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_ABSTRACT_OBJECT_REFLECTOR(osgParticle::Emitter)
I_DeclaringFile("osgParticle/Emitter");
I_BaseType(osgParticle::ParticleProcessor);
I_Constructor0(____Emitter,
"",
"");
I_ConstructorWithDefaults2(IN, const osgParticle::Emitter &, copy, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY,
____Emitter__C5_Emitter_R1__C5_osg_CopyOp_R1,
"",
"");
I_Method0(const char *, libraryName,
Properties::VIRTUAL,
__C5_char_P1__libraryName,
"return the name of the node's library. ",
"");
I_Method0(const char *, className,
Properties::VIRTUAL,
__C5_char_P1__className,
"return the name of the node's class type. ",
"");
I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
Properties::VIRTUAL,
__bool__isSameKindAs__C5_osg_Object_P1,
"return true if this and obj are of the same kind of object. ",
"");
I_Method1(void, accept, IN, osg::NodeVisitor &, nv,
Properties::VIRTUAL,
__void__accept__osg_NodeVisitor_R1,
"Visitor Pattern : calls the apply method of a NodeVisitor with this node's type. ",
"");
I_Method0(const osgParticle::Particle &, getParticleTemplate,
Properties::NON_VIRTUAL,
__C5_Particle_R1__getParticleTemplate,
"Get the particle template. ",
"");
I_Method1(void, setParticleTemplate, IN, const osgParticle::Particle &, p,
Properties::NON_VIRTUAL,
__void__setParticleTemplate__C5_Particle_R1,
"Set the particle template (particle is copied). ",
"");
I_Method0(bool, getUseDefaultTemplate,
Properties::NON_VIRTUAL,
__bool__getUseDefaultTemplate,
"Return whether the particle system's default template should be used. ",
"");
I_Method1(void, setUseDefaultTemplate, IN, bool, v,
Properties::NON_VIRTUAL,
__void__setUseDefaultTemplate__bool,
"Set whether the default particle template should be used. ",
"When this flag is true, the particle template is ignored, and the particle system's default template is used instead. ");
I_ProtectedMethod1(void, process, IN, double, dt,
Properties::VIRTUAL,
Properties::NON_CONST,
__void__process__double,
"",
"");
I_ProtectedMethod1(void, emit, IN, double, dt,
Properties::PURE_VIRTUAL,
Properties::NON_CONST,
__void__emit__double,
"",
"");
I_SimpleProperty(const osgParticle::Particle &, ParticleTemplate,
__C5_Particle_R1__getParticleTemplate,
__void__setParticleTemplate__C5_Particle_R1);
I_SimpleProperty(bool, UseDefaultTemplate,
__bool__getUseDefaultTemplate,
__void__setUseDefaultTemplate__bool);
END_REFLECTOR
| 39.329897 | 133 | 0.603932 |
f4ab44e636aa92f02d494f3c626325500d4f0c26 | 666 | cpp | C++ | src/SerialMenu.cpp | rico-quidel/SerialMenu | 4891c0b670aecd23fd5c7d7906c012147f2c24b7 | [
"MIT"
] | 7 | 2020-02-02T21:13:26.000Z | 2021-07-27T22:24:50.000Z | src/SerialMenu.cpp | rico-quidel/SerialMenu | 4891c0b670aecd23fd5c7d7906c012147f2c24b7 | [
"MIT"
] | 4 | 2020-02-06T17:50:34.000Z | 2022-01-03T12:59:44.000Z | src/SerialMenu.cpp | rico-quidel/SerialMenu | 4891c0b670aecd23fd5c7d7906c012147f2c24b7 | [
"MIT"
] | 7 | 2020-12-22T01:23:49.000Z | 2022-02-23T12:59:25.000Z | ///////////////////////////////////////////////////////////////////////////////
// Serial port Menus
// SerialMenu - Copyright (c) 2019 Dan Truong
// See SerialMenu.hpp for details
///////////////////////////////////////////////////////////////////////////////
#define SERIALMENU_DISABLE_PROGMEM_SUPPORT true
#define SERIALMENU_MINIMAL_FOOTPRINT true
#include <SerialMenu.hpp>
// Instantiate the singleton menu instance. It is initialized when called
//SerialMenu SerialMenu::singleton;
SerialMenu* SerialMenu::singleton = nullptr;
const SerialMenuEntry* SerialMenu::menu = nullptr;
uint16_t SerialMenu::waiting = uint16_t(0);
uint8_t SerialMenu::size = uint8_t(0); | 44.4 | 79 | 0.608108 |
f4ab84cd87a1853294e48fc98a7110a2fd1a11f9 | 6,507 | hpp | C++ | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDMacroEng_StdClass.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 01/24/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// 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 is the header file for the CIDMacroEng_StdClass.cpp file, which
// implements derivates of the class info and class value classes that are
// used by the compiler for compiled macros from user code. These classes
// are all the same except for the classpath of the class. The members of
// such a class are all dynamically controlled and added as method, var,
// import, and so forth objects. The invocation is just a passthrough to
// the targeted method object.
//
// The value class is just a dummy, since we don't need any actual C++
// level data members, but we must have an instance data class. At some
// point, it might be used to keep some housekeeping, instrumentation, or
// debugging info. The macro level member objects are handled by the common
// base value class. Any classes which only need macro level members objects
// can use this class for their value object, which is all macro level
// defined classes, but also any wrapped C++ classes which store their
// data as standard macro level value objects (and they all should if they
// can.)
//
// Copying to and from involves copying the contents of each defined
// variable for that class. We initially set the class as copyable, but
// if any non-coypable member is added, it becomes non-copyable.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TMEngStdClassInfo;
// ---------------------------------------------------------------------------
// CLASS: TMEngStdClassVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
class CIDMACROENGEXP TMEngStdClassVal : public TMEngClassVal
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMEngStdClassVal
(
const TString& strName
, const tCIDLib::TCard2 c2ClassId
, const tCIDMacroEng::EConstTypes eConst
);
TMEngStdClassVal(const TMEngStdClassVal&) = delete;
~TMEngStdClassVal();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMEngStdClassVal& operator=(const TMEngStdClassVal&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bDbgFormat
(
TTextOutStream& strmTarget
, const TMEngClassInfo& meciThis
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices eRadix
, const TCIDMacroEngine& meOwner
) const override;
tCIDLib::TVoid CopyFrom
(
const TMEngClassVal& mecvToCopy
, TCIDMacroEngine& meOwner
) override;
protected :
// -------------------------------------------------------------------
// Declare our friends. We want our info class to be our friend so
// that, when he creates a new instance, he can load us up with
// value objects for our members.
// -------------------------------------------------------------------
friend class TMEngStdClassInfo;
private :
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMEngStdClassVal,TMEngClassVal)
};
// ---------------------------------------------------------------------------
// CLASS: TMEngStdClassInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
class CIDMACROENGEXP TMEngStdClassInfo : public TMEngClassInfo
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMEngStdClassInfo
(
const TString& strName
, const TString& strBasePath
, TCIDMacroEngine& meOwner
, const TString& strParentClassPath
);
TMEngStdClassInfo(const TMEngStdClassInfo&) = delete;
~TMEngStdClassInfo();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMEngStdClassInfo& operator=(const TMEngStdClassInfo&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
TMEngClassVal* pmecvMakeStorage
(
const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst
) const override;
protected :
// -------------------------------------------------------------------
// Protected, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bInvokeMethod
(
TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance
) override;
private :
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMEngStdClassInfo,TMEngClassInfo)
};
#pragma CIDLIB_POPPACK
| 35.950276 | 78 | 0.442908 |
f4ac64b514f7a6a1259d2da3562e3034220407b8 | 16,221 | cc | C++ | swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc | TimothyZhang023/swapdb | e40c1ddf46892e698acf54f26b02927f0505ea84 | [
"BSD-2-Clause"
] | 242 | 2017-12-14T00:31:28.000Z | 2022-02-16T02:00:15.000Z | swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc | javaperson/swapdb | 66efd9f919dfaa56dcefd9b39a8bdabe57624546 | [
"BSD-2-Clause"
] | 7 | 2017-12-14T08:34:43.000Z | 2020-12-19T02:53:03.000Z | swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc | javaperson/swapdb | 66efd9f919dfaa56dcefd9b39a8bdabe57624546 | [
"BSD-2-Clause"
] | 47 | 2017-12-26T03:11:26.000Z | 2022-01-26T07:46:45.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sstream>
#include "SSDB_client.h"
#include "gtest/gtest.h"
#include "ssdb_test.h"
using namespace std;
class HashTest : public SSDBTest
{
public:
ssdb::Status s;
std::vector<std::string> list, keys, kvs2;
std::map<std::string, std::string> kvs;
string key, val, getVal, field;
uint16_t keysNum;
int64_t ret;
};
TEST_F(HashTest, Test_hash_hset) {
#define OKHset s = client->hset(key, field, val);\
ASSERT_TRUE(s.ok())<<"fail to hset key!"<<endl;\
s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.ok()&&(val == getVal))<<"fail to hget key val!"<<s.code()<<key<<endl;
#define FalseHset s = client->hset(key, field, val);\
ASSERT_TRUE(s.error())<<"this key should set fail!"<<s.code()<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHset
// set exsit key
field = GetRandomField_();
val = GetRandomVal_();
OKHset
s = client->multi_del(key);
}
// Some random keys
keysNum = 100;
val = "";
key = GetRandomKey_();
field = GetRandomField_();
s = client->multi_del(key);
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
OKHset
}
s = client->hsize(key, &ret);
ASSERT_EQ(keysNum, ret);
s = client->multi_del(key);
//other types key
field = GetRandomField_();
val = GetRandomVal_();
client->multi_del(key);
s = client->set(key, val);
FalseHset
client->multi_del(key);
client->sadd(key, val);
FalseHset
client->multi_del(key);
client->qpush_front(key, val);
FalseHset
client->multi_del(key);
client->zset(key, field, 1.0);
FalseHset
client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hget) {
#define NotFoundHget s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
// Some random keys
for(int n = 0; n < 5; n++)
{
key = GetRandomKey_();
val = GetRandomVal_();
field = GetRandomField_();
s = client->multi_del(key);
NotFoundHget
}
keysNum = 100;
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
s = client->hset(key, field, val);
}
field = field+itoa(keysNum);
NotFoundHget
s = client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hdel) {
#define OKHdel s = client->multi_hdel(key, field);\
ASSERT_TRUE(s.ok())<<"fail to delete key!"<<key<<endl;\
s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.not_found())<<"this key should be deleted!"<<key<<endl;
#define NotFoundHdel s = client->multi_hdel(key, field);\
ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
//Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
client->multi_del(key);
val = GetRandomVal_();
field = GetRandomField_();
s = client->hset(key, field, val);
OKHdel
// NotFoundHdel
}
keysNum = 100;
val = "";
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
s = client->hset(key, field, val);
OKHdel
// NotFoundHdel
}
}
TEST_F(HashTest, Test_hash_hincrby) {
#define OKHincr incr = GetRandomInt64_();\
s = client->multi_del(key);\
s = client->hincr(key, field, incr, &ret);\
ASSERT_TRUE(s.ok());\
s = client->hget(key, field, &getVal);\
ASSERT_EQ(to_string(incr), getVal);\
\
s = client->hincr(key, field, n, &ret);\
ASSERT_TRUE(s.ok());\
s = client->hget(key, field, &getVal);\
ASSERT_EQ(to_string(incr+n), getVal);\
s = client->multi_hdel(key, field);
#define FalseHincr s = client->hincr(key, field, 1, &ret);\
ASSERT_TRUE(s.error())<<"this key should hincr fail!"<<endl;
int64_t incr, ret, n = 0;
//Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
n++;
key = *it;
field = GetRandomField_();
OKHincr
client->multi_del(key);
}
//Some random keys
keysNum = 10;
val = "";
for(n = 0; n < keysNum; n++)
{
key = GetRandomKey_();
field = GetRandomField_();
OKHincr
client->multi_del(key);
}
s = client->multi_del(key);
s = client->hincr(key, field, MAX_INT64, &ret);
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MAX_INT64), getVal);
s = client->hincr(key, field, 1, &ret);
ASSERT_TRUE(s.error());
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MAX_INT64), getVal);
s = client->multi_del(key);
s = client->hincr(key, field, MIN_INT64, &ret);
ASSERT_EQ((MIN_INT64), ret);
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MIN_INT64), getVal);
s = client->hincr(key, field, -1, &ret);
ASSERT_TRUE(s.error());
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MIN_INT64), getVal);
s = client->multi_hdel(key, field);
//other types key
field = GetRandomField_();
val = GetRandomVal_();
client->multi_del(key);
s = client->set(key, val);
FalseHincr
client->multi_del(key);
client->sadd(key, val);
FalseHincr
client->multi_del(key);
client->qpush_front(key, val);
FalseHincr
client->multi_del(key);
client->zset(key, field, 1.0);
FalseHincr
client->multi_del(key);
}
//hdecr removed
//TEST_F(HashTest, Test_hash_hdecrby) {
//#define OKHdecr decr = GetRandomInt64_();\
// s = client->multi_del(key);\
// s = client->hdecr(key, field, decr, &ret);\
// ASSERT_TRUE(s.ok());\
// s = client->hget(key, field, &getVal);\
// ASSERT_EQ(to_string(-1*decr), getVal);\
// \
// s = client->hdecr(key, field, n, &ret);\
// ASSERT_TRUE(s.ok());\
// s = client->hget(key, field, &getVal);\
// ASSERT_EQ(to_string(-1*(decr+n)), getVal);\
// s = client->multi_hdel(key, field);
//
// int64_t decr, ret, n = 0;
// //Some special keys
// for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
// {
// n++;
// key = *it;
// field = GetRandomField_();
// OKHdecr
// client->multi_del(key);
// }
//}
TEST_F(HashTest, Test_hash_hgetall) {
#define NotExsitHgetall s = client->hgetall(key, &list);\
ASSERT_TRUE(s.ok());\
ASSERT_EQ(0, list.size())<<"get list should be empty!"<<endl;
// EXPECT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
key = GetRandomKey_();
val = GetRandomVal_();
field = GetRandomField_();
s = client->multi_del(key);
NotExsitHgetall
keysNum = 10;
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
val = val+itoa(n);
kvs.insert(std::make_pair(field, val));
s = client->hset(key, field, val);
}
s = client->hgetall(key, &list);
for(int n = 0; n < keysNum; n += 2)
{
EXPECT_EQ(kvs[list[n]], list[n+1]);
}
s = client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hsize) {
#define OKHsize(num) s = client->hsize(key, &ret);\
ASSERT_EQ(ret, num)<<"fail to hsize key!"<<key<<endl;\
ASSERT_TRUE(s.ok())<<"hsize key not ok!"<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHsize(0)
s = client->hset(key, field, val);
OKHsize(1)
s = client->multi_hdel(key, field);
}
key = GetRandomKey_();
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
for(int n = 0; n < 10; n++)
{
field = field+itoa(n);
val = val+itoa(n);
client->hset(key, field, val);
OKHsize(n+1)
}
s = client->multi_del(key);
}
//use del instead of hclear,and hclear cannot clear 100 elements hash key now.
/*
TEST_F(HashTest, Test_hash_hclear) {
#define OKHclear(num) s = client->hclear(key, &ret);\
ASSERT_EQ(ret , num)<<"fail to hclear key!"<<key<<endl;\
s = client->hsize(key, &ret);\
ASSERT_EQ(ret, 0)<<"key is not null!"<<key<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHclear(0)
s = client->hset(key, field, val);
OKHclear(1)
}
key = GetRandomKey_();
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
for(int n = 0; n < 100; n++)
{
field = field+itoa(n);
val = val+itoa(n);
client->hset(key, field, val);
}
OKHclear(100)
} */
TEST_F(HashTest, Test_hash_hkeys) {
key = GetRandomKey_();
s = client->hkeys(key, "", "", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 0);
list.clear();
client->hset(key, "000000001","");
client->hset(key, "000000002","");
client->hset(key, "000000003","");
//TODO HKEYS command changed
s = client->hkeys(key, "000000000", "000000002", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
ASSERT_EQ("000000001", list[0]);
ASSERT_EQ("000000002", list[1]);
list.clear();
s = client->hkeys(key, "000000000", "000000003", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
ASSERT_EQ("000000003", list[2]);
list.clear();
s = client->hkeys(key, "000000000", "000000003", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
s = client->multi_del(key);
}
TEST_F(HashTest, DISABLED_Test_hash_hscan) {
key = GetRandomKey_();
s = client->hscan(key, "", "", 2, &list);
ASSERT_TRUE(s.ok() && list.size() <= 4);
list.clear();
client->multi_del("key");
client->hset("key", "00000000f1","v1");
client->hset("key", "00000000f2","v2");
s = client->hscan("key", "00000000f0", "00000000f2", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 4);
ASSERT_EQ("00000000f1", list[0]);
ASSERT_EQ("v1", list[1]);
ASSERT_EQ("00000000f2", list[2]);
ASSERT_EQ("v2", list[3]);
list.clear();
s = client->hscan("key", "00000000f2", "00000000f0", 2, &list);
ASSERT_EQ(0, list.size());
s = client->multi_del("key");
s = client->hscan("key", "00000000f0", "00000000f2", 2, &list);
ASSERT_EQ(0, list.size());
}
//remove hrscan
/* TEST_F(HashTest, Test_hash_hrscan) {
key = GetRandomKey_();
s = client->hrscan(key, "", "", 2, &list);
ASSERT_TRUE(s.ok() && list.size() <= 4);
list.clear();
client->multi_del("key");
client->hset("key", "00000000f1","v1");
client->hset("key", "00000000f2","v2");
s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 4);
ASSERT_EQ("00000000f2", list[0]);
ASSERT_EQ("v2", list[1]);
ASSERT_EQ("00000000f1", list[2]);
ASSERT_EQ("v1", list[3]);
list.clear();
s = client->hrscan("key", "00000000f1", "00000000f3", 2, &list);
ASSERT_EQ(0, list.size());
s = client->multi_del("key");
s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list);
ASSERT_EQ(0, list.size());
} */
TEST_F(HashTest, Test_hash_hmset_hmget_hdel) {
//Redis hmset/hmget/hdel
string key, field1, field2, field3, val1, val2, val3;
key = GetRandomKey_();
field1 = GetRandomField_();
field2 = field1+'2';
field3 = field1+'3';
val1 = GetRandomVal_();
val2 = val1+'2';
val3 = val1+'3';
kvs.clear();
keys.clear();
list.clear();
kvs.insert(std::make_pair(field1, val1));
kvs.insert(std::make_pair(field2, val2));
keys.push_back(field1);
keys.push_back(field2);
keys.push_back(field3);
//all keys not exist
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(0, ret);
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(4, list.size());
ASSERT_EQ(field1, list[0]);
ASSERT_EQ(val1, list[1]);
ASSERT_EQ(field2, list[2]);
ASSERT_EQ(val2, list[3]);
kvs.insert(std::make_pair(field3, val3));
//one key not exist, two keys exist
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(6, list.size());
kvs.clear();
val1 = val1+'1';
val2 = val2+'2';
val3 = val3+'3';
kvs.insert(std::make_pair(field1, val1));
kvs.insert(std::make_pair(field2, val2));
kvs.insert(std::make_pair(field3, val3));
//all keys exist, update their vals
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(6, list.size());
ASSERT_EQ(field1, list[0]);
ASSERT_EQ(val1, list[1]);
ASSERT_EQ(field2, list[2]);
ASSERT_EQ(val2, list[3]);
ASSERT_EQ(field3, list[4]);
ASSERT_EQ(val3, list[5]);
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(3, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
kvs.clear();
list.clear();
keys.clear();
int fieldNum = 10;
for(int n = 0; n < fieldNum; n++)
{
kvs.insert(std::make_pair(field1 + itoa(n), val1 + itoa(n)));
keys.push_back(field1 + itoa(n));
}
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(fieldNum*2, list.size());
for(int n = 0; n < fieldNum; n++)
{
ASSERT_EQ(field1 + itoa(n), list[n*2]);
ASSERT_EQ(val1 + itoa(n), list[n*2+1]);
}
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(fieldNum, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
client->sadd(key, "val");
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.error());
s = client->multi_hget(key, keys, &list);
ASSERT_TRUE(s.error());
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.error());
client->multi_del(key);
}
TEST_F(HashTest, Test_hash_samefields_hmset_hmget_hdel) {
//simulate process same fields at one time.
key = "hkey";
field = "hfield_";
val = "hval_";
keysNum = 1;
kvs2.clear();
keys.clear();
for(int m = 0;m < 2;m++){
for(int n = 0;n < keysNum;n++) {
keys.push_back(field+itoa(n));
kvs2.push_back(field+itoa(n));
kvs2.push_back(val+itoa(n));
}
}
//all keys not exist
client->multi_del(key);
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(0, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
//same field same value hmset
s = client->multi_hset(key, kvs2);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(keys.size()*2, list.size());
for(int n = 0;n < 2*keysNum;n++) {
ASSERT_EQ(field+itoa(n%keysNum), list[2*n]);
ASSERT_EQ(val+itoa(n%keysNum), list[2*n+1]);
}
//same key diff value mset
for(int n = 0;n < keysNum;n++) {
keys.push_back(field+itoa(n));
kvs2.push_back(field+itoa(n));
kvs2.push_back(val+itoa(n*2));
}
s = client->multi_hset(key, kvs2);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(keys.size()*2, list.size());
for(int n = 0;n < 3*keysNum;n++) {
ASSERT_EQ(field+itoa(n%keysNum), list[2*n]);
ASSERT_EQ(val+itoa(n%keysNum*2), list[2*n+1]);
}
client->multi_hdel(key, keys, &ret);
ASSERT_EQ(keysNum, ret);
}
| 28.308901 | 87 | 0.573208 |
f4acf5c25709d692fda58cf417492ad69f05621d | 3,227 | cpp | C++ | src/HandGunC.cpp | pablojor/mood | 779af33ae3fc596c1749901917f67c0d8a14d63f | [
"MIT"
] | null | null | null | src/HandGunC.cpp | pablojor/mood | 779af33ae3fc596c1749901917f67c0d8a14d63f | [
"MIT"
] | 2 | 2020-04-12T14:01:00.000Z | 2020-05-20T12:53:11.000Z | src/HandGunC.cpp | NoVariableGlobal/mood | e3446857a1d309dfac71beaf6407bb905f02a912 | [
"MIT"
] | 1 | 2020-10-07T15:09:45.000Z | 2020-10-07T15:09:45.000Z | #include "HandGunC.h"
#include "BulletC.h"
#include "ComponentsManager.h"
#include "Entity.h"
#include "FactoriesFactory.h"
#include "Ogre.h"
#include "OgreQuaternion.h"
#include "RigidbodyPC.h"
#include "Scene.h"
#include "TransformComponent.h"
#include <json.h>
void HandGunC::onShoot(TransformComponent* transform, RigidbodyPC* rigidBody) {
Ogre::Quaternion quat = getOrientation();
transform->setPosition(myTransform_->getPosition() +
(quat * Ogre::Vector3::UNIT_Y) * 25 +
(quat * Ogre::Vector3::UNIT_Z) * 10);
transform->setOrientation(myTransform_->getOrientation());
rigidBody->setLinearVelocity((quat * Ogre::Vector3::UNIT_Z) * bulletSpeed_);
GunC::onShoot(transform, rigidBody);
}
// FACTORY INFRASTRUCTURE
HandGunCFactory::HandGunCFactory() = default;
Component* HandGunCFactory::create(Entity* _father, Json::Value& _data,
Scene* _scene) {
HandGunC* hg = new HandGunC();
_scene->getComponentsManager()->addDC(hg);
hg->setFather(_father);
hg->setScene(_scene);
hg->setSoundManager();
if (!_data["bulletTag"].isString())
throw std::exception("HandGunC: bulletTag is not a string");
hg->setBulletTag(_data["bulletTag"].asString());
if (!_data["bulletchamberMax"].isInt())
throw std::exception("HandGunC: bulletchamberMax is not an int");
hg->setbulletchamber(_data["bulletchamberMax"].asInt());
if (!_data["munition"].isInt())
throw std::exception("HandGunC: munition is not an int");
hg->setmunition(_data["munition"].asInt());
if (!_data["bulletDamage"].isDouble())
throw std::exception("HandGunC: bulletDamage is not a double");
hg->setbulletdamage(_data["bulletDamage"].asDouble());
if (!_data["bulletSpeed"].isDouble())
throw std::exception("HandGunC: bulletSpeed is not a double");
hg->setbulletspeed(_data["bulletSpeed"].asDouble());
if (!_data["cadence"].isDouble())
throw std::exception("HandGunC: cadence is not an int");
hg->setcadence(_data["cadence"].asFloat());
if (!_data["automatic"].isBool())
throw std::exception("HandGunC: semiautomatic is not an bool");
hg->setautomatic(_data["automatic"].asBool());
if (!_data["instakill"].isBool())
throw std::exception("HandGunC: instakill is not an bool");
hg->setInstakill(_data["instakill"].asBool());
if (_data["infiniteAmmo"].isBool())
hg->setInfiniteAmmo(_data["infiniteAmmo"].asBool());
if (!_data["bulletType"].isString())
throw std::exception("HandGunC: bulletType is not a string");
hg->setBulletType(_data["bulletType"].asString());
if (!_data["shotSound"].isString())
throw std::exception("HandGunC: shotSound is not a string");
hg->setShotSound(_data["shotSound"].asString());
if (!_data["bulletComponent"].isString())
throw std::exception("HandGunC: bulletComponent is not a string");
hg->setBulletComponentName(_data["bulletComponent"].asString());
hg->setTransform(reinterpret_cast<TransformComponent*>(
_father->getComponent("TransformComponent")));
return hg;
};
DEFINE_FACTORY(HandGunC);
| 35.076087 | 80 | 0.662845 |
f4ad65e4c0e2b702c324528a34702eec26bceafb | 6,137 | cpp | C++ | opt_kappa.cpp | dokyum/tiLDA | 7dc3a2c8023bfc92b777fa9a2f50ace65209fccc | [
"Apache-2.0"
] | 2 | 2016-01-21T02:40:42.000Z | 2018-12-22T18:07:02.000Z | opt_kappa.cpp | vineelpratap/tiLDA | 7dc3a2c8023bfc92b777fa9a2f50ace65209fccc | [
"Apache-2.0"
] | null | null | null | opt_kappa.cpp | vineelpratap/tiLDA | 7dc3a2c8023bfc92b777fa9a2f50ace65209fccc | [
"Apache-2.0"
] | 2 | 2015-02-13T20:53:34.000Z | 2021-01-30T17:11:51.000Z | #include "opt_kappa.h"
#define KAPPA_NEWTON_THRESH 1e-6
#define KAPPA_MAX_ITER 5000
#define LIKELIHOOD_DECREASE_ALLOWANCE 1e-5
extern double oneoverk;
double opt_kappa(double* kappa, int ntopics, int nchildren,
double* dirichlet_prior,
double alpha, double tau,
double* digamma_sum_over_children,
int node_index)
{
double* g = NULL;
double* h = NULL;
double* delta_kappa = NULL;
double* new_kappa = NULL;
g = zero_init_double_array(ntopics);
h = zero_init_double_array(ntopics);
delta_kappa = zero_init_double_array(ntopics);
new_kappa = zero_init_double_array(ntopics);
for (int i = 0; i < ntopics; ++i) {
kappa[i] = oneoverk;
}
#ifdef _DEBUG
// printf("kappa opt start %d : nchildren %d \t alpha %5.15f \t tau %5.15f \n",
// node_index, nchildren, alpha, tau);
// for (int i = 0; i < ntopics; ++i) {
// printf("kappa opt start %d %d : dirichlet_prior %5.15f \t kappa %5.15f \n",
// node_index, i, dirichlet_prior[i], kappa[i]);
// }
#endif
double invhsum = 0;
double goverhsum = 0;
double coefficient = 0;
double old_likelihood = 0;
// double likelihood = 0;
double sqr_newton_decrement = 0;
double step_size;
double indep_new_likelihood = 0;
double dep_new_likelihood = 0;
double new_likelihood;
double expected_increase;
#ifdef _DEBUG
double initial_likelihood;
#endif
int iter = 0;
for (int i = 0; i < ntopics; ++i) {
double const taukappai = tau * kappa[i];
double const alphakappai = alpha * kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const digammataukappai = digamma(taukappai);
double const logkappai = log(kappa[i]);
dep_new_likelihood += digammataukappai * common;
indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai);
indep_new_likelihood += alphakappai * digamma_sum_over_children[i];
dep_new_likelihood += lgamma(taukappai);
}
new_likelihood = indep_new_likelihood + dep_new_likelihood;
#ifdef _DEBUG
initial_likelihood = new_likelihood;
#endif
do {
iter++;
invhsum = 0;
goverhsum = 0;
coefficient = 0;
for (int i = 0; i < ntopics; ++i) {
double const taukappai = tau * kappa[i];
double const alphakappai = alpha * kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const digammataukappai = digamma(taukappai);
double const trigammataukappai = trigamma(taukappai);
double const logkappai = log(kappa[i]);
g[i] = tau * trigammataukappai * common
- nchildren * alpha * (digamma(alphakappai) - logkappai + digammataukappai - 1)
- nchildren / kappa[i]
+ alpha * digamma_sum_over_children[i];
h[i] = tau * tau * tetragamma(taukappai) * common
- tau * trigammataukappai * (tau + 2 * alpha * nchildren)
- alpha * alpha * trigamma(alphakappai) * nchildren
+ alpha * nchildren / kappa[i]
+ nchildren / (kappa[i] * kappa[i]);
invhsum += 1 / h[i];
goverhsum += g[i] / h[i];
}
old_likelihood = new_likelihood;
coefficient = goverhsum / invhsum;
sqr_newton_decrement = 0;
expected_increase = 0;
step_size = 1;
for (int i = 0; i < ntopics; ++i) {
delta_kappa[i] = (coefficient - g[i]) / h[i];
sqr_newton_decrement -= h[i] * delta_kappa[i] * delta_kappa[i]; // this one is maximization
expected_increase += g[i] * delta_kappa[i];
//sqr_newton_decrement += g[i] * delta_kappa[i];
if (delta_kappa[i] < 0) {
double limit = (kappa[i] - 1e-10) / -(delta_kappa[i]);
if (step_size > limit) {
step_size = limit;
}
}
}
#ifdef _DEBUG
printf("kappa maximization %d : L %5.15f \t dL %5.15f \t indL %5.15f \t newton %5.15f \t %5.15f\n",
node_index, old_likelihood, dep_new_likelihood, indep_new_likelihood, sqr_newton_decrement / 2, step_size);
// for (int i = 0; i < ntopics; ++i) {
// printf("kappa maximization %d %d: delta_kappa %5.15f \n",
// node_index, i, delta_kappa[i]);
// }
#endif
if (sqr_newton_decrement < KAPPA_NEWTON_THRESH * 2 || step_size < 1e-8 ) {
break;
}
// backtracking line search
while(1) {
// double sum_new_kappa = 0.0;
indep_new_likelihood = 0.0;
dep_new_likelihood = 0.0;
for (int i = 0; i < ntopics; ++i) {
new_kappa[i] = kappa[i] + step_size * delta_kappa[i];
double const taukappai = tau * new_kappa[i];
double const alphakappai = alpha * new_kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const logkappai = log(new_kappa[i]);
dep_new_likelihood += digamma(taukappai) * common;
indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai);
indep_new_likelihood += alphakappai * digamma_sum_over_children[i];
dep_new_likelihood += lgamma(taukappai);
}
new_likelihood = indep_new_likelihood + dep_new_likelihood;
#ifdef _DEBUG
printf("line search %d : nL: %5.15f \t bound: %5.15f \t step_size: %5.15f \n",
node_index, new_likelihood, old_likelihood + 0.4 * step_size * expected_increase, step_size);
#endif
if (new_likelihood > old_likelihood + 0.4 * step_size * expected_increase) {
// if (new_likelihood > old_likelihood + 0.4 * step_size * sqr_newton_decrement) {
break;
}
step_size *= 0.9;
if (step_size < 1e-8) break;
}
if (step_size < 1e-8) break;
for (int i = 0; i < ntopics; ++i) {
kappa[i] = new_kappa[i];
assert(!std::isnan(kappa[i]));
assert(kappa[i] > 0);
}
} while (iter < KAPPA_MAX_ITER);
if (iter >= KAPPA_MAX_ITER) {
printf("KAPPA_MAX_ITER reached\n");
exit(-1);
}
#ifdef _DEBUG
printf("%d TL %5.15f \t IL %5.15f \n", node_index, new_likelihood, initial_likelihood);
assert(new_likelihood >= initial_likelihood ||
( ((initial_likelihood - new_likelihood) / fabs(initial_likelihood) < LIKELIHOOD_DECREASE_ALLOWANCE)
&& (iter >= 3) )
);
#endif
free(new_kappa);
free(delta_kappa);
free(g);
free(h);
return new_likelihood;
}
| 31.311224 | 112 | 0.653577 |
f4aef88cf32cde12ced412931608263def713ce6 | 1,686 | cpp | C++ | Utility/lib/src/utility/math_utils.cpp | tdenis8/S3DR | fb8f4c0c98b5571abb12a51e03229978115b099b | [
"MIT"
] | 1 | 2019-07-10T04:25:45.000Z | 2019-07-10T04:25:45.000Z | Utility/lib/src/utility/math_utils.cpp | tdenis8/S3DR | fb8f4c0c98b5571abb12a51e03229978115b099b | [
"MIT"
] | null | null | null | Utility/lib/src/utility/math_utils.cpp | tdenis8/S3DR | fb8f4c0c98b5571abb12a51e03229978115b099b | [
"MIT"
] | null | null | null | #include "math_utils.hpp"
#include <cmath>
glm::vec3 MeanPoint(const std::vector<glm::vec3> & points){
glm::vec3 result(0.0, 0.0, 0.0);
auto size=points.size();
for(auto it=points.begin(); it<points.end(); ++it){
result += *it;
}
if(size>0){
result /= size;
}
return result;
}
float DegToRad(float angle_deg)
{
const float deg_to_rad = 3.14159f * 2.0f / 360.0f;
return angle_deg * deg_to_rad;
}
bool IsNull(float value){
if(value < 0.000000001){
return true;
}
return false;
}
glm::vec3 CircleCenterFromCirclePoints(const std::vector<glm::vec3> & points){
if(points.size()!=3){
return glm::vec3(0.0, 0.0, 0.0);
}
const glm::vec3 & p1 = points[0];
const glm::vec3 & p2 = points[1];
const glm::vec3 & p3 = points[2];
auto tmp = glm::length(glm::cross(p1-p2, p2-p3));
if(IsNull(tmp)){
return glm::vec3(0.0, 0.0, 0.0);
}
auto k = 1/(2*tmp*tmp);
tmp = glm::length(p2-p3);
glm::vec3 a = (tmp*tmp) * glm::cross(p1-p2,p1-p3) * k;
tmp = glm::length(p1-p3);
glm::vec3 b = (tmp*tmp) * glm::cross(p2-p1,p2-p3) * k;
tmp = glm::length(p1-p2);
glm::vec3 c = (tmp*tmp) * glm::cross(p3-p1,p3-p2) * k;
return a*p1 + b*p2 + c*p3;
}
float CircleRadiusFromCirclePoints(const std::vector<glm::vec3> & points){
if(points.size()!=3){
return 0.0;;
}
const glm::vec3 & p1 = points[0];
const glm::vec3 & p2 = points[1];
const glm::vec3 & p3 = points[2];
float tmp1 = glm::length(p1-p2) * glm::length(p2-p3) * glm::length(p3-p1);
float tmp2 = 2 * glm::length(glm::cross(p1-p2, p2-p3));
if(IsNull(tmp2)){
return 0.0;
}
return tmp1/tmp2;
} | 21.896104 | 78 | 0.578885 |
f4b24fd42585dcb7dc04986e92fbbad1563f21a0 | 944 | cc | C++ | dreal/util/infty.cc | martinjos/dlinear4 | c0569f49762393eab2cd5d8823db8decb3cbe15e | [
"Apache-2.0"
] | 2 | 2020-07-12T18:01:24.000Z | 2020-10-02T21:11:51.000Z | dreal/util/infty.cc | martinjos/dlinear4 | c0569f49762393eab2cd5d8823db8decb3cbe15e | [
"Apache-2.0"
] | null | null | null | dreal/util/infty.cc | martinjos/dlinear4 | c0569f49762393eab2cd5d8823db8decb3cbe15e | [
"Apache-2.0"
] | null | null | null | /// @file infty.cc
///
#include "dreal/util/infty.h"
namespace dreal {
namespace util {
mpq_class* mpq_class_infinity = nullptr;
mpq_class* mpq_class_ninfinity = nullptr;
void InftyStart(double val) {
mpq_class_infinity = new mpq_class(val);
mpq_class_ninfinity = new mpq_class(-val);
}
void InftyStart(const mpq_class& val) {
mpq_class_infinity = new mpq_class(val);
mpq_class_ninfinity = new mpq_class(-val);
}
void InftyStart(const mpq_t infty, const mpq_t ninfty) {
mpq_class_infinity = new mpq_class(infty);
mpq_class_ninfinity = new mpq_class(ninfty);
}
void InftyFinish() {
delete mpq_class_infinity;
delete mpq_class_ninfinity;
}
// Important: must call InftyStart() first!
// Also, if using QSXStart(), must call it before InftyStart().
const mpq_class& mpq_infty() {
return *mpq_class_infinity;
}
const mpq_class& mpq_ninfty() {
return *mpq_class_ninfinity;
}
} // namespace util
} // namespace dreal
| 20.977778 | 63 | 0.739407 |
f4b9f8ed45470d551028eb05368f1f2c8ae8d057 | 2,856 | cpp | C++ | naklibsrc/src/core/MessageHash/Base58EncDec.cpp | murphyj8/testNakStructure | fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a | [
"Unlicense"
] | 1 | 2021-07-01T02:01:27.000Z | 2021-07-01T02:01:27.000Z | naklibsrc/src/core/MessageHash/Base58EncDec.cpp | murphyj8/testNakStructure | fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a | [
"Unlicense"
] | 1 | 2020-09-23T12:34:34.000Z | 2020-09-23T12:34:34.000Z | naklibsrc/src/core/MessageHash/Base58EncDec.cpp | murphyj8/testNakStructure | fbd9fc0784b6b7ee3b176cb28d2b6e26abd2b48a | [
"Unlicense"
] | null | null | null | #include "MessageHash/Base58EncDec.h"
#include "MessageHash/Base58EncDecImpl.h"
Base58EncDec::Base58EncDec() : m_pImpl(new Base58EncDecImpl){
return ;
}
Base58EncDec::~Base58EncDec(){
return ;
}
std::string Base58EncDec::encode (const std::vector<uint8_t>& vch){
return (m_pImpl->encode(vch));
}
std::string Base58EncDec::encodeCheck (const std::vector<uint8_t>& vch){
return (m_pImpl->encodeCheck(vch));
}
messageVec Base58EncDec::decode (const std::string& msg){
return (m_pImpl->decode(msg));
}
messageVec Base58EncDec::decodeCheck(const std::string& msg){
return (m_pImpl->decodeCheck(msg));
}
std::string EncodeBase58 (const std::string& msg)
{
std::vector<uint8_t> vec;
for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter)
{
vec.push_back(*iter);
}
Base58EncDec encdec ;
std::string encVal = encdec.encode (vec);
return encVal ;
}
std::string DecodeBase58 (const std::string& msg)
{
std::string nonConstMsg ( msg );
nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1);
std::unique_ptr<unsigned char[]> msgPtr ( new unsigned char [nonConstMsg.length()+1]);
std::fill_n(msgPtr.get(), msg.length()+1, 0x00);
std::string::const_iterator iter = nonConstMsg.begin();
for (unsigned int i = 0; i < nonConstMsg.size();++i)
{
msgPtr.get()[i] = *iter ; ++ iter ;
}
Base58EncDec encdec;
std::vector<uint8_t> decodedVal = encdec.decode(nonConstMsg);
std::string retVal;
for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter)
{
retVal.push_back(*iter);
}
return retVal ;
}
std::string EncodeBase58Checked (const std::string& msg)
{
std::vector<uint8_t> vec;
for (std::string::const_iterator iter = msg.begin(); iter != msg.end(); ++ iter)
{
vec.push_back(*iter);
}
Base58EncDec encdec ;
std::string encVal = encdec.encodeCheck (vec);
return encVal ;
}
std::string DecodeBase58Checked (const std::string& msg)
{
std::string nonConstMsg ( msg );
nonConstMsg = nonConstMsg.erase(nonConstMsg.find_last_not_of("\t\n\v\f\r ")+1);
std::unique_ptr<unsigned char> msgPtr ( new unsigned char [nonConstMsg.length()+1]);
std::fill_n(msgPtr.get(), msg.length()+1, 0x00);
std::string::const_iterator iter = nonConstMsg.begin();
for (unsigned int i = 0; i < nonConstMsg.size();++i)
{
msgPtr.get()[i] = *iter ; ++ iter ;
}
Base58EncDec encdec;
std::vector<uint8_t> decodedVal = encdec.decodeCheck(nonConstMsg);
std::string retVal;
for(std::vector<uint8_t>::const_iterator iter = decodedVal.begin();iter != decodedVal.end(); ++ iter)
{
retVal.push_back(*iter);
}
return retVal ;
} | 30.382979 | 105 | 0.644258 |
f4bafce0eb4329174202ea4c22b8e6b84b9afafe | 94,230 | cpp | C++ | src/raven_src/src/StandardOutput.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | src/raven_src/src/StandardOutput.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | src/raven_src/src/StandardOutput.cpp | Okanagan-Basin-Water-Board/obwb-hydro-modelling | 91ee6b914e344de65a495093c3b9427986182ef2 | [
"Artistic-2.0"
] | null | null | null | /*----------------------------------------------------------------
Raven Library Source Code
Copyright (c) 2008-2020 the Raven Development Team
Includes CModel routines for writing output headers and contents:
CModel::CloseOutputStreams()
CModel::WriteOutputFileHeaders()
CModel::WriteMinorOutput()
CModel::WriteMajorOutput()
CModel::SummarizeToScreen()
CModel::RunDiagnostics()
Ensim output routines
NetCDF output routines
----------------------------------------------------------------*/
#include "Model.h"
#include "StateVariables.h"
#if defined(_WIN32)
#include <direct.h>
#elif defined(__linux__)
#include <sys/stat.h>
#endif
int NetCDFAddMetadata (const int fileid,const int time_dimid, string shortname,string longname,string units);
int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units);
void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript);
void AddSingleValueToNetCDF (const int out_ncid,const string &label,const size_t time_index,const double &value);
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the flow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousFlowObs(CTimeSeriesABC *pObs,long SBID)
{
// clears up terribly ugly repeated if statements
if(pObs==NULL){return false;}
if (s_to_l(pObs->GetTag().c_str()) != SBID){ return false; }//SBID is correct
if(pObs->GetType() != CTimeSeriesABC::TS_REGULAR){ return false; }
return (!strcmp(pObs->GetName().c_str(),"HYDROGRAPH")); //name ="HYDROGRAPH"
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir stage series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousStageObs(CTimeSeriesABC *pObs,long SBID)
{
// clears up terribly ugly repeated if statements
if(pObs==NULL){return false;}
return (
(!strcmp(pObs->GetName().c_str(),"RESERVOIR_STAGE")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousInflowObs(CTimeSeriesABC *pObs, long SBID)
{
// clears up terribly ugly repeated if statements
if (pObs == NULL) { return false; }
return (
(!strcmp(pObs->GetName().c_str(), "RESERVOIR_INFLOW")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief returns true if specified observation time series is the reservoir inflow series for subbasin SBID
/// \param pObs [in] observation time series
/// \param SBID [in] subbasin ID
//
bool IsContinuousNetInflowObs(CTimeSeriesABC *pObs, long SBID)
{
// clears up terribly ugly repeated if statements
if (pObs == NULL) { return false; }
return (
(!strcmp(pObs->GetName().c_str(), "RESERVOIR_NETINFLOW")) &&
(s_to_l(pObs->GetTag().c_str()) == SBID) &&
(pObs->GetType() == CTimeSeriesABC::TS_REGULAR)
);
}
//////////////////////////////////////////////////////////////////
/// \brief Adds output directory & prefix to base file name
/// \param filebase [in] base filename, with extension, no directory information
/// \param &Options [in] Global model options information
//
string FilenamePrepare(string filebase, const optStruct &Options)
{
string fn;
if (Options.run_name==""){fn=Options.output_dir+filebase;}
else {fn=Options.output_dir+Options.run_name+"_"+filebase;}
return fn;
}
//////////////////////////////////////////////////////////////////
/// \brief Closes output file streams
/// \details after end of simulation from Main() or in ExitGracefully; All file streams are opened in WriteOutputFileHeaders() routine
//
void CModel::CloseOutputStreams()
{
for (int c=0;c<_nCustomOutputs;c++){
_pCustomOutputs[c]->CloseFiles();
}
_pTransModel->CloseOutputFiles();
if(_pGWModel!=NULL) {
_pGWModel->CloseOutputFiles();
}
if ( _STORAGE.is_open()){ _STORAGE.close();}
if ( _HYDRO.is_open()){ _HYDRO.close();}
if (_FORCINGS.is_open()){_FORCINGS.close();}
if (_RESSTAGE.is_open()){_RESSTAGE.close();}
if ( _DEMANDS.is_open()){ _DEMANDS.close();}
#ifdef _RVNETCDF_
/* close netcdfs */
int retval; // error value for NetCDF routines
if (_HYDRO_ncid != -9) {retval = nc_close(_HYDRO_ncid); HandleNetCDFErrors(retval); }
_HYDRO_ncid = -9;
if (_STORAGE_ncid != -9) {retval = nc_close(_STORAGE_ncid); HandleNetCDFErrors(retval); }
_STORAGE_ncid = -9;
if (_FORCINGS_ncid != -9) {retval = nc_close(_FORCINGS_ncid); HandleNetCDFErrors(retval); }
_FORCINGS_ncid = -9;
#endif // end compilation if NetCDF library is available
}
//////////////////////////////////////////////////////////////////
/// \brief Write output file headers
/// \details Called prior to simulation (but after initialization) from CModel::Initialize()
/// \param &Options [in] Global model options information
//
void CModel::WriteOutputFileHeaders(const optStruct &Options)
{
int i,j,p;
string tmpFilename;
if(!Options.silent) { cout<<" Writing Output File Headers..."<<endl; }
if (Options.output_format==OUTPUT_STANDARD)
{
//WatershedStorage.csv
//--------------------------------------------------------------
if (Options.write_watershed_storage)
{
tmpFilename=FilenamePrepare("WatershedStorage.csv",Options);
_STORAGE.open(tmpFilename.c_str());
if (_STORAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
_STORAGE<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE],Channel Storage [mm],Reservoir Storage [mm],Rivulet Storage [mm]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i])){
if (i!=iAtmPrecip){
_STORAGE<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
//_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
}
}
}
_STORAGE<<", Total [mm], Cum. Inputs [mm], Cum. Outflow [mm], MB Error [mm]"<<endl;
}
//Hydrographs.csv
//--------------------------------------------------------------
tmpFilename=FilenamePrepare("Hydrographs.csv",Options);
_HYDRO.open(tmpFilename.c_str());
if (_HYDRO.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_HYDRO<<"time,date,hour";
_HYDRO<<",precip [mm/day]";
for (p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && _pSubBasins[p]->IsEnabled()){
string name;
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" [m3/s]";}
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]";}
}
}
}
if (_pSubBasins[p]->GetReservoir() != NULL){
if (_pSubBasins[p]->GetName()==""){_HYDRO<<",ID="<<_pSubBasins[p]->GetID() <<" (res. inflow) [m3/s]";}
else {_HYDRO<<"," <<_pSubBasins[p]->GetName()<<" (res. inflow) [m3/s]";}
}
}
}
_HYDRO<<endl;
}
else if (Options.output_format==OUTPUT_ENSIM)
{
WriteEnsimStandardHeaders(Options);
}
else if (Options.output_format==OUTPUT_NETCDF)
{
WriteNetcdfStandardHeaders(Options); // creates NetCDF files, writes dimensions and creates variables (without writing actual values)
}
//WatershedEnergyStorage.csv
//--------------------------------------------------------------
if (Options.write_energy)
{
ofstream EN_STORAGE;
tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options);
EN_STORAGE.open(tmpFilename.c_str());
if (EN_STORAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
EN_STORAGE<<"time[d],date,hour,temp[C],net incoming [MJ/m2/d]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsEnergyStorage(_aStateVarType[i])){
EN_STORAGE<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [MJ/m2]";
}
}
EN_STORAGE<<", Total [MJ/m2], Cum. In [MJ/m2], Cum. Out [MJ/m2], EB Error [MJ/m2]"<<endl;
EN_STORAGE.close();
}
//ReservoirStages.csv
//--------------------------------------------------------------
if((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE))
{
tmpFilename=FilenamePrepare("ReservoirStages.csv",Options);
_RESSTAGE.open(tmpFilename.c_str());
if(_RESSTAGE.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_RESSTAGE<<"time,date,hour";
_RESSTAGE<<",precip [mm/day]";
for(p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
string name;
if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" "; }
else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" "; }
}
//if (Options.print_obs_hydro)
{
for(i = 0; i < _nObservedTS; i++){
if(IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
if(_pSubBasins[p]->GetName()==""){ _RESSTAGE<<",ID="<<_pSubBasins[p]->GetID() <<" (observed) [m3/s]"; }
else { _RESSTAGE<<"," <<_pSubBasins[p]->GetName()<<" (observed) [m3/s]"; }
}
}
}
}
_RESSTAGE<<endl;
}
//ReservoirStages.csv
//--------------------------------------------------------------
if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE))
{
tmpFilename=FilenamePrepare("Demands.csv",Options);
_DEMANDS.open(tmpFilename.c_str());
if(_DEMANDS.fail()) {
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_DEMANDS<<"time,date,hour";
for(p=0;p<_nSubBasins;p++) {
if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand())) {
string name;
if(_pSubBasins[p]->GetName()=="") { name="ID="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
_DEMANDS<<","<<name<<" [m3/s]";
_DEMANDS<<","<<name<<" (demand) [m3/s]";
_DEMANDS<<","<<name<<" (min.) [m3/s]";
_DEMANDS<<","<<name<<" (unmet) [m3/s]";
}
}
_DEMANDS<<endl;
}
//ReservoirMassBalance.csv
//--------------------------------------------------------------
if ((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE))
{
ofstream RES_MB;
string name;
tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options);
RES_MB.open(tmpFilename.c_str());
if (RES_MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
RES_MB<<"time,date,hour";
RES_MB<<",precip [mm/day]";
for(p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
RES_MB<<"," <<name<<" inflow [m3]";
RES_MB<<"," <<name<<" outflow [m3]";
RES_MB<<"," <<name<<" volume [m3]";
RES_MB<<"," <<name<<" losses [m3]";
RES_MB<<"," <<name<<" MB error [m3]";
RES_MB<<"," <<name<<" constraint";
}
}
RES_MB<<endl;
RES_MB.close();
}
//WatershedMassEnergyBalance.csv
//--------------------------------------------------------------
if (Options.write_mass_bal)
{
ofstream MB;
tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options);
MB.open(tmpFilename.c_str());
if (MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
MB<<"time [d],date,hour";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());
MB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]";
}
}
MB<<endl;
MB<<",,from:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]);
MB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
MB<<endl;
MB<<",,to:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]);
MB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
MB<<endl;
MB.close();
}
//WatershedMassEnergyBalance.csv
//--------------------------------------------------------------
if (Options.write_group_mb!=DOESNT_EXIST)
{
int kk=Options.write_group_mb;
ofstream HGMB;
tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options);
HGMB.open(tmpFilename.c_str());
if (HGMB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
HGMB<<"time [d],date,hour";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
HGMB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());
HGMB<<"["<<CStateVariable::GetStateVarUnits(_aStateVarType[_pProcesses[j]->GetFromIndices()[q]])<<"]";
}
}
HGMB<<endl;
HGMB<<",,from:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetFromIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetFromIndices()[q]);
HGMB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
HGMB<<endl;
HGMB<<",,to:";
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
sv_type typ=GetStateVarType (_pProcesses[j]->GetToIndices()[q]);
int ind=GetStateVarLayer(_pProcesses[j]->GetToIndices()[q]);
HGMB<<","<<CStateVariable::SVTypeToString(typ,ind);
}
}
HGMB<<endl;
HGMB.close();
}
//ExhaustiveMassBalance.csv
//--------------------------------------------------------------
if (Options.write_exhaustiveMB)
{
ofstream MB;
tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options);
MB.open(tmpFilename.c_str());
if (MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
MB<<"time[d],date,hour";
bool first;
for (i=0;i<_nStateVars;i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
MB<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]);
first=true;
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetFromIndices()[q]==i){
if (!first){MB<<",";}first=false;
}
}
}
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetToIndices()[q]==i){
if (!first){MB<<",";}first=false;
}
}
}
for(j=0;j<_nProcesses;j++){
for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if(pProc->GetLateralToIndices()[q]==i){
if(!first){ MB<<","; }first=false;break;
}
if (pProc->GetLateralFromIndices()[q]==i){
if (!first){MB<<",";}first=false;break;
}
}
}
MB<<",,,";//cum, stor, error
}
}
MB<<endl;
MB<<",,";//time,date,hour
for (i=0;i<_nStateVars;i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());}
}
}
for (j=0;j<_nProcesses;j++){
for (int q=0;q<_pProcesses[j]->GetNumConnections();q++){
if (_pProcesses[j]->GetToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());}
}
}
for(j=0;j<_nProcesses;j++){
for(int q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if (pProc->GetLateralToIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;}
if (pProc->GetLateralFromIndices()[q]==i){MB<<","<<GetProcessName(_pProcesses[j]->GetProcessType());break;}
}
}
MB<<",cumulative,storage,error";
}
}
MB<<endl;
MB.close();
}
//ForcingFunctions.csv
//--------------------------------------------------------------
if (Options.write_forcings)
{
tmpFilename=FilenamePrepare("ForcingFunctions.csv",Options);
_FORCINGS.open(tmpFilename.c_str());
if (_FORCINGS.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_FORCINGS<<"time [d],date,hour,day_angle,";
_FORCINGS<<" rain [mm/d], snow [mm/d], temp [C], temp_daily_min [C], temp_daily_max [C],temp_daily_ave [C],temp_monthly_min [C],temp_monthly_max [C],";
_FORCINGS<<" air dens. [kg/m3], air pres. [KPa], rel hum. [-],";
_FORCINGS<<" cloud cover [-],";
_FORCINGS<<" ET radiation [MJ/m2/d], SW radiation [MJ/m2/d], net SW radiation [MJ/m2/d], LW radiation [MJ/m2/d], wind vel. [m/s],";
_FORCINGS<<" PET [mm/d], OW PET [mm/d],";
_FORCINGS<<" daily correction [-], potential melt [mm/d]";
_FORCINGS<<endl;
}
// HRU Storage files
//--------------------------------------------------------------
if (_pOutputGroup!=NULL){
for (int kk=0; kk<_pOutputGroup->GetNumHRUs();kk++)
{
ofstream HRUSTOR;
tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv";
tmpFilename=FilenamePrepare(tmpFilename,Options);
HRUSTOR.open(tmpFilename.c_str());
if (HRUSTOR.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
HRUSTOR<<"time [d],date,hour,rainfall [mm/day],snowfall [mm/d SWE]";
for (i=0;i<GetNumStateVars();i++){
if (CStateVariable::IsWaterStorage(_aStateVarType[i])){
if (i!=iAtmPrecip){
HRUSTOR<<","<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
//HRUSTOR<<","<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i])<<" [mm]";
}
}
}
HRUSTOR<<", Total [mm]"<<endl;
HRUSTOR.close();
}
}
// Custom output files
//--------------------------------------------------------------
for (int c=0;c<_nCustomOutputs;c++)
{
_pCustomOutputs[c]->WriteFileHeader(Options);
}
// Transport output files
//--------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
_pTransModel->WriteOutputFileHeaders(Options);
}
else if (Options.output_format==OUTPUT_ENSIM)
{
_pTransModel->WriteEnsimOutputFileHeaders(Options);
}
// Groundwater output files
//-------------------------------------------------------------
_pGWModel->WriteOutputFileHeaders(Options);
//raven_debug.csv
//--------------------------------------------------------------
if (Options.debug_mode)
{
ofstream DEBUG;
tmpFilename=FilenamePrepare("raven_debug.csv",Options);
DEBUG.open(tmpFilename.c_str());
if (DEBUG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
DEBUG<<"time[d],date,hour,debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10"<<endl;
DEBUG.close();
}
//opens and closes diagnostics.csv so that this warning doesn't show up at end of simulation
//--------------------------------------------------------------
if ((_nObservedTS>0) && (_nDiagnostics>0))
{
ofstream DIAG;
tmpFilename=FilenamePrepare("Diagnostics.csv",Options);
DIAG.open(tmpFilename.c_str());
if(DIAG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
DIAG.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output to file at the end of each timestep (or multiple thereof)
/// \note only thing this modifies should be output streams
/// \param &Options [in] Global model options information
/// \param &tt [in] Local (model) time *at the end of* the pertinent time step
//
void CModel::WriteMinorOutput(const optStruct &Options,const time_struct &tt)
{
int i,iCumPrecip,k;
double output_int = 0.0;
double mod_final = 0.0;
double S,currentWater;
string thisdate;
string thishour;
bool silent=true;
bool quiet=true;
double t;
string tmpFilename;
if ((tt.model_time==0) && (Options.suppressICs)){return;}
//converts the 'write every x timesteps' into a 'write at time y' value
output_int = Options.output_interval * Options.timestep;
mod_final = ffmod(tt.model_time,output_int);
iCumPrecip=GetStateVarIndex(ATMOS_PRECIP);
if(fabs(mod_final) <= 0.5*Options.timestep) //checks to see if sufficiently close to timestep
//(this should account for any roundoff error in timestep calcs)
{
thisdate=tt.date_string; //refers to date and time at END of time step
thishour=DecDaysToHours(tt.julian_day);
t =tt.model_time;
time_struct prev;
JulianConvert(t-Options.timestep,Options.julian_start_day,Options.julian_start_year,Options.calendar,prev); //get start of time step, prev
double usetime=tt.model_time;
string usedate=thisdate;
string usehour=thishour;
if(Options.period_starting){
usedate=prev.date_string;
usehour=DecDaysToHours(prev.julian_day);
usetime=tt.model_time-Options.timestep;
}
// Console output
//----------------------------------------------------------------
if ((quiet) && (!Options.silent) && (tt.day_of_month==1) && ((tt.julian_day)-floor(tt.julian_day+TIME_CORRECTION)<Options.timestep/2))
{
cout<<thisdate <<endl;
}
if(!silent)
{
cout <<thisdate<<" "<<thishour<<":";
if (t!=0){cout <<" | P: "<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<GetAveragePrecip();}
else {cout <<" | P: ------";}
}
//Write current state of water storage in system to WatershedStorage.csv (ALWAYS DONE if not switched OFF)
//----------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
if (Options.write_watershed_storage)
{
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
_STORAGE<<tt.model_time <<","<<thisdate<<","<<thishour; //instantaneous, so thishour rather than usehour used.
if (t!=0){_STORAGE<<","<<precip-snowfall<<","<<snowfall;}//precip
else {_STORAGE<<",---,---";}
_STORAGE<<","<<channel_stor<<","<<reservoir_stor<<","<<rivulet_stor;
currentWater=0.0;
for (i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip))
{
S=GetAvgStateVar(i);
if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;}
_STORAGE<<","<<FormatDouble(S);
currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor+reservoir_stor;
if(t==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
_STORAGE<<","<<currentWater<<","<<_CumulInput<<","<<_CumulOutput<<","<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput));
_STORAGE<<endl;
}
//Write hydrographs for gauged watersheds (ALWAYS DONE)
//----------------------------------------------------------------
if ((Options.ave_hydrograph) && (t!=0.0))
{
_HYDRO<<usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<","<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++)
{
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep); //time shift handled in CTimeSeries::Parse
if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; }
else { _HYDRO << ","; }
}
}
}
if (_pSubBasins[p]->GetReservoir() != NULL){
_HYDRO<<","<<_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
}
}
_HYDRO<<endl;
}
else //point value hydrograph or t==0
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
_HYDRO<<t<<","<<thisdate<<","<<thishour;
if(t!=0){ _HYDRO<<","<<GetAveragePrecip(); }//watershed-wide precip
else { _HYDRO<<",---"; }
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<","<<_pSubBasins[p]->GetOutflowRate();
//if (Options.print_obs_hydro)
{
for(i = 0; i < _nObservedTS; i++){
if(IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep);
if((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _HYDRO << "," << val; }
else { _HYDRO << ","; }
}
}
}
if(_pSubBasins[p]->GetReservoir() != NULL){
_HYDRO<<","<<_pSubBasins[p]->GetReservoirInflow();
}
}
}
_HYDRO<<endl;
}
}
}
else if (Options.output_format==OUTPUT_ENSIM)
{
WriteEnsimMinorOutput(Options,tt);
}
else if (Options.output_format==OUTPUT_NETCDF)
{
WriteNetcdfMinorOutput(Options,tt);
}
//Write cumulative mass balance info to HRUGroup_MassEnergyBalance.csv
//----------------------------------------------------------------
if (Options.write_group_mb!=DOESNT_EXIST)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
double sum;
int kk=Options.write_group_mb;
ofstream HGMB;
tmpFilename=FilenamePrepare(_pHRUGroups[kk]->GetName()+"_MassEnergyBalance.csv",Options);
HGMB.open(tmpFilename.c_str(),ios::app);
HGMB<<usetime<<","<<usedate<<","<<usehour;
double areasum=0.0;
for(k = 0; k < _nHydroUnits; k++){
if(_pHRUGroups[kk]->IsInGroup(k)){
areasum+=_pHydroUnits[k]->GetArea();
}
}
for(int js=0;js<_nTotalConnections;js++)
{
sum=0.0;
for(k = 0; k < _nHydroUnits; k++){
if(_pHRUGroups[kk]->IsInGroup(k)){
sum += _aCumulativeBal[k][js] * _pHydroUnits[k]->GetArea();
}
}
HGMB<<","<<sum/areasum;
}
HGMB<<endl;
HGMB.close();
}
}
//Write cumulative mass balance info to WatershedMassEnergyBalance.csv
//----------------------------------------------------------------
if (Options.write_mass_bal)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
double sum;
ofstream MB;
tmpFilename=FilenamePrepare("WatershedMassEnergyBalance.csv",Options);
MB.open(tmpFilename.c_str(),ios::app);
MB<<usetime<<","<<usedate<<","<<usehour;
for(int js=0;js<_nTotalConnections;js++)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<sum/_WatershedArea;
}
MB<<endl;
MB.close();
}
}
//ReservoirStages.csv
//--------------------------------------------------------------
if ((Options.write_reservoir) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
_RESSTAGE<< t<<","<<thisdate<<","<<thishour<<","<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if ((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
_RESSTAGE<<","<<_pSubBasins[p]->GetReservoir()->GetResStage();
}
//if (Options.print_obs_hydro)
{
for (i = 0; i < _nObservedTS; i++){
if (IsContinuousStageObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(tt.model_time,Options.timestep);
if ((val != RAV_BLANK_DATA) && (tt.model_time>0)){ _RESSTAGE << "," << val; }
else { _RESSTAGE << ","; }
}
}
}
}
_RESSTAGE<<endl;
}
}
//Demands.csv
//----------------------------------------------------------------
if((Options.write_demandfile) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)) {}//don't write anything at time zero
else {
_DEMANDS<< t<<","<<thisdate<<","<<thishour;
for(int p=0;p<_nSubBasins;p++) {
if((_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->HasIrrigationDemand()))
{
double irr =_pSubBasins[p]->GetIrrigationDemand(tt.model_time);
double eF =_pSubBasins[p]->GetEnviroMinFlow (tt.model_time);
double Q =_pSubBasins[p]->GetOutflowRate (); //AFTER irrigation removed
double Qirr=_pSubBasins[p]->GetIrrigationRate ();
double unmet=max(irr-Qirr,0.0);
_DEMANDS<<","<<Q<<","<<irr<<","<<eF<<","<<unmet;
}
}
_DEMANDS<<endl;
}
}
//ReservoirMassBalance.csv
//----------------------------------------------------------------
if((Options.write_reservoirMB) && (Options.output_format!=OUTPUT_NONE))
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
ofstream RES_MB;
tmpFilename=FilenamePrepare("ReservoirMassBalance.csv",Options);
RES_MB.open(tmpFilename.c_str(),ios::app);
if(RES_MB.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
RES_MB<< usetime<<","<<usedate<<","<<usehour<<","<<GetAveragePrecip();
double in,out,loss,stor,oldstor;
for(int p=0;p<_nSubBasins;p++){
if((_pSubBasins[p]->IsGauged()) && (_pSubBasins[p]->IsEnabled()) && (_pSubBasins[p]->GetReservoir()!=NULL)) {
string name,constraint_str;
if(_pSubBasins[p]->GetName()==""){ name=to_string(_pSubBasins[p]->GetID())+"="+to_string(_pSubBasins[p]->GetID()); }
else { name=_pSubBasins[p]->GetName(); }
in =_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep);//m3
out =_pSubBasins[p]->GetIntegratedOutflow(Options.timestep);//m3
stor =_pSubBasins[p]->GetReservoir()->GetStorage();//m3
oldstor=_pSubBasins[p]->GetReservoir()->GetOldStorage();//m3
loss =_pSubBasins[p]->GetReservoir()->GetReservoirLosses(Options.timestep);//m3
constraint_str=_pSubBasins[p]->GetReservoir()->GetCurrentConstraint();
if(tt.model_time==0.0){ in=0.0; }
RES_MB<<","<<in<<","<<out<<","<<stor<<","<<loss<<","<<in-out-loss-(stor-oldstor)<<","<<constraint_str;
}
}
RES_MB<<endl;
RES_MB.close();
}
}
// WatershedEnergyStorage.csv
//----------------------------------------------------------------
double sum=0.0;
if (Options.write_energy)
{
force_struct F=GetAverageForcings();
ofstream EN_STORAGE;
tmpFilename=FilenamePrepare("WatershedEnergyStorage.csv",Options);
EN_STORAGE.open(tmpFilename.c_str(),ios::app);
EN_STORAGE<<t<<","<<thisdate<<","<<thishour;
EN_STORAGE<<","<<F.temp_ave;
EN_STORAGE<<",TMP_DEBUG";
// STOR<<","<<GetAverageNetRadiation();//TMP DEBUG
for (i=0;i<GetNumStateVars();i++)
{
if (CStateVariable::IsEnergyStorage(_aStateVarType[i]))
{
S=GetAvgStateVar(i);
if (!silent){cout<<" |"<< setw(6)<<setiosflags(ios::fixed) << setprecision(2)<<S;}
EN_STORAGE<<","<<S;
sum+=S;
}
}
EN_STORAGE<<","<<sum<<","<<_CumEnergyGain<<","<<_CumEnergyLoss<<","<<_CumEnergyGain-sum-_CumEnergyLoss;
EN_STORAGE<<endl;
EN_STORAGE.close();
}
if (!silent){cout<<endl;}
// ExhaustiveMassBalance.csv
//--------------------------------------------------------------
if (Options.write_exhaustiveMB)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
int j,js,q;
double cumsum;
ofstream MB;
tmpFilename=FilenamePrepare("ExhaustiveMassBalance.csv",Options);
MB.open(tmpFilename.c_str(),ios::app);
MB<<usetime<<","<<usedate<<","<<usehour;
for(i=0;i<_nStateVars;i++)
{
if(CStateVariable::IsWaterStorage(_aStateVarType[i]))
{
cumsum=0.0;
js=0;
for(j=0;j<_nProcesses;j++){
for(q=0;q<_pProcesses[j]->GetNumConnections();q++){
if(_pProcesses[j]->GetFromIndices()[q]==i)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<-sum/_WatershedArea;
cumsum-=sum/_WatershedArea;
}
js++;
}
}
js=0;
for(j=0;j<_nProcesses;j++){
for(q=0;q<_pProcesses[j]->GetNumConnections();q++){
if(_pProcesses[j]->GetToIndices()[q]==i)
{
sum=0.0;
for(k=0;k<_nHydroUnits;k++){
if(_pHydroUnits[k]->IsEnabled())
{
sum+=_aCumulativeBal[k][js]*_pHydroUnits[k]->GetArea();
}
}
MB<<","<<sum/_WatershedArea;
cumsum+=sum/_WatershedArea;
}
js++;
}
}
js=0;
bool found;
for(j=0;j<_nProcesses;j++){
sum=0;
found=false;
for(q=0;q<_pProcesses[j]->GetNumLatConnections();q++){
CLateralExchangeProcessABC *pProc=static_cast<CLateralExchangeProcessABC *>(_pProcesses[j]);
if (pProc->GetLateralToIndices()[q]==i){
sum+=_aCumulativeLatBal[js];found=true;
}
if (pProc->GetLateralFromIndices()[q]==i){
sum-=_aCumulativeLatBal[js];found=true;
}
js++;
}
if((_pProcesses[j]->GetNumLatConnections()>0) && (found==true)){
MB<<","<<sum/_WatershedArea;
cumsum+=sum/_WatershedArea;
}
}
//Cumulative, storage, error
double Initial_i=0.0; //< \todo [bug] need to evaluate and store initial storage actross watershed!!!
MB<<","<<cumsum<<","<<GetAvgStateVar(i)<<","<<cumsum-GetAvgStateVar(i)-Initial_i;
}
}
MB<<endl;
MB.close();
}
}
// ForcingFunctions.csv
//----------------------------------------------------------------
if (Options.write_forcings)
{
if((Options.period_starting) && (t==0)){}//don't write anything at time zero
else{
force_struct *pFave;
force_struct faveStruct = GetAverageForcings();
pFave = &faveStruct;
_FORCINGS<<usetime<<","<<usedate<<","<<usehour<<",";
_FORCINGS<<pFave->day_angle<<",";
_FORCINGS<<pFave->precip*(1-pFave->snow_frac) <<",";
_FORCINGS<<pFave->precip*(pFave->snow_frac) <<",";
_FORCINGS<<pFave->temp_ave<<",";
_FORCINGS<<pFave->temp_daily_min<<",";
_FORCINGS<<pFave->temp_daily_max<<",";
_FORCINGS<<pFave->temp_daily_ave<<",";
_FORCINGS<<pFave->temp_month_min<<",";
_FORCINGS<<pFave->temp_month_max<<",";
_FORCINGS<<pFave->air_dens<<",";
_FORCINGS<<pFave->air_pres<<",";
_FORCINGS<<pFave->rel_humidity<<",";
_FORCINGS<<pFave->cloud_cover<<",";
_FORCINGS<<pFave->ET_radia<<",";
_FORCINGS<<pFave->SW_radia<<",";
_FORCINGS<<pFave->SW_radia_net<<",";
//_FORCINGS<<pFave->LW_incoming<<",";
_FORCINGS<<pFave->LW_radia_net<<",";
_FORCINGS<<pFave->wind_vel<<",";
_FORCINGS<<pFave->PET<<",";
_FORCINGS<<pFave->OW_PET<<",";
_FORCINGS<<pFave->subdaily_corr<<",";
_FORCINGS<<pFave->potential_melt;
_FORCINGS<<endl;
}
}
// Transport output files
//--------------------------------------------------------------
if (Options.output_format==OUTPUT_STANDARD)
{
_pTransModel->WriteMinorOutput(Options,tt);
}
else if (Options.output_format==OUTPUT_ENSIM)
{
_pTransModel->WriteEnsimMinorOutput(Options,tt);
}
// Groundwater output files
//--------------------------------------------------------------
_pGWModel->WriteMinorOutput(Options,tt);
// raven_debug.csv
//--------------------------------------------------------------
if (Options.debug_mode)
{
ofstream DEBUG;
tmpFilename=FilenamePrepare("raven_debug.csv",Options);
DEBUG.open(tmpFilename.c_str(),ios::app);
DEBUG<<t<<","<<thisdate<<","<<thishour;
for(i=0;i<10;i++){DEBUG<<","<<g_debug_vars[i];}
DEBUG<<endl;
DEBUG.close();
}
// HRU storage output
//--------------------------------------------------------------
if (_pOutputGroup!=NULL)
{
for (int kk=0;kk<_pOutputGroup->GetNumHRUs();kk++)
{
ofstream HRUSTOR;
tmpFilename="HRUStorage_"+to_string(_pOutputGroup->GetHRU(kk)->GetID())+".csv";
tmpFilename=FilenamePrepare(tmpFilename,Options);
HRUSTOR.open(tmpFilename.c_str(),ios::app);
const force_struct *F=_pOutputGroup->GetHRU(kk)->GetForcingFunctions();
HRUSTOR<<tt.model_time <<","<<thisdate<<","<<thishour;//instantaneous -no period starting correction
if (t!=0){HRUSTOR<<","<<F->precip*(1-F->snow_frac)<<","<<F->precip*(F->snow_frac);}//precip
else {HRUSTOR<<",---,---";}
currentWater=0;
for (i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip))
{
S=_pOutputGroup->GetHRU(kk)->GetStateVarValue(i);
HRUSTOR<<","<<S;
currentWater+=S;
}
}
HRUSTOR<<","<<currentWater;
HRUSTOR<<endl;
HRUSTOR.close();
}
}
} // end of write output interval if statement
// Custom output files
//--------------------------------------------------------------
for (int c=0;c<_nCustomOutputs;c++)
{
_pCustomOutputs[c]->WriteCustomOutput(tt,Options);
}
// Write major output, if necessary
//--------------------------------------------------------------
if ((_nOutputTimes>0) && (tt.model_time>_aOutputTimes[_currOutputTimeInd]-0.5*Options.timestep))
{
_currOutputTimeInd++;
tmpFilename="state_"+tt.date_string;
WriteMajorOutput(tmpFilename,Options,tt,false);
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes major output to file at the end of simulation
/// \details Writes:
/// - Solution file of all state variables; and
/// - Autogenerated parameters
///
/// \param &Options [in] Global model options information
//
void CModel::WriteMajorOutput(string solfile, const optStruct &Options, const time_struct &tt, bool final) const
{
int i,k;
string tmpFilename;
// WRITE {RunName}_solution.rvc - final state variables file
ofstream OUT;
tmpFilename=FilenamePrepare(solfile+".rvc",Options);
OUT.open(tmpFilename.c_str());
if (OUT.fail()){
WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy);
}
OUT<<":TimeStamp "<<tt.date_string<<" "<<DecDaysToHours(tt.julian_day)<<endl;
//Header--------------------------
OUT<<":HRUStateVariableTable"<<endl;
OUT<<" :Attributes,";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<CStateVariable::SVTypeToString(_aStateVarType[i],_aStateVarLayer[i]);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
OUT<<" :Units,";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<CStateVariable::GetStateVarUnits(_aStateVarType[i]);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
//Data----------------------------
for (k=0;k<_nHydroUnits;k++)
{
OUT<<std::fixed; OUT.precision(5);
OUT<<" "<<_pHydroUnits[k]->GetID()<<",";
for (i=0;i<GetNumStateVars();i++)
{
OUT<<_pHydroUnits[k]->GetStateVarValue(i);
if (i!=GetNumStateVars()-1){OUT<<",";}
}
OUT<<endl;
}
OUT<<":EndHRUStateVariableTable"<<endl;
//By basin------------------------
OUT<<":BasinStateVariables"<<endl;
for (int p=0;p<_nSubBasins;p++){
OUT<<" :BasinIndex "<<_pSubBasins[p]->GetID()<<",";
_pSubBasins[p]->WriteToSolutionFile(OUT);
}
OUT<<":EndBasinStateVariables"<<endl;
OUT.close();
if(Options.write_channels){
CChannelXSect::WriteRatingCurves();
}
if(Options.write_basinfile) {
ofstream BASIN;
tmpFilename=FilenamePrepare("SubbasinParams.csv",Options);
BASIN.open(tmpFilename.c_str());
if(BASIN.fail()) {
WriteWarning(("CModel::WriteMajorOutput: Unable to open output file "+tmpFilename+" for writing.").c_str(),Options.noisy);
}
BASIN<<"SBID,Reference Discharge [m3/s],Reach Length [m],Reach Celerity [m/s],Reach Diffusivity [m2/s]"<<endl;
for(int p=0;p<_nSubBasins;p++) {
BASIN<<_pSubBasins[p]->GetID()<<","<<_pSubBasins[p]->GetReferenceFlow()<<","<<_pSubBasins[p]->GetReachLength()<<",";
BASIN<<_pSubBasins[p]->GetReferenceCelerity()<<","<<_pSubBasins[p]->GetDiffusivity()<<endl;
}
BASIN.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes progress file in JSON format (mainly for PAVICS runs)
/// Looks like:
/// {
/// "% progress": 65,
/// "seconds remaining": 123
/// }
///
/// \note Does not account for initialization (reading) and final writing of model outputs. Only pure modeling time.
///
/// \param &Options [in] Global model options information
/// \param &elapsed_time [in] elapsed time (computational time markers)
/// \param elapsed_steps [in] elapsed number of simulation steps to perform (to determine % progress)
/// \param total_steps [in] total number of simulation steps to perform (to determine % progress)
//
void CModel::WriteProgressOutput(const optStruct &Options, clock_t elapsed_time, int elapsed_steps, int total_steps)
{
if (Options.pavics)
{
ofstream PROGRESS;
PROGRESS.open((Options.main_output_dir+"Raven_progress.txt").c_str());
if (PROGRESS.fail()){
PROGRESS.close();
ExitGracefully("ParseInput:: Unable to open Raven_progress.txt. Bad output directory specified?",RUNTIME_ERR);
}
float total_time = (float(total_steps) * float(elapsed_time) / float(elapsed_steps)) / CLOCKS_PER_SEC;
if (Options.benchmarking){ total_time =float(elapsed_time);}
PROGRESS<<"{"<<endl;
PROGRESS<<" \"% progress\": " << int( float(elapsed_steps) * 100.0 / float(total_steps) ) <<","<< endl;
PROGRESS<<" \"seconds remaining\": "<< total_time - float(elapsed_time) / CLOCKS_PER_SEC <<endl;
PROGRESS<<"}"<<endl;
PROGRESS.close();
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes model summary information to screen
/// \param &Options [in] Global model options information
//
void CModel::SummarizeToScreen (const optStruct &Options) const
{
int rescount=0;
for (int p = 0; p < _nSubBasins; p++){
if (_pSubBasins[p]->GetReservoir() != NULL){rescount++;}
}
int disablecount=0;
double allarea=0.0;
for(int k=0;k<_nHydroUnits; k++){
if(!_pHydroUnits[k]->IsEnabled()){disablecount++;}
allarea+=_pHydroUnits[k]->GetArea();
}
int SBdisablecount=0;
for(int p=0;p<_nSubBasins; p++){
if(!_pSubBasins[p]->IsEnabled()){SBdisablecount++;}
}
if(!Options.silent){
cout <<"==MODEL SUMMARY======================================="<<endl;
cout <<" Model Run: "<<Options.run_name <<endl;
cout <<" rvi filename: "<<Options.rvi_filename<<endl;
cout <<"Output Directory: "<<Options.main_output_dir <<endl;
cout <<" # SubBasins: "<<GetNumSubBasins() << " ("<< rescount << " reservoirs) ("<<SBdisablecount<<" disabled)"<<endl;
cout <<" # HRUs: "<<GetNumHRUs() << " ("<<disablecount<<" disabled)"<<endl;
cout <<" # Gauges: "<<GetNumGauges() <<endl;
cout <<"#State Variables: "<<GetNumStateVars() <<endl;
for (int i=0;i<GetNumStateVars();i++){
//don't write if convolution storage or advection storage?
cout<<" - ";
cout<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<" (";
cout<<CStateVariable::SVTypeToString (_aStateVarType[i],_aStateVarLayer[i])<<")"<<endl;
}
cout <<" # Processes: "<<GetNumProcesses() <<endl;
for (int j=0;j<GetNumProcesses();j++)
{
cout<<" - ";
cout<<GetProcessName(GetProcessType(j))<<endl;
}
cout <<" #Connections: "<<_nTotalConnections <<endl;
cout <<"#Lat.Connections: "<<_nTotalLatConnections <<endl;
cout <<" Duration: "<<Options.duration <<" d"<<endl;
cout <<" Time step: "<<Options.timestep <<" d"<<endl;
cout <<" Watershed Area: "<<_WatershedArea <<" km2 (simulated) of "<<allarea<<" km2"<<endl;
cout <<"======================================================"<<endl;
cout <<endl;
if((Options.modeltype == MODELTYPE_COUPLED) || (Options.modeltype == MODELTYPE_GROUNDWATER))
{
cout <<"==GROUNDWATER SUMMARY================================"<<endl;
//CAquiferStack::SummarizeToScreen();
CGWGeometryClass::SummarizeToScreen();
CGWStressPeriodClass::SummarizeToScreen();
COverlapExchangeClass::SummarizeToScreen();
cout <<"====================================================="<<endl;
}
}
}
//////////////////////////////////////////////////////////////////
/// \brief run model diagnostics (at end of simulation)
///
/// \param &Options [in] global model options
//
void CModel::RunDiagnostics (const optStruct &Options)
{
if ((_nObservedTS==0) || (_nDiagnostics==0)) {return;}
ofstream DIAG;
string tmpFilename;
tmpFilename=FilenamePrepare("Diagnostics.csv",Options);
DIAG.open(tmpFilename.c_str());
if (DIAG.fail()){
ExitGracefully(("CModel::WriteOutputFileHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
//header
DIAG<<"observed data series,filename,";
for (int j=0; j<_nDiagnostics;j++){
DIAG<<_pDiagnostics[j]->GetName()<<",";
}
DIAG<<endl;
//body
for (int i=0;i<_nObservedTS;i++)
{
DIAG<<_pObservedTS[i]->GetName()<<","<<_pObservedTS[i]->GetSourceFile() <<",";
for (int j=0; j<_nDiagnostics;j++){
DIAG<<_pDiagnostics[j]->CalculateDiagnostic(_pModeledTS[i],_pObservedTS[i],_pObsWeightTS[i],Options)<<",";
}
DIAG<<endl;
}
DIAG.close();
}
//////////////////////////////////////////////////////////////////
/// \brief Writes output headers for WatershedStorage.tb0 and Hydrographs.tb0
///
/// \param &Options [in] global model options
//
void CModel::WriteEnsimStandardHeaders(const optStruct &Options)
{
int i;
time_struct tt, tt2;
JulianConvert(0.0, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt);//start of the timestep
JulianConvert(Options.timestep, Options.julian_start_day, Options.julian_start_year, Options.calendar, tt2);//end of the timestep
//WatershedStorage.tb0
//--------------------------------------------------------------
int iAtmPrecip = GetStateVarIndex(ATMOS_PRECIP);
string tmpFilename;
if (Options.write_watershed_storage)
{
tmpFilename = FilenamePrepare("WatershedStorage.tb0", Options);
_STORAGE.open(tmpFilename.c_str());
if (_STORAGE.fail()){
ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_STORAGE << "#########################################################################" << endl;
_STORAGE << ":FileType tb0 ASCII EnSim 1.0" << endl;
_STORAGE << "#" << endl;
_STORAGE << ":Application Raven" << endl;
if(!Options.benchmarking){
_STORAGE << ":Version " << Options.version << endl;
_STORAGE << ":CreationDate " << GetCurrentTime() << endl;
}
_STORAGE << "#" << endl;
_STORAGE << "#------------------------------------------------------------------------" << endl;
_STORAGE << "#" << endl;
_STORAGE << ":RunName " << Options.run_name << endl;
_STORAGE << ":Format Instantaneous" << endl;
_STORAGE << "#" << endl;
if (Options.suppressICs){
_STORAGE << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl;
}
else{
_STORAGE << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl;
}
if (Options.timestep != 1.0){ _STORAGE << ":DeltaT " << DecDaysToHours(Options.timestep) << endl; }
else { _STORAGE << ":DeltaT 24:00:00.00" << endl; }
_STORAGE << "#" << endl;
_STORAGE<<":ColumnMetaData"<<endl;
_STORAGE<<" :ColumnName rainfall snowfall \"Channel storage\" \"Rivulet storage\"";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){
_STORAGE<<" \""<<CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i])<<"\"";}}
_STORAGE<<" \"Total storage\" \"Cum. precip\" \"Cum. outflow\" \"MB error\""<<endl;
_STORAGE<<" :ColumnUnits mm/d mm/d mm mm ";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" mm";}}
_STORAGE<<" mm mm mm mm"<<endl;
_STORAGE<<" :ColumnType float float float float";
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){_STORAGE<<" float";}}
_STORAGE<<" float float float float"<<endl;
_STORAGE << " :ColumnFormat -1 -1 0 0";
for (i = 0; i < GetNumStateVars(); i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i != iAtmPrecip)){
_STORAGE << " 0";
}
}
_STORAGE << " 0 0 0 0" << endl;
_STORAGE << ":EndColumnMetaData" << endl;
_STORAGE << ":EndHeader" << endl;
}
//Hydrographs.tb0
//--------------------------------------------------------------
tmpFilename = FilenamePrepare("Hydrographs.tb0", Options);
_HYDRO.open(tmpFilename.c_str());
if (_HYDRO.fail()){
ExitGracefully(("CModel::WriteEnsimStandardHeaders: Unable to open output file "+tmpFilename+" for writing.").c_str(),FILE_OPEN_ERR);
}
_HYDRO << "#########################################################################" << endl;
_HYDRO << ":FileType tb0 ASCII EnSim 1.0" << endl;
_HYDRO << "#" << endl;
_HYDRO << ":Application Raven" << endl;
if(!Options.benchmarking){
_HYDRO << ":Version " << Options.version << endl;
_HYDRO << ":CreationDate " << GetCurrentTime() << endl;
}
_HYDRO << "#" << endl;
_HYDRO << "#------------------------------------------------------------------------" << endl;
_HYDRO << "#" << endl;
_HYDRO << ":RunName " << Options.run_name << endl;
_HYDRO << "#" << endl;
if (Options.ave_hydrograph){
_HYDRO << ":Format PeriodEnding" << endl;
}
else{
_HYDRO << ":Format Instantaneous" << endl;
}
if (((Options.period_ending) && (Options.ave_hydrograph)) || (Options.suppressICs )){
_HYDRO << ":StartTime " << tt2.date_string << " " << DecDaysToHours(tt2.julian_day) << endl;
}
else{
_HYDRO << ":StartTime " << tt.date_string << " " << DecDaysToHours(tt.julian_day) << endl;
}
if (Options.timestep!=1.0){_HYDRO<<":DeltaT " <<DecDaysToHours(Options.timestep)<<endl;}
else {_HYDRO<<":DeltaT 24:00:00.00" <<endl;}
_HYDRO<<"#"<<endl;
double val = 0; //snapshot hydrograph
double val2=1;
if (Options.ave_hydrograph){ val = 1; } //continuous hydrograph
if (Options.period_ending) { val *= -1; val2*=-1;}//period ending
_HYDRO<<":ColumnMetaData"<<endl;
_HYDRO<<" :ColumnName precip";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" Q_"<<_pSubBasins[p]->GetID();}_HYDRO<<endl;
_HYDRO<<" :ColumnUnits mm/d";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" m3/s";}_HYDRO<<endl;
_HYDRO<<" :ColumnType float";
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" float";}_HYDRO<<endl;
_HYDRO<<" :ColumnFormat "<<val2;
for (int p=0;p<_nSubBasins;p++){_HYDRO<<" "<<val;}_HYDRO<<endl;
_HYDRO<<":EndColumnMetaData"<<endl;
_HYDRO<<":EndHeader"<<endl;
}
//////////////////////////////////////////////////////////////////
/// \brief Writes output headers for WatershedStorage.nc and Hydrographs.nc
///
/// \param &Options [in] global model options
/// original code developed by J. Mai
//
void CModel::WriteNetcdfStandardHeaders(const optStruct &Options)
{
#ifdef _RVNETCDF_
time_struct tt; // start time structure
const int ndims1 = 1;
const int ndims2 = 2;
int dimids1[ndims1]; // array which will contain all dimension ids for a variable
int ncid, varid_pre; // When we create netCDF variables and dimensions, we get back an ID for each one.
int time_dimid, varid_time; // dimension ID (holds number of time steps) and variable ID (holds time values) for time
int nSim, nbasins_dimid, varid_bsim; // # of sub-basins with simulated outflow, dimension ID, and
// // variable to write basin IDs for simulated outflows
int varid_qsim; // variable ID for simulated outflows
int varid_qobs; // variable ID for observed outflows
int varid_qin; // variable ID for observed inflows
int retval; // error value for NetCDF routines
string tmpFilename;
int ibasin, p; // loop over all sub-basins
size_t start[1], count[1]; // determines where and how much will be written to NetCDF
const char *current_basin_name[1]; // current time in days since start time
string tmp,tmp2,tmp3;
// initialize all potential file IDs with -9 == "not existing and hence not opened"
_HYDRO_ncid = -9; // output file ID for Hydrographs.nc (-9 --> not opened)
_STORAGE_ncid = -9; // output file ID for WatershedStorage.nc (-9 --> not opened)
_FORCINGS_ncid = -9; // output file ID for ForcingFunctions.nc (-9 --> not opened)
//converts start day into "days since YYYY-MM-DD HH:MM:SS" (model start time)
char starttime[200]; // start time string in format 'days since YYY-MM-DD HH:MM:SS'
JulianConvert( 0.0,Options.julian_start_day, Options.julian_start_year, Options.calendar, tt);
strcpy(starttime, "days since ") ;
strcat(starttime, tt.date_string.c_str()) ;
strcat(starttime, " ");
strcat(starttime, DecDaysToHours(tt.julian_day,true).c_str());
if(Options.time_zone!=0) { strcat(starttime,TimeZoneToString(Options.time_zone).c_str()); }
//====================================================================
// Hydrographs.nc
//====================================================================
// Create the file.
tmpFilename = FilenamePrepare("Hydrographs.nc", Options);
retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval);
_HYDRO_ncid = ncid;
// ----------------------------------------------------------
// global attributes
// ----------------------------------------------------------
WriteNetCDFGlobalAttributes(_HYDRO_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time
// ----------------------------------------------------------
// (a) Define the DIMENSIONS. NetCDF will hand back an ID
retval = nc_def_dim(_HYDRO_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval);
/// Define the time variable. Assign units attributes to the netCDF VARIABLES.
dimids1[0] = time_dimid;
retval = nc_def_var(_HYDRO_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_time, "standard_name", strlen("time"), "time"); HandleNetCDFErrors(retval);
// define precipitation variable
varid_pre= NetCDFAddMetadata(_HYDRO_ncid, time_dimid,"precip","Precipitation","mm d**-1");
// ----------------------------------------------------------
// simulated/observed outflows
// ----------------------------------------------------------
// (a) count number of simulated outflows "nSim"
nSim = 0;
for (p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;}
}
if (nSim > 0)
{
// (b) create dimension "nbasins"
retval = nc_def_dim(_HYDRO_ncid, "nbasins", nSim, &nbasins_dimid); HandleNetCDFErrors(retval);
// (c) create variable and set attributes for"basin_name"
dimids1[0] = nbasins_dimid;
retval = nc_def_var(_HYDRO_ncid, "basin_name", NC_STRING, ndims1, dimids1, &varid_bsim); HandleNetCDFErrors(retval);
tmp ="Name/ID of sub-basins with simulated outflows";
tmp2="timeseries_id";
tmp3="1";
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "long_name", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "cf_role" , tmp2.length(),tmp2.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_HYDRO_ncid, varid_bsim, "units" , tmp3.length(),tmp3.c_str()); HandleNetCDFErrors(retval);
varid_qsim= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_sim","Simulated outflows","m**3 s**-1");
varid_qobs= NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_obs","Observed outflows" ,"m**3 s**-1");
varid_qin = NetCDFAddMetadata2D(_HYDRO_ncid, time_dimid,nbasins_dimid,"q_in" ,"Observed inflows" ,"m**3 s**-1");
}// end if nSim>0
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_HYDRO_ncid); HandleNetCDFErrors(retval);
// write values to NetCDF
// (a) write gauged basin names/IDs to variable "basin_name"
ibasin = 0;
for(p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
if(_pSubBasins[p]->GetName()==""){ current_basin_name[0] = (to_string(_pSubBasins[p]->GetID())).c_str(); }
else { current_basin_name[0] = (_pSubBasins[p]->GetName()).c_str(); }
// write sub-basin name
start[0] = ibasin;
count[0] = 1;
retval = nc_put_vara_string(_HYDRO_ncid,varid_bsim,start,count,¤t_basin_name[0]); HandleNetCDFErrors(retval);
ibasin++;
}
}
//====================================================================
// WatershedStorage.nc
//====================================================================
if (Options.write_watershed_storage)
{
tmpFilename = FilenamePrepare("WatershedStorage.nc", Options);
retval = nc_create(tmpFilename.c_str(), NC_CLOBBER|NC_NETCDF4, &ncid); HandleNetCDFErrors(retval);
_STORAGE_ncid = ncid;
// ----------------------------------------------------------
// global attributes
// ----------------------------------------------------------
WriteNetCDFGlobalAttributes(_STORAGE_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time vector
// ----------------------------------------------------------
// Define the DIMENSIONS. NetCDF will hand back an ID
retval = nc_def_dim(_STORAGE_ncid, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval);
/// Define the time variable.
dimids1[0] = time_dimid;
retval = nc_def_var(_STORAGE_ncid, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_STORAGE_ncid, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_STORAGE_ncid, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval);
// ----------------------------------------------------------
// precipitation / channel storage / state vars / MB diagnostics
// ----------------------------------------------------------
int varid;
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"rainfall","rainfall","mm d**-1");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"snowfall","snowfall","mm d**-1");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Channel Storage","Channel Storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Reservoir Storage","Reservoir Storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Rivulet Storage","Rivulet Storage","mm");
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
for(int i=0;i<_nStateVars;i++){
if((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip)){
string name =CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]);
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,name,name,"mm");
}
}
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Total","total water storage","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Input","cumulative water input","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"Cum. Outflow","cumulative water output","mm");
varid= NetCDFAddMetadata(_STORAGE_ncid, time_dimid,"MB Error","mass balance error","mm");
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_STORAGE_ncid); HandleNetCDFErrors(retval);
}
//====================================================================
// ForcingFunctions.nc
//====================================================================
if(Options.write_forcings)
{
tmpFilename = FilenamePrepare("ForcingFunctions.nc",Options);
retval = nc_create(tmpFilename.c_str(),NC_CLOBBER|NC_NETCDF4,&ncid); HandleNetCDFErrors(retval);
_FORCINGS_ncid = ncid;
WriteNetCDFGlobalAttributes(_FORCINGS_ncid,Options,"Standard Output");
// ----------------------------------------------------------
// time vector
// ----------------------------------------------------------
retval = nc_def_dim(_FORCINGS_ncid,"time",NC_UNLIMITED,&time_dimid); HandleNetCDFErrors(retval);
dimids1[0] = time_dimid;
retval = nc_def_var(_FORCINGS_ncid,"time",NC_DOUBLE,ndims1,dimids1,&varid_time); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"units",strlen(starttime),starttime); HandleNetCDFErrors(retval);
retval = nc_put_att_text(_FORCINGS_ncid,varid_time,"calendar",strlen("gregorian"),"gregorian"); HandleNetCDFErrors(retval);
// ----------------------------------------------------------
int varid;
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"rainfall","rainfall","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"snowfall","snowfall","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp","temp","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_min","temp_daily_min","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_max","temp_daily_max","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"temp_daily_ave","temp_daily_ave","C");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air density","air density","kg m**-3");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"air pressure","air pressure","kPa");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"relative humidity","relative humidity","");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"cloud cover","cloud cover","");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"ET radiation","ET radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"SW radiation","SW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"net SW radiation","net SW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"LW radiation","LW radiation","MJ m**-2 d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"wind velocity","wind velocity","m s**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"PET","PET","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"OW PET","OW PET","mm d**-1");
varid= NetCDFAddMetadata(_FORCINGS_ncid,time_dimid,"potential melt","potential melt","mm d**-1");
// End define mode. This tells netCDF we are done defining metadata.
retval = nc_enddef(_FORCINGS_ncid); HandleNetCDFErrors(retval);
}
#endif // end compilation if NetCDF library is available
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output data to WatershedStorage.tb0 and Hydrographs.tb0
///
/// \param &Options [in] global model options
/// \param &tt [in] current time structure
/// \todo [reorg] merge with WriteMinorOutput - too much complex code repetition here when only difference is (1) delimeter and (2) timestep info included in the .csv file
//
void CModel::WriteEnsimMinorOutput (const optStruct &Options,
const time_struct &tt)
{
double currentWater;
double S;
int i;
int iCumPrecip=GetStateVarIndex(ATMOS_PRECIP);
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
if ((tt.model_time==0) && (Options.suppressICs==true) && (Options.period_ending)){return;}
//----------------------------------------------------------------
// write watershed state variables (WatershedStorage.tb0)
if (Options.write_watershed_storage)
{
if (tt.model_time!=0){_STORAGE<<" "<<precip-snowfall<<" "<<snowfall;}//precip
else {_STORAGE<<" 0.0 0.0";}
_STORAGE<<" "<<channel_stor+reservoir_stor<<" "<<rivulet_stor;
currentWater=0.0;
for (i=0;i<GetNumStateVars();i++){
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iCumPrecip)){
S=GetAvgStateVar(i);_STORAGE<<" "<<FormatDouble(S);currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor;
if(tt.model_time==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
_STORAGE<<" "<<currentWater<<" "<<_CumulInput<<" "<<_CumulOutput<<" "<<FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput));
_STORAGE<<endl;
}
//----------------------------------------------------------------
//Write hydrographs for gauged watersheds (ALWAYS DONE) (Hydrographs.tb0)
if ((Options.ave_hydrograph) && (tt.model_time!=0))
{
_HYDRO<<" "<<GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<" "<<_pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
}
_HYDRO<<endl;
}
else
{
if (tt.model_time!=0){_HYDRO<<" "<<GetAveragePrecip();}
else {_HYDRO<<" 0.0";}
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled()))
{
_HYDRO<<" "<<_pSubBasins[p]->GetOutflowRate();
}
}
_HYDRO<<endl;
}
}
//////////////////////////////////////////////////////////////////
/// \brief Writes minor output data to WatershedStorage.nc and Hydrographs.nc
///
/// \param &Options [in] global model options
/// \param &tt [in] current time structure
//
void CModel::WriteNetcdfMinorOutput ( const optStruct &Options,
const time_struct &tt)
{
#ifdef _RVNETCDF_
int retval; // error value for NetCDF routines
int time_id; // variable id in NetCDF for time
size_t time_index[1], count1[1]; // determines where and how much will be written to NetCDF; 1D variable (pre, time)
size_t start2[2], count2[2]; // determines where and how much will be written to NetCDF; 2D variable (qsim, qobs, qin)
double current_time[1]; // current time in days since start time
double current_prec[1]; // precipitation of current time step
size_t time_ind2;
current_time[0] = tt.model_time;
time_index [0] = int(round(tt.model_time/Options.timestep)); // element of NetCDF array that will be written
time_ind2 =int(round(tt.model_time/Options.timestep));
count1[0] = 1; // writes exactly one time step
//====================================================================
// Hydrographs.nc
//====================================================================
int precip_id; // variable id in NetCDF for precipitation
int qsim_id; // variable id in NetCDF for simulated outflow
int qobs_id; // variable id in NetCDF for observed outflow
int qin_id; // variable id in NetCDF for observed inflow
// (a) count how many values need to be written for q_obs, q_sim, q_in
int iSim, nSim; // current and total # of sub-basins with simulated outflows
nSim = 0;
for (int p=0;p<_nSubBasins;p++){
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){nSim++;}
}
// (b) allocate memory if necessary
double *outflow_obs=NULL; // q_obs
double *outflow_sim=NULL; // q_sim
double *inflow_obs =NULL; // q_in
if(nSim>0){
outflow_sim=new double[nSim];
outflow_obs=new double[nSim];
inflow_obs =new double[nSim];
}
// (c) obtain data
iSim = 0;
current_prec[0] = NETCDF_BLANK_VALUE;
if ((Options.ave_hydrograph) && (current_time[0] != 0.0))
{
current_prec[0] = GetAveragePrecip();
for (int p=0;p<_nSubBasins;p++)
{
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
outflow_sim[iSim] = _pSubBasins[p]->GetIntegratedOutflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
outflow_obs[iSim] = NETCDF_BLANK_VALUE;
for (int i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep); //time shift handled in CTimeSeries::Parse
if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; }
}
}
inflow_obs[iSim] =NETCDF_BLANK_VALUE;
if (_pSubBasins[p]->GetReservoir() != NULL){
inflow_obs[iSim] = _pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/(Options.timestep*SEC_PER_DAY);
}
iSim++;
}
}
}
else { // point-value hydrograph
if (current_time[0] != 0.0){current_prec[0] = GetAveragePrecip();} //watershed-wide precip
else {current_prec[0] = NETCDF_BLANK_VALUE;} // was originally '---'
for (int p=0;p<_nSubBasins;p++)
{
if (_pSubBasins[p]->IsGauged() && (_pSubBasins[p]->IsEnabled())){
outflow_sim[iSim] = _pSubBasins[p]->GetOutflowRate();
outflow_obs[iSim] = NETCDF_BLANK_VALUE;
for (int i = 0; i < _nObservedTS; i++){
if (IsContinuousFlowObs(_pObservedTS[i],_pSubBasins[p]->GetID()))
{
double val = _pObservedTS[i]->GetAvgValue(current_time[0],Options.timestep);
if ((val != RAV_BLANK_DATA) && (current_time[0]>0)){ outflow_obs[iSim] = val; }
}
}
inflow_obs[iSim] =NETCDF_BLANK_VALUE;
if (_pSubBasins[p]->GetReservoir() != NULL){
inflow_obs[iSim] = _pSubBasins[p]->GetReservoirInflow();
}
iSim++;
}
}
}
// write new time step
retval = nc_inq_varid (_HYDRO_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
// write precipitation values
retval = nc_inq_varid (_HYDRO_ncid, "precip", &precip_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid,precip_id,time_index,count1,¤t_prec[0]); HandleNetCDFErrors(retval);
// write simulated outflow/obs outflow/obs inflow values
if (nSim > 0){
start2[0] = int(round(current_time[0]/Options.timestep)); // element of NetCDF array that will be written
start2[1] = 0; // element of NetCDF array that will be written
count2[0] = 1; // writes exactly one time step
count2[1] = nSim; // writes exactly nSim elements
retval = nc_inq_varid (_HYDRO_ncid, "q_sim", &qsim_id); HandleNetCDFErrors(retval);
retval = nc_inq_varid (_HYDRO_ncid, "q_obs", &qobs_id); HandleNetCDFErrors(retval);
retval = nc_inq_varid (_HYDRO_ncid, "q_in", &qin_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qsim_id, start2, count2, &outflow_sim[0]); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qobs_id, start2, count2, &outflow_obs[0]); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_HYDRO_ncid, qin_id, start2, count2, &inflow_obs[0]); HandleNetCDFErrors(retval);
}
delete[] outflow_obs;
delete[] outflow_sim;
delete[] inflow_obs;
//====================================================================
// WatershedStorage.nc
//====================================================================
if (Options.write_watershed_storage)
{
double snowfall =GetAverageSnowfall();
double precip =GetAveragePrecip();
double channel_stor =GetTotalChannelStorage();
double reservoir_stor=GetTotalReservoirStorage();
double rivulet_stor =GetTotalRivuletStorage();
// write new time step
retval = nc_inq_varid (_STORAGE_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_STORAGE_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
if(tt.model_time!=0){
AddSingleValueToNetCDF(_STORAGE_ncid,"rainfall" ,time_ind2,precip-snowfall);
AddSingleValueToNetCDF(_STORAGE_ncid,"snowfall" ,time_ind2,snowfall);
}
AddSingleValueToNetCDF(_STORAGE_ncid,"Channel Storage" ,time_ind2,channel_stor);
AddSingleValueToNetCDF(_STORAGE_ncid,"Reservoir Storage",time_ind2,reservoir_stor);
AddSingleValueToNetCDF(_STORAGE_ncid,"Rivulet Storage" ,time_ind2,rivulet_stor);
double currentWater=0.0;
double S;string short_name;
int iAtmPrecip=GetStateVarIndex(ATMOS_PRECIP);
for (int i=0;i<GetNumStateVars();i++)
{
if ((CStateVariable::IsWaterStorage(_aStateVarType[i])) && (i!=iAtmPrecip))
{
S=FormatDouble(GetAvgStateVar(i));
short_name=CStateVariable::GetStateVarLongName(_aStateVarType[i],_aStateVarLayer[i]);
AddSingleValueToNetCDF(_STORAGE_ncid, short_name.c_str(),time_ind2,S);
currentWater+=S;
}
}
currentWater+=channel_stor+rivulet_stor+reservoir_stor;
if(tt.model_time==0){
// \todo [fix]: this fixes a mass balance bug in reservoir simulations, but there is certainly a more proper way to do it
// JRC: I think somehow this is being double counted in the delta V calculations in the first timestep
for(int p=0;p<_nSubBasins;p++){
if(_pSubBasins[p]->GetReservoir()!=NULL){
currentWater+=_pSubBasins[p]->GetIntegratedReservoirInflow(Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
currentWater-=_pSubBasins[p]->GetIntegratedOutflow (Options.timestep)/2.0/_WatershedArea*MM_PER_METER/M2_PER_KM2;
}
}
}
AddSingleValueToNetCDF(_STORAGE_ncid,"Total" ,time_ind2,currentWater);
AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Input" ,time_ind2,_CumulInput);
AddSingleValueToNetCDF(_STORAGE_ncid,"Cum. Outflow" ,time_ind2,_CumulOutput);
AddSingleValueToNetCDF(_STORAGE_ncid,"MB Error" ,time_ind2,FormatDouble((currentWater-_initWater)+(_CumulOutput-_CumulInput)));
}
//====================================================================
// ForcingFunctions.nc
//====================================================================
if(Options.write_forcings)
{
force_struct *pFave;
force_struct faveStruct = GetAverageForcings();
pFave = &faveStruct;
// write new time step
retval = nc_inq_varid (_FORCINGS_ncid, "time", &time_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(_FORCINGS_ncid, time_id, time_index, count1, ¤t_time[0]); HandleNetCDFErrors(retval);
// write data
AddSingleValueToNetCDF(_FORCINGS_ncid,"rainfall" ,time_ind2,pFave->precip*(1.0-pFave->snow_frac));
AddSingleValueToNetCDF(_FORCINGS_ncid,"snowfall" ,time_ind2,pFave->precip*( pFave->snow_frac));
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp" ,time_ind2,pFave->temp_ave);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_min" ,time_ind2,pFave->temp_daily_min);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_max" ,time_ind2,pFave->temp_daily_max);
AddSingleValueToNetCDF(_FORCINGS_ncid,"temp_daily_ave" ,time_ind2,pFave->temp_daily_ave);
AddSingleValueToNetCDF(_FORCINGS_ncid,"air density" ,time_ind2,pFave->air_dens);
AddSingleValueToNetCDF(_FORCINGS_ncid,"air pressure" ,time_ind2,pFave->air_pres);
AddSingleValueToNetCDF(_FORCINGS_ncid,"relative humidity",time_ind2,pFave->rel_humidity);
AddSingleValueToNetCDF(_FORCINGS_ncid,"cloud cover" ,time_ind2,pFave->cloud_cover);
AddSingleValueToNetCDF(_FORCINGS_ncid,"ET radiation" ,time_ind2,pFave->ET_radia);
AddSingleValueToNetCDF(_FORCINGS_ncid,"SW radiation" ,time_ind2,pFave->SW_radia);
AddSingleValueToNetCDF(_FORCINGS_ncid,"net SW radiation" ,time_ind2,pFave->SW_radia_net);
AddSingleValueToNetCDF(_FORCINGS_ncid,"LW radiation" ,time_ind2,pFave->cloud_cover);
AddSingleValueToNetCDF(_FORCINGS_ncid,"wind velocity" ,time_ind2,pFave->wind_vel);
AddSingleValueToNetCDF(_FORCINGS_ncid,"PET" ,time_ind2,pFave->PET);
AddSingleValueToNetCDF(_FORCINGS_ncid,"OW PET" ,time_ind2,pFave->OW_PET);
AddSingleValueToNetCDF(_FORCINGS_ncid,"potential melt" ,time_ind2,pFave->potential_melt);
}
#endif
}
//////////////////////////////////////////////////////////////////
/// \brief creates specified output directory, if needed
///
/// \param &Options [in] global model options
//
void PrepareOutputdirectory(const optStruct &Options)
{
if (Options.output_dir!="")
{
#if defined(_WIN32)
_mkdir(Options.output_dir.c_str());
#elif defined(__linux__)
mkdir(Options.output_dir.c_str(), 0777);
#endif
}
g_output_directory=Options.main_output_dir;//necessary evil
}
//////////////////////////////////////////////////////////////////
/// \brief returns directory path given filename
///
/// \param fname [in] filename, e.g., C:\temp\thisfile.txt returns c:\temp
//
string GetDirectoryName(const string &fname)
{
size_t pos = fname.find_last_of("\\/");
if (std::string::npos == pos){ return ""; }
else { return fname.substr(0, pos);}
}
//////////////////////////////////////////////////////////////////
/// \brief returns directory path given filename and relative path
///
/// \param filename [in] filename, e.g., C:/temp/thisfile.txt returns c:/temp
/// \param relfile [in] filename of reference file
/// e.g.,
/// absolute path of reference file is adopted
/// if filename = something.txt and relfile= c:/temp/myfile.rvi, returns c:/temp/something.txt
///
/// relative path of reference file is adopted
/// if filename = something.txt and relfile= ../dir/myfile.rvi, returns ../dir/something.txt
///
/// if path of reference file is same as file, then nothing changes
/// if filename = ../temp/something.txt and relfile= ../temp/myfile.rvi, returns ../temp/something.txt
///
/// if absolute paths of file is given, nothing changes
/// if filename = c:/temp/something.txt and relfile= ../temp/myfile.rvi, returns c:/temp/something.txt
//
string CorrectForRelativePath(const string filename,const string relfile)
{
string filedir = GetDirectoryName(relfile); //if a relative path name, e.g., "/path/model.rvt", only returns e.g., "/path"
if (StringToUppercase(filename).find(StringToUppercase(filedir)) == string::npos)//checks to see if absolute dir already included in redirect filename
{
string firstchar = filename.substr(0, 1); // if '/' --> absolute path on UNIX systems
string secondchar = filename.substr(1, 1); // if ':' --> absolute path on WINDOWS system
if ( (firstchar.compare("/") != 0) && (secondchar.compare(":") != 0) ){
// cout << "This is not an absolute filename! --> " << filename << endl;
//+"//"
//cout << "StandardOutput: corrected filename: " << filedir + "//" + filename << endl;
return filedir + "//" + filename;
}
}
// cout << "StandardOutput: corrected filename: " << filename << endl;
return filename;
}
//////////////////////////////////////////////////////////////////
/// \brief adds metadata of attribute to NetCDF file
/// \param fileid [in] NetCDF output file id
/// \param time_dimid [in], identifier of time attribute
/// \param shortname [in] attribute short name
/// \param longname [in] attribute long name
/// \param units [in] attribute units as string
//
int NetCDFAddMetadata(const int fileid,const int time_dimid,string shortname,string longname,string units)
{
int varid(0);
#ifdef _RVNETCDF_
int retval;
int dimids[1];
dimids[0] = time_dimid;
static double fill_val[] = {NETCDF_BLANK_VALUE};
static double miss_val[] = {NETCDF_BLANK_VALUE};
// (a) create variable precipitation
retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,1,dimids,&varid); HandleNetCDFErrors(retval);
// (b) add attributes to variable
retval = nc_put_att_text (fileid,varid,"units",units.length(),units.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text (fileid,varid,"long_name",longname.length(),longname.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"_FillValue",NC_DOUBLE,1,fill_val); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"missing_value",NC_DOUBLE,1,miss_val); HandleNetCDFErrors(retval);
#endif
return varid;
}
//////////////////////////////////////////////////////////////////
/// \brief adds metadata of attribute to NetCDF file for 2D data (time,nbasins)
/// \param fileid [in] NetCDF output file id
/// \param time_dimid [in], identifier of time attribute
/// \param nbasins_dimid [in], identifier of # basins attribute
/// \param shortname [in] attribute short name
/// \param longname [in] attribute long name
/// \param units [in] attribute units as string
//
int NetCDFAddMetadata2D(const int fileid,const int time_dimid,int nbasins_dimid,string shortname,string longname,string units)
{
int varid(0);
#ifdef _RVNETCDF_
int retval;
int dimids2[2];
string tmp;
static double fill_val[] = {NETCDF_BLANK_VALUE};
static double miss_val[] = {NETCDF_BLANK_VALUE};
dimids2[0] = time_dimid;
dimids2[1] = nbasins_dimid;
// (a) create variable
retval = nc_def_var(fileid,shortname.c_str(),NC_DOUBLE,2,dimids2,&varid); HandleNetCDFErrors(retval);
tmp = "basin_name";
// (b) add attributes to variable
retval = nc_put_att_text( fileid,varid,"units", units.length(), units.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_text( fileid,varid,"long_name", longname.length(),longname.c_str()); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"_FillValue", NC_DOUBLE,1, fill_val); HandleNetCDFErrors(retval);
retval = nc_put_att_double(fileid,varid,"missing_value", NC_DOUBLE,1, miss_val); HandleNetCDFErrors(retval);
retval = nc_put_att_text( fileid,varid,"coordinates", tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval);
#endif
return varid;
}
//////////////////////////////////////////////////////////////////
/// \brief writes global attributes to netcdf file identified with out_ncid. Must be timeSeries featureType.
/// \param out_ncid [in] NetCDF file identifier
/// \param Options [in] model Options structure
/// \param descript [in] contents of NetCDF description attribute
//
void WriteNetCDFGlobalAttributes(const int out_ncid,const optStruct &Options,const string descript)
{
ExitGracefullyIf(out_ncid==-9,"WriteNetCDFGlobalAttributes: netCDF file not open",RUNTIME_ERR);
int retval(0);
string att,val;
#ifdef _RVNETCDF_
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "Conventions", strlen("CF-1.6"), "CF-1.6"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "featureType", strlen("timeSeries"), "timeSeries"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "history", strlen("Created by Raven"),"Created by Raven"); HandleNetCDFErrors(retval);
retval = nc_put_att_text(out_ncid, NC_GLOBAL, "description", strlen(descript.c_str()), descript.c_str()); HandleNetCDFErrors(retval);
for(int i=0;i<Options.nNetCDFattribs;i++){
att=Options.aNetCDFattribs[i].attribute;
val=Options.aNetCDFattribs[i].value;
retval = nc_put_att_text(out_ncid,NC_GLOBAL,att.c_str(),strlen(val.c_str()),val.c_str());
HandleNetCDFErrors(retval);
}
#endif
}
//////////////////////////////////////////////////////////////////
/// \brief adds single value of attribute 'shortname' linked to time time_index to NetCDF file
/// \param out_ncid [in] NetCDF file identifier
/// \param shortname [in] short name of attribute (e.g., 'rainfall')
/// \param time_index [in] index of current time step
/// \param value [in] value of attribute at current time step
//
void AddSingleValueToNetCDF(const int out_ncid,const string &shortname,const size_t time_index,const double &value)
{
static size_t count1[1]; //static for speed of execution
static size_t time_ind[1];
static double val[1];
int var_id(0),retval(0);
time_ind[0]=time_index;
count1[0]=1;
val[0]=value;
#ifdef _RVNETCDF_
retval = nc_inq_varid (out_ncid,shortname.c_str(),&var_id); HandleNetCDFErrors(retval);
retval = nc_put_vara_double(out_ncid,var_id,time_ind,count1,&val[0]); HandleNetCDFErrors(retval);
#endif
}
| 43.10613 | 171 | 0.582575 |
f4bc121c4304525c02031b34fad39c65d8a34747 | 798 | cpp | C++ | src/modules/osg/generated_code/ClipPlaneList.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/ClipPlaneList.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/ClipPlaneList.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/vector.hpp"
#include "wrap_osg.h"
#include "_ref_ptr_less__osg_scope_ClipPlane__greater___value_traits.pypp.hpp"
#include "clipplanelist.pypp.hpp"
namespace bp = boost::python;
void register_ClipPlaneList_class(){
{ //::std::vector< osg::ref_ptr<osg::ClipPlane> >
typedef bp::class_< std::vector< osg::ref_ptr<osg::ClipPlane> > > ClipPlaneList_exposer_t;
ClipPlaneList_exposer_t ClipPlaneList_exposer = ClipPlaneList_exposer_t( "ClipPlaneList" );
bp::scope ClipPlaneList_scope( ClipPlaneList_exposer );
ClipPlaneList_exposer.def( bp::indexing::vector_suite< std::vector< osg::ref_ptr<osg::ClipPlane> > >() );
}
}
| 36.272727 | 113 | 0.740602 |
f4bd24595ae54aaad502d864082ac65a7180b5d7 | 739 | cpp | C++ | Structure_and_pointer_using_arrow_operator.cpp | gptakhil/Cpp-Revision | ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b | [
"MIT"
] | null | null | null | Structure_and_pointer_using_arrow_operator.cpp | gptakhil/Cpp-Revision | ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b | [
"MIT"
] | null | null | null | Structure_and_pointer_using_arrow_operator.cpp | gptakhil/Cpp-Revision | ae2a9e9ed4eaeb66a4b00787637ae4ff3132b57b | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
// Student structure
struct Student {
string name;
int roll_number;
int marks;
};
// main function
int main() {
// Declare structure variable
struct Student s1;
// Declare structure pointer
struct Student *ptrs1;
// Store address of structure variable in structure pointer
ptrs1 = &s1;
// Set value of name
ptrs1->name = "John";
// Set value of roll_number
ptrs1->roll_number = 1;
// Set value of marks
ptrs1->marks = 50;
// Print value of structure member
cout << "s1 Information:" << endl;
cout << "Name = " << ptrs1->name << endl;
cout << "Roll Number = " << ptrs1->roll_number << endl;
cout << "Marks = " << ptrs1->marks << endl;
return 0;
}
| 19.972973 | 61 | 0.640054 |
f4bd493befc9a42fcd2e0c51b941f91c214307bd | 2,440 | cpp | C++ | metaforce-gui/CVarDialog.cpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | 267 | 2016-03-10T21:59:16.000Z | 2021-03-28T18:21:03.000Z | metaforce-gui/CVarDialog.cpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 129 | 2016-03-12T10:17:32.000Z | 2021-04-05T20:45:19.000Z | metaforce-gui/CVarDialog.cpp | cobalt2727/metaforce | 3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a | [
"MIT"
] | 31 | 2016-03-20T00:20:11.000Z | 2021-03-10T21:14:11.000Z | #include "CVarDialog.hpp"
#include "ui_CVarDialog.h"
#include <utility>
enum class CVarType {
String,
Boolean,
};
struct CVarItem {
QString m_name;
CVarType m_type;
QVariant m_defaultValue;
CVarItem(QString name, CVarType type, QVariant defaultValue)
: m_name(std::move(name)), m_type(type), m_defaultValue(std::move(defaultValue)) {}
};
static std::array cvarList{
CVarItem{QStringLiteral("tweak.game.FieldOfView"), CVarType::String, 55},
CVarItem{QStringLiteral("debugOverlay.playerInfo"), CVarType::Boolean, false},
CVarItem{QStringLiteral("debugOverlay.areaInfo"), CVarType::Boolean, false},
// TODO expand
};
CVarDialog::CVarDialog(QWidget* parent) : QDialog(parent), m_ui(std::make_unique<Ui::CVarDialog>()) {
m_ui->setupUi(this);
QStringList list;
for (const auto& item : cvarList) {
list << item.m_name;
}
m_model.setStringList(list);
m_ui->cvarList->setModel(&m_model);
connect(m_ui->cvarList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,
SLOT(handleSelectionChanged(QItemSelection)));
}
CVarDialog::~CVarDialog() = default;
void CVarDialog::on_buttonBox_accepted() {
const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes();
if (list.isEmpty()) {
reject();
} else {
accept();
}
}
void CVarDialog::on_buttonBox_rejected() { reject(); }
void CVarDialog::handleSelectionChanged(const QItemSelection& selection) {
const QModelIndexList& list = selection.indexes();
if (list.isEmpty()) {
return;
}
const auto item = cvarList[(*list.begin()).row()];
m_ui->valueStack->setCurrentIndex(static_cast<int>(item.m_type));
if (item.m_type == CVarType::String) {
m_ui->stringValueField->setText(item.m_defaultValue.toString());
} else if (item.m_type == CVarType::Boolean) {
m_ui->booleanValueField->setChecked(item.m_defaultValue.toBool());
}
}
QString CVarDialog::textValue() {
const QModelIndexList& list = m_ui->cvarList->selectionModel()->selectedIndexes();
if (list.isEmpty()) {
return QStringLiteral("");
}
const auto item = cvarList[(*list.begin()).row()];
QVariant value;
if (item.m_type == CVarType::String) {
value = m_ui->stringValueField->text();
} else if (item.m_type == CVarType::Boolean) {
value = m_ui->booleanValueField->isChecked();
}
return QStringLiteral("+") + item.m_name + QStringLiteral("=") + value.toString();
}
| 30.886076 | 107 | 0.703279 |
f4bddf3d7b8570b8edff54fcafb5860712621925 | 2,097 | hpp | C++ | ziomon/ziorep_framer.hpp | nikita-dubrovskii/s390-tools | 074de1e14ed785c18f55ecf9762ac3f5de3465b4 | [
"MIT"
] | 43 | 2017-08-21T12:18:57.000Z | 2021-01-21T09:20:59.000Z | ziomon/ziorep_framer.hpp | nikita-dubrovskii/s390-tools | 074de1e14ed785c18f55ecf9762ac3f5de3465b4 | [
"MIT"
] | 99 | 2017-08-21T20:41:13.000Z | 2021-01-27T16:23:07.000Z | ziomon/ziorep_framer.hpp | nikita-dubrovskii/s390-tools | 074de1e14ed785c18f55ecf9762ac3f5de3465b4 | [
"MIT"
] | 37 | 2017-08-21T20:37:32.000Z | 2021-02-02T10:10:45.000Z | /*
* FCP report generators
*
* Class for reading messages into frames.
*
* Copyright IBM Corp. 2008, 2017
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef ZIOREP_FRAMER
#define ZIOREP_FRAMER
#include <list>
#include "ziorep_filters.hpp"
#include "ziorep_frameset.hpp"
using std::list;
extern "C" {
#include "ziomon_dacc.h"
}
class Framer {
public:
/**
* Note: Filter parameters transfer memory ownership to class.
* 'filter_types' is an optional list of message types that should
* be processed exclusively, anything else will be ignored. If not set,
* all messages will be processed.
*/
Framer(__u64 begin, __u64 end, __u32 interval_length,
list<MsgTypes> *filter_types, DeviceFilter *devFilter,
const char *filename, int *rc);
~Framer();
/**
* Retrieve the next set of messages.
* Returns 0 in case of success, <0 in case of failure
* and >0 in case end of data has been reached.
* Set 'replace_missing' to fill in for non-present datasets.
* E.g. if no utilization data was found in the interval (since there
* was no traffic), a dataset with the expected number of samples
* (but all 0s for the values) will be generated.
*/
int get_next_frameset(Frameset &frameset, bool replace_missing = false);
private:
void handle_msg(struct message *msg, Frameset &frameset) const;
bool handle_agg_data(Frameset &frameset) const;
/* timestamps of samples to consider
* These are exact timestamps, we shift them a bit to make sure that
* we catch any late or early messages as well */
__u64 m_begin;
__u64 m_end;
/// user-specified interval length
__u32 m_interval_length;
/* Criteria to identify the right messages */
MsgTypeFilter *m_type_filter;
DeviceFilter *m_device_filter;
// filename without extension
const char *m_filename;
FILE *m_fp;
struct file_header m_fhdr;
struct aggr_data *m_agg_data;
/// indicates whether the .agg file was already read or not
bool m_agg_read;
};
#endif
| 25.573171 | 73 | 0.72103 |
f4bfc17b377b3c5017fcc97a6105b03afe47b3c0 | 27,119 | cpp | C++ | src/SphinxService.cpp | ExpandingDev/PyramidASR | dbfddc13bb6dde7a8e349e87e4ca9df229d64703 | [
"Unlicense"
] | null | null | null | src/SphinxService.cpp | ExpandingDev/PyramidASR | dbfddc13bb6dde7a8e349e87e4ca9df229d64703 | [
"Unlicense"
] | 10 | 2019-07-08T03:38:52.000Z | 2019-11-20T20:57:17.000Z | src/SphinxService.cpp | ExpandingDev/PyramidASR | dbfddc13bb6dde7a8e349e87e4ca9df229d64703 | [
"Unlicense"
] | null | null | null | #include "SphinxService.h"
#include "ReplyType.h"
#include "Buckey.h"
#include "HypothesisEventData.h"
#include <chrono>
using namespace std::chrono;
SphinxService * SphinxService::instance;
std::atomic<bool> SphinxService::instanceSet(false);
unsigned long SphinxService::onEnterPromptEventHandlerID;
unsigned long SphinxService::onConversationEndEventHandlerID;
SphinxService * SphinxService::getInstance() {
if(!instanceSet) {
instance = new SphinxService();
instanceSet.store(true);
}
return instance;
}
std::string SphinxService::getName() const {
return "sphinx";
}
void SphinxService::setupAssets(cppfs::FileHandle aDir) {
cppfs::FileHandle confirmGram = aDir.open("confirm.gram");
if(!confirmGram.writeFile("#JSGF v1.0;\n\
grammar confirm;\n\
public <command> = <positive> {yes} | <deny> {no};\n\
<positive> = yes | yeah | ok | positive | confirm | of course | please do | yes sir;\n\
<deny> = no | deny | reject | [please] don't | nope | do not;")) {
///TODO: Error setting up confirm.gram
Buckey::logError("SphinxService failed to create confirm.gram asset file.");
}
}
void SphinxService::setupConfig(cppfs::FileHandle cDir) {
YAML::Node n;
n["logfile"] = "/dev/null";
n["max-frame-size"] = 2048;
n["hmm-dir"] = "/usr/local/share/pocketsphinx/model/en-us/en-us";
n["dict-dir"] = "/usr/local/share/pocketsphinx/model/en-us/cmudict-en-us.dict";
// n["speech-device"] = "default";
n["default-lm"] = "/usr/local/share/pocketsphinx/model/en-us/en-us.lm.bin";
n["max-decoders"] = 2;
n["samples-per-second"] = 16000; // Taken from libsphinxad ad.h is usually 16000
cppfs::FileHandle cFile = cDir.open("decoder.conf");
YAML::Emitter e;
e << n;
cFile.writeFile(e.c_str());
}
SphinxService::SphinxService() : manageThreadRunning(false), currentDecoderIndex(0), inUtterance(false), endLoop(false), paused(false), pressToSpeakMode(false), pressToSpeakPressed(false) {
}
SphinxService::~SphinxService()
{
endLoop.store(true);
//usleep(100); // TODO: Windows portability
if(manageThreadRunning.load() || recognizerLoop.joinable()) {
recognizerLoop.join();
}
for(std::thread & t : miscThreads) {
t.join();
}
for(SphinxDecoder * sd : decoders) {
delete sd;
}
instanceSet.store(false);
}
void SphinxService::start() {
setState(ServiceState::STARTING);
endLoop.store(false);
voiceDetected.store(false);
recognizing.store(false);
isRecording.store(false);
paused.store(false);
pressToSpeakMode.store(false);
pressToSpeakPressed.store(false);
config = YAML::LoadFile(configDir.open("decoder.conf").path());
maxDecoders = config["max-decoders"].as<unsigned int>();
deviceName = "";
if(config["speech-device"]) {
deviceName = config["speech-device"].as<std::string>();
}
for(unsigned short i = 0; i < maxDecoders; i++) {
SphinxDecoder * sd = new SphinxDecoder("base-grammar", config["default-lm"].as<std::string>(), SphinxHelper::SearchMode::LM, config["hmm-dir"].as<std::string>(), config["dict-dir"].as<std::string>(), config["logfile"].as<std::string>(), true);
decoders.push_back(sd);
}
startPressToSpeakRecognition(deviceName);
///TODO: Set listeners
onEnterPromptEventHandlerID = Buckey::getInstance()->addListener("onEnterPromptEvent", onEnterPromptEventHandler);
onConversationEndEventHandlerID = Buckey::getInstance()->addListener("onExitPromptEvent", onConversationEndEventHandler);
setState(ServiceState::RUNNING);
}
void SphinxService::stop() {
if(getState() == ServiceState::RUNNING) {
Buckey::getInstance()->unsetListener("onEnterPromptEvent", onEnterPromptEventHandlerID);
Buckey::getInstance()->unsetListener("onExitPromptEvent", onConversationEndEventHandlerID);
stopRecognition();
}
setState(ServiceState::STOPPED);
}
void SphinxService::stopRecognition() {
Buckey::logInfo("Received request to stop recognition.");
endLoop.store(true);
if(manageThreadRunning.load()) {
recognizerLoop.join();
}
}
void SphinxService::pauseRecognition() {
paused.store(true);
triggerEvents(ON_PAUSE, new EventData());
}
void SphinxService::resumeRecognition() {
triggerEvents(ON_RESUME, new EventData());
paused.store(false);
}
bool SphinxService::isRecordingToFile() {
return isRecording;
}
void SphinxService::stopRecordingToFile() {
isRecording.store(false);
fflush(recordingFileHandle);
fclose(recordingFileHandle);
}
bool SphinxService::startRecordingToFile() {
if(recordingFileHandle != NULL) {
isRecording.store(false);
return true;
}
else {
return false;
}
}
void SphinxService::onEnterPromptEventHandler(EventData * data, std::atomic<bool> * done) {
PromptEventData * d = (PromptEventData *) data;
Buckey::logInfo("enter prompt event handler");
if(d->getType() == "confirm") {
SphinxService::getInstance()->updateJSGFPath(SphinxService::getInstance()->assetsDir.open("confirm.gram").path());
SphinxService::getInstance()->applyUpdates();
Buckey::logInfo("switched grammars");
}
done->store(true);
}
void SphinxService::onConversationEndEventHandler(EventData * data, std::atomic<bool> * done) {
Buckey::logInfo("exit prompt event handler");
SphinxService::getInstance()->setJSGF(Buckey::getInstance()->getRootGrammar());
SphinxService::getInstance()->applyUpdates();
done->store(true);
}
bool SphinxService::recordAudioToFile(std::string pathToAudioFile) {
recordingFile = pathToAudioFile;
recordingFileHandle = fopen(pathToAudioFile.c_str(), "wb");
//TODO: Implement proper file closing when stop recording method is called. Currently stops recording when it reaches the end of an audio file, but does not close it when the stop function is called.
if(recordingFileHandle == NULL) {
Buckey::logError("Unable to open raw audio file to write recorded audio! " + pathToAudioFile);
return false;
}
else {
isRecording.store(true);
return true;
}
}
///Static loop that runs during non-continuous/push to speak recognition
void SphinxService::manageNonContinuousDecoders(SphinxService * sr) {
//Lock all mutexes and flags first
sr->manageThreadRunning.store(true);
sr->updateLock.lock();
Buckey * b = Buckey::getInstance();
ad_rec_t *ad = nullptr; // Audio source
int16 adbuf[sr->config["max-frame-size"].as<int>()]; //buffer that audio frames are copied into
int32 frameCount = 0; // Number of frames read into the adbuf
sr->endLoop.store(false);
sr->inUtterance.store(false);
sr->voiceDetected.store(false); // Reset this as its used to keep track of state
Buckey::logInfo("Decoder management thread started");
if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Opening audio device for recognition");
if(sr->deviceName == "") {
if ((ad = ad_open_sps(sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else if((ad = ad_open_dev(sr->deviceName.c_str(), sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else {
Buckey::logWarn("Cannot open noncontinuous decoding for FILE!");
sr->recognizing.store(false);
return;
}
sr->currentDecoderIndex.store(0);
Buckey::logInfo("Starting Utterances...");
// Start up all of the utterances
for(SphinxDecoder * sd : sr->decoders) {
sd->startUtterance();
}
Buckey::logInfo("Done starting Utterances.");
while(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::NOT_INITIALIZED) {
//Wait until the decoder is ready
}
sr->recognizing.store(false);
sr->triggerEvents(ON_READY, new EventData());
Buckey::getInstance()->reply("Sphinx Speech Recognition Ready", ReplyType::CONSOLE);
sr->updateLock.unlock();
sr->triggerEvents(ON_SERVICE_READY, new EventData());
while(!b->isKilled() && !sr->endLoop.load()) {
while(!b->isKilled() && !sr->endLoop.load() && !sr->pressToSpeakPressed.load()) {
//Wait until press to speak is pressed or we have to stop
}
//Make sure we didn't exit the loop because we have to stop
if(b->isKilled() || sr->endLoop.load()) {
break;
}
sr->recognizing.store(true);
auto start = high_resolution_clock::now();
//Start recording from audio device
if (ad_start_rec(ad) < 0) {
Buckey::logError("Failed to start recording");
sr->recognizing.store(false);
break;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
std::cout << "Time to start recording: " << duration.count() << std::endl;
// Read from the audio buffer while press to speak is pressed
while(sr->pressToSpeakPressed.load() && !sr->endLoop.load() && !b->isKilled()) {
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
//Check to make sure we got frames from the audio device
if(frameCount < 0 ) {
if(sr->source == SphinxHelper::DEVICE) {
Buckey::logError("Failed to read from audio device for sphinx recognizer!");
/// TODO: Maybe fail a bit more gracefully
sr->killThreads();
break;
}
}
else if(sr->isRecording) {
fwrite(adbuf, sizeof(int16), frameCount, sr->recordingFileHandle);
fflush(sr->recordingFileHandle);
}
// Check to make sure our current decoder has not errored out
if(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::ERROR) {
Buckey::logError("Decoder is errored out! Trying next decoder...");
bool found = false;
for(unsigned short i = sr->currentDecoderIndex; i < sr->maxDecoders - 1; i++) {
if(sr->decoders[sr->currentDecoderIndex]->isReady()) {
sr->currentDecoderIndex.store(sr->currentDecoderIndex + i);
found = true;
break;
}
}
if(!found) {
Buckey::logError("No more good decoders to use! Stopping speech recognition!");
sr->killThreads();
break;
}
}
/*
// Check to make sure our current decoder is still ready to process speech (make sure the utterance has been started)
if(sr->decoders[sr->currentDecoderIndex]->state != SphinxHelper::DecoderState::UTTERANCE_STARTED) {
sr->decoders[sr->currentDecoderIndex]->startUtterance();
}
*/
// Process the frames
sr->voiceDetected.store(sr->decoders[sr->currentDecoderIndex]->processRawAudio(adbuf, frameCount));
// Silence to speech transition
// Trigger onSpeechStart
if(sr->voiceDetected && !sr->inUtterance) {
sr->triggerEvents(ON_START_SPEECH, new EventData());
sr->inUtterance.store(true);
b->playSoundEffect(SoundEffects::READY, false);
}
}
//Make sure we didn't exit the loop because we have to stop
if(b->isKilled() || sr->endLoop.load()) {
break;
}
//Stop recording
ad_stop_rec(ad);
//End and get hypothesis
sr->decoderIndexLock.lock();
sr->inUtterance.store(false);
sr->recognizing.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
//Refresh decoders
sr->decoderIndexLock.lock();
for(unsigned short i = 0; i < sr->maxDecoders; i++) {
if(sr->decoders[i]->isReady()) {
sr->currentDecoderIndex.store(i);
}
}
sr->decoderIndexLock.unlock();
}
//Close the device audio source
Buckey::logInfo("Closing audio device");
ad_close(ad);
sr->recognizing.store(false);
sr->pressToSpeakMode.store(false);
sr->pressToSpeakPressed.store(false);
sr->manageThreadRunning.store(false);
}
bool SphinxService::inPressToSpeak() {
return pressToSpeakMode.load();
}
bool SphinxService::pressToSpeakIsPressed() {
return pressToSpeakPressed.load();
}
bool SphinxService::isPaused() {
return paused.load();
}
/// Static loop that runs during continuous recognition
void SphinxService::manageContinuousDecoders(SphinxService * sr) {
Buckey * b = Buckey::getInstance();
sr->manageThreadRunning.store(true);
sr->updateLock.lock();
Buckey::logInfo("Decoder management thread started");
sr->endLoop.store(false);
ad_rec_t *ad = nullptr; // Audio source
int16 adbuf[sr->config["max-frame-size"].as<int>()]; //buffer that audio frames are copied into
int32 frameCount = 0; // Number of frames read into the adbuf
sr->inUtterance.store(false);
sr->voiceDetected.store(false); // Reset this as its used to keep track of state
if(sr->source == SphinxHelper::FILE) {
Buckey::logInfo("Opening file for recognition");
// TODO: Implement opening the file, reliant upon specifying the args passed during startFileRecognition
}
else if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Opening audio device for recognition");
// TODO: Use ad_open_dev without pocketsphinx's terrible configuration functions
//if ((ad = ad_open_dev(NULL,(int) cmd_ln_float32_r(sr->decoders[0]->getConfig(),"-samprate"))) == NULL) {
Buckey::logInfo("Opening audio device for recognition");
if(sr->deviceName == "") {
if ((ad = ad_open_sps(sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
}
else if((ad = ad_open_dev(sr->deviceName.c_str(), sr->config["samples-per-second"].as<int>())) == NULL) { // DEFAULT_SAMPLES_PER_SEC is taken from libsphinxad ad.h is usually 16000
Buckey::logError("Failed to open audio device");
sr->recognizing.store(false);
return;
}
if (ad_start_rec(ad) < 0) {
Buckey::logError("Failed to start recording\n");
sr->recognizing.store(false);
return;
}
}
sr->currentDecoderIndex.store(0);
Buckey::logInfo("Starting Utterances...");
// Start up all of the utterances
for(SphinxDecoder * sd : sr->decoders) {
sd->startUtterance();
}
Buckey::logInfo("Done starting Utterances.");
while(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::NOT_INITIALIZED) {
//Wait until the decoder is ready
}
sr->recognizing.store(true);
sr->triggerEvents(ON_READY, new EventData());
Buckey::getInstance()->reply("Sphinx Speech Recognition Ready", ReplyType::CONSOLE);
sr->updateLock.unlock();
sr->triggerEvents(ON_SERVICE_READY, new EventData());
while(!sr->endLoop.load()) {
// Read from the audio buffer
if(sr->source == SphinxHelper::DEVICE) {
if(sr->paused.load()) {
sr->decoderIndexLock.lock();
sr->decoders[sr->currentDecoderIndex]->endUtterance();
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->startUtterance();
sr->decoderIndexLock.unlock();
}
while(sr->paused.load() && !sr->endLoop) {
//Wait until not paused, but continue reading frames so that we only read current frames when we resume recognition
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
}
if(sr->endLoop) {
break;
}
frameCount = ad_read(ad, adbuf, AUDIO_FRAME_SIZE);
}
else if (sr->source == SphinxHelper::FILE) {
///NOTE: Pausing and resuming recognition only works from a device, not a file.
frameCount = fread(adbuf, sizeof(int16), AUDIO_FRAME_SIZE, sr->sourceFile);
}
if(frameCount < 0 ) {
if(sr->source == SphinxHelper::DEVICE) {
Buckey::logError("Failed to read from audio device for sphinx recognizer!");
// TODO: Maybe fail a bit more gracefully
sr->killThreads();
exit(-1);
}
}
else if(sr->isRecording) {
fwrite(adbuf, sizeof(int16), frameCount, sr->recordingFileHandle);
fflush(sr->recordingFileHandle);
}
// Check to make sure our current decoder has not errored out
if(sr->decoders[sr->currentDecoderIndex]->state == SphinxHelper::DecoderState::ERROR) {
Buckey::logError("Decoder is errored out! Trying next decoder...");
bool found = false;
for(unsigned short i = sr->currentDecoderIndex; i < sr->maxDecoders - 1; i++) {
if(sr->decoders[sr->currentDecoderIndex]->isReady()) {
sr->currentDecoderIndex.store(sr->currentDecoderIndex + i);
found = true;
break;
}
}
if(!found) {
Buckey::logError("No more good decoders to use! Stopping speech recognition!");
sr->killThreads();
return;
}
}
if(frameCount <= 0 && sr->source == SphinxHelper::FILE) {
Buckey::logInfo("Reached end of audio file, stopping speech recognition...");
if(sr->inUtterance) { // Reached end of file before end of speech, so stop recognition and get the hypothesis
sr->decoderIndexLock.lock();
sr->triggerEvents(ON_END_SPEECH, new EventData()); // TODO: Add event data
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
if(sr->isRecording) {
sr->isRecording.store(false);
fflush(sr->recordingFileHandle);
fclose(sr->recordingFileHandle);
}
break;
}
}
// Process the frames
sr->voiceDetected.store(sr->decoders[sr->currentDecoderIndex]->processRawAudio(adbuf, frameCount));
// Silence to speech transition
// Trigger onSpeechStart
if(sr->voiceDetected && !sr->inUtterance) {
sr->triggerEvents(ON_START_SPEECH, new EventData());
sr->inUtterance.store(true);
b->playSoundEffect(SoundEffects::READY, false);
}
//Speech to silence transition
//Trigger onSpeechEnd
//And get hypothesis
if(!sr->voiceDetected && sr->inUtterance) {
sr->decoderIndexLock.lock();
sr->triggerEvents(ON_END_SPEECH, new EventData()); //TODO: Add event data
sr->inUtterance.store(false);
sr->decoders[sr->currentDecoderIndex]->ready = false;
sr->miscThreads.push_back(std::thread(endAndGetHypothesis, sr, sr->decoders[sr->currentDecoderIndex]));
sr->decoderIndexLock.unlock();
usleep(100); // TODO: Windows portability
sr->decoderIndexLock.lock();
for(unsigned short i = 0; i < sr->maxDecoders; i++) {
if(sr->decoders[i]->isReady()) {
sr->currentDecoderIndex.store(i);
}
}
sr->decoderIndexLock.unlock();
}
}
if(sr->source == SphinxHelper::FILE) {
fclose(sr->sourceFile);
}
//Close the device audio source
if (sr->source == SphinxHelper::DEVICE) {
Buckey::logInfo("Closing audio device");
ad_close(ad);
}
sr->recognizing.store(false);
sr->manageThreadRunning.store(false);
}
void SphinxService::startContinuousDeviceRecognition(std::string device) {
Buckey::logInfo("Starting device recognition");
if(!recognizing) {
source = SphinxHelper::DEVICE;
if(device != "") {
deviceName = device;
}
else {
// deviceName = config["speech-device"].as<std::string>();
device = "";
}
if(recognizerLoop.joinable()) {
recognizerLoop.join();
}
pressToSpeakMode.store(false);
recognizerLoop = std::thread(manageContinuousDecoders, this);
}
else {
Buckey::logWarn("Calling start device recognition while recognition already in progress!");
}
}
void SphinxService::startPressToSpeakRecognition(std::string device) {
Buckey::logInfo("Starting press to speak device recognition");
if(!recognizing) {
source = SphinxHelper::DEVICE;
if(device != "") {
deviceName = device;
}
else {
// deviceName = config["speech-device"].as<std::string>();
deviceName = "";
}
if(recognizerLoop.joinable()) {
recognizerLoop.join();
}
pressToSpeakMode.store(true);
recognizerLoop = std::thread(manageNonContinuousDecoders, this);
}
else {
Buckey::logWarn("Calling start device recognition while recognition already in progress!");
}
}
void SphinxService::pressToSpeakButtonDown() {
pressToSpeakPressed.store(true);
}
void SphinxService::pressToSpeakButtonUp() {
pressToSpeakPressed.store(false);
}
void SphinxService::endAndGetHypothesis(SphinxService * sr, SphinxDecoder * sd) {
sd->endUtterance();
std::string hyp = sd->getHypothesis();
if(hyp != "") { // Ignore false alarms
Buckey::logInfo("Got hypothesis: " + hyp);
Buckey::getInstance()->playSoundEffect(SoundEffects::OK, false);
sr->triggerEvents(ON_HYPOTHESIS, new HypothesisEventData(hyp));
Buckey::getInstance()->passInput(hyp);
}
sd->startUtterance();
}
void SphinxService::startFileRecognition(std::string pathToFile) {
if((sourceFile = fopen(pathToFile.c_str(), "rb")) == NULL) {
Buckey::logError("Unable to open file for speech recognition: " + pathToFile);
stopRecognition();
for(std::thread & t : miscThreads) {
t.join();
}
for(SphinxDecoder * sd : decoders) {
delete sd;
}
exit(-1);
}
else {
source = SphinxHelper::FILE;
Buckey::logInfo("Opened file for speech recognition: " + pathToFile);
}
recognizerLoop = std::thread(manageContinuousDecoders, this);
}
bool SphinxService::wordExists(std::string word) {
bool res = false;
bool found = false;
while(!found) {
for(unsigned short i = 0; i < maxDecoders - 1; i++) {
if(decoders[currentDecoderIndex]->isReady()) {
res = decoders[currentDecoderIndex]->wordExists(word);
found = true;
break;
}
}
}
return res;
}
void SphinxService::addWord(std::string word, std::string phones) {
for(unsigned short i = 0; i < maxDecoders - 1; i++) {
if(decoders[currentDecoderIndex]->getState() != SphinxHelper::DecoderState::ERROR && decoders[currentDecoderIndex]->getState() != SphinxHelper::DecoderState::NOT_INITIALIZED) {
decoders[currentDecoderIndex]->addWord(word, phones);
}
else {
Buckey::logWarn("Unable to add word " + word + " to decoder because it was not initialized or errored out!");
}
}
}
void SphinxService::updateDictionary(std::string pathToDictionary) {
for(SphinxDecoder * sd : decoders) {
sd->updateDictionary(pathToDictionary, false);
}
}
void SphinxService::updateAcousticModel(std::string pathToHMM) {
for(SphinxDecoder * sd : decoders) {
sd->updateAcousticModel(pathToHMM, false);
}
}
void SphinxService::updateJSGFPath(std::string pathToJSGF) {
for(SphinxDecoder * sd : decoders) {
sd->updateJSGF(pathToJSGF, false);
}
}
void SphinxService::updateLMPath(std::string pathToLM) {
for(SphinxDecoder * sd : decoders) {
sd->updateLM(pathToLM, false);
}
}
void SphinxService::updateLogPath(std::string pathToLog) {
for(SphinxDecoder * sd : decoders) {
sd->updateLoggingFile(pathToLog, false);
}
}
void SphinxService::updateSearchMode(SphinxHelper::SearchMode mode) {
for(SphinxDecoder * sd : decoders) {
sd->updateSearchMode(mode, false);
}
}
void SphinxService::setJSGF(Grammar * g) {
///TODO: Save Grammar to a temp file, pass the path of the temp file on to the sphinx decoders
cppfs::FileHandle t = Buckey::getInstance()->getTempFile(".gram");
t.writeFile("#JSGF V1.0;\n" + g->getText());
updateJSGFPath(t.path());
}
/// Applies previous updates and also initializes decoders if there weren't already when this object was constructed.
void SphinxService::applyUpdates() {
updateLock.lock();
Buckey::logInfo("Starting to apply updates.");
auto start = high_resolution_clock::now();
if(isRecognizing()) { // Decoders are in use so reload the ones not in use
Buckey::logInfo("Attempting to update while recognizing...");
unsigned short k = decoders.size();
unsigned short decodersDone[k];
unsigned short decoderDoneCount = 0;
while(decoderDoneCount != decoders.size()) {
for(unsigned short i = 0; i < decoders.size(); i++) {
unsigned short * c = std::find(decodersDone, decodersDone+k, i);
if(c != decodersDone+k) {
// This one was already updated, let it go
}
else {
//Not updated yet
if(i == currentDecoderIndex) {
if(!inUtterance) {
if(decoderDoneCount > 0) {
decoderIndexLock.lock();
currentDecoderIndex.store(decodersDone[0]);
decoderIndexLock.unlock();
}
}
}
else {
if(decoders[i]->getState() == SphinxHelper::DecoderState::UTTERANCE_STARTED) {
decoders[i]->reloadDecoder();
decoders[i]->startUtterance();
decodersDone[decoderDoneCount] = i;
decoderDoneCount++;
}
}
}
}
}
}
else { // Decoders are not in use so restart them all now
Buckey::logInfo("Applying updates while not recognizing...");
for(unsigned short i = 0; i < decoders.size(); i++) {
decoders[i]->reloadDecoder();
decoders[i]->startUtterance();
if(i == 0) { // Select the first decoder that we update so it is ready ASAP
decoderIndexLock.lock();
currentDecoderIndex.store(0);
decoderIndexLock.unlock();
}
}
}
Buckey::logInfo("Decoder Update Applied");
updateLock.unlock();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
std::cout << "Time to apply decoder update: " << duration.count() << std::endl;
}
bool SphinxService::isRecognizing() {
return recognizing;
}
bool SphinxService::voiceFound() {
return voiceDetected.load();
}
SphinxDecoder * SphinxService::getDecoder(unsigned short decoderIndex) {
return decoders[decoderIndex];
}
void SphinxService::addOnSpeechStart(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_START_SPEECH, handler);
}
void SphinxService::addOnSpeechEnd(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_END_SPEECH, handler);
}
void SphinxService::addOnHypothesis(void(*handler)(EventData *, std::atomic<bool> *)) {
addListener(ON_HYPOTHESIS, handler);
}
void SphinxService::clearSpeechStartListeners() {
clearListeners(ON_START_SPEECH);
}
void SphinxService::clearSpeechEndListeners() {
clearListeners(ON_END_SPEECH);
}
void SphinxService::clearOnHypothesisListeners() {
clearListeners(ON_HYPOTHESIS);
}
void SphinxService::clearOnPauseListeners() {
clearListeners(ON_PAUSE);
}
void SphinxService::clearOnResumeListeners() {
clearListeners(ON_RESUME);
}
| 32.911408 | 245 | 0.668424 |
f4c255172c3cff4a99ca1c0952190ae2834d4131 | 848 | hpp | C++ | Object.hpp | LinarAbdrazakov/MIPT_GAME | 55d96906cb60752c3907fb83ce70910879dc4ed8 | [
"MIT"
] | null | null | null | Object.hpp | LinarAbdrazakov/MIPT_GAME | 55d96906cb60752c3907fb83ce70910879dc4ed8 | [
"MIT"
] | null | null | null | Object.hpp | LinarAbdrazakov/MIPT_GAME | 55d96906cb60752c3907fb83ce70910879dc4ed8 | [
"MIT"
] | null | null | null | #ifndef OBJECT_HPP
#define OBJECT_HPP
#include <SFML/Graphics.hpp>
class Object
{
private:
int id_;
sf::Sprite* sprite_;
sf::Vector2f coordinate_;
sf::Vector2f speed_;
sf::Vector2i size_;
float* dt_;
public:
explicit Object();
Object(const Object&);
Object(int, sf::Vector2f, sf::Vector2f, sf::Vector2i, float*);
~Object();
const int GetId() const;
sf::Sprite* GetSprite() const;
const sf::Vector2f GetCoordinate() const;
const sf::Vector2f GetSpeed() const;
const sf::Vector2i GetSize() const;
float* GetDt() const;
void SetId (int);
void SetSprite (sf::Sprite*);
void SetCoordinate(sf::Vector2f);
void SetSpeed (sf::Vector2f);
void SetSize (sf::Vector2i);
void SetDt (float*);
};
#endif
| 22.315789 | 64 | 0.595519 |
f4c3d5422d8acf9ab1abf0cfabafd06a5f731f38 | 1,493 | hpp | C++ | lib/qt/LocationListComboBox.hpp | ncorgan/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 4 | 2017-06-10T13:21:44.000Z | 2019-10-30T21:20:19.000Z | lib/qt/LocationListComboBox.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 12 | 2017-04-05T11:13:34.000Z | 2018-06-03T14:31:03.000Z | lib/qt/LocationListComboBox.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 2 | 2019-01-22T21:02:31.000Z | 2019-10-30T21:20:20.000Z | /*
* Copyright (c) 2016,2018 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef PKMN_QT_LOCATIONLISTCOMBOBOX_HPP
#define PKMN_QT_LOCATIONLISTCOMBOBOX_HPP
#include <pkmn/config.hpp>
#ifdef PKMN_ENABLE_QT
#include <QComboBox>
#include <QString>
#else
#error Qt support is not enabled in this build of LIbPKMN.
#endif
namespace pkmn { namespace qt {
/*!
* @brief A ComboBox populated with an alphabetized list of locations available in the given
* game (or generation).
*/
class PKMN_API LocationListComboBox: public QComboBox
{
Q_OBJECT
public:
/*!
* @brief Constructor.
*
* Note: even if wholeGeneration is set to true, Game Boy Advance locations will not appear in
* a list of Gamecube locations, and vice versa.
*
* \param game which game
* \param wholeGeneration include locations from all games in this generation
* \param parent parent widget
* \throws std::invalid_argument if the given game is invalid
*/
LocationListComboBox(
const QString& game,
bool wholeGeneration,
QWidget* parent
);
signals:
public slots:
};
}}
#endif /* PKMN_QT_LOCATIONLISTCOMBOBOX_HPP */
| 27.145455 | 106 | 0.618218 |
f4c4917cbb9b86920862bb09496beeb71e3ec2c3 | 3,786 | cpp | C++ | src/VideoDevice.cpp | nayanavenkataramana/earlyapp | eafd8ae8507dee79d2b751f7c5d9320f5519029b | [
"MIT"
] | 5 | 2019-01-02T18:34:52.000Z | 2021-05-13T16:09:10.000Z | src/VideoDevice.cpp | nayanavenkataramana/earlyapp | eafd8ae8507dee79d2b751f7c5d9320f5519029b | [
"MIT"
] | 10 | 2018-10-26T06:11:45.000Z | 2019-06-24T06:25:43.000Z | src/VideoDevice.cpp | nayanavenkataramana/earlyapp | eafd8ae8507dee79d2b751f7c5d9320f5519029b | [
"MIT"
] | 20 | 2018-10-26T02:16:51.000Z | 2021-02-17T11:39:59.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 Intel Corporation
//
// 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.
//
// SPDX-License-Identifier: MIT
//
////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <boost/format.hpp>
#include "EALog.h"
#include "OutputDevice.hpp"
#include "VideoDevice.hpp"
#include "Configuration.hpp"
// A log tag for video device.
#define TAG "VIDEO"
namespace earlyapp
{
/*
Define a device instance variable.
*/
VideoDevice* VideoDevice::m_pVDev = nullptr;
/*
Destructor.
*/
VideoDevice::~VideoDevice(void)
{
if(m_pVDev != nullptr)
{
delete m_pVDev;
}
}
/*
A static function to get an instance(singleton).
*/
VideoDevice* VideoDevice::getInstance(void)
{
if(m_pVDev == nullptr)
{
LINF_(TAG, "Creating a VideoDevice instance");
m_pVDev = new VideoDevice();
}
return m_pVDev;
}
/*
Intialize
*/
void VideoDevice::init(std::shared_ptr<Configuration> pConf)
{
OutputDevice::init(pConf);
m_pDecPipeline = new CDecodingPipeline(m_pGPIOCtrl);
if(m_pDecPipeline == nullptr)
{
LERR_(TAG, "Failed to create decoder instance.");
return;
}
m_Params.bUseHWLib = true;
m_Params.bUseFullColorRange = false;
m_Params.videoType = MFX_CODEC_AVC;
m_Params.mode = MODE_RENDERING;
m_Params.memType = D3D9_MEMORY;
m_Params.mode = MODE_RENDERING;
// File path.
strcpy(m_Params.strSrcFile, pConf->videoSplashPath().c_str());
// Width
m_Params.Width = pConf->displayWidth();
// Height
m_Params.Height = pConf->displayHeight();
// Default ASync depth.
m_Params.nAsyncDepth = 4;
// Initialize decoding pipeline.
m_pDecPipeline->Init(&m_Params);
LINF_(TAG, "VideoDevice initialized.");
}
/*
Play the video device.
*/
void VideoDevice::play(void)
{
LINF_(TAG, "VideoDevice play");
// Start decoding and display.
m_pDecPipeline->RunDecoding();
}
/*
Stop.
*/
void VideoDevice::stop(void)
{
LINF_(TAG, "VideoDevice stop");
// Stop play
if(m_pDecPipeline)
{
delete m_pDecPipeline;
m_pDecPipeline = nullptr;
}
}
/*
Terminate
*/
void VideoDevice::terminate(void)
{
LINF_(TAG, "VideoDevice terminate");
// TODO: release resources.
}
} // namespace
| 25.409396 | 80 | 0.596408 |
f4c4ea6bac0a1d4a5e6e89bd188e9b83f1d875cb | 7,360 | cpp | C++ | src/caffe/layers/cross_correlation_layer.cpp | NicoleWang/caffe-for-rfcn | fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/cross_correlation_layer.cpp | NicoleWang/caffe-for-rfcn | fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/cross_correlation_layer.cpp | NicoleWang/caffe-for-rfcn | fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d | [
"BSD-2-Clause"
] | null | null | null | #include <algorithm>
#include <cfloat>
#include <vector>
#include "caffe/layers/cross_correlation_layer.hpp"
#include "caffe/util/math_functions.hpp"
#define DEBUG_INFO
#undef DEBUG_INFO
namespace caffe {
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
// std::cout << "Enter cross relation reshape function" << std::endl;
//delete bottom size constraint
//bottom[0]: feature map from last layer
//bottom[1]: kernel
const int first_spatial_axis = this->channel_axis_ + 1;
CHECK_EQ(bottom[0]->num_axes(), first_spatial_axis + this->num_spatial_axes_)
<< "bottom num_axes may not change.";
this->num_ = bottom[0]->count(0, this->channel_axis_);
CHECK_EQ(bottom[0]->shape(this->channel_axis_), this->channels_)
<< "Input size incompatible with convolution kernel.";
// TODO: generalize to handle inputs of different shapes.
// for (int bottom_id = 1; bottom_id < bottom.size(); ++bottom_id) {
// CHECK(bottom[0]->shape() == bottom[bottom_id]->shape())
// << "All inputs must have the same shape.";
// }
// Shape the tops.
this->bottom_shape_ = &bottom[0]->shape();
this->compute_output_shape();
vector<int> top_shape(bottom[0]->shape().begin(),
bottom[0]->shape().begin() + this->channel_axis_);
top_shape.push_back(this->num_output_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
top_shape.push_back(this->output_shape_[i]);
}
for (int top_id = 0; top_id < top.size(); ++top_id) {
top[top_id]->Reshape(top_shape);
}
if (this->reverse_dimensions()) {
this->conv_out_spatial_dim_ = bottom[0]->count(first_spatial_axis);
} else {
this->conv_out_spatial_dim_ = top[0]->count(first_spatial_axis);
}
this->col_offset_ = this->kernel_dim_ * this->conv_out_spatial_dim_;
this->output_offset_ = this->conv_out_channels_ * this->conv_out_spatial_dim_ / this->group_;
// Setup input dimensions (conv_input_shape_).
vector<int> bottom_dim_blob_shape(1, this->num_spatial_axes_ + 1);
this->conv_input_shape_.Reshape(bottom_dim_blob_shape);
int* conv_input_shape_data = this->conv_input_shape_.mutable_cpu_data();
for (int i = 0; i < this->num_spatial_axes_ + 1; ++i) {
if (this->reverse_dimensions()) {
conv_input_shape_data[i] = top[0]->shape(this->channel_axis_ + i);
} else {
conv_input_shape_data[i] = bottom[0]->shape(this->channel_axis_ + i);
}
}
// The im2col result buffer will only hold one image at a time to avoid
// overly large memory usage. In the special case of 1x1 convolution
// it goes lazily unused to save memory.
this->col_buffer_shape_.clear();
this->col_buffer_shape_.push_back(this->kernel_dim_ * this->group_);
for (int i = 0; i < this->num_spatial_axes_; ++i) {
if (this->reverse_dimensions()) {
this->col_buffer_shape_.push_back(this->input_shape(i + 1));
} else {
this->col_buffer_shape_.push_back(this->output_shape_[i]);
}
}
this->col_buffer_.Reshape(this->col_buffer_shape_);
this->bottom_dim_ = bottom[0]->count(this->channel_axis_);
this->top_dim_ = top[0]->count(this->channel_axis_);
this->num_kernels_im2col_ = this->conv_in_channels_ * this->conv_out_spatial_dim_;
this->num_kernels_col2im_ = this->reverse_dimensions() ? this->top_dim_ : this->bottom_dim_;
// Set up the all ones "bias multiplier" for adding biases by BLAS
this->out_spatial_dim_ = top[0]->count(first_spatial_axis);
if (this->bias_term_) {
vector<int> bias_multiplier_shape(1, this->out_spatial_dim_);
this->bias_multiplier_.Reshape(bias_multiplier_shape);
caffe_set(this->bias_multiplier_.count(), Dtype(1),
this->bias_multiplier_.mutable_cpu_data());
}
}
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
const Dtype* weight = bottom[1]->cpu_data();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
for (int n = 0; n < this->num_; ++n) {
this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight,
top_data + n * this->top_dim_);
if (this->bias_term_) {
const Dtype* bias = this->blobs_[1]->cpu_data();
this->forward_cpu_bias(top_data + n * this->top_dim_, bias);
}
}
}
template <typename Dtype>
void CrossCorrelationLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
const Dtype* weight = bottom[1]->cpu_data();
Dtype* weight_diff = bottom[1]->mutable_cpu_diff();
for (int i = 0; i < 1; ++i) {
Dtype* top_diff = top[i]->mutable_cpu_diff();
/*
const Dtype* tdata = top[i]->cpu_diff();
std::cout << " CROSS WEIGHT DIFF: " << std::endl;
for (int j = 0; j < top[i]->count(); ++j) {
std::cout << tdata[j] << " ";
}
std::cout << std::endl << std::endl << std::endl;
*/
const Dtype* bottom_data = bottom[i]->cpu_data();
Dtype* bottom_diff = bottom[i]->mutable_cpu_diff();
// Bias gradient, if necessary.
if (this->bias_term_) {
Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff();
for (int n = 0; n < this->num_; ++n) {
this->backward_cpu_bias(bias_diff, top_diff + n * this->top_dim_);
}
}
if (this->param_propagate_down_[0] || propagate_down[i]) {
for (int n = 0; n < this->num_; ++n) {
// gradient w.r.t. weight. Note that we will accumulate diffs.
if (this->param_propagate_down_[0] || true) {
this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_,
top_diff + n * this->top_dim_, weight_diff);
}
// gradient w.r.t. bottom data, if necessary.
if (propagate_down[i]) {
this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight,
bottom_diff + n * this->bottom_dim_);
}
}
}
}//end of for
#ifdef DEBUG_INFO
if (this->layer_param().name() == "cross" || true) {
const Dtype* top_diff_0 = top[0]->cpu_diff();
const Dtype* bottom_diff_0 = bottom[0]->cpu_data();
const Dtype* bottom_diff_1 = bottom[1]->cpu_data();
Dtype sum_top_0 = 0.0, sum_bottom_0 = 0.0, sum_bottom_1 = 0.0;
std::cout << "top diff: " << std::endl;
for (int i = 0; i < top[0]->count(); ++i) {
//std::cout << top_diff_0[i] << " ";
sum_top_0 += top_diff_0[i];
}
std::cout << std::endl;
std::cout << "bottom 0 diff: " << std::endl;
for (int i = 0; i < 50; ++i) {
std::cout << bottom_diff_0[i * 50] << " ";
sum_bottom_0 += bottom_diff_0[i];
}
std::cout << std::endl;
std::cout << "bottom 1 diff: " << std::endl;
for (int i = 0; i < 50; ++i) {
std::cout << bottom_diff_1[i * 50] << " ";
sum_bottom_1 += bottom_diff_1[i];
}
std::cout << std::endl;
//std::cout << this->layer_param().name() << " cross top 0 bottom 0 1 diff: ";
//std::cout << sum_top_0 << " " << sum_bottom_0 << " " << sum_bottom_1 << std::endl;
}
#endif
}
#ifdef CPU_ONLY
STUB_GPU(CrossCorrelationLayer);
#endif
INSTANTIATE_CLASS(CrossCorrelationLayer);
REGISTER_LAYER_CLASS(CrossCorrelation);
} // namespace caffe
| 40.43956 | 95 | 0.640353 |
f4c62a895f625fee35ffda86d37a343556908493 | 4,779 | cxx | C++ | PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWG/FLOW/Tasks/AliAnalysisTaskLYZEventPlane.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <stdlib.h>
#include "Riostream.h" //needed as include
#include "TChain.h"
#include "TTree.h"
#include "TProfile.h"
#include "TFile.h"
#include "TList.h"
class AliAnalysisTaskSE;
#include "AliAnalysisManager.h"
#include "AliFlowEventSimple.h"
#include "AliAnalysisTaskLYZEventPlane.h"
#include "AliFlowCommonHist.h"
#include "AliFlowCommonHistResults.h"
#include "AliFlowLYZEventPlane.h"
#include "AliFlowAnalysisWithLYZEventPlane.h"
// AliAnalysisTaskLYZEventPlane:
//
// analysis task for Lee Yang Zeros Event Plane
//
// Author: Naomi van der Kolk (kolk@nikhef.nl)
using std::cout;
using std::endl;
ClassImp(AliAnalysisTaskLYZEventPlane)
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane(const char *name) :
AliAnalysisTaskSE(name),
fEvent(NULL),
fLyzEp(NULL),
fLyz(NULL),
fListHistos(NULL),
fSecondRunFile(NULL)
{
// Constructor
cout<<"AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane(const char *name)"<<endl;
// Define input and output slots here
// Input slot #0 works with an AliFlowEventSimple
DefineInput(0, AliFlowEventSimple::Class());
DefineInput(1, TList::Class());
// Output slot #0 writes into a TList container
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane() :
AliAnalysisTaskSE(),
fEvent(NULL),
fLyzEp(NULL),
fLyz(NULL),
fListHistos(NULL),
fSecondRunFile(NULL)
{
// Constructor
cout<<"AliAnalysisTaskLYZEventPlane::AliAnalysisTaskLYZEventPlane()"<<endl;
}
//________________________________________________________________________
AliAnalysisTaskLYZEventPlane::~AliAnalysisTaskLYZEventPlane()
{
//destructor
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::UserCreateOutputObjects()
{
// Called once
cout<<"AliAnalysisTaskLYZEventPlane::CreateOutputObjects()"<<endl;
//lee yang zeros event plane
fLyzEp = new AliFlowLYZEventPlane() ;
//Analyser
fLyz = new AliFlowAnalysisWithLYZEventPlane() ;
// Get data from input slot
TList* pSecondRunList = (TList*)GetInputData(1);
if (pSecondRunList) {
fLyzEp -> SetSecondRunList(pSecondRunList);
fLyz -> SetSecondRunList(pSecondRunList);
} else { cout<<"No Second run List!"<<endl; exit(0); }
fLyzEp-> Init();
fLyz-> Init();
if (fLyz->GetHistList()) {
fListHistos = fLyz->GetHistList();
//fListHistos->Print();
}
else { cout<<"ERROR: Could not retrieve histogram list"<<endl;}
PostData(1,fListHistos);
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::UserExec(Option_t *)
{
// Main loop
// Called for each event
fEvent = dynamic_cast<AliFlowEventSimple*>(GetInputData(0));
if (fEvent) {
fLyz->Make(fEvent,fLyzEp);
}
else {
cout << "Warning no input data!!!" << endl;}
PostData(1,fListHistos);
}
//________________________________________________________________________
void AliAnalysisTaskLYZEventPlane::Terminate(Option_t *)
{
// Called once at the end of the query
AliFlowAnalysisWithLYZEventPlane* lyzTerm = new AliFlowAnalysisWithLYZEventPlane() ;
fListHistos = (TList*)GetOutputData(1);
//cout << "histogram list in Terminate" << endl;
if (fListHistos) {
lyzTerm -> GetOutputHistograms(fListHistos);
lyzTerm -> Finish();
PostData(1,fListHistos);
//fListHistos->Print();
} else { cout << "histogram list pointer is empty" << endl;}
//cout<<".....finished LYZ EventPlane"<<endl;
delete lyzTerm;
}
| 31.235294 | 93 | 0.686545 |
f4cab2b2c4c57009bb838b1d3b13e58fcdb8e847 | 787 | cpp | C++ | backend/sgx/trusted/src/encryption.cpp | alxshine/eNNclave | 639aa7e8df9440922788d0c2a79846b198f117aa | [
"MIT"
] | null | null | null | backend/sgx/trusted/src/encryption.cpp | alxshine/eNNclave | 639aa7e8df9440922788d0c2a79846b198f117aa | [
"MIT"
] | null | null | null | backend/sgx/trusted/src/encryption.cpp | alxshine/eNNclave | 639aa7e8df9440922788d0c2a79846b198f117aa | [
"MIT"
] | null | null | null | #include "encryption.h"
#include "sgxParameterLoader.h"
#include <memory>
#include "output.h"
using namespace eNNclave;
using namespace std;
namespace
{
std::unique_ptr<SgxParameterLoader> parameterLoader;
} // namespace
void open_encrypted_parameters()
{
parameterLoader = std::unique_ptr<SgxParameterLoader>(new SgxParameterLoader("backend/generated/parameters.bin.aes", true)); // TODO: handle potential exception
}
int encrypt_parameters(float *target_buffer, int num_elements){
try{
parameterLoader->WriteParameters(target_buffer, num_elements);
}catch(logic_error e){
print_err(e.what());
return 1;
}
return 0;
};
void close_encrypted_parameters()
{
auto *actualLoader = parameterLoader.release();
delete actualLoader;
} | 23.848485 | 164 | 0.733164 |
f4cb58df8bc7c0e402744e2a1a91c261ba5edabc | 1,797 | cpp | C++ | src/Display.cpp | yann-boyer/OKUR | f575dbd3d06fa8f669bfadc2918e757168e231be | [
"Zlib"
] | 1 | 2022-03-22T15:10:44.000Z | 2022-03-22T15:10:44.000Z | src/Display.cpp | yann-boyer/OKUR | f575dbd3d06fa8f669bfadc2918e757168e231be | [
"Zlib"
] | null | null | null | src/Display.cpp | yann-boyer/OKUR | f575dbd3d06fa8f669bfadc2918e757168e231be | [
"Zlib"
] | null | null | null | /*
This file is a part of OKUR.
This file contains code to emulate
Chip8 screen.
Copyright (c) 2022 - Yann BOYER.
*/
#include "Display.hpp"
Display::Display() {
chip8Window = SDL_CreateWindow(
"OKUR Chip8 Emu by Yann BOYER.",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
SDL_WINDOW_SHOWN |
SDL_WINDOW_OPENGL |
SDL_WINDOW_RESIZABLE |
SDL_WINDOW_ALLOW_HIGHDPI
);
if(chip8Window == nullptr) {
std::cerr << "Unable to create and initialize window !" << std::endl;
exit(EXIT_FAILURE);
}
chip8Renderer = SDL_CreateRenderer(chip8Window, -1, 0);
if(chip8Renderer == nullptr) {
std::cerr << "Unable to create and initialize renderer !" << std::endl;
exit(EXIT_FAILURE);
}
chip8Texture = SDL_CreateTexture(
chip8Renderer,
SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET,
SCREEN_WIDTH,
SCREEN_HEIGHT
);
if(chip8Texture == nullptr) {
std::cerr << "Unable to create and initialize texture !" << std::endl;
exit(EXIT_FAILURE);
}
SDL_SetRenderDrawColor(chip8Renderer, 0, 0, 0, 0);
SDL_RenderClear(chip8Renderer);
SDL_RenderPresent(chip8Renderer);
}
void Display::bufferGraphics(MMU &mmu) {
for(uint8_t y = 0; y < 32; y++) {
for(uint8_t x = 0; x < 64; x++) {
uint8_t pixel = mmu.gfx[y][x];
pixelBuffer[(y * SCREEN_WIDTH) + x] = (pixel * 0xFFFFFF00) | 0x000000FF;
}
}
}
void Display::drawGraphics(void) {
SDL_UpdateTexture(chip8Texture, NULL, pixelBuffer, SCREEN_WIDTH * sizeof(uint32_t));
SDL_RenderClear(chip8Renderer);
SDL_RenderCopy(chip8Renderer, chip8Texture, NULL, NULL);
SDL_RenderPresent(chip8Renderer);
}
void Display::destroyDisplay(void) {
SDL_DestroyWindow(chip8Window);
SDL_DestroyRenderer(chip8Renderer);
SDL_DestroyTexture(chip8Texture);
delete[] pixelBuffer;
SDL_Quit();
} | 23.337662 | 85 | 0.723984 |
f4d79e89943264d79c4041097bad11fe2e7f6c89 | 37,548 | cpp | C++ | 3p/ClassLib/Windows/window.cpp | stbrenner/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 2 | 2018-11-20T15:58:08.000Z | 2021-12-15T14:51:10.000Z | 3p/ClassLib/Windows/window.cpp | stbrenner/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 1 | 2016-12-27T08:26:27.000Z | 2016-12-27T08:26:27.000Z | 3p/ClassLib/Windows/window.cpp | ymx/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 1 | 2016-08-09T10:44:48.000Z | 2016-08-09T10:44:48.000Z | //
// window.cpp
//
// (C) Copyright 2000 Jan van den Baard.
// All Rights Reserved.
//
#include "window.h"
#include "mdiwindow.h"
#include "../application.h"
#include "../gdi/gdiobject.h"
#include "../gdi/dc.h"
#include "../menus/menu.h"
#include "../menus/bitmapmenu.h"
#include "../tools/multimonitor.h"
#include "../tools/xpcolors.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Just in case...
#ifndef WM_QUERYUISTATE
#define WM_CHANGEUISTATE 0x0127
#define WM_UPDATEUISTATE 0x0128
#define WM_QUERYUISTATE 0x0129
#endif
// Lists of all window objects created.
ClsLinkedList<ClsWindow> temporary_window_list;
ClsLinkedList<ClsWindow> global_window_list;
typedef BOOL ( CALLBACK *ANIMATEWINDOW )( HWND, DWORD, DWORD );
typedef BOOL ( CALLBACK *SETLAYEREDWINDOWATTRIBUTES )( HWND, COLORREF, BYTE, DWORD );
// Statics.
HMENU ClsWindow::s_hMenu = NULL;
HWND ClsWindow::s_hMDIClient = NULL;
static ANIMATEWINDOW StaticAnimateWindow = NULL;
static SETLAYEREDWINDOWATTRIBUTES StaticSetLayeredWindowAttributes = NULL;
// Defined in "bitmapmenu.cpp".
extern ClsLinkedList<ClsMenu> global_menu_list;
// Finds a window object in the list by it's handle
// value.
ClsWindow *ClsFindObjectByHandle( ClsLinkedList<ClsWindow>& list, HWND hWnd )
{
_ASSERT_VALID( hWnd ); // This must be valid.
_ASSERT( IsWindow( hWnd )); // Only window handles.
// Iterate the nodes.
for ( ClsWindow *pWindow = list.GetFirst(); pWindow; pWindow = list.GetNext( pWindow ))
{
// Is the handle wrapped by this object
// the one we are looking for?
if ( pWindow->GetSafeHWND() == hWnd )
// Yes. Return a pointer to the object.
return pWindow;
}
// Object not in the list.
return NULL;
}
// Constructor. Setup data field(s).
ClsWindow::ClsWindow()
{
// Setup window type.
m_bIsDialog = FALSE;
m_bIsMDIFrame = FALSE;
m_bIsPopup = FALSE;
// Clear data.
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
m_bDestroyHandle = TRUE;
s_hMenu = NULL;
// Add this object to the global list.
global_window_list.AddHead( this );
}
// Destructor. Destroys the window
// unless it is detached.
ClsWindow::~ClsWindow()
{
// Destroy the window.
Destroy();
// Remove us from the global list if we where
// still linked into it.
ClsWindow *pWindow;
for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow ))
{
// Is this us?
if ( pWindow == this )
{
// Yes. remove us from the list.
global_window_list.Remove( this );
return;
}
}
}
// Destroys the wrapped window if
// possible.
void ClsWindow::Destroy()
{
// Do we wrap a valid handle?
if ( GetSafeHWND())
{
// Destroy the window.
if ( m_bDestroyHandle )
// Destroy the handle.
::DestroyWindow( m_hWnd );
else
// Detach the handle to reset
// the original window procedure.
Detach();
}
}
// Detaches the window from the
// object.
HWND ClsWindow::Detach()
{
// Handle valid?
if ( GetSafeHWND())
{
// Did we subclass the window? If not we can't
// detach it. If we did the window would be left
// without a window procedure.
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Set back the original window procedure.
::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )m_lpfnOldWndProc );
// Get return code.
HWND hWnd = m_hWnd;
// Clear fields.
m_bIsDialog = FALSE;
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
// Return result.
return hWnd;
}
}
return NULL;
}
// Attach a window handle to this object. This will only
// work if this object does not already have a handle
// attached to it.
BOOL ClsWindow::Attach( HWND hWnd, BOOL bDestroy /* = FALSE */ )
{
_ASSERT_VALID( IsWindow( hWnd ) ); // Handle must be valid.
_ASSERT( GetSafeHWND() == NULL ); // Already has a handle.
// Is the handle already attached to
// another object? If so it may not
// be set to be destroyed by this object.
if ( bDestroy )
{
if ( ClsFindObjectByHandle( global_window_list, hWnd ) ||
ClsFindObjectByHandle( temporary_window_list, hWnd ))
{
_ASSERT( bDestroy == FALSE );
return FALSE;
}
}
// First we see if the handle is a normal window
// or a dialog.
TCHAR szClassName[ 10 ];
if ( ::GetClassName( hWnd, szClassName, 10 ))
{
// Is it a dialog?
m_bIsDialog = ( BOOL )( _tcscmp( _T( "#32770" ), szClassName ) == 0 );
// Save the handle.
m_hWnd = hWnd;
m_bDestroyHandle = bDestroy;
// Get the window procedure.
m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC );
// Is the window proc already our static
// window procedure?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Call the PreSubclassWindow() override.
PreSubclassWindow();
// Subclass the original window
// procedure.
::SetWindowLongPtr( hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc );
}
// Return success.
return TRUE;
}
// Failed.
m_lpfnOldWndProc = NULL;
m_hWnd = NULL;
return FALSE;
}
// Create the window.
BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hwndParent, HMENU nIDorHMenu )
{
_ASSERT( m_hWnd == NULL ); // Must be zero!
// Do we already have a handle?
if ( GetSafeHWND() )
return FALSE;
// Setup the CREATESTRUCT.
CREATESTRUCT cs;
cs.dwExStyle = dwExStyle;
cs.lpszClass = lpszClassName;
cs.lpszName = lpszWindowName;
cs.style = dwStyle;
cs.x = x;
cs.y = y;
cs.cx = nWidth;
cs.cy = nHeight;
cs.hwndParent = hwndParent;
cs.hMenu = nIDorHMenu;
cs.lpCreateParams = 0L;
// Call the PreCreateWindow() function.
if ( PreCreateWindow( &cs ))
{
_ASSERT_VALID( cs.lpszClass ); // This must be known by now!
// Create the window.
m_hWnd = ::CreateWindowEx( cs.dwExStyle,
cs.lpszClass,
cs.lpszName,
cs.style,
cs.x,
cs.y,
cs.cx,
cs.cy,
cs.hwndParent,
cs.hMenu,
ClsGetInstanceHandle(),
( LPVOID )this );
// Subclass the window.
if ( m_hWnd )
{
// We destroy the handle.
m_bDestroyHandle = TRUE;
// Get the window procedure.
m_lpfnOldWndProc = ( WNDPROC )::GetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC );
// Is the window proc already our static
// window procedure?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
{
// Call the PreSubclassWindow() override.
PreSubclassWindow();
// Subclass the original window
// procedure.
if ( ::SetWindowLongPtr( m_hWnd, m_bIsDialog ? DWL_DLGPROC : GWL_WNDPROC, ( LONG_PTR )ClsWindow::StaticWindowProc ))
// Return success.
return TRUE;
}
else
// Return success.
return TRUE;
}
// return success or failure.
return ( BOOL )( m_hWnd );
}
return FALSE;
}
// Create the window.
BOOL ClsWindow::Create( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const ClsRect& crBounds, HWND hwndParent, HMENU nIDorHMenu )
{
// Create the window.
return Create( dwExStyle, lpszClassName, lpszWindowName, dwStyle, crBounds.Left(), crBounds.Top(), crBounds.Width(), crBounds.Height(), hwndParent, nIDorHMenu );
}
// Modify the window style.
void ClsWindow::ModifyStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// First we get the current window style.
DWORD dwStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_STYLE );
// Change bits.
dwStyle &= ~dwRemove;
dwStyle |= dwAdd;
// Change the style.
::SetWindowLongPtr( m_hWnd, GWL_STYLE, ( LONG_PTR )( dwStyle | dwFlags ));
}
// Modify the extended window style.
void ClsWindow::ModifyExStyle( DWORD dwRemove, DWORD dwAdd, DWORD dwFlags /* = 0 */ )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// First we get the current window extended style.
DWORD dwExStyle = ( DWORD )::GetWindowLongPtr( m_hWnd, GWL_EXSTYLE );
// Change bits.
dwExStyle &= ~dwRemove;
dwExStyle |= dwAdd;
// Change the extended style.
::SetWindowLongPtr( m_hWnd, GWL_EXSTYLE, ( LONG_PTR )( dwExStyle | dwFlags ));
}
// Get the rectangle of a child window.
ClsRect ClsWindow::GetChildRect( UINT nID ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
ClsRect crRect;
GetChildRect( crRect, nID );
return crRect;
}
// Get the rectangle of a child window.
void ClsWindow::GetChildRect( ClsRect& crRect, UINT nID ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// Get the child window.
HWND hWndChild = ::GetDlgItem( m_hWnd, nID );
// OK?
if ( hWndChild )
{
// Get it's rectangle.
::GetWindowRect( hWndChild, crRect );
// Map to the window.
::MapWindowPoints( NULL, m_hWnd, ( LPPOINT )( LPRECT )crRect, 2 );
}
}
// Set the window text.
void ClsWindow::SetWindowText( LPCTSTR pszText )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// If the hi-order word of "pszText" is 0
// we load the string from the resources.
if ( pszText && HIWORD( pszText ) == 0 )
{
// Load the string.
ClsString str( pszText );
::SetWindowText( m_hWnd, str );
return;
}
// Set the text.
::SetWindowText( m_hWnd, pszText );
}
// Get the checked radion button.
int ClsWindow::GetCheckedRadioButton( int nIDFirstButton, int nIDLastButton )
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
// Get button checked states.
for ( int i = nIDFirstButton; i <= nIDLastButton; i++ )
{
// Is it checked?
if ( ::IsDlgButtonChecked( m_hWnd, i ))
return i;
}
return 0;
}
int ClsWindow::GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const
{ _ASSERT_VALID( GetSafeHWND() );
ClsWindow *pWindow = GetDlgItem( nID );
if ( pWindow )
return pWindow->GetWindowText( lpStr, nMaxCount );
return 0;
}
int ClsWindow::GetDlgItemText( int nID, ClsString& rString ) const
{
_ASSERT_VALID( GetSafeHWND() ); // Must be valid.
ClsWindow *pWindow = GetDlgItem( nID );
if ( pWindow )
return pWindow->GetWindowText( rString );
return 0;
}
void ClsWindow::DeleteTempObjects()
{
ClsWindow *pWindow;
// Remove all objects and delete them.
while (( pWindow = temporary_window_list.RemoveHead()) != NULL )
delete pWindow;
}
// Called just before the window is subclassed.
void ClsWindow::PreSubclassWindow()
{
}
// Called just before the window is created.
BOOL ClsWindow::PreCreateWindow( LPCREATESTRUCT pCS )
{
// Use default class if none is given.
if ( pCS->lpszClass == NULL )
pCS->lpszClass = _T( "ClsWindowClass" );
// Continue creating the window.
return TRUE;
}
// Handle message traffic.
LRESULT ClsWindow::HandleMessageTraffic()
{
BOOL bTranslate = FALSE;
MSG msg;
// Enter the message loop.
while ( GetMessage( &msg, NULL, 0, 0 ) > 0 )
{
// Accelerator?
if ( msg.hwnd == NULL || ( ClsGetApp()->TranslateAccelerator( &msg )))
continue;
// Is there an MDI client? If so try to translate the
// accelerators.
if ( ClsWindow::s_hMDIClient && TranslateMDISysAccel( ClsWindow::s_hMDIClient, &msg ))
continue;
// Get the message window object. The message window may not
// be located in the global window list since it might be a
// child of the window located in the global window list.
//
// For example the messages from a edit control in a combobox
// control. In this case, when the message window is not found,
// we look up it's parent in the global window list.
ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, msg.hwnd );
if ( pWindow == NULL && IsChild( msg.hwnd )) pWindow = ClsFindObjectByHandle( global_window_list, ::GetParent( msg.hwnd ));
// Call the PreTranslateMessage() function to pre-process
// the message.
if ( pWindow )
{
bTranslate = pWindow->PreTranslateMessage( &msg );
}
else
{
// A dialog message for the active window?
bTranslate = ::IsDialogMessage( GetActiveWindow(), &msg );
if ( ! bTranslate )
{
// Is it a child window? If so we iterate the
// parent windows until we find one that
// translates the message or has no parent.
if ( IsChild( msg.hwnd ))
{
HWND hParent = ::GetParent( msg.hwnd );
ClsWindow *pTemp;
// Does the parent exist?
if ( hParent )
{
// Wrap the handle.
pTemp = ClsWindow::FromHandle( hParent );
// Do a translation.
if ( ! pTemp->PreTranslateMessage( &msg ))
{
// The message did not translate. Iterate until we
// find a parent which does.
while (( hParent = ::GetParent( hParent )) != NULL )
{
// Wrap the handle.
pTemp = ClsWindow::FromHandle( hParent );
// Does this one translate?
if ( pTemp->PreTranslateMessage( &msg ) == TRUE )
{
// Yes. Break up the loop.
bTranslate = TRUE;
break;
}
}
}
else
// Message was translated.
bTranslate = TRUE;
}
else
{
// Try it as a dialog message for the active window.
bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg );
}
}
else
{
// Try it as a dialog message for the active window.
bTranslate = ::IsDialogMessage( ::GetActiveWindow(), &msg );
}
}
}
// Can we dispatch?
if ( ! bTranslate )
{
// Message was not handled. Dispatch it.
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
// Delete temporary GDI, Window and (Bitmap)Menu objects.
ClsGdiObject::DeleteTempObjects();
ClsMenu::DeleteTempObjects();
ClsBitmapMenu::DeleteTempObjects();
ClsWindow::DeleteTempObjects();
}
// Return the result.
return ( LRESULT )msg.wParam;
}
// Called just after the WM_NCDESTROY message
// was handled.
void ClsWindow::PostNcDestroy()
{
// Reset variables.
m_bIsDialog = FALSE;
m_hWnd = NULL;
m_lpfnOldWndProc = NULL;
}
// Returns FALSE by default.
BOOL ClsWindow::PreTranslateMessage( LPMSG pMsg )
{
// Are we a dialog? If so see if the message can be
// processed by IsDialogMessage.
if ( m_bIsDialog && IsDialogMessage( pMsg ))
return TRUE;
// Are we a child window? If so we see if our parent
// is a dialog and let it have a go at the message
// first.
ClsWindow *pParent = GetParent();
if ( pParent /*&& pParent->m_bIsDialog*/ && pParent->IsDialogMessage( pMsg ))
return TRUE;
// Message not processed.
return FALSE;
}
// WM_COMMAND message handler.
LRESULT ClsWindow::OnCommand( UINT nNotifyCode, UINT nCtrlID, HWND hWndCtrl )
{
// Not handled.
return -1;
}
// Reflected WM_COMMAND message handler.
LRESULT ClsWindow::OnReflectedCommand( UINT nNotifyCode, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_NOTIFY message handler.
LRESULT ClsWindow::OnNotify( LPNMHDR pNMHDR )
{
// Not handled.
return -1;
}
// Reflected WM_NOTIFY message handler.
LRESULT ClsWindow::OnReflectedNotify( LPNMHDR pNMHDR, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_PAINT message handler.
LRESULT ClsWindow::OnPaint( ClsDC *pDC )
{
// Not handled.
return -1;
}
// WM_ERASEBKGND message handler.
LRESULT ClsWindow::OnEraseBkgnd( ClsDC *pDC )
{
// Not handled.
return -1;
}
// WM_SIZE message handler.
LRESULT ClsWindow::OnSize( UINT nSizeType, int nWidth, int nHeight )
{
// Not handled.
return -1;
}
// WM_MOVE message handler.
LRESULT ClsWindow::OnMove( int xPos, int yPos )
{
// Not handled.
return -1;
}
// WM_DESTROY message handler.
LRESULT ClsWindow::OnDestroy()
{
// Not handled.
return -1;
}
// WM_CLOSE message handler.
LRESULT ClsWindow::OnClose()
{
// Not handled.
return -1;
}
// WM_MEASUREITEM message handler.
LRESULT ClsWindow::OnMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis )
{
// Not handled.
return -1;
}
// WM_DRAWITEM message handler.
LRESULT ClsWindow::OnDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis )
{
// Not handled.
return -1;
}
// Reflected WM_MEASUREITEM message handler.
LRESULT ClsWindow::OnReflectedMeasureItem( UINT nID, LPMEASUREITEMSTRUCT pMis, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// Reflected WM_DRAWITEM message handler.
LRESULT ClsWindow::OnReflectedDrawItem( UINT nID, LPDRAWITEMSTRUCT pDis, BOOL& bNotifyParent )
{
// Not handled.
return -1;
}
// WM_CREATE message handler.
LRESULT ClsWindow::OnCreate( LPCREATESTRUCT pCS )
{
// Not handled. Note this is a special case. -1
// means failure with WM_CREATE messages.
return -2;
}
// Window procedure.
LRESULT ClsWindow::WindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam )
{
LRESULT lResult = 0;
// Do we have an original window procedure to call?
if ( m_lpfnOldWndProc && m_lpfnOldWndProc != ( WNDPROC )ClsWindow::StaticWindowProc )
// Call the original window procedure.
lResult = ::CallWindowProc( m_lpfnOldWndProc, GetSafeHWND(), uMsg, wParam, lParam );
else if ( m_bIsDialog == FALSE )
{
// Are we an MDI frame?
if ( m_bIsMDIFrame )
// Call the default procedure for MDI frames.
//
// The casting of the this pointer I do here is dangerous. If someone
// decides to create a "ClsWindow" derived class and set the "m_bIsMDIFrame"
// we are screwed. For now it works but I should consider another approach...
lResult = ::DefFrameProc( GetSafeHWND(), reinterpret_cast< ClsMDIMainWindow * >( this )->GetMDIClient()->GetSafeHWND(), uMsg, wParam, lParam );
else
// Call the default window procedure.
lResult = ::DefWindowProc( GetSafeHWND(), uMsg, wParam, lParam );
}
// Return the result.
return lResult;
}
// By default we use the current window size...
BOOL ClsWindow::OnGetMinSize( ClsSize& szMinSize )
{
ClsRect rc;
GetWindowRect( rc );
szMinSize = rc.Size();
return TRUE;
}
// Operator overload.
ClsWindow::operator HWND() const
{
return m_hWnd;
}
LRESULT CALLBACK ClsWindow::StaticWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// We will need this.
ClsWindow *pWindow = NULL;
BOOL bFromTemp = FALSE;
// Do we need to attach the handle to it's
// object?
if ( uMsg == WM_NCCREATE )
{
// The object pointer of this window must be
// passed using the lParam field of the
// CREATESTRUCT structure.
pWindow = ( ClsWindow * )(( LPCREATESTRUCT )lParam )->lpCreateParams;
// Should be valid.
//_ASSERT_VALID( pWindow );
// Attach us to the object.
if ( pWindow ) pWindow->Attach( hWnd, TRUE );
}
else if ( uMsg == WM_INITDIALOG )
{
_ASSERT_VALID( lParam ); // Must be a valid pointer.
// First we check to see if the lParam parameter is
// an object from our global window list.
for ( pWindow = global_window_list.GetFirst(); pWindow != ( ClsWindow * )lParam && pWindow; pWindow = global_window_list.GetNext( pWindow ));
// If the object was not found in the list it must be
// a PROPSHEETPAGE pointer. In this case the object should
// be in the lParam field of this structure.
if ( pWindow == NULL )
pWindow = ( ClsWindow * )(( PROPSHEETPAGE * )lParam )->lParam;
// Should be valid.
_ASSERT_VALID( pWindow );
// Attach us to the object.
pWindow->Attach( hWnd, TRUE );
}
else
{
// When we reach this place the handle must be attached
// already.
pWindow = ClsFindObjectByHandle( global_window_list, hWnd );
if ( pWindow == NULL )
{
// We were not located in the globals list
// so we must be in the temporary list.
bFromTemp = TRUE;
pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd );
}
}
// Do we have a valid object pointer?
if ( pWindow != NULL && pWindow->GetSafeHWND() )
{
// Preset message result.
LRESULT lResult = -1;
// Get message type.
switch ( uMsg )
{
case WM_UPDATEUISTATE:
case WM_SYSCOLORCHANGE:
// Update XP colorschemes.
XPColors.CreateColorTable();
// Pass on to the children.
EnumChildWindows( pWindow->GetSafeHWND(), DistributeMessage, WM_SYSCOLORCHANGE );
// Fall through when the message was WM_UPDATEUISTATE...
if ( uMsg == WM_SYSCOLORCHANGE )
break;
case WM_CHANGEUISTATE:
// Are we a child window?
if ( pWindow->GetStyle() & WS_CHILD )
// Repaint...
pWindow->Invalidate();
break;
case WM_CREATE:
// Call virtual message handler.
lResult = pWindow->OnCreate(( LPCREATESTRUCT )lParam );
break;
case WM_CLOSE:
// Call virtual message handler.
lResult = pWindow->OnClose();
break;
case WM_DESTROY:
{
// Does this window have a menu?
HMENU hMenu = pWindow->GetMenu();
if ( hMenu )
{
// See if it is wrapped by an object in the global
// menu list.
for ( ClsMenu *pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu ))
{
// Is this it?
if ( *pMenu == hMenu )
{
// We detach the menu from the window before the window
// destroys the menu handle. This is necessary because the
// destructor of "ClsBitmapMenu" derived classes need the
// handle valid to free used resources.
pWindow->SetMenu( NULL );
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnDestroy();
break;
}
case WM_MOVE:
// Call virtual message handler.
lResult = pWindow->OnMove(( int )LOWORD( lParam ), ( int )HIWORD( lParam ));
break;
case WM_SIZE:
// Call virtual message handler.
lResult = pWindow->OnSize(( UINT )wParam, ( int )LOWORD( lParam ), ( int )HIWORD( lParam ));
break;
case WM_PAINT:
{
// Do we have a DC?
ClsDC *pDC = wParam ? ClsDC::FromHandle(( HDC )wParam ) : NULL;
// Call virtual message handler.
lResult = pWindow->OnPaint( pDC );
break;
}
case WM_ERASEBKGND:
{
// Wrap handle.
ClsDC *pDC = ClsDC::FromHandle(( HDC )wParam );
// Call virtual message handler.
lResult = pWindow->OnEraseBkgnd( pDC );
break;
}
case WM_INITMENU:
// Store the menu handle which just opened.
ClsWindow::s_hMenu = ( HMENU )wParam;
// OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenu() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedInitMenu( pWindow );
}
break;
case WM_INITMENUPOPUP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedInitMenuPopup( pWindow, ( HMENU )wParam, LOWORD( lParam ), HIWORD( lParam ));
}
break;
case WM_UNINITMENUPOPUP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedUnInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedUnInitMenuPopup( pWindow, ( HMENU )wParam, lParam );
}
break;
case WM_EXITMENULOOP:
// Menu handle OK?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Get object and call OnReflectedInitMenuPopup() overidable.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu ) pMenu->OnReflectedExitMenuLoop( pWindow, ( BOOL )wParam );
}
// Clear the menu handle.
ClsWindow::s_hMenu = NULL;
break;
case WM_MEASUREITEM:
// Control?
if ( wParam )
{
// Try to get the window object of the control.
ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPMEASUREITEMSTRUCT )lParam )->CtlID ));
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the measure item message to the child
// window.
lResult = pChild->OnReflectedMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
else
{
// Find the menu.
if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu();
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Wrap the handle.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu )
{
// Call the overidable.
lResult = pMenu->OnReflectedMeasureItem(( LPMEASUREITEMSTRUCT ) lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnMeasureItem(( UINT )wParam, ( LPMEASUREITEMSTRUCT )lParam );
break;
case WM_DRAWITEM:
// Control?
if ( wParam )
{
// Try to get the window object of the control.
ClsWindow *pChild = pWindow->FromHandle( pWindow->GetDlgItemHandle((( LPDRAWITEMSTRUCT )lParam )->CtlID ));
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the draw item message to the child
// window.
lResult = pChild->OnReflectedDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
else
{
// Find the menu.
if ( ! ClsWindow::s_hMenu ) ClsWindow::s_hMenu = pWindow->GetMenu();
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Wrap the handle.
ClsMenu *pMenu = ClsMenu::FromHandle( ClsWindow::s_hMenu );
if ( pMenu )
{
// Call the overidable.
lResult = pMenu->OnReflectedDrawItem(( LPDRAWITEMSTRUCT )lParam, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
}
// Call virtual message handler.
lResult = pWindow->OnDrawItem(( UINT )wParam, ( LPDRAWITEMSTRUCT )lParam );
break;
case WM_COMMAND:
{
// Message originates from a control?
if ( lParam )
{
// Try to get the window object of the control which
// sent the message.
ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, ( HWND )lParam );
// Found it?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the command message to the child
// window.
lResult = pChild->OnReflectedCommand(( UINT )HIWORD( wParam ), bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Should we notify the parent?
if ( ! bNotifyParent )
break;
}
}
// Call virtual message handler.
lResult = pWindow->OnCommand(( UINT )HIWORD( wParam ), ( UINT )LOWORD( wParam ), ( HWND )lParam );
break;
}
case WM_NOTIFY:
LPNMHDR pNMHDR = ( LPNMHDR )lParam;
// Try to get the window object of the
// notification control.
ClsWindow *pChild = ClsFindObjectByHandle( global_window_list, pNMHDR->hwndFrom );
// Where we able to find the object in our
// global list?
if ( pChild )
{
// By default we do notify the parent.
BOOL bNotifyParent = TRUE;
// Reflect the notification message to the
// child window.
lResult = pChild->OnReflectedNotify( pNMHDR, bNotifyParent );
// Are we a dialog?
if ( lResult != -1 && pWindow->IsDialog())
{
// Set message result.
pWindow->SetWindowLong64( DWL_MSGRESULT, ( LONG_PTR )lResult );
lResult = TRUE;
}
// Must we notify the parent?
if ( ! bNotifyParent )
break;
}
// Simply forward the message.
pWindow->OnNotify( pNMHDR );
break;
}
// Are we still alive?
//if ( ! bFromTemp )
// for ( ClsWindow *pTmp = global_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = global_window_list.GetNext( pTmp ));
//else
// for ( ClsWindow *pTmp = temporary_window_list.GetFirst(); pTmp != pWindow && pTmp; pTmp = temporary_window_list.GetNext( pTmp ));
//
// We may not have been deleted by any of the virtual
// message handlers!
//_ASSERT( pTmp != NULL );
// If the message was not handled (lResult is -1) and the
// object window handle is still valid we call the virtual
// window procedure.
//
// Note: The WM_CREATE message is a special case which returns
// -2 when the message was not handled since -1 indicates that
// the window should not be created when -1 is returned.
if ((( lResult == -1 && uMsg != WM_CREATE ) || ( lResult == -2 && uMsg == WM_CREATE )) && pWindow->GetSafeHWND())
// Call the procedure.
lResult = pWindow->WindowProc( uMsg, wParam, lParam );
// Are we being destroyed?
if ( uMsg == WM_NCDESTROY )
{
// detach the handle from the object.
if ( pWindow->GetSafeHWND())
{
// Detach the handle.
pWindow->Detach();
// Just in case these are not cleared which will
// happen when the window has the ClsWindow::StaticWindowProc
// as the default window procedure.
pWindow->m_hWnd = NULL;
pWindow->m_lpfnOldWndProc = NULL;
}
// Call the PostNcDestroy() routine if the class pointer
// still exists in the global window list.
ClsWindow *pTmp;
for ( pTmp = global_window_list.GetFirst(); pTmp; pTmp = global_window_list.GetNext( pTmp ))
{
// Is this it?
if ( pTmp == pWindow )
{
// Call it.
pWindow->PostNcDestroy();
return lResult;
}
}
}
// return the result of the message handling.
return lResult;
}
// We did not find the handle in our global
// window list which means that it was not (yet)
// attached to a ClsWindow object.
//
// In this case we simply let windows handle
// the messages.
TCHAR szClassName[ 10 ];
// Get the class name of the window.
if ( ::GetClassName( hWnd, szClassName, 10 ))
{
// Is it a dialog box? If so we return 0 and do not
// call the default window procedure.
if ( _tcscmp( _T( "#32770" ), szClassName ) == 0 )
return 0;
}
// Return the result of the default window
// procedure.
return ::DefWindowProc( hWnd, uMsg, wParam, lParam );
}
// Helper which will try to locate the window object of the
// given handle. If it does not find it it will create an
// object for it and append it to the temporary object list.
ClsWindow *ClsWindow::FindWindow( HWND hWnd )
{
// Return NULL if the input is NULL.
if ( hWnd == NULL ) return NULL;
// First we try to locate the handle in the
// global window list.
ClsWindow *pWindow = ClsFindObjectByHandle( global_window_list, hWnd );
// Found it?
if ( pWindow == NULL )
{
// No. Try to locate it in our temporary object list.
pWindow = ClsFindObjectByHandle( temporary_window_list, hWnd );
if ( pWindow == NULL )
{
// Not found. Create a new object.
pWindow = new ClsWindow;
pWindow->Attach( hWnd );
// Remove it from the global list and
// move it into the temporary object list.
global_window_list.Remove( pWindow );
temporary_window_list.AddHead( pWindow );
}
}
// Return the object.
return pWindow;
}
// Close all windows marked as being a popup.
void ClsWindow::ClosePopups()
{
// Iterate the global window list.
ClsWindow *pWindow;
for ( pWindow = global_window_list.GetFirst(); pWindow; pWindow = global_window_list.GetNext( pWindow ))
{
// A popup?
if ( pWindow->m_bIsPopup )
{
// Get a pointer to the next in the list. Close the popup
// and set the pointer to the next.
ClsWindow *pNext = global_window_list.GetNext( pWindow );
pWindow->SendMessage( WM_CLOSE );
pWindow = pNext;
}
}
// Iterate the temporary window list.
for ( pWindow = temporary_window_list.GetFirst(); pWindow; pWindow = temporary_window_list.GetNext( pWindow ))
{
// A popup?
if ( pWindow->m_bIsPopup )
{
// Get a pointer to the next in the list. Close the popup
// and set the pointer to the next.
ClsWindow *pNext = temporary_window_list.GetNext( pWindow );
pWindow->SendMessage( WM_CLOSE );
pWindow = pNext;
}
}
}
// Center the window on another window or
// on the desktop.
BOOL ClsWindow::CenterWindow( ClsWindow *pOn )
{
_ASSERT_VALID( GetSafeHWND() );
// Obtain the child window
// screen bounds.
ClsRect rc, prc, screen;
GetWindowRect( rc );
// Get the rectangle of the display monitor which
// the window intersects the most.
ClsMultiMon mon;
int nMonitor;
mon.MonitorNumberFromWindow( GetSafeHWND(), MONITOR_DEFAULTTONEAREST, nMonitor );
mon.GetMonitorRect( nMonitor, prc, TRUE );
screen = prc;
// Do we have a valid parent
// handle?
if ( pOn )
// Obtain the parent window
// screen bounds.
pOn->GetWindowRect( prc );
// Compute offsets...
int x = prc.Left() + (( prc.Width() / 2 ) - ( rc.Width() / 2 ));
int y = prc.Top() + (( prc.Height() / 2 ) - ( rc.Height() / 2 ));
// Make sure the whole window remains visible on the screen.
if (( x + rc.Width()) > screen.Right()) x = screen.Right() - rc.Width();
if ( x < screen.Left()) x = screen.Left();
if (( y + rc.Height()) > screen.Bottom()) y = screen.Bottom() - rc.Height();
if ( y < screen.Top()) y = screen.Top();
// Move the window so that it is
// centered.
return SetWindowPos( NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE );
}
// AnimateWindow() API.
BOOL ClsWindow::AnimateWindow( DWORD dwTime, DWORD dwFlags )
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Just in case...
#ifndef AW_HIDE
#define AW_HIDE 0x00010000
#endif
// Function known?
if ( StaticAnimateWindow )
return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags );
// Get the procedure address.
StaticAnimateWindow = ( ANIMATEWINDOW )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "AnimateWindow" );
if ( StaticAnimateWindow )
return ( *StaticAnimateWindow )( m_hWnd, dwTime, dwFlags );
return FALSE;
}
// SetLayeredWindowAttributes() API.
BOOL ClsWindow::SetLayeredWindowAttributes( COLORREF crKey, BYTE bAlpha, DWORD dwFlags )
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Function known?
if ( StaticSetLayeredWindowAttributes )
return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags );
// Get the procedure address.
StaticSetLayeredWindowAttributes = ( SETLAYEREDWINDOWATTRIBUTES )GetProcAddress( GetModuleHandle( _T( "user32.dll" )), "SetLayeredWindowAttributes" );
if ( StaticSetLayeredWindowAttributes )
return ( *StaticSetLayeredWindowAttributes )( m_hWnd, crKey, bAlpha, dwFlags );
return FALSE;
}
// Get a pointer to the active menu object.
ClsMenu *ClsWindow::GetActiveMenu()
{
// Is there an active menu?
if ( ClsWindow::s_hMenu && ::IsMenu( ClsWindow::s_hMenu ))
{
// Look it up.
ClsMenu *pMenu;
for ( pMenu = global_menu_list.GetFirst(); pMenu; pMenu = global_menu_list.GetNext( pMenu ))
{
// Is this the one?
if (( HMENU )*pMenu == ClsWindow::s_hMenu )
return pMenu;
}
}
return NULL;
}
// Get state of the UI.
DWORD ClsWindow::GetUIState() const
{
_ASSERT_VALID( GetSafeHWND()); // Must be valid.
// Supported?
if ( ClsGetApp()->GetPlatformID() == VER_PLATFORM_WIN32_NT && ClsGetApp()->GetMajorVersion() >= 5 )
// Get the UI state.
return ( DWORD )::SendMessage( m_hWnd, WM_QUERYUISTATE, 0, 0 );
// No UI state.
return 0L;
}
// Functions which make use of the ClsDC class.
ClsDC *ClsWindow::BeginPaint( LPPAINTSTRUCT pPaintStruct )
{
_ASSERT_VALID( GetSafeHWND() );
_ASSERT_VALID( pPaintStruct );
return ClsDC::FromHandle( ::BeginPaint( m_hWnd, pPaintStruct ));
}
ClsDC *ClsWindow::GetDC()
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetDC( m_hWnd ));
}
ClsDC *ClsWindow::GetDCEx( ClsRgn* prgnClip, DWORD flags )
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetDCEx( m_hWnd, prgnClip ? ( HRGN )*prgnClip : NULL, flags ));
}
ClsDC *ClsWindow::GetWindowDC()
{
_ASSERT_VALID( GetSafeHWND() );
return ClsDC::FromHandle( ::GetWindowDC( m_hWnd ));
}
int ClsWindow::ReleaseDC( ClsDC *pDC )
{
_ASSERT_VALID( GetSafeHWND() );
return ::ReleaseDC( m_hWnd, *pDC );
}
| 26.800857 | 177 | 0.6562 |
f4d992fa6259231d30a542a191c9d94793d23fc2 | 3,110 | cpp | C++ | libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | 31 | 2020-04-29T06:11:54.000Z | 2021-11-10T19:14:09.000Z | libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | 11 | 2020-07-27T17:12:05.000Z | 2021-12-01T16:33:18.000Z | libs/ofxLineaDeTiempo/src/View/KeyframeTrackHeader.cpp | roymacdonald/ofxLineaDeTiempo | 1a080c7d5533dc9b0e587bd1557506fe288f05e8 | [
"MIT"
] | null | null | null | //
// KeyframeTrackHeader.cpp
// ofxGuiWidgetDOMintegration
//
// Created by Roy Macdonald on 4/12/20.
//
#include "LineaDeTiempo/View/KeyframeTrackHeader.h"
#include "LineaDeTiempo/View/TrackGroupView.h"
#include "LineaDeTiempo/View/BaseTrackView.h"
namespace ofx {
namespace LineaDeTiempo {
template<typename ParamType>
KeyframeTrackHeader<ParamType>::KeyframeTrackHeader(ofParameter<ParamType> & param, const std::string& id, const ofRectangle& rect, BaseTrackView* track, TrackGroupView* group, bool belongsToPanel)
: TrackHeader(id, rect, track, group, belongsToPanel)
{
_gui = addChild<ofxGuiView<ParamType>>(param, group->getTracksHeaderWidth(), this);
_gui->setPosition(0, 0);//ConstVars::ViewTopHeaderHeight);
_ofxGuiHeightChangeListener = _gui->shapeChanged.newListener(this, &KeyframeTrackHeader::_ofxGuiHeightChange);
_colorListener = track->colorChangeEvent.newListener(this, &KeyframeTrackHeader::_colorChanged);
}
template<typename ParamType>
float KeyframeTrackHeader<ParamType>::_getMinHeight()
{
return _gui->getShape().getMaxY();
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_onShapeChange(const DOM::ShapeChangeEventArgs& e)
{
if(e.widthChanged())
{
_gui->setWidth(getWidth());
}
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_ofxGuiHeightChange(DOM::ShapeChangeEventArgs& args)
{
if(args.changedVertically())
{
if(getHeight() < args.shape.getMaxY())
{
setHeight(args.shape.getMaxY());
}
}
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::onDraw() const
{
// the intention of this override is to avoid the drawing of the TrackHeader class
}
template<typename ParamType>
void KeyframeTrackHeader<ParamType>::_colorChanged(ofColor& color)
{
if(_gui && _gui->getOfxGui())
{
_gui->getOfxGui()->setHeaderBackgroundColor(color);
_gui->getOfxGui()->setBackgroundColor(color);
}
}
template class KeyframeTrackHeader<ofRectangle>;
template class KeyframeTrackHeader<ofColor>;
template class KeyframeTrackHeader<ofShortColor>;
template class KeyframeTrackHeader<ofFloatColor>;
template class KeyframeTrackHeader<glm::vec2>;
template class KeyframeTrackHeader<glm::vec3>;
template class KeyframeTrackHeader<glm::vec4>;
//template class KeyframeTrackHeader<glm::quat>;
//template class KeyframeTrackHeader<glm::mat4>;
template class KeyframeTrackHeader<bool>;
template class KeyframeTrackHeader<void>;
template class KeyframeTrackHeader<int8_t>;
template class KeyframeTrackHeader<uint8_t>;
template class KeyframeTrackHeader<int16_t>;
template class KeyframeTrackHeader<uint16_t>;
template class KeyframeTrackHeader<int32_t>;
template class KeyframeTrackHeader<uint32_t>;
template class KeyframeTrackHeader<int64_t>;
template class KeyframeTrackHeader<uint64_t>;
template class KeyframeTrackHeader<float>;
template class KeyframeTrackHeader<double>;
#ifndef TARGET_LINUX
template class KeyframeTrackHeader<typename std::conditional<std::is_same<uint32_t, size_t>::value || std::is_same<uint64_t, size_t>::value, bool, size_t>::type>;
#endif
} } // ofx::LineaDeTiempo
| 26.581197 | 198 | 0.791318 |
f4dbb4983a66a6d8cdf4192b8d85e3ba544a2928 | 104,662 | cpp | C++ | sxaccelerate/src/math/SxBlasLib.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | 1 | 2020-02-29T03:26:32.000Z | 2020-02-29T03:26:32.000Z | sxaccelerate/src/math/SxBlasLib.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | sxaccelerate/src/math/SxBlasLib.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | // ---------------------------------------------------------------------------
//
// The general purpose cross platform C/C++ framework
//
// S x A c c e l e r a t e
//
// Home: https://www.sxlib.de
// License: Apache 2
// Authors: see src/AUTHORS
//
// ---------------------------------------------------------------------------
// ref1 - Comp. Phys. Comm (128), 1-45 (2000)
//#include <stdio.h>
//#include <string.h>
//#include <stdlib.h>
//#include <iostream>
#include <math.h>
#include <SxBlasLib.h>
#include <SxError.h>
#ifdef USE_OPENMP
#include <omp.h>
#endif
//#include <SxRandom.h>
// --- BLAS, LAPACK
#if defined(USE_VECLIB)
//# include <veclib.h> // --- don't use HP header files!
//# include <lapack.h> // more details in SxMLIB.h
# include <SxMLIB.h>
#elif defined (ESSE_ESSL)
// --- before including ESSL we have to do a messy definition
// otherwise it doesn't compile. i don't know a better way.
// see also: SxFFT.h
# define _ESV_COMPLEX_
# include <complex>
# include <essl.h>
#elif defined (USE_INTEL_MKL)
// mkl uses 'long long', which is not ISO C++. Disable errors here.
//#pragma GCC diagnostic push
//#pragma GCC diagnostic warning "-Wlong-long"
extern "C" {
# include <mkl.h>
}
//#pragma GCC diagnostic pop
#elif defined (USE_ACML)
extern "C" {
# include <acml.h>
}
#elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
# define blasint int
extern "C" {
# include <f2c.h>
# include <cblas.h>
# include <clapack.h>
}
#elif defined (USE_ATLAS)
# if defined (USE_ACCELERATE_FRAMEWORK)
# include <Accelerate/Accelerate.h>
typedef __CLPK_integer integer;
typedef __CLPK_logical logical;
typedef __CLPK_real real;
typedef __CLPK_doublereal doublereal;
typedef __CLPK_ftnlen ftnlen;
typedef __CLPK_complex complex;
typedef __CLPK_doublecomplex doublecomplex;
# else
extern "C" {
# include <f2c.h>
# include <cblas.h>
# include <clapack.h>
}
# endif /* USE_ACCELERATE_FRAMEWORK */
#else
# error "No numeric library specified"
// make sure that we do not drown in error messages
#define SX_IGNORE_THE_REST_OF_THE_FILE
#endif
#ifndef SX_IGNORE_THE_REST_OF_THE_FILE
//------------------------------------------------------------------------------
// BLAS/LAPACK error handling
//------------------------------------------------------------------------------
#if defined (USE_VECLIB)
// error handling not yet supported
#elif defined (USE_ESSL)
// error handling not yet supported
#elif defined (USE_INTEL_MKL)
// error handling not yet supported
#elif defined (USE_ACML)
// error handling not yet supported
#elif defined (USE_GOTO)
// error handling not yet supported
#else
# include <stdarg.h>
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
extern "C" void cblas_xerbla (int p, char *rout, char *form, ...)
# else
extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...)
# endif /* DIST_VERSION_L */
#else
extern "C" void cblas_xerbla (int p, const char *rout, const char *form, ...)
#endif /* MACOSX */
{
//sxprintf ("\nA BLAS/LAPACK error has occured!\n");
std::cout << "\nA BLAS/LAPACK error has occured!\n";
// --- original code from ATLAS/interfaces/blas/C/src/cblas_xerbla.c
va_list argptr;
va_start(argptr, form);
# ifdef GCCWIN
//if (p) sxprintf("Parameter %d to routine %s was incorrect\n", p, rout);
if (p) std::cout << "Parameter " << p << " to routine "
<< rout << " was incorrect\n";
vprintf(form, argptr);
# else
if (p)
fprintf(stderr, "Parameter %d to routine %s was incorrect\n",
p, rout);
vfprintf(stderr, form, argptr);
# endif /* CYGWIN */
va_end(argptr);
// --- end of original ATLAS code
SX_EXIT;
}
#endif /* USE_VECLIB */
//------------------------------------------------------------------------------
// norm of vectors
//------------------------------------------------------------------------------
float norm2 (const float *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return snrm2 (&n, (float *)vec, &incx);
# elif defined (USE_ESSL)
return snrm2 (n, vec, incx);
# elif defined (USE_INTEL_MKL)
return snrm2 (&n, const_cast<float *>(vec), &incx);
# elif defined (USE_ACML)
return snrm2 (n, const_cast<float *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_snrm2 (n, const_cast<float *>(vec), incx);
# else
return cblas_snrm2 (n, vec, incx);
# endif
}
double norm2 (const double *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return dnrm2 (&n, (double *)vec, &incx);
# elif defined (USE_ESSL)
return dnrm2 (n, vec, incx);
# elif defined (USE_INTEL_MKL)
return dnrm2 (&n, const_cast<double *>(vec), &incx);
# elif defined (USE_ACML)
return dnrm2 (n, const_cast<double *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_dnrm2 (n, const_cast<double*>(vec), incx);
# else
return cblas_dnrm2 (n, vec, incx);
# endif
}
float norm2 (const SxComplex8 *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return scnrm2 (&n, (complex8_t *)vec, &incx);
# elif defined (USE_ESSL)
return scnrm2 (n, (const complex<float> *)vec, incx);
# elif defined (USE_INTEL_MKL)
return scnrm2 (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(vec), &incx);
# elif defined (USE_ACML)
return scnrm2 (n, (complex *)const_cast<SxComplex8 *>(vec), incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_scnrm2 (n, (float*)vec, incx);
# else
return cblas_scnrm2 (n, vec, incx);
# endif
}
double norm2 (const SxComplex16 *vec, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
return dznrm2 (&n, (complex16_t *)vec, &incx);
# elif defined (USE_ESSL)
return dznrm2 (n, (const complex<double> *)vec, incx);
# elif defined (USE_INTEL_MKL)
return dznrm2 (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(vec), &incx);
# elif defined (USE_ACML)
return dznrm2 (n, (doublecomplex *)const_cast<SxComplex16 *>(vec),
incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
return cblas_dznrm2 (n, (double*)vec, incx);
# else
return cblas_dznrm2 (n, vec, incx);
# endif
}
//------------------------------------------------------------------------------
// scale vectors
//------------------------------------------------------------------------------
void scale (float *vec, const float alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
sscal (&n, (float *)&alpha, (float *)vec, &incx);
# elif defined (USE_ESSL)
sscal (n, alpha, vec, incx);
# elif defined (USE_INTEL_MKL)
sscal (&n, const_cast<float *>(&alpha), (float *)vec, &incx);
# elif defined (USE_ACML)
sscal (n, alpha, vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_sscal (n, alpha, vec, incx);
# else
cblas_sscal (n, alpha, vec, incx);
# endif
}
void scale (double *vec, const double alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
dscal (&n, (double *)&alpha, (double *)vec, &incx);
# elif defined (USE_ESSL)
dscal (n, alpha, vec, incx);
# elif defined (USE_INTEL_MKL)
dscal (&n, const_cast<double *>(&alpha), (double *)vec, &incx);
# elif defined (USE_ACML)
dscal (n, alpha, vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_dscal (n, alpha, vec, incx);
# else
cblas_dscal (n, alpha, vec, incx);
# endif
}
void scale (SxComplex8 *vec, const SxComplex8 &alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
cscal (&n, (complex8_t *)&alpha, (complex8_t *)vec, &incx);
# elif defined (USE_ESSL)
const complex<float> alphaTmp (alpha.re, alpha.im);
cscal (n, alphaTmp, (complex<float> *)vec, incx);
# elif defined (USE_INTEL_MKL)
cscal (&n, (MKL_Complex8 *)const_cast<SxComplex8*>(&alpha),
(MKL_Complex8 *)vec, &incx);
# elif defined (USE_ACML)
cscal (n, (complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_cscal (n, (float*)&alpha, (float*)vec, incx);
# else
cblas_cscal (n, &alpha, vec, incx);
# endif
}
void scale (SxComplex16 *vec, const SxComplex16 &alpha, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
zscal (&n, (complex16_t *)&alpha, (complex16_t *)vec, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
zscal (n, alphaTmp, (complex<double> *)vec, incx);
# elif defined (USE_INTEL_MKL)
zscal (&n, (MKL_Complex16 *)const_cast<SxComplex16*>(&alpha),
(MKL_Complex16 *)vec, &incx);
# elif defined (USE_ACML)
zscal (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)vec, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_zscal (n, (double*)&alpha, (double*)vec, incx);
# else
cblas_zscal (n, &alpha, vec, incx);
# endif
}
//------------------------------------------------------------------------------
// Y += a*X
//------------------------------------------------------------------------------
void axpy (float *yOut, const float &alpha, const float *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
saxpy (&n, (float *)&alpha,
(float *)xIn, &incx, (float *)yOut, &incx);
# elif defined (USE_ESSL)
saxpy (n, a,
(float *)xIn, incx, (float *)yOut, incx);
# elif defined (USE_INTEL_MKL)
saxpy (&n, const_cast<float *>(&alpha),
const_cast<float *>(xIn), &incx, yOut, &incx);
# elif defined (USE_ACML)
saxpy (n, alpha, (float *)const_cast<float *>(xIn),
incx, (float *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_saxpy (n, alpha, const_cast<float*>(xIn), incx, yOut, incx);
# else
cblas_saxpy (n, alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (double *yOut, const double &alpha, const double *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
daxpy (&n, (double *)&alpha,
(double *)xIn, &incx, (double *)yOut, &incx);
# elif defined (USE_ESSL)
daxpy (n, a,
(double *)xIn, incx, (double *)yOut, incx);
# elif defined (USE_INTEL_MKL)
daxpy (&n, const_cast<double *>(&alpha),
const_cast<double *>(xIn), &incx, (double *)yOut, &incx);
# elif defined (USE_ACML)
daxpy (n, alpha, (double *)const_cast<double *>(xIn),
incx, (double *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_daxpy (n, alpha, const_cast<double*>(xIn), incx, yOut, incx);
# else
cblas_daxpy (n, alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (SxComplex8 *yOut,
const SxComplex8 &alpha, const SxComplex8 *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
caxpy (&n, (complex8_t *)&alpha,
(complex8_t *)xIn, &incx, (complex8_t *)yOut, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
caxpy (n, alphaTmp,
(complex<float> *)xIn, incx, (complex<float> *)yOut, incx);
# elif defined (USE_INTEL_MKL)
caxpy (&n, (MKL_Complex8 *)const_cast<SxComplex8 *>(&alpha),
(MKL_Complex8 *)const_cast<SxComplex8 *>(xIn), &incx,
(MKL_Complex8 *)yOut, &incx);
# elif defined (USE_ACML)
caxpy (n, (complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(xIn), incx,
(complex *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_caxpy (n, (float*)&alpha, (float*)xIn, incx, (float*)yOut, incx);
# else
cblas_caxpy (n, &alpha, xIn, incx, yOut, incx);
# endif
}
void axpy (SxComplex16 *yOut,
const SxComplex16 &alpha, const SxComplex16 *xIn, int n)
{
int incx = 1;
# if defined (USE_VECLIB)
zaxpy (&n, (complex16_t *)&alpha,
(complex16_t *)xIn, &incx, (complex16_t *)yOut, &incx);
# elif defined (USE_ESSL)
const complex<double> alphaTmp (alpha.re, alpha.im);
zaxpy (n, alphaTmp,
(complex<double> *)xIn, incx, (complex<double> *)yOut, incx);
# elif defined (USE_INTEL_MKL)
zaxpy (&n, (MKL_Complex16 *)const_cast<SxComplex16 *>(&alpha),
(MKL_Complex16 *)const_cast<SxComplex16 *>(xIn), &incx,
(MKL_Complex16 *)yOut, &incx);
# elif defined (USE_ACML)
zaxpy (n, (doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(xIn),
incx, (doublecomplex *)yOut, incx);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_zaxpy (n, (double*)&alpha, (double*)xIn, incx, (double*)yOut, incx);
# else
cblas_zaxpy (n, &alpha, xIn, incx, yOut, incx);
# endif
}
//------------------------------------------------------------------------------
// scalar product
//------------------------------------------------------------------------------
float scalarProduct (const float *aVec, const float *bVec, int n)
{
const float *aPtr = aVec;
const float *bPtr = bVec;
float res = 0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += *aPtr * *bPtr;
return res;
}
double scalarProduct (const double *aVec, const double *bVec, int n)
{
const double *aPtr = aVec;
const double *bPtr = bVec;
double res = 0;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += *aPtr * *bPtr;
return res;
}
SxComplex8 scalarProduct (const SxComplex8 *aVec, const SxComplex8 *bVec, int n)
{
const SxComplex8 *aPtr = aVec;
const SxComplex8 *bPtr = bVec;
SxComplex8 res = (SxComplex8)0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += aPtr->conj() * *bPtr;
return res;
}
SxComplex16 scalarProduct (const SxComplex16 *aVec, const SxComplex16 *bVec, int n)
{
const SxComplex16 *aPtr = aVec;
const SxComplex16 *bPtr = bVec;
SxComplex16 res = (SxComplex8)0.;
for (int i=0; i < n; i++, aPtr++, bPtr++)
res += aPtr->conj() * *bPtr;
return res;
}
//------------------------------------------------------------------------------
// general matrix-matrix multiplication
//------------------------------------------------------------------------------
void matmult (float *resMat, const float *aMat, const float *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
float alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
char noTrans = 'N';
sgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, (float *)aMat, &aMatRows,
(float *)bMat, &aMatCols, &beta, (float *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
sgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
sgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
&alpha, const_cast<float *>(aMat), &aMatRows,
const_cast<float *>(bMat), &aMatCols, &beta, resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
sgemm (noTrans, noTrans, aMatRows, bMatCols, aMatCols,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float *>(bMat), aMatCols, beta, resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<float*>(aMat), aMatRows,
const_cast<float*>(bMat), aMatCols, beta, resMat,
aMatRows);
# else
cblas_sgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# endif
}
void matmult (double *resMat, const double *aMat, const double *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
double alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
char noTrans = 'N';
dgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, (double *)aMat, &aMatRows,
(double *)bMat, &aMatCols, &beta, (double *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
dgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
dgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
&alpha, const_cast<double *>(aMat), &aMatRows,
const_cast<double *>(bMat), &aMatCols, &beta, resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
dgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<double *>(aMat), aMatRows,
const_cast<double *>(bMat), aMatCols, beta, resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), aMatCols, beta, resMat, aMatRows);
# else
cblas_dgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
alpha, aMat, aMatRows,
bMat, aMatCols, beta, resMat, aMatRows);
# endif
}
void matmult (SxComplex8 *resMat,
const SxComplex8 *aMat, const SxComplex8 *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
char noTrans = 'N';
cgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
(complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows,
(complex8_t *)bMat, &aMatCols, (complex8_t *)&beta,
(complex8_t *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
complex<float> alphaT (alpha.re, alpha.im);
complex<float> betaT (beta.re, beta.im);
cgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alphaT, (complex<float> *)aMat, aMatRows,
(complex<float> *)bMat, aMatCols, betaT,
(complex<float> *)resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
cgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
(MKL_Complex8 *)&alpha,
(MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows,
(MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &aMatCols,
(MKL_Complex8 *)&beta,
(MKL_Complex8 *)resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
cgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
(complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(aMat), aMatRows,
(complex *)const_cast<SxComplex8 *>(bMat), aMatCols,
(complex *)const_cast<SxComplex8 *>(&beta),
(complex *)resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, aMatCols, (float*)&beta,
(float*)resMat, aMatRows);
# else
cblas_cgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
&alpha, aMat, aMatRows,
bMat, aMatCols, &beta, resMat, aMatRows);
# endif
}
void matmult (SxComplex16 *resMat,
const SxComplex16 *aMat, const SxComplex16 *bMat,
int aMatRows, int aMatCols, int bMatCols)
{
SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
char noTrans = 'N';
zgemm (&noTrans, &noTrans,
&aMatRows, &bMatCols, &aMatCols,
(complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows,
(complex16_t *)bMat, &aMatCols, (complex16_t *)&beta,
(complex16_t *)resMat, &aMatRows, 0, 0);
# elif defined (USE_ESSL)
const char noTrans = 'N';
complex<double> alphaT (alpha.re, alpha.im);
complex<double> betaT (beta.re, beta.im);
zgemm (&noTrans, &noTrans,
aMatRows, bMatCols, aMatCols,
alphaT, (complex<double> *)aMat, aMatRows,
(complex<double> *)bMat, aMatCols, betaT,
(complex<double> *)resMat, aMatRows);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N';
zgemm (&noTrans, &noTrans, &aMatRows, &bMatCols, &aMatCols,
(MKL_Complex16 *)&alpha,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
(MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &aMatCols,
(MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatRows);
# elif defined (USE_ACML)
char noTrans = 'N';
zgemm (noTrans, noTrans,
aMatRows, bMatCols, aMatCols,
(doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(bMat), aMatCols,
(doublecomplex *)const_cast<SxComplex16 *>(&beta),
(doublecomplex *)resMat, aMatRows);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, 1, (double*)&beta, (double*)resMat, 1);
} else if (aMatRows == 1) {
cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols,
(double*)&alpha, (double*)bMat, aMatCols,
(double*)aMat, 1, (double*)&beta, (double*)resMat, 1);
} else {
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, aMatCols, (double*)&beta, (double*)resMat,
aMatRows);
}
# else
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasNoTrans, aMatRows, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatRows == 1) {
cblas_zgemv (CblasColMajor, CblasTrans, aMatCols, bMatCols,
&alpha, bMat, aMatCols,
aMat, 1, &beta, resMat, 1);
} else {
#if defined(USE_OPENMP) && defined(USE_ATLAS)
if (aMatRows > 1024) {
# pragma omp parallel
{
int nThreads = omp_get_num_threads ();
int nb = aMatRows / nThreads;
// distribute remaining elements over all threads
if (nb * nThreads < aMatRows) nb++;
int offset = omp_get_thread_num () * nb;
// reduce nb for last thread
if (offset + nb > aMatRows) nb = aMatRows - offset;
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
nb, bMatCols, aMatCols,
&alpha, aMat + offset, aMatRows,
bMat, aMatCols, &beta, resMat + offset, aMatRows);
}
} else // no openMP parallelism ...
#endif
cblas_zgemm (CblasColMajor, CblasNoTrans, CblasNoTrans,
aMatRows, bMatCols, aMatCols,
&alpha, aMat, aMatRows,
bMat, aMatCols, &beta, resMat, aMatRows);
}
# endif
}
//------------------------------------------------------------------------------
// overlap matrices
//------------------------------------------------------------------------------
void matovlp (float *resMat,
const float *aMat, const float *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
float alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, (float *)aMat, &aMatRows,
(float *)bMat, &bMatRows, &beta,
(float *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
// SX_EXIT; // not tested
// change by khr
char noTrans = 'N', conjTrans = 'C';
sgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, const_cast<float *>(aMat), &aMatRows,
const_cast<float *>(bMat), &bMatRows, &beta, resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
sgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float *>(bMat), bMatRows,
beta, resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, const_cast<float*>(aMat), aMatRows,
const_cast<float*>(bMat), 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, const_cast<float*>(bMat), bMatRows,
const_cast<float*>(aMat), 1, beta, resMat, 1);
} else {
cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<float *>(aMat), aMatRows,
const_cast<float*>(bMat), bMatRows, beta, resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, aMat, aMatRows,
bMat, 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_sgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, bMat, bMatRows,
aMat, 1, beta, resMat, 1);
} else {
cblas_sgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
}
# endif
}
void matovlp (double *resMat,
const double *aMat, const double *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
double alpha = 1.0, beta = 0.0;
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, (double *)aMat, &aMatRows,
(double *)bMat, &bMatRows, &beta,
(double *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
// SX_EXIT; // not tested
// change by khr
char noTrans = 'N', conjTrans = 'C';
dgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
&alpha, const_cast<double *>(aMat), &aMatRows,
const_cast<double *>(bMat), &bMatRows, &beta, resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
dgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<double *>(aMat), aMatRows,
const_cast<double *>(bMat), bMatRows,
beta, resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, const_cast<double*>(bMat), bMatRows,
const_cast<double*>(aMat), 1, beta, resMat, 1);
} else {
cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, const_cast<double*>(aMat), aMatRows,
const_cast<double*>(bMat), bMatRows, beta, resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
alpha, aMat, aMatRows,
bMat, 1, beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_dgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
alpha, bMat, bMatRows,
aMat, 1, beta, resMat, 1);
} else {
cblas_dgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
alpha, aMat, aMatRows,
bMat, bMatRows, beta, resMat, aMatCols);
}
# endif
}
void matovlp (SxComplex8 *resMat,
const SxComplex8 *aMat, const SxComplex8 *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
SxComplex8 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
cgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
(complex8_t *)&alpha, (complex8_t *)aMat, &aMatRows,
(complex8_t *)bMat, &bMatRows, (complex8_t *)&beta,
(complex8_t *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
complex<float> alphaT (alpha.re, alpha.im);
complex<float> betaT (beta.re, beta.im);
cgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alphaT, (complex<float> *)aMat, aMatRows,
(complex<float> *)bMat, bMatRows, betaT,
(complex<float> *)resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N', conjTrans = 'C';
cgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize,
(MKL_Complex8 *)&alpha,
(MKL_Complex8 *)const_cast<SxComplex8 *>(aMat), &aMatRows,
(MKL_Complex8 *)const_cast<SxComplex8 *>(bMat), &bMatRows,
(MKL_Complex8 *)&beta, (MKL_Complex8 *)resMat, &aMatCols);
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
cgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
(complex *)const_cast<SxComplex8 *>(&alpha),
(complex *)const_cast<SxComplex8 *>(aMat), aMatRows,
(complex *)const_cast<SxComplex8 *>(bMat), bMatRows,
(complex *)const_cast<SxComplex8 *>(&beta),
(complex *)resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, 1, (float*)&beta, (float*)resMat, 1);
} else if (aMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
(float*)&alpha, (float*)bMat, bMatRows,
(float*)aMat, 1, (float*)&beta, (float*)resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
(float*)&alpha, (float*)aMat, aMatRows,
(float*)bMat, bMatRows, (float*)&beta, (float*)resMat,
aMatCols);
}
# else
if (bMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_cgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
&alpha, bMat, bMatRows,
aMat, 1, &beta, resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_cgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
&alpha, aMat, aMatRows,
bMat, bMatRows, &beta, resMat, aMatCols);
}
# endif
}
/*
#include <SxTimer.h>
enum BlasLibTimer { Matovlp };
REGISTER_TIMERS (BlasLibTimer)
{
regTimer (Matovlp, "matovlp");
}
*/
void matovlp (SxComplex16 *resMat,
const SxComplex16 *aMat, const SxComplex16 *bMat,
int aMatRows, int aMatCols, int bMatRows, int bMatCols,
int sumSize)
{
SxComplex16 alpha (1.0, 0.0), beta (0.0, 0.0);
# if defined (USE_VECLIB)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
zgemm (&conjTrans, &noTrans,
&aMatCols, &bMatCols, &sumSize,
(complex16_t *)&alpha, (complex16_t *)aMat, &aMatRows,
(complex16_t *)bMat, &bMatRows, (complex16_t *)&beta,
(complex16_t *)resMat, &aMatCols, 0, 0);
# elif defined (USE_ESSL)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
complex<double> alphaT (alpha.re, alpha.im);
complex<double> betaT (beta.re, beta.im);
zgemm (&conjTrans, &noTrans,
aMatCols, bMatCols, sumSize,
alphaT, (complex<double> *)aMat, aMatRows,
(complex<double> *)bMat, bMatRows, betaT,
(complex<double> *)resMat, aMatCols);
# elif defined (USE_INTEL_MKL)
char noTrans = 'N', conjTrans = 'C';
if (aMat == bMat && aMatRows == bMatRows && aMatCols == bMatCols) {
// special case: A.overlap (A) => use Hermitean routine ...
char uplo = 'U';
zherk (&uplo, &conjTrans, &aMatCols, &sumSize,
&alpha.re,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
&beta.re, (MKL_Complex16 *)resMat, &aMatCols);
// ... and copy upper half to lower half
for (int i = 0; i < aMatCols; i++)
for (int j = 0; j < i; j++)
resMat[i + aMatCols * j] = resMat[j + aMatCols * i].conj ();
} else {
zgemm (&conjTrans, &noTrans, &aMatCols, &bMatCols, &sumSize,
(MKL_Complex16 *)&alpha,
(MKL_Complex16 *)const_cast<SxComplex16 *>(aMat), &aMatRows,
(MKL_Complex16 *)const_cast<SxComplex16 *>(bMat), &bMatRows,
(MKL_Complex16 *)&beta, (MKL_Complex16 *)resMat, &aMatCols);
}
# elif defined (USE_ACML)
SX_EXIT; // not tested
char noTrans = 'N', conjTrans = 'C';
zgemm (conjTrans, noTrans,
aMatCols, bMatCols, sumSize,
(doublecomplex *)const_cast<SxComplex16 *>(&alpha),
(doublecomplex *)const_cast<SxComplex16 *>(aMat), aMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(bMat), bMatRows,
(doublecomplex *)const_cast<SxComplex16 *>(&beta),
(doublecomplex *)resMat, aMatCols);
# elif defined (USE_GOTO) // khr: GotoBLAS, experimental!
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, 1, (double*)&beta, (double*)resMat, 1);
} else if (aMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
(double*)&alpha, (double*)bMat, bMatRows,
(double*)aMat, 1, (double*)&beta, (double*)resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
(double*)&alpha, (double*)aMat, aMatRows,
(double*)bMat, bMatRows, (double*)&beta,
(double*)resMat, aMatCols);
}
# else
if (bMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, aMatCols,
&alpha, aMat, aMatRows,
bMat, 1, &beta, resMat, 1);
} else if (aMatCols == 1) {
cblas_zgemv (CblasColMajor, CblasConjTrans, sumSize, bMatCols,
&alpha, bMat, bMatRows,
aMat, 1, &beta, resMat, 1);
// now resMat contains (B.adjoint () ^ A)
// perform conjugate (note: res is a vector)
for (ssize_t i = 0; i < bMatCols; ++i)
resMat[i].im = -resMat[i].im;
} else {
#ifndef USE_OPENMP
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize,
&alpha, aMat, aMatRows,
bMat, bMatRows, &beta, resMat, aMatCols);
#else
//CLOCK (Matovlp);
int nb = 128;
int np = sumSize / nb;
// --- compute contribution from rest elements
if (sumSize > nb * np) {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, sumSize - nb * np,
&alpha, aMat + nb * np, aMatRows,
bMat + nb * np, bMatRows, &beta, resMat, aMatCols);
} else {
for (int i = 0; i < aMatCols * bMatCols; ++i)
resMat[i].re = resMat[i].im = 0.;
}
# pragma omp parallel
{
SxComplex16 *part = NULL;
// --- compute partial results (in parallel)
# pragma omp for
for (int ip = 0; ip < np; ip++) {
if (!part) {
part = new SxComplex16[aMatCols * bMatCols];
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, nb,
&alpha, aMat + ip * nb, aMatRows,
bMat + ip * nb, bMatRows, &beta, part, aMatCols);
} else {
cblas_zgemm (CblasColMajor, CblasConjTrans, CblasNoTrans,
aMatCols, bMatCols, nb,
&alpha, aMat + ip * nb, aMatRows,
bMat + ip * nb, bMatRows, &alpha, part, aMatCols);
}
}
// --- sum partial results
if (part) {
# pragma omp critical
cblas_zaxpy (aMatCols * bMatCols, &alpha, part, 1, resMat, 1);
delete [] part;
}
}
# endif
}
# endif
}
//------------------------------------------------------------------------------
// Matrix decompositions
//------------------------------------------------------------------------------
void cholesky (float *resMat, enum UPLO uplo, float * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
spotrf (&uploChar, &n, (float *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
spotrf (&uploChar, n, resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
spotrf (&uploChar, &n, resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
spotrf (uploChar, n, resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
spotrf_ (&uploChar, &rank, (real *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (double *resMat, enum UPLO uplo, double * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
dpotrf (&uploChar, &n, (double *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
dpotrf (&uploChar, n, resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
dpotrf (&uploChar, &n, resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
dpotrf (uploChar, n, resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
dpotrf_ (&uploChar, &rank, (doublereal *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (SxComplex8 *resMat, enum UPLO uplo,
SxComplex8 * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
cpotrf (&uploChar, &n, (complex8_t *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
cpotrf (&uploChar, n, (complex<float> *)resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
cpotrf (&uploChar, &n, (MKL_Complex8 *)resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
cpotrf (uploChar, n, (complex *)resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
cpotrf_ (&uploChar, &rank, (complex *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void cholesky (SxComplex16 *resMat, enum UPLO uplo,
SxComplex16 * /*inMat*/, int n)
{
char uploChar = (uplo == UpperRight) ? 'U' : 'L';
# if defined (USE_VECLIB)
int err = 0;
zpotrf (&uploChar, &n, (complex16_t *)resMat, &n, &err, 0);
# elif defined (USE_ESSL)
int err = 0;
zpotrf (&uploChar, n, (complex<double> *)resMat, n, err);
# elif defined (USE_INTEL_MKL)
int err = 0;
zpotrf(&uploChar, &n, (MKL_Complex16 *)resMat, &n, &err);
# elif defined (USE_ACML)
int err = 0;
zpotrf(uploChar, n, (doublecomplex *)resMat, n, &err);
# else
integer rank = (integer)n, err = 0;
zpotrf_ (&uploChar, &rank, (doublecomplex *)resMat, &rank, &err);
if ( err ) { // TODO: throw exception
std::cout << "cholesky err=" << err << std::endl;
SX_EXIT;
}
# endif
}
void singularValueDecomp (float *mat, int nRows, int nCols,
float *vals,
float *left,
float *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
int ldvt = zeroSpace ? nCols : minMN;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// workspace query:
int *iwork = new int[8 * minMN];
int err = 0;
int lwork = -1;
float optwork;
sgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (int)optwork;
float* work = new float[lwork];
// --- actual compute
sgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer *iwork = new integer[8 * minMN];
integer lwork = -1;
integer err = 0;
// workspace query:
float optwork;
integer nr = nRows, nc = nCols, ldvt_ = ldvt;
sgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork;
float* work = new float[lwork];
// --- actual compute
sgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
delete[] iwork;
}
void singularValueDecomp (double *mat, int nRows, int nCols,
double *vals,
double *left,
double *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
int ldvt = zeroSpace ? nCols : minMN;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// workspace query:
int err = 0;
int *iwork = new int[8 * minMN];
int lwork = -1;
double optwork;
dgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork));
double* work = new double[lwork];
// --- actual compute
dgesdd(&jobz, &nRows, &nCols, mat, &nRows,
vals, left, &nRows, right, &ldvt,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer err = 0;
integer lwork = -1;
integer *iwork = new integer[8 * minMN];
// workspace query:
double optwork;
integer nr = nRows, nc = nCols, ldvt_ = ldvt;
dgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
&optwork, &lwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork;
double* work = new double[lwork];
// --- actual compute
dgesdd_(&jobz, &nr, &nc, mat, &nr,
vals, left, &nr, right, &ldvt_,
work, &lwork, iwork, &err );
delete[] work;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
delete[] iwork;
}
void singularValueDecomp (SxComplex8 *mat, int nRows, int nCols,
float *vals,
SxComplex8 *left,
SxComplex8 *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
int ldvt = zeroSpace ? nCols : minMN;
int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
int err = 0;
int lwork = -1;
float *rwork = new float[lrwork];
int *iwork = new int[8 * minMN];
// workspace query:
MKL_Complex8 optwork;
cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows,
vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork.real));
MKL_Complex8* work = new MKL_Complex8[lwork];
// --- actual compute
cgesdd(&jobz, &nRows, &nCols, (MKL_Complex8*)mat, &nRows,
vals, (MKL_Complex8*)left, &nRows, (MKL_Complex8*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer ldvt = zeroSpace ? nCols : minMN;
integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
integer err = 0;
integer lwork = -1;
float *rwork = new float[lrwork];
integer *iwork = new integer[8 * minMN];
// workspace query:
integer nr = nRows, nc = nCols;
complex optwork;
SX_EXIT;
/* missing prototype
cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr,
vals, (complex*)left, &nr, (complex*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
*/
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork.r;
complex* work = new complex[lwork];
// --- actual compute
SX_EXIT;
/* missing prototype
cgesdd_(&jobz, &nr, &nc, (complex *)mat, &nr,
vals, (complex*)left, &nr, (complex*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
*/
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
}
void singularValueDecomp (SxComplex16 *mat, int nRows, int nCols,
double *vals,
SxComplex16 *left,
SxComplex16 *right, // V^H
bool zeroSpace)
{
char jobz = zeroSpace ? 'A' // U= M x M, V=N x N
: 'S'; // U=M x s, V= s x N
if (!left || !right) {
jobz = 'N';
if (left || right) {
// It is not possible to compute only left or only right vectors.
std::cout << "Internal error in singular-value decomposition"
<< std::endl;
SX_EXIT;
}
}
int minMN = nRows < nCols ? nRows : nCols;
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
int ldvt = zeroSpace ? nCols : minMN;
int lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
int err = 0;
int lwork = -1;
double *rwork = new double[lrwork];
int *iwork = new int[8 * minMN];
// workspace query:
MKL_Complex16 optwork;
zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows,
vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = int(lround(optwork.real));
MKL_Complex16* work = new MKL_Complex16[lwork];
// --- actual compute
zgesdd(&jobz, &nRows, &nCols, (MKL_Complex16*)mat, &nRows,
vals, (MKL_Complex16*)left, &nRows, (MKL_Complex16*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# elif defined (USE_ACML)
SX_EXIT;
# else
integer ldvt = zeroSpace ? nCols : minMN;
integer lrwork = (jobz == 'N') ? (7 * minMN) : ( (5 * minMN + 7) * minMN);
integer err = 0;
integer lwork = -1;
double *rwork = new double[lrwork];
integer *iwork = new integer[8 * minMN];
// workspace query:
doublecomplex optwork;
integer nr = nRows, nc = nCols;
SX_EXIT;
/* missing prototype:
zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr,
vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt,
&optwork, &lwork, rwork, iwork, &err );
*/
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
lwork = (integer)optwork.r;
doublecomplex* work = new doublecomplex[lwork];
// --- actual compute
/* missing prototype:
zgesdd_(&jobz, &nr, &nc, (doublecomplex *)mat, &nr,
vals, (doublecomplex*)left, &nr, (doublecomplex*)right, &ldvt,
work, &lwork, rwork, iwork, &err );
*/
delete[] work;
delete[] iwork;
delete[] rwork;
if (err) {
std::cout << "svd err = " << err << std::endl;
SX_EXIT;
}
# endif
}
//------------------------------------------------------------------------------
// Matrix inversion
//------------------------------------------------------------------------------
void matInverse (float *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (&nRows, &nCols, (float *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (nRows, nCols, mat, r, pivots, err);
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (&nRows, &nCols, mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
sgetrf (nRows, nCols, mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
sgetrf_ (&r, &c, (real *)mat, &r, pivots, &err);
# endif
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in SGETRF: " << err <<std::endl;
delete [] pivots;
SX_EXIT;
}
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (&r, (float *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (r, mat, r, pivots, work, lWork, err);
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
float *work = new float [lWork];
sgetri (&r, mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
float *work = NULL; // ACML doesn't use work
sgetri (r, mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
real *work = new real [lWork];
sgetri_ (&r, (real *)mat, &r, pivots, work, &lWork, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in SGETRI: " << err <<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
}
void matInverse (double *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (&nRows, &nCols, (double *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (nRows, nCols, mat, r, pivots, err);
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (&nRows, &nCols, mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
dgetrf (nRows, nCols, mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
dgetrf_ (&r, &c, (doublereal *)mat, &r, pivots, &err);
# endif
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in DGETRF: " << err <<std::endl;
delete [] pivots;
SX_EXIT;
}
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (&nRows, (double *)mat, &nRows, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (nRows, mat, nRows, pivots, work, lWork, err);
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
double *work = new double [lWork];
dgetri (&nRows, mat, &nRows, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
dgetri (nRows, mat, nRows, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
doublereal *work = new doublereal [lWork];
dgetri_ (&r, (doublereal *)mat, &r, pivots, work, &lWork, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in DGETRI: " << err <<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
}
void matInverse (SxComplex8 *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (&r, &c, (complex8_t *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r, c, err=0;
// map complex inversion to real inversion
// +----+----+ +-----+-----+
// +----+ | Re |-Im | | re1 | im1 |
// |cmlx| => +----+----+ = +-----+-----+
// +----+ | Im | Re | | im2 | re2 |
// +----+----+ +-----+-----+
SxComplex8 *matPtr = mat;
float *realMat = new float [ (2*nRows)*(2*nCols) ];
float *re1Ptr = realMat;
float *im1Ptr = &realMat[nCols];
float *im2Ptr = &realMat[2*nRows*nCols];
float *re2Ptr = &realMat[2*nRows*nCols + nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols,
im1Ptr+=nCols, im2Ptr+=nCols)
{
for (c=0; c<nCols; c++, matPtr++) {
*re1Ptr++ = *re2Ptr++ = matPtr->re;
*im1Ptr++ = -matPtr->im;
*im2Ptr++ = matPtr->im;
}
}
// --- compute inverse of real helper matrix
matInverse (realMat, 2*nRows, 2*nCols);
// construct complex result
// +----+----+ +-----+-----+
// | Re | * | | re1 | * | +----+
// +----+----+ = +-----+-----+ => |cmlx|
// | Im | * | | im2 | * | +----+
// +----+----+ +-----+-----+
matPtr = mat;
re1Ptr = realMat;
im2Ptr = &realMat[2*nRows*nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) {
for (c=0; c<nCols; c++, matPtr++) {
matPtr->re = *re1Ptr++;
matPtr->im = *im2Ptr++;
}
}
delete [] realMat;
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (&r, &c, (MKL_Complex8 *)mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
cgetrf (r, c, (complex *)mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
cgetrf_ (&r, &c, (complex *)mat, &r, pivots, &err);
# endif
# ifndef USE_ESSL
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in CGETRF: "<<err<<std::endl;
delete [] pivots;
SX_EXIT;
}
# endif
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex8_t *work = new complex8_t [lWork];
cgetri (&r, (complex8_t *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
// empty
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
MKL_Complex8 *work = new MKL_Complex8 [lWork];
cgetri (&r, (MKL_Complex8 *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
complex *work = NULL; // ACML doesn't use work
cgetri (r, (complex *)mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex *work = new complex [lWork];
cgetri_ (&r, (complex *)mat, &r, pivots, work, &lWork, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in CGETRI: "<<err<<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverse (SxComplex16 *mat, int nRows, int nCols)
{
# if defined (USE_VECLIB)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (&r, &c, (complex16_t *)mat, &r, pivots, &err);
# elif defined (USE_ESSL)
int r, c, err=0;
// map complex inversion to real inversion
// +----+----+ +-----+-----+
// +----+ | Re |-Im | | re1 | im1 |
// |cmlx| => +----+----+ = +-----+-----+
// +----+ | Im | Re | | im2 | re2 |
// +----+----+ +-----+-----+
SxComplex16 *matPtr = mat;
double *realMat = new double [ (2*nRows)*(2*nCols) ];
double *re1Ptr = realMat;
double *im1Ptr = &realMat[nCols];
double *im2Ptr = &realMat[2*nRows*nCols];
double *re2Ptr = &realMat[2*nRows*nCols + nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, re2Ptr+=nCols,
im1Ptr+=nCols, im2Ptr+=nCols)
{
for (c=0; c<nCols; c++, matPtr++) {
*re1Ptr++ = *re2Ptr++ = matPtr->re;
*im1Ptr++ = -matPtr->im;
*im2Ptr++ = matPtr->im;
}
}
// --- compute inverse of real helper matrix
matInverse (realMat, 2*nRows, 2*nCols);
// construct complex result
// +----+----+ +-----+-----+
// | Re | * | | re1 | * | +----+
// +----+----+ = +-----+-----+ => |cmlx|
// | Im | * | | im2 | * | +----+
// +----+----+ +-----+-----+
matPtr = mat;
re1Ptr = realMat;
im2Ptr = &realMat[2*nRows*nCols];
for (r=0; r<nRows; r++, re1Ptr+=nCols, im2Ptr+=nCols) {
for (c=0; c<nCols; c++, matPtr++) {
matPtr->re = *re1Ptr++;
matPtr->im = *im2Ptr++;
}
}
delete [] realMat;
# elif defined (USE_INTEL_MKL)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (&r, &c, (MKL_Complex16 *)mat, &r, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, c = nCols, err = 0;
int *pivots = new int [r < c ? r : c];
zgetrf (r, c, (doublecomplex *)mat, r, pivots, &err);
# else
integer r = (integer)nRows, c = (integer)nCols, err = 0;
integer *pivots = new integer[r < c ? r : c];
zgetrf_ (&r, &c, (doublecomplex *)mat, &r, pivots, &err);
# endif
# ifndef USE_ESSL
if (err) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in ZGETRF: "<<err<<std::endl;
delete [] pivots;
SX_EXIT;
}
# endif
// --- (2) diagonalization
# if defined (USE_VECLIB)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
complex16_t *work = new complex16_t [lWork];
zgetri (&r, (complex16_t *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ESSL)
// empty
# elif defined (USE_INTEL_MKL)
int lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
MKL_Complex16 *work = new MKL_Complex16 [lWork];
zgetri (&r, (MKL_Complex16 *)mat, &r, pivots, work, &lWork, &err);
# elif defined (USE_ACML)
doublecomplex *work = NULL; // ACML doesn't use work
zgetri (r, (doublecomplex *)mat, r, pivots, &err);
# else
integer lWork = r; // for opt. performance = r * OPT_BLOCKSIZE (from ILAENV)
doublecomplex *work = new doublecomplex [lWork];
zgetri_ (&r, (doublecomplex *)mat, &r, pivots, work, &lWork, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverse: Error in ZGETRI: "<<err<<std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverseTri (float * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
void matInverseTri (double *mat, int nRows, enum UPLO uplo)
{
char uploChar = (uplo == UpperRight ? 'U' : 'L');
// --- (1) Factorization: A = U*D*U^t
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined ( USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// int err = 0;
// SX_EXIT; // not yet implemented
// change by khr
int r = nRows, err = 0;
int *pivots = new int[r];
dsptrf (&uploChar, &r, mat, pivots, &err);
# elif defined (USE_ACML)
int r = nRows, err = 0;
int *pivots = new int[r];
dsptrf (uploChar, r, mat, pivots, &err);
# else
integer r = (integer)nRows, err = 0;
integer *pivots = new integer[r];
dsptrf_ (&uploChar, &r, (doublereal *)mat, pivots, &err);
# endif
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRF: "
<< err << std::endl;
SX_EXIT;
}
// --- (2) Inverse of A
# if defined (USE_VECLIB)
SX_EXIT; // not yet implemented
# elif defined (USE_ESSL)
SX_EXIT; // not yet implemented
# elif defined (USE_INTEL_MKL)
// double *work = NULL, *pivots=NULL;
// SX_EXIT; // not yet implemented
// change by khr
double *work = new double [r];
dsptri (&uploChar, &r, mat, pivots, work, &err);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
dsptri (uploChar, r, mat, pivots, &err);
# else
doublereal *work = new doublereal [r];
dsptri_ (&uploChar, &r, (doublereal *)mat, pivots, work, &err);
# endif
# ifndef USE_ESSL
if ( err ) { // TODO: throw execption
std::cout << "SxMatrix<T>::inverseTri: Error in DSPTRI: "
<< err << std::endl;
delete [] work; delete [] pivots;
SX_EXIT;
}
delete [] work; delete [] pivots;
# endif
}
void matInverseTri (SxComplex8 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
void matInverseTri (SxComplex16 * /*mat*/, int /*nRows*/, enum UPLO /*uplo*/)
{
SX_EXIT; // not yet implemented
}
//------------------------------------------------------------------------------
// Linear equation solver (least square based)
//------------------------------------------------------------------------------
void solveLinEq (float *mat, int nRows, int nCols, float *b, int bCols)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
int iopt = 2; //compute singulare Values, V and U^TB
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
char transa = 'N';
int naux = 0; //ESSL choose size of work array dynamically
float *aux = NULL; //workarray is ignored
int info;
float *s = new float [n];
float *x = new float [n*nrhs];
float tau = 1e-10; // error tolerance for zero
sgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux);
sgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau);
// results are now in x; copy to b
for(int i = 0; i < n*nrhs; i++) {
b[i] = x[i];
}
delete [] s; delete [] x;
//TODO TEST
SX_EXIT;
# elif defined (USE_INTEL_MKL)
// for ilaenv
MKL_INT iSpec = 9;
char *name = const_cast<char*>("SGELSD");
char *opts = const_cast<char*>(" ");
MKL_INT n1 = 0;
MKL_INT n2 = 0;
MKL_INT n3 = 0;
MKL_INT n4 = 0;
// for dgelsd
MKL_INT m = nRows;
MKL_INT n = nCols;
MKL_INT minmn = n < m ? n : m;
MKL_INT nrhs = bCols;
MKL_INT lda = m;
MKL_INT ldb = m;
float *s = new float [minmn];
float rcond = -1.;
MKL_INT rank;
MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4);
MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1;
MKL_INT NLVL = 0 < logVal ? logVal : 0;
MKL_INT lwork = -1;
float autolwork;
MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn;
MKL_INT *iwork = new MKL_INT [liwork];
MKL_INT info;
// determine optimal lwork
// dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = MKL_INT(autolwork+0.5);
float *work = new float [lwork];
sgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
//TODO TEST
SX_EXIT;
# elif defined (USE_ACML)
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
int minmn = n < m ? n : m;
float *s = new float [minmn];
float rcond = -1.;
int rank;
int info;
sgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info);
delete [] s;
//TODO TEST
SX_EXIT;
# else
// for ilaenv
integer iSpec = 9;
char *name = const_cast<char*>("SGELSD");
char *opts = const_cast<char*>(" ");
integer n1 = 0;
integer n2 = 0;
integer n3 = 0;
integer n4 = 0;
ftnlen lname = 6;
ftnlen lopts = 1;
// for sgelsd
integer m = nRows;
integer n = nCols;
integer minmn = n < m ? n : m;
integer nrhs = bCols;
integer lda = m;
integer ldb = m;
float *s = new float [minmn];
float rcond = -1.;
integer rank;
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4);
# else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
# endif /* DIST_VERSION_L */
#else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
#endif /* MACOSX */
integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1;
integer NLVL = 0 < logVal ? logVal : 0;
integer lwork = -1;
float autolwork;
integer liwork = 3 * minmn * NLVL + 11 * minmn;
integer *iwork = new integer [liwork];
integer info;
// determine optimal lwork
sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = integer(autolwork+0.5);
float *work = new float [lwork];
sgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# endif
}
void solveLinEq (double *mat, int nRows, int nCols, double *b, int bCols)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
int iopt = 2; //compute singulare Values, V and U^TB
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
char transa = 'N';
int naux = 0; //ESSL choose size of work array dynamically
double *aux = NULL; //workarray is ignored
int info;
double *s = new double [n];
double *x = new double [n*nrhs];
double tau = 1e-10; // error tolerance for zero
dgesvf(iopt,mat,lda,b,ldb,nrhs,s,m,n,aux,naux);
dgesvs (mat,n,b,n,nrhs,s,x,n,m,n,tau);
// results are now in x; copy to b
for(int i = 0; i < n*nrhs; i++) {
b[i] = x[i];
}
delete [] s; delete [] x;
//TODO TEST
SX_EXIT;
# elif defined (USE_INTEL_MKL)
// for ilaenv
MKL_INT iSpec = 9;
char *name = const_cast<char*>("DGELSD");
char *opts = const_cast<char*>(" ");
MKL_INT n1 = 0;
MKL_INT n2 = 0;
MKL_INT n3 = 0;
MKL_INT n4 = 0;
// for dgelsd
MKL_INT m = nRows;
MKL_INT n = nCols;
MKL_INT minmn = n < m ? n : m;
MKL_INT nrhs = bCols;
MKL_INT lda = m;
MKL_INT ldb = m;
double *s = new double [minmn];
double rcond = -1.;
MKL_INT rank;
MKL_INT SMLSIZ = ilaenv(&iSpec,name,opts,&n1,&n2,&n3,&n4);
MKL_INT logVal = MKL_INT(log( 1.0*n/(SMLSIZ+1))/log(2.0)) + 1;
MKL_INT NLVL = 0 < logVal ? logVal : 0;
MKL_INT lwork = -1;
double autolwork;
MKL_INT liwork = 3 * minmn * NLVL + 11 * minmn;
MKL_INT *iwork = new MKL_INT [liwork];
MKL_INT info;
// determine optimal lwork
dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = MKL_INT(autolwork+0.5);
double *work = new double [lwork];
dgelsd (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# elif defined (USE_ACML)
int m = nRows;
int n = nCols;
int nrhs = bCols;
int lda = m;
int ldb = m;
int minmn = n < m ? n : m;
double *s = new double [minmn];
double rcond = -1.;
int rank;
int info;
dgelsd (m,n,nrhs,mat,lda,b,ldb,s,rcond,&rank,&info);
delete [] s;
//TODO TEST
SX_EXIT;
# else
// for ilaenv
integer iSpec = 9;
char *name = const_cast<char*>("DGELSD");
char *opts = const_cast<char*>(" ");
integer n1 = 0;
integer n2 = 0;
integer n3 = 0;
integer n4 = 0;
ftnlen lname = 6;
ftnlen lopts = 1;
// for dgelsd
integer m = nRows;
integer n = nCols;
integer minmn = n < m ? n : m;
integer nrhs = bCols;
integer lda = m;
integer ldb = m;
double *s = new double [minmn];
double rcond = -1.;
integer rank;
#ifdef MACOSX
# if ( DIST_VERSION_L >= 1070L )
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4);
# else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
# endif /* DIST_VERSION_L */
#else
integer SMLSIZ = ilaenv_(&iSpec,name,opts,&n1,&n2,&n3,&n4,lname,lopts);
#endif /* MACOSX */
integer logVal = integer(log( double(n)/double(SMLSIZ+1))/log(2.0)) + 1;
integer NLVL = 0 < logVal ? logVal : 0;
integer lwork = -1;
double autolwork;
integer liwork = 3 * minmn * NLVL + 11 * minmn;
integer *iwork = new integer [liwork];
integer info;
// determine optimal lwork
dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,&autolwork,&lwork,iwork,&info);
lwork = integer(autolwork+0.5);
double *work = new double [lwork];
dgelsd_ (&m,&n,&nrhs,mat,&lda,b,&ldb,s,&rcond,&rank,work,&lwork,iwork,&info);
delete [] s; delete [] work; delete [] iwork;
# endif
}
void solveLinEq (SxComplex8 * /*mat*/, int /*nRows*/, int /*nCols*/,
SxComplex8 * /*b*/, int /*bCols*/)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
//TODO
SX_EXIT;
# elif defined (USE_INTEL_MKL)
//TODO
SX_EXIT;
# elif defined (USE_ACML)
//TODO
SX_EXIT;
# endif
}
void solveLinEq (SxComplex16 * /*mat*/, int /*nRows*/, int /*nCols*/,
SxComplex16 * /*b*/, int /*bCols*/)
{
# if defined (USE_VECLIB)
//TODO
SX_EXIT;
# elif defined (USE_ESSL)
//TODO
SX_EXIT;
# elif defined (USE_INTEL_MKL)
//TODO
SX_EXIT;
# elif defined (USE_ACML)
//TODO
SX_EXIT;
# else
//TODO
SX_EXIT;
# endif
}
//------------------------------------------------------------------------------
// Eigensolver
//------------------------------------------------------------------------------
int matEigensolver (SxComplex8 *eigVals, float *eigVecs,
float *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 4*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
float *work = new float [workDim];
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (&jobvl, &jobvr,
&rank, (float *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (float *)eigVecs, &rank, work, &lWork, &info, 0, 0);
# elif defined (USE_ESSL)
complex<float> *vecs = new complex<float> [rank*rank];
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
sgeev (iOpt, inMat, rank,
(complex<float> *)eigVals, vecs, rank,
NULL, rank, NULL, 0);
complex<float> *srcPtr = vecs;
float *dstPtr = eigVecs;
int i, len = n*n;
for (i=0; i < len; i++, srcPtr++) {
*dstPtr++ = real(*srcPtr);
}
// --- normalize eigenvectors
float c;
for (i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
delete [] vecs;
return 0;
# elif defined (USE_INTEL_MKL)
float *work = new float [workDim];
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (&jobvl, &jobvr,
&rank, inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, eigVecs, &rank, work, &lWork, &info);
# elif defined (USE_ACML)
float *work = NULL; // ACML doesn't use work
float *epsRe = new float [n], *epsIm = new float [n];
float *eigVecLeft = new float [ldVecLeft];
sgeev (jobvl, jobvr,
rank, inMat, rank, epsRe, epsIm, eigVecLeft,
ldVecLeft, eigVecs, rank, &info);
# else
real *work = new real [workDim];
real *epsRe = new real[n], *epsIm = new real[n];
real *eigVecLeft = new real [ldVecLeft];
sgeev_ (&jobvl, &jobvr,
&rank, (real *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (real *)eigVecs, &rank, work, &lWork, &info);
# endif
# ifndef USE_ESSL
float *ptr=(float *)eigVals;
float *rePtr=(float *)epsRe, *imPtr=(float *)epsIm;
for (int i=0; i < n; i++) {
*ptr++ = *rePtr++; // eigVals[i].re = epsRe[i];
*ptr++ = *imPtr++; // eigVals[i].im = epsIm[i];
}
delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work;
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in SGEEV: " << info << std::endl;
SX_EXIT;
}
return (cmd == OptSize) ? (int)work[0] : 0;
# endif
}
int matEigensolver (SxComplex16 *eigVals, double *eigVecs,
double *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 4*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 4*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
double *work = new double [workDim];
double *epsRe = new double[n], *epsIm = new double[n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (&jobvl, &jobvr,
&rank, (double *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (double *)eigVecs, &rank, work, &lWork, &info, 0, 0);
# elif defined (USE_ESSL)
complex<double> *vecs = new complex<double> [rank*rank];
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
dgeev (iOpt, inMat, rank,
(complex<double> *)eigVals, vecs, rank,
NULL, rank, NULL, 0);
complex<double> *srcPtr = vecs;
double *dstPtr = eigVecs;
int i, len = n*n;
for (i=0; i < len; i++, srcPtr++) {
*dstPtr++ = real(*srcPtr);
}
// --- normalize eigenvectors
double c;
for (i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
delete [] vecs;
return 0;
# elif defined (USE_INTEL_MKL)
double *work = new double [workDim];
double *epsRe = new double [n], *epsIm = new double [n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (&jobvl, &jobvr,
&rank, inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, eigVecs, &rank, work, &lWork, &info);
# elif defined (USE_ACML)
double *work = NULL; // ACML doesn't use work
double *epsRe = new double [n], *epsIm = new double [n];
double *eigVecLeft = new double [ldVecLeft];
dgeev (jobvl, jobvr,
rank, inMat, rank, epsRe, epsIm, eigVecLeft,
ldVecLeft, eigVecs, rank, &info);
# else
doublereal *work = new doublereal [workDim];
doublereal *epsRe = new doublereal[n], *epsIm = new doublereal[n];
doublereal *eigVecLeft = new doublereal [ldVecLeft];
dgeev_ (&jobvl, &jobvr,
&rank, (doublereal *)inMat, &rank, epsRe, epsIm, eigVecLeft,
&ldVecLeft, (doublereal *)eigVecs, &rank, work, &lWork, &info);
# endif
# ifndef USE_ESSL
double *ptr=(double *)eigVals;
double *rePtr=(double *)epsRe, *imPtr=(double *)epsIm;
for (int i=0; i < n; i++) {
*ptr++ = *rePtr++; // eigVals[i].re = epsRe[i];
*ptr++ = *imPtr++; // eigVals[i].im = epsIm[i];
}
delete [] eigVecLeft; delete [] epsIm; delete [] epsRe; delete [] work;
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl;
SX_EXIT;
}
return (cmd == OptSize) ? (int)work[0] : 0;
# endif
}
int matEigensolver (SxComplex8 *eigVals, SxComplex8 *eigVecs,
SxComplex8 *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 2*n : size;
integer workDim = lWork;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
complex8_t *eigVecLeft = new complex8_t [ldVecLeft];
complex8_t *work = new complex8_t [workDim];
float *rWork = new float [workDim];
cgeev (&jobvl, &jobvr,
&rank, (complex8_t *)inMat, &rank,
(complex8_t *)eigVals, eigVecLeft,
&ldVecLeft, (complex8_t *)eigVecs, &rank, work, &lWork,
rWork, &info, 0, 0);
if (cmd == OptSize) lWork = (int)work[0].re;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ESSL)
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
cgeev (iOpt, (complex<float> *)inMat, rank,
(complex<float> *)eigVals, (complex<float> *)eigVecs, rank,
NULL, rank, NULL, 0);
// --- normalize eigenvectors
double c;
for (int i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
# elif defined (USE_INTEL_MKL)
MKL_Complex8 *eigVecLeft = new MKL_Complex8 [ldVecLeft];
MKL_Complex8 *work = new MKL_Complex8 [workDim];
float *rWork = new float [workDim];
cgeev (&jobvl, &jobvr,
&rank, (MKL_Complex8 *)inMat, &rank,
(MKL_Complex8 *)eigVals, eigVecLeft,
&ldVecLeft, (MKL_Complex8 *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].real;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ACML)
complex *eigVecLeft = new complex [ldVecLeft];
cgeev (jobvl, jobvr,
rank, (complex *)inMat, rank,
(complex *)eigVals, eigVecLeft,
ldVecLeft, (complex *)eigVecs, rank, &info);
delete eigVecLeft;
# else
complex *eigVecLeft = new complex [ldVecLeft];
complex *work = new complex [workDim];
real *rWork = new real [workDim];
cgeev_ (&jobvl, &jobvr,
&rank, (complex *)inMat, &rank,
(complex *)eigVals, eigVecLeft,
&ldVecLeft, (complex *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].r;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# endif
# ifndef USE_ESSL
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in CGEEV: " << info << std::endl;
SX_EXIT;
}
# endif
# if defined (USE_VECLIB)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ESSL)
return 0;
# elif defined (USE_INTEL_MKL)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ACML)
return 0;
# else
return (cmd == OptSize) ? (int)lWork : 0;
# endif
}
int matEigensolver (SxComplex16 *eigVals, SxComplex16 *eigVecs,
SxComplex16 *inMat, int n, EIGCMD cmd, int size)
{
# if defined (USE_VECLIB)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ESSL)
int rank = n, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_INTEL_MKL)
int rank = n, info = 0, ldVecLeft = 1;
int lWork = !size ? 2*n : size;
int workDim = lWork;
# elif defined (USE_ACML)
int rank = n, info = 0, ldVecLeft = 1, lWork=size;
# else
integer rank = (integer)n, info = 0, ldVecLeft = 1;
integer lWork = !size ? 2*n : size;
integer workDim = !size ? 2*n : size;
# endif
if ( cmd == OptSize ) lWork = -1;
char jobvl = 'N', jobvr = 'V';
# if defined (USE_VECLIB)
complex16_t *eigVecLeft = new complex16_t [ldVecLeft];
complex16_t *work = new complex16_t [workDim];
double *rWork = new double [workDim];
zgeev (&jobvl, &jobvr,
&rank, (complex16_t *)inMat, &rank,
(complex16_t *)eigVals, eigVecLeft,
&ldVecLeft, (complex16_t *)eigVecs, &rank, work, &lWork,
rWork, &info, 0, 0);
if (cmd == OptSize) lWork = (int)work[0].re;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# elif defined (USE_ESSL)
int iOpt = 1; // compute both vecs and vals
if (cmd != OptSize) { // not supported by ESSL
if (cmd == ValuesOnly) iOpt = 0;
zgeev (iOpt, (complex<double> *)inMat, rank,
(complex<double> *)eigVals, (complex<double> *)eigVecs, rank,
NULL, rank, NULL, 0);
// --- normalize eigenvectors
double c;
for (int i=0; i < n; i++) {
c = 1. / norm2 (&eigVecs[i*n], n);
scale (&eigVecs[i*n], c, n);
}
}
# elif defined (USE_INTEL_MKL)
MKL_Complex16 *eigVecLeft = new MKL_Complex16 [ldVecLeft];
MKL_Complex16 *work = new MKL_Complex16 [workDim];
double *rWork = new double [workDim];
zgeev (&jobvl, &jobvr,
&rank, (MKL_Complex16 *)inMat, &rank,
(MKL_Complex16 *)eigVals, eigVecLeft,
&ldVecLeft, (MKL_Complex16 *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].real;
delete [] rWork;
delete [] work;
delete [] eigVecLeft;
# elif defined (USE_ACML)
doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft];
zgeev (jobvl, jobvr,
rank, (doublecomplex *)inMat, rank,
(doublecomplex *)eigVals, eigVecLeft,
ldVecLeft, (doublecomplex *)eigVecs, rank, &info);
delete [] eigVecLeft;
# else
doublecomplex *eigVecLeft = new doublecomplex [ldVecLeft];
doublecomplex *work = new doublecomplex [workDim];
doublereal *rWork = new doublereal [workDim];
zgeev_ (&jobvl, &jobvr,
&rank, (doublecomplex *)inMat, &rank,
(doublecomplex *)eigVals, eigVecLeft,
&ldVecLeft, (doublecomplex *)eigVecs, &rank, work, &lWork,
rWork, &info);
if (cmd == OptSize) lWork = (int)work[0].r;
delete [] rWork; delete [] work; delete [] eigVecLeft;
# endif
# ifndef USE_ESSL
if ( info ) { // TODO: throw exception
std::cout << "matEigensolver: Error in DGEEV: " << info << std::endl;
SX_EXIT;
}
# endif
# if defined (USE_VECLIB)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ESSL)
return 0;
# elif defined (USE_INTEL_MKL)
return (cmd == OptSize) ? lWork : 0;
# elif defined (USE_ACML)
return 0;
# else
return (cmd == OptSize) ? (int)lWork : 0;
# endif
}
//------------------------------------------------------------------------------
// Eigensolver - tridiagonal matrices
//------------------------------------------------------------------------------
void matEigensolverTri (float *eigVals, float *eigVecs,
float *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
float *work = new float [workDim];
sspev (&jobz, &uploChar,
&rank, (float *)inMat, (float *)eigVals,
(float *)eigVecs, &ldEigVecs,
work, &info, 0, 0);
delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
sspev (iOpt, inMat, eigVals,
eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
float *work = new float [workDim];
sspev (&jobz, &uploChar,
&rank, (float *)inMat, (float *)eigVals,
(float *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
sspev (jobz, uploChar,
rank, inMat, eigVals,
eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 3*n;
real *work = new real [workDim];
sspev_ (&jobz, &uploChar,
&rank, (real *)inMat, (real *)eigVals,
(real *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in SSPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (double *eigVals, double *eigVecs,
double *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
double *work = new double [workDim];
dspev (&jobz, &uploChar,
&rank, (double *)inMat, (double *)eigVals,
(double *)eigVecs, &ldEigVecs,
work, &info, 0, 0);
delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
dspev (iOpt, inMat, eigVals,
eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 3*n;
double *work = new double [workDim];
dspev (&jobz, &uploChar,
&rank, (double *)inMat, (double *)eigVals,
(double *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
dspev (jobz, uploChar,
rank, inMat, eigVals,
eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 3*n;
doublereal *work = new doublereal [workDim];
dspev_ (&jobz, &uploChar,
&rank, (doublereal *)inMat, (doublereal *)eigVals,
(doublereal *)eigVecs, &ldEigVecs,
work, &info);
delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in DSPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (float *eigVals, SxComplex8 *eigVecs,
SxComplex8 *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
complex8_t *work = new complex8_t [workDim];
float *rWork = new float [rWorkDim];
chpev (&jobz, &uploChar,
&rank, (complex8_t *)inMat, (float *)eigVals,
(complex8_t *)eigVecs, &ldEigVecs,
work, rWork, &info, 0, 0);
delete [] rWork; delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
chpev (iOpt, (complex<float> *)inMat, eigVals,
(complex<float> *)eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
MKL_Complex8 *work = new MKL_Complex8 [workDim];
float *rWork = new float [rWorkDim];
chpev (&jobz, &uploChar,
&rank, (MKL_Complex8 *)inMat, (float *)eigVals,
(MKL_Complex8 *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
chpev (jobz, uploChar,
rank, (complex *)inMat, (float *)eigVals,
(complex *)eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 2*n-1;
integer rWorkDim = 3*n-2;
complex *work = new complex [workDim];
real *rWork = new real [rWorkDim];
chpev_ (&jobz, &uploChar,
&rank, (complex *)inMat, (real *)eigVals,
(complex *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in CHPEV: " << info << std::endl;
SX_EXIT;
}
}
void matEigensolverTri (double *eigVals, SxComplex16 *eigVecs,
SxComplex16 *inMat, int n, enum UPLO uplo,
EIGCMD
# ifdef USE_ESSL
cmd
# endif
)
{
char jobz = 'V';
char uploChar = (uplo == UpperRight ? 'U' : 'L');
# if defined (USE_VECLIB)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
complex16_t *work = new complex16_t [workDim];
double *rWork = new double[rWorkDim];
zhpev (&jobz, &uploChar,
&rank, (complex16_t *)inMat, (double *)eigVals,
(complex16_t *)eigVecs, &ldEigVecs,
work, rWork, &info, 0, 0);
delete [] rWork; delete [] work;
# elif defined (USE_ESSL)
int info = 0, iOpt = 1;
if (cmd == VectorsOnly) iOpt = 0;
if (uplo == UpperRight) iOpt += 20;
int rank = n;
zhpev (iOpt, (complex<double> *)inMat, eigVals,
(complex<double> *)eigVecs, rank, n, NULL, 0);
# elif defined (USE_INTEL_MKL)
int rank = n;
int ldEigVecs = rank;
int info = 0;
int workDim = 2*n-1;
int rWorkDim = 3*n-2;
MKL_Complex16 *work = new MKL_Complex16 [workDim];
double *rWork = new double[rWorkDim];
zhpev (&jobz, &uploChar,
&rank, (MKL_Complex16 *)inMat, (double *)eigVals,
(MKL_Complex16 *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# elif defined (USE_ACML)
int rank = n;
int ldEigVecs = rank;
int info = 0;
zhpev (jobz, uploChar,
rank, (doublecomplex *)inMat, (double *)eigVals,
(doublecomplex *)eigVecs, ldEigVecs, &info);
# else
integer rank = (integer)n;
integer ldEigVecs = rank;
integer info = 0;
integer workDim = 2*n-1;
integer rWorkDim = 3*n-2;
doublecomplex *work = new doublecomplex [workDim];
doublereal *rWork = new doublereal [rWorkDim];
zhpev_ (&jobz, &uploChar,
&rank, (doublecomplex *)inMat, (doublereal *)eigVals,
(doublecomplex *)eigVecs, &ldEigVecs,
work, rWork, &info);
delete [] rWork; delete [] work;
# endif
if ( info ) { // TODO: throw exception
std::cout << "matEigensolverHerm: Error in ZHPEV: " << info << std::endl;
SX_EXIT;
}
}
// -------------------------- SX_IGNORE_THE_REST_OF_THE_FILE
# endif
// --------------------------
| 36.127718 | 90 | 0.524202 |
f4e35f80c0c5af0818c4a4e061d12b0d1d2fb196 | 890 | tpp | C++ | lib/include/ellcpp/oracles/sdp_oracle.tpp | luk036/ellcpp | 3415e7ffb70b63edb9ce4d6c2b9fee92898538bc | [
"MIT"
] | 2 | 2020-07-26T04:58:11.000Z | 2021-01-26T06:29:59.000Z | lib/include/ellcpp/oracles/sdp_oracle.tpp | luk036/ellcpp | 3415e7ffb70b63edb9ce4d6c2b9fee92898538bc | [
"MIT"
] | null | null | null | lib/include/ellcpp/oracles/sdp_oracle.tpp | luk036/ellcpp | 3415e7ffb70b63edb9ce4d6c2b9fee92898538bc | [
"MIT"
] | 2 | 2018-06-03T08:20:20.000Z | 2019-06-30T10:41:49.000Z | // -*- coding: utf-8 -*-
#pragma once
#include "lmi_oracle.hpp"
namespace bnu = boost::numeric::ublas;
class sdp_oracle
{
using Mat = bnu::symmetric_matrix<double, bnu::upper>;
using Vec = bnu::vector<double>;
using Arr = bnu::vector<Mat>;
public:
sdp_oracle(const Vec& c, const Arr& F)
: _c {c}
, _lmi {lmi_oracle(F)}
{
}
auto operator()(const Vec& x, double& t) const
{
auto [g, fj] = _lmi.chk_spd(x);
if (fj > 0)
{
return std::make_tuple(g, fj, false);
}
auto f0 = bnu::inner_prod(_c, x);
fj = f0 - t;
g = _c;
if (fj > 0)
{
return std::make_tuple(g, fj, false);
}
t = f0;
return std::make_tuple(g, 0., true);
}
private:
const Vec& _c;
lmi_oracle _lmi;
};
| 20.697674 | 59 | 0.477528 |
f4e85aaa6bbe122fff1af5ec5d461311f2ed6228 | 10,000 | hpp | C++ | metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp | juanbarrios/multimedia_tools | 91fe64779168c3dd3ad4e51e089df9ccad5f176b | [
"BSD-2-Clause"
] | 6 | 2015-09-08T00:14:59.000Z | 2018-09-11T09:46:40.000Z | metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp | juanbarrios/multimedia_tools | 91fe64779168c3dd3ad4e51e089df9ccad5f176b | [
"BSD-2-Clause"
] | null | null | null | metricknn/metricknn_lib/src/metricknn/metricknn_cpp/mknn_predefined_distance.hpp | juanbarrios/multimedia_tools | 91fe64779168c3dd3ad4e51e089df9ccad5f176b | [
"BSD-2-Clause"
] | 1 | 2020-11-13T15:55:30.000Z | 2020-11-13T15:55:30.000Z | /*
* Copyright (C) 2012-2015, Juan Manuel Barrios <http://juan.cl/>
* All rights reserved.
*
* This file is part of MetricKnn. http://metricknn.org/
* MetricKnn is made available under the terms of the BSD 2-Clause License.
*/
#ifndef MKNN_PREDEFINED_DISTANCE_HPP_
#define MKNN_PREDEFINED_DISTANCE_HPP_
#include "../metricknn_cpp.hpp"
namespace mknn {
/**
* MetricKnn provides a set of pre-defined distances.
*
* The generic way for instantiating a predefined distance is to use the method
* Distance::newPredefined, which requires the ID and parameters of the distance.
*
* The complete list of predefined distances can be listed by calling
* Distance::helpListDistances. The parameters supported by each distance
* can be listed by calling PredefDistance::helpPrintDistance.
*
* This class contains some functions to ease the instantiation of some predefined distances.
*
*/
class PredefDistance {
public:
/**
* @name Help functions
* @{
*/
/**
* Lists to standard output all pre-defined distances.
*/
static void helpListDistances();
/**
* Prints to standard output the help for a distance.
*
* @param id_dist the unique identifier of a pre-defined distance.
*/
static void helpPrintDistance(std::string id_dist);
/**
* Tests whether the given string references a valid pre-defined distance.
*
* @param id_dist the unique identifier of a pre-defined distance.
* @return true whether @p id_dist corresponds to a pre-defined distance, and false otherwise.
*/
static bool testDistanceId(std::string id_dist);
/**
* @}
*/
/**
* Creates an object for Manhattan or Taxi-cab distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{L1}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^{n} |x_i - y_i|
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams L1();
/**
* Creates an object for Euclidean distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{L2}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sqrt{ \sum_{i=1}^{n} (x_i - y_i)^2 }
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams L2();
/**
* Creates an object for L-max distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Lmax}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \max_{i \in \{1,...,n\}} |x_i - y_i|
* \f]
*
* This distance satisfies the metric properties, therefore it can be used by Metric Indexes to obtain exact nearest neighbors.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Lmax();
/**
* Creates an object for Minkowski distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Lp}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \left( {\sum_{i=1}^n |x_i-y_i|^p } \right)^{\frac{1}{p}}
* \f]
*
* @note This distance satisfies the metric properties only when \f$ p \geq 1 \f$.
* When \f$ 0 < p < 1 \f$ the Metric Indexes may not obtain exact nearest neighbors.
*
* @param order the order \f$ p \f$ of the distance \f$ p > 0 \f$.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Lp(double order);
/**
* Creates an object for Hamming distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Hamming}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^n \bar{p}_i
* \f]
*
* where \f$ \bar{p}_i= \left\{ \begin{array}{ll} 0 & x_i = y_i\\ 1 & x_i \neq y_i\\ \end{array} \right. \f$ .
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Hamming();
/**
* Creates an object for Chi2 distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \chi^2(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sum_{i=1}^n \frac{ (x_i - \bar{m}_i )^2 }{ \bar{m}_i }
* \f]
*
* where \f$ \bar{m}_i=\frac{x_i+y_i}{2} \f$ .
*
* @note This distance does not satisfy the metric properties.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Chi2();
/**
* Creates an object for Hellinger distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{Hellinger}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \sqrt { \frac { \sum_{i=1}^n ( \sqrt{x_i} - \sqrt{y_i} )^2} { 2 } }
* \f]
*
* @note This distance does not satisfy the metric properties.
*
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams Hellinger();
/**
* Creates an object for Cosine Similarity.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{cos}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \frac { \sum_{i=1}^n x_i \cdot y_i } {\sqrt{ \sum_{i=1}^{n} {x_i}^2 } \cdot \sqrt{ \sum_{i=1}^{n} {y_i}^2 } }
* \f]
*
* @note This is a similarity function, therefore a search for the Farthest Neighbors is needed. See #CosineDistance
* for a distance version.
*
* @param normalize_vectors Computes the euclidean norm for each vector. If this is set to false, it assumes the vectors are already normalized
* thus the value \f$ \sqrt{ \sum_{i=1}^{n} {x_i}^2 } \cdot \sqrt{ \sum_{i=1}^{n} {y_i}^2 } \f$ is equal to 1.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams CosineSimilarity(bool normalize_vectors);
/**
* Creates an object for Cosine Distance.
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{CosineDistance}(\vec{x},\vec{y}) = \sqrt{ 2 ( 1 - \cos(\vec{x},\vec{y})) }
* \f]
*
* where \f$ \cos(\vec{x},\vec{y}) \f$ is the cosine similarity between vectors \f$ \vec{x} \f$ and \f$ \vec{y} \f$ as defined in #CosineSimilarity.
*
* The nearest neighbors obtained by this distance are identical to the farthest neighbor obtained by cosine similarity (if vectors
* are normalized). Therefore, this distance can be used accelerate the search using cosine similarity.
*
* @param normalize_vectors The cosine similarity must normalize vectors to euclidean norm 1 prior to each computation.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams CosineDistance(bool normalize_vectors);
/**
* Creates an object for Earth Mover's Distance.
*
* This function uses OpenCV's implementation, see http://docs.opencv.org/modules/imgproc/doc/histograms.html#emd .
*
* @note Depending on the cost_matrix this distance may or may not satisfy the metric properties. If the values in cost_matrix
* where computed by a metric distance, then the EMD will also be a metric distance.
*
* @param matrix_rows
* @param matrix_cols
* @param cost_matrix an array of length <tt>matrix_rows * matrix_cols</tt> with the
* cost for each pair of dimensions.
* @param normalize_vectors normalizes (sum 1) both vectors before computing the distance.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams EMD(long long matrix_rows, long long matrix_cols,
double *cost_matrix, bool normalize_vectors);
/**
* Creates an object for Dynamic Partial Function distance. See definition http://dx.doi.org/10.1109/ICIP.2002.1040021 .
*
* The distance between two n-dimensional vectors is defined as:
* \f[
* \textrm{DPF}(\{x_1,...,x_n\},\{y_1,...,y_n\}) = \left( {\sum_{i \in \Delta_m} |x_i-y_i|^p } \right)^{\frac{1}{p}}
* \f]
*
* where \f$ \Delta_m \f$ is the subset of the \f$ m \f$ smallest values of \f$ |x_i-y_i| \f$.
*
* @param order the order \f$ p \f$ of the distance \f$ p > 0 \f$.
* @param num_dims_discard fixed number of dimensions to discard <tt>0 @< num_dims_discard @< num_dimensions</tt>.
* @param pct_discard fixed number of dimensions to discard computed as a fraction of @p num_dimensions <tt>0 @< pct_discard @< 1</tt>.
* <tt>num_dims_discard = round(pct_discard * num_dimensions)</tt>
* @param threshold_discard discard all dimensions which difference is higher than @p threshold_discard.
* It produces a variable number of dimensions to discard.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams DPF(double order, long long num_dims_discard,
double pct_discard, double threshold_discard);
/**
* Defines a multi-distance, which is a weighted combination of distances.
*
* @warning Under construction.
*
* @param subdistances the distances to combine
* @param free_subdistances_on_release to release the subdistances together with this distance
* @param normalization_values the value to divide each distance.
* @param ponderation_values the value to weight each distance.
* @param with_auto_config run algorithms to automatically locate normalization or ponderation values.
* @param auto_config_dataset the data to be used by the algorithms.
* @param auto_normalize_alpha the value to be used by the alpha-normalization.
* @param auto_ponderation_maxrho run the automatic ponderation according to max rho criterium.
* @param auto_ponderation_maxtau run the automatic ponderation according to max tau criterium.
* @return parameters to create a distance (it must be deleted)
*/
static DistanceParams MultiDistance(
const std::vector<Distance> &subdistances,
bool free_subdistances_on_release,
const std::vector<double> &normalization_values,
const std::vector<double> &ponderation_values,
bool with_auto_config, Dataset &auto_config_dataset,
double auto_normalize_alpha, bool auto_ponderation_maxrho,
bool auto_ponderation_maxtau);
};
}
#endif
| 37.593985 | 162 | 0.6887 |
f4e96d63ad6cb13ab1d635f38a2c82281158d907 | 4,545 | cpp | C++ | Engine/__Deprecated/ImGui/ImUtil.cpp | zolo-mario/ZeloEngine | e595467dd057157c47cc8fa91399b0c7137dae63 | [
"MIT"
] | 98 | 2019-09-13T16:00:57.000Z | 2022-03-25T05:15:36.000Z | Engine/__Deprecated/ImGui/ImUtil.cpp | zolo-mario/ZeloEngine | e595467dd057157c47cc8fa91399b0c7137dae63 | [
"MIT"
] | 269 | 2019-08-22T01:47:09.000Z | 2021-12-01T14:47:47.000Z | Engine/__Deprecated/ImGui/ImUtil.cpp | zolo-mario/ZeloEngine | e595467dd057157c47cc8fa91399b0c7137dae63 | [
"MIT"
] | 5 | 2021-05-07T11:11:40.000Z | 2022-03-29T08:38:33.000Z | // ImUtil.cpp
// created on 2021/5/28
// author @zoloypzuo
#include "ZeloPreCompiledHeader.h"
#include "ImUtil.h"
#include "ImGuiInternal.h"
int ImStricmp(const char *str1, const char *str2) {
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) {
str1++;
str2++;
}
return d;
}
const char *ImStristr(const char *haystack, const char *needle, const char *needle_end) {
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = toupper(*needle);
while (*haystack) {
if (toupper(*haystack) == un0) {
const char *b = needle + 1;
for (const char *a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
ImU32 crc32(const void *data, size_t data_size, ImU32 seed) {
static ImU32 crc32_lut[256] = {0};
if (!crc32_lut[1]) {
const ImU32 polynomial = 0xEDB88320;
for (ImU32 i = 0; i < 256; i++) {
ImU32 crc = i;
for (ImU32 j = 0; j < 8; j++)
crc = (crc >> 1) ^ (-int(crc & 1) & polynomial);
crc32_lut[i] = crc;
}
}
ImU32 crc = ~seed;
const unsigned char *current = (const unsigned char *) data;
while (data_size--)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
return ~crc;
}
size_t ImFormatString(char *buf, size_t buf_size, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
buf[buf_size - 1] = 0;
if (w == -1) w = buf_size;
return w;
}
size_t ImFormatStringV(char *buf, size_t buf_size, const char *fmt, va_list args) {
int w = vsnprintf(buf, buf_size, fmt, args);
buf[buf_size - 1] = 0;
if (w == -1) w = buf_size;
return w;
}
ImU32 ImConvertColorFloat4ToU32(const ImVec4 &in) {
ImU32 out = ((ImU32) (ImSaturate(in.x) * 255.f));
out |= ((ImU32) (ImSaturate(in.y) * 255.f) << 8);
out |= ((ImU32) (ImSaturate(in.z) * 255.f) << 16);
out |= ((ImU32) (ImSaturate(in.w) * 255.f) << 24);
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImConvertColorRGBtoHSV(float r, float g, float b, float &out_h, float &out_s, float &out_v) {
float K = 0.f;
if (g < b) {
const float tmp = g;
g = b;
b = tmp;
K = -1.f;
}
if (r < g) {
const float tmp = r;
r = g;
g = tmp;
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = abs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImConvertColorHSVtoRGB(float h, float s, float v, float &out_r, float &out_g, float &out_b) {
if (s == 0.0f) {
// gray
out_r = out_g = out_b = v;
return;
}
h = fmodf(h, 1.0f) / (60.0f / 360.0f);
int i = (int) h;
float f = h - (float) i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i) {
case 0:
out_r = v;
out_g = t;
out_b = p;
break;
case 1:
out_r = q;
out_g = v;
out_b = p;
break;
case 2:
out_r = p;
out_g = v;
out_b = t;
break;
case 3:
out_r = p;
out_g = q;
out_b = v;
break;
case 4:
out_r = t;
out_g = p;
out_b = v;
break;
case 5:
default:
out_r = v;
out_g = p;
out_b = q;
break;
}
}
//-----------------------------------------------------------------------------
ImGuiOncePerFrame::ImGuiOncePerFrame() : LastFrame(-1) {}
bool ImGuiOncePerFrame::TryIsNewFrame() const {
const int current_frame = ImGui::GetFrameCount();
if (LastFrame == current_frame) return false;
LastFrame = current_frame;
return true;
}
ImGuiOncePerFrame::operator bool() const { return TryIsNewFrame(); }
| 27.545455 | 102 | 0.492629 |
f4edd60f9853e6fd95b8846f13265c60b1d426d9 | 3,854 | cpp | C++ | manycal/nodes/camera_throttler.cpp | Humhu/argus | 8b112382038c6df1ecf15d9c872b6cc9b471cd22 | [
"AFL-3.0"
] | 6 | 2017-08-02T20:32:52.000Z | 2021-06-15T09:33:33.000Z | manycal/nodes/camera_throttler.cpp | Humhu/argus | 8b112382038c6df1ecf15d9c872b6cc9b471cd22 | [
"AFL-3.0"
] | 1 | 2018-03-12T22:57:59.000Z | 2018-03-13T02:52:36.000Z | manycal/nodes/camera_throttler.cpp | Humhu/argus | 8b112382038c6df1ecf15d9c872b6cc9b471cd22 | [
"AFL-3.0"
] | 4 | 2017-03-25T08:36:17.000Z | 2019-04-23T00:28:16.000Z | #include <ros/ros.h>
#include <deque>
#include <boost/foreach.hpp>
#include "image_transport/image_transport.h"
#include "cv_bridge/cv_bridge.h"
#include "argus_utils/synchronization/MessageThrottler.hpp"
#include "manycal/SetThrottleWeight.h"
#include "argus_utils/utils/ParamUtils.h"
using namespace argus;
class CameraThrottler
{
public:
CameraThrottler( ros::NodeHandle& nh, ros::NodeHandle& ph )
: publicPort( nh )
{
// TODO Parameters for _throttle?
unsigned int buffLen;
GetParamRequired( ph, "buffer_length", buffLen );
double r;
GetParamRequired( ph, "max_rate", r );
_throttle.SetBufferLength( buffLen );
_throttle.SetTargetRate( r );
GetParamRequired( ph, "update_rate", r );
_updateTimer = nh.createTimer( ros::Duration( 1.0/r ), &CameraThrottler::TimerCallback, this );
YAML::Node sources;
GetParamRequired( ph, "sources", sources );
YAML::Node::const_iterator iter;
for( iter = sources.begin(); iter != sources.end(); ++iter )
{
const std::string& name = iter->first.as<std::string>();
const YAML::Node& info = iter->second;
std::string input_topic, output_topic;
GetParamRequired( info, "input", input_topic );
GetParamRequired( info, "output", output_topic );
ROS_INFO_STREAM( "Registering source " << name << " with input " << input_topic <<
" and output " << output_topic );
_throttle.RegisterSource( name );
_throttle.SetSourceWeight( name, 1.0 );
_subscribers.emplace_back(
publicPort.subscribeCamera(input_topic, 10,
boost::bind(&CameraThrottler::CameraCallback, this, name, _1, _2)) );
_publishers[name] = publicPort.advertiseCamera(output_topic, 10);
}
_throttleServer = ph.advertiseService( "set_throttle", &CameraThrottler::SetThrottleCallback,
this );
}
private:
ros::Timer _updateTimer;
ros::ServiceServer _throttleServer;
image_transport::ImageTransport publicPort;
std::deque<image_transport::CameraSubscriber> _subscribers;
std::map<std::string, image_transport::CameraPublisher> _publishers;
typedef std::pair<sensor_msgs::Image::ConstPtr, sensor_msgs::CameraInfo::ConstPtr> CameraData;
typedef MessageThrottler<CameraData> DataThrottler;
DataThrottler _throttle;
bool SetThrottleCallback( manycal::SetThrottleWeight::Request& req,
manycal::SetThrottleWeight::Response& res )
{
try
{
_throttle.SetSourceWeight( req.name, req.weight );
return true;
}
catch ( const std::invalid_argument& e )
{
return false;
}
}
void TimerCallback( const ros::TimerEvent& event )
{
DataThrottler::KeyedData out;
if( _throttle.GetOutput( event.current_real.toSec(), out ) )
{
_publishers[out.first].publish( out.second.first, out.second.second );
}
}
void CameraCallback( const std::string& name,
const sensor_msgs::Image::ConstPtr& image,
const sensor_msgs::CameraInfo::ConstPtr& info )
{
_throttle.BufferData( name, CameraData( image, info ) );
}
};
int main( int argc, char** argv )
{
ros::init( argc, argv, "camera_throttler" );
ros::NodeHandle nh;
ros::NodeHandle ph( "~" );
unsigned int numThreads;
GetParam<unsigned int>( ph, "num_threads", numThreads, 1 );
CameraThrottler throttler( nh, ph );
// ros::spin();
ros::AsyncSpinner spinner( numThreads );
spinner.start();
ros::waitForShutdown();
return 0;
}
| 31.080645 | 103 | 0.614427 |