text stringlengths 54 60.6k |
|---|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "geojson_datasource.hpp"
#include "geojson_featureset.hpp"
#include "large_geojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
// mapnik
#include <mapnik/boolean.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/geometry_to_ds_type.hpp>
#include <mapnik/util/variant.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/make_unique.hpp>
#include <mapnik/json/feature_collection_grammar.hpp>
#include <mapnik/json/extract_bounding_box_grammar_impl.hpp>
#include <mapnik/util/boost_geometry_adapters.hpp> // boost.geometry - register box2d<double>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(geojson_datasource)
struct attr_value_converter
{
mapnik::eAttributeType operator() (mapnik::value_integer) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& ) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& ) const
{
return mapnik::String;
}
};
geojson_datasource::geojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(geojson_datasource::name(),
*params.get<std::string>("encoding","utf-8")),
filename_(),
inline_string_(),
extent_(),
features_(),
tree_(nullptr)
{
boost::optional<std::string> inline_string = params.get<std::string>("inline");
if (inline_string)
{
inline_string_ = *inline_string;
}
else
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
filename_ = *base + "/" + *file;
else
filename_ = *file;
}
if (!inline_string_.empty())
{
parse_geojson(inline_string_);
}
else
{
mapnik::util::file file(filename_);
if (!file.open())
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'");
}
std::string file_buffer;
file_buffer.resize(file.size());
std::fread(&file_buffer[0], file.size(), 1, file.get());
cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true);
if (cache_features_)
{
parse_geojson(file_buffer);
}
else
{
initialise_index(file_buffer.begin(), file_buffer.end());
}
}
}
namespace {
using base_iterator_type = std::string::const_iterator;
const mapnik::transcoder tr("utf8");
const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> fc_grammar(tr);
}
template <typename Iterator>
void geojson_datasource::initialise_index(Iterator start, Iterator end)
{
mapnik::json::boxes boxes;
mapnik::json::extract_bounding_box_grammar<Iterator> bbox_grammar;
boost::spirit::standard_wide::space_type space;
if (!boost::spirit::qi::phrase_parse(start, end, (bbox_grammar)(boost::phoenix::ref(boxes)) , space))
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'");
}
std::cerr << "OK size=" << boxes.size() << std::endl;
std::cerr << "Populate index" << std::endl;
#if BOOST_VERSION >= 105600
tree_ = std::make_unique<spatial_index_type>(boxes);
#else
tree_ = std::make_unique<spatial_index_type>(16, 4);
#endif
std::cerr << "Calculate total extent" << std::endl;
for (auto const& item : boxes)
{
auto const& box = std::get<0>(item);
#if BOOST_VERSION < 105600
auto const& geometry_index = std::get<1>(item);
tree_->insert(box, geometry_index);
#endif
if (!extent_.valid())
{
extent_ = box;
}
else
{
extent_.expand_to_include(box);
}
}
std::cerr << "Extent: " << extent_ << std::endl;
}
template <typename T>
void geojson_datasource::parse_geojson(T const& buffer)
{
boost::spirit::standard_wide::space_type space;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
std::size_t start_id = 1;
bool result = boost::spirit::qi::phrase_parse(buffer.begin(), buffer.end(), (fc_grammar)
(boost::phoenix::ref(ctx),boost::phoenix::ref(start_id)),
space, features_);
if (!result)
{
if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string");
else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'");
}
#if BOOST_VERSION >= 105600
using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>;
values_container values;
values.reserve(features_.size());
#else
tree_ = std::make_unique<spatial_index_type>(16, 4);
#endif
std::size_t geometry_index = 0;
for (mapnik::feature_ptr const& f : features_)
{
mapnik::box2d<double> box = f->envelope();
if (box.valid())
{
if (geometry_index == 0)
{
extent_ = box;
for ( auto const& kv : *f)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
#if BOOST_VERSION >= 105600
values.emplace_back(box, std::make_pair(geometry_index,0));
#else
tree_->insert(box, std::make_pair(geometry_index));
#endif
++geometry_index;
}
#if BOOST_VERSION >= 105600
// packing algorithm
tree_ = std::make_unique<spatial_index_type>(values);
#endif
}
geojson_datasource::~geojson_datasource() { }
const char * geojson_datasource::name()
{
return "geojson";
}
boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
unsigned num_features = features_.size();
for (unsigned i = 0; i < num_features && i < 5; ++i)
{
mapnik::util::to_ds_type(features_[i]->paths(),result);
if (result)
{
int type = static_cast<int>(*result);
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t geojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> geojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor geojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& box = q.get_bbox();
if (extent_.intersects(box))
{
#if BOOST_VERSION >= 105600
geojson_featureset::array_type index_array;
if (tree_)
{
tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array));
if (cache_features_)
{
return std::make_shared<geojson_featureset>(features_, std::move(index_array));
}
else
{
std::cerr << "Query size=" << index_array.size() << std::endl;
std::cerr << "Sort index_array by offsets" << std::endl;
std::sort(index_array.begin(),index_array.end(),
[] (item_type const& item0, item_type const& item1)
{
return item0.second.first < item1.second.first;
});
std::cerr << "Done" << std::endl;
return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array));
}
}
#else
if (tree_)
{
if (cache_features_)
return std::make_shared<geojson_featureset>(features_, tree_->find(box));
else
return std::make_shared<large_geojson_featureset>(features_, tree_->find(box));
}
#endif
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors();
std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
for ( ;itr!=end;++itr)
{
q.add_property_name(itr->get_name());
}
return features(q);
}
<commit_msg>extract attributes schema + remove std::cerr<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "geojson_datasource.hpp"
#include "geojson_featureset.hpp"
#include "large_geojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
// mapnik
#include <mapnik/boolean.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/geometry_to_ds_type.hpp>
#include <mapnik/util/variant.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/make_unique.hpp>
#include <mapnik/json/feature_collection_grammar.hpp>
#include <mapnik/json/extract_bounding_box_grammar_impl.hpp>
#include <mapnik/util/boost_geometry_adapters.hpp> // boost.geometry - register box2d<double>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(geojson_datasource)
struct attr_value_converter
{
mapnik::eAttributeType operator() (mapnik::value_integer) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& ) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& ) const
{
return mapnik::String;
}
};
geojson_datasource::geojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(geojson_datasource::name(),
*params.get<std::string>("encoding","utf-8")),
filename_(),
inline_string_(),
extent_(),
features_(),
tree_(nullptr)
{
boost::optional<std::string> inline_string = params.get<std::string>("inline");
if (inline_string)
{
inline_string_ = *inline_string;
}
else
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
filename_ = *base + "/" + *file;
else
filename_ = *file;
}
if (!inline_string_.empty())
{
parse_geojson(inline_string_);
}
else
{
mapnik::util::file file(filename_);
if (!file.open())
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'");
}
std::string file_buffer;
file_buffer.resize(file.size());
std::fread(&file_buffer[0], file.size(), 1, file.get());
cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true);
if (cache_features_)
{
parse_geojson(file_buffer);
}
else
{
initialise_index(file_buffer.begin(), file_buffer.end());
}
}
}
namespace {
using base_iterator_type = std::string::const_iterator;
const mapnik::transcoder tr("utf8");
const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> fc_grammar(tr);
}
template <typename Iterator>
void geojson_datasource::initialise_index(Iterator start, Iterator end)
{
mapnik::json::boxes boxes;
mapnik::json::extract_bounding_box_grammar<Iterator> bbox_grammar;
boost::spirit::standard_wide::space_type space;
if (!boost::spirit::qi::phrase_parse(start, end, (bbox_grammar)(boost::phoenix::ref(boxes)) , space))
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'");
}
#if BOOST_VERSION >= 105600
tree_ = std::make_unique<spatial_index_type>(boxes);
#else
tree_ = std::make_unique<spatial_index_type>(16, 4);
#endif
for (auto const& item : boxes)
{
auto const& box = std::get<0>(item);
auto const& geometry_index = std::get<1>(item);
#if BOOST_VERSION < 105600
tree_->insert(box, geometry_index);
#endif
if (!extent_.valid())
{
extent_ = box;
// parse first feature to extract attributes schema.
// NOTE: this doesn't yield correct answer for geoJSON in general, just an indication
mapnik::util::file file(filename_);
if (!file.open())
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'");
}
std::fseek(file.get(), geometry_index.first, SEEK_SET);
std::vector<char> json;
json.resize(geometry_index.second);
std::fread(json.data(), geometry_index.second, 1, file.get());
using chr_iterator_type = std::vector<char>::const_iterator;
chr_iterator_type start = json.begin();
chr_iterator_type end = json.end();
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
using namespace boost::spirit;
standard_wide::space_type space;
if (!qi::phrase_parse(start, end, (fc_grammar.feature_g)(boost::phoenix::ref(*feature)), space))
{
throw std::runtime_error("Failed to parse geojson feature");
}
for ( auto const& kv : *feature)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
}
template <typename T>
void geojson_datasource::parse_geojson(T const& buffer)
{
boost::spirit::standard_wide::space_type space;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
std::size_t start_id = 1;
bool result = boost::spirit::qi::phrase_parse(buffer.begin(), buffer.end(), (fc_grammar)
(boost::phoenix::ref(ctx),boost::phoenix::ref(start_id)),
space, features_);
if (!result)
{
if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string");
else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'");
}
#if BOOST_VERSION >= 105600
using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>;
values_container values;
values.reserve(features_.size());
#else
tree_ = std::make_unique<spatial_index_type>(16, 4);
#endif
std::size_t geometry_index = 0;
for (mapnik::feature_ptr const& f : features_)
{
mapnik::box2d<double> box = f->envelope();
if (box.valid())
{
if (geometry_index == 0)
{
extent_ = box;
for ( auto const& kv : *f)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
#if BOOST_VERSION >= 105600
values.emplace_back(box, std::make_pair(geometry_index,0));
#else
tree_->insert(box, std::make_pair(geometry_index));
#endif
++geometry_index;
}
#if BOOST_VERSION >= 105600
// packing algorithm
tree_ = std::make_unique<spatial_index_type>(values);
#endif
}
geojson_datasource::~geojson_datasource() { }
const char * geojson_datasource::name()
{
return "geojson";
}
boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
unsigned num_features = features_.size();
for (unsigned i = 0; i < num_features && i < 5; ++i)
{
mapnik::util::to_ds_type(features_[i]->paths(),result);
if (result)
{
int type = static_cast<int>(*result);
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t geojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> geojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor geojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& box = q.get_bbox();
if (extent_.intersects(box))
{
#if BOOST_VERSION >= 105600
geojson_featureset::array_type index_array;
if (tree_)
{
tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array));
if (cache_features_)
{
return std::make_shared<geojson_featureset>(features_, std::move(index_array));
}
else
{
std::sort(index_array.begin(),index_array.end(),
[] (item_type const& item0, item_type const& item1)
{
return item0.second.first < item1.second.first;
});
return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array));
}
}
#else
if (tree_)
{
if (cache_features_)
return std::make_shared<geojson_featureset>(features_, tree_->find(box));
else
return std::make_shared<large_geojson_featureset>(features_, tree_->find(box));
}
#endif
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors();
std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
for ( ;itr!=end;++itr)
{
q.add_property_name(itr->get_name());
}
return features(q);
}
<|endoftext|> |
<commit_before>#include <Patcher/Patcher.hpp>
#include <Patcher/Config.hpp>
#include <Patcher/WebConnection.hpp>
#include <QProgressBar>
#include <QListWidgetItem>
#include <QLabel>
#include <QGroupBox>
#include <QScrollArea>
#include <QMessageBox>
#include <Patcher/Config.hpp>
#include <Patcher/Log.hpp>
#include <iostream>
#define ADD_ACTION(parent,var,str) QAction* var = new QAction(str,this);\
parent->addAction(var);
#define ADD_MENU(parent,var,str) QMenu* var = parent->addMenu(str);
namespace patcher
{
Patcher::Patcher(const std::string& soft) : QMainWindow(), maj_avalible(0)//, logList(nullptr)
{
patcher::Config::softname = soft;
setWindowTitle(("Patcher - "+soft).c_str());
initMenu();
iniMainArea();
soft_thread.setStandardOutputFile(("logs/"+soft+".txt").c_str(),QIODevice::Append);
soft_thread.setStandardErrorFile(("logs/"+soft+".err.txt").c_str(),QIODevice::Append);
QStringList env = QProcess::systemEnvironment();
env<<"LD_LIBRARY_PATH=.";
soft_thread.setEnvironment(env);
}
Patcher::~Patcher()
{
}
void Patcher::start()
{
configMaj();
}
//// SLOTS //////
void Patcher::showVersion()const
{
QMessageBox::information(nullptr,"Version","Version acctuelle:\n"+QString(Config::numberToString(Config::getVersion()).c_str()));
}
void Patcher::configSetUrl()const
{
Config::setUrl();
Config::makeFile();
}
void Patcher::configMaj()
{
Config::init();
patcher::WebConnection con;
std::list<Log> logs;
majs = con.getMaj(logs);
//layout.clear();
for(Log& log : logs)
{
QLabel* widget = new QLabel((log.getNumber()
+": "
+log.getMsg()).c_str());
//widget->setMinimumSize(widget->minimumSizeHint());
this->layout.addWidget(widget);
std::cout<<log.getNumber()<<" "<<log.getMsg()<<std::endl;
}
maj_avalible = majs.size();
if(maj_avalible > 0)
{
execMaj();
}
}
void Patcher::configReset()const
{
Config::makeDefault();
}
void Patcher::runSoft()
{
QString name = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + QDir::separator() + Config::softname.c_str()).toString();
#if __WIN32
name +=".exe";
#endif
soft_thread.start(name);
}
void Patcher::quit()
{
if(soft_thread.state() == QProcess::Running)
{
QMessageBox::warning(nullptr,"Error",QString((Config::softname+" is running. Close it.").c_str()));
}
else
qApp->quit();
}
////////
void Patcher::initMenu()
{
//Fichier
QMenu* menuFichier = menuBar()->addMenu("&Fichier");
///Quitter
ADD_ACTION(menuFichier,actionRun,("Lancer" + Config::softname).c_str());
connect(actionRun, SIGNAL(triggered()),this, SLOT(runSoft()));
actionRun->setShortcut(QKeySequence("Ctrl+Enter"));
ADD_ACTION(menuFichier,actionQuitter,"&Quitter");
connect(actionQuitter, SIGNAL(triggered()),this, SLOT(quit()));
actionQuitter->setShortcut(QKeySequence("Ctrl+Q"));
//actionQuitter->setIcon(QIcon("quitter.png"));
//Edition
QMenu* menuEdition = menuBar()->addMenu("&Edition");
//actionGras->setCheckable(true);
ADD_MENU(menuEdition,menuConfiguration,"&Configuration");
ADD_ACTION(menuConfiguration,actionConfigurationUrl,"Definir l'url du site");
connect(actionConfigurationUrl,SIGNAL(triggered()),this,SLOT(configSetUrl()));
ADD_ACTION(menuConfiguration,actionConfigurationMaj,"Lancer une Maj");
connect(actionConfigurationMaj,SIGNAL(triggered()),this,SLOT(configMaj()));
actionConfigurationMaj->setShortcut(QKeySequence("F5"));
ADD_ACTION(menuConfiguration,actionConfigurationReset,"Reset");
connect(actionConfigurationReset,SIGNAL(triggered()),this,SLOT(configReset()));
actionConfigurationReset->setShortcut(QKeySequence("Ctrl+L"));
//Aide
QMenu* menuAide = menuBar()->addMenu("&Aide");
///Version
ADD_ACTION(menuAide,actionVersion,"&Version")
connect(actionVersion, SIGNAL(triggered()),this, SLOT(showVersion()));
}
void Patcher::iniMainArea()
{
QWidget* zoneCentrale = new QScrollArea;
zoneCentrale->setLayout(&layout);
setCentralWidget(zoneCentrale);
}
int Patcher::execMaj()
{
if (maj_avalible <= 0)
return 0;
QProgressBar progressBar;
progressBar.setMaximumHeight(16);
progressBar.setMaximumWidth(200);
//progressBar->setTextVisible(false);
progressBar.setRange(0,maj_avalible);
this->statusBar()->addPermanentWidget(&progressBar, 0);
this->statusBar()->showMessage(QString("Loading"));
int nb = 0;
int i = 1;
for(patcher::Maj& maj : majs)
{
this->statusBar()->showMessage(QString("download "+QString::number(i)+"/"+QString::number(maj_avalible)));
if(not maj.isDone())
nb+= maj.apply();
progressBar.setValue(++i);
}
this->statusBar()->clearMessage();
this->statusBar()->removeWidget(&progressBar);
return nb;
}
}
<commit_msg>chage window size<commit_after>#include <Patcher/Patcher.hpp>
#include <Patcher/Config.hpp>
#include <Patcher/WebConnection.hpp>
#include <QProgressBar>
#include <QListWidgetItem>
#include <QLabel>
#include <QGroupBox>
#include <QScrollArea>
#include <QMessageBox>
#include <Patcher/Config.hpp>
#include <Patcher/Log.hpp>
#include <iostream>
#define ADD_ACTION(parent,var,str) QAction* var = new QAction(str,this);\
parent->addAction(var);
#define ADD_MENU(parent,var,str) QMenu* var = parent->addMenu(str);
namespace patcher
{
Patcher::Patcher(const std::string& soft) : QMainWindow(), maj_avalible(0)//, logList(nullptr)
{
patcher::Config::softname = soft;
setFixedSize(400,300);
setWindowTitle(("Patcher - "+soft).c_str());
initMenu();
iniMainArea();
soft_thread.setStandardOutputFile(("logs/"+soft+".txt").c_str(),QIODevice::Append);
soft_thread.setStandardErrorFile(("logs/"+soft+".err.txt").c_str(),QIODevice::Append);
QStringList env = QProcess::systemEnvironment();
env<<"LD_LIBRARY_PATH=.";
soft_thread.setEnvironment(env);
}
Patcher::~Patcher()
{
}
void Patcher::start()
{
configMaj();
}
//// SLOTS //////
void Patcher::showVersion()const
{
QMessageBox::information(nullptr,"Version","Version acctuelle:\n"+QString(Config::numberToString(Config::getVersion()).c_str()));
}
void Patcher::configSetUrl()const
{
Config::setUrl();
Config::makeFile();
}
void Patcher::configMaj()
{
Config::init();
patcher::WebConnection con;
std::list<Log> logs;
majs = con.getMaj(logs);
//layout.clear();
for(Log& log : logs)
{
QLabel* widget = new QLabel((log.getNumber()
+": "
+log.getMsg()).c_str());
//widget->setMinimumSize(widget->minimumSizeHint());
this->layout.addWidget(widget);
std::cout<<log.getNumber()<<" "<<log.getMsg()<<std::endl;
}
maj_avalible = majs.size();
if(maj_avalible > 0)
{
execMaj();
}
}
void Patcher::configReset()const
{
Config::makeDefault();
}
void Patcher::runSoft()
{
QString name = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + QDir::separator() + Config::softname.c_str()).toString();
#if __WIN32
name +=".exe";
#endif
soft_thread.start(name);
}
void Patcher::quit()
{
if(soft_thread.state() == QProcess::Running)
{
QMessageBox::warning(nullptr,"Error",QString((Config::softname+" is running. Close it.").c_str()));
}
else
qApp->quit();
}
////////
void Patcher::initMenu()
{
//Fichier
QMenu* menuFichier = menuBar()->addMenu("&Fichier");
///Quitter
ADD_ACTION(menuFichier,actionRun,("Lancer" + Config::softname).c_str());
connect(actionRun, SIGNAL(triggered()),this, SLOT(runSoft()));
actionRun->setShortcut(QKeySequence("Ctrl+Enter"));
ADD_ACTION(menuFichier,actionQuitter,"&Quitter");
connect(actionQuitter, SIGNAL(triggered()),this, SLOT(quit()));
actionQuitter->setShortcut(QKeySequence("Ctrl+Q"));
//actionQuitter->setIcon(QIcon("quitter.png"));
//Edition
QMenu* menuEdition = menuBar()->addMenu("&Edition");
//actionGras->setCheckable(true);
ADD_MENU(menuEdition,menuConfiguration,"&Configuration");
ADD_ACTION(menuConfiguration,actionConfigurationUrl,"Definir l'url du site");
connect(actionConfigurationUrl,SIGNAL(triggered()),this,SLOT(configSetUrl()));
ADD_ACTION(menuConfiguration,actionConfigurationMaj,"Lancer une Maj");
connect(actionConfigurationMaj,SIGNAL(triggered()),this,SLOT(configMaj()));
actionConfigurationMaj->setShortcut(QKeySequence("F5"));
ADD_ACTION(menuConfiguration,actionConfigurationReset,"Reset");
connect(actionConfigurationReset,SIGNAL(triggered()),this,SLOT(configReset()));
actionConfigurationReset->setShortcut(QKeySequence("Ctrl+L"));
//Aide
QMenu* menuAide = menuBar()->addMenu("&Aide");
///Version
ADD_ACTION(menuAide,actionVersion,"&Version")
connect(actionVersion, SIGNAL(triggered()),this, SLOT(showVersion()));
}
void Patcher::iniMainArea()
{
QWidget* zoneCentrale = new QScrollArea;
zoneCentrale->setLayout(&layout);
setCentralWidget(zoneCentrale);
}
int Patcher::execMaj()
{
if (maj_avalible <= 0)
return 0;
QProgressBar progressBar;
progressBar.setMaximumHeight(16);
progressBar.setMaximumWidth(200);
//progressBar->setTextVisible(false);
progressBar.setRange(0,maj_avalible);
this->statusBar()->addPermanentWidget(&progressBar, 0);
this->statusBar()->showMessage(QString("Loading"));
int nb = 0;
int i = 1;
for(patcher::Maj& maj : majs)
{
this->statusBar()->showMessage(QString("download "+QString::number(i)+"/"+QString::number(maj_avalible)));
if(not maj.isDone())
nb+= maj.apply();
progressBar.setValue(++i);
}
this->statusBar()->clearMessage();
this->statusBar()->removeWidget(&progressBar);
return nb;
}
}
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <SOIL.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Shader.h"
GLfloat mix_value=0.2f;
glm::vec3 camera_position=glm::vec3(0.0f,0.0f,3.0f);
glm::vec3 camera_front=glm::vec3(0.0f,0.0f,-1.0f);
glm::vec3 camera_up=glm::vec3(0.0f,1.0f,0.0f);
void key_callback(GLFWwindow* window,int key,int scancode,int action,int mode)
{
if(key==GLFW_KEY_ESCAPE && action==GLFW_PRESS)
glfwSetWindowShouldClose(window,GL_TRUE);
if(key==GLFW_KEY_UP && action==GLFW_PRESS)
{
mix_value+=0.1f;
if(mix_value>1.0f) mix_value=1.0f;
}
if(key==GLFW_KEY_DOWN && action==GLFW_PRESS)
{
mix_value-=0.1f;
if(mix_value<0.0f) mix_value=0.0f;
}
GLfloat camera_speed=0.05f;
if(key==GLFW_KEY_W) camera_position+=camera_speed*camera_front;
if(key==GLFW_KEY_S) camera_position-=camera_speed*camera_front;
if(key==GLFW_KEY_A) camera_position-=glm::normalize(glm::cross(camera_front,camera_up))*camera_speed;
if(key==GLFW_KEY_D) camera_position+=glm::normalize(glm::cross(camera_front,camera_up))*camera_speed;
}
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
GLFWwindow *window=glfwCreateWindow(800,600,"Learn OpenGL",nullptr,nullptr);
if(window==nullptr)
{
std::cout<<"Failed to create GLFW window!"<<std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental=GL_TRUE;
if(glewInit()!=GLEW_OK)
{
std::cout<<"Failed to initialize GLEW!"<<std::endl;
return -1;
}
int width,height;
glfwGetFramebufferSize(window,&width,&height);
glViewport(0,0,width,height);
// projection matrix
glm::mat4 projection;
projection=glm::perspective(glm::radians(45.0f),(float)width/height,0.1f,100.0f);
glfwSetKeyCallback(window,key_callback);
Shader our_shader("shader.vs","shader.frag");
GLuint texture1,texture2;
// generate texture 1
glGenTextures(1,&texture1);
glBindTexture(GL_TEXTURE_2D,texture1);
// set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
// set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
// load, create and generate mipmaps
unsigned char* image=SOIL_load_image("container.jpg",&width,&height,0,SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
// free image data
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D,0);
// generate texture 2
glGenTextures(1,&texture2);
glBindTexture(GL_TEXTURE_2D,texture2);
// set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
// set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
// load, create and generate mipmaps
image=SOIL_load_image("awesomeface.png",&width,&height,0,SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
// free image data
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D,0);
GLfloat vertices[]={
// positions // textures
-0.5f,-0.5f,-0.5f, 0.0f,0.0f,
0.5f,-0.5f,-0.5f, 1.0f,0.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,0.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,1.0f,
0.5f, 0.5f, 0.5f, 1.0f,1.0f,
-0.5f, 0.5f, 0.5f, 0.0f,1.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f, 0.5f,-0.5f, 1.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f, 0.5f, 0.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f,-0.5f, 1.0f,1.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f, 0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f
};
glm::vec3 cube_positions[]={
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f,-15.0f),
glm::vec3(-1.5f,-2.2f,-2.5f),
glm::vec3(-3.8f,-2.0f,-12.3f),
glm::vec3( 2.4f,-0.4f,-3.5f),
glm::vec3(-1.7f, 3.0f,-7.5f),
glm::vec3( 1.3f,-2.0f,-2.5f),
glm::vec3( 1.5f, 2.0f,-2.5f),
glm::vec3( 1.5f, 0.2f,-1.5f),
glm::vec3(-1.3f, 1.0f,-1.5f)
};
GLuint VAO,VBO;
glGenBuffers(1,&VBO);
glGenVertexArrays(1,&VAO);
// bind vertex array object
glBindVertexArray(VAO);
// copy the vertices in a buffer
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
// set position attribute pointers
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,5*sizeof(GL_FLOAT),(GLvoid*)0);
glEnableVertexAttribArray(0);
// set texture attribute pointers
glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,5*sizeof(GL_FLOAT),(GLvoid*)(3*sizeof(GLfloat)));
glEnableVertexAttribArray(1);
// unbind the vertex array object
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
GLfloat radius=10.0f;
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(.2f,.3f,.3f,1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// use shader program
our_shader.Use();
// bind textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,texture1);
glUniform1i(glGetUniformLocation(our_shader.program,"our_texture1"),0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D,texture2);
glUniform1i(glGetUniformLocation(our_shader.program,"our_texture2"),1);
glUniform1f(glGetUniformLocation(our_shader.program,"mix_value"),mix_value);
// view space transform
glm::mat4 view=glm::lookAt(camera_position,camera_position+camera_front,camera_up);
GLuint model_location=glGetUniformLocation(our_shader.program,"model");
GLuint view_location=glGetUniformLocation(our_shader.program,"view");
glUniformMatrix4fv(view_location,1,GL_FALSE,glm::value_ptr(view));
GLuint projection_location=glGetUniformLocation(our_shader.program,"projection");
glUniformMatrix4fv(projection_location,1,GL_FALSE,glm::value_ptr(projection));
// draw
glBindVertexArray(VAO);
for(GLuint i=0;i<10;++i)
{
// world space transform
glm::mat4 model;
model=glm::translate(model,cube_positions[i]);
model=glm::rotate(model,glm::radians((GLfloat)glfwGetTime()*50.0f),glm::vec3(0.5f,1.0f,0.0f));
GLfloat angle=glm::radians(20.0f*i);
model=glm::rotate(model,angle,glm::vec3(1.0f,0.3f,0.5f));
glUniformMatrix4fv(model_location,1,GL_FALSE,glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES,0,36);
}
glBindVertexArray(0);
glfwSwapBuffers(window);
}
// deallocate all resources
glDeleteVertexArrays(1,&VAO);
glDeleteBuffers(1,&VBO);
// terminate GLFW
glfwTerminate();
return 0;
}
<commit_msg>hardware-independent smooth/uniform movement.<commit_after>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <SOIL.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Shader.h"
GLfloat mix_value=0.2f;
bool keys[1024];
GLfloat delta_time=0.0f; // time between current frame and last frame
GLfloat last_frame=0.0f; // time of last frame
glm::vec3 camera_position=glm::vec3(0.0f,0.0f,3.0f);
glm::vec3 camera_front=glm::vec3(0.0f,0.0f,-1.0f);
glm::vec3 camera_up=glm::vec3(0.0f,1.0f,0.0f);
void do_movement()
{
// camera controls
GLfloat camera_speed=5.0f*delta_time;
if(keys[GLFW_KEY_W]) camera_position+=camera_speed*camera_front;
if(keys[GLFW_KEY_S]) camera_position-=camera_speed*camera_front;
if(keys[GLFW_KEY_A]) camera_position-=glm::normalize(glm::cross(camera_front,camera_up))*camera_speed;
if(keys[GLFW_KEY_D]) camera_position+=glm::normalize(glm::cross(camera_front,camera_up))*camera_speed;
}
void key_callback(GLFWwindow* window,int key,int scancode,int action,int mode)
{
if(key==GLFW_KEY_ESCAPE && action==GLFW_PRESS)
glfwSetWindowShouldClose(window,GL_TRUE);
if(key==GLFW_KEY_UP && action==GLFW_PRESS)
{
mix_value+=0.1f;
if(mix_value>1.0f) mix_value=1.0f;
}
if(key==GLFW_KEY_DOWN && action==GLFW_PRESS)
{
mix_value-=0.1f;
if(mix_value<0.0f) mix_value=0.0f;
}
if(action==GLFW_PRESS) keys[key]=true;
else if(action==GLFW_RELEASE) keys[key]=false;
}
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
GLFWwindow *window=glfwCreateWindow(800,600,"Learn OpenGL",nullptr,nullptr);
if(window==nullptr)
{
std::cout<<"Failed to create GLFW window!"<<std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental=GL_TRUE;
if(glewInit()!=GLEW_OK)
{
std::cout<<"Failed to initialize GLEW!"<<std::endl;
return -1;
}
int width,height;
glfwGetFramebufferSize(window,&width,&height);
glViewport(0,0,width,height);
// projection matrix
glm::mat4 projection;
projection=glm::perspective(glm::radians(45.0f),(float)width/height,0.1f,100.0f);
glfwSetKeyCallback(window,key_callback);
Shader our_shader("shader.vs","shader.frag");
GLuint texture1,texture2;
// generate texture 1
glGenTextures(1,&texture1);
glBindTexture(GL_TEXTURE_2D,texture1);
// set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
// set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
// load, create and generate mipmaps
unsigned char* image=SOIL_load_image("container.jpg",&width,&height,0,SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
// free image data
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D,0);
// generate texture 2
glGenTextures(1,&texture2);
glBindTexture(GL_TEXTURE_2D,texture2);
// set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
// set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
// load, create and generate mipmaps
image=SOIL_load_image("awesomeface.png",&width,&height,0,SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,image);
glGenerateMipmap(GL_TEXTURE_2D);
// free image data
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D,0);
GLfloat vertices[]={
// positions // textures
-0.5f,-0.5f,-0.5f, 0.0f,0.0f,
0.5f,-0.5f,-0.5f, 1.0f,0.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,0.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,1.0f,
0.5f, 0.5f, 0.5f, 1.0f,1.0f,
-0.5f, 0.5f, 0.5f, 0.0f,1.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f, 0.5f,-0.5f, 1.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f, 0.5f, 0.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
0.5f,-0.5f,-0.5f, 1.0f,1.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
0.5f,-0.5f, 0.5f, 1.0f,0.0f,
-0.5f,-0.5f, 0.5f, 0.0f,0.0f,
-0.5f,-0.5f,-0.5f, 0.0f,1.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f,
0.5f, 0.5f,-0.5f, 1.0f,1.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
0.5f, 0.5f, 0.5f, 1.0f,0.0f,
-0.5f, 0.5f, 0.5f, 0.0f,0.0f,
-0.5f, 0.5f,-0.5f, 0.0f,1.0f
};
glm::vec3 cube_positions[]={
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f,-15.0f),
glm::vec3(-1.5f,-2.2f,-2.5f),
glm::vec3(-3.8f,-2.0f,-12.3f),
glm::vec3( 2.4f,-0.4f,-3.5f),
glm::vec3(-1.7f, 3.0f,-7.5f),
glm::vec3( 1.3f,-2.0f,-2.5f),
glm::vec3( 1.5f, 2.0f,-2.5f),
glm::vec3( 1.5f, 0.2f,-1.5f),
glm::vec3(-1.3f, 1.0f,-1.5f)
};
GLuint VAO,VBO;
glGenBuffers(1,&VBO);
glGenVertexArrays(1,&VAO);
// bind vertex array object
glBindVertexArray(VAO);
// copy the vertices in a buffer
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
// set position attribute pointers
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,5*sizeof(GL_FLOAT),(GLvoid*)0);
glEnableVertexAttribArray(0);
// set texture attribute pointers
glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,5*sizeof(GL_FLOAT),(GLvoid*)(3*sizeof(GLfloat)));
glEnableVertexAttribArray(1);
// unbind the vertex array object
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
GLfloat radius=10.0f;
while(!glfwWindowShouldClose(window))
{
glfwPollEvents();
do_movement();
glClearColor(.2f,.3f,.3f,1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLfloat current_frame=glfwGetTime();
delta_time=current_frame-last_frame;
last_frame=current_frame;
// use shader program
our_shader.Use();
// bind textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,texture1);
glUniform1i(glGetUniformLocation(our_shader.program,"our_texture1"),0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D,texture2);
glUniform1i(glGetUniformLocation(our_shader.program,"our_texture2"),1);
glUniform1f(glGetUniformLocation(our_shader.program,"mix_value"),mix_value);
// view space transform
glm::mat4 view=glm::lookAt(camera_position,camera_position+camera_front,camera_up);
GLuint model_location=glGetUniformLocation(our_shader.program,"model");
GLuint view_location=glGetUniformLocation(our_shader.program,"view");
glUniformMatrix4fv(view_location,1,GL_FALSE,glm::value_ptr(view));
GLuint projection_location=glGetUniformLocation(our_shader.program,"projection");
glUniformMatrix4fv(projection_location,1,GL_FALSE,glm::value_ptr(projection));
// draw
glBindVertexArray(VAO);
for(GLuint i=0;i<10;++i)
{
// world space transform
glm::mat4 model;
model=glm::translate(model,cube_positions[i]);
model=glm::rotate(model,glm::radians((GLfloat)glfwGetTime()*50.0f),glm::vec3(0.5f,1.0f,0.0f));
GLfloat angle=glm::radians(20.0f*i);
model=glm::rotate(model,angle,glm::vec3(1.0f,0.3f,0.5f));
glUniformMatrix4fv(model_location,1,GL_FALSE,glm::value_ptr(model));
glDrawArrays(GL_TRIANGLES,0,36);
}
glBindVertexArray(0);
glfwSwapBuffers(window);
}
// deallocate all resources
glDeleteVertexArrays(1,&VAO);
glDeleteBuffers(1,&VBO);
// terminate GLFW
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return false;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
int uart_num = UART_NUM_2;
uart_write_bytes(uart_num, (const char*)value, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
<commit_msg>Update MFRC522.cpp<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return false;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
uart_port_t uart_num = UART_NUM_2;
uart_write_bytes(uart_num, (const char*)value, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return false;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
uart_port_t uart_num = UART_NUM_2;
uart_write_bytes(uart_num, (const char*)value, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
extern "C" void MFRC522_main() {
MFRC522 Conector;
Conector.begin();
printf("begin :\n");
//while(true)
{
//Conector.readCardSerial();
printf("readCardSerial :\n");
Conector.wait();
}
}
<commit_msg>Update MFRC522.cpp<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return false;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
uart_port_t uart_num = UART_NUM_2;
char data[1];
data[0] = value;
uart_write_bytes(uart_num, (const char*)data, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
extern "C" void MFRC522_main() {
MFRC522 Conector;
Conector.begin();
printf("begin :\n");
//while(true)
{
//Conector.readCardSerial();
printf("readCardSerial :\n");
Conector.wait();
}
}
<|endoftext|> |
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "cpputil.hh"
#include "ilist.hh"
#include "mtrace.h"
extern "C" void zpage(void*);
extern "C" void zrun_nc(void*);
static const bool prezero = true;
struct free_page
{
ilink<free_page> link;
typedef ilist<free_page, &free_page::link> list_t;
};
struct zallocator {
// pages and nPages must only be accessed by the local CPU and must
// be accessed with interrupts disabled.
free_page::list_t pages;
unsigned nPages;
wframe frame;
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame)
: frame_(frame)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
auto *r = (struct free_page*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
scoped_cli cli;
z_->pages.push_front(r);
++z_->nPages;
}
frame_->dec();
delete this;
}
wframe* frame_;
NEW_DELETE_OPS(zwork);
};
static void
tryrefill(void)
{
int cpu = myid();
if (prezero && z_[cpu].nPages < 16 && z_[cpu].frame.zero()) {
zwork* w = new zwork(&z_[cpu].frame);
if (wqcrit_push(w, cpu) < 0)
delete w;
}
}
// Allocate a zeroed page. This page can be freed with kfree or, if
// it is known to be zeroed when it is freed, zfree.
char*
zalloc(const char* name)
{
char* p = nullptr;
{
scoped_cli cli;
if (!z_->pages.empty()) {
p = (char*)&z_->pages.front();
z_->pages.pop_front();
--z_->nPages;
}
}
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
} else {
mtlabel(mtrace_label_block, p, PGSIZE, name, strlen(name));
// Zero the free_page header
memset(p, 0, sizeof(struct free_page));
if (0)
for (int i = 0; i < PGSIZE; i++)
assert(p[i] == 0);
}
tryrefill();
return p;
}
// Free a page that is known to be zero
void
zfree(void* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(((char*)p)[i] == 0);
scoped_cli cli;
z_->pages.push_front((struct free_page*)p);
++z_->nPages;
}
void
initz(void)
{
}
<commit_msg>mtrace fixes in zalloc<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "cpputil.hh"
#include "ilist.hh"
#include "mtrace.h"
extern "C" void zpage(void*);
extern "C" void zrun_nc(void*);
static const bool prezero = true;
struct free_page
{
ilink<free_page> link;
typedef ilist<free_page, &free_page::link> list_t;
};
struct zallocator {
// pages and nPages must only be accessed by the local CPU and must
// be accessed with interrupts disabled.
free_page::list_t pages;
unsigned nPages;
wframe frame;
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame)
: frame_(frame)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
auto *r = (struct free_page*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
scoped_cli cli;
z_->pages.push_front(r);
++z_->nPages;
}
frame_->dec();
delete this;
}
wframe* frame_;
NEW_DELETE_OPS(zwork);
};
static void
tryrefill(void)
{
int cpu = myid();
if (prezero && z_[cpu].nPages < 16 && z_[cpu].frame.zero()) {
zwork* w = new zwork(&z_[cpu].frame);
if (wqcrit_push(w, cpu) < 0)
delete w;
}
}
// Allocate a zeroed page. This page can be freed with kfree or, if
// it is known to be zeroed when it is freed, zfree.
char*
zalloc(const char* name)
{
char* p = nullptr;
{
scoped_cli cli;
if (!z_->pages.empty()) {
p = (char*)&z_->pages.front();
z_->pages.pop_front();
--z_->nPages;
}
}
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
} else {
mtunlabel(mtrace_label_block, p);
mtlabel(mtrace_label_block, p, PGSIZE, name, strlen(name));
// Zero the free_page header
memset(p, 0, sizeof(struct free_page));
if (0)
for (int i = 0; i < PGSIZE; i++)
assert(p[i] == 0);
}
tryrefill();
return p;
}
// Free a page that is known to be zero
void
zfree(void* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(((char*)p)[i] == 0);
scoped_cli cli;
mtunlabel(mtrace_label_block, p);
z_->pages.push_front((struct free_page*)p);
++z_->nPages;
}
void
initz(void)
{
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iomanip>
#include <iostream>
#include "duration.h"
#include "function.h"
#include "function_statistics.h"
#include "performance_counter.h"
#include "statistics_writer_xml.h"
#include "statistics.h"
#include "time_utils.h"
namespace amx_profiler {
void StatisticsWriterXml::Write(const Statistics *stats)
{
*stream() << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
<< "<stats script=\"" << script_name() << "\"";
if (print_date()) {
*stream() << " timestamp=\"" << TimeStamp::Now() << "\"";
}
if (print_run_time()) {
*stream() << " run_time=\"" << Seconds(stats->GetTotalRunTime()).count() << "\'";
}
*stream() << ">\n";
std::vector<FunctionStatistics*> all_fn_stats;
stats->GetStatistics(all_fn_stats);
Nanoseconds time_all;
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
time_all += fn_stats->total_time() - fn_stats->child_time();
}
Nanoseconds total_time_all;
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
total_time_all += fn_stats->total_time();
}
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
double self_time_sec = Seconds(fn_stats->GetSelfTime()).count();
double self_time_percent = fn_stats->GetSelfTime().count() * 100 / time_all.count();
double total_time_sec = Seconds(fn_stats->total_time()).count();
double total_time_percent = fn_stats->total_time().count() * 100 / total_time_all.count();
*stream() << "\t<function"
<< " type=\"" << fn_stats->function()->GetTypeString() << "\""
<< " name=\"" << fn_stats->function()->name() << "\""
<< " calls=\"" << fn_stats->num_calls() << "\""
<< " self_time=\"" << fn_stats->GetSelfTime().count() << "\""
<< " self_time_sec=\"" << self_time_sec << "\""
<< " self_time_percent=\"" << std::fixed << std::setprecision(2) << self_time_percent << "\""
<< " total_time=\"" << fn_stats->total_time().count() << "\""
<< " total_time_sec=\"" << total_time_sec << "\""
<< " total_time_percent=\"" << std::fixed << std::setprecision(2) << total_time_percent << "\""
<< "/>\n";
}
*stream() << "</stats>";
}
} // namespace amx_profiler
<commit_msg>Remove "self_time_sec" and "total_time_sec" attributes in XML output<commit_after>// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iomanip>
#include <iostream>
#include "duration.h"
#include "function.h"
#include "function_statistics.h"
#include "performance_counter.h"
#include "statistics_writer_xml.h"
#include "statistics.h"
#include "time_utils.h"
namespace amx_profiler {
void StatisticsWriterXml::Write(const Statistics *stats)
{
*stream() << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
<< "<stats script=\"" << script_name() << "\"";
if (print_date()) {
*stream() << " timestamp=\"" << TimeStamp::Now() << "\"";
}
if (print_run_time()) {
*stream() << " run_time=\"" << Seconds(stats->GetTotalRunTime()).count() << "\'";
}
*stream() << ">\n";
std::vector<FunctionStatistics*> all_fn_stats;
stats->GetStatistics(all_fn_stats);
Nanoseconds time_all;
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
time_all += fn_stats->total_time() - fn_stats->child_time();
}
Nanoseconds total_time_all;
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
total_time_all += fn_stats->total_time();
}
for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
iterator != all_fn_stats.end(); ++iterator)
{
const FunctionStatistics *fn_stats = *iterator;
double self_time_percent = fn_stats->GetSelfTime().count() * 100 / time_all.count();
double total_time_percent = fn_stats->total_time().count() * 100 / total_time_all.count();
*stream() << "\t<function"
<< " type=\"" << fn_stats->function()->GetTypeString() << "\""
<< " name=\"" << fn_stats->function()->name() << "\""
<< " calls=\"" << fn_stats->num_calls() << "\""
<< " self_time=\"" << fn_stats->GetSelfTime().count() << "\""
<< " self_time_percent=\"" << std::fixed << std::setprecision(2) << self_time_percent << "\""
<< " total_time=\"" << fn_stats->total_time().count() << "\""
<< " total_time_percent=\"" << std::fixed << std::setprecision(2) << total_time_percent << "\""
<< "/>\n";
}
*stream() << "</stats>";
}
} // namespace amx_profiler
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "IFile.h"
#include "IFolder.h"
#include "IMediaLibrary.h"
#include "filesystem/IDirectory.h"
#include "filesystem/IFile.h"
#include "Utils.h"
#include <memory>
#include <unordered_map>
namespace mock
{
class File : public fs::IFile
{
public:
File( const std::string& filePath )
: m_name( utils::file::fileName( filePath ) )
, m_path( utils::file::directory( filePath ) )
, m_fullPath( filePath )
, m_extension( utils::file::extension( filePath ) )
, m_lastModification( 0 )
{
}
File( const File& ) = default;
virtual const std::string& name() const override
{
return m_name;
}
virtual const std::string& path() const override
{
return m_path;
}
virtual const std::string& fullPath() const override
{
return m_fullPath;
}
virtual const std::string& extension() const override
{
return m_extension;
}
virtual unsigned int lastModificationDate() const override
{
return m_lastModification;
}
std::string m_name;
std::string m_path;
std::string m_fullPath;
std::string m_extension;
unsigned int m_lastModification;
};
class Directory : public fs::IDirectory
{
public:
Directory( const std::string& path, unsigned int lastModif )
: m_path( path )
, m_lastModificationDate( lastModif )
{
}
virtual const std::string& path() const
{
return m_path;
}
virtual const std::vector<std::string>& files() const
{
return m_files;
}
virtual const std::vector<std::string>& dirs() const
{
return m_dirs;
}
virtual unsigned int lastModificationDate() const override
{
return m_lastModificationDate;
}
void addFile( const std::string& fileName )
{
m_files.emplace_back( m_path + fileName );
m_lastModificationDate++;
}
void addFolder( const std::string& folder )
{
m_dirs.emplace_back( m_path + folder );
m_lastModificationDate++;
}
private:
std::string m_path;
std::vector<std::string> m_files;
std::vector<std::string> m_dirs;
unsigned int m_lastModificationDate;
};
struct FileSystemFactory : public factory::IFileSystem
{
static constexpr const char* Root = "/a/";
static constexpr const char* SubFolder = "/a/folder/";
FileSystemFactory()
{
dirs[Root] = std::unique_ptr<mock::Directory>( new Directory{ Root, 123 } );
addFile( Root, "video.avi" );
addFile( Root, "audio.mp3" );
addFile( Root, "not_a_media.something" );
addFile( Root, "some_other_file.seaotter" );
addFolder( Root, "folder/", 456 );
addFile( SubFolder, "subfile.mp4" );
}
void addFile( const std::string& path, const std::string& fileName )
{
dirs[path]->addFile( fileName );
files[path + fileName] = std::unique_ptr<mock::File>( new mock::File( path + fileName ) );
}
void addFolder( const std::string& parentPath, const std::string& path, unsigned int lastModif )
{
auto parent = dirs[parentPath];
parent->addFolder( path );
dirs[parentPath + path] = std::unique_ptr<mock::Directory>( new Directory( parent, parentPath + path, lastModif ) );
}
virtual std::unique_ptr<fs::IDirectory> createDirectory(const std::string& path) override
{
mock::Directory* res = nullptr;
if ( path == "." )
{
res = dirs[Root].get();
}
else
{
auto it = dirs.find( path );
if ( it != end( dirs ) )
res = it->second.get();
}
if ( res == nullptr )
throw std::runtime_error("Invalid path");
return std::unique_ptr<fs::IDirectory>( new Directory( *res ) );
}
virtual std::unique_ptr<fs::IFile> createFile( const std::string &filePath ) override
{
const auto it = files.find( filePath );
if ( it == end( files ) )
files[filePath].reset( new File( filePath ) );
return std::unique_ptr<fs::IFile>( new File( static_cast<const mock::File&>( * it->second.get() ) ) );
}
std::unordered_map<std::string, std::unique_ptr<mock::File>> files;
std::unordered_map<std::string, std::unique_ptr<mock::Directory>> dirs;
};
}
class Folders : public testing::Test
{
public:
static std::unique_ptr<IMediaLibrary> ml;
std::shared_ptr<mock::FileSystemFactory> fsMock;
protected:
virtual void Reload()
{
ml.reset( MediaLibraryFactory::create() );
bool res = ml->initialize( "test.db", fsMock );
ASSERT_TRUE( res );
}
virtual void SetUp()
{
fsMock.reset( new mock::FileSystemFactory );
Reload();
}
virtual void TearDown()
{
ml.reset();
unlink("test.db");
}
};
std::unique_ptr<IMediaLibrary> Folders::ml;
TEST_F( Folders, Add )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
ASSERT_FALSE( files[0]->isStandAlone() );
}
TEST_F( Folders, Delete )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto folderPath = f->path();
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
auto filePath = files[0]->mrl();
ml->deleteFolder( f );
f = ml->folder( folderPath );
ASSERT_EQ( nullptr, f );
files = ml->files();
ASSERT_EQ( files.size(), 0u );
// Check the file isn't cached anymore:
auto file = ml->file( filePath );
ASSERT_EQ( nullptr, file );
SetUp();
// Recheck folder deletion from DB:
f = ml->folder( folderPath );
ASSERT_EQ( nullptr, f );
}
TEST_F( Folders, Load )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
SetUp();
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
for ( auto& f : files )
ASSERT_FALSE( f->isStandAlone() );
}
TEST_F( Folders, InvalidPath )
{
auto f = ml->addFolder( "/invalid/path" );
ASSERT_EQ( f, nullptr );
auto files = ml->files();
ASSERT_EQ( files.size(), 0u );
}
TEST_F( Folders, List )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto files = f->files();
ASSERT_EQ( files.size(), 2u );
SetUp();
f = ml->folder( f->path() );
files = f->files();
ASSERT_EQ( files.size(), 2u );
}
TEST_F( Folders, AbsolutePath )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f->path(), "." );
}
TEST_F( Folders, ListFolders )
{
auto f = ml->addFolder( "." );
auto subFolders = f->folders();
ASSERT_EQ( 1u, subFolders.size() );
auto subFolder = subFolders[0];
auto subFiles = subFolder->files();
ASSERT_EQ( 1u, subFiles.size() );
auto file = subFiles[0];
ASSERT_EQ( std::string{ mock::FileSystemFactory::SubFolder } + "subfile.mp4", file->mrl() );
// Now again, without cache
SetUp();
f = ml->folder( f->path() );
subFolders = f->folders();
ASSERT_EQ( 1u, subFolders.size() );
subFolder = subFolders[0];
subFiles = subFolder->files();
ASSERT_EQ( 1u, subFiles.size() );
file = subFiles[0];
ASSERT_EQ( std::string{ mock::FileSystemFactory::SubFolder } + "subfile.mp4", file->mrl() );
}
TEST_F( Folders, LastModificationDate )
{
auto f = ml->addFolder( "." );
ASSERT_NE( 0u, f->lastModificationDate() );
auto subFolders = f->folders();
ASSERT_NE( 0u, subFolders[0]->lastModificationDate() );
SetUp();
f = ml->folder( f->path() );
ASSERT_NE( 0u, f->lastModificationDate() );
subFolders = f->folders();
ASSERT_NE( 0u, subFolders[0]->lastModificationDate() );
}
TEST_F( Folders, NewFile )
{
ml->addFolder( "." );
ASSERT_EQ( 3u, ml->files().size() );
// Do not watch for live changes
ml.reset();
auto newFolder = std::string(mock::FileSystemFactory::Root) + "newfolder/";
fsMock->addFolder( mock::FileSystemFactory::Root, "newfolder/", time( nullptr ) );
fsMock->addFile( newFolder, "newfile.avi" );
Reload();
ASSERT_EQ( 4u, ml->files().size() );
auto file = ml->file( newFolder + "newfile.avi" );
ASSERT_NE( nullptr, file );
}
<commit_msg>tests: FS mock: Propagate changes to parent folders<commit_after>#include "gtest/gtest.h"
#include "IFile.h"
#include "IFolder.h"
#include "IMediaLibrary.h"
#include "filesystem/IDirectory.h"
#include "filesystem/IFile.h"
#include "Utils.h"
#include <memory>
#include <unordered_map>
namespace mock
{
class File : public fs::IFile
{
public:
File( const std::string& filePath )
: m_name( utils::file::fileName( filePath ) )
, m_path( utils::file::directory( filePath ) )
, m_fullPath( filePath )
, m_extension( utils::file::extension( filePath ) )
, m_lastModification( 0 )
{
}
File( const File& ) = default;
virtual const std::string& name() const override
{
return m_name;
}
virtual const std::string& path() const override
{
return m_path;
}
virtual const std::string& fullPath() const override
{
return m_fullPath;
}
virtual const std::string& extension() const override
{
return m_extension;
}
virtual unsigned int lastModificationDate() const override
{
return m_lastModification;
}
std::string m_name;
std::string m_path;
std::string m_fullPath;
std::string m_extension;
unsigned int m_lastModification;
};
class Directory : public fs::IDirectory
{
public:
Directory( std::shared_ptr<mock::Directory> parent, const std::string& path, unsigned int lastModif )
: m_path( path )
, m_parent( parent )
, m_lastModificationDate( lastModif )
{
}
virtual const std::string& path() const
{
return m_path;
}
virtual const std::vector<std::string>& files() const
{
return m_files;
}
virtual const std::vector<std::string>& dirs() const
{
return m_dirs;
}
virtual unsigned int lastModificationDate() const override
{
return m_lastModificationDate;
}
void addFile( const std::string& fileName )
{
m_files.emplace_back( m_path + fileName );
markAsModified();
}
void addFolder( const std::string& folder )
{
m_dirs.emplace_back( m_path + folder );
markAsModified();
}
void markAsModified()
{
if ( m_parent != nullptr )
m_parent->markAsModified();
m_lastModificationDate++;
}
private:
std::string m_path;
std::vector<std::string> m_files;
std::vector<std::string> m_dirs;
std::shared_ptr<mock::Directory> m_parent;
unsigned int m_lastModificationDate;
};
struct FileSystemFactory : public factory::IFileSystem
{
static constexpr const char* Root = "/a/";
static constexpr const char* SubFolder = "/a/folder/";
FileSystemFactory()
{
dirs[Root] = std::unique_ptr<mock::Directory>( new Directory{ nullptr, Root, 123 } );
addFile( Root, "video.avi" );
addFile( Root, "audio.mp3" );
addFile( Root, "not_a_media.something" );
addFile( Root, "some_other_file.seaotter" );
addFolder( Root, "folder/", 456 );
addFile( SubFolder, "subfile.mp4" );
}
void addFile( const std::string& path, const std::string& fileName )
{
dirs[path]->addFile( fileName );
files[path + fileName] = std::unique_ptr<mock::File>( new mock::File( path + fileName ) );
}
void addFolder( const std::string& parentPath, const std::string& path, unsigned int lastModif )
{
auto parent = dirs[parentPath];
parent->addFolder( path );
dirs[parentPath + path] = std::unique_ptr<mock::Directory>( new Directory( parent, parentPath + path, lastModif ) );
}
virtual std::unique_ptr<fs::IDirectory> createDirectory(const std::string& path) override
{
mock::Directory* res = nullptr;
if ( path == "." )
{
res = dirs[Root].get();
}
else
{
auto it = dirs.find( path );
if ( it != end( dirs ) )
res = it->second.get();
}
if ( res == nullptr )
throw std::runtime_error("Invalid path");
return std::unique_ptr<fs::IDirectory>( new Directory( *res ) );
}
virtual std::unique_ptr<fs::IFile> createFile( const std::string &filePath ) override
{
const auto it = files.find( filePath );
if ( it == end( files ) )
files[filePath].reset( new File( filePath ) );
return std::unique_ptr<fs::IFile>( new File( static_cast<const mock::File&>( * it->second.get() ) ) );
}
std::unordered_map<std::string, std::shared_ptr<mock::File>> files;
std::unordered_map<std::string, std::shared_ptr<mock::Directory>> dirs;
};
}
class Folders : public testing::Test
{
public:
static std::unique_ptr<IMediaLibrary> ml;
std::shared_ptr<mock::FileSystemFactory> fsMock;
protected:
virtual void Reload()
{
ml.reset( MediaLibraryFactory::create() );
bool res = ml->initialize( "test.db", fsMock );
ASSERT_TRUE( res );
}
virtual void SetUp()
{
fsMock.reset( new mock::FileSystemFactory );
Reload();
}
virtual void TearDown()
{
ml.reset();
unlink("test.db");
}
};
std::unique_ptr<IMediaLibrary> Folders::ml;
TEST_F( Folders, Add )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
ASSERT_FALSE( files[0]->isStandAlone() );
}
TEST_F( Folders, Delete )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto folderPath = f->path();
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
auto filePath = files[0]->mrl();
ml->deleteFolder( f );
f = ml->folder( folderPath );
ASSERT_EQ( nullptr, f );
files = ml->files();
ASSERT_EQ( files.size(), 0u );
// Check the file isn't cached anymore:
auto file = ml->file( filePath );
ASSERT_EQ( nullptr, file );
SetUp();
// Recheck folder deletion from DB:
f = ml->folder( folderPath );
ASSERT_EQ( nullptr, f );
}
TEST_F( Folders, Load )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
SetUp();
auto files = ml->files();
ASSERT_EQ( files.size(), 3u );
for ( auto& f : files )
ASSERT_FALSE( f->isStandAlone() );
}
TEST_F( Folders, InvalidPath )
{
auto f = ml->addFolder( "/invalid/path" );
ASSERT_EQ( f, nullptr );
auto files = ml->files();
ASSERT_EQ( files.size(), 0u );
}
TEST_F( Folders, List )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f, nullptr );
auto files = f->files();
ASSERT_EQ( files.size(), 2u );
SetUp();
f = ml->folder( f->path() );
files = f->files();
ASSERT_EQ( files.size(), 2u );
}
TEST_F( Folders, AbsolutePath )
{
auto f = ml->addFolder( "." );
ASSERT_NE( f->path(), "." );
}
TEST_F( Folders, ListFolders )
{
auto f = ml->addFolder( "." );
auto subFolders = f->folders();
ASSERT_EQ( 1u, subFolders.size() );
auto subFolder = subFolders[0];
auto subFiles = subFolder->files();
ASSERT_EQ( 1u, subFiles.size() );
auto file = subFiles[0];
ASSERT_EQ( std::string{ mock::FileSystemFactory::SubFolder } + "subfile.mp4", file->mrl() );
// Now again, without cache
SetUp();
f = ml->folder( f->path() );
subFolders = f->folders();
ASSERT_EQ( 1u, subFolders.size() );
subFolder = subFolders[0];
subFiles = subFolder->files();
ASSERT_EQ( 1u, subFiles.size() );
file = subFiles[0];
ASSERT_EQ( std::string{ mock::FileSystemFactory::SubFolder } + "subfile.mp4", file->mrl() );
}
TEST_F( Folders, LastModificationDate )
{
auto f = ml->addFolder( "." );
ASSERT_NE( 0u, f->lastModificationDate() );
auto subFolders = f->folders();
ASSERT_NE( 0u, subFolders[0]->lastModificationDate() );
SetUp();
f = ml->folder( f->path() );
ASSERT_NE( 0u, f->lastModificationDate() );
subFolders = f->folders();
ASSERT_NE( 0u, subFolders[0]->lastModificationDate() );
}
TEST_F( Folders, NewFile )
{
ml->addFolder( "." );
ASSERT_EQ( 3u, ml->files().size() );
// Do not watch for live changes
ml.reset();
auto newFolder = std::string(mock::FileSystemFactory::Root) + "newfolder/";
fsMock->addFolder( mock::FileSystemFactory::Root, "newfolder/", time( nullptr ) );
fsMock->addFile( newFolder, "newfile.avi" );
Reload();
ASSERT_EQ( 4u, ml->files().size() );
auto file = ml->file( newFolder + "newfile.avi" );
ASSERT_NE( nullptr, file );
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/viz/vizcore.hpp>
#include <kfusion/kinfu.hpp>
#include <io/capture.hpp>
using namespace kfusion;
struct KinFuApp
{
static void KeyboardCallback(const cv::viz::KeyboardEvent& event, void* pthis)
{
KinFuApp& kinfu = *static_cast<KinFuApp*>(pthis);
if(event.action != cv::viz::KeyboardEvent::KEY_DOWN)
return;
if(event.code == 't' || event.code == 'T')
kinfu.take_cloud(*kinfu.kinfu_);
if(event.code == 'i' || event.code == 'I')
kinfu.iteractive_mode_ = !kinfu.iteractive_mode_;
}
KinFuApp(OpenNISource& source) : exit_ (false), iteractive_mode_(false), capture_ (source), pause_(false)
{
KinFuParams params = KinFuParams::default_params();
kinfu_ = KinFu::Ptr( new KinFu(params) );
capture_.setRegistration(true);
cv::viz::WCube cube(cv::Vec3d::all(0), cv::Vec3d(params.volume_size), true, cv::viz::Color::apricot());
viz.showWidget("cube", cube, params.volume_pose);
viz.showWidget("coor", cv::viz::WCoordinateSystem(0.1));
viz.registerKeyboardCallback(KeyboardCallback, this);
}
void show_depth(const cv::Mat& depth)
{
cv::Mat display;
//cv::normalize(depth, display, 0, 255, cv::NORM_MINMAX, CV_8U);
depth.convertTo(display, CV_8U, 255.0/4000);
cv::imshow("Depth", display);
}
void show_raycasted(KinFu& kinfu)
{
const int mode = 3;
if (iteractive_mode_)
kinfu.renderImage(view_device_, viz.getViewerPose(), mode);
else
kinfu.renderImage(view_device_, mode);
view_host_.create(view_device_.rows(), view_device_.cols(), CV_8UC4);
view_device_.download(view_host_.ptr<void>(), view_host_.step);
cv::imshow("Scene", view_host_);
}
void take_cloud(KinFu& kinfu)
{
cuda::DeviceArray<Point> cloud = kinfu.tsdf().fetchCloud(cloud_buffer);
cv::Mat cloud_host(1, (int)cloud.size(), CV_32FC4);
cloud.download(cloud_host.ptr<Point>());
viz.showWidget("cloud", cv::viz::WCloud(cloud_host));
//viz.showWidget("cloud", cv::viz::WPaintedCloud(cloud_host));
}
bool execute()
{
KinFu& kinfu = *kinfu_;
cv::Mat depth, image;
double time_ms = 0;
bool has_image = false;
for (int i = 0; !exit_ && !viz.wasStopped(); ++i)
{
bool has_frame = capture_.grab(depth, image);
if (!has_frame)
return std::cout << "Can't grab" << std::endl, false;
depth_device_.upload(depth.data, depth.step, depth.rows, depth.cols);
{
SampledScopeTime fps(time_ms); (void)fps;
has_image = kinfu(depth_device_);
}
if (has_image)
show_raycasted(kinfu);
show_depth(depth);
//cv::imshow("Image", image);
if (!iteractive_mode_)
viz.setViewerPose(kinfu.getCameraPose());
int key = cv::waitKey(pause_ ? 0 : 3);
switch(key)
{
case 't': case 'T' : take_cloud(kinfu); break;
case 'i': case 'I' : iteractive_mode_ = !iteractive_mode_; break;
case 27: exit_ = true; break;
case 32: pause_ = !pause_; break;
}
//exit_ = exit_ || i > 100;
viz.spinOnce(3, true);
}
return true;
}
bool pause_ /*= false*/;
bool exit_, iteractive_mode_;
OpenNISource& capture_;
KinFu::Ptr kinfu_;
cv::viz::Viz3d viz;
cv::Mat view_host_;
cuda::Image view_device_;
cuda::Depth depth_device_;
cuda::DeviceArray<Point> cloud_buffer;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[])
{
int device = 0;
cuda::setDevice (device);
cuda::printShortCudaDeviceInfo (device);
if(cuda::checkIfPreFermiGPU(device))
return std::cout << std::endl << "Kinfu is not supported for pre-Fermi GPU architectures, and not built for them by default. Exiting..." << std::endl, 1;
OpenNISource capture;
capture.open(argv[1]);
KinFuApp app (capture);
// executing
try { app.execute (); }
catch (const std::bad_alloc& /*e*/) { std::cout << "Bad alloc" << std::endl; }
catch (const std::exception& /*e*/) { std::cout << "Exception" << std::endl; }
return 0;
}
<commit_msg>fixed typos<commit_after>#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/viz/vizcore.hpp>
#include <kfusion/kinfu.hpp>
#include <io/capture.hpp>
using namespace kfusion;
struct KinFuApp
{
static void KeyboardCallback(const cv::viz::KeyboardEvent& event, void* pthis)
{
KinFuApp& kinfu = *static_cast<KinFuApp*>(pthis);
if(event.action != cv::viz::KeyboardEvent::KEY_DOWN)
return;
if(event.code == 't' || event.code == 'T')
kinfu.take_cloud(*kinfu.kinfu_);
if(event.code == 'i' || event.code == 'I')
kinfu.interactive_mode_ = !kinfu.interactive_mode_;
}
KinFuApp(OpenNISource& source) : exit_ (false), interactive_mode_(false), capture_ (source), pause_(false)
{
KinFuParams params = KinFuParams::default_params();
kinfu_ = KinFu::Ptr( new KinFu(params) );
capture_.setRegistration(true);
cv::viz::WCube cube(cv::Vec3d::all(0), cv::Vec3d(params.volume_size), true, cv::viz::Color::apricot());
viz.showWidget("cube", cube, params.volume_pose);
viz.showWidget("coor", cv::viz::WCoordinateSystem(0.1));
viz.registerKeyboardCallback(KeyboardCallback, this);
}
void show_depth(const cv::Mat& depth)
{
cv::Mat display;
//cv::normalize(depth, display, 0, 255, cv::NORM_MINMAX, CV_8U);
depth.convertTo(display, CV_8U, 255.0/4000);
cv::imshow("Depth", display);
}
void show_raycasted(KinFu& kinfu)
{
const int mode = 3;
if (interactive_mode_)
kinfu.renderImage(view_device_, viz.getViewerPose(), mode);
else
kinfu.renderImage(view_device_, mode);
view_host_.create(view_device_.rows(), view_device_.cols(), CV_8UC4);
view_device_.download(view_host_.ptr<void>(), view_host_.step);
cv::imshow("Scene", view_host_);
}
void take_cloud(KinFu& kinfu)
{
cuda::DeviceArray<Point> cloud = kinfu.tsdf().fetchCloud(cloud_buffer);
cv::Mat cloud_host(1, (int)cloud.size(), CV_32FC4);
cloud.download(cloud_host.ptr<Point>());
viz.showWidget("cloud", cv::viz::WCloud(cloud_host));
// viz.showWidget("cloud", cv::viz::WPaintedCloud(cloud_host));
}
bool execute()
{
KinFu& kinfu = *kinfu_;
cv::Mat depth, image;
double time_ms = 0;
bool has_image = false;
for (int i = 0; !exit_ && !viz.wasStopped(); ++i)
{
bool has_frame = capture_.grab(depth, image);
if (!has_frame)
return std::cout << "Can't grab" << std::endl, false;
depth_device_.upload(depth.data, depth.step, depth.rows, depth.cols);
{
SampledScopeTime fps(time_ms); (void)fps;
has_image = kinfu(depth_device_);
}
if (has_image)
show_raycasted(kinfu);
show_depth(depth);
//cv::imshow("Image", image);
if (!interactive_mode_)
viz.setViewerPose(kinfu.getCameraPose());
int key = cv::waitKey(pause_ ? 0 : 3);
switch(key)
{
case 't': case 'T' : take_cloud(kinfu); break;
case 'i': case 'I' : interactive_mode_ = !interactive_mode_; break;
case 27: exit_ = true; break;
case 32: pause_ = !pause_; break;
}
//exit_ = exit_ || i > 100;
viz.spinOnce(3, true);
}
return true;
}
bool pause_ /*= false*/;
bool exit_, interactive_mode_;
OpenNISource& capture_;
KinFu::Ptr kinfu_;
cv::viz::Viz3d viz;
cv::Mat view_host_;
cuda::Image view_device_;
cuda::Depth depth_device_;
cuda::DeviceArray<Point> cloud_buffer;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main (int argc, char* argv[])
{
int device = 0;
cuda::setDevice (device);
cuda::printShortCudaDeviceInfo (device);
if(cuda::checkIfPreFermiGPU(device))
return std::cout << std::endl << "Kinfu is not supported for pre-Fermi GPU architectures, and not built for them by default. Exiting..." << std::endl, 1;
OpenNISource capture;
capture.open(argv[1]);
KinFuApp app (capture);
// executing
try { app.execute (); }
catch (const std::bad_alloc& /*e*/) { std::cout << "Bad alloc" << std::endl; }
catch (const std::exception& /*e*/) { std::cout << "Exception" << std::endl; }
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <glog/logging.h>
#include "unsupported/Eigen/CXX11/Tensor"
namespace paddle {
template <class T>
struct EigenBlasGemm {
typedef Eigen::TensorMap<Eigen::Tensor<T, 2, Eigen::RowMajor, int>,
Eigen::Aligned>
Matrix;
static void compute(const bool transA,
const bool transB,
const int M,
const int N,
const int K,
const T alpha,
const T* A,
const int lda,
const T* B,
const int ldb,
const T beta,
T* C,
const int ldc) {
Eigen::array<int, 2> sizeA;
if (transA) {
sizeA[0] = K;
sizeA[1] = M;
CHECK_EQ(M, lda);
} else {
sizeA[0] = M;
sizeA[1] = K;
CHECK_EQ(K, lda);
}
Eigen::array<int, 2> sizeB;
if (transB) {
sizeB[0] = N;
sizeB[1] = K;
CHECK_EQ(K, ldb);
} else {
sizeB[0] = K;
sizeB[1] = N;
CHECK_EQ(N, ldb);
}
Eigen::array<int, 2> sizeC;
sizeC[0] = M;
sizeC[1] = N;
CHECK_EQ(N, ldc);
const Matrix a(const_cast<T*>(A), sizeA);
const Matrix b(const_cast<T*>(B), sizeB);
Matrix c(C, sizeC);
typedef typename Eigen::Tensor<T, 2>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims;
dims[0] = DimPair(1, 0);
dims[0].first = transA ? 0 : 1;
dims[0].second = transB ? 1 : 0;
Eigen::DefaultDevice device;
if (alpha == T(1) && beta == T(0)) {
c.device(device) = a.contract(b, dims);
} else if (alpha == T(1) && beta == T(1)) {
c.device(device) += a.contract(b, dims);
} else {
c.device(device) = alpha * a.contract(b, dims) + beta * c;
}
}
};
#ifdef PADDLE_TYPE_DOUBLE
template struct EigenBlasGemm<double>;
#else
template struct EigenBlasGemm<float>;
#endif
} // namespace paddle
<commit_msg>Enable the case N != ldc in EigenBlasGemm. (#5976)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <glog/logging.h>
#include "unsupported/Eigen/CXX11/Tensor"
namespace paddle {
template <class T>
struct EigenBlasGemm {
typedef Eigen::TensorMap<Eigen::Tensor<T, 2, Eigen::RowMajor, int>,
Eigen::Aligned>
EigenMatrix;
static void compute(const bool transA,
const bool transB,
const int M,
const int N,
const int K,
const T alpha,
const T* A,
const int lda,
const T* B,
const int ldb,
const T beta,
T* C,
const int ldc) {
Eigen::array<int, 2> sizeA;
if (transA) {
sizeA[0] = K;
sizeA[1] = M;
CHECK_EQ(M, lda);
} else {
sizeA[0] = M;
sizeA[1] = K;
CHECK_EQ(K, lda);
}
Eigen::array<int, 2> sizeB;
if (transB) {
sizeB[0] = N;
sizeB[1] = K;
CHECK_EQ(K, ldb);
} else {
sizeB[0] = K;
sizeB[1] = N;
CHECK_EQ(N, ldb);
}
Eigen::array<int, 2> sizeC = {{M, ldc}};
Eigen::array<int, 2> offsetC = {{0, 0}};
Eigen::array<int, 2> extentC = {{M, N}};
const EigenMatrix a(const_cast<T*>(A), sizeA);
const EigenMatrix b(const_cast<T*>(B), sizeB);
EigenMatrix c(C, sizeC);
typedef typename Eigen::Tensor<T, 2>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims;
dims[0] = DimPair(1, 0);
dims[0].first = transA ? 0 : 1;
dims[0].second = transB ? 1 : 0;
Eigen::DefaultDevice device;
if (N == ldc) {
if (alpha == T(1) && beta == T(0)) {
c.device(device) = a.contract(b, dims);
} else if (alpha == T(1) && beta == T(1)) {
c.device(device) += a.contract(b, dims);
} else {
c.device(device) = alpha * a.contract(b, dims) + beta * c;
}
} else {
if (alpha == T(1) && beta == T(0)) {
c.slice(offsetC, extentC).device(device) = a.contract(b, dims);
} else if (alpha == T(1) && beta == T(1)) {
c.slice(offsetC, extentC).device(device) += a.contract(b, dims);
} else {
c.slice(offsetC, extentC).device(device) =
alpha * a.contract(b, dims) + beta * c.slice(offsetC, extentC);
}
}
}
};
#ifdef PADDLE_TYPE_DOUBLE
template struct EigenBlasGemm<double>;
#else
template struct EigenBlasGemm<float>;
#endif
} // namespace paddle
<|endoftext|> |
<commit_before>#include "dumper.hpp"
#include "../coding/multilang_utf8_string.hpp"
#include "../indexer/classificator.hpp"
#include "../indexer/feature_processor.hpp"
#include "../std/algorithm.hpp"
#include "../std/bind.hpp"
#include "../std/iostream.hpp"
#include "../std/map.hpp"
#include "../std/vector.hpp"
namespace feature
{
class TypesCollector
{
vector<uint32_t> m_currFeatureTypes;
public:
typedef map<vector<uint32_t>, size_t> value_type;
value_type m_stats;
size_t m_namesCount;
size_t m_totalCount;
TypesCollector() : m_namesCount(0), m_totalCount(0) {}
void operator()(FeatureType & f, uint32_t)
{
++m_totalCount;
if (!f.GetPreferredDrawableName().empty())
++m_namesCount;
m_currFeatureTypes.clear();
f.ForEachTypeRef(*this);
CHECK(!m_currFeatureTypes.empty(), ("Feature without any type???"));
pair<value_type::iterator, bool> found = m_stats.insert(make_pair(m_currFeatureTypes, 1));
if (!found.second)
found.first->second++;
}
void operator()(uint32_t type)
{
m_currFeatureTypes.push_back(type);
}
};
template <class T>
static bool SortFunc(T const & first, T const & second)
{
return first.second > second.second;
}
void DumpTypes(string const & fPath)
{
TypesCollector doClass;
feature::ForEachFromDat(fPath, doClass);
typedef pair<vector<uint32_t>, size_t> stats_elem_type;
typedef vector<stats_elem_type> vec_to_sort;
vec_to_sort vecToSort(doClass.m_stats.begin(), doClass.m_stats.end());
sort(vecToSort.begin(), vecToSort.end(), &SortFunc<stats_elem_type>);
for (vec_to_sort::iterator it = vecToSort.begin(); it != vecToSort.end(); ++it)
{
cout << it->second << " ";
for (size_t i = 0; i < it->first.size(); ++i)
cout << classif().GetFullObjectName(it->first[i]) << " ";
cout << endl;
}
cout << "Total features: " << doClass.m_totalCount << endl;
cout << "Features with names: " << doClass.m_namesCount << endl;
}
///////////////////////////////////////////////////////////////////
typedef map<int8_t, map<string, size_t> > TokensContainerT;
class PrefixesCollector
{
public:
TokensContainerT m_stats;
bool operator()(int8_t langCode, string const & name)
{
CHECK(!name.empty(), ("Feature name is empty"));
vector<string> tokens;
strings::SimpleTokenizer tok(name, " ");
while (tok)
{
tokens.push_back(*tok);
++tok;
}
if (tokens.empty())
return true;
// ignore token if it's first letter is an uppercase letter
strings::UniString const s1 = strings::MakeUniString(tokens[0]);
strings::UniString const s2 = strings::MakeLowerCase(s1);
if (s1[0] != s2[0])
return true;
for (size_t i = 1; i < tokens.size(); ++i)
{
string s;
for (size_t numTokens = 0; numTokens < i; ++numTokens)
{
s += tokens[numTokens];
s += " ";
}
pair<TokensContainerT::mapped_type::iterator, bool> found = m_stats[langCode].insert(make_pair(s, 1));
if (!found.second)
found.first->second++;
}
return true;
}
void operator()(FeatureType & f, uint32_t)
{
f.ForEachNameRef(*this);
}
};
static size_t const MIN_OCCURRENCE = 3;
void Print(int8_t langCode, TokensContainerT::mapped_type const & container)
{
typedef pair<string, size_t> NameElemT;
typedef vector<NameElemT> VecToSortT;
VecToSortT v(container.begin(), container.end());
sort(v.begin(), v.end(), &SortFunc<NameElemT>);
// do not display prefixes with low occurrences
if (v[0].second > MIN_OCCURRENCE)
{
cout << "Language code: " << StringUtf8Multilang::GetLangByCode(langCode) << endl;
for (VecToSortT::iterator it = v.begin(); it != v.end(); ++it)
{
if (it->second <= MIN_OCCURRENCE)
break;
cout << it->second << " " << it->first << endl;
}
}
}
void DumpPrefixes(string const & fPath)
{
PrefixesCollector doClass;
feature::ForEachFromDat(fPath, doClass);
for (TokensContainerT::iterator it = doClass.m_stats.begin();
it != doClass.m_stats.end(); ++it)
{
Print(it->first, it->second);
}
}
}
<commit_msg>[generator] Output sample names in --dump_prefixes.<commit_after>#include "dumper.hpp"
#include "../coding/multilang_utf8_string.hpp"
#include "../indexer/classificator.hpp"
#include "../indexer/feature_processor.hpp"
#include "../std/algorithm.hpp"
#include "../std/bind.hpp"
#include "../std/iostream.hpp"
#include "../std/map.hpp"
#include "../std/vector.hpp"
namespace feature
{
class TypesCollector
{
vector<uint32_t> m_currFeatureTypes;
public:
typedef map<vector<uint32_t>, size_t> value_type;
value_type m_stats;
size_t m_namesCount;
size_t m_totalCount;
TypesCollector() : m_namesCount(0), m_totalCount(0) {}
void operator()(FeatureType & f, uint32_t)
{
++m_totalCount;
if (!f.GetPreferredDrawableName().empty())
++m_namesCount;
m_currFeatureTypes.clear();
f.ForEachTypeRef(*this);
CHECK(!m_currFeatureTypes.empty(), ("Feature without any type???"));
pair<value_type::iterator, bool> found = m_stats.insert(make_pair(m_currFeatureTypes, 1));
if (!found.second)
found.first->second++;
}
void operator()(uint32_t type)
{
m_currFeatureTypes.push_back(type);
}
};
template <class T>
static bool SortFunc(T const & first, T const & second)
{
return first.second > second.second;
}
void DumpTypes(string const & fPath)
{
TypesCollector doClass;
feature::ForEachFromDat(fPath, doClass);
typedef pair<vector<uint32_t>, size_t> stats_elem_type;
typedef vector<stats_elem_type> vec_to_sort;
vec_to_sort vecToSort(doClass.m_stats.begin(), doClass.m_stats.end());
sort(vecToSort.begin(), vecToSort.end(), &SortFunc<stats_elem_type>);
for (vec_to_sort::iterator it = vecToSort.begin(); it != vecToSort.end(); ++it)
{
cout << it->second << " ";
for (size_t i = 0; i < it->first.size(); ++i)
cout << classif().GetFullObjectName(it->first[i]) << " ";
cout << endl;
}
cout << "Total features: " << doClass.m_totalCount << endl;
cout << "Features with names: " << doClass.m_namesCount << endl;
}
///////////////////////////////////////////////////////////////////
typedef map<int8_t, map<string, pair<unsigned int, string> > > TokensContainerT;
class PrefixesCollector
{
public:
TokensContainerT m_stats;
bool operator()(int8_t langCode, string const & name)
{
CHECK(!name.empty(), ("Feature name is empty"));
vector<string> tokens;
strings::SimpleTokenizer tok(name, " ");
while (tok)
{
tokens.push_back(*tok);
++tok;
}
if (tokens.empty())
return true;
// ignore token if it's first letter is an uppercase letter
strings::UniString const s1 = strings::MakeUniString(tokens[0]);
strings::UniString const s2 = strings::MakeLowerCase(s1);
if (s1[0] != s2[0])
return true;
for (size_t i = 1; i < tokens.size(); ++i)
{
string s;
for (size_t numTokens = 0; numTokens < i; ++numTokens)
{
s += tokens[numTokens];
s += " ";
}
pair<TokensContainerT::mapped_type::iterator, bool> found =
m_stats[langCode].insert(make_pair(s, make_pair(1U, name)));
if (!found.second)
found.first->second.first++;
}
return true;
}
void operator()(FeatureType & f, uint32_t)
{
f.ForEachNameRef(*this);
}
};
static size_t const MIN_OCCURRENCE = 3;
void Print(int8_t langCode, TokensContainerT::mapped_type const & container)
{
typedef pair<string, pair<unsigned int, string> > NameElemT;
typedef vector<NameElemT> VecToSortT;
VecToSortT v(container.begin(), container.end());
sort(v.begin(), v.end(), &SortFunc<NameElemT>);
// do not display prefixes with low occurrences
if (v[0].second.first > MIN_OCCURRENCE)
{
cout << "Language code: " << StringUtf8Multilang::GetLangByCode(langCode) << endl;
for (VecToSortT::iterator it = v.begin(); it != v.end(); ++it)
{
if (it->second.first <= MIN_OCCURRENCE)
break;
cout << it->second.first << " " << it->first << " \"" << it->second.second << "\"" << endl;
}
}
}
void DumpPrefixes(string const & fPath)
{
PrefixesCollector doClass;
feature::ForEachFromDat(fPath, doClass);
for (TokensContainerT::iterator it = doClass.m_stats.begin();
it != doClass.m_stats.end(); ++it)
{
Print(it->first, it->second);
}
}
}
<|endoftext|> |
<commit_before>#include "photoeffects.hpp"
#include <math.h>
using namespace cv;
#define MAX_KERNELSIZE 15
#define PI 3.14159265359
int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)
{
CV_Assert(src.type() == CV_8UC3);
Mat image = src.getMat(), outputImage(image.size(), CV_8UC3);
float kSizeEdges = (image.rows / 2.0f)
* (image.rows / 2.0f)
/ (image.rows / 2.0f - indentTop)
/ (image.rows / 2.0f - indentTop)
+ (image.cols / 2.0f)
* (image.cols / 2.0f)
/ (image.cols / 2.0f - indentLeft)
/ (image.cols / 2.0f - indentLeft);
if (kSizeEdges > MAX_KERNELSIZE)
{
kSizeEdges = MAX_KERNELSIZE;
}
Mat bearingImage(image.rows + 2 * kSizeEdges,
image.cols + 2 * kSizeEdges,
CV_8UC3);
copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,
kSizeEdges, kSizeEdges, BORDER_REPLICATE);
float radius;
int size;
float B, G, R, sumC;
Vec3b Color;
float coeff;
for (int i = kSizeEdges; i < (bearingImage.rows - kSizeEdges); i++)
{
for (int j = kSizeEdges; j < (bearingImage.cols - kSizeEdges); j++)
{
radius = (bearingImage.rows / 2.0f - i)
* (bearingImage.rows / 2.0f - i)
/ (image.rows / 2.0f - indentTop)
/ (image.rows / 2.0f - indentTop)
+ (bearingImage.cols / 2.0f - j)
* (bearingImage.cols / 2.0f - j)
/ (image.cols / 2.0f - indentLeft)
/ (image.cols / 2.0f - indentLeft);
if (radius < 1.0f)
{
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =
bearingImage.at<Vec3b>(i, j);
continue;
}
else
{
R = G = B = sumC = 0.0f;
size = radius;
radius -= 0.5f;
radius *= radius;
if (size > kSizeEdges)
{
size = kSizeEdges;
}
for (int x = i - size; x <= i + size; x++)
{
for (int y = j - size; y <= j + size; y++)
{
coeff = 1.0f / (2.0f * PI * radius)
* exp(- ((x - i)*(x - i) + (y - j)*(y - j))
/ (2.0f * radius));
Color = bearingImage.at<Vec3b>(x, y);
B = B + coeff * Color[0];
G = G + coeff * Color[1];
R = R + coeff * Color[2];
sumC += coeff;
}
}
B /= sumC;
G /= sumC;
R /= sumC;
Color = Vec3b(B, G, R);
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = Color;
}
}
}
outputImage.convertTo(dst, CV_8UC3);
return 0;
}
<commit_msg>Assert<commit_after>#include "photoeffects.hpp"
#include <math.h>
using namespace cv;
#define MAX_KERNELSIZE 15
#define PI 3.14159265359
int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)
{
CV_Assert(src.type() == CV_8UC3);
Mat image = src.getMat(), outputImage(image.size(), CV_8UC3);
CV_Assert(indentTop >= 0 && indentTop <= (image.rows / 2.0f - 10));
CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols / 2.0f - 10));
float kSizeEdges = (image.rows / 2.0f)
* (image.rows / 2.0f)
/ (image.rows / 2.0f - indentTop)
/ (image.rows / 2.0f - indentTop)
+ (image.cols / 2.0f)
* (image.cols / 2.0f)
/ (image.cols / 2.0f - indentLeft)
/ (image.cols / 2.0f - indentLeft);
if (kSizeEdges > MAX_KERNELSIZE)
{
kSizeEdges = MAX_KERNELSIZE;
}
Mat bearingImage(image.rows + 2 * kSizeEdges,
image.cols + 2 * kSizeEdges,
CV_8UC3);
copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,
kSizeEdges, kSizeEdges, BORDER_REPLICATE);
float radius;
int size;
float B, G, R, sumC;
Vec3b Color;
float coeff;
for (int i = kSizeEdges; i < (bearingImage.rows - kSizeEdges); i++)
{
for (int j = kSizeEdges; j < (bearingImage.cols - kSizeEdges); j++)
{
radius = (bearingImage.rows / 2.0f - i)
* (bearingImage.rows / 2.0f - i)
/ (image.rows / 2.0f - indentTop)
/ (image.rows / 2.0f - indentTop)
+ (bearingImage.cols / 2.0f - j)
* (bearingImage.cols / 2.0f - j)
/ (image.cols / 2.0f - indentLeft)
/ (image.cols / 2.0f - indentLeft);
if (radius < 1.0f)
{
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =
bearingImage.at<Vec3b>(i, j);
continue;
}
else
{
R = G = B = sumC = 0.0f;
size = radius;
radius -= 0.5f;
radius *= radius;
if (size > kSizeEdges)
{
size = kSizeEdges;
}
for (int x = i - size; x <= i + size; x++)
{
for (int y = j - size; y <= j + size; y++)
{
coeff = 1.0f / (2.0f * PI * radius)
* exp(- ((x - i)*(x - i) + (y - j)*(y - j))
/ (2.0f * radius));
Color = bearingImage.at<Vec3b>(x, y);
B = B + coeff * Color[0];
G = G + coeff * Color[1];
R = R + coeff * Color[2];
sumC += coeff;
}
}
B /= sumC;
G /= sumC;
R /= sumC;
Color = Vec3b(B, G, R);
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = Color;
}
}
}
outputImage.convertTo(dst, CV_8UC3);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/zorba.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "zorbatypes/xqpstring.h"
#include "util/properties.h"
#include <zorba/util/path.h>
#include "store/api/item.h"
#include "zorba_test_setting.h"
#ifndef ZORBA_MINIMAL_STORE
#include <simplestore/simplestore.h>
#include "store/naive/simple_store.h"
#else
#include "store/minimal/min_store.h"
#endif
using namespace zorba;
using namespace std;
void set_var (string name, string val, DynamicContext* dctx)
{
if (name [name.size () - 1] == ':')
{
Item lItem = Zorba::getInstance(NULL)->getItemFactory()->createString(val);
if(name != ".") {
dctx->setVariable(name.substr (0, name.size () - 1), lItem);
} else
dctx->setContextItem(lItem);
}
else if (name[name.size () - 1] != ':')
{
ifstream* is = new ifstream(val.c_str ());
assert (*is);
if(name != ".")
dctx->setVariableAsDocument(name, val.c_str(), std::auto_ptr<std::istream>(is));
else
dctx->setContextItemAsDocument(val.c_str(), std::auto_ptr<std::istream>(is));
}
}
// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
// read the command file properties
if (! Properties::load(argc,argv))
return 4;
Properties* lProp = Properties::instance();
if (! lProp->hasSingleQuery ()) {
cout << "Error: either a single inline query or a single query file must be supplied" << endl;
return 4;
}
Zorba_CompilerHints chints;
chints.opt_level = (lProp->optimizer () ?
ZORBA_OPT_LEVEL_O1:
ZORBA_OPT_LEVEL_O0);
// output file (either a file or the standard out if no file is specified)
auto_ptr<ostream> outputFile (lProp->resultFile ().empty ()
? NULL : new ofstream (lProp->resultFile().c_str()));
ostream *resultFile = outputFile.get ();
if (resultFile == NULL)
resultFile = &cout;
// input file (either from a file or given as parameter)
auto_ptr<istream> qfile;
filesystem_path path;
if (! lProp->inlineQuery()) {
path = lProp->queryFile ();
path.resolve_relative ();
std::string fname = path.get_path ();
qfile.reset (new ifstream (fname.c_str ()));
if (!qfile->good() || qfile->eof()) {
cerr << "no query given or not readable " << fname << endl;
return 3;
}
} else {
qfile.reset (new istringstream(lProp->query ()));
}
// print the query if requested
if (lProp->printQuery()) {
cout << "Query text:\n";
copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (cout));
cout << "\n" << endl;
qfile->seekg(0); // go back to the beginning
}
// Instantiate the simple store
#ifdef ZORBA_MINIMAL_STORE
zorba::storeminimal::SimpleStore* store =
zorba::storeminimal::SimpleStore::getInstance();
#else
zorba::simplestore::SimpleStore* store =
zorba::simplestore::SimpleStoreManager::getStore();
#endif
// start processing
Zorba* zengine = Zorba::getInstance(store);
// start parsing the query
XQuery_t query = zengine->createQuery ();
#ifdef ZORBA_DEBUGGER
query->setDebugMode(lProp->debug());
#endif
if (! lProp->inlineQuery())
query->setFileName (path.get_path ());
try {
query->compile(*qfile, chints);
} catch (ZorbaException &e) {
// no need to close because the object is not valid
cerr << "Compilation error: " << e << endl;
return 1;
}
// set external variables
vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
DynamicContext* dctx = query->getDynamicContext ();
dctx->setImplicitTimezone (lProp->tz ());
for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
iter != ext_vars.end (); iter++) {
set_var (iter->first, iter->second, dctx);
}
if (! lProp->compileOnly ()) {
// output the result (either using xml serialization or using show)
// cout << "Running query and printing result..." << endl;
try {
if (lProp->useSerializer()) {
if (query->isUpdateQuery()) {
query->applyUpdates();
} else {
Zorba_SerializerOptions opts = Zorba_SerializerOptions::SerializerOptionsFromStringParams(lProp->getSerializerParameters());
query->serialize(*resultFile, &opts);
// *resultFile << query;
}
} else {
if (query->isUpdateQuery()) {
query->applyUpdates();
} else {
ResultIterator_t result = query->iterator();
result->open();
Item lItem;
while (result->next(lItem)) {
// unmarshall the store item from the api item
store::Item_t lStoreItem = Unmarshaller::getInternalItem(lItem);
*resultFile << lStoreItem->show() << endl;
}
result->close();
}
}
} catch (ZorbaException &e) {
query->close();
zengine->shutdown();
store->shutdown();
cerr << "Execution error: ";
if (dynamic_cast<QueryException *> (&e) != NULL)
cerr << (QueryException &) e;
else
cerr << e;
cerr << endl;
return 2;
}
}
query->close();
zengine->shutdown();
store->shutdown();
return 0;
}
<commit_msg>Changed apitest to process also .xqx XQueryX files.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <zorba/zorba.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
// tests are allowed to use internals
#include "api/unmarshaller.h"
#include "zorbatypes/xqpstring.h"
#include "util/properties.h"
#include <zorba/util/path.h>
#include "store/api/item.h"
#include "zorba_test_setting.h"
#ifndef ZORBA_MINIMAL_STORE
#include <simplestore/simplestore.h>
#include "store/naive/simple_store.h"
#else
#include "store/minimal/min_store.h"
#endif
using namespace zorba;
using namespace std;
void set_var (string name, string val, DynamicContext* dctx)
{
if (name [name.size () - 1] == ':')
{
Item lItem = Zorba::getInstance(NULL)->getItemFactory()->createString(val);
if(name != ".") {
dctx->setVariable(name.substr (0, name.size () - 1), lItem);
} else
dctx->setContextItem(lItem);
}
else if (name[name.size () - 1] != ':')
{
ifstream* is = new ifstream(val.c_str ());
assert (*is);
if(name != ".")
dctx->setVariableAsDocument(name, val.c_str(), std::auto_ptr<std::istream>(is));
else
dctx->setContextItemAsDocument(val.c_str(), std::auto_ptr<std::istream>(is));
}
}
// TODO: for now apitest users expect 0 even for error results; this should change
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
// read the command file properties
if (! Properties::load(argc,argv))
return 4;
Properties* lProp = Properties::instance();
if (! lProp->hasSingleQuery ()) {
cout << "Error: either a single inline query or a single query file must be supplied" << endl;
return 4;
}
Zorba_CompilerHints chints;
chints.opt_level = (lProp->optimizer () ?
ZORBA_OPT_LEVEL_O1:
ZORBA_OPT_LEVEL_O0);
// output file (either a file or the standard out if no file is specified)
auto_ptr<ostream> outputFile (lProp->resultFile ().empty ()
? NULL : new ofstream (lProp->resultFile().c_str()));
ostream *resultFile = outputFile.get ();
if (resultFile == NULL)
resultFile = &cout;
// input file (either from a file or given as parameter)
auto_ptr<istream> qfile;
filesystem_path path;
bool is_xqueryx = false;
if (! lProp->inlineQuery()) {
path = lProp->queryFile ();
path.resolve_relative ();
std::string fname = path.get_path ();
if(fname.substr(fname.length()-4) == ".xqx")
is_xqueryx = true;
qfile.reset (new ifstream (fname.c_str ()));
if (!qfile->good() || qfile->eof()) {
cerr << "no query given or not readable " << fname << endl;
return 3;
}
} else {
qfile.reset (new istringstream(lProp->query ()));
}
// print the query if requested
if (lProp->printQuery()) {
cout << "Query text:\n";
copy (istreambuf_iterator<char> (*qfile), istreambuf_iterator<char> (), ostreambuf_iterator<char> (cout));
cout << "\n" << endl;
qfile->seekg(0); // go back to the beginning
}
// Instantiate the simple store
#ifdef ZORBA_MINIMAL_STORE
zorba::storeminimal::SimpleStore* store =
zorba::storeminimal::SimpleStore::getInstance();
#else
zorba::simplestore::SimpleStore* store =
zorba::simplestore::SimpleStoreManager::getStore();
#endif
// start processing
Zorba* zengine = Zorba::getInstance(store);
// start parsing the query
XQuery_t query;
if(!is_xqueryx)
query = zengine->createQuery ();
else
query = zengine->createXQueryX ();
#ifdef ZORBA_DEBUGGER
query->setDebugMode(lProp->debug());
#endif
if (! lProp->inlineQuery())
query->setFileName (path.get_path ());
try {
query->compile(*qfile, chints);
} catch (ZorbaException &e) {
// no need to close because the object is not valid
cerr << "Compilation error: " << e << endl;
return 1;
}
// set external variables
vector<pair <string, string> > ext_vars = lProp->getExternalVars ();
DynamicContext* dctx = query->getDynamicContext ();
dctx->setImplicitTimezone (lProp->tz ());
for (vector<pair <string, string> >::const_iterator iter = ext_vars.begin ();
iter != ext_vars.end (); iter++) {
set_var (iter->first, iter->second, dctx);
}
if (! lProp->compileOnly ()) {
// output the result (either using xml serialization or using show)
// cout << "Running query and printing result..." << endl;
try {
if (lProp->useSerializer()) {
if (query->isUpdateQuery()) {
query->applyUpdates();
} else {
Zorba_SerializerOptions opts = Zorba_SerializerOptions::SerializerOptionsFromStringParams(lProp->getSerializerParameters());
query->serialize(*resultFile, &opts);
// *resultFile << query;
}
} else {
if (query->isUpdateQuery()) {
query->applyUpdates();
} else {
ResultIterator_t result = query->iterator();
result->open();
Item lItem;
while (result->next(lItem)) {
// unmarshall the store item from the api item
store::Item_t lStoreItem = Unmarshaller::getInternalItem(lItem);
*resultFile << lStoreItem->show() << endl;
}
result->close();
}
}
} catch (ZorbaException &e) {
query->close();
zengine->shutdown();
store->shutdown();
cerr << "Execution error: ";
if (dynamic_cast<QueryException *> (&e) != NULL)
cerr << (QueryException &) e;
else
cerr << e;
cerr << endl;
return 2;
}
}
query->close();
zengine->shutdown();
store->shutdown();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef HASHTABLE_HH
#define HASHTABLE_HH
#include "khmer.hh"
#include <fstream>
#include <string>
#define MAX_COUNT 255
namespace khmer {
typedef unsigned char BoundedCounterType;
class Hashtable {
protected:
const WordLength _ksize;
const HashIntoType _tablesize;
BoundedCounterType * _counts;
void _allocate_counters() {
_counts = new BoundedCounterType[_tablesize];
memset(_counts, 0, _tablesize * sizeof(BoundedCounterType));
}
public:
Hashtable(WordLength ksize, HashIntoType tablesize) :
_ksize(ksize), _tablesize(tablesize) {
_allocate_counters();
}
~Hashtable() {
delete _counts; _counts = NULL;
}
// accessor to get 'k'
const WordLength ksize() const { return _ksize; }
// accessors to get table info
const HashIntoType n_entries() const { return _tablesize; }
void count(const char * kmer) {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
void count(HashIntoType khash) {
HashIntoType bin = khash % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
// get the count for the given k-mer.
const BoundedCounterType get_count(const char * kmer) const {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
return _counts[bin];
}
// get the count for the given k-mer hash.
const BoundedCounterType get_count(HashIntoType khash) const {
HashIntoType bin = khash % _tablesize;
return _counts[bin];
}
// count every k-mer in the string.
unsigned int consume_string(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// checks each read for non-ACGT characters
unsigned int checkAndProcessRead(const std::string &read,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// count every k-mer in the FASTA file.
unsigned int consume_fasta(const std::string &filename,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// filter/trim through the given FASTA file.
void filter_fasta_file(const std::string &inputfile,
const std::string &outputfile,
int minLength,
int threshold);
// @@CTB doc
BoundedCounterType get_min_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
BoundedCounterType get_max_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
};
class HashtableIntersect {
protected:
khmer::Hashtable * _kh1;
khmer::Hashtable * _kh2;
public:
HashtableIntersect(WordLength ksize,
HashIntoType tablesize1, HashIntoType tablesize2)
{
_kh1 = new Hashtable(ksize, tablesize1);
_kh2 = new Hashtable(ksize, tablesize2);
}
~HashtableIntersect()
{
delete _kh1;
delete _kh2;
}
// count every k-mer in the string.
void consume_string(const std::string &s)
{
_kh1->consume_string(s);
_kh2->consume_string(s);
}
BoundedCounterType get_min_count(const std::string &s)
{
BoundedCounterType kh1Min = _kh1->get_min_count(s);
BoundedCounterType kh2Min = _kh2->get_min_count(s);
if (kh1Min < kh2Min) {
return kh1Min;
} else {
return kh2Min;
}
}
BoundedCounterType get_max_count(const std::string &s)
{
BoundedCounterType kh1Max = _kh1->get_max_count(s);
BoundedCounterType kh2Max = _kh2->get_max_count(s);
if (kh1Max > kh2Max) {
return kh1Max;
} else {
return kh2Max;
}
}
};
};
#endif // HASHTABLE_HH
<commit_msg>put guard around _counts<commit_after>#ifndef HASHTABLE_HH
#define HASHTABLE_HH
#include "khmer.hh"
#include <fstream>
#include <string>
#define MAX_COUNT 255
namespace khmer {
typedef unsigned char BoundedCounterType;
class Hashtable {
protected:
const WordLength _ksize;
const HashIntoType _tablesize;
BoundedCounterType * _counts;
void _allocate_counters() {
_counts = new BoundedCounterType[_tablesize];
memset(_counts, 0, _tablesize * sizeof(BoundedCounterType));
}
public:
Hashtable(WordLength ksize, HashIntoType tablesize) :
_ksize(ksize), _tablesize(tablesize) {
_allocate_counters();
}
~Hashtable() {
if (_counts) { delete _counts; _counts = NULL; }
}
// accessor to get 'k'
const WordLength ksize() const { return _ksize; }
// accessors to get table info
const HashIntoType n_entries() const { return _tablesize; }
void count(const char * kmer) {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
void count(HashIntoType khash) {
HashIntoType bin = khash % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
// get the count for the given k-mer.
const BoundedCounterType get_count(const char * kmer) const {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
return _counts[bin];
}
// get the count for the given k-mer hash.
const BoundedCounterType get_count(HashIntoType khash) const {
HashIntoType bin = khash % _tablesize;
return _counts[bin];
}
// count every k-mer in the string.
unsigned int consume_string(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// checks each read for non-ACGT characters
unsigned int checkAndProcessRead(const std::string &read,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// count every k-mer in the FASTA file.
unsigned int consume_fasta(const std::string &filename,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// filter/trim through the given FASTA file.
void filter_fasta_file(const std::string &inputfile,
const std::string &outputfile,
int minLength,
int threshold);
// @@CTB doc
BoundedCounterType get_min_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
BoundedCounterType get_max_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
};
class HashtableIntersect {
protected:
khmer::Hashtable * _kh1;
khmer::Hashtable * _kh2;
public:
HashtableIntersect(WordLength ksize,
HashIntoType tablesize1, HashIntoType tablesize2)
{
_kh1 = new Hashtable(ksize, tablesize1);
_kh2 = new Hashtable(ksize, tablesize2);
}
~HashtableIntersect()
{
delete _kh1;
delete _kh2;
}
// count every k-mer in the string.
void consume_string(const std::string &s)
{
_kh1->consume_string(s);
_kh2->consume_string(s);
}
BoundedCounterType get_min_count(const std::string &s)
{
BoundedCounterType kh1Min = _kh1->get_min_count(s);
BoundedCounterType kh2Min = _kh2->get_min_count(s);
if (kh1Min < kh2Min) {
return kh1Min;
} else {
return kh2Min;
}
}
BoundedCounterType get_max_count(const std::string &s)
{
BoundedCounterType kh1Max = _kh1->get_max_count(s);
BoundedCounterType kh2Max = _kh2->get_max_count(s);
if (kh1Max > kh2Max) {
return kh1Max;
} else {
return kh2Max;
}
}
};
};
#endif // HASHTABLE_HH
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file context.cpp
\author Tom Fogal
SCI Institute
University of Utah
\brief Establishes an OpenGL context.
*/
#include "StdTuvokDefines.h"
#ifdef DETECTED_OS_WINDOWS
# include <GL/wgl.h>
# include <windows.h>
#elif defined(DETECTED_OS_LINUX)
# include <GL/glx.h>
# include <X11/Xlib.h>
#endif
#include "Controller/Controller.h"
#include "context.h"
TvkContext::~TvkContext() { }
#ifdef DETECTED_OS_LINUX
struct xinfo {
Display *display;
XVisualInfo *visual;
Window win;
GLXContext ctx;
Colormap cmap;
};
class TvkGLXContext: public TvkContext {
public:
TvkGLXContext(uint32_t w, uint32_t h, uint8_t color_bits,
uint8_t depth_bits, uint8_t stencil_bits,
bool double_buffer);
virtual ~TvkGLXContext();
bool isValid() const;
bool makeCurrent();
bool swapBuffers();
private:
struct xinfo xi;
};
#endif
class TvkWGLContext: public TvkContext {
public:
TvkWGLContext(uint32_t w, uint32_t h, uint8_t color_bits,
uint8_t depth_bits, uint8_t stencil_bits,
bool double_buffer);
virtual ~TvkWGLContext() {}
bool isValid() const;
bool makeCurrent();
bool swapBuffers();
private:
#ifdef DETECTED_OS_WINDOWS
HDC deviceContext;
HGLRC renderingContext;
HWND window;
#endif
};
TvkContext* TvkContext::Create(uint32_t width, uint32_t height,
uint8_t color_bits, uint8_t depth_bits,
uint8_t stencil_bits, bool double_buffer)
{
#ifdef DETECTED_OS_WINDOWS
return new TvkWGLContext(width, height, color_bits, depth_bits, stencil_bits,
double_buffer);
#else
return new TvkGLXContext(width, height, color_bits, depth_bits, stencil_bits,
double_buffer);
#endif
}
#ifdef DETECTED_OS_LINUX
static struct xinfo x_connect(uint32_t, uint32_t, bool);
static XVisualInfo* find_visual(Display*, bool);
static void glx_init(Display*, XVisualInfo*, Window, GLXContext&);
TvkGLXContext::TvkGLXContext(uint32_t w, uint32_t h, uint8_t,
uint8_t, uint8_t,
bool double_buffer)
{
// if you *really* require a specific value... just hack this class
// to your liking. You probably want to add those parameters to x_connect
// and use them there.
WARNING("Ignoring color, depth, stencil bits. For many applications, it "
"is better to let the GLX library choose the \"best\" visual.");
this->xi = x_connect(w, h, double_buffer);
glx_init(xi.display, xi.visual, xi.win, xi.ctx);
}
TvkGLXContext::~TvkGLXContext()
{
glXDestroyContext(xi.display, xi.ctx);
XDestroyWindow(xi.display, xi.win);
XFree(xi.visual);
XCloseDisplay(xi.display);
}
bool TvkGLXContext::isValid() const
{
return this->xi.display != NULL && this->xi.ctx != NULL;
}
bool TvkGLXContext::makeCurrent()
{
if(glXMakeCurrent(this->xi.display, this->xi.win, this->xi.ctx) != True) {
T_ERROR("Could not make context current!");
return false;
}
return true;
}
bool TvkGLXContext::swapBuffers()
{
glXSwapBuffers(this->xi.display, this->xi.win);
// SwapBuffers generates an X error if it fails.
return true;
}
static struct xinfo
x_connect(uint32_t width, uint32_t height, bool dbl_buffer)
{
struct xinfo rv;
rv.display = XOpenDisplay(NULL);
if(rv.display == NULL) {
T_ERROR("Could not connect to display: '%s'!", XDisplayName(NULL));
throw NoAvailableContext();
}
XSynchronize(rv.display, True);
rv.visual = find_visual(rv.display, dbl_buffer);
Window parent = RootWindow(rv.display, rv.visual->screen);
XSetWindowAttributes xw_attr;
xw_attr.override_redirect = False;
xw_attr.background_pixel = 0;
xw_attr.colormap = XCreateColormap(rv.display, parent, rv.visual->visual,
AllocNone);
xw_attr.event_mask = StructureNotifyMask | ExposureMask;
rv.win = XCreateWindow(rv.display, parent, 0,0, width,height, 0,
rv.visual->depth,
InputOutput, rv.visual->visual,
CWBackPixel | CWBorderPixel | CWColormap |
CWOverrideRedirect | CWEventMask,
&xw_attr);
XStoreName(rv.display, rv.win, "Tuvok testing");
XSync(rv.display, False);
return rv;
}
static void
glx_init(Display *disp, XVisualInfo *visual, Window win, GLXContext& ctx)
{
if(!glXQueryExtension(disp, NULL, NULL)) {
T_ERROR("Display does not support glX.");
return;
}
ctx = glXCreateContext(disp, visual, 0, GL_TRUE);
if(!ctx) {
T_ERROR("glX Context creation failed.");
}
if(glXMakeCurrent(disp, win, ctx) == True) {
MESSAGE("Make current succeeded: %p", glXGetCurrentContext());
} else {
T_ERROR("make current FAILED: %p", glXGetCurrentContext());
return;
}
}
static XVisualInfo *
find_visual(Display *d, bool double_buffered)
{
XVisualInfo *ret_v;
// GLX_USE_GL is basically a no-op, so this provides a convenient
// way of specifying double buffering or not.
int att_buf = double_buffered ? GLX_DOUBLEBUFFER : GLX_USE_GL;
int attr[] = {
GLX_RGBA,
att_buf,
GLX_RED_SIZE, 5,
GLX_GREEN_SIZE, 6,
GLX_BLUE_SIZE, 5,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 8,
GLX_ACCUM_RED_SIZE, 1,
GLX_ACCUM_GREEN_SIZE, 1,
GLX_ACCUM_BLUE_SIZE, 1,
None
};
ret_v = glXChooseVisual(d, DefaultScreen(d), attr);
MESSAGE("ChooseVisual got us %p", (const void*)ret_v);
return ret_v;
}
#endif
#ifdef DETECTED_OS_WINDOWS
#endif
<commit_msg>Use classes' makeCurrent instead of duplicating.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2010 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file context.cpp
\author Tom Fogal
SCI Institute
University of Utah
\brief Establishes an OpenGL context.
*/
#include "StdTuvokDefines.h"
#ifdef DETECTED_OS_WINDOWS
# include <GL/wgl.h>
# include <windows.h>
#elif defined(DETECTED_OS_LINUX)
# include <GL/glx.h>
# include <X11/Xlib.h>
#endif
#include "Controller/Controller.h"
#include "context.h"
TvkContext::~TvkContext() { }
#ifdef DETECTED_OS_LINUX
struct xinfo {
Display *display;
XVisualInfo *visual;
Window win;
GLXContext ctx;
Colormap cmap;
};
class TvkGLXContext: public TvkContext {
public:
TvkGLXContext(uint32_t w, uint32_t h, uint8_t color_bits,
uint8_t depth_bits, uint8_t stencil_bits,
bool double_buffer);
virtual ~TvkGLXContext();
bool isValid() const;
bool makeCurrent();
bool swapBuffers();
private:
struct xinfo xi;
};
#endif
class TvkWGLContext: public TvkContext {
public:
TvkWGLContext(uint32_t w, uint32_t h, uint8_t color_bits,
uint8_t depth_bits, uint8_t stencil_bits,
bool double_buffer);
virtual ~TvkWGLContext() {}
bool isValid() const;
bool makeCurrent();
bool swapBuffers();
private:
#ifdef DETECTED_OS_WINDOWS
HDC deviceContext;
HGLRC renderingContext;
HWND window;
#endif
};
TvkContext* TvkContext::Create(uint32_t width, uint32_t height,
uint8_t color_bits, uint8_t depth_bits,
uint8_t stencil_bits, bool double_buffer)
{
#ifdef DETECTED_OS_WINDOWS
return new TvkWGLContext(width, height, color_bits, depth_bits, stencil_bits,
double_buffer);
#else
return new TvkGLXContext(width, height, color_bits, depth_bits, stencil_bits,
double_buffer);
#endif
}
#ifdef DETECTED_OS_LINUX
static struct xinfo x_connect(uint32_t, uint32_t, bool);
static XVisualInfo* find_visual(Display*, bool);
static void glx_init(Display*, XVisualInfo*, GLXContext&);
TvkGLXContext::TvkGLXContext(uint32_t w, uint32_t h, uint8_t,
uint8_t, uint8_t,
bool double_buffer)
{
// if you *really* require a specific value... just hack this class
// to your liking. You probably want to add those parameters to x_connect
// and use them there.
WARNING("Ignoring color, depth, stencil bits. For many applications, it "
"is better to let the GLX library choose the \"best\" visual.");
this->xi = x_connect(w, h, double_buffer);
glx_init(xi.display, xi.visual, xi.ctx);
this->makeCurrent();
MESSAGE("Current context: %p", glXGetCurrentContext());
}
TvkGLXContext::~TvkGLXContext()
{
glXDestroyContext(xi.display, xi.ctx);
XDestroyWindow(xi.display, xi.win);
XFree(xi.visual);
XCloseDisplay(xi.display);
}
bool TvkGLXContext::isValid() const
{
return this->xi.display != NULL && this->xi.ctx != NULL;
}
bool TvkGLXContext::makeCurrent()
{
if(glXMakeCurrent(this->xi.display, this->xi.win, this->xi.ctx) != True) {
T_ERROR("Could not make context current!");
return false;
}
return true;
}
bool TvkGLXContext::swapBuffers()
{
glXSwapBuffers(this->xi.display, this->xi.win);
// SwapBuffers generates an X error if it fails.
return true;
}
static struct xinfo
x_connect(uint32_t width, uint32_t height, bool dbl_buffer)
{
struct xinfo rv;
rv.display = XOpenDisplay(NULL);
if(rv.display == NULL) {
T_ERROR("Could not connect to display: '%s'!", XDisplayName(NULL));
throw NoAvailableContext();
}
XSynchronize(rv.display, True);
rv.visual = find_visual(rv.display, dbl_buffer);
Window parent = RootWindow(rv.display, rv.visual->screen);
XSetWindowAttributes xw_attr;
xw_attr.override_redirect = False;
xw_attr.background_pixel = 0;
xw_attr.colormap = XCreateColormap(rv.display, parent, rv.visual->visual,
AllocNone);
xw_attr.event_mask = StructureNotifyMask | ExposureMask;
rv.win = XCreateWindow(rv.display, parent, 0,0, width,height, 0,
rv.visual->depth,
InputOutput, rv.visual->visual,
CWBackPixel | CWBorderPixel | CWColormap |
CWOverrideRedirect | CWEventMask,
&xw_attr);
XStoreName(rv.display, rv.win, "Tuvok testing");
XSync(rv.display, False);
return rv;
}
static void
glx_init(Display *disp, XVisualInfo *visual, GLXContext& ctx)
{
if(!glXQueryExtension(disp, NULL, NULL)) {
T_ERROR("Display does not support glX.");
return;
}
ctx = glXCreateContext(disp, visual, 0, GL_TRUE);
if(!ctx) {
T_ERROR("glX Context creation failed.");
}
}
static XVisualInfo *
find_visual(Display *d, bool double_buffered)
{
XVisualInfo *ret_v;
// GLX_USE_GL is basically a no-op, so this provides a convenient
// way of specifying double buffering or not.
int att_buf = double_buffered ? GLX_DOUBLEBUFFER : GLX_USE_GL;
int attr[] = {
GLX_RGBA,
att_buf,
GLX_RED_SIZE, 5,
GLX_GREEN_SIZE, 6,
GLX_BLUE_SIZE, 5,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 8,
GLX_ACCUM_RED_SIZE, 1,
GLX_ACCUM_GREEN_SIZE, 1,
GLX_ACCUM_BLUE_SIZE, 1,
None
};
ret_v = glXChooseVisual(d, DefaultScreen(d), attr);
MESSAGE("ChooseVisual got us %p", (const void*)ret_v);
return ret_v;
}
#endif
#ifdef DETECTED_OS_WINDOWS
#endif
<|endoftext|> |
<commit_before>/* cuda_wrapper/texture.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* This file is part of HALMD.
*
* HALMD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_TEXTURE_HPP
#define CUDA_TEXTURE_HPP
#include <cuda_runtime.h>
#ifndef __CUDACC__
# include <cuda_wrapper/error.hpp>
# include <cuda_wrapper/vector.hpp>
#endif
/*
* CUDA texture management
*/
namespace cuda
{
template<class T>
class texture
{
public:
#ifdef __CUDACC__
/**
* type-safe constructor for CUDA host code
*/
texture(::texture<T, 1, cudaReadModeElementType> const& tex) : tex(tex) {}
#else
/**
* bind CUDA texture to device memory array
*/
void bind(cuda::vector<T> const& g_array)
{
CUDA_CALL(cudaBindTexture(NULL, &tex, g_array.data(), &tex.channelDesc));
}
/**
* unbind CUDA texture
*/
void unbind()
{
CUDA_CALL(cudaUnbindTexture(&tex));
}
private:
/**
* bogus constructor to avoid GCC 4.4 compiler warning
*/
texture(textureReference const& tex) : tex(tex) {}
#endif
private:
textureReference const& tex;
};
}
#endif /* ! CUDA_TEXTURE_HPP */
<commit_msg>Implement cuda::texture following RAII pattern<commit_after>/* cuda_wrapper/texture.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* This file is part of HALMD.
*
* HALMD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CUDA_TEXTURE_HPP
#define CUDA_TEXTURE_HPP
#include <boost/noncopyable.hpp>
#include <cuda_runtime.h>
#ifndef __CUDACC__
# include <cuda_wrapper/error.hpp>
# include <cuda_wrapper/vector.hpp>
#endif
/*
* CUDA texture management
*/
namespace cuda
{
template<class T>
class texture
: boost::noncopyable
{
public:
#ifndef __CUDACC__
/**
* bind CUDA texture to device memory array
*/
texture(texture const& texture_, vector<T> const& vector_)
: texref_(texture_.texref_)
{
CUDA_CALL(cudaBindTexture(NULL, &texref_, vector_.data(), &texref_.channelDesc));
}
/**
* unbind CUDA texture
*/
~texture()
{
CUDA_CALL(cudaUnbindTexture(&texref_));
}
#else
/**
* store CUDA texture reference
*/
texture(::texture<T> const& texref)
: texref_(texref)
{}
#endif
private:
::textureReference const& texref_;
};
}
#endif /* ! CUDA_TEXTURE_HPP */
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <algorithm>
#include "RenderDevice.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace graphics
{
RenderDevice::RenderDevice(Renderer::Driver aDriver):
driver(aDriver),
projectionTransform(Matrix4::IDENTITY),
renderTargetProjectionTransform(Matrix4::IDENTITY),
refillQueue(true),
currentFPS(0.0f),
accumulatedFPS(0.0f)
{
}
RenderDevice::~RenderDevice()
{
}
bool RenderDevice::init(Window* newWindow,
const Size2& newSize,
uint32_t newSampleCount,
Texture::Filter newTextureFilter,
uint32_t newMaxAnisotropy,
bool newVerticalSync,
bool newDepth,
bool newDebugRenderer)
{
window = newWindow;
size = newSize;
sampleCount = newSampleCount;
textureFilter = newTextureFilter;
maxAnisotropy = newMaxAnisotropy;
verticalSync = newVerticalSync;
depth = newDepth;
debugRenderer = newDebugRenderer;
clearColor = Color::BLACK;
previousFrameTime = std::chrono::steady_clock::now();
return true;
}
bool RenderDevice::process()
{
std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);
previousFrameTime = currentTime;
float delta = diff.count() / 1000000000.0f;
if (delta > 0.0f)
{
currentFPS = 1.0f / delta;
}
accumulatedTime += delta;
currentAccumulatedFPS += 1.0f;
if (accumulatedTime > 1.0f)
{
accumulatedFPS = currentAccumulatedFPS;
accumulatedTime = 0.0f;
currentAccumulatedFPS = 0.0f;
}
std::vector<DrawCommand> drawCommands;
{
#if OUZEL_MULTITHREADED
std::unique_lock<std::mutex> lock(drawQueueMutex);
while (!queueFinished)
{
queueCondition.wait(lock);
}
#endif
drawCommands = std::move(drawQueue);
drawQueue.reserve(drawCommands.size());
queueFinished = false;
}
std::vector<std::unique_ptr<Resource>> deleteResources;
{
std::lock_guard<std::mutex> lock(resourceMutex);
deleteResources = std::move(resourceDeleteSet);
}
// refills the draw queue
refillQueue = true;
executeAll();
++currentFrame;
if (!draw(drawCommands))
{
return false;
}
deleteResources.clear(); // delete all resources in delete set
return true;
}
void RenderDevice::setClearColorBuffer(bool clear)
{
clearColorBuffer = clear;
}
void RenderDevice::setClearDepthBuffer(bool clear)
{
clearDepthBuffer = clear;
}
void RenderDevice::setClearColor(Color color)
{
clearColor = color;
}
void RenderDevice::setClearDepth(float newClearDepth)
{
clearDepth = newClearDepth;
}
void RenderDevice::setSize(const Size2& newSize)
{
size = newSize;
}
std::vector<Size2> RenderDevice::getSupportedResolutions() const
{
return std::vector<Size2>();
}
void RenderDevice::deleteResource(Resource* resource)
{
std::lock_guard<std::mutex> lock(resourceMutex);
auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<Resource>& ptr) {
return ptr.get() == resource;
});
if (resourceIterator != resources.end())
{
resourceDeleteSet.push_back(std::move(*resourceIterator));
resources.erase(resourceIterator);
}
}
bool RenderDevice::addDrawCommand(const DrawCommand& drawCommand)
{
std::lock_guard<std::mutex> lock(drawQueueMutex);
drawQueue.push_back(drawCommand);
return true;
}
void RenderDevice::flushCommands()
{
refillQueue = false;
{
std::lock_guard<std::mutex> lock(drawQueueMutex);
queueFinished = true;
drawCallCount = static_cast<uint32_t>(drawQueue.size());
}
#if OUZEL_MULTITHREADED
queueCondition.notify_one();
#endif
}
bool RenderDevice::generateScreenshot(const std::string&)
{
return true;
}
void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)
{
std::lock_guard<std::mutex> lock(executeMutex);
executeQueue.push(func);
}
void RenderDevice::executeAll()
{
std::function<void(void)> func;
for (;;)
{
{
std::lock_guard<std::mutex> lock(executeMutex);
if (executeQueue.empty())
{
break;
}
func = std::move(executeQueue.front());
executeQueue.pop();
}
if (func)
{
func();
}
}
}
} // namespace graphics
} // namespace ouzel
<commit_msg>Don't erase and recreate draw queue<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <algorithm>
#include "RenderDevice.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace graphics
{
RenderDevice::RenderDevice(Renderer::Driver aDriver):
driver(aDriver),
projectionTransform(Matrix4::IDENTITY),
renderTargetProjectionTransform(Matrix4::IDENTITY),
refillQueue(true),
currentFPS(0.0f),
accumulatedFPS(0.0f)
{
}
RenderDevice::~RenderDevice()
{
}
bool RenderDevice::init(Window* newWindow,
const Size2& newSize,
uint32_t newSampleCount,
Texture::Filter newTextureFilter,
uint32_t newMaxAnisotropy,
bool newVerticalSync,
bool newDepth,
bool newDebugRenderer)
{
window = newWindow;
size = newSize;
sampleCount = newSampleCount;
textureFilter = newTextureFilter;
maxAnisotropy = newMaxAnisotropy;
verticalSync = newVerticalSync;
depth = newDepth;
debugRenderer = newDebugRenderer;
clearColor = Color::BLACK;
previousFrameTime = std::chrono::steady_clock::now();
return true;
}
bool RenderDevice::process()
{
std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);
previousFrameTime = currentTime;
float delta = diff.count() / 1000000000.0f;
if (delta > 0.0f)
{
currentFPS = 1.0f / delta;
}
accumulatedTime += delta;
currentAccumulatedFPS += 1.0f;
if (accumulatedTime > 1.0f)
{
accumulatedFPS = currentAccumulatedFPS;
accumulatedTime = 0.0f;
currentAccumulatedFPS = 0.0f;
}
std::vector<DrawCommand> drawCommands;
{
#if OUZEL_MULTITHREADED
std::unique_lock<std::mutex> lock(drawQueueMutex);
while (!queueFinished)
{
queueCondition.wait(lock);
}
#endif
drawCommands = drawQueue;
drawQueue.clear();
queueFinished = false;
}
std::vector<std::unique_ptr<Resource>> deleteResources;
{
std::lock_guard<std::mutex> lock(resourceMutex);
deleteResources = std::move(resourceDeleteSet);
}
// refills the draw queue
refillQueue = true;
executeAll();
++currentFrame;
if (!draw(drawCommands))
{
return false;
}
deleteResources.clear(); // delete all resources in delete set
return true;
}
void RenderDevice::setClearColorBuffer(bool clear)
{
clearColorBuffer = clear;
}
void RenderDevice::setClearDepthBuffer(bool clear)
{
clearDepthBuffer = clear;
}
void RenderDevice::setClearColor(Color color)
{
clearColor = color;
}
void RenderDevice::setClearDepth(float newClearDepth)
{
clearDepth = newClearDepth;
}
void RenderDevice::setSize(const Size2& newSize)
{
size = newSize;
}
std::vector<Size2> RenderDevice::getSupportedResolutions() const
{
return std::vector<Size2>();
}
void RenderDevice::deleteResource(Resource* resource)
{
std::lock_guard<std::mutex> lock(resourceMutex);
auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<Resource>& ptr) {
return ptr.get() == resource;
});
if (resourceIterator != resources.end())
{
resourceDeleteSet.push_back(std::move(*resourceIterator));
resources.erase(resourceIterator);
}
}
bool RenderDevice::addDrawCommand(const DrawCommand& drawCommand)
{
std::lock_guard<std::mutex> lock(drawQueueMutex);
drawQueue.push_back(drawCommand);
return true;
}
void RenderDevice::flushCommands()
{
refillQueue = false;
{
std::lock_guard<std::mutex> lock(drawQueueMutex);
queueFinished = true;
drawCallCount = static_cast<uint32_t>(drawQueue.size());
}
#if OUZEL_MULTITHREADED
queueCondition.notify_one();
#endif
}
bool RenderDevice::generateScreenshot(const std::string&)
{
return true;
}
void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)
{
std::lock_guard<std::mutex> lock(executeMutex);
executeQueue.push(func);
}
void RenderDevice::executeAll()
{
std::function<void(void)> func;
for (;;)
{
{
std::lock_guard<std::mutex> lock(executeMutex);
if (executeQueue.empty())
{
break;
}
func = std::move(executeQueue.front());
executeQueue.pop();
}
if (func)
{
func();
}
}
}
} // namespace graphics
} // namespace ouzel
<|endoftext|> |
<commit_before>/*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* DummyPlugin.cpp
* The Dummy plugin for ola, contains a single dummy device
* Copyright (C) 2005-2007 Simon Newton
*/
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include "olad/PluginAdaptor.h"
#include "plugins/dummy/DummyDevice.h"
#include "plugins/dummy/DummyPlugin.h"
/*
* Entry point to this plugin
*/
extern "C" ola::AbstractPlugin* create(
const ola::PluginAdaptor *plugin_adaptor) {
return new ola::plugin::dummy::DummyPlugin(plugin_adaptor);
}
namespace ola {
namespace plugin {
namespace dummy {
using std::string;
const char DummyPlugin::PLUGIN_NAME[] = "Dummy";
const char DummyPlugin::PLUGIN_PREFIX[] = "dummy";
const char DummyPlugin::DEVICE_NAME[] = "Dummy Device";
/*
* Start the plugin
*
* Lets keep it simple, one device for this plugin
*/
bool DummyPlugin::StartHook() {
m_device = new DummyDevice(this, DEVICE_NAME);
m_device->Start();
m_plugin_adaptor->RegisterDevice(m_device);
return true;
}
/*
* Stop the plugin
* @return true on sucess, false on failure
*/
bool DummyPlugin::StopHook() {
if (m_device) {
m_plugin_adaptor->UnregisterDevice(m_device);
bool ret = m_device->Stop();
delete m_device;
return ret;
}
return true;
}
string DummyPlugin::Description() const {
return
"Dummy Plugin\n"
"----------------------------\n"
"\n"
"The plugin creates a single device with one port. "
"When used as an output port it prints the first two bytes of dmx data to "
"stdout.\n\n"
"It also emulates a simple RDM device which can be querried and the DMX\n"
"start address can be changed.\n";
}
} // dummy
} // plugin
} // ola
<commit_msg> * clean up the dummy docs<commit_after>/*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* DummyPlugin.cpp
* The Dummy plugin for ola, contains a single dummy device
* Copyright (C) 2005-2007 Simon Newton
*/
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include "olad/PluginAdaptor.h"
#include "plugins/dummy/DummyDevice.h"
#include "plugins/dummy/DummyPlugin.h"
/*
* Entry point to this plugin
*/
extern "C" ola::AbstractPlugin* create(
const ola::PluginAdaptor *plugin_adaptor) {
return new ola::plugin::dummy::DummyPlugin(plugin_adaptor);
}
namespace ola {
namespace plugin {
namespace dummy {
using std::string;
const char DummyPlugin::PLUGIN_NAME[] = "Dummy";
const char DummyPlugin::PLUGIN_PREFIX[] = "dummy";
const char DummyPlugin::DEVICE_NAME[] = "Dummy Device";
/*
* Start the plugin
*
* Lets keep it simple, one device for this plugin
*/
bool DummyPlugin::StartHook() {
m_device = new DummyDevice(this, DEVICE_NAME);
m_device->Start();
m_plugin_adaptor->RegisterDevice(m_device);
return true;
}
/*
* Stop the plugin
* @return true on sucess, false on failure
*/
bool DummyPlugin::StopHook() {
if (m_device) {
m_plugin_adaptor->UnregisterDevice(m_device);
bool ret = m_device->Stop();
delete m_device;
return ret;
}
return true;
}
string DummyPlugin::Description() const {
return
"Dummy Plugin\n"
"----------------------------\n"
"\n"
"The plugin creates a single device with one port. When used as an output\n"
"port it prints the first two bytes of dmx data to stdout.\n\n"
"It also creates a fake RDM device which can be querried and the DMX start\n"
"address can be changed.\n";
}
} // dummy
} // plugin
} // ola
<|endoftext|> |
<commit_before>//===--- Type.cpp - Swift Language Type ASTs ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Type class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Types.h"
#include "swift/AST/AST.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
// Only allow allocation of Stmts using the allocator in ASTContext.
void *TypeBase::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) throw() {
return C.Allocate(Bytes, Alignment);
}
//===----------------------------------------------------------------------===//
// Various Type Methods.
//===----------------------------------------------------------------------===//
/// isEqual - Return true if these two types are equal, ignoring sugar.
bool TypeBase::isEqual(Type Other) {
return getCanonicalType() == Other.getPointer()->getCanonicalType();
}
/// isMaterializable - Is this type 'materializable' according to the
/// rules of the language? Basically, does it not contain any l-value
/// types?
bool TypeBase::isMaterializable() {
if (TupleType *tuple = getAs<TupleType>()) {
for (auto &field : tuple->getFields())
if (!field.getType()->isMaterializable())
return false;
return true;
}
return !is<LValueType>();
}
/// getCanonicalType - Return the canonical version of this type, which has
/// sugar from all levels stripped off.
TypeBase *TypeBase::getCanonicalType() {
assert(this != 0 &&
"Cannot call getCanonicalType before name binding is complete");
// If the type is itself canonical, return it.
if (CanonicalType.is<ASTContext*>())
return this;
// If the canonical type was already computed, just return what we have.
if (TypeBase *CT = CanonicalType.get<TypeBase*>())
return CT;
// Otherwise, compute and cache it.
TypeBase *Result = 0;
switch (getKind()) {
#define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
#define UNCHECKED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("these types are always canonical");
#define SUGARED_TYPE(id, parent) \
case TypeKind::id: \
Result = cast<id##Type>(this)->getDesugaredType()->getCanonicalType(); \
break;
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Tuple: {
TupleType *TT = cast<TupleType>(this);
assert(!TT->getFields().empty() && "Empty tuples are always canonical");
SmallVector<TupleTypeElt, 8> CanElts;
CanElts.reserve(TT->getFields().size());
for (const TupleTypeElt &field : TT->getFields()) {
assert(!field.getType().isNull() &&
"Cannot get canonical type of un-typechecked TupleType!");
CanElts.push_back(TupleTypeElt(field.getType()->getCanonicalType(),
field.getName()));
}
Result = TupleType::get(CanElts, CanElts[0].getType()->getASTContext());
break;
}
case TypeKind::LValue: {
LValueType *lvalue = cast<LValueType>(this);
Type objectType = lvalue->getObjectType();
objectType = objectType->getCanonicalType();
Result = LValueType::get(objectType, lvalue->getQualifiers(),
objectType->getASTContext());
break;
}
case TypeKind::Function: {
FunctionType *FT = cast<FunctionType>(this);
Type In = FT->getInput()->getCanonicalType();
Type Out = FT->getResult()->getCanonicalType();
Result = FunctionType::get(In, Out, FT->isAutoClosure(),
In->getASTContext());
break;
}
case TypeKind::Array:
ArrayType *AT = cast<ArrayType>(this);
Type EltTy = AT->getBaseType()->getCanonicalType();
Result = ArrayType::get(EltTy, AT->getSize(), EltTy->getASTContext());
break;
}
// Cache the canonical type for future queries.
assert(Result && "Case not implemented!");
CanonicalType = Result;
return Result;
}
TypeBase *TypeBase::getDesugaredType() {
switch (getKind()) {
#define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
#define UNCHECKED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Tuple:
case TypeKind::Function:
case TypeKind::Array:
case TypeKind::LValue:
// None of these types have sugar at the outer level.
return this;
case TypeKind::Paren:
return cast<ParenType>(this)->getDesugaredType();
case TypeKind::Identifier:
return cast<IdentifierType>(this)->getDesugaredType();
case TypeKind::NameAlias:
return cast<NameAliasType>(this)->getDesugaredType();
}
llvm_unreachable("Unknown type kind");
}
TypeBase *ParenType::getDesugaredType() {
return getUnderlyingType()->getDesugaredType();
}
TypeBase *NameAliasType::getDesugaredType() {
return getDecl()->getUnderlyingType()->getDesugaredType();
}
TypeBase *IdentifierType::getDesugaredType() {
return getMappedType()->getDesugaredType();
}
const llvm::fltSemantics &BuiltinFloatType::getAPFloatSemantics() const {
switch (getFPKind()) {
case BuiltinFloatType::IEEE16: return APFloat::IEEEhalf;
case BuiltinFloatType::IEEE32: return APFloat::IEEEsingle;
case BuiltinFloatType::IEEE64: return APFloat::IEEEdouble;
case BuiltinFloatType::IEEE80: return APFloat::x87DoubleExtended;
case BuiltinFloatType::IEEE128: return APFloat::IEEEquad;
case BuiltinFloatType::PPC128: return APFloat::PPCDoubleDouble;
}
assert(0 && "Unknown FP semantics");
return APFloat::IEEEhalf;
}
Type IdentifierType::getMappedType() {
assert(!Components.back().Value.isNull() &&
"Name binding haven't resolved this to a type yet");
return Components.back().Value.get<TypeBase*>();
}
/// hasAnyDefaultValues - Return true if any of our elements has a default
/// value.
bool TupleType::hasAnyDefaultValues() const {
for (const TupleTypeElt &Elt : Fields)
if (Elt.hasInit())
return true;
return false;
}
/// getNamedElementId - If this tuple has a field with the specified name,
/// return the field index, otherwise return -1.
int TupleType::getNamedElementId(Identifier I) const {
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
if (Fields[i].getName() == I)
return i;
}
// Otherwise, name not found.
return -1;
}
/// getFieldForScalarInit - If a tuple of this type can be initialized with a
/// scalar, return the field number that the scalar is assigned to. If not,
/// return -1.
int TupleType::getFieldForScalarInit() const {
if (Fields.empty()) return -1;
int FieldWithoutDefault = -1;
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
// Ignore fields with a default value.
if (Fields[i].hasInit()) continue;
// If we already saw a field missing a default value, then we cannot assign
// a scalar to this tuple.
if (FieldWithoutDefault != -1)
return -1;
// Otherwise, remember this field number.
FieldWithoutDefault = i;
}
// If all the elements have default values, the scalar initializes the first
// value in the tuple.
return FieldWithoutDefault == -1 ? 0 : FieldWithoutDefault;
}
/// updateInitializedElementType - This methods updates the element type and
/// initializer for a non-canonical TupleType that has an initializer for the
/// specified element. This should only be used by TypeChecker.
void TupleType::updateInitializedElementType(unsigned EltNo, Type NewTy,
Expr *NewInit) {
assert(!hasCanonicalTypeComputed() &&
"Cannot munge an already canonicalized type!");
TupleTypeElt &Elt = const_cast<TupleTypeElt&>(Fields[EltNo]);
assert(Elt.hasInit() && "Can only update elements with default values");
Elt = TupleTypeElt(NewTy, Elt.getName(), NewInit);
}
OneOfElementDecl *OneOfType::getElement(Identifier Name) const {
// FIXME: Linear search is not great for large oneof decls.
for (OneOfElementDecl *Elt : Elements)
if (Elt->getName() == Name)
return Elt;
return 0;
}
bool OneOfType::isTransparentType() const {
return Elements.size() == 1 && !Elements[0]->getArgumentType().isNull();
}
Type OneOfType::getTransparentType() const {
assert(Elements.size() == 1);
assert(!Elements[0]->getArgumentType().isNull());
return Elements[0]->getArgumentType();
}
//===----------------------------------------------------------------------===//
// Type Printing
//===----------------------------------------------------------------------===//
void Type::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void Type::print(raw_ostream &OS) const {
if (isNull())
OS << "<null>";
else
Ptr->print(OS);
}
/// getString - Return the name of the type as a string, for use in
/// diagnostics only.
std::string Type::getString() const {
std::string Result;
llvm::raw_string_ostream OS(Result);
print(OS);
return OS.str();
}
/// getString - Return the name of the type as a string, for use in
/// diagnostics only.
std::string TypeBase::getString() const {
std::string Result;
llvm::raw_string_ostream OS(Result);
print(OS);
return OS.str();
}
void TypeBase::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void TypeBase::print(raw_ostream &OS) const {
switch (getKind()) {
#define TYPE(id, parent) \
case TypeKind::id: return cast<id##Type>(this)->print(OS);
#include "swift/AST/TypeNodes.def"
}
llvm_unreachable("bad type kind!");
}
void BuiltinIntegerType::print(raw_ostream &OS) const {
OS << "Builtin::int" << cast<BuiltinIntegerType>(this)->getBitWidth();
}
void BuiltinFloatType::print(raw_ostream &OS) const {
switch (getFPKind()) {
case IEEE16: OS << "Builtin::FP_IEEE16"; return;
case IEEE32: OS << "Builtin::FP_IEEE32"; return;
case IEEE64: OS << "Builtin::FP_IEEE64"; return;
case IEEE80: OS << "Builtin::FP_IEEE80"; return;
case IEEE128: OS << "Builtin::FP_IEEE128"; return;
case PPC128: OS << "Builtin::FP_PPC128"; return;
}
}
void ErrorType::print(raw_ostream &OS) const {
OS << "<<error type>>";
}
void DependentType::print(raw_ostream &OS) const {
OS << "<<dependent type>>";
}
void ParenType::print(raw_ostream &OS) const {
OS << '(';
UnderlyingType->print(OS);
OS << ')';
}
void NameAliasType::print(raw_ostream &OS) const {
OS << TheDecl->getName().get();
}
void IdentifierType::print(raw_ostream &OS) const {
OS << Components[0].Id.get();
for (const Component &C : Components.slice(1, Components.size()-1))
OS << '.' << C.Id.get();
}
void OneOfType::print(raw_ostream &OS) const {
OS << "oneof { ";
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
if (i) OS << ", ";
OS << Elements[i]->getName();
if (!Elements[i]->getArgumentType().isNull())
OS << " : " << Elements[i]->getArgumentType();
}
OS << '}';
}
void MetaTypeType::print(raw_ostream &OS) const {
OS << "metatype<" << TheType->getName() << '>';
}
void ModuleType::print(raw_ostream &OS) const {
OS << "module<" << TheModule->Name << '>';
}
void TupleType::print(raw_ostream &OS) const {
OS << "(";
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
if (i) OS << ", ";
const TupleTypeElt &TD = Fields[i];
if (TD.hasName())
OS << TD.getName() << " : ";
OS << TD.getType();
}
OS << ')';
}
void FunctionType::print(raw_ostream &OS) const {
if (isAutoClosure())
OS << "[auto_closure]";
OS << Input << " -> " << Result;
}
void ArrayType::print(raw_ostream &OS) const {
OS << Base << '[';
if (Size)
OS << Size;
OS << ']';
}
void ProtocolType::print(raw_ostream &OS) const {
OS << "protocol {";
for (Decl *D : Elements)
D->print(OS);
OS << '}';
}
void LValueType::print(raw_ostream &OS) const {
OS << "[byref";
Qual qs = getQualifiers();
if (qs & (Qual::Implicit)) {
OS << '(';
if (qs & Qual::Implicit) OS << "implicit";
OS << ')';
}
OS << "] ";
getObjectType()->print(OS);
}
<commit_msg>Fix pretty-printing of builtin types: we use . instead :: now.<commit_after>//===--- Type.cpp - Swift Language Type ASTs ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Type class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Types.h"
#include "swift/AST/AST.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
// Only allow allocation of Stmts using the allocator in ASTContext.
void *TypeBase::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) throw() {
return C.Allocate(Bytes, Alignment);
}
//===----------------------------------------------------------------------===//
// Various Type Methods.
//===----------------------------------------------------------------------===//
/// isEqual - Return true if these two types are equal, ignoring sugar.
bool TypeBase::isEqual(Type Other) {
return getCanonicalType() == Other.getPointer()->getCanonicalType();
}
/// isMaterializable - Is this type 'materializable' according to the
/// rules of the language? Basically, does it not contain any l-value
/// types?
bool TypeBase::isMaterializable() {
if (TupleType *tuple = getAs<TupleType>()) {
for (auto &field : tuple->getFields())
if (!field.getType()->isMaterializable())
return false;
return true;
}
return !is<LValueType>();
}
/// getCanonicalType - Return the canonical version of this type, which has
/// sugar from all levels stripped off.
TypeBase *TypeBase::getCanonicalType() {
assert(this != 0 &&
"Cannot call getCanonicalType before name binding is complete");
// If the type is itself canonical, return it.
if (CanonicalType.is<ASTContext*>())
return this;
// If the canonical type was already computed, just return what we have.
if (TypeBase *CT = CanonicalType.get<TypeBase*>())
return CT;
// Otherwise, compute and cache it.
TypeBase *Result = 0;
switch (getKind()) {
#define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
#define UNCHECKED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("these types are always canonical");
#define SUGARED_TYPE(id, parent) \
case TypeKind::id: \
Result = cast<id##Type>(this)->getDesugaredType()->getCanonicalType(); \
break;
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Tuple: {
TupleType *TT = cast<TupleType>(this);
assert(!TT->getFields().empty() && "Empty tuples are always canonical");
SmallVector<TupleTypeElt, 8> CanElts;
CanElts.reserve(TT->getFields().size());
for (const TupleTypeElt &field : TT->getFields()) {
assert(!field.getType().isNull() &&
"Cannot get canonical type of un-typechecked TupleType!");
CanElts.push_back(TupleTypeElt(field.getType()->getCanonicalType(),
field.getName()));
}
Result = TupleType::get(CanElts, CanElts[0].getType()->getASTContext());
break;
}
case TypeKind::LValue: {
LValueType *lvalue = cast<LValueType>(this);
Type objectType = lvalue->getObjectType();
objectType = objectType->getCanonicalType();
Result = LValueType::get(objectType, lvalue->getQualifiers(),
objectType->getASTContext());
break;
}
case TypeKind::Function: {
FunctionType *FT = cast<FunctionType>(this);
Type In = FT->getInput()->getCanonicalType();
Type Out = FT->getResult()->getCanonicalType();
Result = FunctionType::get(In, Out, FT->isAutoClosure(),
In->getASTContext());
break;
}
case TypeKind::Array:
ArrayType *AT = cast<ArrayType>(this);
Type EltTy = AT->getBaseType()->getCanonicalType();
Result = ArrayType::get(EltTy, AT->getSize(), EltTy->getASTContext());
break;
}
// Cache the canonical type for future queries.
assert(Result && "Case not implemented!");
CanonicalType = Result;
return Result;
}
TypeBase *TypeBase::getDesugaredType() {
switch (getKind()) {
#define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
#define UNCHECKED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Tuple:
case TypeKind::Function:
case TypeKind::Array:
case TypeKind::LValue:
// None of these types have sugar at the outer level.
return this;
case TypeKind::Paren:
return cast<ParenType>(this)->getDesugaredType();
case TypeKind::Identifier:
return cast<IdentifierType>(this)->getDesugaredType();
case TypeKind::NameAlias:
return cast<NameAliasType>(this)->getDesugaredType();
}
llvm_unreachable("Unknown type kind");
}
TypeBase *ParenType::getDesugaredType() {
return getUnderlyingType()->getDesugaredType();
}
TypeBase *NameAliasType::getDesugaredType() {
return getDecl()->getUnderlyingType()->getDesugaredType();
}
TypeBase *IdentifierType::getDesugaredType() {
return getMappedType()->getDesugaredType();
}
const llvm::fltSemantics &BuiltinFloatType::getAPFloatSemantics() const {
switch (getFPKind()) {
case BuiltinFloatType::IEEE16: return APFloat::IEEEhalf;
case BuiltinFloatType::IEEE32: return APFloat::IEEEsingle;
case BuiltinFloatType::IEEE64: return APFloat::IEEEdouble;
case BuiltinFloatType::IEEE80: return APFloat::x87DoubleExtended;
case BuiltinFloatType::IEEE128: return APFloat::IEEEquad;
case BuiltinFloatType::PPC128: return APFloat::PPCDoubleDouble;
}
assert(0 && "Unknown FP semantics");
return APFloat::IEEEhalf;
}
Type IdentifierType::getMappedType() {
assert(!Components.back().Value.isNull() &&
"Name binding haven't resolved this to a type yet");
return Components.back().Value.get<TypeBase*>();
}
/// hasAnyDefaultValues - Return true if any of our elements has a default
/// value.
bool TupleType::hasAnyDefaultValues() const {
for (const TupleTypeElt &Elt : Fields)
if (Elt.hasInit())
return true;
return false;
}
/// getNamedElementId - If this tuple has a field with the specified name,
/// return the field index, otherwise return -1.
int TupleType::getNamedElementId(Identifier I) const {
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
if (Fields[i].getName() == I)
return i;
}
// Otherwise, name not found.
return -1;
}
/// getFieldForScalarInit - If a tuple of this type can be initialized with a
/// scalar, return the field number that the scalar is assigned to. If not,
/// return -1.
int TupleType::getFieldForScalarInit() const {
if (Fields.empty()) return -1;
int FieldWithoutDefault = -1;
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
// Ignore fields with a default value.
if (Fields[i].hasInit()) continue;
// If we already saw a field missing a default value, then we cannot assign
// a scalar to this tuple.
if (FieldWithoutDefault != -1)
return -1;
// Otherwise, remember this field number.
FieldWithoutDefault = i;
}
// If all the elements have default values, the scalar initializes the first
// value in the tuple.
return FieldWithoutDefault == -1 ? 0 : FieldWithoutDefault;
}
/// updateInitializedElementType - This methods updates the element type and
/// initializer for a non-canonical TupleType that has an initializer for the
/// specified element. This should only be used by TypeChecker.
void TupleType::updateInitializedElementType(unsigned EltNo, Type NewTy,
Expr *NewInit) {
assert(!hasCanonicalTypeComputed() &&
"Cannot munge an already canonicalized type!");
TupleTypeElt &Elt = const_cast<TupleTypeElt&>(Fields[EltNo]);
assert(Elt.hasInit() && "Can only update elements with default values");
Elt = TupleTypeElt(NewTy, Elt.getName(), NewInit);
}
OneOfElementDecl *OneOfType::getElement(Identifier Name) const {
// FIXME: Linear search is not great for large oneof decls.
for (OneOfElementDecl *Elt : Elements)
if (Elt->getName() == Name)
return Elt;
return 0;
}
bool OneOfType::isTransparentType() const {
return Elements.size() == 1 && !Elements[0]->getArgumentType().isNull();
}
Type OneOfType::getTransparentType() const {
assert(Elements.size() == 1);
assert(!Elements[0]->getArgumentType().isNull());
return Elements[0]->getArgumentType();
}
//===----------------------------------------------------------------------===//
// Type Printing
//===----------------------------------------------------------------------===//
void Type::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void Type::print(raw_ostream &OS) const {
if (isNull())
OS << "<null>";
else
Ptr->print(OS);
}
/// getString - Return the name of the type as a string, for use in
/// diagnostics only.
std::string Type::getString() const {
std::string Result;
llvm::raw_string_ostream OS(Result);
print(OS);
return OS.str();
}
/// getString - Return the name of the type as a string, for use in
/// diagnostics only.
std::string TypeBase::getString() const {
std::string Result;
llvm::raw_string_ostream OS(Result);
print(OS);
return OS.str();
}
void TypeBase::dump() const {
print(llvm::errs());
llvm::errs() << '\n';
}
void TypeBase::print(raw_ostream &OS) const {
switch (getKind()) {
#define TYPE(id, parent) \
case TypeKind::id: return cast<id##Type>(this)->print(OS);
#include "swift/AST/TypeNodes.def"
}
llvm_unreachable("bad type kind!");
}
void BuiltinIntegerType::print(raw_ostream &OS) const {
OS << "Builtin.int" << cast<BuiltinIntegerType>(this)->getBitWidth();
}
void BuiltinFloatType::print(raw_ostream &OS) const {
switch (getFPKind()) {
case IEEE16: OS << "Builtin.FP_IEEE16"; return;
case IEEE32: OS << "Builtin.FP_IEEE32"; return;
case IEEE64: OS << "Builtin.FP_IEEE64"; return;
case IEEE80: OS << "Builtin.FP_IEEE80"; return;
case IEEE128: OS << "Builtin.FP_IEEE128"; return;
case PPC128: OS << "Builtin.FP_PPC128"; return;
}
}
void ErrorType::print(raw_ostream &OS) const {
OS << "<<error type>>";
}
void DependentType::print(raw_ostream &OS) const {
OS << "<<dependent type>>";
}
void ParenType::print(raw_ostream &OS) const {
OS << '(';
UnderlyingType->print(OS);
OS << ')';
}
void NameAliasType::print(raw_ostream &OS) const {
OS << TheDecl->getName().get();
}
void IdentifierType::print(raw_ostream &OS) const {
OS << Components[0].Id.get();
for (const Component &C : Components.slice(1, Components.size()-1))
OS << '.' << C.Id.get();
}
void OneOfType::print(raw_ostream &OS) const {
OS << "oneof { ";
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
if (i) OS << ", ";
OS << Elements[i]->getName();
if (!Elements[i]->getArgumentType().isNull())
OS << " : " << Elements[i]->getArgumentType();
}
OS << '}';
}
void MetaTypeType::print(raw_ostream &OS) const {
OS << "metatype<" << TheType->getName() << '>';
}
void ModuleType::print(raw_ostream &OS) const {
OS << "module<" << TheModule->Name << '>';
}
void TupleType::print(raw_ostream &OS) const {
OS << "(";
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
if (i) OS << ", ";
const TupleTypeElt &TD = Fields[i];
if (TD.hasName())
OS << TD.getName() << " : ";
OS << TD.getType();
}
OS << ')';
}
void FunctionType::print(raw_ostream &OS) const {
if (isAutoClosure())
OS << "[auto_closure]";
OS << Input << " -> " << Result;
}
void ArrayType::print(raw_ostream &OS) const {
OS << Base << '[';
if (Size)
OS << Size;
OS << ']';
}
void ProtocolType::print(raw_ostream &OS) const {
OS << "protocol {";
for (Decl *D : Elements)
D->print(OS);
OS << '}';
}
void LValueType::print(raw_ostream &OS) const {
OS << "[byref";
Qual qs = getQualifiers();
if (qs & (Qual::Implicit)) {
OS << '(';
if (qs & Qual::Implicit) OS << "implicit";
OS << ')';
}
OS << "] ";
getObjectType()->print(OS);
}
<|endoftext|> |
<commit_before>
#include "Uniform.h"
#include "Utilities.h"
#include <ionMath.h>
#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>
namespace ion
{
namespace GL
{
template <>
void Uniform::Bind<float>(uint const Handle, float const & Value)
{
CheckedGLCall(glUniform1f(Handle, Value));
}
template <>
void Uniform::Bind<int>(uint const Handle, int const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value));
}
template <>
void Uniform::Bind<uint>(uint const Handle, uint const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value));
}
template <>
void Uniform::Bind<glm::mat4>(uint const Handle, glm::mat4 const & Value)
{
CheckedGLCall(glUniformMatrix4fv(Handle, 1, GL_FALSE, glm::value_ptr(Value)));
}
template <>
void Uniform::Bind<vec2f>(uint const Handle, vec2f const & Value)
{
CheckedGLCall(glUniform2f(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3f>(uint const Handle, vec3f const & Value)
{
CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4f>(uint const Handle, vec4f const & Value)
{
CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<color3f>(uint const Handle, color3f const & Value)
{
CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<color4f>(uint const Handle, color4f const & Value)
{
CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<vec2i>(uint const Handle, vec2i const & Value)
{
CheckedGLCall(glUniform2i(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3i>(uint const Handle, vec3i const & Value)
{
CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4i>(uint const Handle, vec4i const & Value)
{
CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<color3i>(uint const Handle, color3i const & Value)
{
CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<color4i>(uint const Handle, color4i const & Value)
{
CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<vec2u>(uint const Handle, vec2u const & Value)
{
CheckedGLCall(glUniform2ui(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3u>(uint const Handle, vec3u const & Value)
{
CheckedGLCall(glUniform3ui(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4u>(uint const Handle, vec4u const & Value)
{
CheckedGLCall(glUniform4ui(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<bool>(uint const Handle, bool const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value ? 1 : 0));
}
template <>
void Uniform::Bind<vector<glm::mat4>>(uint const Handle, vector<glm::mat4> const & Value)
{
static vector<float> Temp;
for (auto Mat : Value)
{
auto ValuePtr = glm::value_ptr(Mat);
for (int i = 0; i < 16; ++ i)
Temp.push_back(((float *) ValuePtr)[i]);
}
CheckedGLCall(glUniformMatrix4fv(Handle, (int) Value.size(), GL_FALSE, Temp.data()));
}
template <>
void Uniform::Bind<vector<glm::mat4 *>>(uint const Handle, vector<glm::mat4 *> const & Value)
{
static vector<float> Temp;
for (auto Mat : Value)
{
auto ValuePtr = glm::value_ptr(* Mat);
for (int i = 0; i < 16; ++ i)
Temp.push_back(((float *) ValuePtr)[i]);
}
CheckedGLCall(glUniformMatrix4fv(Handle, (int) Value.size(), GL_FALSE, Temp.data()));
}
}
}
<commit_msg>Fix issue with matrix array upload<commit_after>
#include "Uniform.h"
#include "Utilities.h"
#include <ionMath.h>
#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>
namespace ion
{
namespace GL
{
template <>
void Uniform::Bind<float>(uint const Handle, float const & Value)
{
CheckedGLCall(glUniform1f(Handle, Value));
}
template <>
void Uniform::Bind<int>(uint const Handle, int const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value));
}
template <>
void Uniform::Bind<uint>(uint const Handle, uint const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value));
}
template <>
void Uniform::Bind<glm::mat4>(uint const Handle, glm::mat4 const & Value)
{
CheckedGLCall(glUniformMatrix4fv(Handle, 1, GL_FALSE, glm::value_ptr(Value)));
}
template <>
void Uniform::Bind<vec2f>(uint const Handle, vec2f const & Value)
{
CheckedGLCall(glUniform2f(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3f>(uint const Handle, vec3f const & Value)
{
CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4f>(uint const Handle, vec4f const & Value)
{
CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<color3f>(uint const Handle, color3f const & Value)
{
CheckedGLCall(glUniform3f(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<color4f>(uint const Handle, color4f const & Value)
{
CheckedGLCall(glUniform4f(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<vec2i>(uint const Handle, vec2i const & Value)
{
CheckedGLCall(glUniform2i(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3i>(uint const Handle, vec3i const & Value)
{
CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4i>(uint const Handle, vec4i const & Value)
{
CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<color3i>(uint const Handle, color3i const & Value)
{
CheckedGLCall(glUniform3i(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<color4i>(uint const Handle, color4i const & Value)
{
CheckedGLCall(glUniform4i(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<vec2u>(uint const Handle, vec2u const & Value)
{
CheckedGLCall(glUniform2ui(Handle, Value[0], Value[1]));
}
template <>
void Uniform::Bind<vec3u>(uint const Handle, vec3u const & Value)
{
CheckedGLCall(glUniform3ui(Handle, Value[0], Value[1], Value[2]));
}
template <>
void Uniform::Bind<vec4u>(uint const Handle, vec4u const & Value)
{
CheckedGLCall(glUniform4ui(Handle, Value[0], Value[1], Value[2], Value[3]));
}
template <>
void Uniform::Bind<bool>(uint const Handle, bool const & Value)
{
CheckedGLCall(glUniform1i(Handle, Value ? 1 : 0));
}
template <>
void Uniform::Bind<vector<glm::mat4>>(uint const Handle, vector<glm::mat4> const & Value)
{
static vector<float> Temp;
for (auto Mat : Value)
{
auto ValuePtr = glm::value_ptr(Mat);
for (int i = 0; i < 16; ++ i)
Temp.push_back(((float *) ValuePtr)[i]);
}
CheckedGLCall(glUniformMatrix4fv(Handle, (int) Value.size(), GL_FALSE, Temp.data()));
Temp.clear();
}
template <>
void Uniform::Bind<vector<glm::mat4 *>>(uint const Handle, vector<glm::mat4 *> const & Value)
{
static vector<float> Temp;
for (auto Mat : Value)
{
auto ValuePtr = glm::value_ptr(* Mat);
for (int i = 0; i < 16; ++ i)
Temp.push_back(((float *) ValuePtr)[i]);
}
CheckedGLCall(glUniformMatrix4fv(Handle, (int) Value.size(), GL_FALSE, Temp.data()));
Temp.clear();
}
}
}
<|endoftext|> |
<commit_before>#include "base/logging.h"
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif
#if defined(USING_GLES2)
#if defined(ANDROID)
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLMAPBUFFERPROC glMapBuffer;
#endif
#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)
PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif
OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;
int OpenGLState::state_count = 0;
void OpenGLState::Initialize() {
if(initialized) return;
Restore();
initialized = true;
}
void OpenGLState::Restore() {
int count = 0;
blend.restore(); count++;
blendEquation.restore(); count++;
blendFuncSeparate.restore(); count++;
blendColor.restore(); count++;
#if !defined(USING_GLES2)
colorLogicOp.restore(); count++;
logicOp.restore(); count++;
#endif
#ifdef ANDROID
if (gl_extensions.QCOM_alpha_test) {
alphaTestQCOM.restore(); count++;
alphaFuncQCOM.restore(); count++;
}
#endif
scissorTest.restore(); count++;
scissorRect.restore(); count++;
cullFace.restore(); count++;
cullFaceMode.restore(); count++;
frontFace.restore(); count++;
depthTest.restore(); count++;
depthRange.restore(); count++;
depthFunc.restore(); count++;
depthWrite.restore(); count++;
colorMask.restore(); count++;
viewport.restore(); count++;
stencilTest.restore(); count++;
stencilOp.restore(); count++;
stencilFunc.restore(); count++;
dither.restore(); count++;
if (count != state_count) {
FLOG("OpenGLState::Restore is missing some states");
}
}
// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array
void CheckGLExtensions() {
static bool done = false;
if (done)
return;
done = true;
memset(&gl_extensions, 0, sizeof(gl_extensions));
const char *extString = (const char *)glGetString(GL_EXTENSIONS);
if (extString) {
g_all_gl_extensions = extString;
} else {
g_all_gl_extensions = "";
}
#ifdef WIN32
const char *wglString = wglGetExtensionsStringEXT();
if (wglString) {
gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
g_all_egl_extensions = wglString;
} else {
g_all_egl_extensions = "";
}
#elif !defined(USING_GLES2)
// const char *glXString = glXQueryExtensionString();
// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif
#ifdef USING_GLES2
gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)
gl_extensions.OES_vertex_array_object = false;
gl_extensions.EXT_discard_framebuffer = false;
#else
gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
if (gl_extensions.OES_vertex_array_object) {
glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
}
gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
if (gl_extensions.EXT_discard_framebuffer) {
glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
}
#endif
#endif
#ifdef ANDROID
if (gl_extensions.OES_mapbuffer) {
glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
}
gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
// Load extensions that are not auto-loaded by Android.
if (gl_extensions.QCOM_alpha_test) {
glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
}
// Look for EGL extensions
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
if (eglString) {
g_all_egl_extensions = eglString;
gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;
if (gl_extensions.EGL_NV_system_time) {
eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
}
} else {
g_all_egl_extensions = "";
}
#endif
#ifdef USING_GLES2
gl_extensions.FBO_ARB = true;
gl_extensions.FBO_EXT = false;
#else
gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
#endif
}
void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
if( wglSwapIntervalEXT )
wglSwapIntervalEXT(interval);
#endif
}
<commit_msg>Add gl_extensions.QCOM_binning_control<commit_after>#include "base/logging.h"
#include "gl_state.h"
#ifdef _WIN32
#include "GL/wglew.h"
#endif
#if defined(USING_GLES2)
#if defined(ANDROID)
PFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;
PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;
PFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;
PFNGLMAPBUFFERPROC glMapBuffer;
#endif
#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)
PFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;
PFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;
#endif
#endif
OpenGLState glstate;
GLExtensions gl_extensions;
std::string g_all_gl_extensions;
std::string g_all_egl_extensions;
int OpenGLState::state_count = 0;
void OpenGLState::Initialize() {
if(initialized) return;
Restore();
initialized = true;
}
void OpenGLState::Restore() {
int count = 0;
blend.restore(); count++;
blendEquation.restore(); count++;
blendFuncSeparate.restore(); count++;
blendColor.restore(); count++;
#if !defined(USING_GLES2)
colorLogicOp.restore(); count++;
logicOp.restore(); count++;
#endif
#ifdef ANDROID
if (gl_extensions.QCOM_alpha_test) {
alphaTestQCOM.restore(); count++;
alphaFuncQCOM.restore(); count++;
}
#endif
scissorTest.restore(); count++;
scissorRect.restore(); count++;
cullFace.restore(); count++;
cullFaceMode.restore(); count++;
frontFace.restore(); count++;
depthTest.restore(); count++;
depthRange.restore(); count++;
depthFunc.restore(); count++;
depthWrite.restore(); count++;
colorMask.restore(); count++;
viewport.restore(); count++;
stencilTest.restore(); count++;
stencilOp.restore(); count++;
stencilFunc.restore(); count++;
dither.restore(); count++;
if (count != state_count) {
FLOG("OpenGLState::Restore is missing some states");
}
}
// http://stackoverflow.com/questions/16147700/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array
void CheckGLExtensions() {
static bool done = false;
if (done)
return;
done = true;
memset(&gl_extensions, 0, sizeof(gl_extensions));
const char *extString = (const char *)glGetString(GL_EXTENSIONS);
if (extString) {
g_all_gl_extensions = extString;
} else {
g_all_gl_extensions = "";
}
#ifdef WIN32
const char *wglString = wglGetExtensionsStringEXT();
if (wglString) {
gl_extensions.EXT_swap_control_tear = strstr(wglString, "WGL_EXT_swap_control_tear") != 0;
g_all_egl_extensions = wglString;
} else {
g_all_egl_extensions = "";
}
#elif !defined(USING_GLES2)
// const char *glXString = glXQueryExtensionString();
// gl_extensions.EXT_swap_control_tear = strstr(glXString, "GLX_EXT_swap_control_tear") != 0;
#endif
#ifdef USING_GLES2
gl_extensions.OES_packed_depth_stencil = strstr(extString, "GL_OES_packed_depth_stencil") != 0;
gl_extensions.OES_depth24 = strstr(extString, "GL_OES_depth24") != 0;
gl_extensions.OES_depth_texture = strstr(extString, "GL_OES_depth_texture") != 0;
gl_extensions.OES_mapbuffer = strstr(extString, "GL_OES_mapbuffer") != 0;
#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)
gl_extensions.OES_vertex_array_object = false;
gl_extensions.EXT_discard_framebuffer = false;
#else
gl_extensions.OES_vertex_array_object = strstr(extString, "GL_OES_vertex_array_object") != 0;
if (gl_extensions.OES_vertex_array_object) {
glGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( "glGenVertexArraysOES" );
glBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( "glBindVertexArrayOES" );
glDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( "glDeleteVertexArraysOES" );
glIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( "glIsVertexArrayOES" );
}
gl_extensions.EXT_discard_framebuffer = strstr(extString, "GL_EXT_discard_framebuffer") != 0;
if (gl_extensions.EXT_discard_framebuffer) {
glDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress("glDiscardFramebufferEXT");
}
#endif
#endif
#ifdef ANDROID
if (gl_extensions.OES_mapbuffer) {
glMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( "glMapBufferOES" );
}
gl_extensions.QCOM_binning_control = strstr(extString, "GL_QCOM_binning_control") != 0;
gl_extensions.QCOM_alpha_test = strstr(extString, "GL_QCOM_alpha_test") != 0;
// Load extensions that are not auto-loaded by Android.
if (gl_extensions.QCOM_alpha_test) {
glAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress("glAlphaFuncQCOM");
}
// Look for EGL extensions
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
const char *eglString = eglQueryString(display, EGL_EXTENSIONS);
if (eglString) {
g_all_egl_extensions = eglString;
gl_extensions.EGL_NV_system_time = strstr(eglString, "EGL_NV_system_time") != 0;
gl_extensions.EGL_NV_coverage_sample = strstr(eglString, "EGL_NV_coverage_sample") != 0;
if (gl_extensions.EGL_NV_system_time) {
eglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress("eglGetSystemTimeNV");
eglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress("eglGetSystemTimeFrequencyNV");
}
} else {
g_all_egl_extensions = "";
}
#endif
#ifdef USING_GLES2
gl_extensions.FBO_ARB = true;
gl_extensions.FBO_EXT = false;
#else
gl_extensions.FBO_ARB = strstr(extString, "GL_ARB_framebuffer_object") != 0;
gl_extensions.FBO_EXT = strstr(extString, "GL_EXT_framebuffer_object") != 0;
#endif
}
void OpenGLState::SetVSyncInterval(int interval) {
#ifdef _WIN32
if( wglSwapIntervalEXT )
wglSwapIntervalEXT(interval);
#endif
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <utility>
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/util/batch_util.h"
namespace tensorflow {
namespace data {
namespace experimental {
namespace {
class UnbatchDatasetOp : public UnaryDatasetOpKernel {
public:
explicit UnbatchDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) override {
*output = new Dataset(ctx, input);
}
private:
class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, DatasetBase* input)
: DatasetBase(DatasetContext(ctx)), input_(input) {
input_->Ref();
batch_size_ = -1;
for (const PartialTensorShape& shape : input->output_shapes()) {
if (!shape.unknown_rank()) {
if (batch_size_ < 0 && shape.dim_size(0) >= 0) {
batch_size_ = shape.dim_size(0);
}
gtl::InlinedVector<int64_t, 4> partial_dim_sizes;
for (int i = 1; i < shape.dims(); ++i) {
partial_dim_sizes.push_back(shape.dim_size(i));
}
shapes_.emplace_back(std::move(partial_dim_sizes));
} else {
// If the input shape is unknown, the output shape will be unknown.
shapes_.emplace_back();
}
}
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(
Iterator::Params{this, strings::StrCat(prefix, "::Unbatch")});
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return shapes_;
}
string DebugString() const override { return "UnbatchDatasetOp::Dataset"; }
int64_t Cardinality() const override {
int64_t n = input_->Cardinality();
if (n == kInfiniteCardinality || n == kUnknownCardinality) {
return n;
}
if (batch_size_ > 0) {
return n * batch_size_;
}
return kUnknownCardinality;
}
Status InputDatasets(
std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return Status::OK();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
current_index_(0),
current_batch_size_(0),
shapes_(params.dataset->output_shapes().size()) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, this, prefix(),
&input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return Status::OK();
}
*end_of_sequence = false;
while (!*end_of_sequence) {
if (current_index_ < current_batch_size_) {
out_tensors->clear();
out_tensors->reserve(tensors_.size());
for (int i = 0; i < tensors_.size(); ++i) {
out_tensors->push_back(
MaybeCopySubSlice(tensors_[i], current_index_));
}
++current_index_;
*end_of_sequence = false;
return Status::OK();
}
current_index_ = 0;
current_batch_size_ = 0;
tensors_.clear();
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, &tensors_, end_of_sequence));
if (!*end_of_sequence) {
for (size_t i = 0; i < tensors_.size(); ++i) {
if (tensors_[i].dims() == 0) {
return errors::InvalidArgument(
"Input element must have a non-scalar value in each "
"component.");
}
if (tensors_[i].dim_size(0) != tensors_[0].dim_size(0)) {
return errors::InvalidArgument(
"Input element must have the same batch size in each "
"component. Component 0 had size ",
tensors_[0].dim_size(0), " but component ", i,
" had size, ", tensors_[i].dim_size(0), ".");
}
shapes_[i] = tensors_[i].shape();
shapes_[i].RemoveDim(0);
}
current_batch_size_ = tensors_[0].dim_size(0);
}
}
input_impl_.reset();
return Status::OK();
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
// Unbatch assumes that all input components have the same leading
// dimension. If it is statically known for any component, we model the
// transformation using `KnownRatio`. Otherwise, we use `UnknownRatio`.
for (auto& shape : dataset()->input_->output_shapes()) {
if (shape.dims() > 0 && shape.dim_size(0) > 0) {
return model::MakeKnownRatioNode(
std::move(args), 1.0 / static_cast<double>(shape.dim_size(0)));
}
}
return model::MakeUnknownRatioNode(std::move(args));
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
}
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("current_index"), current_index_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("n"), current_batch_size_));
if (current_index_ < current_batch_size_) {
for (size_t i = 0; i < tensors_.size(); ++i) {
TF_RETURN_IF_ERROR(writer->WriteTensor(
full_name(strings::StrCat("tensors[", i, "]")), tensors_[i]));
}
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("current_index"), ¤t_index_));
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("n"), ¤t_batch_size_));
tensors_.clear();
tensors_.resize(dataset()->output_dtypes().size());
if (current_index_ < current_batch_size_) {
for (size_t i = 0; i < tensors_.size(); ++i) {
TF_RETURN_IF_ERROR(reader->ReadTensor(
ctx->flr(), full_name(strings::StrCat("tensors[", i, "]")),
&tensors_[i]));
shapes_[i] = tensors_[i].shape();
shapes_[i].RemoveDim(0);
}
}
return Status::OK();
}
private:
mutex mu_;
int64_t current_index_ TF_GUARDED_BY(mu_);
int64_t current_batch_size_ TF_GUARDED_BY(mu_);
std::vector<Tensor> tensors_ TF_GUARDED_BY(mu_);
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
std::vector<TensorShape> shapes_ TF_GUARDED_BY(mu_);
};
const DatasetBase* const input_;
std::vector<PartialTensorShape> shapes_;
// batch_size_ may or may not be known, with -1 as unknown
int64_t batch_size_;
};
};
REGISTER_KERNEL_BUILDER(Name("UnbatchDataset").Device(DEVICE_CPU),
UnbatchDatasetOp);
REGISTER_KERNEL_BUILDER(Name("ExperimentalUnbatchDataset").Device(DEVICE_CPU),
UnbatchDatasetOp);
} // namespace
} // namespace experimental
} // namespace data
} // namespace tensorflow
<commit_msg>Undo cl/380581935 in unbatch() to fix memory leak<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <utility>
#include "tensorflow/core/data/dataset_utils.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/util/batch_util.h"
namespace tensorflow {
namespace data {
namespace experimental {
namespace {
class UnbatchDatasetOp : public UnaryDatasetOpKernel {
public:
explicit UnbatchDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) override {
*output = new Dataset(ctx, input);
}
private:
class Dataset : public DatasetBase {
public:
explicit Dataset(OpKernelContext* ctx, DatasetBase* input)
: DatasetBase(DatasetContext(ctx)), input_(input) {
input_->Ref();
batch_size_ = -1;
for (const PartialTensorShape& shape : input->output_shapes()) {
if (!shape.unknown_rank()) {
if (batch_size_ < 0 && shape.dim_size(0) >= 0) {
batch_size_ = shape.dim_size(0);
}
gtl::InlinedVector<int64_t, 4> partial_dim_sizes;
for (int i = 1; i < shape.dims(); ++i) {
partial_dim_sizes.push_back(shape.dim_size(i));
}
shapes_.emplace_back(std::move(partial_dim_sizes));
} else {
// If the input shape is unknown, the output shape will be unknown.
shapes_.emplace_back();
}
}
}
~Dataset() override { input_->Unref(); }
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(
Iterator::Params{this, strings::StrCat(prefix, "::Unbatch")});
}
const DataTypeVector& output_dtypes() const override {
return input_->output_dtypes();
}
const std::vector<PartialTensorShape>& output_shapes() const override {
return shapes_;
}
string DebugString() const override { return "UnbatchDatasetOp::Dataset"; }
int64_t Cardinality() const override {
int64_t n = input_->Cardinality();
if (n == kInfiniteCardinality || n == kUnknownCardinality) {
return n;
}
if (batch_size_ > 0) {
return n * batch_size_;
}
return kUnknownCardinality;
}
Status InputDatasets(
std::vector<const DatasetBase*>* inputs) const override {
inputs->push_back(input_);
return Status::OK();
}
Status CheckExternalState() const override {
return input_->CheckExternalState();
}
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
Node* input_graph_node = nullptr;
TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node));
TF_RETURN_IF_ERROR(b->AddDataset(this, {input_graph_node}, output));
return Status::OK();
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params),
current_index_(0),
current_batch_size_(0),
shapes_(params.dataset->output_shapes().size()) {}
Status Initialize(IteratorContext* ctx) override {
return dataset()->input_->MakeIterator(ctx, this, prefix(),
&input_impl_);
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (!input_impl_) {
*end_of_sequence = true;
return Status::OK();
}
*end_of_sequence = false;
while (!*end_of_sequence) {
if (current_index_ < current_batch_size_) {
out_tensors->clear();
out_tensors->reserve(tensors_.size());
for (int i = 0; i < tensors_.size(); ++i) {
// TODO(b/201790899): Investigate why using MaybeCopySubSlice
// may lead to a memory leak.
out_tensors->emplace_back(ctx->allocator({}), tensors_[i].dtype(),
shapes_[i]);
TF_RETURN_IF_ERROR(batch_util::MaybeMoveSliceToElement(
&tensors_[i], &out_tensors->back(), current_index_));
}
++current_index_;
*end_of_sequence = false;
return Status::OK();
}
current_index_ = 0;
current_batch_size_ = 0;
tensors_.clear();
TF_RETURN_IF_ERROR(
input_impl_->GetNext(ctx, &tensors_, end_of_sequence));
if (!*end_of_sequence) {
for (size_t i = 0; i < tensors_.size(); ++i) {
if (tensors_[i].dims() == 0) {
return errors::InvalidArgument(
"Input element must have a non-scalar value in each "
"component.");
}
if (tensors_[i].dim_size(0) != tensors_[0].dim_size(0)) {
return errors::InvalidArgument(
"Input element must have the same batch size in each "
"component. Component 0 had size ",
tensors_[0].dim_size(0), " but component ", i,
" had size, ", tensors_[i].dim_size(0), ".");
}
shapes_[i] = tensors_[i].shape();
shapes_[i].RemoveDim(0);
}
current_batch_size_ = tensors_[0].dim_size(0);
}
}
input_impl_.reset();
return Status::OK();
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
// Unbatch assumes that all input components have the same leading
// dimension. If it is statically known for any component, we model the
// transformation using `KnownRatio`. Otherwise, we use `UnknownRatio`.
for (auto& shape : dataset()->input_->output_shapes()) {
if (shape.dims() > 0 && shape.dim_size(0) > 0) {
return model::MakeKnownRatioNode(
std::move(args), 1.0 / static_cast<double>(shape.dim_size(0)));
}
}
return model::MakeUnknownRatioNode(std::move(args));
}
Status SaveInternal(SerializationContext* ctx,
IteratorStateWriter* writer) override {
mutex_lock l(mu_);
if (input_impl_) {
TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));
} else {
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("input_impl_empty"), ""));
}
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("current_index"), current_index_));
TF_RETURN_IF_ERROR(
writer->WriteScalar(full_name("n"), current_batch_size_));
if (current_index_ < current_batch_size_) {
for (size_t i = 0; i < tensors_.size(); ++i) {
TF_RETURN_IF_ERROR(writer->WriteTensor(
full_name(strings::StrCat("tensors[", i, "]")), tensors_[i]));
}
}
return Status::OK();
}
Status RestoreInternal(IteratorContext* ctx,
IteratorStateReader* reader) override {
mutex_lock l(mu_);
if (!reader->Contains(full_name("input_impl_empty"))) {
TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_));
} else {
input_impl_.reset();
}
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("current_index"), ¤t_index_));
TF_RETURN_IF_ERROR(
reader->ReadScalar(full_name("n"), ¤t_batch_size_));
tensors_.clear();
tensors_.resize(dataset()->output_dtypes().size());
if (current_index_ < current_batch_size_) {
for (size_t i = 0; i < tensors_.size(); ++i) {
TF_RETURN_IF_ERROR(reader->ReadTensor(
ctx->flr(), full_name(strings::StrCat("tensors[", i, "]")),
&tensors_[i]));
shapes_[i] = tensors_[i].shape();
shapes_[i].RemoveDim(0);
}
}
return Status::OK();
}
private:
mutex mu_;
int64_t current_index_ TF_GUARDED_BY(mu_);
int64_t current_batch_size_ TF_GUARDED_BY(mu_);
std::vector<Tensor> tensors_ TF_GUARDED_BY(mu_);
std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_);
std::vector<TensorShape> shapes_ TF_GUARDED_BY(mu_);
};
const DatasetBase* const input_;
std::vector<PartialTensorShape> shapes_;
// batch_size_ may or may not be known, with -1 as unknown
int64_t batch_size_;
};
};
REGISTER_KERNEL_BUILDER(Name("UnbatchDataset").Device(DEVICE_CPU),
UnbatchDatasetOp);
REGISTER_KERNEL_BUILDER(Name("ExperimentalUnbatchDataset").Device(DEVICE_CPU),
UnbatchDatasetOp);
} // namespace
} // namespace experimental
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/proto/bounding_box_proto_inc.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/image_tensor_specs.h"
namespace tflite {
namespace task {
namespace processor {
namespace {
// Number of bytes required for 8-bit per pixel RGB color space.
static constexpr int kRgbPixelBytes = 3;
using ::tflite::task::vision::BoundingBox;
using ::tflite::task::vision::FrameBuffer;
} // namespace
// Returns false if image preprocessing could be skipped, true otherwise.
bool ImagePreprocessor::IsImagePreprocessingNeeded(
const FrameBuffer& frame_buffer, const BoundingBox& roi) {
// Is crop required?
if (roi.origin_x() != 0 || roi.origin_y() != 0 ||
roi.width() != frame_buffer.dimension().width ||
roi.height() != frame_buffer.dimension().height) {
return true;
}
// Are image transformations required?
if (frame_buffer.orientation() != FrameBuffer::Orientation::kTopLeft ||
frame_buffer.format() != FrameBuffer::Format::kRGB ||
frame_buffer.dimension().width != input_specs_.image_width ||
frame_buffer.dimension().height != input_specs_.image_height) {
return true;
}
return false;
}
absl::Status ImagePreprocessor::Init(
const vision::FrameBufferUtils::ProcessEngine& process_engine) {
frame_buffer_utils_ = vision::FrameBufferUtils::Create(process_engine);
ASSIGN_OR_RETURN(input_specs_, vision::BuildInputImageTensorSpecs(
*engine_->interpreter(),
*engine_->metadata_extractor()));
if (input_specs_.color_space != tflite::ColorSpaceType_RGB) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kUnimplemented,
"ImagePreprocessor only supports RGB color space for now.");
}
return absl::OkStatus();
}
absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer) {
BoundingBox roi;
roi.set_width(frame_buffer.dimension().width);
roi.set_height(frame_buffer.dimension().height);
return Preprocess(frame_buffer, roi);
}
absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer,
const BoundingBox& roi) {
// Input data to be normalized (if needed) and used for inference. In most
// cases, this is the result of image preprocessing. In case no image
// preprocessing is needed (see below), this points to the input frame
// buffer raw data.
const uint8* input_data;
size_t input_data_byte_size;
// Optional buffers in case image preprocessing is needed.
std::unique_ptr<FrameBuffer> preprocessed_frame_buffer;
std::vector<uint8> preprocessed_data;
if (IsImagePreprocessingNeeded(frame_buffer, roi)) {
// Preprocess input image to fit model requirements.
// For now RGB is the only color space supported, which is ensured by
// `InitInternal`.
FrameBuffer::Dimension to_buffer_dimension = {input_specs_.image_width,
input_specs_.image_height};
input_data_byte_size =
GetBufferByteSize(to_buffer_dimension, FrameBuffer::Format::kRGB);
preprocessed_data.resize(input_data_byte_size / sizeof(uint8), 0);
input_data = preprocessed_data.data();
FrameBuffer::Plane preprocessed_plane = {
/*buffer=*/preprocessed_data.data(),
/*stride=*/{input_specs_.image_width * kRgbPixelBytes, kRgbPixelBytes}};
preprocessed_frame_buffer = FrameBuffer::Create(
{preprocessed_plane}, to_buffer_dimension, FrameBuffer::Format::kRGB,
FrameBuffer::Orientation::kTopLeft);
RETURN_IF_ERROR(frame_buffer_utils_->Preprocess(
frame_buffer, roi, preprocessed_frame_buffer.get()));
} else {
// Input frame buffer already targets model requirements: skip image
// preprocessing. For RGB, the data is always stored in a single plane.
input_data = frame_buffer.plane(0).buffer;
input_data_byte_size = frame_buffer.plane(0).stride.row_stride_bytes *
frame_buffer.dimension().height;
}
// Then normalize pixel data (if needed) and populate the input tensor.
switch (input_specs_.tensor_type) {
case kTfLiteUInt8:
if (Tensor()->bytes != input_data_byte_size) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"Size mismatch or unsupported padding bytes between pixel data "
"and input tensor.");
}
// No normalization required: directly populate data.
tflite::task::core::PopulateTensor(
input_data, input_data_byte_size / sizeof(uint8), Tensor());
break;
case kTfLiteFloat32: {
if (Tensor()->bytes / sizeof(float) !=
input_data_byte_size / sizeof(uint8)) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"Size mismatch or unsupported padding bytes between pixel data "
"and input tensor.");
}
// Normalize and populate.
float* normalized_input_data =
tflite::task::core::AssertAndReturnTypedTensor<float>(Tensor());
const tflite::task::vision::NormalizationOptions& normalization_options =
input_specs_.normalization_options.value();
for (int i = 0; i < normalization_options.num_values; i++) {
if (std::abs(normalization_options.std_values[i]) <
std::numeric_limits<float>::epsilon()) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"NormalizationOptions.std_values can't be 0. Please check if the "
"tensor metadata has been populated correctly.");
}
}
if (normalization_options.num_values == 1) {
float mean_value = normalization_options.mean_values[0];
float inv_std_value = (1.0f / normalization_options.std_values[0]);
for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
i++, input_data++, normalized_input_data++) {
*normalized_input_data =
inv_std_value * (static_cast<float>(*input_data) - mean_value);
}
} else {
std::array<float, 3> inv_std_values = {
1.0f / normalization_options.std_values[0],
1.0f / normalization_options.std_values[1],
1.0f / normalization_options.std_values[2]};
for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
i++, input_data++, normalized_input_data++) {
*normalized_input_data = inv_std_values[i % 3] *
(static_cast<float>(*input_data) -
normalization_options.mean_values[i % 3]);
}
}
break;
}
case kTfLiteInt8:
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kUnimplemented,
"kTfLiteInt8 input type is not implemented yet.");
default:
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal, "Unexpected input tensor type.");
}
return absl::OkStatus();
}
} // namespace processor
} // namespace task
} // namespace tflite
<commit_msg>Resize graph inside Preprocess().<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/vision/proto/bounding_box_proto_inc.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_utils.h"
#include "tensorflow_lite_support/cc/task/vision/utils/image_tensor_specs.h"
namespace tflite {
namespace task {
namespace processor {
namespace {
// Number of bytes required for 8-bit per pixel RGB color space.
static constexpr int kRgbPixelBytes = 3;
using ::tflite::task::vision::BoundingBox;
using ::tflite::task::vision::FrameBuffer;
} // namespace
// Returns false if image preprocessing could be skipped, true otherwise.
bool ImagePreprocessor::IsImagePreprocessingNeeded(
const FrameBuffer& frame_buffer, const BoundingBox& roi) {
// Is crop required?
if (roi.origin_x() != 0 || roi.origin_y() != 0 ||
roi.width() != frame_buffer.dimension().width ||
roi.height() != frame_buffer.dimension().height) {
return true;
}
// Are image transformations required?
if (frame_buffer.orientation() != FrameBuffer::Orientation::kTopLeft ||
frame_buffer.format() != FrameBuffer::Format::kRGB ||
frame_buffer.dimension().width != input_specs_.image_width ||
frame_buffer.dimension().height != input_specs_.image_height) {
return true;
}
return false;
}
// Returns true if the model expects dynamic image shape, false otherwise.
bool ImagePreprocessor::IsInputImageDynamic()
{
// Determine if the input shape is resizable.
const TfLiteIntArray* dims_signature = Tensor()->dims_signature;
if (dims_signature == nullptr) return false;
bool height_or_width_mutable = dims_signature->data[1] == -1 ||
dims_signature->data[2] == -1;
// Only the HXW dimensions support mutability.
bool batch_and_color_fixed = dims_signature->data[0] != -1 &&
dims_signature->data[3] != -1;
if (height_or_width_mutable && batch_and_color_fixed) return true;
return false;
}
absl::Status ImagePreprocessor::Init(
const vision::FrameBufferUtils::ProcessEngine& process_engine) {
frame_buffer_utils_ = vision::FrameBufferUtils::Create(process_engine);
ASSIGN_OR_RETURN(input_specs_, vision::BuildInputImageTensorSpecs(
*engine_->interpreter(),
*engine_->metadata_extractor()));
if (input_specs_.color_space != tflite::ColorSpaceType_RGB) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kUnimplemented,
"ImagePreprocessor only supports RGB color space for now.");
}
return absl::OkStatus();
}
absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer) {
BoundingBox roi;
roi.set_width(frame_buffer.dimension().width);
roi.set_height(frame_buffer.dimension().height);
return Preprocess(frame_buffer, roi);
}
absl::Status ImagePreprocessor::Preprocess(const FrameBuffer& frame_buffer,
const BoundingBox& roi) {
// Input data to be normalized (if needed) and used for inference. In most
// cases, this is the result of image preprocessing. In case no image
// preprocessing is needed (see below), this points to the input frame
// buffer raw data.
const uint8* input_data;
size_t input_data_byte_size;
// Optional buffers in case image preprocessing is needed.
std::unique_ptr<FrameBuffer> preprocessed_frame_buffer;
std::vector<uint8> preprocessed_data;
if (IsImagePreprocessingNeeded(frame_buffer, roi) && !IsInputImageDynamic()) {
// Preprocess input image to fit model requirements.
// For now RGB is the only color space supported, which is ensured by
// `InitInternal`.
FrameBuffer::Dimension to_buffer_dimension = {input_specs_.image_width,
input_specs_.image_height};
input_data_byte_size =
GetBufferByteSize(to_buffer_dimension, FrameBuffer::Format::kRGB);
preprocessed_data.resize(input_data_byte_size / sizeof(uint8), 0);
input_data = preprocessed_data.data();
FrameBuffer::Plane preprocessed_plane = {
/*buffer=*/preprocessed_data.data(),
/*stride=*/{input_specs_.image_width * kRgbPixelBytes, kRgbPixelBytes}};
preprocessed_frame_buffer = FrameBuffer::Create(
{preprocessed_plane}, to_buffer_dimension, FrameBuffer::Format::kRGB,
FrameBuffer::Orientation::kTopLeft);
RETURN_IF_ERROR(frame_buffer_utils_->Preprocess(
frame_buffer, roi, preprocessed_frame_buffer.get()));
} else {
// Input frame buffer already targets model requirements: skip image
// preprocessing. For RGB, the data is always stored in a single plane.
// If dynamic, it will re-dim the entire graph as per the input.
if (IsInputImageDynamic()) {
// Determine if the input shape is resizable.
const TfLiteIntArray* dims_signature = Tensor()->dims_signature;
const bool height_mutable = dims_signature->data[1] == -1;
const bool width_mutable = dims_signature->data[2] == -1;
if (height_mutable || width_mutable) {
const TfLiteIntArray* dims = Tensor()->dims;
const Interpreter* interpreter = engine_->interpreter();
// The expected BXHXWXD values of the model.
const int expected_batch = Tensor()->dims->data[0];
int expected_height = Tensor()->dims->data[1];
int expected_width = Tensor()->dims->data[2];
const int expected_depth = Tensor()->dims->data[3];
// HXW of the input image.
int image_height = frame_buffer.dimension().height;
int image_width = frame_buffer.dimension().width;
int height = height_mutable ? image_height : expected_height;
int width = width_mutable ? image_width : expected_width;
const std::vector<int> new_dims {expected_batch, height, width, expected_depth};
interpreter->ResizeInputTensorStrict(0, new_dims);
}
}
input_data = frame_buffer.plane(0).buffer;
input_data_byte_size = frame_buffer.plane(0).stride.row_stride_bytes *
frame_buffer.dimension().height;
}
// Then normalize pixel data (if needed) and populate the input tensor.
switch (input_specs_.tensor_type) {
case kTfLiteUInt8:
if (Tensor()->bytes != input_data_byte_size) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"Size mismatch or unsupported padding bytes between pixel data "
"and input tensor.");
}
// No normalization required: directly populate data.
tflite::task::core::PopulateTensor(
input_data, input_data_byte_size / sizeof(uint8), Tensor());
break;
case kTfLiteFloat32: {
if (Tensor()->bytes / sizeof(float) !=
input_data_byte_size / sizeof(uint8)) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"Size mismatch or unsupported padding bytes between pixel data "
"and input tensor.");
}
// Normalize and populate.
float* normalized_input_data =
tflite::task::core::AssertAndReturnTypedTensor<float>(Tensor());
const tflite::task::vision::NormalizationOptions& normalization_options =
input_specs_.normalization_options.value();
for (int i = 0; i < normalization_options.num_values; i++) {
if (std::abs(normalization_options.std_values[i]) <
std::numeric_limits<float>::epsilon()) {
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal,
"NormalizationOptions.std_values can't be 0. Please check if the "
"tensor metadata has been populated correctly.");
}
}
if (normalization_options.num_values == 1) {
float mean_value = normalization_options.mean_values[0];
float inv_std_value = (1.0f / normalization_options.std_values[0]);
for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
i++, input_data++, normalized_input_data++) {
*normalized_input_data =
inv_std_value * (static_cast<float>(*input_data) - mean_value);
}
} else {
std::array<float, 3> inv_std_values = {
1.0f / normalization_options.std_values[0],
1.0f / normalization_options.std_values[1],
1.0f / normalization_options.std_values[2]};
for (size_t i = 0; i < input_data_byte_size / sizeof(uint8);
i++, input_data++, normalized_input_data++) {
*normalized_input_data = inv_std_values[i % 3] *
(static_cast<float>(*input_data) -
normalization_options.mean_values[i % 3]);
}
}
break;
}
case kTfLiteInt8:
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kUnimplemented,
"kTfLiteInt8 input type is not implemented yet.");
default:
return tflite::support::CreateStatusWithPayload(
absl::StatusCode::kInternal, "Unexpected input tensor type.");
}
return absl::OkStatus();
}
} // namespace processor
} // namespace task
} // namespace tflite
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "sitkProcessObject.h"
#include "sitkCommand.h"
#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"
#include <iostream>
#include <algorithm>
#include "nsstd/functional.h"
namespace itk {
namespace simple {
namespace
{
static bool GlobalDefaultDebug = false;
static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;
// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
: public itk::Command
{
public:
typedef SimpleAdaptorCommand Self;
typedef SmartPointer< Self > Pointer;
itkNewMacro(Self);
itkTypeMacro(SimpleAdaptorCommand, Command);
void SetSimpleCommand( itk::simple::Command *cmd )
{
m_That=cmd;
}
/** Invoke the member function. */
virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
{
if (m_That)
{
m_That->Execute();
}
}
/** Invoke the member function with a const object */
virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
{
if ( m_That )
{
m_That->Execute();
}
}
protected:
itk::simple::Command * m_That;
SimpleAdaptorCommand():m_That(0) {}
virtual ~SimpleAdaptorCommand() {}
private:
SimpleAdaptorCommand(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
};
} // end anonymous namespace
//----------------------------------------------------------------------------
//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
: m_Debug(ProcessObject::GetGlobalDefaultDebug()),
m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
m_ActiveProcess(SITK_NULLPTR),
m_ProgressMeasurement(0.0)
{
}
//
// Destructor
//
ProcessObject::~ProcessObject ()
{
// ensure to remove reference between sitk commands and process object
Self::RemoveAllCommands();
}
std::string ProcessObject::ToString() const
{
std::ostringstream out;
out << " Debug: ";
this->ToStringHelper(out, this->m_Debug) << std::endl;
out << " NumberOfThreads: ";
this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;
out << " Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
assert( i->m_Command );
out << " Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
}
out << " ProgressMeasurement: ";
this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;
out << " ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
if( this->m_ActiveProcess )
{
this->m_ActiveProcess->Print(out, itk::Indent(4));
}
return out.str();
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
os << int(v);
return os;
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
os << int(v);
return os;
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
os << int(v);
return os;
}
void ProcessObject::DebugOn()
{
this->m_Debug = true;
}
void ProcessObject::DebugOff()
{
this->m_Debug = false;
}
bool ProcessObject::GetDebug() const
{
return this->m_Debug;
}
void ProcessObject::SetDebug(bool debugFlag)
{
this->m_Debug = debugFlag;
}
void ProcessObject::GlobalDefaultDebugOn()
{
GlobalDefaultDebug = true;
}
void ProcessObject::GlobalDefaultDebugOff()
{
GlobalDefaultDebug = false;
}
bool ProcessObject::GetGlobalDefaultDebug()
{
return GlobalDefaultDebug;
}
void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
GlobalDefaultDebug = debugFlag;
}
void ProcessObject::GlobalWarningDisplayOn()
{
itk::Object::GlobalWarningDisplayOn();
}
void ProcessObject::GlobalWarningDisplayOff()
{
itk::Object::GlobalWarningDisplayOff();
}
bool ProcessObject::GetGlobalWarningDisplay()
{
return itk::Object::GetGlobalWarningDisplay();
}
void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
itk::Object::SetGlobalWarningDisplay(flag);
}
double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}
void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}
double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}
void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}
void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
MultiThreader::SetGlobalDefaultNumberOfThreads(n);
}
unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
return MultiThreader::GetGlobalDefaultNumberOfThreads();
}
void ProcessObject::SetNumberOfThreads(unsigned int n)
{
m_NumberOfThreads = n;
}
unsigned int ProcessObject::GetNumberOfThreads() const
{
return m_NumberOfThreads;
}
int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
// add to our list of event, command pairs
m_Commands.push_back(EventCommand(event,&cmd));
// register ourselves with the command
cmd.AddProcessObject(this);
if (this->m_ActiveProcess)
{
this->AddObserverToActiveProcessObject( m_Commands.back() );
}
else
{
m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
}
return 0;
}
void ProcessObject::RemoveAllCommands()
{
// set's the m_Commands to an empty list via a swap
std::list<EventCommand> oldCommands;
swap(oldCommands, m_Commands);
// remove commands from active process object
std::list<EventCommand>::iterator i = oldCommands.begin();
while( i != oldCommands.end() && this->m_ActiveProcess )
{
this->RemoveObserverFromActiveProcessObject(*i);
++i;
}
// we must only call RemoveProcessObject once for each command
// so make a unique list of the Commands.
oldCommands.sort();
oldCommands.unique();
i = oldCommands.begin();
while( i != oldCommands.end() )
{
// note: this may call onCommandDelete, but we have already copied
// this->m_Command will be empty
i++->m_Command->RemoveProcessObject(this);
}
}
bool ProcessObject::HasCommand( EventEnum event ) const
{
std::list<EventCommand>::const_iterator i = m_Commands.begin();
while( i != m_Commands.end() )
{
if (i->m_Event == event)
{
return true;
}
++i;
}
return false;
}
float ProcessObject::GetProgress( ) const
{
if ( this->m_ActiveProcess )
{
return this->m_ActiveProcess->GetProgress();
}
return m_ProgressMeasurement;
}
void ProcessObject::Abort()
{
if ( this->m_ActiveProcess )
{
this->m_ActiveProcess->AbortGenerateDataOn();
}
}
void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
assert(p);
// propagate number of threads
p->SetNumberOfThreads(this->GetNumberOfThreads());
try
{
this->m_ActiveProcess = p;
// add command on active process deletion
itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
p->AddObserver(itk::DeleteEvent(), onDelete);
// register commands
for (std::list<EventCommand>::iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
this->AddObserverToActiveProcessObject(*i);
}
}
catch (...)
{
this->m_ActiveProcess = SITK_NULLPTR;
throw;
}
sitkDebugMacro( "Executing ITK filter:\n" << *p );
}
unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
itk::Command *c)
{
assert(this->m_ActiveProcess);
return this->m_ActiveProcess->AddObserver(e,c);
}
void ProcessObject::RemoveITKObserver( EventCommand &e )
{
assert(this->m_ActiveProcess);
this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}
const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
switch (e)
{
case sitkAnyEvent:
return eventAnyEvent;
case sitkAbortEvent:
return eventAbortEvent;
case sitkDeleteEvent:
return eventDeleteEvent;
case sitkEndEvent:
return eventEndEvent;
case sitkIterationEvent:
return eventIterationEvent;
case sitkProgressEvent:
return eventProgressEvent;
case sitkStartEvent:
return eventStartEvent;
case sitkUserEvent:
return eventUserEvent;
case sitkMultiResolutionIterationEvent:
return eventMultiResolutionIterationEvent;
default:
sitkExceptionMacro("LogicError: Unexpected event case!");
}
}
itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
if (this->m_ActiveProcess)
{
return this->m_ActiveProcess;
}
sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}
void ProcessObject::OnActiveProcessDelete( )
{
if (this->m_ActiveProcess)
{
this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
}
else
{
this->m_ProgressMeasurement = 0.0f;
}
// clear registered command IDs
for (std::list<EventCommand>::iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
i->m_ITKTag = std::numeric_limits<unsigned long>::max();
}
this->m_ActiveProcess = SITK_NULLPTR;
}
void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
// remove command from m_Command book keeping list, and remove it
// from the ITK ProcessObject
std::list<EventCommand>::iterator i = this->m_Commands.begin();
while ( i != this->m_Commands.end() )
{
if ( cmd == i->m_Command )
{
if ( this->m_ActiveProcess )
{
this->RemoveObserverFromActiveProcessObject( *i );
}
this->m_Commands.erase(i++);
}
else
{
++i;
}
}
}
unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
assert( this->m_ActiveProcess );
if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
{
sitkExceptionMacro("Commands already registered to another process object!");
}
const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);
// adapt sitk command to itk command
SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
itkCommand->SetSimpleCommand(eventCommand.m_Command);
itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());
return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}
void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
{
assert( this->m_ActiveProcess );
if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
{
this->RemoveITKObserver(e);
e.m_ITKTag = std::numeric_limits<unsigned long>::max();
}
}
} // end namespace simple
} // end namespace itk
<commit_msg>Use MultiThreader typedef for future ITK compatibility.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "sitkProcessObject.h"
#include "sitkCommand.h"
#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"
#include <iostream>
#include <algorithm>
#include "nsstd/functional.h"
namespace itk {
namespace simple {
namespace
{
static bool GlobalDefaultDebug = false;
static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;
// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
: public itk::Command
{
public:
typedef SimpleAdaptorCommand Self;
typedef SmartPointer< Self > Pointer;
itkNewMacro(Self);
itkTypeMacro(SimpleAdaptorCommand, Command);
void SetSimpleCommand( itk::simple::Command *cmd )
{
m_That=cmd;
}
/** Invoke the member function. */
virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
{
if (m_That)
{
m_That->Execute();
}
}
/** Invoke the member function with a const object */
virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
{
if ( m_That )
{
m_That->Execute();
}
}
protected:
itk::simple::Command * m_That;
SimpleAdaptorCommand():m_That(0) {}
virtual ~SimpleAdaptorCommand() {}
private:
SimpleAdaptorCommand(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
};
} // end anonymous namespace
//----------------------------------------------------------------------------
//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
: m_Debug(ProcessObject::GetGlobalDefaultDebug()),
m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
m_ActiveProcess(SITK_NULLPTR),
m_ProgressMeasurement(0.0)
{
}
//
// Destructor
//
ProcessObject::~ProcessObject ()
{
// ensure to remove reference between sitk commands and process object
Self::RemoveAllCommands();
}
std::string ProcessObject::ToString() const
{
std::ostringstream out;
out << " Debug: ";
this->ToStringHelper(out, this->m_Debug) << std::endl;
out << " NumberOfThreads: ";
this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;
out << " Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
assert( i->m_Command );
out << " Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
}
out << " ProgressMeasurement: ";
this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;
out << " ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
if( this->m_ActiveProcess )
{
this->m_ActiveProcess->Print(out, itk::Indent(4));
}
return out.str();
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
os << int(v);
return os;
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
os << int(v);
return os;
}
std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
os << int(v);
return os;
}
void ProcessObject::DebugOn()
{
this->m_Debug = true;
}
void ProcessObject::DebugOff()
{
this->m_Debug = false;
}
bool ProcessObject::GetDebug() const
{
return this->m_Debug;
}
void ProcessObject::SetDebug(bool debugFlag)
{
this->m_Debug = debugFlag;
}
void ProcessObject::GlobalDefaultDebugOn()
{
GlobalDefaultDebug = true;
}
void ProcessObject::GlobalDefaultDebugOff()
{
GlobalDefaultDebug = false;
}
bool ProcessObject::GetGlobalDefaultDebug()
{
return GlobalDefaultDebug;
}
void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
GlobalDefaultDebug = debugFlag;
}
void ProcessObject::GlobalWarningDisplayOn()
{
itk::Object::GlobalWarningDisplayOn();
}
void ProcessObject::GlobalWarningDisplayOff()
{
itk::Object::GlobalWarningDisplayOff();
}
bool ProcessObject::GetGlobalWarningDisplay()
{
return itk::Object::GetGlobalWarningDisplay();
}
void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
itk::Object::SetGlobalWarningDisplay(flag);
}
double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}
void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}
double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}
void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}
void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
itk::ProcessObject::MultiThreaderType::SetGlobalDefaultNumberOfThreads(n);
}
unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
return itk::ProcessObject::MultiThreaderType::GetGlobalDefaultNumberOfThreads();
}
void ProcessObject::SetNumberOfThreads(unsigned int n)
{
m_NumberOfThreads = n;
}
unsigned int ProcessObject::GetNumberOfThreads() const
{
return m_NumberOfThreads;
}
int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
// add to our list of event, command pairs
m_Commands.push_back(EventCommand(event,&cmd));
// register ourselves with the command
cmd.AddProcessObject(this);
if (this->m_ActiveProcess)
{
this->AddObserverToActiveProcessObject( m_Commands.back() );
}
else
{
m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
}
return 0;
}
void ProcessObject::RemoveAllCommands()
{
// set's the m_Commands to an empty list via a swap
std::list<EventCommand> oldCommands;
swap(oldCommands, m_Commands);
// remove commands from active process object
std::list<EventCommand>::iterator i = oldCommands.begin();
while( i != oldCommands.end() && this->m_ActiveProcess )
{
this->RemoveObserverFromActiveProcessObject(*i);
++i;
}
// we must only call RemoveProcessObject once for each command
// so make a unique list of the Commands.
oldCommands.sort();
oldCommands.unique();
i = oldCommands.begin();
while( i != oldCommands.end() )
{
// note: this may call onCommandDelete, but we have already copied
// this->m_Command will be empty
i++->m_Command->RemoveProcessObject(this);
}
}
bool ProcessObject::HasCommand( EventEnum event ) const
{
std::list<EventCommand>::const_iterator i = m_Commands.begin();
while( i != m_Commands.end() )
{
if (i->m_Event == event)
{
return true;
}
++i;
}
return false;
}
float ProcessObject::GetProgress( ) const
{
if ( this->m_ActiveProcess )
{
return this->m_ActiveProcess->GetProgress();
}
return m_ProgressMeasurement;
}
void ProcessObject::Abort()
{
if ( this->m_ActiveProcess )
{
this->m_ActiveProcess->AbortGenerateDataOn();
}
}
void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
assert(p);
// propagate number of threads
p->SetNumberOfThreads(this->GetNumberOfThreads());
try
{
this->m_ActiveProcess = p;
// add command on active process deletion
itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
p->AddObserver(itk::DeleteEvent(), onDelete);
// register commands
for (std::list<EventCommand>::iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
this->AddObserverToActiveProcessObject(*i);
}
}
catch (...)
{
this->m_ActiveProcess = SITK_NULLPTR;
throw;
}
sitkDebugMacro( "Executing ITK filter:\n" << *p );
}
unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
itk::Command *c)
{
assert(this->m_ActiveProcess);
return this->m_ActiveProcess->AddObserver(e,c);
}
void ProcessObject::RemoveITKObserver( EventCommand &e )
{
assert(this->m_ActiveProcess);
this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}
const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
switch (e)
{
case sitkAnyEvent:
return eventAnyEvent;
case sitkAbortEvent:
return eventAbortEvent;
case sitkDeleteEvent:
return eventDeleteEvent;
case sitkEndEvent:
return eventEndEvent;
case sitkIterationEvent:
return eventIterationEvent;
case sitkProgressEvent:
return eventProgressEvent;
case sitkStartEvent:
return eventStartEvent;
case sitkUserEvent:
return eventUserEvent;
case sitkMultiResolutionIterationEvent:
return eventMultiResolutionIterationEvent;
default:
sitkExceptionMacro("LogicError: Unexpected event case!");
}
}
itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
if (this->m_ActiveProcess)
{
return this->m_ActiveProcess;
}
sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}
void ProcessObject::OnActiveProcessDelete( )
{
if (this->m_ActiveProcess)
{
this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
}
else
{
this->m_ProgressMeasurement = 0.0f;
}
// clear registered command IDs
for (std::list<EventCommand>::iterator i = m_Commands.begin();
i != m_Commands.end();
++i)
{
i->m_ITKTag = std::numeric_limits<unsigned long>::max();
}
this->m_ActiveProcess = SITK_NULLPTR;
}
void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
// remove command from m_Command book keeping list, and remove it
// from the ITK ProcessObject
std::list<EventCommand>::iterator i = this->m_Commands.begin();
while ( i != this->m_Commands.end() )
{
if ( cmd == i->m_Command )
{
if ( this->m_ActiveProcess )
{
this->RemoveObserverFromActiveProcessObject( *i );
}
this->m_Commands.erase(i++);
}
else
{
++i;
}
}
}
unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
assert( this->m_ActiveProcess );
if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
{
sitkExceptionMacro("Commands already registered to another process object!");
}
const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);
// adapt sitk command to itk command
SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
itkCommand->SetSimpleCommand(eventCommand.m_Command);
itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());
return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}
void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
{
assert( this->m_ActiveProcess );
if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
{
this->RemoveITKObserver(e);
e.m_ITKTag = std::numeric_limits<unsigned long>::max();
}
}
} // end namespace simple
} // end namespace itk
<|endoftext|> |
<commit_before>// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL
template<typename T>
struct X0 {
typedef int size_type;
size_type f0() const;
};
template<typename T>
typename X0<T>::size_type X0<T>::f0() const { }
<commit_msg>Make the recanonicalization-for-an-out-of-line-definition test case a bit trickier<commit_after>// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL
template<typename T> struct X1 { };
template<typename T>
struct X0 {
typedef int size_type;
typedef T value_type;
size_type f0() const;
value_type *f1();
X1<value_type*> f2();
};
template<typename T>
typename X0<T>::size_type X0<T>::f0() const {
return 0;
}
template<typename U>
typename X0<U>::value_type *X0<U>::f1() {
return 0;
};
template<typename U>
X1<typename X0<U>::value_type*> X0<U>::f2() {
return 0;
};
<|endoftext|> |
<commit_before>/**
* @file log_softmax_layer.hpp
* @author Marcus Edel
*
* Definition of the LogSoftmaxLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the log softmax layer. The log softmax loss layer computes
* the multinomial logistic loss of the softmax of its inputs. This layer is
* meant to be used in combination with the negative log likelihood layer
* (NegativeLogLikelihoodLayer), which expects that the input contains
* log-probabilities for each class.
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
public:
/**
* Create the LogSoftmaxLayer object.
*/
LogSoftmaxLayer() { /* Nothing to do here. */ }
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
output = (maxInput - input);
// Approximation of the hyperbolic tangent. The acuracy however is
// about 0.00001 lower as using tanh. Credits go to Leon Bottou.
output.transform( [](double x)
{
//! Fast approximation of exp(-x) for x positive.
constexpr double A0 = 1.0;
constexpr double A1 = 0.125;
constexpr double A2 = 0.0078125;
constexpr double A3 = 0.00032552083;
constexpr double A4 = 1.0172526e-5;
if (x < 13.0)
{
double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
y *= y;
y *= y;
y *= y;
y = 1 / y;
return y;
}
return 0.0;
} );
output = input - (maxInput + std::log(arma::accu(output)));
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& input,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g)
{
g = gy - arma::exp(input) * arma::accu(gy);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
InputDataType& Delta() const { return delta; }
//! Modify the delta.
InputDataType& Delta() { return delta; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class LogSoftmaxLayer
}; // namespace ann
}; // namespace mlpack
#endif
<commit_msg>only initialize variable once<commit_after>/**
* @file log_softmax_layer.hpp
* @author Marcus Edel
*
* Definition of the LogSoftmaxLayer class.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the log softmax layer. The log softmax loss layer computes
* the multinomial logistic loss of the softmax of its inputs. This layer is
* meant to be used in combination with the negative log likelihood layer
* (NegativeLogLikelihoodLayer), which expects that the input contains
* log-probabilities for each class.
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
public:
/**
* Create the LogSoftmaxLayer object.
*/
LogSoftmaxLayer() { /* Nothing to do here. */ }
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
output = (maxInput - input);
// Approximation of the hyperbolic tangent. The acuracy however is
// about 0.00001 lower as using tanh. Credits go to Leon Bottou.
output.transform( [](double x)
{
//! Fast approximation of exp(-x) for x positive.
static constexpr double A0 = 1.0;
static constexpr double A1 = 0.125;
static constexpr double A2 = 0.0078125;
static constexpr double A3 = 0.00032552083;
static constexpr double A4 = 1.0172526e-5;
if (x < 13.0)
{
double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
y *= y;
y *= y;
y *= y;
y = 1 / y;
return y;
}
return 0.0;
} );
output = input - (maxInput + std::log(arma::accu(output)));
}
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards trough f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& input,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g)
{
g = gy - arma::exp(input) * arma::accu(gy);
}
//! Get the input parameter.
InputDataType& InputParameter() const { return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
InputDataType& Delta() const { return delta; }
//! Modify the delta.
InputDataType& Delta() { return delta; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class LogSoftmaxLayer
}; // namespace ann
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <forward_list>
// explicit forward_list(size_type n);
// explicit forward_list(size_type n, const Alloc& a);
#include <forward_list>
#include <cassert>
#include <cstddef>
#include "test_macros.h"
#include "DefaultOnly.h"
#include "min_allocator.h"
template <class T, class Allocator>
void check_allocator(unsigned n, Allocator const &alloc = Allocator())
{
#if TEST_STD_VER > 11
typedef std::forward_list<T, Allocator> C;
C d(n, alloc);
assert(d.get_allocator() == alloc);
assert(static_cast<std::size_t>(std::distance(d.begin(), d.end())) == n);
#endif
}
int main()
{
{
typedef DefaultOnly T;
typedef std::forward_list<T> C;
unsigned N = 10;
C c(N);
unsigned n = 0;
for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
assert(*i == T());
#else
;
#endif
assert(n == N);
}
#if TEST_STD_VER >= 11
{
typedef DefaultOnly T;
typedef std::forward_list<T, min_allocator<T>> C;
unsigned N = 10;
C c(N);
unsigned n = 0;
for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
assert(*i == T());
#else
;
#endif
assert(n == N);
check_allocator<T, min_allocator<T>> ( 0 );
check_allocator<T, min_allocator<T>> ( 3 );
}
#endif
}
<commit_msg>Fix yet another missed -Wunused warning. Hopefully this is the last one<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <forward_list>
// explicit forward_list(size_type n);
// explicit forward_list(size_type n, const Alloc& a);
#include <forward_list>
#include <cassert>
#include <cstddef>
#include "test_macros.h"
#include "DefaultOnly.h"
#include "min_allocator.h"
template <class T, class Allocator>
void check_allocator(unsigned n, Allocator const &alloc = Allocator())
{
#if TEST_STD_VER > 11
typedef std::forward_list<T, Allocator> C;
C d(n, alloc);
assert(d.get_allocator() == alloc);
assert(static_cast<std::size_t>(std::distance(d.begin(), d.end())) == n);
#else
((void)n);
((void)alloc);
#endif
}
int main()
{
{
typedef DefaultOnly T;
typedef std::forward_list<T> C;
unsigned N = 10;
C c(N);
unsigned n = 0;
for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n) {
#if TEST_STD_VER >= 11
assert(*i == T());
#else
((void)0);
#endif
}
assert(n == N);
}
#if TEST_STD_VER >= 11
{
typedef DefaultOnly T;
typedef std::forward_list<T, min_allocator<T>> C;
unsigned N = 10;
C c(N);
unsigned n = 0;
for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
assert(*i == T());
assert(n == N);
check_allocator<T, min_allocator<T>> ( 0 );
check_allocator<T, min_allocator<T>> ( 3 );
}
#endif
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType, size_t bits, class URNG>
// RealType generate_canonical(URNG& g);
#include <random>
#include <cassert>
#include "test_macros.h"
#include "truncate_fp.h"
int main(int, char**)
{
{
typedef std::minstd_rand0 E;
typedef float F;
E r;
F f = std::generate_canonical<F, 0>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef float F;
E r;
F f = std::generate_canonical<F, 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef double F;
E r;
F f = std::generate_canonical<F, 0>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef double F;
E r;
F f = std::generate_canonical<F, 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
}
{
typedef std::minstd_rand0 E;
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (E::max() - E::min() + F(1))) /
((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
}
{
typedef std::minstd_rand0 E;
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (E::max() - E::min() + F(1))) /
((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
}
{
typedef std::minstd_rand0 E;
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (E::max() - E::min() + F(1))) /
((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
}
return 0;
}
<commit_msg>[libc++] Avoid implicit conversion warning in a <random> test<commit_after>//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType, size_t bits, class URNG>
// RealType generate_canonical(URNG& g);
#include <random>
#include <cassert>
#include "test_macros.h"
#include "truncate_fp.h"
int main(int, char**)
{
typedef std::minstd_rand0 E;
auto range = E::max() - E::min();
{
typedef float F;
E r;
F f = std::generate_canonical<F, 0>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef float F;
E r;
F f = std::generate_canonical<F, 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef float F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef double F;
E r;
F f = std::generate_canonical<F, 0>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef double F;
E r;
F f = std::generate_canonical<F, 1>(r);
assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
}
{
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (range + F(1))) /
((range + F(1)) * (range + F(1)))));
}
{
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (range + F(1))) /
((range + F(1)) * (range + F(1)))));
}
{
typedef double F;
E r;
F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
assert(f == truncate_fp(
(16807 - E::min() +
(282475249 - E::min()) * (range + F(1))) /
((range + F(1)) * (range + F(1)))));
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "xyz/openbmc_project/PLDM/PDR/server.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <vector>
#include "libpldm/pdr.h"
#include "libpldm/platform.h"
namespace pldm
{
namespace dbus_api
{
using PdrIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::PLDM::server::PDR>;
/** @class Pdr
* @brief OpenBMC PLDM.PDR Implementation
* @details A concrete implementation for the
* xyz.openbmc_project.PLDM.PDR DBus APIs.
*/
class Pdr : public PdrIntf
{
public:
Pdr() = delete;
Pdr(const Pdr&) = delete;
Pdr& operator=(const Pdr&) = delete;
Pdr(Pdr&&) = delete;
Pdr& operator=(Pdr&&) = delete;
virtual ~Pdr() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
* @param[in] repo - pointer to BMC's primary PDR repo
*/
Pdr(sdbusplus::bus::bus& bus, const std::string& path,
const pldm_pdr* repo) :
PdrIntf(bus, path.c_str(), repo),
pdrRepo(repo){};
/** @brief Implementation for PdrIntf.FindStateEffecterPDR
* @param[in] tid - PLDM terminus ID.
* @param[in] entityID - entity that can be associated with PLDM State set.
* @param[in] stateSetId - value that identifies PLDM State set.
*/
std::vector<std::vector<uint8_t>>
findStateEffecterPDR(uint8_t tid, uint16_t entityID,
uint16_t stateSetId) override;
private:
/** @brief pointer to BMC's primary PDR repo */
const pldm_pdr* pdrRepo;
};
} // namespace dbus_api
} // namespace pldm
<commit_msg>Fix OpenBMC CI fail<commit_after>#pragma once
#include "xyz/openbmc_project/PLDM/PDR/server.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <vector>
#include "libpldm/pdr.h"
#include "libpldm/platform.h"
namespace pldm
{
namespace dbus_api
{
using PdrIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::PLDM::server::PDR>;
/** @class Pdr
* @brief OpenBMC PLDM.PDR Implementation
* @details A concrete implementation for the
* xyz.openbmc_project.PLDM.PDR DBus APIs.
*/
class Pdr : public PdrIntf
{
public:
Pdr() = delete;
Pdr(const Pdr&) = delete;
Pdr& operator=(const Pdr&) = delete;
Pdr(Pdr&&) = delete;
Pdr& operator=(Pdr&&) = delete;
virtual ~Pdr() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
* @param[in] repo - pointer to BMC's primary PDR repo
*/
Pdr(sdbusplus::bus::bus& bus, const std::string& path,
const pldm_pdr* repo) :
PdrIntf(bus, path.c_str(), repo),
pdrRepo(repo){};
/** @brief Implementation for PdrIntf.FindStateEffecterPDR
* @param[in] tid - PLDM terminus ID.
* @param[in] entityID - entity that can be associated with PLDM State set.
* @param[in] stateSetId - value that identifies PLDM State set.
*/
std::vector<std::vector<uint8_t>>
findStateEffecterPDR(uint8_t tid, uint16_t entityID,
uint16_t stateSetId) override;
/** @brief Implementation for PdrIntf.FindStateSensorPDR
* @param[in] tid - PLDM terminus ID.
* @param[in] entityID - entity that can be associated with PLDM State set.
* @param[in] stateSetId - value that identifies PLDM State set.
*/
std::vector<std::vector<uint8_t>>
findStateSensorPDR(uint8_t tid, uint16_t entityID,
uint16_t stateSetId) override
{
return {};
}
private:
/** @brief pointer to BMC's primary PDR repo */
const pldm_pdr* pdrRepo;
};
} // namespace dbus_api
} // namespace pldm
<|endoftext|> |
<commit_before>/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#if defined(__ANDROID__) && !defined (NOT_USE_PTHREAD_CANCEL)
#include <pthread_setcanceltype.h>
#endif
#include "./BaseThread.h"
#if defined(_WIN32) || defined(_WIN64) ||defined(_WIN32_WCE)
#include <winbase.h>
#else
#include <signal.h>
#include "time.h"
#endif
namespace NSThreads
{
class CThreadDescriptor
{
public:
CThreadDescriptor()
{
}
virtual ~CThreadDescriptor()
{
}
};
ASC_THREAD_ID GetCurrentThreadId()
{
#if defined(_WIN32) || defined (_WIN64)
return ::GetCurrentThreadId();
#else
return pthread_self();
#endif
}
void Sleep(int nMilliseconds)
{
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
::Sleep((DWORD)nMilliseconds);
#else
struct timespec tim, tim2;
tim.tv_sec = nMilliseconds / 1000;
tim.tv_nsec = (nMilliseconds % 1000) * 1000000;
::nanosleep(&tim , &tim2);
#endif
}
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
DWORD WINAPI CBaseThread::__ThreadProc(void* pv)
{
CBaseThread* pThis = (CBaseThread*)pv;
DWORD value = pThis->ThreadProc();
if (pThis->m_bIsNeedDestroy)
delete pThis;
return value;
}
class __native_thread : public CThreadDescriptor
{
friend class CBaseThread;
private:
HANDLE m_thread = nullptr;
public:
__native_thread() : CThreadDescriptor()
{
}
virtual ~__native_thread()
{
if (m_thread)
{
CloseHandle(m_thread);
m_thread = NULL;
}
}
};
#else
void* CBaseThread::__ThreadProc(void* pv)
{
#ifndef NOT_USE_PTHREAD_CANCEL
int old_thread_type;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_thread_type);
#endif
CBaseThread* pThis = (CBaseThread*)pv;
pThis->ThreadProc();
if (pThis->m_bIsNeedDestroy)
delete pThis;
return NULL;
}
class __native_thread : public CThreadDescriptor
{
friend class CBaseThread;
private:
pthread_t m_thread;
public:
__native_thread() : CThreadDescriptor()
{
m_thread = NULL;
}
virtual ~__native_thread()
{
}
};
#endif
CBaseThread::CBaseThread()
{
m_hThread = NULL;
m_bRunThread = FALSE;
m_bSuspend = FALSE;
m_lError = 0;
m_lThreadPriority = 0;
m_bIsNeedDestroy = false;
}
CBaseThread::~CBaseThread()
{
Stop();
}
void CBaseThread::Start(int lPriority)
{
if (m_bRunThread)
return;
m_lError = 0;
m_bSuspend = FALSE;
m_hThread = new __native_thread();
m_bRunThread = TRUE;
m_bIsExit.store(false);
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
DWORD dwTemp;
((__native_thread*)m_hThread)->m_thread = CreateThread(NULL, 0, &__ThreadProc, (void*)this, 0, &dwTemp);
SetThreadPriority(((__native_thread*)m_hThread)->m_thread, lPriority);
#else
pthread_create(&((__native_thread*)m_hThread)->m_thread, 0, &__ThreadProc, (void*)this);
#endif
m_lThreadPriority = lPriority;
}
void CBaseThread::Suspend()
{
m_bSuspend = TRUE;
}
void CBaseThread::Resume()
{
m_bSuspend = FALSE;
}
void CBaseThread::Stop()
{
if (!m_bRunThread)
return;
m_bIsExit.store(true);
m_bRunThread = FALSE;
Join();
RELEASEOBJECT(m_hThread);
}
void CBaseThread::StopNoJoin()
{
m_bRunThread = FALSE;
RELEASEOBJECT(m_bIsExit);
RELEASEOBJECT(m_hThread);
}
void CBaseThread::DestroyOnFinish()
{
m_bIsNeedDestroy = true;
}
INT CBaseThread::IsSuspended() { return m_bSuspend; }
INT CBaseThread::IsRunned() { return m_bRunThread; }
int CBaseThread::GetError() { return m_lError; }
bool CBaseThread::isAborted() {return m_bIsExit && m_bIsExit.load();}
CThreadDescriptor* CBaseThread::GetDescriptor() { return m_hThread; }
int CBaseThread::GetPriority() { return m_lThreadPriority; }
void CBaseThread::CheckSuspend()
{
while (m_bSuspend && m_bRunThread)
NSThreads::Sleep(10);
}
void CBaseThread::Join()
{
if (NULL == m_hThread)
return;
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
WaitForSingleObject(((__native_thread*)m_hThread)->m_thread, INFINITE);
#else
pthread_join(((__native_thread*)m_hThread)->m_thread, 0);
#endif
}
void CBaseThread::Cancel()
{
if (NULL == m_hThread)
return;
m_bIsExit.store(true);
m_bRunThread = FALSE;
Join();
RELEASEOBJECT(m_hThread);
}
}
<commit_msg>[Network] debug<commit_after>/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#if defined(__ANDROID__) && !defined (NOT_USE_PTHREAD_CANCEL)
#include <pthread_setcanceltype.h>
#endif
#include "./BaseThread.h"
#if defined(_WIN32) || defined(_WIN64) ||defined(_WIN32_WCE)
#include <winbase.h>
#else
#include <signal.h>
#include "time.h"
#endif
namespace NSThreads
{
class CThreadDescriptor
{
public:
CThreadDescriptor()
{
}
virtual ~CThreadDescriptor()
{
}
};
ASC_THREAD_ID GetCurrentThreadId()
{
#if defined(_WIN32) || defined (_WIN64)
return ::GetCurrentThreadId();
#else
return pthread_self();
#endif
}
void Sleep(int nMilliseconds)
{
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
::Sleep((DWORD)nMilliseconds);
#else
struct timespec tim, tim2;
tim.tv_sec = nMilliseconds / 1000;
tim.tv_nsec = (nMilliseconds % 1000) * 1000000;
::nanosleep(&tim , &tim2);
#endif
}
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
DWORD WINAPI CBaseThread::__ThreadProc(void* pv)
{
CBaseThread* pThis = (CBaseThread*)pv;
DWORD value = pThis->ThreadProc();
if (pThis->m_bIsNeedDestroy)
delete pThis;
return value;
}
class __native_thread : public CThreadDescriptor
{
friend class CBaseThread;
private:
HANDLE m_thread = nullptr;
public:
__native_thread() : CThreadDescriptor()
{
}
virtual ~__native_thread()
{
if (m_thread)
{
CloseHandle(m_thread);
m_thread = NULL;
}
}
};
#else
void* CBaseThread::__ThreadProc(void* pv)
{
#ifndef NOT_USE_PTHREAD_CANCEL
int old_thread_type;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_thread_type);
#endif
CBaseThread* pThis = (CBaseThread*)pv;
pThis->ThreadProc();
if (pThis->m_bIsNeedDestroy)
delete pThis;
return NULL;
}
class __native_thread : public CThreadDescriptor
{
friend class CBaseThread;
private:
pthread_t m_thread;
public:
__native_thread() : CThreadDescriptor()
{
m_thread = NULL;
}
virtual ~__native_thread()
{
}
};
#endif
CBaseThread::CBaseThread()
{
m_hThread = NULL;
m_bRunThread = FALSE;
m_bSuspend = FALSE;
m_lError = 0;
m_lThreadPriority = 0;
m_bIsNeedDestroy = false;
}
CBaseThread::~CBaseThread()
{
Stop();
}
void CBaseThread::Start(int lPriority)
{
if (m_bRunThread)
return;
m_lError = 0;
m_bSuspend = FALSE;
m_hThread = new __native_thread();
m_bRunThread = TRUE;
m_bIsExit.store(false);
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
DWORD dwTemp;
((__native_thread*)m_hThread)->m_thread = CreateThread(NULL, 0, &__ThreadProc, (void*)this, 0, &dwTemp);
SetThreadPriority(((__native_thread*)m_hThread)->m_thread, lPriority);
#else
pthread_create(&((__native_thread*)m_hThread)->m_thread, 0, &__ThreadProc, (void*)this);
#endif
m_lThreadPriority = lPriority;
}
void CBaseThread::Suspend()
{
m_bSuspend = TRUE;
}
void CBaseThread::Resume()
{
m_bSuspend = FALSE;
}
void CBaseThread::Stop()
{
if (!m_bRunThread)
return;
m_bIsExit.store(true);
m_bRunThread = FALSE;
Join();
RELEASEOBJECT(m_hThread);
}
void CBaseThread::StopNoJoin()
{
m_bRunThread = FALSE;
m_bIsExit.store(true);
RELEASEOBJECT(m_hThread);
}
void CBaseThread::DestroyOnFinish()
{
m_bIsNeedDestroy = true;
}
INT CBaseThread::IsSuspended() { return m_bSuspend; }
INT CBaseThread::IsRunned() { return m_bRunThread; }
int CBaseThread::GetError() { return m_lError; }
bool CBaseThread::isAborted() {return m_bIsExit && m_bIsExit.load();}
CThreadDescriptor* CBaseThread::GetDescriptor() { return m_hThread; }
int CBaseThread::GetPriority() { return m_lThreadPriority; }
void CBaseThread::CheckSuspend()
{
while (m_bSuspend && m_bRunThread)
NSThreads::Sleep(10);
}
void CBaseThread::Join()
{
if (NULL == m_hThread)
return;
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
WaitForSingleObject(((__native_thread*)m_hThread)->m_thread, INFINITE);
#else
pthread_join(((__native_thread*)m_hThread)->m_thread, 0);
#endif
}
void CBaseThread::Cancel()
{
if (NULL == m_hThread)
return;
m_bIsExit.store(true);
m_bRunThread = FALSE;
Join();
RELEASEOBJECT(m_hThread);
}
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s)
{
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos)
{
return "";
} else if (b1 != string::npos && b2 != string::npos)
{
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
double distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{
double closestLen = 100000; //large number
int closestWaypoint = 0;
for(int i = 0; i < maps_x.size(); i++)
{
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x,y,map_x,map_y);
if(dist < closestLen)
{
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y-y),(map_x-x));
double angle = fabs(theta-heading);
angle = min(2*pi() - angle, angle);
if(angle > pi()/4)
{
closestWaypoint++;
if (closestWaypoint == maps_x.size())
{
closestWaypoint = 0;
}
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);
int prev_wp;
prev_wp = next_wp-1;
if(next_wp == 0)
{
prev_wp = maps_x.size()-1;
}
double n_x = maps_x[next_wp]-maps_x[prev_wp];
double n_y = maps_y[next_wp]-maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
double proj_x = proj_norm*n_x;
double proj_y = proj_norm*n_y;
double frenet_d = distance(x_x,x_y,proj_x,proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000-maps_x[prev_wp];
double center_y = 2000-maps_y[prev_wp];
double centerToPos = distance(center_x,center_y,x_x,x_y);
double centerToRef = distance(center_x,center_y,proj_x,proj_y);
if(centerToPos <= centerToRef)
{
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for(int i = 0; i < prev_wp; i++)
{
frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
}
frenet_s += distance(0,0,proj_x,proj_y);
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
{
int prev_wp = -1;
while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
{
prev_wp++;
}
int wp2 = (prev_wp+1)%maps_x.size();
double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s-maps_s[prev_wp]);
double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
double seg_y = maps_y[prev_wp]+seg_s*sin(heading);
double perp_heading = heading-pi()/2;
double x = seg_x + d*cos(perp_heading);
double y = seg_y + d*sin(perp_heading);
return {x,y};
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line))
{
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
h.onMessage([&map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode)
{
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "")
{
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry")
{
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
// TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds
// Experimental: Drive at current car yaw i.e. in a straight line
double d_inc = 0.44; // spacing between subsequent points, controls car speed
for(int i = 0; i < 50; i++)
{
double next_x = car_x + (i + 1) * d_inc * cos(deg2rad(car_yaw));
double next_y = car_y + (i + 1) * d_inc * sin(deg2rad(car_yaw));
next_x_vals.push_back(next_x);
next_y_vals.push_back(next_y);
}
// END
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} // end hasData() check in s
else
{
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
} // end Manual driving
} // end websocket message event
}); // end onMessage
// We don't need this since we're not using HTTP but if it's removed the
// program doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t)
{
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
} else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req)
{
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length)
{
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<commit_msg>feat: add experimental code to drive in current lane<commit_after>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s)
{
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos)
{
return "";
} else if (b1 != string::npos && b2 != string::npos)
{
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
double distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{
double closestLen = 100000; //large number
int closestWaypoint = 0;
for(int i = 0; i < maps_x.size(); i++)
{
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x,y,map_x,map_y);
if(dist < closestLen)
{
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y-y),(map_x-x));
double angle = fabs(theta-heading);
angle = min(2*pi() - angle, angle);
if(angle > pi()/4)
{
closestWaypoint++;
if (closestWaypoint == maps_x.size())
{
closestWaypoint = 0;
}
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);
int prev_wp;
prev_wp = next_wp-1;
if(next_wp == 0)
{
prev_wp = maps_x.size()-1;
}
double n_x = maps_x[next_wp]-maps_x[prev_wp];
double n_y = maps_y[next_wp]-maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
double proj_x = proj_norm*n_x;
double proj_y = proj_norm*n_y;
double frenet_d = distance(x_x,x_y,proj_x,proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000-maps_x[prev_wp];
double center_y = 2000-maps_y[prev_wp];
double centerToPos = distance(center_x,center_y,x_x,x_y);
double centerToRef = distance(center_x,center_y,proj_x,proj_y);
if(centerToPos <= centerToRef)
{
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for(int i = 0; i < prev_wp; i++)
{
frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
}
frenet_s += distance(0,0,proj_x,proj_y);
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
{
int prev_wp = -1;
while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
{
prev_wp++;
}
int wp2 = (prev_wp+1)%maps_x.size();
double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s-maps_s[prev_wp]);
double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
double seg_y = maps_y[prev_wp]+seg_s*sin(heading);
double perp_heading = heading-pi()/2;
double x = seg_x + d*cos(perp_heading);
double y = seg_y + d*sin(perp_heading);
return {x,y};
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line))
{
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
h.onMessage([&map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode)
{
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "")
{
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry")
{
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
// TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds
// Experimental: Drive in current lane
double d_inc = 0.44; // spacing between subsequent points, controls car speed
for(int i = 0; i < 50; i++)
{
double next_s = car_s + (i + 1) * d_inc;
double next_d = 6; // assuming car starts in middle lane and a lane width of 4m
vector<double> xy = getXY(next_s, next_d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
next_x_vals.push_back(xy[0]);
next_y_vals.push_back(xy[1]);
}
// end drive in current lane
// // Experimental: Drive at current car yaw i.e. in a straight line
// double d_inc = 0.44; // spacing between subsequent points, controls car speed
// for(int i = 0; i < 50; i++)
// {
// double next_x = car_x + (i + 1) * d_inc * cos(deg2rad(car_yaw));
// double next_y = car_y + (i + 1) * d_inc * sin(deg2rad(car_yaw));
// next_x_vals.push_back(next_x);
// next_y_vals.push_back(next_y);
// }
// // end drive in straight line
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} // end hasData() check in s
else
{
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
} // end Manual driving
} // end websocket message event
}); // end onMessage
// We don't need this since we're not using HTTP but if it's removed the
// program doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t)
{
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
} else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req)
{
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length)
{
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "shared.h"
#include "v8.h"
int main() {
v8::HandleScope handle_scope;
std::cout << "Hello world!\n";
return 0;
}<commit_msg>removed failing code<commit_after>#include <iostream>
#include "shared.h"
#include "v8.h"
int main() {
std::cout << "Hello world!\n";
return 0;
}<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors (rdo@rk9.bmstu.ru)
\authors (impus@hotbox.ru)
\date 2.10.2011
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <list>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------
typedef std::list<double> Container;
typedef const tstring contstr;
const long int g_seed = 123456789; //!<
contstr g_fileNormalName = _T("data_normal.txt"); //!<
contstr g_fileUniformName = _T("data_uniform.txt"); //!<
contstr g_fileExponentialName = _T("data_exponential.txt"); //!<
contstr g_fileTriangularName = _T("data_trinagular.txt"); //!<
const ruint g_count = 100000; //!<
const double g_main = 10.0; //!<
const double g_var = 1.0; //!<
const double g_from = 1.0; //!<
const double g_to = 7.0; //!<
const double g_top = 5.0; //!<
const ruint g_precision = 20; //!<
const ruint g_countOfExamples = 2000; //!<
const ruint g_countOfFree = 39; //!<
const double pi = 3.141592653; //!<
// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
if (rdo::File::exist(g_fileName.c_str()))
return;
T sequence(g_seed);
Container test;
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
std::ofstream stream(g_fileName.c_str());
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
stream << *it << std::endl;
}
}
template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
std::ifstream stream(g_fileName.c_str());
BOOST_CHECK(stream.good());
Container test;
T sequence(g_seed);
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
BOOST_CHECK(stream.good());
tstring str;
stream >> str;
double val;
BOOST_CHECK(sscanf_s(str.c_str(), _T("%lf"), &val) == 1);
BOOST_CHECK(val == *it);
if (val != *it)
{
std::cout.precision(g_precision);
std::cout << *it << std::endl;
std::cout << val << std::endl;
}
}
}
template <class T,class F>
double area (F binder, double elem, double n, double m)
{
double S1 = 1;
double S2 = 0;
ruint t = (n-m)/elem;
while (fabs(S1-S2)/S1 > 0.01)
{
S2 = S1;
S1 = 0;
for (ruint i = 0; i < t; ++i)
{
T sequnece(i*(n-m)/t);
S1 += binder.operator()(&sequence);
}
S1 *= 0.5*(m-n);
t *= 10;
}
return S1;
}
template <class T,class F>
void onCheckKsi(F binder, double left, double right)
{
Container xITemp; // ,
double elem = (right-left)/(1000*g_countOfFree);// ,
for (ruint i = 0; i < g_countOfFree*1000+1; ++i)// . , ( )
{
xITemp.push_back(elem*i);
}
Container xI; // ,
Container::iterator it = xI.begin();
xI.push_back(left); // , - right
STL_FOR_ALL(xITemp, itTemp)
{
if (fabs(area(binder, elem, *it, *itTemp) - 1/g_countOfFree) < fabs(area(binder, elem, *it, *(++itTemp)) - 1/g_countOfFree))
{
xI.push_back(*((--itTemp)++);
++it;
}
--itTemp;
}
if(xI.size() == (g_countOfFree - 1)) // , . - . .
{
xI.push_back(right);
}
//, right , .. . ,
}
// --------------------------------------------------------------------------------
class SequenceNormal
{
public:
SequenceNormal(double x): m_x(x)
{}
double next(double main, double var)
{
return 1/(sqrt(2*pi)*sqrt(var)*exp((m_x - main)*(m_x - main)/(2*var))); // . . 3 .
}
private:
double m_x;
};
BOOST_AUTO_TEST_SUITE(RDOSequencesTest)
// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorNormal>
(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
}
BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorNormal>
(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
onCheckKsi<SequenceNormal>
(boost::bind(&SequenceNormal::next, _1, g_main, g_var), g_main-4*sqrt(g_var), g_main+4*sqrt(g_var));
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorUniform>
(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorUniform>
(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorExponential>
(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorExponential>
(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorTriangular>
(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorTriangular>
(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END()<commit_msg> - исправлено вычисление площади<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file main.cpp
\authors (rdo@rk9.bmstu.ru)
\authors (impus@hotbox.ru)
\date 2.10.2011
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <list>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------
typedef std::list<double> Container;
typedef const tstring contstr;
const long int g_seed = 123456789; //!<
contstr g_fileNormalName = _T("data_normal.txt"); //!<
contstr g_fileUniformName = _T("data_uniform.txt"); //!<
contstr g_fileExponentialName = _T("data_exponential.txt"); //!<
contstr g_fileTriangularName = _T("data_trinagular.txt"); //!<
const ruint g_count = 100000; //!<
const double g_main = 10.0; //!<
const double g_var = 1.0; //!<
const double g_from = 1.0; //!<
const double g_to = 7.0; //!<
const double g_top = 5.0; //!<
const ruint g_precision = 20; //!<
const ruint g_countOfExamples = 2000; //!<
const ruint g_countOfFree = 39; //!<
const double pi = 3.141592653; //!<
// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
if (rdo::File::exist(g_fileName.c_str()))
return;
T sequence(g_seed);
Container test;
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
std::ofstream stream(g_fileName.c_str());
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
stream << *it << std::endl;
}
}
template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
std::ifstream stream(g_fileName.c_str());
BOOST_CHECK(stream.good());
Container test;
T sequence(g_seed);
for (ruint i = 0; i < g_count; ++i)
{
test.push_back(binder.operator()(&sequence));
}
stream.precision(g_precision);
STL_FOR_ALL(test, it)
{
BOOST_CHECK(stream.good());
tstring str;
stream >> str;
double val;
BOOST_CHECK(sscanf_s(str.c_str(), _T("%lf"), &val) == 1);
BOOST_CHECK(val == *it);
if (val != *it)
{
std::cout.precision(g_precision);
std::cout << *it << std::endl;
std::cout << val << std::endl;
}
}
}
template <class T,class F>
double area (F binder, double elem, double n, double m)
{
int k = 1;
double S1 = 1;
double S2 = 0;
ruint t = (m-n)/elem;
while (fabs(S1-S2)/S1 > 0.01)
{
S2 = S1;
S1 = 0;
for (ruint i = 1; i < t-1; ++i)
{
if ((i == 0) || (i == t - 1))
k = 0.5;
T sequence(i*(m-n)/t);
S1 += k*(binder.operator()(&sequence));
k = 1;
}
S1 *= (m-n);
t *= 10;
}
return S1;
}
template <class T,class F>
void onCheckKsi(F binder, double left, double right)
{
Container xITemp; // ,
double elem = (right-left)/(1000*g_countOfFree);// ,
for (ruint i = 0; i < g_countOfFree*1000+1; ++i)// . , ( )
{
xITemp.push_back(elem*i);
}
Container xI; // ,
Container::iterator it = xI.begin();
xI.push_back(left); // , - right
STL_FOR_ALL(xITemp, itTemp)
{
if (fabs(area(binder, elem, *it, *itTemp) - 1/g_countOfFree) < fabs(area(binder, elem, *it, *(++itTemp)) - 1/g_countOfFree))
{
xI.push_back(*((--itTemp)++);
++it;
}
--itTemp;
}
if(xI.size() == (g_countOfFree - 1)) // , . - . .
{
xI.push_back(right);
}
//, right , .. . ,
}
// --------------------------------------------------------------------------------
class SequenceNormal
{
public:
SequenceNormal(double x): m_x(x)
{}
double next(double main, double var)
{
return 1/(sqrt(2*pi)*sqrt(var)*exp((m_x - main)*(m_x - main)/(2*var))); // . . 3 .
}
private:
double m_x;
};
BOOST_AUTO_TEST_SUITE(RDOSequencesTest)
// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorNormal>
(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
}
BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorNormal>
(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
onCheckKsi<SequenceNormal>
(boost::bind(&SequenceNormal::next, _1, g_main, g_var), g_main-4*sqrt(g_var), g_main+4*sqrt(g_var));
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorUniform>
(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorUniform>
(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorExponential>
(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorExponential>
(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
onGenerateData<rdoRuntime::RandGeneratorTriangular>
(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
onCheckData<rdoRuntime::RandGeneratorTriangular>
(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_SUITE_END()<|endoftext|> |
<commit_before><commit_msg>When parsing the type declaration for a new variable, there comes a point where we have thrown away a space character after seeing "operator<" and we must put it back, because it might actually be "operator< <int>(" and removing the space is fatal in that case.<commit_after><|endoftext|> |
<commit_before>#include "kinc.h"
#include <mcheck.h>
/**
* Prints the command-line usage instructions for the similarity command
*/
void print_usage() {
printf("\n");
printf("Usage: ./kinc [command]\n");
printf("Available commands:\n");
printf(" similarity Performs pair-wise similarity calculations using an input expression matrix.\n");
printf(" threshold Identifies a threshold for cutting the similarity matrix\n");
printf(" extract Outputs the network edges file\n");
printf(" help [command] Prints these instructions. Include the command to print help\n");
printf(" for a specific command (e.g. kinc help similarity)\n");
printf("\n");
}
/**
* The main subroutine. Parses the input parameters and executes the program
* accordingly.
*/
int main(int argc, char *argv[]) {
// Enable mtrace memory leak checking
mtrace();
// The return value
int retval = 0;
// make sure we have at least one input argument for the command
if (argc == 1) {
printf("ERROR: Please provide the command to execute.\n\n");
print_usage();
retval = -1;
}
// construct the similarity matrix
else if (strcmp(argv[1], "similarity") == 0) {
RunSimilarity * similarity = new RunSimilarity(argc, argv);
similarity->execute();
delete similarity;
}
// construct the similarity matrix
else if (strcmp(argv[1], "index") == 0) {
RunIndex * index = new RunIndex(argc, argv);
index->execute();
delete index;
}
// construct the similarity matrix
else if (strcmp(argv[1], "query") == 0) {
RunQuery * query = new RunQuery(argc, argv);
query->execute();
delete query;
}
// identify the threshold for cutting the similarity matrix
else if (strcmp(argv[1], "threshold") == 0) {
RunThreshold * threshold = new RunThreshold(argc, argv);
threshold->execute();
delete threshold;
}
// extract a given element from the matrix or a network
else if (strcmp(argv[1], "extract") == 0) {
RunExtract * extract = new RunExtract(argc, argv);
extract->execute();
delete extract;
}
// print help documentation
else if (strcmp(argv[1], "help") == 0) {
if (argc == 3) {
if (strcmp(argv[2], "similarity") == 0) {
RunSimilarity::printUsage();
}
if (strcmp(argv[2], "threshold") == 0) {
RunThreshold::printUsage();
}
if (strcmp(argv[2], "extract") == 0) {
RunExtract::printUsage();
}
if (strcmp(argv[2], "index") == 0) {
RunIndex::printUsage();
}
if (strcmp(argv[2], "query") == 0) {
RunQuery::printUsage();
}
}
else {
print_usage();
}
}
else {
printf("ERROR: Unknown command.\n\n");
print_usage();
retval = -1;
}
return retval;
}
/**
*
*/
void start_mpi() {
// // MPI variables
// int mpi_err, mpi_num_procs, mpi_id;
//
// // Initialize MPI.
// mpi_err = MPI_Init(&argc, &argv);
//
// // Find out my process ID, and how many processes were started.
// mpi_err |= MPI_Comm_rank(MPI_COMM_WORLD, &mpi_id);
// mpi_err |= MPI_Comm_size(MPI_COMM_WORLD, &mpi_num_procs);
//
// if (mpi_err != 0) {
// printf("MPI initialization failed\n");
// exit(1);
// }
// For testing a single process... should comment out when not testing.
// if (mpi_id + 1 != 5) {
// mpi_err = MPI_Finalize();
// return 1;
// }
// printf("Using %i out of %i processes.\n", mpi_id + 1, mpi_num_procs);
}
/**
*
*/
void end_mpi() {
// Wait until all other processes are completed before closing the manager
// MPI_Status stat;
// char message[10];
// if (mpi_id > 0 ) {
// // All non master processes should report done when completed.
// sprintf(message, "Done");
// MPI_Send(message, strlen(message)+1, MPI_BYTE, 0,1,MPI_COMM_WORLD);
// }
// else {
// // The master process should wait to get 'Done' from each process
// // before terminating
// int proc;
// for (proc = 1; proc < mpi_num_procs; proc++) {
// MPI_Recv(message, sizeof(message), MPI_BYTE, proc, 1, MPI_COMM_WORLD, &stat);
// }
// }
//
// // Terminate MPI.
// mpi_err = MPI_Finalize();
}
<commit_msg>Forgot to remove mtrace line<commit_after>#include "kinc.h"
#include <mcheck.h>
/**
* Prints the command-line usage instructions for the similarity command
*/
void print_usage() {
printf("\n");
printf("Usage: ./kinc [command]\n");
printf("Available commands:\n");
printf(" similarity Performs pair-wise similarity calculations using an input expression matrix.\n");
printf(" threshold Identifies a threshold for cutting the similarity matrix\n");
printf(" extract Outputs the network edges file\n");
printf(" help [command] Prints these instructions. Include the command to print help\n");
printf(" for a specific command (e.g. kinc help similarity)\n");
printf("\n");
}
/**
* The main subroutine. Parses the input parameters and executes the program
* accordingly.
*/
int main(int argc, char *argv[]) {
// Enable mtrace memory leak checking
//mtrace();
// The return value
int retval = 0;
// make sure we have at least one input argument for the command
if (argc == 1) {
printf("ERROR: Please provide the command to execute.\n\n");
print_usage();
retval = -1;
}
// construct the similarity matrix
else if (strcmp(argv[1], "similarity") == 0) {
RunSimilarity * similarity = new RunSimilarity(argc, argv);
similarity->execute();
delete similarity;
}
// construct the similarity matrix
else if (strcmp(argv[1], "index") == 0) {
RunIndex * index = new RunIndex(argc, argv);
index->execute();
delete index;
}
// construct the similarity matrix
else if (strcmp(argv[1], "query") == 0) {
RunQuery * query = new RunQuery(argc, argv);
query->execute();
delete query;
}
// identify the threshold for cutting the similarity matrix
else if (strcmp(argv[1], "threshold") == 0) {
RunThreshold * threshold = new RunThreshold(argc, argv);
threshold->execute();
delete threshold;
}
// extract a given element from the matrix or a network
else if (strcmp(argv[1], "extract") == 0) {
RunExtract * extract = new RunExtract(argc, argv);
extract->execute();
delete extract;
}
// print help documentation
else if (strcmp(argv[1], "help") == 0) {
if (argc == 3) {
if (strcmp(argv[2], "similarity") == 0) {
RunSimilarity::printUsage();
}
if (strcmp(argv[2], "threshold") == 0) {
RunThreshold::printUsage();
}
if (strcmp(argv[2], "extract") == 0) {
RunExtract::printUsage();
}
if (strcmp(argv[2], "index") == 0) {
RunIndex::printUsage();
}
if (strcmp(argv[2], "query") == 0) {
RunQuery::printUsage();
}
}
else {
print_usage();
}
}
else {
printf("ERROR: Unknown command.\n\n");
print_usage();
retval = -1;
}
return retval;
}
/**
*
*/
void start_mpi() {
// // MPI variables
// int mpi_err, mpi_num_procs, mpi_id;
//
// // Initialize MPI.
// mpi_err = MPI_Init(&argc, &argv);
//
// // Find out my process ID, and how many processes were started.
// mpi_err |= MPI_Comm_rank(MPI_COMM_WORLD, &mpi_id);
// mpi_err |= MPI_Comm_size(MPI_COMM_WORLD, &mpi_num_procs);
//
// if (mpi_err != 0) {
// printf("MPI initialization failed\n");
// exit(1);
// }
// For testing a single process... should comment out when not testing.
// if (mpi_id + 1 != 5) {
// mpi_err = MPI_Finalize();
// return 1;
// }
// printf("Using %i out of %i processes.\n", mpi_id + 1, mpi_num_procs);
}
/**
*
*/
void end_mpi() {
// Wait until all other processes are completed before closing the manager
// MPI_Status stat;
// char message[10];
// if (mpi_id > 0 ) {
// // All non master processes should report done when completed.
// sprintf(message, "Done");
// MPI_Send(message, strlen(message)+1, MPI_BYTE, 0,1,MPI_COMM_WORLD);
// }
// else {
// // The master process should wait to get 'Done' from each process
// // before terminating
// int proc;
// for (proc = 1; proc < mpi_num_procs; proc++) {
// MPI_Recv(message, sizeof(message), MPI_BYTE, proc, 1, MPI_COMM_WORLD, &stat);
// }
// }
//
// // Terminate MPI.
// mpi_err = MPI_Finalize();
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/*
Author: R. GUERNANE LPSC Grenoble CNRS/IN2P3
*/
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloBunchInfo.h"
#include "AliCaloFitResults.h"
#include "AliLog.h"
#include "TMath.h"
#include <stdexcept>
#include <iostream>
#include "TF1.h"
#include "TGraph.h"
#include "AliCaloConstants.h"
using namespace std;
ClassImp( AliCaloRawAnalyzerFakeALTRO )
AliCaloRawAnalyzerFakeALTRO::AliCaloRawAnalyzerFakeALTRO() : AliCaloRawAnalyzerFitter("Chi Square Fit", "LMS")
{
}
AliCaloRawAnalyzerFakeALTRO::~AliCaloRawAnalyzerFakeALTRO()
{
//delete fTf1;
}
AliCaloFitResults
AliCaloRawAnalyzerFakeALTRO::Evaluate( const vector<AliCaloBunchInfo> &bunchvector, const UInt_t altrocfg1, const UInt_t altrocfg2 )
{
// Extracting signal parameters using fitting
short maxampindex; //index of maximum amplitude
short maxamp; //Maximum amplitude
int index = SelectBunch( bunchvector, &maxampindex, &maxamp );
if( index >= 0)
{
Float_t ped = ReverseAndSubtractPed( &(bunchvector.at(index)) , altrocfg1, altrocfg2, fReversed );
Float_t maxf = TMath::MaxElement( bunchvector.at(index).GetLength(), fReversed );
short maxrev = maxampindex - bunchvector.at(index).GetStartBin();
// timebinOffset is timebin value at maximum (maxrev)
short timebinOffset = maxampindex - (bunchvector.at(index).GetLength()-1);
if( maxf < fAmpCut || ( maxamp - ped) > fOverflowCut ) // (maxamp - ped) > fOverflowCut = Close to saturation (use low gain then)
{
return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, timebinOffset);
}
else if ( maxf >= fAmpCut )
{
int first = 0;
int last = 0;
SelectSubarray( fReversed, bunchvector.at(index).GetLength(), maxrev, &first, &last, fFitArrayCut );
int nsamples = last - first + 1;
if( ( nsamples ) >= fNsampleCut )
{
Float_t tmax = (maxrev - first); // local tmax estimate
TGraph *graph = new TGraph( nsamples, fXaxis, &fReversed[first] );
fTf1->SetParameter(0, maxf*fkEulerSquared );
fTf1->SetParameter(1, tmax - fTau);
// set rather loose parameter limits
fTf1->SetParLimits(0, 0.5*maxf*fkEulerSquared, 2*maxf*fkEulerSquared );
fTf1->SetParLimits(1, tmax - fTau - 4, tmax - fTau + 4);
if (fFixTau) {
fTf1->FixParameter(2, fTau);
}
else {
fTf1->ReleaseParameter(2); // allow par. to vary
fTf1->SetParameter(2, fTau);
}
Short_t tmpStatus = 0;
try {
tmpStatus = graph->Fit(fTf1, "Q0RW");
}
catch (const std::exception & e) {
AliError( Form("TGraph Fit exception %s", e.what()) );
return AliCaloFitResults( maxamp, ped, Ret::kNoFit, maxf, timebinOffset,
timebinOffset, Ret::kDummy, Ret::kDummy, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
}
if( fVerbose == true )
{
AliCaloRawAnalyzer::PrintBunch( bunchvector.at(index) );
PrintFitResult( fTf1 ) ;
}
// global tmax
tmax = fTf1->GetParameter(1) + timebinOffset - (maxrev - first) // abs. t0
+ fTf1->GetParameter(2); // +tau, makes sum tmax
delete graph;
return AliCaloFitResults( maxamp, ped , Ret::kFitPar,
fTf1->GetParameter(0)/fkEulerSquared,
tmax,
timebinOffset,
fTf1->GetChisquare(),
fTf1->GetNDF(),
Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
// delete graph;
}
else
{
Float_t chi2 = CalculateChi2(maxf, maxrev, first, last);
Int_t ndf = last - first - 1; // nsamples - 2
return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, timebinOffset,
timebinOffset, chi2, ndf, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
}
} // ampcut
}
return AliCaloFitResults( Ret::kInvalid, Ret::kInvalid );
}
<commit_msg>Bug fix: The fitting algorithm variable was not initialized for this class<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, 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. *
**************************************************************************/
/*
Author: R. GUERNANE LPSC Grenoble CNRS/IN2P3
*/
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloBunchInfo.h"
#include "AliCaloFitResults.h"
#include "AliLog.h"
#include "TMath.h"
#include <stdexcept>
#include <iostream>
#include "TF1.h"
#include "TGraph.h"
#include "AliCaloConstants.h"
using namespace std;
ClassImp( AliCaloRawAnalyzerFakeALTRO )
AliCaloRawAnalyzerFakeALTRO::AliCaloRawAnalyzerFakeALTRO() : AliCaloRawAnalyzerFitter("Chi Square Fit", "LMS")
{
fAlgo= Algo::kFakeAltro;
}
AliCaloRawAnalyzerFakeALTRO::~AliCaloRawAnalyzerFakeALTRO()
{
//delete fTf1;
}
AliCaloFitResults
AliCaloRawAnalyzerFakeALTRO::Evaluate( const vector<AliCaloBunchInfo> &bunchvector, const UInt_t altrocfg1, const UInt_t altrocfg2 )
{
// Extracting signal parameters using fitting
short maxampindex; //index of maximum amplitude
short maxamp; //Maximum amplitude
int index = SelectBunch( bunchvector, &maxampindex, &maxamp );
if( index >= 0)
{
Float_t ped = ReverseAndSubtractPed( &(bunchvector.at(index)) , altrocfg1, altrocfg2, fReversed );
Float_t maxf = TMath::MaxElement( bunchvector.at(index).GetLength(), fReversed );
short maxrev = maxampindex - bunchvector.at(index).GetStartBin();
// timebinOffset is timebin value at maximum (maxrev)
short timebinOffset = maxampindex - (bunchvector.at(index).GetLength()-1);
if( maxf < fAmpCut || ( maxamp - ped) > fOverflowCut ) // (maxamp - ped) > fOverflowCut = Close to saturation (use low gain then)
{
return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, timebinOffset);
}
else if ( maxf >= fAmpCut )
{
int first = 0;
int last = 0;
SelectSubarray( fReversed, bunchvector.at(index).GetLength(), maxrev, &first, &last, fFitArrayCut );
int nsamples = last - first + 1;
if( ( nsamples ) >= fNsampleCut )
{
Float_t tmax = (maxrev - first); // local tmax estimate
TGraph *graph = new TGraph( nsamples, fXaxis, &fReversed[first] );
fTf1->SetParameter(0, maxf*fkEulerSquared );
fTf1->SetParameter(1, tmax - fTau);
// set rather loose parameter limits
fTf1->SetParLimits(0, 0.5*maxf*fkEulerSquared, 2*maxf*fkEulerSquared );
fTf1->SetParLimits(1, tmax - fTau - 4, tmax - fTau + 4);
if (fFixTau) {
fTf1->FixParameter(2, fTau);
}
else {
fTf1->ReleaseParameter(2); // allow par. to vary
fTf1->SetParameter(2, fTau);
}
Short_t tmpStatus = 0;
try {
tmpStatus = graph->Fit(fTf1, "Q0RW");
}
catch (const std::exception & e) {
AliError( Form("TGraph Fit exception %s", e.what()) );
return AliCaloFitResults( maxamp, ped, Ret::kNoFit, maxf, timebinOffset,
timebinOffset, Ret::kDummy, Ret::kDummy, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
}
if( fVerbose == true )
{
AliCaloRawAnalyzer::PrintBunch( bunchvector.at(index) );
PrintFitResult( fTf1 ) ;
}
// global tmax
tmax = fTf1->GetParameter(1) + timebinOffset - (maxrev - first) // abs. t0
+ fTf1->GetParameter(2); // +tau, makes sum tmax
delete graph;
return AliCaloFitResults( maxamp, ped , Ret::kFitPar,
fTf1->GetParameter(0)/fkEulerSquared,
tmax,
timebinOffset,
fTf1->GetChisquare(),
fTf1->GetNDF(),
Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
// delete graph;
}
else
{
Float_t chi2 = CalculateChi2(maxf, maxrev, first, last);
Int_t ndf = last - first - 1; // nsamples - 2
return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, timebinOffset,
timebinOffset, chi2, ndf, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) );
}
} // ampcut
}
return AliCaloFitResults( Ret::kInvalid, Ret::kInvalid );
}
<|endoftext|> |
<commit_before>/*
* GStreamer
* Copyright (C) 2009 Julien Isorce <julien.isorce@gmail.com>
* Copyright (C) 2009 Andrey Nechypurenko <andreynech@gmail.com>
* Copyright (C) 2010 Nuno Santos <nunosantos@imaginando.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <QtGui>
#include "gstthread.h"
#include "qglrenderer.h"
#include "pipeline.h"
#if defined(Q_WS_MAC)
extern void *qt_current_nsopengl_context();
#endif
QGLRenderer::QGLRenderer(const QString &videoLocation,
QWidget *parent)
: QGLWidget(parent),
videoLoc(videoLocation),
gst_thread(NULL),
closing(false),
frame(NULL)
{
move(20, 10);
resize(640, 480);
}
QGLRenderer::~QGLRenderer()
{
}
void
QGLRenderer::initializeGL()
{
GLContextID ctx;
#if defined(Q_WS_WIN)
ctx.contextId = wglGetCurrentContext();
ctx.dc = wglGetCurrentDC();
#elif defined (Q_WS_MAC)
ctx.contextId = (NSOpenGLContext*) qt_current_nsopengl_context();
#elif defined(Q_WS_X11)
ctx.contextId = glXGetCurrentContext();
const char *display_name = getenv("DISPLAY");
if(display_name == NULL)
{
// actually we should look for --display command line parameter here
display_name = ":0.0";
}
ctx.display = XOpenDisplay(display_name);
ctx.wnd = this->winId();
#endif
// We need to unset Qt context before initializing gst-gl plugin.
// Otherwise the attempt to share gst-gl context with Qt will fail.
this->doneCurrent();
this->gst_thread =
new GstThread(ctx, this->videoLoc, SLOT(newFrame()), this);
this->makeCurrent();
QObject::connect(this->gst_thread, SIGNAL(finished()),
this, SLOT(close()));
QObject::connect(this, SIGNAL(closeRequested()),
this->gst_thread, SLOT(stop()), Qt::QueuedConnection);
qglClearColor(QApplication::palette().color(QPalette::Active,
QPalette::Window));
//glShadeModel(GL_FLAT);
//glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glEnable(GL_TEXTURE_RECTANGLE_ARB); // Enable Texture Mapping
this->gst_thread->start();
}
void
QGLRenderer::resizeGL(int width, int height)
{
// Reset The Current Viewport And Perspective Transformation
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
void
QGLRenderer::newFrame()
{
Pipeline *pipeline = this->gst_thread->getPipeline();
if(!pipeline)
return;
/* frame is initialized as null */
if (this->frame)
pipeline->queue_output_buf.put(this->frame);
this->frame = pipeline->queue_input_buf.get();
/* direct call to paintGL (no queued) */
this->updateGL();
}
void
QGLRenderer::paintGL()
{
static GLfloat xrot = 0;
static GLfloat yrot = 0;
static GLfloat zrot = 0;
if (this->frame)
{
GLfloat width = this->frame->width;
GLfloat height = this->frame->height;
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, this->frame->texture);
if(glGetError () != GL_NO_ERROR)
{
qDebug ("failed to bind texture that comes from gst-gl");
emit closeRequested();
return;
}
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-5.0f);
glRotatef(xrot,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glRotatef(zrot,0.0f,0.0f,1.0f);
glBegin(GL_QUADS);
// Front Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(width, height); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(width,height); glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(width, height); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
xrot+=0.3f;
yrot+=0.2f;
zrot+=0.4f;
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
}
}
void
QGLRenderer::closeEvent(QCloseEvent* event)
{
if(this->closing == false)
{
this->closing = true;
emit closeRequested();
event->ignore();
}
}
<commit_msg>qglwtextureshare example: fix in qglrenderer.cpp<commit_after>/*
* GStreamer
* Copyright (C) 2009 Julien Isorce <julien.isorce@gmail.com>
* Copyright (C) 2009 Andrey Nechypurenko <andreynech@gmail.com>
* Copyright (C) 2010 Nuno Santos <nunosantos@imaginando.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <QtGui>
#include "gstthread.h"
#include "qglrenderer.h"
#include "pipeline.h"
#if defined(Q_WS_MAC)
extern void *qt_current_nsopengl_context();
#endif
/**
* GluPerspective is part of the GLU library, and not supported as of newer (3.x?)
* versions of OpenGL. An easy way to update the example is to write your own
* replacement, something like this:
*
* See http://stackoverflow.com/questions/9210118/qts-opengl-samples-complain-about-some-errors-and-wont-run
*/
void gluPerspective(double fovy,double aspect, double zNear, double zFar)
{
// Start in projection mode.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double xmin, xmax, ymin, ymax;
ymax = zNear * tan(fovy * M_PI / 360.0);
ymin = -ymax;
xmin = ymin * aspect;
xmax = ymax * aspect;
glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}
QGLRenderer::QGLRenderer(const QString &videoLocation,
QWidget *parent)
: QGLWidget(parent),
videoLoc(videoLocation),
gst_thread(NULL),
closing(false),
frame(NULL)
{
move(20, 10);
resize(640, 480);
}
QGLRenderer::~QGLRenderer()
{
}
void
QGLRenderer::initializeGL()
{
GLContextID ctx;
#if defined(Q_WS_WIN)
ctx.contextId = wglGetCurrentContext();
ctx.dc = wglGetCurrentDC();
#elif defined (Q_WS_MAC)
ctx.contextId = (NSOpenGLContext*) qt_current_nsopengl_context();
#elif defined(Q_WS_X11)
ctx.contextId = glXGetCurrentContext();
const char *display_name = getenv("DISPLAY");
if(display_name == NULL)
{
// actually we should look for --display command line parameter here
display_name = ":0.0";
}
ctx.display = XOpenDisplay(display_name);
ctx.wnd = this->winId();
#endif
// We need to unset Qt context before initializing gst-gl plugin.
// Otherwise the attempt to share gst-gl context with Qt will fail.
this->doneCurrent();
this->gst_thread =
new GstThread(ctx, this->videoLoc, SLOT(newFrame()), this);
this->makeCurrent();
QObject::connect(this->gst_thread, SIGNAL(finished()),
this, SLOT(close()));
QObject::connect(this, SIGNAL(closeRequested()),
this->gst_thread, SLOT(stop()), Qt::QueuedConnection);
qglClearColor(QApplication::palette().color(QPalette::Active,
QPalette::Window));
//glShadeModel(GL_FLAT);
//glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glEnable(GL_TEXTURE_RECTANGLE_ARB); // Enable Texture Mapping
this->gst_thread->start();
}
void
QGLRenderer::resizeGL(int width, int height)
{
// Reset The Current Viewport And Perspective Transformation
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
void
QGLRenderer::newFrame()
{
Pipeline *pipeline = this->gst_thread->getPipeline();
if(!pipeline)
return;
/* frame is initialized as null */
if (this->frame)
pipeline->queue_output_buf.put(this->frame);
this->frame = pipeline->queue_input_buf.get();
/* direct call to paintGL (no queued) */
this->updateGL();
}
void
QGLRenderer::paintGL()
{
static GLfloat xrot = 0;
static GLfloat yrot = 0;
static GLfloat zrot = 0;
if (this->frame)
{
GLfloat width = this->frame->width;
GLfloat height = this->frame->height;
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, this->frame->texture);
if(glGetError () != GL_NO_ERROR)
{
qDebug ("failed to bind texture that comes from gst-gl");
emit closeRequested();
return;
}
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-5.0f);
glRotatef(xrot,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glRotatef(zrot,0.0f,0.0f,1.0f);
glBegin(GL_QUADS);
// Front Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(width, height); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(width,height); glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, height); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(width, height); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(0.0f, height); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(width, height); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
xrot+=0.3f;
yrot+=0.2f;
zrot+=0.4f;
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
}
}
void
QGLRenderer::closeEvent(QCloseEvent* event)
{
if(this->closing == false)
{
this->closing = true;
emit closeRequested();
event->ignore();
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include "cache.h"
#include "associative_cache.h"
#include "global_cached_private.h"
#include "part_global_cached_private.h"
int part_global_cached_private::thread_init() {
/* let's bind the thread to a specific node first. */
struct bitmask *nodemask = numa_allocate_cpumask();
numa_bitmask_clearall(nodemask);
printf("thread %d is associated to node %d\n", idx, get_group_id());
numa_bitmask_setbit(nodemask, get_group_id());
numa_bind(nodemask);
numa_set_strict(1);
numa_set_bind_policy(1);
read_private::thread_init();
request_queue = new bulk_queue<io_request>(REQ_QUEUE_SIZE);
reply_queue = new bulk_queue<io_reply>(REPLY_QUEUE_SIZE);
/*
* there is a global lock for all threads.
* so this lock makes sure cache initialization is serialized
*/
pthread_mutex_lock(&init_mutex);
thread_group *group = &groups[group_idx];
if (group->cache == NULL) {
/* this allocates all pages for the cache. */
page::allocate_cache(cache_size);
group->cache = global_cached_private::create_cache(cache_type, cache_size, manager);
}
num_finish_init++;
pthread_mutex_unlock(&init_mutex);
pthread_mutex_lock(&wait_mutex);
while (num_finish_init < nthreads) {
pthread_cond_wait(&cond, &wait_mutex);
}
pthread_mutex_unlock(&wait_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&wait_mutex);
printf("thread %d finishes initialization\n", idx);
/*
* we have to initialize senders here
* because we need to make sure other threads have
* initialized all queues.
*/
/* there is a request sender for each node. */
req_senders = (msg_sender<io_request> **) numa_alloc_local(
sizeof(msg_sender<io_request> *) * num_groups);
for (int i = 0; i < num_groups; i++) {
bulk_queue<io_request> *queues[groups[i].nthreads];
for (int j = 0; j < groups[i].nthreads; j++)
queues[j] = groups[i].threads[j]->request_queue;
req_senders[i] = new msg_sender<io_request>(BUF_SIZE, queues, groups[i].nthreads);
}
/*
* there is a reply sender for each thread.
* therefore, there is only one queue for a sender.
*/
reply_senders = (msg_sender<io_reply> **) numa_alloc_local(
sizeof(msg_sender<io_reply> *) * nthreads);
int idx = 0;
for (int i = 0; i < num_groups; i++) {
for (int j = 0; j < groups[i].nthreads; j++) {
bulk_queue<io_reply> *queues[1];
assert(idx == groups[i].threads[j]->idx);
queues[0] = groups[i].threads[j]->reply_queue;
reply_senders[idx++] = new msg_sender<io_reply>(BUF_SIZE, queues, 1);
}
}
return 0;
}
part_global_cached_private::part_global_cached_private(int num_groups,
const char *names[], int num, long size, int idx,
long cache_size, int entry_size, int cache_type,
memory_manager *manager): global_cached_private(names,
num, size, idx, entry_size) {
this->manager = manager;
remote_reads = 0;
// assert(nthreads % num_groups == 0);
this->num_groups = num_groups;
this->group_idx = group_id(idx, num_groups);
this->cache_size = cache_size / num_groups;
this->cache_type = cache_type;
processed_requests = 0;
finished_threads = 0;
req_senders = NULL;
reply_senders = NULL;
printf("cache is partitioned\n");
printf("thread id: %d, group id: %d, num groups: %d\n", idx, group_idx, num_groups);
if (groups == NULL) {
pthread_mutex_init(&init_mutex, NULL);
pthread_mutex_init(&wait_mutex, NULL);
pthread_cond_init(&cond, NULL);
num_finish_init = 0;
groups = new thread_group[num_groups];
for (int i = 0; i < num_groups; i++) {
groups[i].id = i;
groups[i].nthreads = nthreads / num_groups;
if (nthreads % num_groups)
groups[i].nthreads++;
groups[i].threads = new part_global_cached_private*[groups[i].nthreads];
groups[i].cache = NULL;
for (int j = 0; j < groups[i].nthreads; j++)
groups[i].threads[j] = NULL;
}
}
/* assign a thread to a group. */
thread_group *group = NULL;
for (int i = 0; i < num_groups; i++) {
if (groups[i].id == group_idx) {
group = &groups[i];
break;
}
}
assert (group);
int i = thread_idx(idx, num_groups);
assert (group->threads[i] == NULL);
group->threads[i] = this;
}
/**
* send replies to the thread that sent the requests.
*/
int part_global_cached_private::reply(io_request *requests,
io_reply *replies, int num) {
for (int i = 0; i < num; i++) {
part_global_cached_private *thread
= (part_global_cached_private *) requests[i].get_thread();
int thread_id = thread->idx;
int num_sent = reply_senders[thread_id]->send_cached(&replies[i]);
if (num_sent == 0) {
// TODO the buffer is already full.
// discard the request for now.
printf("the reply buffer for thread %d is already full\n", thread_id);
continue;
}
}
for (int i = 0; i < nthreads; i++)
reply_senders[i]->flush();
return 0;
}
/* distribute requests to nodes. */
void part_global_cached_private::distribute_reqs(io_request *requests, int num) {
for (int i = 0; i < num; i++) {
int idx = hash_req(&requests[i]);
assert (idx < num_groups);
if (idx != get_group_id())
remote_reads++;
int num_sent = req_senders[idx]->send_cached(&requests[i]);
// TODO if we fail to send the requests to the specific node,
// we should rehash it and give it to another node.
if (num_sent == 0) {
// TODO the buffer is already full.
// discard the request for now.
printf("the request buffer for group %d is already full\n", idx);
continue;
}
}
for (int i = 0; i < num_groups; i++)
req_senders[i]->flush();
}
/* process the requests sent to this thread */
int part_global_cached_private::process_requests(int max_nreqs) {
int num_processed = 0;
io_request local_reqs[BUF_SIZE];
io_reply local_replies[BUF_SIZE];
while (!request_queue->is_empty() && num_processed < max_nreqs) {
int num = request_queue->fetch(local_reqs, BUF_SIZE);
for (int i = 0; i < num; i++) {
io_request *req = &local_reqs[i];
// TODO will it be better if I collect all data
// and send them back to the initiator in blocks?
int access_method = req->get_access_method();
assert(req->get_offset() >= 0);
int ret = global_cached_private::access(req->get_buf(),
req->get_offset(), req->get_size(), access_method);
local_replies[i] = io_reply(req, ret >= 0, errno);
}
num_processed += num;
reply(local_reqs, local_replies, num);
}
processed_requests += num_processed;
return num_processed;
}
/*
* process the replies and return the number
* of bytes that have been accessed.
*/
int part_global_cached_private::process_replies(int max_nreplies) {
int num_processed = 0;
io_reply local_replies[BUF_SIZE];
int size = 0;
while(!reply_queue->is_empty() && num_processed < max_nreplies) {
int num = reply_queue->fetch(local_replies, BUF_SIZE);
for (int i = 0; i < num; i++) {
io_reply *reply = &local_replies[i];
int ret = process_reply(reply);
if (ret >= 0)
size += ret;
}
num_processed += num;
}
return num_processed;
}
int part_global_cached_private::process_reply(io_reply *reply) {
extern bool verify_read_content;
int access_method = reply->get_access_method();
int ret = -1;
if (reply->is_success()) {
read_bytes += reply->get_size();
if (access_method == READ && verify_read_content) {
assert(*(unsigned long *) reply->get_buf()
== reply->get_offset() / sizeof(long));
}
ret = reply->get_size();
buf->free_entry(reply->get_buf());
}
else {
fprintf(stderr, "access error: %s\n",
strerror(reply->get_status()));
}
return ret;
}
ssize_t part_global_cached_private::access(io_request *requests,
int num, int access_method) {
distribute_reqs(requests, num);
/*
* let's process up to twice as many requests as demanded by the upper layer,
* I hope this can help load balancing problem.
*/
int num_recv = 0;
/* we need to process them at least once. */
process_requests(num * 2);
num_recv += process_replies(num * 4);
while (buf->is_full()) {
process_requests(num * 2);
num_recv += process_replies(num * 4);
}
return num_recv;
}
void part_global_cached_private::cleanup() {
int num = 0;
printf("thread %d: start to clean up\n", idx);
for (int i = 0; i < num_groups; i++) {
for (int j = 0; j < groups[i].nthreads; j++)
if (groups[i].threads[j])
__sync_fetch_and_add(&groups[i].threads[j]->finished_threads, 1);
}
while (!request_queue->is_empty()
|| !reply_queue->is_empty()
/*
* if finished_threads == nthreads,
* then all threads have reached the point.
*/
|| finished_threads < nthreads) {
process_requests(200);
process_replies(200);
num++;
}
printf("thread %d processed %ld requests\n", idx, processed_requests);
}
thread_group *part_global_cached_private::groups;
pthread_mutex_t part_global_cached_private::init_mutex;
int part_global_cached_private::num_finish_init;
pthread_mutex_t part_global_cached_private::wait_mutex;
pthread_cond_t part_global_cached_private::cond;
<commit_msg>bind threads to nodes only when NUM_NODES > 1<commit_after>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include "cache.h"
#include "associative_cache.h"
#include "global_cached_private.h"
#include "part_global_cached_private.h"
int part_global_cached_private::thread_init() {
#if NUM_NODES > 1
/* let's bind the thread to a specific node first. */
struct bitmask *nodemask = numa_allocate_cpumask();
numa_bitmask_clearall(nodemask);
printf("thread %d is associated to node %d\n", idx, get_group_id());
numa_bitmask_setbit(nodemask, get_group_id());
numa_bind(nodemask);
numa_set_strict(1);
numa_set_bind_policy(1);
#endif
read_private::thread_init();
request_queue = new bulk_queue<io_request>(REQ_QUEUE_SIZE);
reply_queue = new bulk_queue<io_reply>(REPLY_QUEUE_SIZE);
/*
* there is a global lock for all threads.
* so this lock makes sure cache initialization is serialized
*/
pthread_mutex_lock(&init_mutex);
thread_group *group = &groups[group_idx];
if (group->cache == NULL) {
/* this allocates all pages for the cache. */
page::allocate_cache(cache_size);
group->cache = global_cached_private::create_cache(cache_type, cache_size, manager);
}
num_finish_init++;
pthread_mutex_unlock(&init_mutex);
pthread_mutex_lock(&wait_mutex);
while (num_finish_init < nthreads) {
pthread_cond_wait(&cond, &wait_mutex);
}
pthread_mutex_unlock(&wait_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&wait_mutex);
printf("thread %d finishes initialization\n", idx);
/*
* we have to initialize senders here
* because we need to make sure other threads have
* initialized all queues.
*/
/* there is a request sender for each node. */
req_senders = (msg_sender<io_request> **) numa_alloc_local(
sizeof(msg_sender<io_request> *) * num_groups);
for (int i = 0; i < num_groups; i++) {
bulk_queue<io_request> *queues[groups[i].nthreads];
for (int j = 0; j < groups[i].nthreads; j++)
queues[j] = groups[i].threads[j]->request_queue;
req_senders[i] = new msg_sender<io_request>(BUF_SIZE, queues, groups[i].nthreads);
}
/*
* there is a reply sender for each thread.
* therefore, there is only one queue for a sender.
*/
reply_senders = (msg_sender<io_reply> **) numa_alloc_local(
sizeof(msg_sender<io_reply> *) * nthreads);
int idx = 0;
for (int i = 0; i < num_groups; i++) {
for (int j = 0; j < groups[i].nthreads; j++) {
bulk_queue<io_reply> *queues[1];
assert(idx == groups[i].threads[j]->idx);
queues[0] = groups[i].threads[j]->reply_queue;
reply_senders[idx++] = new msg_sender<io_reply>(BUF_SIZE, queues, 1);
}
}
return 0;
}
part_global_cached_private::part_global_cached_private(int num_groups,
const char *names[], int num, long size, int idx,
long cache_size, int entry_size, int cache_type,
memory_manager *manager): global_cached_private(names,
num, size, idx, entry_size) {
this->manager = manager;
remote_reads = 0;
// assert(nthreads % num_groups == 0);
this->num_groups = num_groups;
this->group_idx = group_id(idx, num_groups);
this->cache_size = cache_size / num_groups;
this->cache_type = cache_type;
processed_requests = 0;
finished_threads = 0;
req_senders = NULL;
reply_senders = NULL;
printf("cache is partitioned\n");
printf("thread id: %d, group id: %d, num groups: %d\n", idx, group_idx, num_groups);
if (groups == NULL) {
pthread_mutex_init(&init_mutex, NULL);
pthread_mutex_init(&wait_mutex, NULL);
pthread_cond_init(&cond, NULL);
num_finish_init = 0;
groups = new thread_group[num_groups];
for (int i = 0; i < num_groups; i++) {
groups[i].id = i;
groups[i].nthreads = nthreads / num_groups;
if (nthreads % num_groups)
groups[i].nthreads++;
groups[i].threads = new part_global_cached_private*[groups[i].nthreads];
groups[i].cache = NULL;
for (int j = 0; j < groups[i].nthreads; j++)
groups[i].threads[j] = NULL;
}
}
/* assign a thread to a group. */
thread_group *group = NULL;
for (int i = 0; i < num_groups; i++) {
if (groups[i].id == group_idx) {
group = &groups[i];
break;
}
}
assert (group);
int i = thread_idx(idx, num_groups);
assert (group->threads[i] == NULL);
group->threads[i] = this;
}
/**
* send replies to the thread that sent the requests.
*/
int part_global_cached_private::reply(io_request *requests,
io_reply *replies, int num) {
for (int i = 0; i < num; i++) {
part_global_cached_private *thread
= (part_global_cached_private *) requests[i].get_thread();
int thread_id = thread->idx;
int num_sent = reply_senders[thread_id]->send_cached(&replies[i]);
if (num_sent == 0) {
// TODO the buffer is already full.
// discard the request for now.
printf("the reply buffer for thread %d is already full\n", thread_id);
continue;
}
}
for (int i = 0; i < nthreads; i++)
reply_senders[i]->flush();
return 0;
}
/* distribute requests to nodes. */
void part_global_cached_private::distribute_reqs(io_request *requests, int num) {
for (int i = 0; i < num; i++) {
int idx = hash_req(&requests[i]);
assert (idx < num_groups);
if (idx != get_group_id())
remote_reads++;
int num_sent = req_senders[idx]->send_cached(&requests[i]);
// TODO if we fail to send the requests to the specific node,
// we should rehash it and give it to another node.
if (num_sent == 0) {
// TODO the buffer is already full.
// discard the request for now.
printf("the request buffer for group %d is already full\n", idx);
continue;
}
}
for (int i = 0; i < num_groups; i++)
req_senders[i]->flush();
}
/* process the requests sent to this thread */
int part_global_cached_private::process_requests(int max_nreqs) {
int num_processed = 0;
io_request local_reqs[BUF_SIZE];
io_reply local_replies[BUF_SIZE];
while (!request_queue->is_empty() && num_processed < max_nreqs) {
int num = request_queue->fetch(local_reqs, BUF_SIZE);
for (int i = 0; i < num; i++) {
io_request *req = &local_reqs[i];
// TODO will it be better if I collect all data
// and send them back to the initiator in blocks?
int access_method = req->get_access_method();
assert(req->get_offset() >= 0);
int ret = global_cached_private::access(req->get_buf(),
req->get_offset(), req->get_size(), access_method);
local_replies[i] = io_reply(req, ret >= 0, errno);
}
num_processed += num;
reply(local_reqs, local_replies, num);
}
processed_requests += num_processed;
return num_processed;
}
/*
* process the replies and return the number
* of bytes that have been accessed.
*/
int part_global_cached_private::process_replies(int max_nreplies) {
int num_processed = 0;
io_reply local_replies[BUF_SIZE];
int size = 0;
while(!reply_queue->is_empty() && num_processed < max_nreplies) {
int num = reply_queue->fetch(local_replies, BUF_SIZE);
for (int i = 0; i < num; i++) {
io_reply *reply = &local_replies[i];
int ret = process_reply(reply);
if (ret >= 0)
size += ret;
}
num_processed += num;
}
return num_processed;
}
int part_global_cached_private::process_reply(io_reply *reply) {
extern bool verify_read_content;
int access_method = reply->get_access_method();
int ret = -1;
if (reply->is_success()) {
read_bytes += reply->get_size();
if (access_method == READ && verify_read_content) {
assert(*(unsigned long *) reply->get_buf()
== reply->get_offset() / sizeof(long));
}
ret = reply->get_size();
buf->free_entry(reply->get_buf());
}
else {
fprintf(stderr, "access error: %s\n",
strerror(reply->get_status()));
}
return ret;
}
ssize_t part_global_cached_private::access(io_request *requests,
int num, int access_method) {
distribute_reqs(requests, num);
/*
* let's process up to twice as many requests as demanded by the upper layer,
* I hope this can help load balancing problem.
*/
int num_recv = 0;
/* we need to process them at least once. */
process_requests(num * 2);
num_recv += process_replies(num * 4);
while (buf->is_full()) {
process_requests(num * 2);
num_recv += process_replies(num * 4);
}
return num_recv;
}
void part_global_cached_private::cleanup() {
int num = 0;
printf("thread %d: start to clean up\n", idx);
for (int i = 0; i < num_groups; i++) {
for (int j = 0; j < groups[i].nthreads; j++)
if (groups[i].threads[j])
__sync_fetch_and_add(&groups[i].threads[j]->finished_threads, 1);
}
while (!request_queue->is_empty()
|| !reply_queue->is_empty()
/*
* if finished_threads == nthreads,
* then all threads have reached the point.
*/
|| finished_threads < nthreads) {
process_requests(200);
process_replies(200);
num++;
}
printf("thread %d processed %ld requests\n", idx, processed_requests);
}
thread_group *part_global_cached_private::groups;
pthread_mutex_t part_global_cached_private::init_mutex;
int part_global_cached_private::num_finish_init;
pthread_mutex_t part_global_cached_private::wait_mutex;
pthread_cond_t part_global_cached_private::cond;
<|endoftext|> |
<commit_before>//===-- sanitizer_posix.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements POSIX-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_LINUX || SANITIZER_MAC
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_stacktrace.h"
#include <sys/mman.h>
#include <signal.h>
namespace __sanitizer {
// ------------- sanitizer_common.h
uptr GetMmapGranularity() {
return GetPageSize();
}
uptr GetMaxVirtualAddress() {
#if SANITIZER_WORDSIZE == 64
# if defined(__powerpc64__)
// On PowerPC64 we have two different address space layouts: 44- and 46-bit.
// We somehow need to figure our which one we are using now and choose
// one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
// Note that with 'ulimit -s unlimited' the stack is moved away from the top
// of the address space, so simply checking the stack address is not enough.
return (1ULL << 44) - 1; // 0x00000fffffffffffUL
# else
return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
# endif
#else // SANITIZER_WORDSIZE == 32
// FIXME: We can probably lower this on Android?
return (1ULL << 32) - 1; // 0xffffffff;
#endif // SANITIZER_WORDSIZE
}
void *MmapOrDie(uptr size, const char *mem_type) {
size = RoundUpTo(size, GetPageSizeCached());
uptr res = internal_mmap(0, size,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
int reserrno;
if (internal_iserror(res, &reserrno)) {
static int recursion_count;
if (recursion_count) {
// The Report() and CHECK calls below may call mmap recursively and fail.
// If we went into recursion, just die.
RawWrite("ERROR: Failed to mmap\n");
Die();
}
recursion_count++;
Report("ERROR: %s failed to allocate 0x%zx (%zd) bytes of %s: %d\n",
SanitizerToolName, size, size, mem_type, reserrno);
DumpProcessMap();
CHECK("unable to mmap" && 0);
}
return (void *)res;
}
void UnmapOrDie(void *addr, uptr size) {
if (!addr || !size) return;
uptr res = internal_munmap(addr, size);
if (internal_iserror(res)) {
Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
SanitizerToolName, size, size, addr);
CHECK("unable to unmap" && 0);
}
}
void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap(0,
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno)) {
Report("ERROR: "
"%s failed to allocate noreserve 0x%zx (%zd) bytes for '%s' (%d)\n",
SanitizerToolName, size, size, mem_type, reserrno);
CHECK("unable to mmap" && 0);
}
return (void *)p;
}
void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno))
Report("ERROR: "
"%s failed to allocate 0x%zx (%zd) bytes at address %zu (%d)\n",
SanitizerToolName, size, size, fixed_addr, reserrno);
return (void *)p;
}
void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno)) {
Report("ERROR:"
" %s failed to allocate 0x%zx (%zd) bytes at address %zu (%d)\n",
SanitizerToolName, size, size, fixed_addr, reserrno);
CHECK("unable to mmap" && 0);
}
return (void *)p;
}
void *Mprotect(uptr fixed_addr, uptr size) {
return (void *)internal_mmap((void*)fixed_addr, size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED |
MAP_NORESERVE, -1, 0);
}
void *MapFileToMemory(const char *file_name, uptr *buff_size) {
uptr openrv = OpenFile(file_name, false);
CHECK(!internal_iserror(openrv));
fd_t fd = openrv;
uptr fsize = internal_filesize(fd);
CHECK_NE(fsize, (uptr)-1);
CHECK_GT(fsize, 0);
*buff_size = RoundUpTo(fsize, GetPageSizeCached());
uptr map = internal_mmap(0, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
return internal_iserror(map) ? 0 : (void *)map;
}
static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
uptr start2, uptr end2) {
CHECK(start1 <= end1);
CHECK(start2 <= end2);
return (end1 < start2) || (end2 < start1);
}
// FIXME: this is thread-unsafe, but should not cause problems most of the time.
// When the shadow is mapped only a single thread usually exists (plus maybe
// several worker threads on Mac, which aren't expected to map big chunks of
// memory).
bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
uptr start, end;
while (proc_maps.Next(&start, &end,
/*offset*/0, /*filename*/0, /*filename_size*/0,
/*protection*/0)) {
if (!IntervalsAreSeparate(start, end, range_start, range_end))
return false;
}
return true;
}
void DumpProcessMap() {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
uptr start, end;
const sptr kBufSize = 4095;
char *filename = (char*)MmapOrDie(kBufSize, __FUNCTION__);
Report("Process memory map follows:\n");
while (proc_maps.Next(&start, &end, /* file_offset */0,
filename, kBufSize, /* protection */0)) {
Printf("\t%p-%p\t%s\n", (void*)start, (void*)end, filename);
}
Report("End of process memory map.\n");
UnmapOrDie(filename, kBufSize);
}
const char *GetPwd() {
return GetEnv("PWD");
}
char *FindPathToBinary(const char *name) {
const char *path = GetEnv("PATH");
if (!path)
return 0;
uptr name_len = internal_strlen(name);
InternalScopedBuffer<char> buffer(kMaxPathLength);
const char *beg = path;
while (true) {
const char *end = internal_strchrnul(beg, ':');
uptr prefix_len = end - beg;
if (prefix_len + name_len + 2 <= kMaxPathLength) {
internal_memcpy(buffer.data(), beg, prefix_len);
buffer[prefix_len] = '/';
internal_memcpy(&buffer[prefix_len + 1], name, name_len);
buffer[prefix_len + 1 + name_len] = '\0';
if (FileExists(buffer.data()))
return internal_strdup(buffer.data());
}
if (*end == '\0') break;
beg = end + 1;
}
return 0;
}
void MaybeOpenReportFile() {
if (!log_to_file) return;
uptr pid = internal_getpid();
// If in tracer, use the parent's file.
if (pid == stoptheworld_tracer_pid)
pid = stoptheworld_tracer_ppid;
if (report_fd_pid == pid) return;
InternalScopedBuffer<char> report_path_full(4096);
internal_snprintf(report_path_full.data(), report_path_full.size(),
"%s.%zu", report_path_prefix, pid);
uptr openrv = OpenFile(report_path_full.data(), true);
if (internal_iserror(openrv)) {
report_fd = kStderrFd;
log_to_file = false;
Report("ERROR: Can't open file: %s\n", report_path_full.data());
Die();
}
if (report_fd != kInvalidFd) {
// We're in the child. Close the parent's log.
internal_close(report_fd);
}
report_fd = openrv;
report_fd_pid = pid;
}
void RawWrite(const char *buffer) {
static const char *kRawWriteError =
"RawWrite can't output requested buffer!\n";
uptr length = (uptr)internal_strlen(buffer);
MaybeOpenReportFile();
if (length != internal_write(report_fd, buffer, length)) {
internal_write(report_fd, kRawWriteError, internal_strlen(kRawWriteError));
Die();
}
}
bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
uptr s, e, off, prot;
InternalScopedString buff(4096);
MemoryMappingLayout proc_maps(/*cache_enabled*/false);
while (proc_maps.Next(&s, &e, &off, buff.data(), buff.size(), &prot)) {
if ((prot & MemoryMappingLayout::kProtectionExecute) != 0
&& internal_strcmp(module, buff.data()) == 0) {
*start = s;
*end = e;
return true;
}
}
return false;
}
} // namespace __sanitizer
#endif // SANITIZER_LINUX || SANITIZER_MAC
<commit_msg>[ASan] Remove an accidentally added include of signal.h<commit_after>//===-- sanitizer_posix.cc ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries and implements POSIX-specific functions from
// sanitizer_libc.h.
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_LINUX || SANITIZER_MAC
#include "sanitizer_common.h"
#include "sanitizer_libc.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_stacktrace.h"
#include <sys/mman.h>
namespace __sanitizer {
// ------------- sanitizer_common.h
uptr GetMmapGranularity() {
return GetPageSize();
}
uptr GetMaxVirtualAddress() {
#if SANITIZER_WORDSIZE == 64
# if defined(__powerpc64__)
// On PowerPC64 we have two different address space layouts: 44- and 46-bit.
// We somehow need to figure our which one we are using now and choose
// one of 0x00000fffffffffffUL and 0x00003fffffffffffUL.
// Note that with 'ulimit -s unlimited' the stack is moved away from the top
// of the address space, so simply checking the stack address is not enough.
return (1ULL << 44) - 1; // 0x00000fffffffffffUL
# else
return (1ULL << 47) - 1; // 0x00007fffffffffffUL;
# endif
#else // SANITIZER_WORDSIZE == 32
// FIXME: We can probably lower this on Android?
return (1ULL << 32) - 1; // 0xffffffff;
#endif // SANITIZER_WORDSIZE
}
void *MmapOrDie(uptr size, const char *mem_type) {
size = RoundUpTo(size, GetPageSizeCached());
uptr res = internal_mmap(0, size,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
int reserrno;
if (internal_iserror(res, &reserrno)) {
static int recursion_count;
if (recursion_count) {
// The Report() and CHECK calls below may call mmap recursively and fail.
// If we went into recursion, just die.
RawWrite("ERROR: Failed to mmap\n");
Die();
}
recursion_count++;
Report("ERROR: %s failed to allocate 0x%zx (%zd) bytes of %s: %d\n",
SanitizerToolName, size, size, mem_type, reserrno);
DumpProcessMap();
CHECK("unable to mmap" && 0);
}
return (void *)res;
}
void UnmapOrDie(void *addr, uptr size) {
if (!addr || !size) return;
uptr res = internal_munmap(addr, size);
if (internal_iserror(res)) {
Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
SanitizerToolName, size, size, addr);
CHECK("unable to unmap" && 0);
}
}
void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap(0,
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno)) {
Report("ERROR: "
"%s failed to allocate noreserve 0x%zx (%zd) bytes for '%s' (%d)\n",
SanitizerToolName, size, size, mem_type, reserrno);
CHECK("unable to mmap" && 0);
}
return (void *)p;
}
void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno))
Report("ERROR: "
"%s failed to allocate 0x%zx (%zd) bytes at address %zu (%d)\n",
SanitizerToolName, size, size, fixed_addr, reserrno);
return (void *)p;
}
void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
uptr PageSize = GetPageSizeCached();
uptr p = internal_mmap((void*)(fixed_addr & ~(PageSize - 1)),
RoundUpTo(size, PageSize),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED,
-1, 0);
int reserrno;
if (internal_iserror(p, &reserrno)) {
Report("ERROR:"
" %s failed to allocate 0x%zx (%zd) bytes at address %zu (%d)\n",
SanitizerToolName, size, size, fixed_addr, reserrno);
CHECK("unable to mmap" && 0);
}
return (void *)p;
}
void *Mprotect(uptr fixed_addr, uptr size) {
return (void *)internal_mmap((void*)fixed_addr, size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_FIXED |
MAP_NORESERVE, -1, 0);
}
void *MapFileToMemory(const char *file_name, uptr *buff_size) {
uptr openrv = OpenFile(file_name, false);
CHECK(!internal_iserror(openrv));
fd_t fd = openrv;
uptr fsize = internal_filesize(fd);
CHECK_NE(fsize, (uptr)-1);
CHECK_GT(fsize, 0);
*buff_size = RoundUpTo(fsize, GetPageSizeCached());
uptr map = internal_mmap(0, *buff_size, PROT_READ, MAP_PRIVATE, fd, 0);
return internal_iserror(map) ? 0 : (void *)map;
}
static inline bool IntervalsAreSeparate(uptr start1, uptr end1,
uptr start2, uptr end2) {
CHECK(start1 <= end1);
CHECK(start2 <= end2);
return (end1 < start2) || (end2 < start1);
}
// FIXME: this is thread-unsafe, but should not cause problems most of the time.
// When the shadow is mapped only a single thread usually exists (plus maybe
// several worker threads on Mac, which aren't expected to map big chunks of
// memory).
bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
uptr start, end;
while (proc_maps.Next(&start, &end,
/*offset*/0, /*filename*/0, /*filename_size*/0,
/*protection*/0)) {
if (!IntervalsAreSeparate(start, end, range_start, range_end))
return false;
}
return true;
}
void DumpProcessMap() {
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
uptr start, end;
const sptr kBufSize = 4095;
char *filename = (char*)MmapOrDie(kBufSize, __FUNCTION__);
Report("Process memory map follows:\n");
while (proc_maps.Next(&start, &end, /* file_offset */0,
filename, kBufSize, /* protection */0)) {
Printf("\t%p-%p\t%s\n", (void*)start, (void*)end, filename);
}
Report("End of process memory map.\n");
UnmapOrDie(filename, kBufSize);
}
const char *GetPwd() {
return GetEnv("PWD");
}
char *FindPathToBinary(const char *name) {
const char *path = GetEnv("PATH");
if (!path)
return 0;
uptr name_len = internal_strlen(name);
InternalScopedBuffer<char> buffer(kMaxPathLength);
const char *beg = path;
while (true) {
const char *end = internal_strchrnul(beg, ':');
uptr prefix_len = end - beg;
if (prefix_len + name_len + 2 <= kMaxPathLength) {
internal_memcpy(buffer.data(), beg, prefix_len);
buffer[prefix_len] = '/';
internal_memcpy(&buffer[prefix_len + 1], name, name_len);
buffer[prefix_len + 1 + name_len] = '\0';
if (FileExists(buffer.data()))
return internal_strdup(buffer.data());
}
if (*end == '\0') break;
beg = end + 1;
}
return 0;
}
void MaybeOpenReportFile() {
if (!log_to_file) return;
uptr pid = internal_getpid();
// If in tracer, use the parent's file.
if (pid == stoptheworld_tracer_pid)
pid = stoptheworld_tracer_ppid;
if (report_fd_pid == pid) return;
InternalScopedBuffer<char> report_path_full(4096);
internal_snprintf(report_path_full.data(), report_path_full.size(),
"%s.%zu", report_path_prefix, pid);
uptr openrv = OpenFile(report_path_full.data(), true);
if (internal_iserror(openrv)) {
report_fd = kStderrFd;
log_to_file = false;
Report("ERROR: Can't open file: %s\n", report_path_full.data());
Die();
}
if (report_fd != kInvalidFd) {
// We're in the child. Close the parent's log.
internal_close(report_fd);
}
report_fd = openrv;
report_fd_pid = pid;
}
void RawWrite(const char *buffer) {
static const char *kRawWriteError =
"RawWrite can't output requested buffer!\n";
uptr length = (uptr)internal_strlen(buffer);
MaybeOpenReportFile();
if (length != internal_write(report_fd, buffer, length)) {
internal_write(report_fd, kRawWriteError, internal_strlen(kRawWriteError));
Die();
}
}
bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
uptr s, e, off, prot;
InternalScopedString buff(4096);
MemoryMappingLayout proc_maps(/*cache_enabled*/false);
while (proc_maps.Next(&s, &e, &off, buff.data(), buff.size(), &prot)) {
if ((prot & MemoryMappingLayout::kProtectionExecute) != 0
&& internal_strcmp(module, buff.data()) == 0) {
*start = s;
*end = e;
return true;
}
}
return false;
}
} // namespace __sanitizer
#endif // SANITIZER_LINUX || SANITIZER_MAC
<|endoftext|> |
<commit_before>//DEFINITION OF A FEW CONSTANTS
AliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC()
{
// Creates HighPtQAMC analysis task and adds it to the analysis manager.
// A. Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskPWG4HighPtQMC", "No analysis manager to connect to.");
return NULL;
}
// B. Check the analysis type using the event handlers connected to the analysis
// manager. The availability of MC handler can also be checked here.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddPWG4TaskHighPtQAMC", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
const char *analysisType = "ESD";//"TPC"
// C. Create the task, add it to manager.
//===========================================================================
//CREATE THE CUTS -----------------------------------------------
//Use AliESDtrackCuts
AliESDtrackCuts *trackCuts = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts");
//Standard Cuts
trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1e10);
trackCuts->SetRequireITSRefit(kFALSE);
AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts with ITSrefit");
//Standard Cuts
trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1e10);
trackCuts->SetRequireITSRefit(kTRUE);
//Create the task
AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC("AliPWG4HighPtQAMC");
taskPWG4QAMC->SetCuts(trackCuts);
taskPWG4QAMC->SetCutsITS(trackCutsITS);
// E. Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
//------ input data ------
// AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
printf("Create output containers \n");
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG4_HighPtQAMC";
//char *outputfile = "outputAliPWG4HighPtQAMCTestTrain.root";
AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer("qa_histsMC", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);
AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer("qa_histsMCITS", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);
mgr->AddTask(taskPWG4QAMC);
mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0);
mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2);
// Return task pointer at the end
return taskPWG4QAMC;
}
<commit_msg>bug fix in definition of track cuts (Marta)<commit_after>//DEFINITION OF A FEW CONSTANTS
AliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC()
{
// Creates HighPtQAMC analysis task and adds it to the analysis manager.
// A. Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskPWG4HighPtQMC", "No analysis manager to connect to.");
return NULL;
}
// B. Check the analysis type using the event handlers connected to the analysis
// manager. The availability of MC handler can also be checked here.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddPWG4TaskHighPtQAMC", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
const char *analysisType = "ESD";//"TPC"
// C. Create the task, add it to manager.
//===========================================================================
//CREATE THE CUTS -----------------------------------------------
//Use AliESDtrackCuts
AliESDtrackCuts *trackCuts = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts");
//Standard Cuts
trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1e10);
trackCuts->SetRequireITSRefit(kFALSE);
AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts with ITSrefit");
//Standard Cuts
trackCutsITS=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection
trackCutsITS->SetEtaRange(-0.9,0.9);
trackCutsITS->SetPtRange(0.15, 1e10);
trackCutsITS->SetRequireITSRefit(kTRUE);
//Create the task
AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC("AliPWG4HighPtQAMC");
taskPWG4QAMC->SetCuts(trackCuts);
taskPWG4QAMC->SetCutsITS(trackCutsITS);
// E. Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
//------ input data ------
// AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
printf("Create output containers \n");
TString outputfile = AliAnalysisManager::GetCommonFileName();
outputfile += ":PWG4_HighPtQAMC";
//char *outputfile = "outputAliPWG4HighPtQAMCTestTrain.root";
AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer("qa_histsMC", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);
AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer("qa_histsMCITS", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);
mgr->AddTask(taskPWG4QAMC);
mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0);
mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2);
// Return task pointer at the end
return taskPWG4QAMC;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/utility/ivf_file_writer.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/thread.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/test/testsupport/fileutils.h"
namespace webrtc {
namespace {
static const int kHeaderSize = 32;
static const int kFrameHeaderSize = 12;
static uint8_t dummy_payload[4] = {0, 1, 2, 3};
static const int kMaxFileRetries = 5;
} // namespace
class IvfFileWriterTest : public ::testing::Test {
protected:
void SetUp() override {
const int64_t start_id =
reinterpret_cast<int64_t>(this) ^ rtc::TimeMicros();
int64_t id = start_id;
do {
std::ostringstream oss;
oss << test::OutputPath() << "ivf_test_file_" << id++ << ".ivf";
file_name_ = oss.str();
} while (id < start_id + 100 && FileExists(false));
ASSERT_LT(id, start_id + 100);
}
bool WriteDummyTestFrames(int width,
int height,
int num_frames,
bool use_capture_tims_ms) {
EncodedImage frame;
frame._buffer = dummy_payload;
frame._encodedWidth = width;
frame._encodedHeight = height;
for (int i = 1; i <= num_frames; ++i) {
frame._length = i % sizeof(dummy_payload);
if (use_capture_tims_ms) {
frame.capture_time_ms_ = i;
} else {
frame._timeStamp = i;
}
if (!file_writer_->WriteFrame(frame))
return false;
}
return true;
}
void VerifyIvfHeader(FileWrapper* file,
const uint8_t fourcc[4],
int width,
int height,
uint32_t num_frames,
bool use_capture_tims_ms) {
ASSERT_TRUE(file->is_open());
uint8_t data[kHeaderSize];
ASSERT_EQ(kHeaderSize, file->Read(data, kHeaderSize));
uint8_t dkif[4] = {'D', 'K', 'I', 'F'};
EXPECT_EQ(0, memcmp(dkif, data, 4));
EXPECT_EQ(0u, ByteReader<uint16_t>::ReadLittleEndian(&data[4]));
EXPECT_EQ(32u, ByteReader<uint16_t>::ReadLittleEndian(&data[6]));
EXPECT_EQ(0, memcmp(fourcc, &data[8], 4));
EXPECT_EQ(width, ByteReader<uint16_t>::ReadLittleEndian(&data[12]));
EXPECT_EQ(height, ByteReader<uint16_t>::ReadLittleEndian(&data[14]));
EXPECT_EQ(use_capture_tims_ms ? 1000u : 90000u,
ByteReader<uint32_t>::ReadLittleEndian(&data[16]));
EXPECT_EQ(1u, ByteReader<uint32_t>::ReadLittleEndian(&data[20]));
EXPECT_EQ(num_frames, ByteReader<uint32_t>::ReadLittleEndian(&data[24]));
EXPECT_EQ(0u, ByteReader<uint32_t>::ReadLittleEndian(&data[28]));
}
void VerifyDummyTestFrames(FileWrapper* file, uint32_t num_frames) {
const int kMaxFrameSize = 4;
for (uint32_t i = 1; i <= num_frames; ++i) {
uint8_t frame_header[kFrameHeaderSize];
ASSERT_EQ(kFrameHeaderSize, file->Read(frame_header, kFrameHeaderSize));
uint32_t frame_length =
ByteReader<uint32_t>::ReadLittleEndian(&frame_header[0]);
EXPECT_EQ(i % 4, frame_length);
uint64_t timestamp =
ByteReader<uint64_t>::ReadLittleEndian(&frame_header[4]);
EXPECT_EQ(i, timestamp);
uint8_t data[kMaxFrameSize] = {};
ASSERT_EQ(frame_length,
static_cast<uint32_t>(file->Read(data, frame_length)));
EXPECT_EQ(0, memcmp(data, dummy_payload, frame_length));
}
}
void RunBasicFileStructureTest(VideoCodecType codec_type,
const uint8_t fourcc[4],
bool use_capture_tims_ms) {
file_writer_ = IvfFileWriter::Open(file_name_, codec_type);
ASSERT_TRUE(file_writer_.get());
const int kWidth = 320;
const int kHeight = 240;
const int kNumFrames = 257;
EXPECT_TRUE(
WriteDummyTestFrames(kWidth, kHeight, kNumFrames, use_capture_tims_ms));
EXPECT_TRUE(file_writer_->Close());
std::unique_ptr<FileWrapper> out_file(FileWrapper::Create());
ASSERT_TRUE(out_file->OpenFile(file_name_.c_str(), true));
VerifyIvfHeader(out_file.get(), fourcc, kWidth, kHeight, kNumFrames,
use_capture_tims_ms);
VerifyDummyTestFrames(out_file.get(), kNumFrames);
out_file->CloseFile();
bool file_removed = false;
for (int i = 0; i < kMaxFileRetries; ++i) {
file_removed = remove(file_name_.c_str()) == 0;
if (file_removed)
break;
// Couldn't remove file for some reason, wait a sec and try again.
rtc::Thread::SleepMs(1000);
}
EXPECT_TRUE(file_removed);
}
// Check whether file exists or not, and if it does not meet expectation,
// wait a bit and check again, up to kMaxFileRetries times. This is an ugly
// hack to avoid flakiness on certain operating systems where antivirus
// software may unexpectedly lock files and keep them from disappearing or
// being reused.
bool FileExists(bool expected) {
bool file_exists = expected;
std::unique_ptr<FileWrapper> file_wrapper;
int iterations = 0;
do {
if (file_wrapper.get() != nullptr)
rtc::Thread::SleepMs(1000);
file_wrapper.reset(FileWrapper::Create());
file_exists = file_wrapper->OpenFile(file_name_.c_str(), true);
file_wrapper->CloseFile();
} while (file_exists != expected && ++iterations < kMaxFileRetries);
return file_exists;
}
std::string file_name_;
std::unique_ptr<IvfFileWriter> file_writer_;
};
TEST_F(IvfFileWriterTest, RemovesUnusedFile) {
file_writer_ = IvfFileWriter::Open(file_name_, kVideoCodecVP8);
ASSERT_TRUE(file_writer_.get() != nullptr);
EXPECT_TRUE(FileExists(true));
EXPECT_TRUE(file_writer_->Close());
EXPECT_FALSE(FileExists(false));
EXPECT_FALSE(file_writer_->Close()); // Can't close twice.
}
TEST_F(IvfFileWriterTest, WritesBasicVP8FileNtpTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '8', '0'};
RunBasicFileStructureTest(kVideoCodecVP8, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicVP8FileMsTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '8', '0'};
RunBasicFileStructureTest(kVideoCodecVP8, fourcc, true);
}
TEST_F(IvfFileWriterTest, WritesBasicVP9FileNtpTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '9', '0'};
RunBasicFileStructureTest(kVideoCodecVP9, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicVP9FileMsTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '9', '0'};
RunBasicFileStructureTest(kVideoCodecVP9, fourcc, true);
}
TEST_F(IvfFileWriterTest, WritesBasicH264FileNtpTimestamp) {
const uint8_t fourcc[4] = {'H', '2', '6', '4'};
RunBasicFileStructureTest(kVideoCodecH264, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicH264FileMsTimestamp) {
const uint8_t fourcc[4] = {'H', '2', '6', '4'};
RunBasicFileStructureTest(kVideoCodecH264, fourcc, true);
}
} // namespace webrtc
<commit_msg>Use a better method to generate a random ID in IvfFileWriterTest.<commit_after>/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/utility/ivf_file_writer.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/helpers.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/thread.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/test/testsupport/fileutils.h"
namespace webrtc {
namespace {
static const int kHeaderSize = 32;
static const int kFrameHeaderSize = 12;
static uint8_t dummy_payload[4] = {0, 1, 2, 3};
static const int kMaxFileRetries = 5;
} // namespace
class IvfFileWriterTest : public ::testing::Test {
protected:
void SetUp() override {
const uint64_t start_id = rtc::CreateRandomId64();
uint64_t id = start_id;
do {
std::ostringstream oss;
oss << test::OutputPath() << "ivf_test_file_" << id++ << ".ivf";
file_name_ = oss.str();
} while ((id - start_id) < 100u && FileExists(false));
ASSERT_LT(id - start_id, 100u);
}
bool WriteDummyTestFrames(int width,
int height,
int num_frames,
bool use_capture_tims_ms) {
EncodedImage frame;
frame._buffer = dummy_payload;
frame._encodedWidth = width;
frame._encodedHeight = height;
for (int i = 1; i <= num_frames; ++i) {
frame._length = i % sizeof(dummy_payload);
if (use_capture_tims_ms) {
frame.capture_time_ms_ = i;
} else {
frame._timeStamp = i;
}
if (!file_writer_->WriteFrame(frame))
return false;
}
return true;
}
void VerifyIvfHeader(FileWrapper* file,
const uint8_t fourcc[4],
int width,
int height,
uint32_t num_frames,
bool use_capture_tims_ms) {
ASSERT_TRUE(file->is_open());
uint8_t data[kHeaderSize];
ASSERT_EQ(kHeaderSize, file->Read(data, kHeaderSize));
uint8_t dkif[4] = {'D', 'K', 'I', 'F'};
EXPECT_EQ(0, memcmp(dkif, data, 4));
EXPECT_EQ(0u, ByteReader<uint16_t>::ReadLittleEndian(&data[4]));
EXPECT_EQ(32u, ByteReader<uint16_t>::ReadLittleEndian(&data[6]));
EXPECT_EQ(0, memcmp(fourcc, &data[8], 4));
EXPECT_EQ(width, ByteReader<uint16_t>::ReadLittleEndian(&data[12]));
EXPECT_EQ(height, ByteReader<uint16_t>::ReadLittleEndian(&data[14]));
EXPECT_EQ(use_capture_tims_ms ? 1000u : 90000u,
ByteReader<uint32_t>::ReadLittleEndian(&data[16]));
EXPECT_EQ(1u, ByteReader<uint32_t>::ReadLittleEndian(&data[20]));
EXPECT_EQ(num_frames, ByteReader<uint32_t>::ReadLittleEndian(&data[24]));
EXPECT_EQ(0u, ByteReader<uint32_t>::ReadLittleEndian(&data[28]));
}
void VerifyDummyTestFrames(FileWrapper* file, uint32_t num_frames) {
const int kMaxFrameSize = 4;
for (uint32_t i = 1; i <= num_frames; ++i) {
uint8_t frame_header[kFrameHeaderSize];
ASSERT_EQ(kFrameHeaderSize, file->Read(frame_header, kFrameHeaderSize));
uint32_t frame_length =
ByteReader<uint32_t>::ReadLittleEndian(&frame_header[0]);
EXPECT_EQ(i % 4, frame_length);
uint64_t timestamp =
ByteReader<uint64_t>::ReadLittleEndian(&frame_header[4]);
EXPECT_EQ(i, timestamp);
uint8_t data[kMaxFrameSize] = {};
ASSERT_EQ(frame_length,
static_cast<uint32_t>(file->Read(data, frame_length)));
EXPECT_EQ(0, memcmp(data, dummy_payload, frame_length));
}
}
void RunBasicFileStructureTest(VideoCodecType codec_type,
const uint8_t fourcc[4],
bool use_capture_tims_ms) {
file_writer_ = IvfFileWriter::Open(file_name_, codec_type);
ASSERT_TRUE(file_writer_.get());
const int kWidth = 320;
const int kHeight = 240;
const int kNumFrames = 257;
EXPECT_TRUE(
WriteDummyTestFrames(kWidth, kHeight, kNumFrames, use_capture_tims_ms));
EXPECT_TRUE(file_writer_->Close());
std::unique_ptr<FileWrapper> out_file(FileWrapper::Create());
ASSERT_TRUE(out_file->OpenFile(file_name_.c_str(), true));
VerifyIvfHeader(out_file.get(), fourcc, kWidth, kHeight, kNumFrames,
use_capture_tims_ms);
VerifyDummyTestFrames(out_file.get(), kNumFrames);
out_file->CloseFile();
bool file_removed = false;
for (int i = 0; i < kMaxFileRetries; ++i) {
file_removed = remove(file_name_.c_str()) == 0;
if (file_removed)
break;
// Couldn't remove file for some reason, wait a sec and try again.
rtc::Thread::SleepMs(1000);
}
EXPECT_TRUE(file_removed);
}
// Check whether file exists or not, and if it does not meet expectation,
// wait a bit and check again, up to kMaxFileRetries times. This is an ugly
// hack to avoid flakiness on certain operating systems where antivirus
// software may unexpectedly lock files and keep them from disappearing or
// being reused.
bool FileExists(bool expected) {
bool file_exists = expected;
std::unique_ptr<FileWrapper> file_wrapper;
int iterations = 0;
do {
if (file_wrapper.get() != nullptr)
rtc::Thread::SleepMs(1000);
file_wrapper.reset(FileWrapper::Create());
file_exists = file_wrapper->OpenFile(file_name_.c_str(), true);
file_wrapper->CloseFile();
} while (file_exists != expected && ++iterations < kMaxFileRetries);
return file_exists;
}
std::string file_name_;
std::unique_ptr<IvfFileWriter> file_writer_;
};
TEST_F(IvfFileWriterTest, RemovesUnusedFile) {
file_writer_ = IvfFileWriter::Open(file_name_, kVideoCodecVP8);
ASSERT_TRUE(file_writer_.get() != nullptr);
EXPECT_TRUE(FileExists(true));
EXPECT_TRUE(file_writer_->Close());
EXPECT_FALSE(FileExists(false));
EXPECT_FALSE(file_writer_->Close()); // Can't close twice.
}
TEST_F(IvfFileWriterTest, WritesBasicVP8FileNtpTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '8', '0'};
RunBasicFileStructureTest(kVideoCodecVP8, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicVP8FileMsTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '8', '0'};
RunBasicFileStructureTest(kVideoCodecVP8, fourcc, true);
}
TEST_F(IvfFileWriterTest, WritesBasicVP9FileNtpTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '9', '0'};
RunBasicFileStructureTest(kVideoCodecVP9, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicVP9FileMsTimestamp) {
const uint8_t fourcc[4] = {'V', 'P', '9', '0'};
RunBasicFileStructureTest(kVideoCodecVP9, fourcc, true);
}
TEST_F(IvfFileWriterTest, WritesBasicH264FileNtpTimestamp) {
const uint8_t fourcc[4] = {'H', '2', '6', '4'};
RunBasicFileStructureTest(kVideoCodecH264, fourcc, false);
}
TEST_F(IvfFileWriterTest, WritesBasicH264FileMsTimestamp) {
const uint8_t fourcc[4] = {'H', '2', '6', '4'};
RunBasicFileStructureTest(kVideoCodecH264, fourcc, true);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <pxp-agent/util/daemonize.hpp>
#include <pxp-agent/configuration.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.util.daemonize"
#include <leatherman/logging/logging.hpp>
#include <sys/types.h>
#include <stdlib.h> // exit()
#include <unistd.h> // _exit(), getpid(), fork(), setsid(), chdir()
#include <sys/wait.h> // waitpid()
#include <sys/stat.h> // umask()
#include <signal.h>
#include <stdio.h>
#include <memory>
#include <vector>
namespace PXPAgent {
namespace Util {
const mode_t UMASK_FLAGS { 002 };
const std::string DEFAULT_DAEMON_WORKING_DIR = "/";
static void sigHandler(int sig) {
// NOTE(ale): if issued by the init process, between SIGTERM and
// the successive SIGKILL there are only 5 s - must be fast
auto pidfile = Configuration::Instance().get<std::string>("pidfile");
LOG_INFO("Caught signal %1% - removing PID file '%2%'",
std::to_string(sig), pidfile);
PIDFile pidf { pidfile };
pidf.cleanup();
exit(EXIT_SUCCESS);
}
static void dumbSigHandler(int sig) {}
std::unique_ptr<PIDFile> daemonize() {
// Check if we're already a daemon
if (getppid() == 1) {
// Parent is init process (PID 1)
LOG_INFO("Already a daemon with PID=%1%", std::to_string(getpid()));
return nullptr;
}
// Set umask; child processes will inherit
umask(UMASK_FLAGS);
// Check PID file; get read lock; ensure we can obtain write lock
auto pidfile = Configuration::Instance().get<std::string>("pidfile");
std::unique_ptr<PIDFile> pidf_ptr { new PIDFile(pidfile) };
auto removeLockAndExit = [&pidf_ptr] () {
pidf_ptr->cleanupWhenDone();
exit(EXIT_FAILURE);
};
if (pidf_ptr->isExecuting()) {
auto pid = pidf_ptr->read();
LOG_ERROR("Already running with PID=%1%", pid);
removeLockAndExit();
}
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained a read lock for the PID file; no other pxp-agent "
"daemon should be executing");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock for the PID file: %1%", e.what());
removeLockAndExit();
}
try {
if (pidf_ptr->canLockWrite()) {
LOG_DEBUG("It is possible to get a write lock for the PID file; no "
"other pxp-agent daemonization should be in progress");
} else {
LOG_ERROR("Cannot acquire the write lock for the PID file; please "
"ensure that there is no other pxp-agent instance executing");
removeLockAndExit();
}
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed to check if we can lock the PID file: %1%", e.what());
removeLockAndExit();
}
// First fork - run in background
auto first_child_pid = fork();
switch (first_child_pid) {
case -1:
LOG_ERROR("Failed to perform the first fork; errno=%1%",
std::to_string(errno));
removeLockAndExit();
case 0:
// CHILD - will fork and exit soon
LOG_DEBUG("First child spawned, with PID=%1%",
std::to_string(getpid()));
break;
default:
// PARENT - wait for the child, to avoid a zombie process
// and don't unlock the PID file
waitpid(first_child_pid, nullptr, 0);
// Exit with _exit(); note that after a fork(), only one
// of parent and child should terminate with exit()
_exit(EXIT_SUCCESS);
}
// Get the read lock
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained the read lock after first fork");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock after first fork: %1%", e.what());
removeLockAndExit();
}
// Create a new group session and become leader in order to
// disassociate from a possible controlling terminal later
if (setsid() == -1) {
LOG_ERROR("Failed to create new session for first child process; "
"errno=%1%", std::to_string(errno));
removeLockAndExit();
}
// Prepare signal mask for the second fork in order to catch the
// child signal: block the child signal for now in order to avoid
// races and change signal disposition for SIGUSR1
sigset_t block_mask, orig_mask, empty_mask;
struct sigaction sa;
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGUSR1);
if (sigprocmask(SIG_BLOCK, &block_mask, &orig_mask) == -1) {
LOG_ERROR("Failed to set the signal mask after first fork");
removeLockAndExit();
}
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = dumbSigHandler;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
LOG_ERROR("Failed to set SIGUSR1 disposition after first fork");
removeLockAndExit();
}
// Second fork - the child won't be a session leader and won't be
// associated with any controlling terminal
auto second_child_pid = fork();
switch (second_child_pid) {
case -1:
LOG_ERROR("Failed to perform the second fork; errno=%1%",
std::to_string(errno));
removeLockAndExit();
case 0:
// CHILD - will be the pxp-agent!
break;
default:
// PARENT - wait for the child signal to avoid unlocking
// the PID file
sigemptyset(&empty_mask);
if (sigsuspend(&empty_mask) == -1 && errno != EINTR) {
LOG_ERROR("Unexpected error while waiting for pending signals "
"after second fork; errno=%1%", errno);
}
_exit(EXIT_SUCCESS);
}
// Get read lock, signal the parent, and restore signal mask
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained the read lock after second fork");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock after second fork: %1%", e.what());
kill(getppid(), SIGUSR1);
removeLockAndExit();
}
kill(getppid(), SIGUSR1);
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) == -1) {
LOG_ERROR("Failed to reset signal mask after second fork; "
"errno=%1%", errno);
removeLockAndExit();
}
auto agent_pid = getpid();
LOG_DEBUG("Second child spawned, with PID=%1%", agent_pid);
// Convert the read lock to a write lock and write PID to file
LOG_DEBUG("About to convert the read lock to write lock after second fork");
try {
pidf_ptr->lockWrite(true); // blocking call
LOG_DEBUG("Successfully converted read lock to write lock");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed to convert to write lock after second fork: %1%",
e.what());
removeLockAndExit();
}
pidf_ptr->write(agent_pid);
// Change work directory
if (chdir(DEFAULT_DAEMON_WORKING_DIR.data())) {
LOG_ERROR("Failed to change work directory to '%1%'; errno=%2%",
DEFAULT_DAEMON_WORKING_DIR, std::to_string(errno));
removeLockAndExit();
} else {
LOG_DEBUG("Changed working directory to '%1%'", DEFAULT_DAEMON_WORKING_DIR);
}
// Change signal dispositions
// HERE(ale): don't touch SIGUSR2; it's used to reopen the logfile
for (auto s : std::vector<int> { SIGINT, SIGTERM, SIGQUIT }) {
if (signal(s, sigHandler) == SIG_ERR) {
LOG_ERROR("Failed to set signal handler for sig %1%", s);
removeLockAndExit();
}
}
signal(SIGCHLD, SIG_DFL);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGHUP, SIG_IGN);
// Redirect standard files; we always use boost::log anyway
stdin = freopen("/dev/null", "r", stdin);
stdout = freopen("/dev/null", "w", stdout);
stderr = freopen("/dev/null", "w", stderr);
LOG_INFO("Daemonization completed; pxp-agent PID=%1%, PID lock file in '%2%'",
agent_pid, pidfile);
// Set PIDFile dtor to clean itself up and return pointer for RAII
pidf_ptr->cleanupWhenDone();
return std::move(pidf_ptr);
}
} // namespace Util
} // namespace PXPAgent
<commit_msg>(maint) Fix compiling on Solaris<commit_after>#include <pxp-agent/util/daemonize.hpp>
#include <pxp-agent/configuration.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.util.daemonize"
#include <leatherman/logging/logging.hpp>
#include <sys/types.h>
#include <stdlib.h> // exit()
#include <unistd.h> // _exit(), getpid(), fork(), setsid(), chdir()
#include <sys/wait.h> // waitpid()
#include <sys/stat.h> // umask()
#include <signal.h>
#include <stdio.h>
#include <memory>
#include <vector>
namespace PXPAgent {
namespace Util {
const mode_t UMASK_FLAGS { 002 };
const std::string DEFAULT_DAEMON_WORKING_DIR = "/";
static void sigHandler(int sig) {
// NOTE(ale): if issued by the init process, between SIGTERM and
// the successive SIGKILL there are only 5 s - must be fast
auto pidfile = Configuration::Instance().get<std::string>("pidfile");
LOG_INFO("Caught signal %1% - removing PID file '%2%'",
std::to_string(sig), pidfile);
PIDFile pidf { pidfile };
pidf.cleanup();
exit(EXIT_SUCCESS);
}
static void dumbSigHandler(int sig) {}
std::unique_ptr<PIDFile> daemonize() {
// Check if we're already a daemon
if (getppid() == 1) {
// Parent is init process (PID 1)
LOG_INFO("Already a daemon with PID=%1%", std::to_string(getpid()));
return nullptr;
}
// Set umask; child processes will inherit
umask(UMASK_FLAGS);
// Check PID file; get read lock; ensure we can obtain write lock
auto pidfile = Configuration::Instance().get<std::string>("pidfile");
std::unique_ptr<PIDFile> pidf_ptr { new PIDFile(pidfile) };
auto removeLockAndExit = [&pidf_ptr] () {
pidf_ptr->cleanupWhenDone();
exit(EXIT_FAILURE);
};
if (pidf_ptr->isExecuting()) {
auto pid = pidf_ptr->read();
LOG_ERROR("Already running with PID=%1%", pid);
removeLockAndExit();
}
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained a read lock for the PID file; no other pxp-agent "
"daemon should be executing");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock for the PID file: %1%", e.what());
removeLockAndExit();
}
try {
if (pidf_ptr->canLockWrite()) {
LOG_DEBUG("It is possible to get a write lock for the PID file; no "
"other pxp-agent daemonization should be in progress");
} else {
LOG_ERROR("Cannot acquire the write lock for the PID file; please "
"ensure that there is no other pxp-agent instance executing");
removeLockAndExit();
}
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed to check if we can lock the PID file: %1%", e.what());
removeLockAndExit();
}
// First fork - run in background
auto first_child_pid = fork();
switch (first_child_pid) {
case -1:
LOG_ERROR("Failed to perform the first fork; errno=%1%",
std::to_string(errno));
removeLockAndExit();
case 0:
// CHILD - will fork and exit soon
LOG_DEBUG("First child spawned, with PID=%1%",
std::to_string(getpid()));
break;
default:
// PARENT - wait for the child, to avoid a zombie process
// and don't unlock the PID file
waitpid(first_child_pid, nullptr, 0);
// Exit with _exit(); note that after a fork(), only one
// of parent and child should terminate with exit()
_exit(EXIT_SUCCESS);
}
// Get the read lock
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained the read lock after first fork");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock after first fork: %1%", e.what());
removeLockAndExit();
}
// Create a new group session and become leader in order to
// disassociate from a possible controlling terminal later
if (setsid() == -1) {
LOG_ERROR("Failed to create new session for first child process; "
"errno=%1%", std::to_string(errno));
removeLockAndExit();
}
// Prepare signal mask for the second fork in order to catch the
// child signal: block the child signal for now in order to avoid
// races and change signal disposition for SIGUSR1
sigset_t block_mask, orig_mask, empty_mask;
struct sigaction sa;
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGUSR1);
if (sigprocmask(SIG_BLOCK, &block_mask, &orig_mask) == -1) {
LOG_ERROR("Failed to set the signal mask after first fork");
removeLockAndExit();
}
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = dumbSigHandler;
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
LOG_ERROR("Failed to set SIGUSR1 disposition after first fork");
removeLockAndExit();
}
// Second fork - the child won't be a session leader and won't be
// associated with any controlling terminal
auto second_child_pid = fork();
switch (second_child_pid) {
case -1:
LOG_ERROR("Failed to perform the second fork; errno=%1%",
std::to_string(errno));
removeLockAndExit();
case 0:
// CHILD - will be the pxp-agent!
break;
default:
// PARENT - wait for the child signal to avoid unlocking
// the PID file
sigemptyset(&empty_mask);
if (sigsuspend(&empty_mask) == -1 && errno != EINTR) {
LOG_ERROR("Unexpected error while waiting for pending signals "
"after second fork; errno=%1%", errno);
}
_exit(EXIT_SUCCESS);
}
// Get read lock, signal the parent, and restore signal mask
try {
pidf_ptr->lockRead();
LOG_DEBUG("Obtained the read lock after second fork");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed get a read lock after second fork: %1%", e.what());
kill(getppid(), SIGUSR1);
removeLockAndExit();
}
kill(getppid(), SIGUSR1);
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) == -1) {
LOG_ERROR("Failed to reset signal mask after second fork; "
"errno=%1%", errno);
removeLockAndExit();
}
auto agent_pid = getpid();
LOG_DEBUG("Second child spawned, with PID=%1%", agent_pid);
// Convert the read lock to a write lock and write PID to file
LOG_DEBUG("About to convert the read lock to write lock after second fork");
try {
pidf_ptr->lockWrite(true); // blocking call
LOG_DEBUG("Successfully converted read lock to write lock");
} catch (const PIDFile::Error& e) {
LOG_ERROR("Failed to convert to write lock after second fork: %1%",
e.what());
removeLockAndExit();
}
pidf_ptr->write(agent_pid);
// Change work directory
if (chdir(DEFAULT_DAEMON_WORKING_DIR.data())) {
LOG_ERROR("Failed to change work directory to '%1%'; errno=%2%",
DEFAULT_DAEMON_WORKING_DIR, std::to_string(errno));
removeLockAndExit();
} else {
LOG_DEBUG("Changed working directory to '%1%'", DEFAULT_DAEMON_WORKING_DIR);
}
// Change signal dispositions
// HERE(ale): don't touch SIGUSR2; it's used to reopen the logfile
for (auto s : std::vector<int> { SIGINT, SIGTERM, SIGQUIT }) {
if (signal(s, sigHandler) == SIG_ERR) {
LOG_ERROR("Failed to set signal handler for sig %1%", s);
removeLockAndExit();
}
}
signal(SIGCHLD, SIG_DFL);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGHUP, SIG_IGN);
// Redirect standard files; we always use boost::log anyway
if (freopen("/dev/null", "r", stdin) == nullptr) {
LOG_WARNING("Failed to redirect stdin to /dev/null; errno=%1%", std::to_string(errno));
}
if (freopen("/dev/null", "w", stdout) == nullptr) {
LOG_WARNING("Failed to redirect stdout to /dev/null; errno=%1%", std::to_string(errno));
}
if (freopen("/dev/null", "w", stderr) == nullptr) {
LOG_WARNING("Failed to redirect stderr to /dev/null; errno=%1%", std::to_string(errno));
}
LOG_INFO("Daemonization completed; pxp-agent PID=%1%, PID lock file in '%2%'",
agent_pid, pidfile);
// Set PIDFile dtor to clean itself up and return pointer for RAII
pidf_ptr->cleanupWhenDone();
return std::move(pidf_ptr);
}
} // namespace Util
} // namespace PXPAgent
<|endoftext|> |
<commit_before>// @(#)root/test:$Name$:$Id$
// Author: Fons Rademakers 19/08/96
#include <stdlib.h>
#include <iostream.h>
#include "TROOT.h"
#include "TString.h"
#include "TObjString.h"
#include "TSortedList.h"
#include "TObjArray.h"
#include "TOrdCollection.h"
#include "THashTable.h"
#include "TBtree.h"
#include "TStopwatch.h"
// To focus on basic collection protocol, this sample program uses
// simple classes inheriting from TObject. One class, TObjString, is a
// collectable string class (a TString wrapped in a TObject) provided
// by the ROOT system. The other class we define below, is an integer
// wrapped in a TObject, just like TObjString.
// TObjNum is a simple container for an integer.
class TObjNum : public TObject {
private:
int num;
public:
TObjNum(int i = 0) : num(i) { }
~TObjNum() { Printf("~TObjNum = %d", num); }
void SetNum(int i) { num = i; }
int GetNum() { return num; }
void Print(Option_t *) { Printf("TObjNum = %d", num); }
ULong_t Hash() { return num; }
Bool_t IsEqual(TObject *obj) { return num == ((TObjNum*)obj)->num; }
Bool_t IsSortable() const { return kTRUE; }
Int_t Compare(TObject *obj) { if (num > ((TObjNum*)obj)->num)
return 1;
else if (num < ((TObjNum*)obj)->num)
return -1;
else
return 0; }
};
void Test_TObjArray()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TObjArray //\n"
"////////////////////////////////////////////////////////////////"
);
// Array of capacity 10, Add() will automatically expand the array if necessary.
TObjArray a(10);
Printf("Filling TObjArray");
a.Add(new TObjNum(1)); // add at next free slot, pos 0
a[1] = new TObjNum(2); // use operator[], put at pos 1
TObjNum *n3 = new TObjNum(3);
a.AddAt(n3,2); // add at position 2
a.Add(new TObjNum(4)); // add at next free slot, pos 3
a.AddLast(new TObjNum(10)); // add at pos 4
TObjNum n6(6); // stack based TObjNum
a.AddAt(&n6,5); // add at pos 5
a[6] = new TObjNum(5); // add at respective positions
a[7] = new TObjNum(8);
a[8] = new TObjNum(7);
// a[10] = &n6; // gives out-of-bound error
Printf("Print array");
a.Print(); // invoke Print() of all objects
Printf("Sort array");
a.Sort();
for (int i = 0; i < a.Capacity(); i++) // typical way of iterating over array
if (a[i])
a[i]->Print(); // can also use operator[] to access elements
else
Printf("%d empty slot", i);
Printf("Use binary search to get position of number 6");
Printf("6 is at position %d", a.BinarySearch(&n6));
Printf("Find number before 6");
a.Before(&n6)->Print();
Printf("Find number after 3");
a.After(n3)->Print();
Printf("Remove 3 and print list again");
a.Remove(n3);
delete n3;
a.Print();
Printf("Iterate forward over list and remove 4 and 7");
// TIter encapsulates the actual class iterator. The type of iterator
// used depends on the type of the collection.
TIter next(&a);
TObjNum *obj;
while ((obj = (TObjNum*)next())) // iterator skips empty slots
if (obj->GetNum() == 4) {
a.Remove(obj);
delete obj;
}
// Reset the iterator and loop again
next.Reset();
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 7) {
a.Remove(obj);
delete obj;
}
Printf("Iterate backward over list and remove 2");
TIter next1(&a, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
a.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1,5,8,10 (6 not deleted since not on heap)");
// Delete heap objects and clear list. Attention: do this only when you
// own all objects stored in the collection. When you stored aliases to
// the actual objects (i.e. you did not create the objects) use Clear()
// instead.
a.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TOrdCollection()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TOrdCollection //\n"
"////////////////////////////////////////////////////////////////"
);
// Create collection with default size, Add() will automatically expand
// the collection if necessary.
TOrdCollection c;
Printf("Filling TOrdCollection");
c.Add(new TObjString("anton")); // add at next free slot, pos 0
c.AddFirst(new TObjString("bobo")); // put at pos 0, bump anton to pos 1
TObjString *s3 = new TObjString("damon");
c.AddAt(s3,1); // add at position 1, bump anton to pos 2
c.Add(new TObjString("cassius")); // add at next free slot, pos 3
c.AddLast(new TObjString("enigma")); // add at pos 4
TObjString s6("fons"); // stack based TObjString
c.AddBefore(s3,&s6); // add at pos 1
c.AddAfter(s3, new TObjString("gaia"));
Printf("Print collection");
c.Print(); // invoke Print() of all objects
Printf("Sort collection");
c.Sort();
c.Print();
Printf("Use binary search to get position of string damon");
Printf("damon is at position %d", c.BinarySearch(s3));
Printf("Find str before fons");
c.Before(&s6)->Print();
Printf("Find string after damon");
c.After(s3)->Print();
Printf("Remove damon and print list again");
c.Remove(s3);
delete s3;
c.Print();
Printf("Iterate forward over list and remove cassius");
TObjString *objs;
TIter next(&c);
while ((objs = (TObjString*)next())) // iterator skips empty slots
if (objs->String() == "cassius") {
c.Remove(objs);
delete objs;
}
Printf("Iterate backward over list and remove gaia");
TIter next1(&c, kIterBackward);
while ((objs = (TObjString*)next1()))
if (objs->String() == "gaia") {
c.Remove(objs);
delete objs;
}
Printf("Delete remainder of list: anton,bobo,enigma (fons not deleted since not on heap)");
c.Delete(); // delete heap objects and clear list
Printf("Delete stack based objects (fons)");
}
void Test_TList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a doubly linked list.
TList l;
Printf("Filling TList");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3, new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
Printf("Print list");
l.Print();
Printf("Remove 3 and print list again");
l.Remove(n3);
delete n3;
l.Print();
Printf("Iterate forward over list and remove 4");
TObjNum *obj;
TIter next(&l);
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over list and remove 2");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
l.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1, 5 (6 not deleted since not on heap)");
l.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TSortedList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TSortedList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a sorted doubly linked list.
TSortedList sl;
Printf("Filling TSortedList");
TObjNum *n3 = new TObjNum(3);
sl.Add(n3);
sl.AddBefore(n3,new TObjNum(5));
sl.AddAfter(n3, new TObjNum(2));
sl.Add(new TObjNum(1));
sl.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
sl.AddFirst(&n6);
Printf("Print list");
sl.Print();
Printf("Delete all heap based objects (6 not deleted since not on heap)");
sl.Delete();
Printf("Delete stack based objects (6)");
}
void Test_THashTable()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of THashTable //\n"
"////////////////////////////////////////////////////////////////"
);
int i;
// Create a hash table with an initial size of 20 (actually the next prime
// above 20). No automatic rehashing.
THashTable ht(20);
Printf("Filling THashTable");
Printf("Number of slots before filling: %d", ht.Capacity());
for (i = 0; i < 1000; i++)
ht.Add(new TObject);
Printf("Average collisions: %f", ht.AverageCollisions());
// rehash the hash table to reduce the collission rate
ht.Rehash(ht.GetSize());
Printf("Number of slots after rehash: %d", ht.Capacity());
Printf("Average collisions after rehash: %f", ht.AverageCollisions());
ht.Delete();
// Create a hash table and trigger automatic rehashing when average
// collision rate becomes larger than 5.
THashTable ht2(20,5);
Printf("Filling THashTable with automatic rehash when AverageCollisions>5");
Printf("Number of slots before filling: %d", ht2.Capacity());
for (i = 0; i < 1000; i++)
ht2.Add(new TObject);
Printf("Number of slots after filling: %d", ht2.Capacity());
Printf("Average collisions: %f", ht2.AverageCollisions());
Printf("\nDelete all heap based objects");
ht2.Delete();
}
void Test_TBtree()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TBtree //\n"
"////////////////////////////////////////////////////////////////"
);
TStopwatch timer; // create a timer
TBtree l; // btree of order 3
Printf("Filling TBtree");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3,new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
timer.Start();
for (int i = 0; i < 50; i++)
l.Add(new TObjNum(i));
timer.Print();
Printf("Print TBtree");
l.Print();
Printf("Remove 3 and print TBtree again");
l.Remove(n3);
l.Print();
Printf("Iterate forward over TBtree and remove 4 from tree");
TIter next(&l);
TObjNum *obj;
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over TBtree and remove 2 from tree");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) l.Remove(obj);
Printf("\nDelete all heap based objects");
l.Delete();
Printf("Delete stack based objects (6)");
}
int main()
{
// Initialize the ROOT framework
TROOT tcollex("Collection", "Test collection classes");
Test_TObjArray();
Test_TOrdCollection();
Test_TList();
Test_TSortedList();
Test_THashTable();
Test_TBtree();
return 0;
}
<commit_msg>Fix const in Hash, Print and Compare functions<commit_after>// @(#)root/test:$Name: $:$Id: tcollex.cxx,v 1.2 2000/07/11 18:05:26 rdm Exp $
// Author: Fons Rademakers 19/08/96
#include <stdlib.h>
#include <iostream.h>
#include "TROOT.h"
#include "TString.h"
#include "TObjString.h"
#include "TSortedList.h"
#include "TObjArray.h"
#include "TOrdCollection.h"
#include "THashTable.h"
#include "TBtree.h"
#include "TStopwatch.h"
// To focus on basic collection protocol, this sample program uses
// simple classes inheriting from TObject. One class, TObjString, is a
// collectable string class (a TString wrapped in a TObject) provided
// by the ROOT system. The other class we define below, is an integer
// wrapped in a TObject, just like TObjString.
// TObjNum is a simple container for an integer.
class TObjNum : public TObject {
private:
int num;
public:
TObjNum(int i = 0) : num(i) { }
~TObjNum() { Printf("~TObjNum = %d", num); }
void SetNum(int i) { num = i; }
int GetNum() { return num; }
void Print(Option_t *) const { Printf("TObjNum = %d", num); }
ULong_t Hash() const { return num; }
Bool_t IsEqual(const TObject *obj) const { return num == ((TObjNum*)obj)->num; }
Bool_t IsSortable() const { return kTRUE; }
Int_t Compare(const TObject *obj) const { if (num > ((TObjNum*)obj)->num)
return 1;
else if (num < ((TObjNum*)obj)->num)
return -1;
else
return 0; }
};
void Test_TObjArray()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TObjArray //\n"
"////////////////////////////////////////////////////////////////"
);
// Array of capacity 10, Add() will automatically expand the array if necessary.
TObjArray a(10);
Printf("Filling TObjArray");
a.Add(new TObjNum(1)); // add at next free slot, pos 0
a[1] = new TObjNum(2); // use operator[], put at pos 1
TObjNum *n3 = new TObjNum(3);
a.AddAt(n3,2); // add at position 2
a.Add(new TObjNum(4)); // add at next free slot, pos 3
a.AddLast(new TObjNum(10)); // add at pos 4
TObjNum n6(6); // stack based TObjNum
a.AddAt(&n6,5); // add at pos 5
a[6] = new TObjNum(5); // add at respective positions
a[7] = new TObjNum(8);
a[8] = new TObjNum(7);
// a[10] = &n6; // gives out-of-bound error
Printf("Print array");
a.Print(); // invoke Print() of all objects
Printf("Sort array");
a.Sort();
for (int i = 0; i < a.Capacity(); i++) // typical way of iterating over array
if (a[i])
a[i]->Print(); // can also use operator[] to access elements
else
Printf("%d empty slot", i);
Printf("Use binary search to get position of number 6");
Printf("6 is at position %d", a.BinarySearch(&n6));
Printf("Find number before 6");
a.Before(&n6)->Print();
Printf("Find number after 3");
a.After(n3)->Print();
Printf("Remove 3 and print list again");
a.Remove(n3);
delete n3;
a.Print();
Printf("Iterate forward over list and remove 4 and 7");
// TIter encapsulates the actual class iterator. The type of iterator
// used depends on the type of the collection.
TIter next(&a);
TObjNum *obj;
while ((obj = (TObjNum*)next())) // iterator skips empty slots
if (obj->GetNum() == 4) {
a.Remove(obj);
delete obj;
}
// Reset the iterator and loop again
next.Reset();
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 7) {
a.Remove(obj);
delete obj;
}
Printf("Iterate backward over list and remove 2");
TIter next1(&a, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
a.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1,5,8,10 (6 not deleted since not on heap)");
// Delete heap objects and clear list. Attention: do this only when you
// own all objects stored in the collection. When you stored aliases to
// the actual objects (i.e. you did not create the objects) use Clear()
// instead.
a.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TOrdCollection()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TOrdCollection //\n"
"////////////////////////////////////////////////////////////////"
);
// Create collection with default size, Add() will automatically expand
// the collection if necessary.
TOrdCollection c;
Printf("Filling TOrdCollection");
c.Add(new TObjString("anton")); // add at next free slot, pos 0
c.AddFirst(new TObjString("bobo")); // put at pos 0, bump anton to pos 1
TObjString *s3 = new TObjString("damon");
c.AddAt(s3,1); // add at position 1, bump anton to pos 2
c.Add(new TObjString("cassius")); // add at next free slot, pos 3
c.AddLast(new TObjString("enigma")); // add at pos 4
TObjString s6("fons"); // stack based TObjString
c.AddBefore(s3,&s6); // add at pos 1
c.AddAfter(s3, new TObjString("gaia"));
Printf("Print collection");
c.Print(); // invoke Print() of all objects
Printf("Sort collection");
c.Sort();
c.Print();
Printf("Use binary search to get position of string damon");
Printf("damon is at position %d", c.BinarySearch(s3));
Printf("Find str before fons");
c.Before(&s6)->Print();
Printf("Find string after damon");
c.After(s3)->Print();
Printf("Remove damon and print list again");
c.Remove(s3);
delete s3;
c.Print();
Printf("Iterate forward over list and remove cassius");
TObjString *objs;
TIter next(&c);
while ((objs = (TObjString*)next())) // iterator skips empty slots
if (objs->String() == "cassius") {
c.Remove(objs);
delete objs;
}
Printf("Iterate backward over list and remove gaia");
TIter next1(&c, kIterBackward);
while ((objs = (TObjString*)next1()))
if (objs->String() == "gaia") {
c.Remove(objs);
delete objs;
}
Printf("Delete remainder of list: anton,bobo,enigma (fons not deleted since not on heap)");
c.Delete(); // delete heap objects and clear list
Printf("Delete stack based objects (fons)");
}
void Test_TList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a doubly linked list.
TList l;
Printf("Filling TList");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3, new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
Printf("Print list");
l.Print();
Printf("Remove 3 and print list again");
l.Remove(n3);
delete n3;
l.Print();
Printf("Iterate forward over list and remove 4");
TObjNum *obj;
TIter next(&l);
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over list and remove 2");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
l.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1, 5 (6 not deleted since not on heap)");
l.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TSortedList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TSortedList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a sorted doubly linked list.
TSortedList sl;
Printf("Filling TSortedList");
TObjNum *n3 = new TObjNum(3);
sl.Add(n3);
sl.AddBefore(n3,new TObjNum(5));
sl.AddAfter(n3, new TObjNum(2));
sl.Add(new TObjNum(1));
sl.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
sl.AddFirst(&n6);
Printf("Print list");
sl.Print();
Printf("Delete all heap based objects (6 not deleted since not on heap)");
sl.Delete();
Printf("Delete stack based objects (6)");
}
void Test_THashTable()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of THashTable //\n"
"////////////////////////////////////////////////////////////////"
);
int i;
// Create a hash table with an initial size of 20 (actually the next prime
// above 20). No automatic rehashing.
THashTable ht(20);
Printf("Filling THashTable");
Printf("Number of slots before filling: %d", ht.Capacity());
for (i = 0; i < 1000; i++)
ht.Add(new TObject);
Printf("Average collisions: %f", ht.AverageCollisions());
// rehash the hash table to reduce the collission rate
ht.Rehash(ht.GetSize());
Printf("Number of slots after rehash: %d", ht.Capacity());
Printf("Average collisions after rehash: %f", ht.AverageCollisions());
ht.Delete();
// Create a hash table and trigger automatic rehashing when average
// collision rate becomes larger than 5.
THashTable ht2(20,5);
Printf("Filling THashTable with automatic rehash when AverageCollisions>5");
Printf("Number of slots before filling: %d", ht2.Capacity());
for (i = 0; i < 1000; i++)
ht2.Add(new TObject);
Printf("Number of slots after filling: %d", ht2.Capacity());
Printf("Average collisions: %f", ht2.AverageCollisions());
Printf("\nDelete all heap based objects");
ht2.Delete();
}
void Test_TBtree()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TBtree //\n"
"////////////////////////////////////////////////////////////////"
);
TStopwatch timer; // create a timer
TBtree l; // btree of order 3
Printf("Filling TBtree");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3,new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
timer.Start();
for (int i = 0; i < 50; i++)
l.Add(new TObjNum(i));
timer.Print();
Printf("Print TBtree");
l.Print();
Printf("Remove 3 and print TBtree again");
l.Remove(n3);
l.Print();
Printf("Iterate forward over TBtree and remove 4 from tree");
TIter next(&l);
TObjNum *obj;
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over TBtree and remove 2 from tree");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) l.Remove(obj);
Printf("\nDelete all heap based objects");
l.Delete();
Printf("Delete stack based objects (6)");
}
int main()
{
// Initialize the ROOT framework
TROOT tcollex("Collection", "Test collection classes");
Test_TObjArray();
Test_TOrdCollection();
Test_TList();
Test_TSortedList();
Test_THashTable();
Test_TBtree();
return 0;
}
<|endoftext|> |
<commit_before>7ba8c00e-2e4d-11e5-9284-b827eb9e62be<commit_msg>7badc1c6-2e4d-11e5-9284-b827eb9e62be<commit_after>7badc1c6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e7237c6a-2e4e-11e5-9284-b827eb9e62be<commit_msg>e7290126-2e4e-11e5-9284-b827eb9e62be<commit_after>e7290126-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>139b4b02-2e4e-11e5-9284-b827eb9e62be<commit_msg>13a04c7e-2e4e-11e5-9284-b827eb9e62be<commit_after>13a04c7e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>14a4e7a2-2e4d-11e5-9284-b827eb9e62be<commit_msg>14a9fc9c-2e4d-11e5-9284-b827eb9e62be<commit_after>14a9fc9c-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>766fc65e-2e4e-11e5-9284-b827eb9e62be<commit_msg>7674cba4-2e4e-11e5-9284-b827eb9e62be<commit_after>7674cba4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>4b09f6e8-2e4d-11e5-9284-b827eb9e62be<commit_msg>4b0f0412-2e4d-11e5-9284-b827eb9e62be<commit_after>4b0f0412-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>8d045ca4-2e4e-11e5-9284-b827eb9e62be<commit_msg>8d096c8a-2e4e-11e5-9284-b827eb9e62be<commit_after>8d096c8a-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>00384a0c-2e4d-11e5-9284-b827eb9e62be<commit_msg>003d88e6-2e4d-11e5-9284-b827eb9e62be<commit_after>003d88e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9f00eb6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>9f05e946-2e4d-11e5-9284-b827eb9e62be<commit_after>9f05e946-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b285b8a6-2e4e-11e5-9284-b827eb9e62be<commit_msg>b28abbb2-2e4e-11e5-9284-b827eb9e62be<commit_after>b28abbb2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>cbefd418-2e4c-11e5-9284-b827eb9e62be<commit_msg>cbf4c43c-2e4c-11e5-9284-b827eb9e62be<commit_after>cbf4c43c-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1ffb2eae-2e4d-11e5-9284-b827eb9e62be<commit_msg>20001e1e-2e4d-11e5-9284-b827eb9e62be<commit_after>20001e1e-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>42904378-2e4d-11e5-9284-b827eb9e62be<commit_msg>42954c1a-2e4d-11e5-9284-b827eb9e62be<commit_after>42954c1a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f759bb28-2e4c-11e5-9284-b827eb9e62be<commit_msg>f75ec74e-2e4c-11e5-9284-b827eb9e62be<commit_after>f75ec74e-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>597c6dbe-2e4d-11e5-9284-b827eb9e62be<commit_msg>59817b74-2e4d-11e5-9284-b827eb9e62be<commit_after>59817b74-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>32baec78-2e4d-11e5-9284-b827eb9e62be<commit_msg>32bffc2c-2e4d-11e5-9284-b827eb9e62be<commit_after>32bffc2c-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e5747718-2e4c-11e5-9284-b827eb9e62be<commit_msg>e5798f6e-2e4c-11e5-9284-b827eb9e62be<commit_after>e5798f6e-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e4fc9874-2e4c-11e5-9284-b827eb9e62be<commit_msg>e501a454-2e4c-11e5-9284-b827eb9e62be<commit_after>e501a454-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>cd010bbe-2e4d-11e5-9284-b827eb9e62be<commit_msg>cd06004c-2e4d-11e5-9284-b827eb9e62be<commit_after>cd06004c-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>955b656a-2e4d-11e5-9284-b827eb9e62be<commit_msg>95607032-2e4d-11e5-9284-b827eb9e62be<commit_after>95607032-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>42cca246-2e4d-11e5-9284-b827eb9e62be<commit_msg>42d1b6b4-2e4d-11e5-9284-b827eb9e62be<commit_after>42d1b6b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ebc1470e-2e4c-11e5-9284-b827eb9e62be<commit_msg>ebc64b82-2e4c-11e5-9284-b827eb9e62be<commit_after>ebc64b82-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>bfbfa1dc-2e4c-11e5-9284-b827eb9e62be<commit_msg>bfc4b6d6-2e4c-11e5-9284-b827eb9e62be<commit_after>bfc4b6d6-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1cf1330a-2e4f-11e5-9284-b827eb9e62be<commit_msg>1cf635da-2e4f-11e5-9284-b827eb9e62be<commit_after>1cf635da-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f23459a4-2e4d-11e5-9284-b827eb9e62be<commit_msg>f239661a-2e4d-11e5-9284-b827eb9e62be<commit_after>f239661a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2d459a2c-2e4d-11e5-9284-b827eb9e62be<commit_msg>2d4a9658-2e4d-11e5-9284-b827eb9e62be<commit_after>2d4a9658-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9c077326-2e4e-11e5-9284-b827eb9e62be<commit_msg>9c0c77ae-2e4e-11e5-9284-b827eb9e62be<commit_after>9c0c77ae-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>da541d34-2e4c-11e5-9284-b827eb9e62be<commit_msg>da5935e4-2e4c-11e5-9284-b827eb9e62be<commit_after>da5935e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fee829ea-2e4e-11e5-9284-b827eb9e62be<commit_msg>feed1aea-2e4e-11e5-9284-b827eb9e62be<commit_after>feed1aea-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>08397ff0-2e4d-11e5-9284-b827eb9e62be<commit_msg>08433d92-2e4d-11e5-9284-b827eb9e62be<commit_after>08433d92-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2e27141a-2e4e-11e5-9284-b827eb9e62be<commit_msg>2e2c2176-2e4e-11e5-9284-b827eb9e62be<commit_after>2e2c2176-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>beadaf9a-2e4d-11e5-9284-b827eb9e62be<commit_msg>beb2a61c-2e4d-11e5-9284-b827eb9e62be<commit_after>beb2a61c-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9307d7f2-2e4e-11e5-9284-b827eb9e62be<commit_msg>930cd482-2e4e-11e5-9284-b827eb9e62be<commit_after>930cd482-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>89c9db3c-2e4d-11e5-9284-b827eb9e62be<commit_msg>89ceedca-2e4d-11e5-9284-b827eb9e62be<commit_after>89ceedca-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2fae5924-2e4e-11e5-9284-b827eb9e62be<commit_msg>2fb34df8-2e4e-11e5-9284-b827eb9e62be<commit_after>2fb34df8-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>038a8b42-2e4e-11e5-9284-b827eb9e62be<commit_msg>038f7ba2-2e4e-11e5-9284-b827eb9e62be<commit_after>038f7ba2-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ae30d5da-2e4c-11e5-9284-b827eb9e62be<commit_msg>ae35cedc-2e4c-11e5-9284-b827eb9e62be<commit_after>ae35cedc-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d485a3a8-2e4e-11e5-9284-b827eb9e62be<commit_msg>d48a9c32-2e4e-11e5-9284-b827eb9e62be<commit_after>d48a9c32-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>de7b761e-2e4c-11e5-9284-b827eb9e62be<commit_msg>de80706a-2e4c-11e5-9284-b827eb9e62be<commit_after>de80706a-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b4405368-2e4e-11e5-9284-b827eb9e62be<commit_msg>b4456c5e-2e4e-11e5-9284-b827eb9e62be<commit_after>b4456c5e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>f2c3a0d2-2e4d-11e5-9284-b827eb9e62be<commit_msg>f2c8ff0a-2e4d-11e5-9284-b827eb9e62be<commit_after>f2c8ff0a-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>15852586-2e4f-11e5-9284-b827eb9e62be<commit_msg>158a3562-2e4f-11e5-9284-b827eb9e62be<commit_after>158a3562-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a0671f30-2e4d-11e5-9284-b827eb9e62be<commit_msg>a06c1238-2e4d-11e5-9284-b827eb9e62be<commit_after>a06c1238-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>30c26192-2e4f-11e5-9284-b827eb9e62be<commit_msg>30c77a24-2e4f-11e5-9284-b827eb9e62be<commit_after>30c77a24-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>063aafac-2e4e-11e5-9284-b827eb9e62be<commit_msg>06407f9a-2e4e-11e5-9284-b827eb9e62be<commit_after>06407f9a-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ea14f748-2e4c-11e5-9284-b827eb9e62be<commit_msg>ea19f32e-2e4c-11e5-9284-b827eb9e62be<commit_after>ea19f32e-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>dd443e28-2e4e-11e5-9284-b827eb9e62be<commit_msg>dd49387e-2e4e-11e5-9284-b827eb9e62be<commit_after>dd49387e-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1bc773c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>1bcc9e08-2e4d-11e5-9284-b827eb9e62be<commit_after>1bcc9e08-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>2dbc5cd2-2e4f-11e5-9284-b827eb9e62be<commit_msg>2dc155e8-2e4f-11e5-9284-b827eb9e62be<commit_after>2dc155e8-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9ecf0f48-2e4d-11e5-9284-b827eb9e62be<commit_msg>9ed410e2-2e4d-11e5-9284-b827eb9e62be<commit_after>9ed410e2-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>130ad234-2e4e-11e5-9284-b827eb9e62be<commit_msg>130fcadc-2e4e-11e5-9284-b827eb9e62be<commit_after>130fcadc-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>4c22eef4-2e4d-11e5-9284-b827eb9e62be<commit_msg>4c280dbc-2e4d-11e5-9284-b827eb9e62be<commit_after>4c280dbc-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>68191584-2e4d-11e5-9284-b827eb9e62be<commit_msg>681e1fb6-2e4d-11e5-9284-b827eb9e62be<commit_after>681e1fb6-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>35c3da56-2e4d-11e5-9284-b827eb9e62be<commit_msg>35c8ee2e-2e4d-11e5-9284-b827eb9e62be<commit_after>35c8ee2e-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>21fa7d26-2e4e-11e5-9284-b827eb9e62be<commit_msg>21ff8582-2e4e-11e5-9284-b827eb9e62be<commit_after>21ff8582-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>b7eaba62-2e4e-11e5-9284-b827eb9e62be<commit_msg>b7efcb92-2e4e-11e5-9284-b827eb9e62be<commit_after>b7efcb92-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9979af3e-2e4e-11e5-9284-b827eb9e62be<commit_msg>997eefa8-2e4e-11e5-9284-b827eb9e62be<commit_after>997eefa8-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.