text
stringlengths
54
60.6k
<commit_before>#include "EditorScene.hpp" EditorScene* EditorScene::activeScene = nullptr; // --------------------------------------------------------------------------- // Prolog Interface to Scene Editing Commands // --------------------------------------------------------------------------- // TODO: Move to appropriate modules PREDICATE0(pd_save) { return false; } PREDICATE(pd_saveas, 1) { return false; } PREDICATE0(pd_exit) { return false; } PREDICATE(pd_add_actor, 1) { try { EditorScene::activeScene->addActor(static_cast<const char*>(A1)); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); return false; } return true; } PREDICATE(pd_select, 2) { return false; } PREDICATE0(pd_deselect) { return false; } PREDICATE0(pd_remove_actor) { return false; } PREDICATE(pd_move_by, 3) { return false; } PREDICATE(pd_move_to, 3) { return false; } PREDICATE(pd_rotate, 3) { return false; } PREDICATE0(pd_add_light) { return false; } PREDICATE(pd_select_light, 1) { return false; } PREDICATE0(pd_remove_light) { return false; } PREDICATE0(pd_edit_light) { return false; } PREDICATE0(pd_load_assets) { return false; } // --------------------------------------------------------------------------- // Scene Overrides // --------------------------------------------------------------------------- EditorScene::EditorScene(const std::string& name) : Scene(name) , m_inputModel("SceneEdit") , m_mutex() , m_runConsole(true) , m_consoleThread([&]() { while(m_runConsole) { std::string command; std::getline(std::cin, command); if(command.at(command.size() - 1) == '\r') command.resize(command.size() - 1); m_mutex.lock(); m_commands.emplace(command); m_mutex.unlock(); } }) { // TODO: Editor mode scene loading // The scene will load normally first. // If the scene file can't be found, we create a new one. // If the scene file is corrupt, we give up. try { m_defaultShader = new Shader("textured.vert.glsl", "textured.frag.glsl"); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); } } EditorScene::~EditorScene() { m_runConsole = false; std::cout << "Press ENTER to quit.\n"; m_consoleThread.join(); delete m_defaultShader; } // The editor works with the initial moment of a scene. // We don't want these functions to do anything. void EditorScene::update(std::chrono::milliseconds) {} void EditorScene::simulate(std::chrono::milliseconds) {} // Similarly, we don't want the Actors processing any input. // Input processing is limited to editor and camera input. void EditorScene::processInput(GLFWwindow& window) { m_inputModel.update(window); m_editorCamera.processInput(window); // Process command queue EditorScene::activeScene = this; std::lock_guard<std::mutex> lock(m_mutex); while(!m_commands.empty()) { std::string command = m_commands.front(); std::cout << (PlCall("do_command", {{command.c_str()}}) ? "Command Succeeded" : "Command Failed") << "\n"; m_commands.pop(); } EditorScene::activeScene = nullptr; } // The scene should draw as per usual, though. //void EditorScene::draw() { Scene::draw(); } void EditorScene::draw() { glm::mat4 projectionMatrix = glm::perspective(45.0f, static_cast<float>(g_renderer.width()) / static_cast<float>(g_renderer.height()), 0.1f, 10000.0f); for(auto actor = m_actors.begin(); actor != m_actors.end(); ++actor) { m_defaultShader->setAmbience(m_ambience); // Send camera position to the GPU. m_defaultShader->setViewMatrix(m_editorCamera.getViewMatrix()); m_defaultShader->setEyePosition(glm::vec3(m_editorCamera.getPosition())); m_defaultShader->setProjectionMatrix(projectionMatrix); m_defaultShader->setObjectID(actor->first); actor->second->draw(*m_defaultShader); } } // --------------------------------------------------------------------------- // Editor Functionality // --------------------------------------------------------------------------- void EditorScene::addActor(const std::string& name) { try { m_actors.emplace( std::make_pair(++m_highestID, std::make_unique<Actor>(name))); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); throw std::runtime_error("Failed to load Actor"); } } <commit_msg>Add some ambient light.<commit_after>#include "EditorScene.hpp" EditorScene* EditorScene::activeScene = nullptr; // --------------------------------------------------------------------------- // Prolog Interface to Scene Editing Commands // --------------------------------------------------------------------------- // TODO: Move to appropriate modules PREDICATE0(pd_save) { return false; } PREDICATE(pd_saveas, 1) { return false; } PREDICATE0(pd_exit) { return false; } PREDICATE(pd_add_actor, 1) { try { EditorScene::activeScene->addActor(static_cast<const char*>(A1)); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); return false; } return true; } PREDICATE(pd_select, 2) { return false; } PREDICATE0(pd_deselect) { return false; } PREDICATE0(pd_remove_actor) { return false; } PREDICATE(pd_move_by, 3) { return false; } PREDICATE(pd_move_to, 3) { return false; } PREDICATE(pd_rotate, 3) { return false; } PREDICATE0(pd_add_light) { return false; } PREDICATE(pd_select_light, 1) { return false; } PREDICATE0(pd_remove_light) { return false; } PREDICATE0(pd_edit_light) { return false; } PREDICATE0(pd_load_assets) { return false; } // --------------------------------------------------------------------------- // Scene Overrides // --------------------------------------------------------------------------- EditorScene::EditorScene(const std::string& name) : Scene(name) , m_inputModel("SceneEdit") , m_mutex() , m_runConsole(true) , m_consoleThread([&]() { while(m_runConsole) { std::string command; std::getline(std::cin, command); if(command.at(command.size() - 1) == '\r') command.resize(command.size() - 1); m_mutex.lock(); m_commands.emplace(command); m_mutex.unlock(); } }) { // TODO: Editor mode scene loading // The scene will load normally first. // If the scene file can't be found, we create a new one. // If the scene file is corrupt, we give up. try { m_defaultShader = new Shader("textured.vert.glsl", "textured.frag.glsl"); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); } m_ambience = 0.2f; } EditorScene::~EditorScene() { m_runConsole = false; std::cout << "Press ENTER to quit.\n"; m_consoleThread.join(); delete m_defaultShader; } // The editor works with the initial moment of a scene. // We don't want these functions to do anything. void EditorScene::update(std::chrono::milliseconds) {} void EditorScene::simulate(std::chrono::milliseconds) {} // Similarly, we don't want the Actors processing any input. // Input processing is limited to editor and camera input. void EditorScene::processInput(GLFWwindow& window) { m_inputModel.update(window); m_editorCamera.processInput(window); // Process command queue EditorScene::activeScene = this; std::lock_guard<std::mutex> lock(m_mutex); while(!m_commands.empty()) { std::string command = m_commands.front(); std::cout << (PlCall("do_command", {{command.c_str()}}) ? "Command Succeeded" : "Command Failed") << "\n"; m_commands.pop(); } EditorScene::activeScene = nullptr; } // The scene should draw as per usual, though. //void EditorScene::draw() { Scene::draw(); } void EditorScene::draw() { glm::mat4 projectionMatrix = glm::perspective(45.0f, static_cast<float>(g_renderer.width()) / static_cast<float>(g_renderer.height()), 0.1f, 10000.0f); for(auto actor = m_actors.begin(); actor != m_actors.end(); ++actor) { m_defaultShader->setAmbience(m_ambience); // Send camera position to the GPU. m_defaultShader->setViewMatrix(m_editorCamera.getViewMatrix()); m_defaultShader->setEyePosition(glm::vec3(m_editorCamera.getPosition())); m_defaultShader->setProjectionMatrix(projectionMatrix); m_defaultShader->setObjectID(actor->first); actor->second->draw(*m_defaultShader); } } // --------------------------------------------------------------------------- // Editor Functionality // --------------------------------------------------------------------------- void EditorScene::addActor(const std::string& name) { try { m_actors.emplace( std::make_pair(++m_highestID, std::make_unique<Actor>(name))); } catch(const std::exception& exception) { g_logger.write(Logger::LOG_ERROR, exception.what()); throw std::runtime_error("Failed to load Actor"); } } <|endoftext|>
<commit_before>#pragma once #include "point2d.hpp" #include "rect2d.hpp" #include "rect_intersect.hpp" #include "angles.hpp" #include "../base/math.hpp" #include <cmath> namespace m2 { /// axis aligned rect template <typename T> class AnyRect { ang::Angle<T> m_angle; /// @todo No need to store orthos separately. They are stored in m_angle. Point<T> m_i; Point<T> m_j; Point<T> m_zero; Rect<T> m_rect; static Point<T> const Convert(Point<T> const & p, Point<T> const & fromI, Point<T> const & fromJ, Point<T> const & toI, Point<T> const & toJ) { Point<T> res; res.x = p.x * DotProduct(fromI, toI) + p.y * DotProduct(fromJ, toI); res.y = p.x * DotProduct(fromI, toJ) + p.y * DotProduct(fromJ, toJ); return res; } public: AnyRect() : m_i(1, 0), m_j(0, 1), m_zero(0, 0), m_rect() {} /// creating from regular rect explicit AnyRect(Rect<T> const & r) : m_angle(0), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()) { if (r.IsValid()) { m_zero = Point<T>(r.minX(), r.minY()); m_rect = Rect<T>(0, 0, r.SizeX(), r.SizeY()); } else { m_zero = Point<T>(0, 0); m_rect = r; } } AnyRect(Point<T> const & zero, ang::Angle<T> const & angle, Rect<T> const & r) : m_angle(angle), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()), m_zero(Convert(zero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j)), m_rect(r) { } Point<T> const & LocalZero() const { return m_zero; } Point<T> const GlobalZero() const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(m_zero, m_i, m_j, i, j); } Point<T> const & i() const { return m_i; } Point<T> const & j() const { return m_j; } void SetAngle(ang::Angle<T> const & a) { m2::Point<T> glbZero = GlobalZero(); m_angle = a; m_i = m2::Point<T>(m_angle.cos(), m_angle.sin()); m_j = m2::Point<T>(-m_angle.sin(), m_angle.cos()); m_zero = Convert(glbZero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j); } ang::Angle<T> const & Angle() const { return m_angle; } Point<T> const GlobalCenter() const { return ConvertFrom(m_rect.Center()); } Point<T> const LocalCenter() const { return m_rect.Center(); } bool IsPointInside(Point<T> const & pt) const { return m_rect.IsPointInside(ConvertTo(pt)); } bool IsRectInside(AnyRect<T> const & r) const { m2::Point<T> pts[4]; r.GetGlobalPoints(pts); ConvertTo(pts, 4); return m_rect.IsPointInside(pts[0]) && m_rect.IsPointInside(pts[1]) && m_rect.IsPointInside(pts[2]) && m_rect.IsPointInside(pts[3]); } bool IsIntersect(AnyRect<T> const & r) const { m2::Point<T> pts[4]; if (r.GetLocalRect() == Rect<T>()) return false; r.GetGlobalPoints(pts); ConvertTo(pts, 4); m2::Rect<T> r1(pts[0], pts[0]); r1.Add(pts[1]); r1.Add(pts[2]); r1.Add(pts[3]); if (!GetLocalRect().IsIntersect(r1)) return false; if (r.IsRectInside(*this)) return true; if (IsRectInside(r)) return true; return Intersect(GetLocalRect(), pts[0], pts[1]) || Intersect(GetLocalRect(), pts[1], pts[2]) || Intersect(GetLocalRect(), pts[2], pts[3]) || Intersect(GetLocalRect(), pts[3], pts[0]); } /// Convert into coordinate system of this AnyRect Point<T> const ConvertTo(Point<T> const & p) const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(p - Convert(m_zero, m_i, m_j, i, j), i, j, m_i, m_j); } void ConvertTo(Point<T> * pts, size_t count) const { for (size_t i = 0; i < count; ++i) pts[i] = ConvertTo(pts[i]); } /// Convert into global coordinates from the local coordinates of this AnyRect Point<T> const ConvertFrom(Point<T> const & p) const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(p + m_zero, m_i, m_j, i, j); } void ConvertFrom(Point<T> * pts, size_t count) const { for (size_t i = 0; i < count; ++i) pts[i] = ConvertFrom(pts[i]); } Rect<T> const & GetLocalRect() const { return m_rect; } Rect<T> const GetGlobalRect() const { Point<T> pts[4]; GetGlobalPoints(pts); Rect<T> res(pts[0].x, pts[0].y, pts[0].x, pts[0].y); res.Add(pts[1]); res.Add(pts[2]); res.Add(pts[3]); return res; } void GetGlobalPoints(Point<T> * pts) const { pts[0] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.minY()))); pts[1] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.maxY()))); pts[2] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.maxY()))); pts[3] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.minY()))); } template <typename U> void Inflate(U const & dx, U const & dy) { m_rect.Inflate(dx, dy); } void Add(AnyRect<T> const & r) { Point<T> pts[4]; r.GetGlobalPoints(pts); ConvertTo(pts, 4); m_rect.Add(pts[0]); m_rect.Add(pts[1]); m_rect.Add(pts[2]); m_rect.Add(pts[3]); } void Offset(Point<T> const & p) { m_zero = ConvertTo(ConvertFrom(m_zero) + p); } }; template <typename T> AnyRect<T> const Offset(AnyRect<T> const & r, Point<T> const & pt) { AnyRect<T> res(r); res.Offset(pt); return res; } template <typename T, typename U> AnyRect<T> const Inflate(AnyRect<T> const & r, U const & dx, U const & dy) { AnyRect<T> res = r; res.Inflate(dx, dy); return res; } template <typename T, typename U> AnyRect<T> const Inflate(AnyRect<T> const & r, Point<U> const & pt) { return Inflate(r, pt.x, pt.y); } typedef AnyRect<double> AnyRectD; typedef AnyRect<float> AnyRectF; template <typename T> inline string DebugPrint(m2::AnyRect<T> const & r) { return DebugPrint(r.GetGlobalRect()); } } <commit_msg>Minor code fix.<commit_after>#pragma once #include "point2d.hpp" #include "rect2d.hpp" #include "rect_intersect.hpp" #include "angles.hpp" #include "../base/math.hpp" #include <cmath> namespace m2 { /// axis aligned rect template <typename T> class AnyRect { ang::Angle<T> m_angle; /// @todo No need to store orthos separately. They are stored in m_angle. Point<T> m_i; Point<T> m_j; Point<T> m_zero; Rect<T> m_rect; static Point<T> const Convert(Point<T> const & p, Point<T> const & fromI, Point<T> const & fromJ, Point<T> const & toI, Point<T> const & toJ) { Point<T> res; res.x = p.x * DotProduct(fromI, toI) + p.y * DotProduct(fromJ, toI); res.y = p.x * DotProduct(fromI, toJ) + p.y * DotProduct(fromJ, toJ); return res; } public: AnyRect() : m_i(1, 0), m_j(0, 1), m_zero(0, 0), m_rect() {} /// creating from regular rect explicit AnyRect(Rect<T> const & r) : m_angle(0), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()) { if (r.IsValid()) { m_zero = Point<T>(r.minX(), r.minY()); m_rect = Rect<T>(0, 0, r.SizeX(), r.SizeY()); } else { m_zero = Point<T>(0, 0); m_rect = r; } } AnyRect(Point<T> const & zero, ang::Angle<T> const & angle, Rect<T> const & r) : m_angle(angle), m_i(m_angle.cos(), m_angle.sin()), m_j(-m_angle.sin(), m_angle.cos()), m_zero(Convert(zero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j)), m_rect(r) { } Point<T> const & LocalZero() const { return m_zero; } Point<T> const GlobalZero() const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(m_zero, m_i, m_j, i, j); } Point<T> const & i() const { return m_i; } Point<T> const & j() const { return m_j; } void SetAngle(ang::Angle<T> const & a) { m2::Point<T> glbZero = GlobalZero(); m_angle = a; m_i = m2::Point<T>(m_angle.cos(), m_angle.sin()); m_j = m2::Point<T>(-m_angle.sin(), m_angle.cos()); m_zero = Convert(glbZero, Point<T>(1, 0), Point<T>(0, 1), m_i, m_j); } ang::Angle<T> const & Angle() const { return m_angle; } Point<T> const GlobalCenter() const { return ConvertFrom(m_rect.Center()); } Point<T> const LocalCenter() const { return m_rect.Center(); } bool IsPointInside(Point<T> const & pt) const { return m_rect.IsPointInside(ConvertTo(pt)); } bool IsRectInside(AnyRect<T> const & r) const { m2::Point<T> pts[4]; r.GetGlobalPoints(pts); ConvertTo(pts, 4); return m_rect.IsPointInside(pts[0]) && m_rect.IsPointInside(pts[1]) && m_rect.IsPointInside(pts[2]) && m_rect.IsPointInside(pts[3]); } bool IsIntersect(AnyRect<T> const & r) const { m2::Point<T> pts[4]; if (r.GetLocalRect() == Rect<T>()) return false; r.GetGlobalPoints(pts); ConvertTo(pts, 4); m2::Rect<T> r1(pts[0], pts[0]); r1.Add(pts[1]); r1.Add(pts[2]); r1.Add(pts[3]); if (!GetLocalRect().IsIntersect(r1)) return false; if (r.IsRectInside(*this)) return true; if (IsRectInside(r)) return true; return Intersect(GetLocalRect(), pts[0], pts[1]) || Intersect(GetLocalRect(), pts[1], pts[2]) || Intersect(GetLocalRect(), pts[2], pts[3]) || Intersect(GetLocalRect(), pts[3], pts[0]); } /// Convert into coordinate system of this AnyRect Point<T> const ConvertTo(Point<T> const & p) const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(p - Convert(m_zero, m_i, m_j, i, j), i, j, m_i, m_j); } void ConvertTo(Point<T> * pts, size_t count) const { for (size_t i = 0; i < count; ++i) pts[i] = ConvertTo(pts[i]); } /// Convert into global coordinates from the local coordinates of this AnyRect Point<T> const ConvertFrom(Point<T> const & p) const { m2::Point<T> i(1, 0); m2::Point<T> j(0, 1); return Convert(p + m_zero, m_i, m_j, i, j); } void ConvertFrom(Point<T> * pts, size_t count) const { for (size_t i = 0; i < count; ++i) pts[i] = ConvertFrom(pts[i]); } Rect<T> const & GetLocalRect() const { return m_rect; } Rect<T> const GetGlobalRect() const { Point<T> pts[4]; GetGlobalPoints(pts); Rect<T> res(pts[0], pts[1]); res.Add(pts[2]); res.Add(pts[3]); return res; } void GetGlobalPoints(Point<T> * pts) const { pts[0] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.minY()))); pts[1] = Point<T>(ConvertFrom(Point<T>(m_rect.minX(), m_rect.maxY()))); pts[2] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.maxY()))); pts[3] = Point<T>(ConvertFrom(Point<T>(m_rect.maxX(), m_rect.minY()))); } template <typename U> void Inflate(U const & dx, U const & dy) { m_rect.Inflate(dx, dy); } void Add(AnyRect<T> const & r) { Point<T> pts[4]; r.GetGlobalPoints(pts); ConvertTo(pts, 4); m_rect.Add(pts[0]); m_rect.Add(pts[1]); m_rect.Add(pts[2]); m_rect.Add(pts[3]); } void Offset(Point<T> const & p) { m_zero = ConvertTo(ConvertFrom(m_zero) + p); } }; template <typename T> AnyRect<T> const Offset(AnyRect<T> const & r, Point<T> const & pt) { AnyRect<T> res(r); res.Offset(pt); return res; } template <typename T, typename U> AnyRect<T> const Inflate(AnyRect<T> const & r, U const & dx, U const & dy) { AnyRect<T> res = r; res.Inflate(dx, dy); return res; } template <typename T, typename U> AnyRect<T> const Inflate(AnyRect<T> const & r, Point<U> const & pt) { return Inflate(r, pt.x, pt.y); } typedef AnyRect<double> AnyRectD; typedef AnyRect<float> AnyRectF; template <typename T> inline string DebugPrint(m2::AnyRect<T> const & r) { return DebugPrint(r.GetGlobalRect()); } } <|endoftext|>
<commit_before>#include "misc_ui.hpp" #include <wx/stdpaths.h> #include <wx/msgdlg.h> #include <wx/arrstr.h> #include <exception> #include <stdexcept> namespace Slic3r { namespace GUI { #ifdef SLIC3R_DEV void check_version(bool manual) { } #else void check_version(bool manual) { } #endif const wxString var(const wxString& in) { // TODO replace center string with path to VAR in actual distribution later if (VAR_ABS) { return wxString(VAR_ABS_PATH) + "/" + in; } else { return bin() + wxString(VAR_REL) + "/" + in; } } const wxString bin() { wxFileName f(wxStandardPaths::Get().GetExecutablePath()); wxString appPath(f.GetPath()); return appPath; } /// Returns the path to Slic3r's default user data directory. const wxString home(const wxString& in) { if (the_os == OS::Windows) return wxGetHomeDir() + "/" + in + "/"; return wxGetHomeDir() + "/." + in + "/"; } wxString decode_path(const wxString& in) { // TODO Stub return in; } wxString encode_path(const wxString& in) { // TODO Stub return in; } void show_error(wxWindow* parent, const wxString& message) { wxMessageDialog(parent, message, _("Error"), wxOK | wxICON_ERROR).ShowModal(); } void show_info(wxWindow* parent, const wxString& message, const wxString& title = _("Notice")) { wxMessageDialog(parent, message, title, wxOK | wxICON_INFORMATION).ShowModal(); } void fatal_error(wxWindow* parent, const wxString& message) { show_error(parent, message); throw std::runtime_error(message.ToStdString()); } wxMenuItem* append_submenu(wxMenu* menu, const wxString& name, const wxString& help, wxMenu* submenu, int id, const wxString& icon) { auto* item {new wxMenuItem(menu, id, name, help)}; set_menu_item_icon(item,icon); item->SetSubMenu(submenu); menu->Append(item); return item; } void set_menu_item_icon(wxMenuItem* item, const wxString& icon) { if (!icon.IsEmpty()) { wxBitmap ico; if(ico.LoadFile(var(icon), wxBITMAP_TYPE_PNG)) item->SetBitmap(ico); else std::cerr<< var(icon) << " failed to load \n"; } } /* sub append_submenu { my ($self, $menu, $string, $description, $submenu, $id, $icon) = @_; $id //= &Wx::NewId(); my $item = Wx::MenuItem->new($menu, $id, $string, $description // ''); $self->set_menu_item_icon($item, $icon); $item->SetSubMenu($submenu); $menu->Append($item); return $item; } */ /* sub scan_serial_ports { my ($self) = @_; my @ports = (); if ($^O eq 'MSWin32') { # Windows if (eval "use Win32::TieRegistry; 1") { my $ts = Win32::TieRegistry->new("HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM", { Access => 'KEY_READ' }); if ($ts) { # when no serial ports are available, the registry key doesn't exist and # TieRegistry->new returns undef $ts->Tie(\my %reg); push @ports, sort values %reg; } } } else { # UNIX and OS X push @ports, glob '/dev/{ttyUSB,ttyACM,tty.,cu.,rfcomm}*'; } return grep !/Bluetooth|FireFly/, @ports; } */ /* sub show_error { my ($parent, $message) = @_; Wx::MessageDialog->new($parent, $message, 'Error', wxOK | wxICON_ERROR)->ShowModal; } */ std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top) { auto dialog {new wxFileDialog((parent != nullptr ? parent : top), _("Choose one or more files") + wxString(" (STL/OBJ/AMF/3MF):"), ".", "", MODEL_WILDCARD, wxFD_OPEN | wxFD_MULTIPLE | wxFD_FILE_MUST_EXIST)}; if (dialog->ShowModal() != wxID_OK) { dialog->Destroy(); return std::vector<wxString>(); } std::vector<wxString> tmp; wxArrayString tmpout; dialog->GetPaths(tmpout); for (const auto& i : tmpout) { tmp.push_back(i); } dialog->Destroy(); return tmp; } }} // namespace Slic3r::GUI <commit_msg>Refactoring Settings store.<commit_after>#include "misc_ui.hpp" #include <wx/stdpaths.h> #include <wx/msgdlg.h> #include <wx/arrstr.h> #include <exception> #include <stdexcept> namespace Slic3r { namespace GUI { #ifdef SLIC3R_DEV void check_version(bool manual) { } #else void check_version(bool manual) { } #endif const wxString var(const wxString& in) { // TODO replace center string with path to VAR in actual distribution later if (VAR_ABS) { return wxString(VAR_ABS_PATH) + "/" + in; } else { return bin() + wxString(VAR_REL) + "/" + in; } } const wxString bin() { wxFileName f(wxStandardPaths::Get().GetExecutablePath()); wxString appPath(f.GetPath()); return appPath; } /// Returns the path to Slic3r's default user data directory. const wxString home(const wxString& in) { if (the_os == OS::Windows) return wxGetHomeDir() + "/" + in + "/"; return wxGetHomeDir() + "/." + in + "/"; } wxString decode_path(const wxString& in) { // TODO Stub return in; } wxString encode_path(const wxString& in) { // TODO Stub return in; } void show_error(wxWindow* parent, const wxString& message) { wxMessageDialog(parent, message, _("Error"), wxOK | wxICON_ERROR).ShowModal(); } void show_info(wxWindow* parent, const wxString& message, const wxString& title = _("Notice")) { wxMessageDialog(parent, message, title, wxOK | wxICON_INFORMATION).ShowModal(); } void fatal_error(wxWindow* parent, const wxString& message) { show_error(parent, message); throw std::runtime_error(message.ToStdString()); } wxMenuItem* append_submenu(wxMenu* menu, const wxString& name, const wxString& help, wxMenu* submenu, int id, const wxString& icon) { auto* item {new wxMenuItem(menu, id, name, help)}; set_menu_item_icon(item,icon); item->SetSubMenu(submenu); menu->Append(item); return item; } void set_menu_item_icon(wxMenuItem* item, const wxString& icon) { if (!icon.IsEmpty()) { wxBitmap ico; if(ico.LoadFile(var(icon), wxBITMAP_TYPE_PNG)) item->SetBitmap(ico); else std::cerr<< var(icon) << " failed to load \n"; } } /* sub append_submenu { my ($self, $menu, $string, $description, $submenu, $id, $icon) = @_; $id //= &Wx::NewId(); my $item = Wx::MenuItem->new($menu, $id, $string, $description // ''); $self->set_menu_item_icon($item, $icon); $item->SetSubMenu($submenu); $menu->Append($item); return $item; } */ /* sub scan_serial_ports { my ($self) = @_; my @ports = (); if ($^O eq 'MSWin32') { # Windows if (eval "use Win32::TieRegistry; 1") { my $ts = Win32::TieRegistry->new("HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM", { Access => 'KEY_READ' }); if ($ts) { # when no serial ports are available, the registry key doesn't exist and # TieRegistry->new returns undef $ts->Tie(\my %reg); push @ports, sort values %reg; } } } else { # UNIX and OS X push @ports, glob '/dev/{ttyUSB,ttyACM,tty.,cu.,rfcomm}*'; } return grep !/Bluetooth|FireFly/, @ports; } */ /* sub show_error { my ($parent, $message) = @_; Wx::MessageDialog->new($parent, $message, 'Error', wxOK | wxICON_ERROR)->ShowModal; } */ std::vector<wxString> open_model(wxWindow* parent, wxWindow* top) { auto dialog {new wxFileDialog((parent != nullptr ? parent : top), _("Choose one or more files") + wxString(" (STL/OBJ/AMF/3MF):"), ".", "", MODEL_WILDCARD, wxFD_OPEN | wxFD_MULTIPLE | wxFD_FILE_MUST_EXIST)}; if (dialog->ShowModal() != wxID_OK) { dialog->Destroy(); return std::vector<wxString>(); } std::vector<wxString> tmp; wxArrayString tmpout; dialog->GetPaths(tmpout); for (const auto& i : tmpout) { tmp.push_back(i); } dialog->Destroy(); return tmp; } }} // namespace Slic3r::GUI <|endoftext|>
<commit_before>#include "Hearthstone.h" #include <QFile> #include <QDesktopServices> #include <QSettings> #include <QTextStream> #include <QRegExp> #include <QJsonDocument> #include <QJsonObject> #include <QDirIterator> #include <QDateTime> #ifdef Q_OS_MAC #include "OSXWindowCapture.h" #elif defined Q_OS_WIN #include "WinWindowCapture.h" #include "Shlobj.h" #endif DEFINE_SINGLETON_SCOPE( Hearthstone ); Hearthstone::Hearthstone() : mCapture( NULL ), mGameRunning( false ), mGameHasFocus( false ) { #ifdef Q_OS_MAC mCapture = new OSXWindowCapture(); #elif defined Q_OS_WIN mCapture = new WinWindowCapture(); #endif // On OS X, WindowFound is quite CPU intensive // Starting time for HS is also long // So just check only once in a while mTimer = new QTimer( this ); connect( mTimer, &QTimer::timeout, this, &Hearthstone::Update ); #ifdef Q_OS_MAC mTimer->start( 5000 ); #else mTimer->start( 250 ); #endif } Hearthstone::~Hearthstone() { if( mCapture != NULL ) delete mCapture; } void Hearthstone::Update() { bool isRunning = mCapture->WindowFound(); if( isRunning ) { bool hasFocus = mCapture->HasFocus(); if( mGameHasFocus != hasFocus ) { mGameHasFocus = hasFocus; emit FocusChanged( hasFocus ); } static int lastLeft = 0, lastTop = 0, lastWidth = 0, lastHeight = 0; if( lastLeft != mCapture->Left() || lastTop != mCapture->Top() || lastWidth != mCapture->Width() || lastHeight != mCapture->Height() ) { lastLeft = mCapture->Left(), lastTop = mCapture->Top(), lastWidth = mCapture->Width(), lastHeight = mCapture->Height(); DBG( "HS window changed %d %d %d %d", lastLeft, lastTop, lastWidth, lastHeight ); emit GameWindowChanged( lastLeft, lastTop, lastWidth, lastHeight ); } } if( mGameRunning != isRunning ) { mGameRunning = isRunning; if( isRunning ) { LOG( "Hearthstone is running" ); emit GameStarted(); } else { LOG( "Hearthstone stopped" ); emit GameStopped(); } } } QString Hearthstone::ReadAgentAttribute( const char *attributeName ) const { #ifdef Q_OS_MAC QString path = "/Users/Shared/Battle.net/Agent/agent.db"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_COMMON_APPDATA, FALSE ); QString programData = QString::fromWCharArray( buffer ); QString path = programData + "\\Battle.net\\Agent\\agent.db"; #endif QFile file( path ); if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { DBG( "Couldn't open %s (%d)", qt2cstr( path ), file.error() ); return ""; } QString contents = file.readAll(); QJsonDocument doc = QJsonDocument::fromJson( contents.toUtf8() ); QJsonObject root = doc.object(); QJsonObject hs = root["/game/hs_beta"].toObject()["resource"].toObject()["game"].toObject(); return hs[ QString( attributeName ) ].toString(); } bool Hearthstone::GameRunning() const { return mGameRunning; } #ifdef Q_OS_WIN inline float roundf( float x ) { return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f ); } #endif bool Hearthstone::CaptureWholeScreen( QPixmap *screen ) { *screen = mCapture->Capture( 0, 0, Width(), Height() ); return true; } QPixmap Hearthstone::Capture( int canvasWidth, int canvasHeight, int cx, int cy, int cw, int ch ) { UNUSED_ARG( canvasWidth ); int x, y, w, h; int windowHeight = mCapture->Height(); float scale = windowHeight / float( canvasHeight ); x = roundf( cx * scale ); y = roundf( cy * scale ); w = roundf( cw * scale ); h = roundf( ch * scale ); return mCapture->Capture( x, y, w, h ); } void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) { if( mCapture != NULL ) delete mCapture; mCapture = windowCapture; } void Hearthstone::EnableLogging() { QString path = LogConfigPath(); QFile file( path ); bool logModified = false; // Read file contents QString contents; if( file.exists() ) { file.open( QIODevice::ReadOnly | QIODevice::Text ); QTextStream in( &file ); contents = in.readAll(); file.close(); } // Check what modules we have to activate QStringList modulesToActivate; for( int i = 0; i < NUM_LOG_MODULES; i++ ) { const char *moduleName = LOG_MODULE_NAMES[ i ]; QString moduleLine = QString( "[%1]" ).arg( moduleName ) ; if( !contents.contains( moduleLine ) ) { contents += "\n"; contents += moduleLine + "\n"; contents += "LogLevel=1\n"; contents += "FilePrinting=true\n"; DBG( "Activate module %s", moduleName ); logModified = true; } } QRegExp regexEnabledConsolePrinting( "ConsolePrinting\\s*=\\s*true", Qt::CaseInsensitive ); QRegExp regexDisabledFilePrinting( "FilePrinting\\s*=\\s*false", Qt::CaseInsensitive ); if( contents.contains( regexEnabledConsolePrinting ) || contents.contains( regexDisabledFilePrinting ) ) { contents.replace( regexEnabledConsolePrinting, "FilePrinting=true" ); contents.replace( regexDisabledFilePrinting, "FilePrinting=true" ); DBG( "FilePrinting enabled" ); logModified = true; } // Finally write updated log.config if( logModified ) { DBG( "Log modified. Write new version" ); if( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) { ERR( "Couldn't create file %s", qt2cstr( path ) ); } else { QTextStream out( &file ); out << contents; } } // Notify about restart if game is running Update(); if( GameRunning() && logModified ) { emit GameRequiresRestart(); } } void Hearthstone::DisableLogging() { QFile file( LogConfigPath() ); if( file.exists() ) { file.remove(); LOG( "Ingame log deactivated." ); } } QString Hearthstone::LogConfigPath() const { #ifdef Q_OS_MAC QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first(); QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE ); QString localAppData = QString::fromWCharArray( buffer ); QString configPath = localAppData + "/Blizzard/Hearthstone/log.config"; #endif return configPath; } QString Hearthstone::DetectHearthstonePath() const { static QString hsPath; if( hsPath.isEmpty() ) { #ifdef Q_OS_WIN QString hsPathByAgent = ReadAgentAttribute( "install_dir" ); QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat ); QString hsPathByRegistry = hsKey.value( "InstallLocation" ).toString(); if( hsPathByAgent.isEmpty() && hsPathByRegistry.isEmpty() ) { LOG( "Game folder not found. Fall back to default game path for now. You should set the path manually in the settings!" ); hsPath = QString( getenv("PROGRAMFILES") ) + "/Hearthstone"; } else if( !hsPathByRegistry.isEmpty() ) { hsPath = hsPathByRegistry; } else { hsPath = hsPathByAgent; } #elif defined Q_OS_MAC hsPath = ReadAgentAttribute( "install_dir" ); if( hsPath.isEmpty() ) { LOG( "Fall back to default game path. You should set the path manually in the settings!" ); hsPath = QStandardPaths::standardLocations( QStandardPaths::ApplicationsLocation ).first() + "/Hearthstone"; } #endif } return hsPath; } QString Hearthstone::DetectRegion() const { QString region = ""; #ifdef Q_OS_MAC QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first(); QString path = homeLocation + "/Library/Application Support/Battle.net/"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE ); QString localAppData = QString::fromWCharArray( buffer ); QString path = localAppData + "/Battle.net/"; #endif QDirIterator it( path, QStringList() << "*.config" ); uint lastModifiedTime = 0; QString lastModifiedPath; while( it.hasNext() ) { it.next(); uint modifiedTime = it.fileInfo().lastModified().toTime_t(); if( modifiedTime > lastModifiedTime ) { lastModifiedPath = it.fileInfo().absoluteFilePath(); lastModifiedTime = modifiedTime; } } if( !lastModifiedPath.isEmpty() ) { QFile file(lastModifiedPath); LOG( "File %s", qt2cstr( lastModifiedPath ) ); if( file.open( QIODevice::ReadOnly ) ) { QByteArray data = file.readAll(); QJsonDocument doc = QJsonDocument::fromJson( data ); QJsonObject root = doc.object(); region = root["User"].toObject() ["Client"].toObject() ["PlayScreen"].toObject() ["GameFamily"].toObject() ["WTCG"].toObject() ["LastSelectedGameRegion"].toString(); } else { LOG( "Couldn't open config file %s", qt2cstr( lastModifiedPath ) ); } } return region; } int Hearthstone::Width() const { return mCapture->Width(); } int Hearthstone::Height() const { return mCapture->Height(); } bool Hearthstone::HasFocus() const { return mGameHasFocus; } <commit_msg>Fix region detection on windows<commit_after>#include "Hearthstone.h" #include <QFile> #include <QDesktopServices> #include <QSettings> #include <QTextStream> #include <QRegExp> #include <QJsonDocument> #include <QJsonObject> #include <QDirIterator> #include <QDateTime> #ifdef Q_OS_MAC #include "OSXWindowCapture.h" #elif defined Q_OS_WIN #include "WinWindowCapture.h" #include "Shlobj.h" #endif DEFINE_SINGLETON_SCOPE( Hearthstone ); Hearthstone::Hearthstone() : mCapture( NULL ), mGameRunning( false ), mGameHasFocus( false ) { #ifdef Q_OS_MAC mCapture = new OSXWindowCapture(); #elif defined Q_OS_WIN mCapture = new WinWindowCapture(); #endif // On OS X, WindowFound is quite CPU intensive // Starting time for HS is also long // So just check only once in a while mTimer = new QTimer( this ); connect( mTimer, &QTimer::timeout, this, &Hearthstone::Update ); #ifdef Q_OS_MAC mTimer->start( 5000 ); #else mTimer->start( 250 ); #endif } Hearthstone::~Hearthstone() { if( mCapture != NULL ) delete mCapture; } void Hearthstone::Update() { bool isRunning = mCapture->WindowFound(); if( isRunning ) { bool hasFocus = mCapture->HasFocus(); if( mGameHasFocus != hasFocus ) { mGameHasFocus = hasFocus; emit FocusChanged( hasFocus ); } static int lastLeft = 0, lastTop = 0, lastWidth = 0, lastHeight = 0; if( lastLeft != mCapture->Left() || lastTop != mCapture->Top() || lastWidth != mCapture->Width() || lastHeight != mCapture->Height() ) { lastLeft = mCapture->Left(), lastTop = mCapture->Top(), lastWidth = mCapture->Width(), lastHeight = mCapture->Height(); DBG( "HS window changed %d %d %d %d", lastLeft, lastTop, lastWidth, lastHeight ); emit GameWindowChanged( lastLeft, lastTop, lastWidth, lastHeight ); } } if( mGameRunning != isRunning ) { mGameRunning = isRunning; if( isRunning ) { LOG( "Hearthstone is running" ); emit GameStarted(); } else { LOG( "Hearthstone stopped" ); emit GameStopped(); } } } QString Hearthstone::ReadAgentAttribute( const char *attributeName ) const { #ifdef Q_OS_MAC QString path = "/Users/Shared/Battle.net/Agent/agent.db"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_COMMON_APPDATA, FALSE ); QString programData = QString::fromWCharArray( buffer ); QString path = programData + "\\Battle.net\\Agent\\agent.db"; #endif QFile file( path ); if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { DBG( "Couldn't open %s (%d)", qt2cstr( path ), file.error() ); return ""; } QString contents = file.readAll(); QJsonDocument doc = QJsonDocument::fromJson( contents.toUtf8() ); QJsonObject root = doc.object(); QJsonObject hs = root["/game/hs_beta"].toObject()["resource"].toObject()["game"].toObject(); return hs[ QString( attributeName ) ].toString(); } bool Hearthstone::GameRunning() const { return mGameRunning; } #ifdef Q_OS_WIN inline float roundf( float x ) { return x >= 0.0f ? floorf( x + 0.5f ) : ceilf( x - 0.5f ); } #endif bool Hearthstone::CaptureWholeScreen( QPixmap *screen ) { *screen = mCapture->Capture( 0, 0, Width(), Height() ); return true; } QPixmap Hearthstone::Capture( int canvasWidth, int canvasHeight, int cx, int cy, int cw, int ch ) { UNUSED_ARG( canvasWidth ); int x, y, w, h; int windowHeight = mCapture->Height(); float scale = windowHeight / float( canvasHeight ); x = roundf( cx * scale ); y = roundf( cy * scale ); w = roundf( cw * scale ); h = roundf( ch * scale ); return mCapture->Capture( x, y, w, h ); } void Hearthstone::SetWindowCapture( WindowCapture *windowCapture ) { if( mCapture != NULL ) delete mCapture; mCapture = windowCapture; } void Hearthstone::EnableLogging() { QString path = LogConfigPath(); QFile file( path ); bool logModified = false; // Read file contents QString contents; if( file.exists() ) { file.open( QIODevice::ReadOnly | QIODevice::Text ); QTextStream in( &file ); contents = in.readAll(); file.close(); } // Check what modules we have to activate QStringList modulesToActivate; for( int i = 0; i < NUM_LOG_MODULES; i++ ) { const char *moduleName = LOG_MODULE_NAMES[ i ]; QString moduleLine = QString( "[%1]" ).arg( moduleName ) ; if( !contents.contains( moduleLine ) ) { contents += "\n"; contents += moduleLine + "\n"; contents += "LogLevel=1\n"; contents += "FilePrinting=true\n"; DBG( "Activate module %s", moduleName ); logModified = true; } } QRegExp regexEnabledConsolePrinting( "ConsolePrinting\\s*=\\s*true", Qt::CaseInsensitive ); QRegExp regexDisabledFilePrinting( "FilePrinting\\s*=\\s*false", Qt::CaseInsensitive ); if( contents.contains( regexEnabledConsolePrinting ) || contents.contains( regexDisabledFilePrinting ) ) { contents.replace( regexEnabledConsolePrinting, "FilePrinting=true" ); contents.replace( regexDisabledFilePrinting, "FilePrinting=true" ); DBG( "FilePrinting enabled" ); logModified = true; } // Finally write updated log.config if( logModified ) { DBG( "Log modified. Write new version" ); if( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) { ERR( "Couldn't create file %s", qt2cstr( path ) ); } else { QTextStream out( &file ); out << contents; } } // Notify about restart if game is running Update(); if( GameRunning() && logModified ) { emit GameRequiresRestart(); } } void Hearthstone::DisableLogging() { QFile file( LogConfigPath() ); if( file.exists() ) { file.remove(); LOG( "Ingame log deactivated." ); } } QString Hearthstone::LogConfigPath() const { #ifdef Q_OS_MAC QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first(); QString configPath = homeLocation + "/Library/Preferences/Blizzard/Hearthstone/log.config"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_LOCAL_APPDATA, FALSE ); QString localAppData = QString::fromWCharArray( buffer ); QString configPath = localAppData + "/Blizzard/Hearthstone/log.config"; #endif return configPath; } QString Hearthstone::DetectHearthstonePath() const { static QString hsPath; if( hsPath.isEmpty() ) { #ifdef Q_OS_WIN QString hsPathByAgent = ReadAgentAttribute( "install_dir" ); QSettings hsKey( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Hearthstone", QSettings::NativeFormat ); QString hsPathByRegistry = hsKey.value( "InstallLocation" ).toString(); if( hsPathByAgent.isEmpty() && hsPathByRegistry.isEmpty() ) { LOG( "Game folder not found. Fall back to default game path for now. You should set the path manually in the settings!" ); hsPath = QString( getenv("PROGRAMFILES") ) + "/Hearthstone"; } else if( !hsPathByRegistry.isEmpty() ) { hsPath = hsPathByRegistry; } else { hsPath = hsPathByAgent; } #elif defined Q_OS_MAC hsPath = ReadAgentAttribute( "install_dir" ); if( hsPath.isEmpty() ) { LOG( "Fall back to default game path. You should set the path manually in the settings!" ); hsPath = QStandardPaths::standardLocations( QStandardPaths::ApplicationsLocation ).first() + "/Hearthstone"; } #endif } return hsPath; } QString Hearthstone::DetectRegion() const { QString region = ""; #ifdef Q_OS_MAC QString homeLocation = QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first(); QString path = homeLocation + "/Library/Application Support/Battle.net/"; #elif defined Q_OS_WIN wchar_t buffer[ MAX_PATH ]; SHGetSpecialFolderPathW( NULL, buffer, CSIDL_APPDATA, FALSE ); QString localAppData = QString::fromWCharArray( buffer ); QString path = localAppData + "/Battle.net/"; #endif QDirIterator it( path, QStringList() << "*.config" ); uint lastModifiedTime = 0; QString lastModifiedPath; while( it.hasNext() ) { it.next(); uint modifiedTime = it.fileInfo().lastModified().toTime_t(); if( modifiedTime > lastModifiedTime ) { lastModifiedPath = it.fileInfo().absoluteFilePath(); lastModifiedTime = modifiedTime; } } if( !lastModifiedPath.isEmpty() ) { QFile file(lastModifiedPath); LOG( "File %s", qt2cstr( lastModifiedPath ) ); if( file.open( QIODevice::ReadOnly ) ) { QByteArray data = file.readAll(); QJsonDocument doc = QJsonDocument::fromJson( data ); QJsonObject root = doc.object(); region = root["User"].toObject() ["Client"].toObject() ["PlayScreen"].toObject() ["GameFamily"].toObject() ["WTCG"].toObject() ["LastSelectedGameRegion"].toString(); } else { LOG( "Couldn't open config file %s", qt2cstr( lastModifiedPath ) ); } } return region; } int Hearthstone::Width() const { return mCapture->Width(); } int Hearthstone::Height() const { return mCapture->Height(); } bool Hearthstone::HasFocus() const { return mGameHasFocus; } <|endoftext|>
<commit_before>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_monitoredConfig(0) , m_iteration(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged())); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); monitorConnectedChange(); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); setMonitorForChanges(true); } void KScreenDaemon::applyIdealConfig() { setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { qDebug() << "displayBtn triggered"; if (m_timer->isActive()) { qDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } setMonitorForChanges(true); m_iteration++; qDebug() << "displayButton: " << m_iteration; KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged() { applyIdealConfig(); } void KScreenDaemon::monitorConnectedChange() { if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); } } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { output->disconnect(); }<commit_msg>Set the changeForMonitor to true in the next loop<commit_after>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <QtCore/QDebug> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_monitoredConfig(0) , m_iteration(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 1); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged())); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); monitorConnectedChange(); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { qDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); QMetaObject::invokeMethod(this, "setMonitorForChanges", Qt::QueuedConnection, Q_ARG(bool, true)); } void KScreenDaemon::applyIdealConfig() { setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { qDebug() << "Change detected"; if (m_pendingSave) { return; } qDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { qDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { qDebug() << "displayBtn triggered"; if (m_timer->isActive()) { qDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } setMonitorForChanges(true); m_iteration++; qDebug() << "displayButton: " << m_iteration; KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged() { applyIdealConfig(); } void KScreenDaemon::monitorConnectedChange() { if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); } } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { output->disconnect(); }<|endoftext|>
<commit_before> #include "CTimeManager.h" #include <GLFW/glfw3.h> f64 CTimeManager::CUpdateTick::GetTick() const { return Tick; } f64 CTimeManager::CUpdateTick::GetElapsedTime() const { return Tick; } f64 CTimeManager::CUpdateTick::GetMaxDuration() const { return MaxDuration; } f64 CTimeManager::CUpdateTick::GetAccumulator() const { return Accumulator; } CTimeManager::CUpdateTick::CUpdateTick(f64 const Duration, f64 const MaxDuration) { this->Tick = Duration; this->MaxDuration = MaxDuration; this->Accumulator = 0; } void CTimeManager::CUpdateTick::Update(f64 const Elapsed) { Accumulator = Min(Accumulator + Elapsed, MaxDuration); while (Accumulator > Tick) { Accumulator -= Tick; TriggerEvent(* this); } } void CTimeManager::Init() { LastTime = glfwGetTime(); RunTime = ElapsedTime = 0; TimeMultiplier = 1; } void CTimeManager::Update() { f64 NewTime = glfwGetTime(); ElapsedTime = (NewTime - LastTime) * TimeMultiplier; RunTime += ElapsedTime; LastTime = NewTime; for (auto & UpdateTick : UpdateTicks) UpdateTick->Update(ElapsedTime); } void CTimeManager::SkipElapsedTime() { LastTime = glfwGetTime(); } f64 CTimeManager::GetElapsedTime() const { return ElapsedTime; } f64 CTimeManager::GetActualElapsedTime() const { return ElapsedTime / TimeMultiplier; } f64 CTimeManager::GetRunTime() const { return RunTime; } f64 CTimeManager::GetTimeMultiplier() const { return TimeMultiplier; } void CTimeManager::SetTimeMultiplier(f64 const TimeMultiplier) { this->TimeMultiplier = TimeMultiplier; } CTimeManager::CUpdateTick * CTimeManager::MakeUpdateTick(f64 const Tick, f32 const MaxDuration) { UpdateTicks.push_back(new CUpdateTick{Tick, MaxDuration}); return UpdateTicks.back(); } CTimeManager::CTimeManager() { } <commit_msg>Whitespace<commit_after> #include "CTimeManager.h" #include <GLFW/glfw3.h> f64 CTimeManager::CUpdateTick::GetTick() const { return Tick; } f64 CTimeManager::CUpdateTick::GetElapsedTime() const { return Tick; } f64 CTimeManager::CUpdateTick::GetMaxDuration() const { return MaxDuration; } f64 CTimeManager::CUpdateTick::GetAccumulator() const { return Accumulator; } CTimeManager::CUpdateTick::CUpdateTick(f64 const Duration, f64 const MaxDuration) { this->Tick = Duration; this->MaxDuration = MaxDuration; this->Accumulator = 0; } void CTimeManager::CUpdateTick::Update(f64 const Elapsed) { Accumulator = Min(Accumulator + Elapsed, MaxDuration); while (Accumulator > Tick) { Accumulator -= Tick; TriggerEvent(* this); } } void CTimeManager::Init() { LastTime = glfwGetTime(); RunTime = ElapsedTime = 0; TimeMultiplier = 1; } void CTimeManager::Update() { f64 NewTime = glfwGetTime(); ElapsedTime = (NewTime - LastTime) * TimeMultiplier; RunTime += ElapsedTime; LastTime = NewTime; for (auto & UpdateTick : UpdateTicks) UpdateTick->Update(ElapsedTime); } void CTimeManager::SkipElapsedTime() { LastTime = glfwGetTime(); } f64 CTimeManager::GetElapsedTime() const { return ElapsedTime; } f64 CTimeManager::GetActualElapsedTime() const { return ElapsedTime / TimeMultiplier; } f64 CTimeManager::GetRunTime() const { return RunTime; } f64 CTimeManager::GetTimeMultiplier() const { return TimeMultiplier; } void CTimeManager::SetTimeMultiplier(f64 const TimeMultiplier) { this->TimeMultiplier = TimeMultiplier; } CTimeManager::CUpdateTick * CTimeManager::MakeUpdateTick(f64 const Tick, f32 const MaxDuration) { UpdateTicks.push_back(new CUpdateTick{Tick, MaxDuration}); return UpdateTicks.back(); } CTimeManager::CTimeManager() { } <|endoftext|>
<commit_before>/* MobaTools.h - a library for model railroaders Author: fpm, fpm@mnet-mail.de Copyright (c) 2019 All right reserved. Functions for the stepper part of MobaTools */ #include <MobaTools.h> // Global Data for all instances and classes -------------------------------- extern uint8_t timerInitialized; // variables for softLeds static ledData_t* ledRootP = NULL; //start of ledData-chain static uint8_t ledNextCyc = TIMERPERIODE / CYCLETIME; // next Cycle that is relevant for leds static uint8_t ledCycleCnt = 0; // count IRQ cycles within PWM cycle static ledData_t* ledDataP; // pointer to active Led in ISR void softledISR(uint8_t cyclesLastIRQ) { // ---------------------- softleds ----------------------------------------------- SET_TP2; ledCycleCnt += cyclesLastIRQ; if ( ledCycleCnt >= ledNextCyc ) { // this IRQ is relevant for softleds ledNextCyc = LED_CYCLE_MAX; // there must be atleast one IRQ per PWM Cycle if ( ledCycleCnt >= LED_CYCLE_MAX ) { // start of a new PWM Cycle - switch all leds with rising/falling state to on ledCycleCnt = 0; for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) { //SET_TP1; // loop over led-objects switch ( ledDataP->state ) { case INCBULB: case INCLIN: // switch on led with linear characteristic if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } // check if led on is reached //if ( ledDataP->aStep >= LED_STEP_MAX-1 ) { if ( ledDataP->aCycle >= LED_CYCLE_MAX ) { // led is full on, remove from active-chain SET_TP4; ledDataP->state = STATE_ON; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; ledDataP->aCycle = 0; CLR_TP4; } else { // switch to next PWM step //ledNextCyc = min( ledDataP->aCycle, ledNextCyc); if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle; ledDataP->actPulse = true; } break; case DECBULB: case DECLIN: // switching off led -> next PWM-step //if ( ledDataP->aStep >= LED_STEP_MAX-1 ) { /*if ( ledDataP->aCycle == 0 ) { // led is full off, remove from active-chain SET_TP4; ledDataP->state = STATE_OFF; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; CLR_TP4; //ledDataP->aCycle = 0; } else */{ // switch to next PWM step if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle; ledDataP->actPulse = true; } break; default: ; } // end of 'switch' //CLR_TP1; } // end of led loop } else { // is switchofftime within PWM cycle SET_TP3; for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) { //SET_TP4; if ( ledDataP->actPulse ) { // led is within PWM cycle with output high if ( ledDataP->aCycle <= ledCycleCnt ) { uint8_t tmpIx; // End of ON-time is reached SET_TP4; if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } CLR_TP4; ledDataP->actPulse = false; // determine length of next PWM Cyle //SET_TP1; SET_TP4; ledDataP->aStep += ledDataP->speed; tmpIx = (ledDataP->aStep/DELTASTEPS); if ( tmpIx > LED_IX_MAX ) { // the end is reached CLR_TP4; switch ( ledDataP->state ) { case DECBULB: case DECLIN: // led is off -> remove from chain ledDataP->state = STATE_OFF; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; break; case INCBULB: case INCLIN: // switch permanetly on wirh next cycle ledDataP->aCycle = LED_CYCLE_MAX; break; default: ; } SET_TP4; } else { // we are still in up/down CLR_TP4; switch ( ledDataP->state ) { case INCBULB: ledDataP->aCycle = pgm_read_byte(&(iSteps[tmpIx])); break; case DECBULB: //CLR_TP1; ledDataP->aCycle = LED_CYCLE_MAX-pgm_read_byte(&(iSteps[tmpIx])); //SET_TP1; break; case INCLIN: ledDataP->aCycle = tmpIx; break; case DECLIN: ledDataP->aCycle = LED_CYCLE_MAX - tmpIx; break; default: // no action if state is one of NOTATTACHED, STATE_ON, STATE_OFF break; } SET_TP4; } CLR_TP4; } else { // End of ON-time not yet reached, compute next necessary step CLR_TP3; ledNextCyc = min( ledDataP->aCycle, ledNextCyc); SET_TP3; } } //CLR_TP4; } CLR_TP3; } //CLR_TP3; } // end of softleds //CLR_TP3; nextCycle = min( nextCycle, ( ledNextCyc-ledCycleCnt ) ); //SET_TP3; CLR_TP2; } //=============================== End of softledISR ======================================== ///////////////////////////////////////////////////////////////////////////// //Class SoftLed - for Led with soft on / soft off --------------------------- // Version with Software PWM SoftLed::SoftLed() { ledData.speed = 0; // defines rising/falling timer ledData.aStep = DELTASTEPS ; // actual PWM step ledData.aCycle = 0; // actual cycle ( =length of PWM pule ) ledData.actPulse = false; // PWM pulse is active ledData.state = NOTATTACHED; // initialize setpoint = OFF ; // initialize to off ledType = LINEAR; ledData.nextLedDataP = NULL; // don't put in ISR chain ledData.invFlg = false; } void SoftLed::mount( LedStats_t stateVal ) { // mount softLed to ISR chain ( if not already in ) // new active Softleds are always inserted at the beginning of the chain // only leds in the ISR chain are processed in ISR noInterrupts(); SET_TP2; // check if it's not already active (mounted) // Leds must not be mounted twice! if ( ledData.state < ACTIVE ) { // write backward reference into the existing first entry // only if the chain is not empty if ( ledRootP ) ledRootP->backLedDataPP = &ledData.nextLedDataP; CLR_TP2; ledData.nextLedDataP = ledRootP; ledRootP = &ledData; ledData.backLedDataPP = &ledRootP; SET_TP2; } ledData.state = stateVal; CLR_TP2; interrupts(); } uint8_t SoftLed::attach(uint8_t pinArg, uint8_t invArg ){ // Led-Ausgang mit Softstart. ledData.invFlg = invArg; pinMode( pinArg, OUTPUT ); //DB_PRINT( "Led attached, ledIx = 0x%x, Count = %d", ledIx, ledCount ); ledData.state = STATE_OFF ; // initialize riseTime( LED_DEFAULT_RISETIME ); if ( ledData.invFlg ) { digitalWrite( pinArg, HIGH ); } else { digitalWrite( pinArg, LOW ); } #ifdef FAST_PORTWRT ledData.portPin.Adr = (byte *) pgm_read_word_near(&port_to_output_PGM[pgm_read_byte_near(&digital_pin_to_port_PGM[pinArg])]); ledData.portPin.Mask = pgm_read_byte_near(&digital_pin_to_bit_mask_PGM[pinArg]); #else ledData.pin=pinArg ; // Pin-Nbr #endif if ( !timerInitialized ) seizeTimer1(); // enable compareB- interrupt #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) TIMSK |= ( _BV(OCIExB) ); // enable compare interrupts #elif defined __AVR_MEGA__ TIMSKx |= _BV(OCIExB) ; #elif defined __STM32F1__ timer_cc_enable(MT_TIMER, STEP_CHN); #endif DB_PRINT("IX_MAX=%d, CYCLE_MAX=%d, STEP_MAX=%d, PWMTIME=%d", LED_IX_MAX, LED_CYCLE_MAX, LED_STEP_MAX, LED_PWMTIME ); return true; } void SoftLed::on(){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance LedStats_t stateT; // Don't do anything if its already ON if ( setpoint != ON ) { setpoint = ON ; ledData.aStep = DELTASTEPS; ledData.speed = ledSpeed; if ( ledType == LINEAR ) { stateT = INCLIN; ledData.aCycle = 1; } else { // is bulb simulation stateT = INCBULB; ledData.aCycle = iSteps[1]; } mount(stateT); } //DB_PRINT( "Led %d On, state=%d", ledIx, ledData.state); } void SoftLed::off(){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance LedStats_t stateT; // Dont do anything if its already OFF if ( setpoint != OFF ) { //SET_TP3; setpoint = OFF; ledData.aStep = DELTASTEPS; ledData.speed = ledSpeed; if ( ledType == LINEAR ) { stateT = DECLIN; ledData.aCycle = LED_IX_MAX; } else { // is bulb simulation //CLR_TP3; stateT = DECBULB; ledData.aCycle = LED_CYCLE_MAX - iSteps[1]; } //CLR_TP3; mount(stateT); } //DB_PRINT( "Led %d Off, state=%d", ledIx, ledData.state); } void SoftLed::toggle( void ) { if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance if ( setpoint == ON ) off(); else on(); } void SoftLed::write( uint8_t setpntVal, uint8_t ledPar ){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance ledType = ledPar; write( setpntVal ) ; } void SoftLed::write( uint8_t setpntVal ){ //DB_PRINT( "LedWrite ix= %d, valid= 0x%x, sp=%d, lT=%d", ledIx, ledValid, setpntVal, ledType ); if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance if ( setpntVal == ON ) on(); else off(); #ifdef debug // im Debugmode hier die Led-Daten ausgeben //DB_PRINT( "LedData[%d]\n\speed=%d, Type=%d, aStep=%d, stpCnt=%d, state=%d, setpoint= %d", ledValid, ledSpeed, ledType, ledData.aStep, ledData.stpCnt, ledData.state, setpoint); //DB_PRINT( "ON=%d, NextCyc=%d, CycleCnt=%d, StepIx=%d, NextStep=%d", // ON, ledNextCyc, ledCycleCnt, ledStepIx, ledNextStep); #endif } void SoftLed::riseTime( uint16_t riseTime ) { if ( ledData.state == NOTATTACHED ) return; // length of startphase in ms (min 20ms, max 10240ms ) // The max value ist slower, if CYCLETIME is reduced. // risetime is computed to a 'speed' Value with 16 beeing the slowest // with speed value = 16 means risetime is (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME / 16) // risetime = (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME) / speed // long riseMax = ((long) LED_CYCLE_MAX * DELTASTEPS * LED_PWMTIME ); if ( riseTime <= 20 ) riseTime = 20; if ( riseTime >= riseMax/16 ) riseTime = riseMax/16; int tmp = ( ((long)riseMax *10) / ( riseTime ) +5 ) /10; ledSpeed = tmp; DB_PRINT( "ledSpeed[%d] = %d ( risetime=%d, riseMax=%d, PWMTIME=%d )", ledIx, ledSpeed, riseTime, riseMax, LED_PWMTIME ); } <commit_msg>Update MoToSoftled.cpp<commit_after>/* MobaTools.h - a library for model railroaders Author: fpm, fpm@mnet-mail.de Copyright (c) 2019 All right reserved. Functions for the stepper part of MobaTools */ #include <MobaTools.h> // Global Data for all instances and classes -------------------------------- extern uint8_t timerInitialized; // variables for softLeds static ledData_t* ledRootP = NULL; //start of ledData-chain static uint8_t ledNextCyc = TIMERPERIODE / CYCLETIME; // next Cycle that is relevant for leds static uint8_t ledCycleCnt = 0; // count IRQ cycles within PWM cycle static ledData_t* ledDataP; // pointer to active Led in ISR void softledISR(uint8_t cyclesLastIRQ) { // ---------------------- softleds ----------------------------------------------- SET_TP2; ledCycleCnt += cyclesLastIRQ; if ( ledCycleCnt >= ledNextCyc ) { // this IRQ is relevant for softleds ledNextCyc = LED_CYCLE_MAX; // there must be atleast one IRQ per PWM Cycle if ( ledCycleCnt >= LED_CYCLE_MAX ) { // start of a new PWM Cycle - switch all leds with rising/falling state to on ledCycleCnt = 0; for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) { //SET_TP1; // loop over led-objects switch ( ledDataP->state ) { case INCBULB: case INCLIN: // switch on led with linear characteristic if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } // check if led on is reached //if ( ledDataP->aStep >= LED_STEP_MAX-1 ) { if ( ledDataP->aCycle >= LED_CYCLE_MAX ) { // led is full on, remove from active-chain SET_TP4; ledDataP->state = STATE_ON; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; ledDataP->aCycle = 0; CLR_TP4; } else { // switch to next PWM step //ledNextCyc = min( ledDataP->aCycle, ledNextCyc); if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle; ledDataP->actPulse = true; } break; case DECBULB: case DECLIN: // switching off led -> next PWM-step //if ( ledDataP->aStep >= LED_STEP_MAX-1 ) { /*if ( ledDataP->aCycle == 0 ) { // led is full off, remove from active-chain SET_TP4; ledDataP->state = STATE_OFF; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; CLR_TP4; //ledDataP->aCycle = 0; } else */{ // switch to next PWM step if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } if ( ledNextCyc > ledDataP->aCycle ) ledNextCyc = ledDataP->aCycle; ledDataP->actPulse = true; } break; default: ; } // end of 'switch' //CLR_TP1; } // end of led loop } else { // is switchofftime within PWM cycle SET_TP3; for ( ledDataP=ledRootP; ledDataP!=NULL; ledDataP = ledDataP->nextLedDataP ) { //SET_TP4; if ( ledDataP->actPulse ) { // led is within PWM cycle with output high if ( ledDataP->aCycle <= ledCycleCnt ) { uint8_t tmpIx; // End of ON-time is reached SET_TP4; if (ledDataP->invFlg ) { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr |= ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, HIGH ); #endif } else { #ifdef FAST_PORTWRT *ledDataP->portPin.Adr &= ~ledDataP->portPin.Mask; #else digitalWrite( ledDataP->pin, LOW ); #endif } CLR_TP4; ledDataP->actPulse = false; // determine length of next PWM Cyle //SET_TP1; SET_TP4; ledDataP->aStep += ledDataP->speed; tmpIx = (ledDataP->aStep/DELTASTEPS); if ( tmpIx > LED_IX_MAX ) { // the end is reached CLR_TP4; switch ( ledDataP->state ) { case DECBULB: case DECLIN: // led is off -> remove from chain ledDataP->state = STATE_OFF; *ledDataP->backLedDataPP = ledDataP->nextLedDataP; if ( ledDataP->nextLedDataP ) ledDataP->nextLedDataP->backLedDataPP = ledDataP->backLedDataPP; break; case INCBULB: case INCLIN: // switch permanetly on wirh next cycle ledDataP->aCycle = LED_CYCLE_MAX; break; default: ; } SET_TP4; } else { // we are still in up/down CLR_TP4; switch ( ledDataP->state ) { case INCBULB: ledDataP->aCycle = pgm_read_byte(&(iSteps[tmpIx])); break; case DECBULB: //CLR_TP1; ledDataP->aCycle = LED_CYCLE_MAX-pgm_read_byte(&(iSteps[tmpIx])); //SET_TP1; break; case INCLIN: ledDataP->aCycle = tmpIx; break; case DECLIN: ledDataP->aCycle = LED_CYCLE_MAX - tmpIx; break; default: // no action if state is one of NOTATTACHED, STATE_ON, STATE_OFF break; } SET_TP4; } CLR_TP4; } else { // End of ON-time not yet reached, compute next necessary step CLR_TP3; ledNextCyc = min( ledDataP->aCycle, ledNextCyc); SET_TP3; } } //CLR_TP4; } CLR_TP3; } //CLR_TP3; } // end of softleds //CLR_TP3; nextCycle = min( nextCycle, ( ledNextCyc-ledCycleCnt ) ); //SET_TP3; CLR_TP2; } //=============================== End of softledISR ======================================== ///////////////////////////////////////////////////////////////////////////// //Class SoftLed - for Led with soft on / soft off --------------------------- // Version with Software PWM SoftLed::SoftLed() { ledData.speed = 0; // defines rising/falling timer ledData.aStep = DELTASTEPS ; // actual PWM step ledData.aCycle = 0; // actual cycle ( =length of PWM pule ) ledData.actPulse = false; // PWM pulse is active ledData.state = NOTATTACHED; // initialize setpoint = OFF ; // initialize to off ledType = LINEAR; ledData.nextLedDataP = NULL; // don't put in ISR chain ledData.invFlg = false; } void SoftLed::mount( LedStats_t stateVal ) { // mount softLed to ISR chain ( if not already in ) // new active Softleds are always inserted at the beginning of the chain // only leds in the ISR chain are processed in ISR noInterrupts(); SET_TP2; // check if it's not already active (mounted) // Leds must not be mounted twice! if ( ledData.state < ACTIVE ) { // write backward reference into the existing first entry // only if the chain is not empty if ( ledRootP ) ledRootP->backLedDataPP = &ledData.nextLedDataP; CLR_TP2; ledData.nextLedDataP = ledRootP; ledRootP = &ledData; ledData.backLedDataPP = &ledRootP; SET_TP2; } ledData.state = stateVal; CLR_TP2; interrupts(); } uint8_t SoftLed::attach(uint8_t pinArg, uint8_t invArg ){ // Led-Ausgang mit Softstart. ledData.invFlg = invArg; pinMode( pinArg, OUTPUT ); //DB_PRINT( "Led attached, ledIx = 0x%x, Count = %d", ledIx, ledCount ); ledData.state = STATE_OFF ; // initialize riseTime( LED_DEFAULT_RISETIME ); if ( ledData.invFlg ) { digitalWrite( pinArg, HIGH ); } else { digitalWrite( pinArg, LOW ); } #ifdef FAST_PORTWRT ledData.portPin.Adr = (byte *) pgm_read_word_near(&port_to_output_PGM[pgm_read_byte_near(&digital_pin_to_port_PGM[pinArg])]); ledData.portPin.Mask = pgm_read_byte_near(&digital_pin_to_bit_mask_PGM[pinArg]); #else ledData.pin=pinArg ; // Pin-Nbr #endif if ( !timerInitialized ) seizeTimer1(); // enable compareB- interrupt #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) TIMSK |= ( _BV(OCIExB) ); // enable compare interrupts #elif defined __AVR_MEGA__ TIMSKx |= _BV(OCIExB) ; #elif defined __STM32F1__ timer_cc_enable(MT_TIMER, STEP_CHN); #endif DB_PRINT("IX_MAX=%d, CYCLE_MAX=%d, PWMTIME=%d", LED_IX_MAX, LED_CYCLE_MAX, LED_PWMTIME ); return true; } void SoftLed::on(){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance LedStats_t stateT; // Don't do anything if its already ON if ( setpoint != ON ) { setpoint = ON ; ledData.aStep = DELTASTEPS; ledData.speed = ledSpeed; if ( ledType == LINEAR ) { stateT = INCLIN; ledData.aCycle = 1; } else { // is bulb simulation stateT = INCBULB; ledData.aCycle = iSteps[1]; } mount(stateT); } //DB_PRINT( "Led %d On, state=%d", ledIx, ledData.state); } void SoftLed::off(){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance LedStats_t stateT; // Dont do anything if its already OFF if ( setpoint != OFF ) { //SET_TP3; setpoint = OFF; ledData.aStep = DELTASTEPS; ledData.speed = ledSpeed; if ( ledType == LINEAR ) { stateT = DECLIN; ledData.aCycle = LED_IX_MAX; } else { // is bulb simulation //CLR_TP3; stateT = DECBULB; ledData.aCycle = LED_CYCLE_MAX - iSteps[1]; } //CLR_TP3; mount(stateT); } //DB_PRINT( "Led %d Off, state=%d", ledIx, ledData.state); } void SoftLed::toggle( void ) { if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance if ( setpoint == ON ) off(); else on(); } void SoftLed::write( uint8_t setpntVal, uint8_t ledPar ){ if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance ledType = ledPar; write( setpntVal ) ; } void SoftLed::write( uint8_t setpntVal ){ //DB_PRINT( "LedWrite ix= %d, valid= 0x%x, sp=%d, lT=%d", ledIx, ledValid, setpntVal, ledType ); if ( ledData.state == NOTATTACHED ) return; // this is not a valid instance if ( setpntVal == ON ) on(); else off(); #ifdef debug // im Debugmode hier die Led-Daten ausgeben //DB_PRINT( "LedData[%d]\n\speed=%d, Type=%d, aStep=%d, stpCnt=%d, state=%d, setpoint= %d", ledValid, ledSpeed, ledType, ledData.aStep, ledData.stpCnt, ledData.state, setpoint); //DB_PRINT( "ON=%d, NextCyc=%d, CycleCnt=%d, StepIx=%d, NextStep=%d", // ON, ledNextCyc, ledCycleCnt, ledStepIx, ledNextStep); #endif } void SoftLed::riseTime( uint16_t riseTime ) { if ( ledData.state == NOTATTACHED ) return; // length of startphase in ms (min 20ms, max 10240ms ) // The max value ist slower, if CYCLETIME is reduced. // risetime is computed to a 'speed' Value with 16 beeing the slowest // with speed value = 16 means risetime is (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME / 16) // risetime = (LED_CYCLE_MAX * LED_PWMTIME * DELTATIME) / speed // long riseMax = ((long) LED_CYCLE_MAX * DELTASTEPS * LED_PWMTIME ); if ( riseTime <= 20 ) riseTime = 20; if ( riseTime >= riseMax/16 ) riseTime = riseMax/16; int tmp = ( ((long)riseMax *10) / ( riseTime ) +5 ) /10; ledSpeed = tmp; DB_PRINT( "ledSpeed = %d ( risetime=%d, riseMax=%d, PWMTIME=%d )", ledSpeed, riseTime, riseMax, LED_PWMTIME ); } <|endoftext|>
<commit_before>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You 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. ****************************************************************************/ /** * @file * @brief IronBee++ Internals --- Hash Tests * * @author Christopher Alfeld <calfeld@qualys.com> **/ #include <ironbeepp/hash.hpp> #include "gtest/gtest.h" #include <string> #include <boost/foreach.hpp> using namespace std; using namespace IronBee; class TestHash : public ::testing::Test { public: TestHash() : m_pool(m_scoped_pool) { // nop } protected: ScopedMemoryPool m_scoped_pool; MemoryPool m_pool; }; TEST_F(TestHash, pointer_hash_const_iterator) { static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; namespace I = Internal; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a); ib_hash_set(h, "key_b", (void *)b); ib_hash_set(h, "key_c", (void *)c); I::pointer_hash_const_iterator<const char*> b_i(h); I::pointer_hash_const_iterator<const char*> e_i; EXPECT_TRUE(b_i != e_i); multiset<string> found_keys; multiset<const char*> found_values; found_keys.insert(string(b_i->first.first, b_i->first.second)); found_values.insert(b_i->second); I::pointer_hash_const_iterator<const char*> n_i = b_i; EXPECT_TRUE(b_i == n_i); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(e_i == n_i); EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); } TEST_F(TestHash, hash_const_iterator) { static const ConstByteString a = ByteString::create(m_pool, "a"); static const ConstByteString b = ByteString::create(m_pool, "b"); static const ConstByteString c = ByteString::create(m_pool, "c"); namespace I = Internal; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a.ib()); ib_hash_set(h, "key_b", (void *)b.ib()); ib_hash_set(h, "key_c", (void *)c.ib()); I::hash_const_iterator<ConstByteString> b_i(h); I::hash_const_iterator<ConstByteString> e_i; EXPECT_TRUE(b_i != e_i); multiset<string> found_keys; multiset<ConstByteString> found_values; found_keys.insert(string(b_i->first.first, b_i->first.second)); found_values.insert(b_i->second); I::hash_const_iterator<ConstByteString> n_i = b_i; EXPECT_TRUE(b_i == n_i); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(e_i == n_i); EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); } TEST_F(TestHash, ConstHash) { static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a); ib_hash_set(h, "key_b", (void *)b); ib_hash_set(h, "key_c", (void *)c); ConstHash<const char*> hash(h); EXPECT_EQ(h, hash.ib()); multiset<string> found_keys; multiset<const char*> found_values; BOOST_FOREACH(ConstHash<const char*>::const_reference v, hash) { found_keys.insert(string(v.first.first, v.first.second)); found_values.insert(v.second); } EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); EXPECT_FALSE(hash.empty()); EXPECT_EQ(3UL, hash.size()); EXPECT_EQ(m_pool, hash.memory_pool()); EXPECT_EQ(a, hash.get("key_a", 5)); EXPECT_EQ(a, hash.get(string("key_a"))); EXPECT_EQ(a, hash.get(ByteString::create(m_pool, "key_a"))); EXPECT_EQ(a, hash[string("key_a")]); EXPECT_EQ(a, hash[ByteString::create(m_pool, "key_a")]); List<const char*> l = List<const char*>::create(m_pool); hash.get_all(l); EXPECT_EQ(3, l.size()); } TEST_F(TestHash, PointerHash) { typedef Hash<const char*> hash_t; hash_t h = hash_t::create(m_pool); ASSERT_TRUE(h); EXPECT_TRUE(h.empty()); EXPECT_EQ(0UL, h.size()); static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; h.set("key_a", 5, a); h.set("key_b", 5, b); h.set("key_c", 5, c); EXPECT_EQ(3UL, h.size()); EXPECT_EQ(a, h.get("key_a")); EXPECT_EQ(b, h.remove("key_b")); EXPECT_EQ(2UL, h.size()); EXPECT_THROW(h.get("key_b"), enoent); h.clear(); EXPECT_TRUE(h.empty()); EXPECT_THROW(h.get("key_a"), enoent); } TEST_F(TestHash, IBHash) { typedef Hash<ConstByteString> hash_t; hash_t h = hash_t::create(m_pool); ASSERT_TRUE(h); EXPECT_TRUE(h.empty()); EXPECT_EQ(0UL, h.size()); static const ConstByteString a = ByteString::create(m_pool, "a"); static const ConstByteString b = ByteString::create(m_pool, "b"); static const ConstByteString c = ByteString::create(m_pool, "c"); h.set("key_a", 5, a); h.set("key_b", 5, b); h.set("key_c", 5, c); EXPECT_EQ(3UL, h.size()); EXPECT_EQ(a, h.get("key_a")); EXPECT_EQ(b, h.remove("key_b")); EXPECT_EQ(2UL, h.size()); EXPECT_THROW(h.get("key_b"), enoent); h.clear(); EXPECT_TRUE(h.empty()); EXPECT_THROW(h.get("key_a"), enoent); } <commit_msg>ironbee++/tests/test_hash: Fix issue with signed vs unsigned.<commit_after>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You 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. ****************************************************************************/ /** * @file * @brief IronBee++ Internals --- Hash Tests * * @author Christopher Alfeld <calfeld@qualys.com> **/ #include <ironbeepp/hash.hpp> #include "gtest/gtest.h" #include <string> #include <boost/foreach.hpp> using namespace std; using namespace IronBee; class TestHash : public ::testing::Test { public: TestHash() : m_pool(m_scoped_pool) { // nop } protected: ScopedMemoryPool m_scoped_pool; MemoryPool m_pool; }; TEST_F(TestHash, pointer_hash_const_iterator) { static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; namespace I = Internal; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a); ib_hash_set(h, "key_b", (void *)b); ib_hash_set(h, "key_c", (void *)c); I::pointer_hash_const_iterator<const char*> b_i(h); I::pointer_hash_const_iterator<const char*> e_i; EXPECT_TRUE(b_i != e_i); multiset<string> found_keys; multiset<const char*> found_values; found_keys.insert(string(b_i->first.first, b_i->first.second)); found_values.insert(b_i->second); I::pointer_hash_const_iterator<const char*> n_i = b_i; EXPECT_TRUE(b_i == n_i); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(e_i == n_i); EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); } TEST_F(TestHash, hash_const_iterator) { static const ConstByteString a = ByteString::create(m_pool, "a"); static const ConstByteString b = ByteString::create(m_pool, "b"); static const ConstByteString c = ByteString::create(m_pool, "c"); namespace I = Internal; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a.ib()); ib_hash_set(h, "key_b", (void *)b.ib()); ib_hash_set(h, "key_c", (void *)c.ib()); I::hash_const_iterator<ConstByteString> b_i(h); I::hash_const_iterator<ConstByteString> e_i; EXPECT_TRUE(b_i != e_i); multiset<string> found_keys; multiset<ConstByteString> found_values; found_keys.insert(string(b_i->first.first, b_i->first.second)); found_values.insert(b_i->second); I::hash_const_iterator<ConstByteString> n_i = b_i; EXPECT_TRUE(b_i == n_i); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(b_i != n_i); EXPECT_TRUE(e_i != n_i); found_keys.insert(string(n_i->first.first, n_i->first.second)); found_values.insert(n_i->second); ++n_i; EXPECT_TRUE(e_i == n_i); EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); } TEST_F(TestHash, ConstHash) { static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; ib_hash_t* h; ASSERT_EQ(IB_OK, ib_hash_create(&h, m_pool.ib())); ib_hash_set(h, "key_a", (void *)a); ib_hash_set(h, "key_b", (void *)b); ib_hash_set(h, "key_c", (void *)c); ConstHash<const char*> hash(h); EXPECT_EQ(h, hash.ib()); multiset<string> found_keys; multiset<const char*> found_values; BOOST_FOREACH(ConstHash<const char*>::const_reference v, hash) { found_keys.insert(string(v.first.first, v.first.second)); found_values.insert(v.second); } EXPECT_EQ(3UL, found_keys.size()); EXPECT_EQ(3UL, found_values.size()); EXPECT_EQ(1UL, found_keys.count("key_a")); EXPECT_EQ(1UL, found_keys.count("key_b")); EXPECT_EQ(1UL, found_keys.count("key_c")); EXPECT_EQ(1UL, found_values.count(a)); EXPECT_EQ(1UL, found_values.count(b)); EXPECT_EQ(1UL, found_values.count(c)); EXPECT_FALSE(hash.empty()); EXPECT_EQ(3UL, hash.size()); EXPECT_EQ(m_pool, hash.memory_pool()); EXPECT_EQ(a, hash.get("key_a", 5)); EXPECT_EQ(a, hash.get(string("key_a"))); EXPECT_EQ(a, hash.get(ByteString::create(m_pool, "key_a"))); EXPECT_EQ(a, hash[string("key_a")]); EXPECT_EQ(a, hash[ByteString::create(m_pool, "key_a")]); List<const char*> l = List<const char*>::create(m_pool); hash.get_all(l); EXPECT_EQ(3UL, l.size()); } TEST_F(TestHash, PointerHash) { typedef Hash<const char*> hash_t; hash_t h = hash_t::create(m_pool); ASSERT_TRUE(h); EXPECT_TRUE(h.empty()); EXPECT_EQ(0UL, h.size()); static const char* a = "a"; static const char* b = "b"; static const char* c = "c"; h.set("key_a", 5, a); h.set("key_b", 5, b); h.set("key_c", 5, c); EXPECT_EQ(3UL, h.size()); EXPECT_EQ(a, h.get("key_a")); EXPECT_EQ(b, h.remove("key_b")); EXPECT_EQ(2UL, h.size()); EXPECT_THROW(h.get("key_b"), enoent); h.clear(); EXPECT_TRUE(h.empty()); EXPECT_THROW(h.get("key_a"), enoent); } TEST_F(TestHash, IBHash) { typedef Hash<ConstByteString> hash_t; hash_t h = hash_t::create(m_pool); ASSERT_TRUE(h); EXPECT_TRUE(h.empty()); EXPECT_EQ(0UL, h.size()); static const ConstByteString a = ByteString::create(m_pool, "a"); static const ConstByteString b = ByteString::create(m_pool, "b"); static const ConstByteString c = ByteString::create(m_pool, "c"); h.set("key_a", 5, a); h.set("key_b", 5, b); h.set("key_c", 5, c); EXPECT_EQ(3UL, h.size()); EXPECT_EQ(a, h.get("key_a")); EXPECT_EQ(b, h.remove("key_b")); EXPECT_EQ(2UL, h.size()); EXPECT_THROW(h.get("key_b"), enoent); h.clear(); EXPECT_TRUE(h.empty()); EXPECT_THROW(h.get("key_a"), enoent); } <|endoftext|>
<commit_before>#include "crange_arch.hh" #include "radix.hh" enum { radix_debug = 0 }; #define dprintf(...) do { if (radix_debug) cprintf(__VA_ARGS__); } while(0) static_assert(key_bits == bits_per_level * radix_levels, "for now, we only support exact multiples of bits_per_level"); // Returns the index needed to reach |level| from |level+1|. static u32 index(u64 key, u32 level) { u64 idx = key >> (bits_per_level * level); idx &= (1 << bits_per_level) - 1; return idx; } // Returns the size of a subtree for a node at |level|. static u64 level_size(u32 level) { return 1L << (bits_per_level * level); } static radix_entry push_down(radix_entry cur, radix_ptr *ptr) { while (cur.state() != entry_node) { // If we're locked, just spin and try again. if (cur.state() == entry_locked) { cur = ptr->load(); continue; } // Make a new node. assert(cur.state() == entry_unlocked); radix_elem *elem = cur.elem(); radix_node *new_rn = new radix_node(); if (elem != nullptr) { for (int i = 0; i < (1<<bits_per_level); i++) { new_rn->child[i].store(radix_entry(elem)); } elem->incref(1<<bits_per_level); } if (ptr->compare_exchange_weak(cur, radix_entry(new_rn))) { // Release the ref from the pointer we replaced. FIXME: Bouncing // on the reference count here is annoying. Maybe the reference // count should be dependent on the high of the leaf? if (elem != nullptr) elem->decref(); } else { // Someone else beat us to it. Back out. FIXME: docs say // compare_exchange_weak can return spuriously. Should avoid // reallocating new_rn if elem doesn't change. // Avoid bouncing on the refcount 1<<bits_per_level times. if (elem != nullptr) { for (int i = 0; i < (1<<bits_per_level); i++) { new_rn->child[i].store(radix_entry(nullptr)); } elem->decref(1<<bits_per_level); } delete new_rn; } } return cur; } // Runs CB of a set of leaves whose disjoint union is the range // [start, end) template <class CB> void update_range(radix_entry cur, radix_ptr *ptr, CB cb, u64 cur_start, u64 cur_end, u64 start, u64 end, u32 level = radix_levels) { assert(level_size(level) == cur_end - cur_start); // Assert that our ranges intersect; if this fails, we got the loop // below wrong. assert(cur_start < end && start < cur_end) // If our range is not strictly contained in the target, ensure we // are at a node. if (start > cur_start || end < cur_end) { cur = push_down(cur, ptr); } if (cur.is_node()) { // Find the place to start. if (start < cur_start) start = cur_start; assert(level > 0); int i = index(start, level - 1); u64 child_size = (cur_end - cur_start) >> bits_per_level; u64 child_start = cur_start + i * child_size; for (; (i < (1<<bits_per_level)) && (child_start < end); i++, child_start += child_size) { radix_ptr *child = &cur.node()->child[i]; update_range(child->load(), child, cb, child_start, child_start + child_size, start, end, level - 1); } } else { // If we're here, the target range must completely contain this // element. assert(start <= cur_start && cur_end <= end); cb(cur, ptr, cur_start, cur_end, level); } } void radix_entry::release() { if (is_null()) return; if (is_node()) { delete node(); } else { elem()->decref(); } } radix_node::~radix_node() { for (int i = 0; i < (1<<bits_per_level); i++) { child[i].load().release(); } } radix::~radix() { root_.load().release(); } radix_elem* radix::search(u64 key) { scoped_gc_epoch gc; radix_entry cur = root_.load(); for (u32 level = radix_levels-1; level >= 0 && !cur.is_elem(); level--) { cur = cur.node()->child[index(key >> shift_, level)].load(); } dprintf("%p: search(%lx) -> %p\n", this, key >> shift_, cur.elem()); return cur.elem(); } radix_range radix::search_lock(u64 start, u64 size) { return radix_range(this, start >> shift_, size >> shift_); } // This should be a lambda, but it's awkward for a lambda to call // itself. struct entry_locker { u64 start_; u64 end_; entry_locker(u64 start, u64 end) : start_(start), end_(end) { } void operator()(radix_entry cur, radix_ptr *ptr, u64 cur_start, u64 cur_end, u32 level) const { while (cur.state() != entry_node) { // Locked -> spin and try again. if (cur.state() == entry_locked) { cur = ptr->load(); continue; } // Otherwise it's unlocked. Try to load it. if (ptr->compare_exchange_weak(cur, cur.with_state(entry_locked))) { // Success. Remember the current value and break out. cur = cur.with_state(entry_locked); break; } } // Someone pushed down. Recurse some more. if (cur.state() == entry_node) { update_range(cur, ptr, *this, cur_start, cur_end, start_, end_, level-1); } else { // We managed to lock! assert(cur.state() == entry_locked); } } }; radix_range::radix_range(radix *r, u64 start, u64 size) : r_(r), start_(start), size_(size) { u64 end = start_ + size_; // Lock the range from left to right. const entry_locker& cb = entry_locker(start_, end); update_range(r_->root_.load(), &r_->root_, cb, 0, 1L << key_bits, start_, end); } radix_range::~radix_range() { if (!r_) return; update_range(r_->root_.load(), &r_->root_, [](radix_entry cur, radix_ptr *ptr, u64 cur_start, u64 cur_end, u32 level) { do { // It had better still be locked. assert(cur.state() == entry_locked); } while (!ptr->compare_exchange_weak(cur, cur.with_state(entry_unlocked))); }, 0, 1L << key_bits, start_, start_ + size_); } void radix_range::replace(u64 start, u64 size, radix_elem *val) { start = start >> r_->shift_; size = size >> r_->shift_; dprintf("%p: replace: [%lx, %lx) with %p\n", r_, start, start + size, val); assert(start >= start_); assert(start + size <= start_ + size_); update_range(r_->root_.load(), &r_->root_, [val](radix_entry cur, radix_ptr *ptr, u64 cur_start, u64 cur_end, u32 level) { dprintf(" -> [%lx, %lx); size = %lx\n", cur_start, cur_end, cur_end - cur_start); do { assert(cur.state() == entry_locked); } while (!ptr->compare_exchange_weak(cur, radix_entry(val, entry_locked))); if (val) val->incref(); if (!cur.is_null()) cur.elem()->decref(); }, 0, 1L << key_bits, start, start + size); } radix_iterator::radix_iterator(const radix* r, u64 k) : r_(r), k_(k) { dprintf("%p: Made iterator with k = %lx\n", r_, k_); if (k_ != ~0ULL) { path_[radix_levels] = r_->root_.load(); if (path_[radix_levels].is_elem()) leaf_ = radix_levels; // Maybe best to not do this... else if (!find_first_leaf(radix_levels - 1)) k_ = ~0ULL; } dprintf("%p: Adjusted: k = %lx\n", r_, k_); } bool radix_iterator::advance(u32 level) { // First, see if we can advance a lower level. if (level > leaf_ && advance(level-1)) { // Nothing more to do. return true; } // Try to advance this level, if we can. u32 start_idx = index(k_, level)+1; if (start_idx < (1<<bits_per_level)) { // Find the first leaf starting at our sibling node. k_ &= ~((1ULL<<((level+1) * bits_per_level)) - 1); k_ |= (u64(start_idx) << (level * bits_per_level)); return find_first_leaf(level); } else { return false; } } bool radix_iterator::find_first_leaf(u32 level) { // Find the first non-empty node after k_ on this level. for (u32 idx = index(k_, level); idx < (1<<bits_per_level); idx++) { radix_entry next = node(level+1)->child[idx].load(); if (!next.is_null()) { if (index(k_, level) != idx) { // We had to advance; clear everything this level and under // and set this one. k_ &= ~((1ULL<<((level+1) * bits_per_level)) - 1); k_ |= (u64(idx) << (level * bits_per_level)); } path_[level] = next; if (next.is_elem()) { // Found a leaf. Stop now. leaf_ = level; return true; } else if (find_first_leaf(level-1)) // Keep looking. return true; } } // Failed to find a leaf. Abort. return false; } <commit_msg>When leaves turn into nodes, drive the recursion in update_range<commit_after>#include "crange_arch.hh" #include "radix.hh" enum { radix_debug = 0 }; #define dprintf(...) do { if (radix_debug) cprintf(__VA_ARGS__); } while(0) static_assert(key_bits == bits_per_level * radix_levels, "for now, we only support exact multiples of bits_per_level"); // Returns the index needed to reach |level| from |level+1|. static u32 index(u64 key, u32 level) { u64 idx = key >> (bits_per_level * level); idx &= (1 << bits_per_level) - 1; return idx; } // Returns the size of a subtree for a node at |level|. static u64 level_size(u32 level) { return 1L << (bits_per_level * level); } static radix_entry push_down(radix_entry cur, radix_ptr *ptr) { while (cur.state() != entry_node) { // If we're locked, just spin and try again. if (cur.state() == entry_locked) { cur = ptr->load(); continue; } // Make a new node. assert(cur.state() == entry_unlocked); radix_elem *elem = cur.elem(); radix_node *new_rn = new radix_node(); if (elem != nullptr) { for (int i = 0; i < (1<<bits_per_level); i++) { new_rn->child[i].store(radix_entry(elem)); } elem->incref(1<<bits_per_level); } if (ptr->compare_exchange_weak(cur, radix_entry(new_rn))) { // Release the ref from the pointer we replaced. FIXME: Bouncing // on the reference count here is annoying. Maybe the reference // count should be dependent on the high of the leaf? if (elem != nullptr) elem->decref(); } else { // Someone else beat us to it. Back out. FIXME: docs say // compare_exchange_weak can return spuriously. Should avoid // reallocating new_rn if elem doesn't change. // Avoid bouncing on the refcount 1<<bits_per_level times. if (elem != nullptr) { for (int i = 0; i < (1<<bits_per_level); i++) { new_rn->child[i].store(radix_entry(nullptr)); } elem->decref(1<<bits_per_level); } delete new_rn; } } return cur; } // Runs |cb| of a set of leaves whose disjoint union is the range // [start, end). Callback returns the last known state of the // radix_ptr. It is assumed |cb| does not convert the leaf into a // node. If |cb| returns an entry_node, we recurse into the node and // call |cb| on the new subtree. template <class CB> void update_range(radix_entry cur, radix_ptr *ptr, CB cb, u64 cur_start, u64 cur_end, u64 start, u64 end, u32 level = radix_levels) { assert(level_size(level) == cur_end - cur_start); // Assert that our ranges intersect; if this fails, we got the loop // below wrong. assert(cur_start < end && start < cur_end) // If our range is not strictly contained in the target, ensure we // are at a node. if (start > cur_start || end < cur_end) { cur = push_down(cur, ptr); } if (cur.is_elem()) { // If we're here, the target range must completely contain this // element. assert(start <= cur_start && cur_end <= end); dprintf(" -> [%lx, %lx); size = %lx\n", cur_start, cur_end, cur_end - cur_start); cur = cb(cur, ptr); } // Recurse if we became a node or we already one. if (cur.is_node()) { // Find the place to start. if (start < cur_start) start = cur_start; assert(level > 0); int i = index(start, level - 1); u64 child_size = (cur_end - cur_start) >> bits_per_level; u64 child_start = cur_start + i * child_size; for (; (i < (1<<bits_per_level)) && (child_start < end); i++, child_start += child_size) { radix_ptr *child = &cur.node()->child[i]; update_range(child->load(), child, cb, child_start, child_start + child_size, start, end, level - 1); } } } void radix_entry::release() { if (is_null()) return; if (is_node()) { delete node(); } else { elem()->decref(); } } radix_node::~radix_node() { for (int i = 0; i < (1<<bits_per_level); i++) { child[i].load().release(); } } radix::~radix() { root_.load().release(); } radix_elem* radix::search(u64 key) { scoped_gc_epoch gc; radix_entry cur = root_.load(); for (u32 level = radix_levels-1; level >= 0 && !cur.is_elem(); level--) { cur = cur.node()->child[index(key >> shift_, level)].load(); } dprintf("%p: search(%lx) -> %p\n", this, key >> shift_, cur.elem()); return cur.elem(); } radix_range radix::search_lock(u64 start, u64 size) { return radix_range(this, start >> shift_, size >> shift_); } radix_range::radix_range(radix *r, u64 start, u64 size) : r_(r), start_(start), size_(size) { u64 end = start_ + size_; // Lock the range from left to right. dprintf("%p: lock [%lx, %lx)\n", r_, start, start + size); update_range(r_->root_.load(), &r_->root_, [](radix_entry cur, radix_ptr *ptr) -> radix_entry { while (cur.state() != entry_node) { // Locked -> spin and try again. if (cur.state() == entry_locked) { cur = ptr->load(); continue; } // Otherwise it's unlocked. Try to load it. if (ptr->compare_exchange_weak(cur, cur.with_state(entry_locked))) { // Success. Remember the current value and break out. cur = cur.with_state(entry_locked); break; } } // We either managed a lock or someone turned us into a node. assert(cur.state() == entry_node || cur.state() == entry_locked); return cur; }, 0, 1L << key_bits, start_, end); } radix_range::~radix_range() { if (!r_) return; dprintf("%p: unlock [%lx, %lx)\n", r_, start_, start_ + size_); update_range(r_->root_.load(), &r_->root_, [](radix_entry cur, radix_ptr *ptr) -> radix_entry { do { // It had better still be locked. assert(cur.state() == entry_locked); } while (!ptr->compare_exchange_weak(cur, cur.with_state(entry_unlocked))); // Not a node, but let's return what it wants anyway. return cur.with_state(entry_unlocked); }, 0, 1L << key_bits, start_, start_ + size_); } void radix_range::replace(u64 start, u64 size, radix_elem *val) { start = start >> r_->shift_; size = size >> r_->shift_; assert(start >= start_); assert(start + size <= start_ + size_); dprintf("%p: replace: [%lx, %lx) with %p\n", r_, start, start + size, val); update_range(r_->root_.load(), &r_->root_, [val](radix_entry cur, radix_ptr *ptr) -> radix_entry { do { assert(cur.state() == entry_locked); } while (!ptr->compare_exchange_weak(cur, radix_entry(val, entry_locked))); if (val) val->incref(); // cur is now the old value. if (!cur.is_null()) cur.elem()->decref(); // Not a node, but let's return what it wants anyway. return radix_entry(val, entry_locked); }, 0, 1L << key_bits, start, start + size); } radix_iterator::radix_iterator(const radix* r, u64 k) : r_(r), k_(k) { dprintf("%p: Made iterator with k = %lx\n", r_, k_); if (k_ != ~0ULL) { path_[radix_levels] = r_->root_.load(); if (path_[radix_levels].is_elem()) leaf_ = radix_levels; // Maybe best to not do this... else if (!find_first_leaf(radix_levels - 1)) k_ = ~0ULL; } dprintf("%p: Adjusted: k = %lx\n", r_, k_); } bool radix_iterator::advance(u32 level) { // First, see if we can advance a lower level. if (level > leaf_ && advance(level-1)) { // Nothing more to do. return true; } // Try to advance this level, if we can. u32 start_idx = index(k_, level)+1; if (start_idx < (1<<bits_per_level)) { // Find the first leaf starting at our sibling node. k_ &= ~((1ULL<<((level+1) * bits_per_level)) - 1); k_ |= (u64(start_idx) << (level * bits_per_level)); return find_first_leaf(level); } else { return false; } } bool radix_iterator::find_first_leaf(u32 level) { // Find the first non-empty node after k_ on this level. for (u32 idx = index(k_, level); idx < (1<<bits_per_level); idx++) { radix_entry next = node(level+1)->child[idx].load(); if (!next.is_null()) { if (index(k_, level) != idx) { // We had to advance; clear everything this level and under // and set this one. k_ &= ~((1ULL<<((level+1) * bits_per_level)) - 1); k_ |= (u64(idx) << (level * bits_per_level)); } path_[level] = next; if (next.is_elem()) { // Found a leaf. Stop now. leaf_ = level; return true; } else if (find_first_leaf(level-1)) // Keep looking. return true; } } // Failed to find a leaf. Abort. return false; } <|endoftext|>
<commit_before>#include "logging.h" #include <iostream> #include <QString> void ERROR(QString mesg){ QString string; string ="ERROR: "+mesg; std::cerr << string.toStdString() << std::endl; } void WARNING(QString mesg){ QString string; string="WARNING: "+mesg; std::cerr << string.toStdString() << std::endl; } <commit_msg>Update logging.cpp<commit_after>#include "logging.h" #include <iostream> #include <QString> void ERROR(QString mesg) { QString string; string ="ERROR: "+mesg; std::cerr << string.toStdString() << std::endl; } void WARNING(QString mesg) { QString string; string="WARNING: "+mesg; std::cerr << string.toStdString() << std::endl; } void ERROR(std::string mesg) { std::string string ="ERROR: "+mesg; std::cerr << string << std::endl; } void WARNING(std::string mesg) { std::string string="WARNING: "+mesg; std::cerr << string << std::endl; } <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.6.90cvs >= 20030620" static const char description[] = I18N_NOOP("Kopete, the KDE Instant Messenger"); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "noconnect" , I18N_NOOP("Disable auto-connection") , 0 }, // { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2003, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org"); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Gadu plugin developer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Yahoo Plugin Maintainer"), "mattrogers@sbcglobal.net" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); //aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former Developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former Developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former Developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <commit_msg>version bump<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.6.90cvs >= 20030713" static const char description[] = I18N_NOOP("Kopete, the KDE Instant Messenger"); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "noconnect" , I18N_NOOP("Disable auto-connection") , 0 }, // { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2003, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org"); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Gadu plugin developer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Yahoo Plugin Maintainer"), "mattrogers@sbcglobal.net" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); //aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former Developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former Developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former Developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <klocale.h> #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN, Chatwindow"), "michael.larouche@kdemail.net", "http://mlarouche.blogspot.com" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Now that xgettext 0.15-pre is used, the placeholders for the translators must be declared correctly. (goutte)<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <klocale.h> #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN, Chatwindow"), "michael.larouche@kdemail.net", "http://mlarouche.blogspot.com" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP2("NAME OF TRANSLATORS","Your names"), I18N_NOOP2("EMAIL OF TRANSLATORS","Your emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>// Copyright 2021 The TCMalloc Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tcmalloc/lifetime_based_allocator.h" #include <stddef.h> #include <stdlib.h> #include <string> #include <thread> // NOLINT(build/c++11) #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/synchronization/barrier.h" #include "absl/time/time.h" #include "tcmalloc/common.h" #include "tcmalloc/huge_page_aware_allocator.h" #include "tcmalloc/huge_pages.h" #include "tcmalloc/testing/testutil.h" namespace tcmalloc { namespace tcmalloc_internal { namespace { using ::testing::StrEq; class LifetimeBasedAllocatorTest : public ::testing::Test { public: // Represents an allocation returned by the lifetime-aware allocator, // including any trackers (if applicable). struct Allocation { LifetimeTracker::Tracker tracker; PageId page; }; // Represents memory (and refcount) allocated by the lifetime-aware allocator. struct BackingMemory { void* ptr; int refcount; }; static constexpr absl::Duration kLifetimeThreshold = absl::Milliseconds(100); static const int kAllocationSize = kPagesPerHugePage.raw_num() - 2; LifetimeBasedAllocatorTest() : LifetimeBasedAllocatorTest(LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, absl::Milliseconds(500))) {} explicit LifetimeBasedAllocatorTest(LifetimePredictionOptions opts) : lifetime_allocator_(opts, &region_alloc_, kFakeClock) {} protected: const Clock kFakeClock = Clock{.now = FakeClock, .freq = GetFakeClockFrequency}; void Advance(absl::Duration d) { clock_ += absl::ToDoubleSeconds(d) * GetFakeClockFrequency(); } class FakeRegionAlloc : public LifetimeBasedAllocator::RegionAlloc { public: explicit FakeRegionAlloc() { region_metadata_ = BackingMemory{.ptr = calloc(1, sizeof(HugeRegion)), .refcount = 0}; region_backing_memory_ = BackingMemory{ .ptr = aligned_alloc(kHugePageSize, HugeRegion::size().in_bytes()), .refcount = 0}; } ~FakeRegionAlloc() override { free(region_metadata_.ptr); free(region_backing_memory_.ptr); } HugeRegion* AllocRegion(HugeLength n, HugeRange* range) override { if (!range->valid()) { CHECK_CONDITION(n.in_bytes() == HugeRegion::size().in_bytes()); CHECK_CONDITION(region_backing_memory_.refcount == 0); ++region_backing_memory_.refcount; *range = HugeRange::Make(HugePageContaining(region_backing_memory_.ptr), n); } CHECK_CONDITION(region_metadata_.refcount == 0); ++region_metadata_.refcount; new (region_metadata_.ptr) HugeRegion(*range, MemoryModifyFunction(NopUnbackFn)); return static_cast<HugeRegion*>(region_metadata_.ptr); } private: BackingMemory region_backing_memory_; BackingMemory region_metadata_; }; static bool NopUnbackFn(void* p, size_t len) { // TODO(b/122551676): Return non-trivial success results. return true; } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL void Allocate( Allocation* out) { Length n = Length(kAllocationSize); LifetimeStats* context = lifetime_allocator_.CollectLifetimeContext(n); absl::base_internal::SpinLockHolder h(&pageheap_lock); bool from_released; auto res = lifetime_allocator_.MaybeGet(n, &from_released, context); if (!res.TryGetAllocation(&out->page)) { // If not allocated in the short-lived region, do not actually back the // memory and return the nullptr span. res.InitTracker(&out->tracker); lifetime_allocator_.MaybeAddTracker(res, &out->tracker); out->page = PageIdContaining(nullptr); } } void Delete(Allocation* alloc) { absl::base_internal::SpinLockHolder h(&pageheap_lock); lifetime_allocator_.MaybePut(alloc->page, Length(kAllocationSize)); lifetime_allocator_.MaybePutTracker(&alloc->tracker, Length(kAllocationSize)); } void GenerateInterestingAllocs() { Allocation long_lived_allocs[10]; for (int i = 0; i < 10; ++i) { Allocation short_lived_allocs[10]; Allocate(&long_lived_allocs[i]); // will be classified as long-lived PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&short_lived_allocs[j]); // will be classified as short-lived } Advance(absl::Microseconds(10)); for (int j = 0; j < 10; ++j) { Delete(&short_lived_allocs[j]); } } Advance(absl::Seconds(10)); for (int i = 0; i < 10; ++i) { Delete(&long_lived_allocs[i]); } } FakeRegionAlloc region_alloc_; LifetimeBasedAllocator lifetime_allocator_; private: static int64_t FakeClock() { return clock_; } static double GetFakeClockFrequency() { return absl::ToDoubleNanoseconds(absl::Seconds(2)); } static int64_t clock_; }; int64_t LifetimeBasedAllocatorTest::clock_{0}; class ParameterizedLifetimeBasedAllocatorTest : public LifetimeBasedAllocatorTest, public ::testing::WithParamInterface<LifetimePredictionOptions> { public: ParameterizedLifetimeBasedAllocatorTest() : LifetimeBasedAllocatorTest(GetParam()) {} ~ParameterizedLifetimeBasedAllocatorTest() override {} }; // Test lifetime predictions. TEST_P(ParameterizedLifetimeBasedAllocatorTest, Basic) { Allocation long_lived_allocs[10]; for (int i = 0; i < 10; ++i) { Allocation short_lived_allocs[10]; Allocation medium_lived_allocs[10]; // This pragma is needed since otherwise the compiler may unroll the loop // and create more than one allocation site. PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&medium_lived_allocs[j]); // will be classified as short-lived } Allocate(&long_lived_allocs[i]); // will be classified as long-lived Advance(absl::Milliseconds(100)); PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&short_lived_allocs[j]); // will be classified as short-lived } Advance(absl::Microseconds(10)); for (int j = 0; j < 10; ++j) { Delete(&short_lived_allocs[j]); Delete(&medium_lived_allocs[j]); } } Advance(absl::Seconds(1)); LifetimeBasedAllocator::Stats stats = lifetime_allocator_.GetStats(); EXPECT_EQ(3, stats.database_size); EXPECT_EQ(0, stats.database_evictions); if (GetParam().always_predict_short_lived()) { EXPECT_EQ(210, stats.tracker.short_lived_predictions); EXPECT_EQ(0, stats.tracker.long_lived_predictions); EXPECT_EQ(110, stats.tracker.expired_lifetimes); EXPECT_EQ(0, stats.tracker.overestimated_lifetimes); EXPECT_EQ(210, stats.region.allocations); EXPECT_EQ(53340, stats.region.allocated_pages); EXPECT_EQ(200, stats.region.deallocations); EXPECT_EQ(50800, stats.region.deallocated_pages); } else { EXPECT_EQ(80, stats.tracker.short_lived_predictions); EXPECT_EQ(130, stats.tracker.long_lived_predictions); EXPECT_EQ(0, stats.tracker.expired_lifetimes); EXPECT_EQ(20, stats.tracker.overestimated_lifetimes); EXPECT_EQ(80, stats.region.allocations); EXPECT_EQ(20320, stats.region.allocated_pages); EXPECT_EQ(80, stats.region.deallocations); EXPECT_EQ(20320, stats.region.deallocated_pages); } EXPECT_NE(LifetimePredictionOptions::Mode::kDisabled, stats.opts.mode()); EXPECT_EQ(absl::Milliseconds(100), stats.opts.threshold()); EXPECT_EQ(GetParam().counterfactual(), stats.opts.counterfactual()); } // During allocation, the lifetime-based allocator drops the page heap lock, // which can lead to complex race conditions. This is a stress-test to uncover // this behavior. TEST_P(ParameterizedLifetimeBasedAllocatorTest, MultithreadingStressTest) { const int kThreads = 100; const int kIterations = 4; const int kAllocations = 10; for (int i = 0; i < kIterations; ++i) { std::vector<std::thread> threads; std::vector<Allocation> allocs; allocs.resize(kThreads); absl::Barrier* b1 = new absl::Barrier(kThreads); absl::Barrier* b2 = new absl::Barrier(kThreads); for (int j = 0; j < kThreads; ++j) { threads.push_back(std::thread([this, j, &b1, &b2, &allocs]() { PRAGMA_NO_UNROLL for (int k = 0; k < kAllocations; ++k) { absl::SleepFor(absl::Microseconds(1)); Allocate(&allocs[j]); // Synchronize the first iteration to ensure that all subsequent // iterations get predicted short-lived. if (k == 0 && b1->Block()) { delete b1; } absl::SleepFor(absl::Microseconds(1)); Delete(&allocs[j]); if (k == 0 && b2->Block()) { delete b2; } } })); } for (auto& t : threads) { t.join(); } } // Check that the lifetime prediction works as expected. LifetimeBasedAllocator::Stats stats = lifetime_allocator_.GetStats(); if (GetParam().always_predict_short_lived()) { EXPECT_EQ(4000, stats.tracker.short_lived_predictions); EXPECT_EQ(0, stats.tracker.long_lived_predictions); } else { EXPECT_EQ(3900, stats.tracker.short_lived_predictions); EXPECT_EQ(100, stats.tracker.long_lived_predictions); } EXPECT_EQ(1, stats.database_size); } TEST_F(LifetimeBasedAllocatorTest, Print) { GenerateInterestingAllocs(); std::string buffer(1024 * 1024, '\0'); { absl::base_internal::SpinLockHolder h(&pageheap_lock); Printer printer(&*buffer.begin(), buffer.size()); lifetime_allocator_.Print(&printer); buffer.erase(printer.SpaceRequired()); } EXPECT_THAT(buffer, StrEq(R"(HugePageAware: *** Lifetime-based regions: *** HugePageAware: Predictions: 80 short / 30 long lived (0 expired, 20 overestimated) HugePageAware: Lifetime-based allocations (enabled / short-lived regions): Threshold = 0.50s, 2 stack traces (0 evicted) LifetimeBasedRegion: 80 allocated (20320 pages), 80 freed (20320 pages) in lifetime region. )")); } TEST_F(LifetimeBasedAllocatorTest, PrintInPbTxt) { GenerateInterestingAllocs(); std::string buffer(1024 * 1024, '\0'); Printer printer(&*buffer.begin(), buffer.size()); { absl::base_internal::SpinLockHolder h(&pageheap_lock); PbtxtRegion region(&printer, kTop); lifetime_allocator_.PrintInPbtxt(&region); } buffer.erase(printer.SpaceRequired()); auto canonicalize = [](std::string* s) { *s = absl::StrReplaceAll(*s, {{"\n", " "}}); absl::RemoveExtraAsciiWhitespace(s); }; canonicalize(&buffer); std::string expected(R"( lifetime_based_allocator_stats { enabled: true counterfactual: false threshold_ms: 500 num_predicted_short_lived: 80 num_predicted_long_lived: 30 num_expired: 0 num_overestimated: 20 database_size: 2 database_evicted_count: 0 lifetime_region_allocated: 80 lifetime_region_allocated_pages: 20320 lifetime_region_freed: 80 lifetime_region_freed_pages: 20320})"); canonicalize(&expected); EXPECT_THAT(buffer, StrEq(expected)); } INSTANTIATE_TEST_SUITE_P( LifetimeTests, ParameterizedLifetimeBasedAllocatorTest, testing::Values( LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kCounterfactual, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kAlwaysShortLivedRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kCounterfactual, LifetimePredictionOptions::Strategy::kAlwaysShortLivedRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold)), [](const testing::TestParamInfo<LifetimePredictionOptions>& info) { return absl::StrFormat( "%s_%s", ((info.index >= 2) ? "always_regions" : "lifetime_regions"), ((info.index % 2 == 0) ? "enabled" : "counterfactual")); }); } // namespace } // namespace tcmalloc_internal } // namespace tcmalloc <commit_msg>Update bug number reference.<commit_after>// Copyright 2021 The TCMalloc Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tcmalloc/lifetime_based_allocator.h" #include <stddef.h> #include <stdlib.h> #include <string> #include <thread> // NOLINT(build/c++11) #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/synchronization/barrier.h" #include "absl/time/time.h" #include "tcmalloc/common.h" #include "tcmalloc/huge_page_aware_allocator.h" #include "tcmalloc/huge_pages.h" #include "tcmalloc/testing/testutil.h" namespace tcmalloc { namespace tcmalloc_internal { namespace { using ::testing::StrEq; class LifetimeBasedAllocatorTest : public ::testing::Test { public: // Represents an allocation returned by the lifetime-aware allocator, // including any trackers (if applicable). struct Allocation { LifetimeTracker::Tracker tracker; PageId page; }; // Represents memory (and refcount) allocated by the lifetime-aware allocator. struct BackingMemory { void* ptr; int refcount; }; static constexpr absl::Duration kLifetimeThreshold = absl::Milliseconds(100); static const int kAllocationSize = kPagesPerHugePage.raw_num() - 2; LifetimeBasedAllocatorTest() : LifetimeBasedAllocatorTest(LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, absl::Milliseconds(500))) {} explicit LifetimeBasedAllocatorTest(LifetimePredictionOptions opts) : lifetime_allocator_(opts, &region_alloc_, kFakeClock) {} protected: const Clock kFakeClock = Clock{.now = FakeClock, .freq = GetFakeClockFrequency}; void Advance(absl::Duration d) { clock_ += absl::ToDoubleSeconds(d) * GetFakeClockFrequency(); } class FakeRegionAlloc : public LifetimeBasedAllocator::RegionAlloc { public: explicit FakeRegionAlloc() { region_metadata_ = BackingMemory{.ptr = calloc(1, sizeof(HugeRegion)), .refcount = 0}; region_backing_memory_ = BackingMemory{ .ptr = aligned_alloc(kHugePageSize, HugeRegion::size().in_bytes()), .refcount = 0}; } ~FakeRegionAlloc() override { free(region_metadata_.ptr); free(region_backing_memory_.ptr); } HugeRegion* AllocRegion(HugeLength n, HugeRange* range) override { if (!range->valid()) { CHECK_CONDITION(n.in_bytes() == HugeRegion::size().in_bytes()); CHECK_CONDITION(region_backing_memory_.refcount == 0); ++region_backing_memory_.refcount; *range = HugeRange::Make(HugePageContaining(region_backing_memory_.ptr), n); } CHECK_CONDITION(region_metadata_.refcount == 0); ++region_metadata_.refcount; new (region_metadata_.ptr) HugeRegion(*range, MemoryModifyFunction(NopUnbackFn)); return static_cast<HugeRegion*>(region_metadata_.ptr); } private: BackingMemory region_backing_memory_; BackingMemory region_metadata_; }; static bool NopUnbackFn(void* p, size_t len) { // TODO(b/258278604): Return non-trivial success results. return true; } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL void Allocate( Allocation* out) { Length n = Length(kAllocationSize); LifetimeStats* context = lifetime_allocator_.CollectLifetimeContext(n); absl::base_internal::SpinLockHolder h(&pageheap_lock); bool from_released; auto res = lifetime_allocator_.MaybeGet(n, &from_released, context); if (!res.TryGetAllocation(&out->page)) { // If not allocated in the short-lived region, do not actually back the // memory and return the nullptr span. res.InitTracker(&out->tracker); lifetime_allocator_.MaybeAddTracker(res, &out->tracker); out->page = PageIdContaining(nullptr); } } void Delete(Allocation* alloc) { absl::base_internal::SpinLockHolder h(&pageheap_lock); lifetime_allocator_.MaybePut(alloc->page, Length(kAllocationSize)); lifetime_allocator_.MaybePutTracker(&alloc->tracker, Length(kAllocationSize)); } void GenerateInterestingAllocs() { Allocation long_lived_allocs[10]; for (int i = 0; i < 10; ++i) { Allocation short_lived_allocs[10]; Allocate(&long_lived_allocs[i]); // will be classified as long-lived PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&short_lived_allocs[j]); // will be classified as short-lived } Advance(absl::Microseconds(10)); for (int j = 0; j < 10; ++j) { Delete(&short_lived_allocs[j]); } } Advance(absl::Seconds(10)); for (int i = 0; i < 10; ++i) { Delete(&long_lived_allocs[i]); } } FakeRegionAlloc region_alloc_; LifetimeBasedAllocator lifetime_allocator_; private: static int64_t FakeClock() { return clock_; } static double GetFakeClockFrequency() { return absl::ToDoubleNanoseconds(absl::Seconds(2)); } static int64_t clock_; }; int64_t LifetimeBasedAllocatorTest::clock_{0}; class ParameterizedLifetimeBasedAllocatorTest : public LifetimeBasedAllocatorTest, public ::testing::WithParamInterface<LifetimePredictionOptions> { public: ParameterizedLifetimeBasedAllocatorTest() : LifetimeBasedAllocatorTest(GetParam()) {} ~ParameterizedLifetimeBasedAllocatorTest() override {} }; // Test lifetime predictions. TEST_P(ParameterizedLifetimeBasedAllocatorTest, Basic) { Allocation long_lived_allocs[10]; for (int i = 0; i < 10; ++i) { Allocation short_lived_allocs[10]; Allocation medium_lived_allocs[10]; // This pragma is needed since otherwise the compiler may unroll the loop // and create more than one allocation site. PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&medium_lived_allocs[j]); // will be classified as short-lived } Allocate(&long_lived_allocs[i]); // will be classified as long-lived Advance(absl::Milliseconds(100)); PRAGMA_NO_UNROLL for (int j = 0; j < 10; ++j) { Allocate(&short_lived_allocs[j]); // will be classified as short-lived } Advance(absl::Microseconds(10)); for (int j = 0; j < 10; ++j) { Delete(&short_lived_allocs[j]); Delete(&medium_lived_allocs[j]); } } Advance(absl::Seconds(1)); LifetimeBasedAllocator::Stats stats = lifetime_allocator_.GetStats(); EXPECT_EQ(3, stats.database_size); EXPECT_EQ(0, stats.database_evictions); if (GetParam().always_predict_short_lived()) { EXPECT_EQ(210, stats.tracker.short_lived_predictions); EXPECT_EQ(0, stats.tracker.long_lived_predictions); EXPECT_EQ(110, stats.tracker.expired_lifetimes); EXPECT_EQ(0, stats.tracker.overestimated_lifetimes); EXPECT_EQ(210, stats.region.allocations); EXPECT_EQ(53340, stats.region.allocated_pages); EXPECT_EQ(200, stats.region.deallocations); EXPECT_EQ(50800, stats.region.deallocated_pages); } else { EXPECT_EQ(80, stats.tracker.short_lived_predictions); EXPECT_EQ(130, stats.tracker.long_lived_predictions); EXPECT_EQ(0, stats.tracker.expired_lifetimes); EXPECT_EQ(20, stats.tracker.overestimated_lifetimes); EXPECT_EQ(80, stats.region.allocations); EXPECT_EQ(20320, stats.region.allocated_pages); EXPECT_EQ(80, stats.region.deallocations); EXPECT_EQ(20320, stats.region.deallocated_pages); } EXPECT_NE(LifetimePredictionOptions::Mode::kDisabled, stats.opts.mode()); EXPECT_EQ(absl::Milliseconds(100), stats.opts.threshold()); EXPECT_EQ(GetParam().counterfactual(), stats.opts.counterfactual()); } // During allocation, the lifetime-based allocator drops the page heap lock, // which can lead to complex race conditions. This is a stress-test to uncover // this behavior. TEST_P(ParameterizedLifetimeBasedAllocatorTest, MultithreadingStressTest) { const int kThreads = 100; const int kIterations = 4; const int kAllocations = 10; for (int i = 0; i < kIterations; ++i) { std::vector<std::thread> threads; std::vector<Allocation> allocs; allocs.resize(kThreads); absl::Barrier* b1 = new absl::Barrier(kThreads); absl::Barrier* b2 = new absl::Barrier(kThreads); for (int j = 0; j < kThreads; ++j) { threads.push_back(std::thread([this, j, &b1, &b2, &allocs]() { PRAGMA_NO_UNROLL for (int k = 0; k < kAllocations; ++k) { absl::SleepFor(absl::Microseconds(1)); Allocate(&allocs[j]); // Synchronize the first iteration to ensure that all subsequent // iterations get predicted short-lived. if (k == 0 && b1->Block()) { delete b1; } absl::SleepFor(absl::Microseconds(1)); Delete(&allocs[j]); if (k == 0 && b2->Block()) { delete b2; } } })); } for (auto& t : threads) { t.join(); } } // Check that the lifetime prediction works as expected. LifetimeBasedAllocator::Stats stats = lifetime_allocator_.GetStats(); if (GetParam().always_predict_short_lived()) { EXPECT_EQ(4000, stats.tracker.short_lived_predictions); EXPECT_EQ(0, stats.tracker.long_lived_predictions); } else { EXPECT_EQ(3900, stats.tracker.short_lived_predictions); EXPECT_EQ(100, stats.tracker.long_lived_predictions); } EXPECT_EQ(1, stats.database_size); } TEST_F(LifetimeBasedAllocatorTest, Print) { GenerateInterestingAllocs(); std::string buffer(1024 * 1024, '\0'); { absl::base_internal::SpinLockHolder h(&pageheap_lock); Printer printer(&*buffer.begin(), buffer.size()); lifetime_allocator_.Print(&printer); buffer.erase(printer.SpaceRequired()); } EXPECT_THAT(buffer, StrEq(R"(HugePageAware: *** Lifetime-based regions: *** HugePageAware: Predictions: 80 short / 30 long lived (0 expired, 20 overestimated) HugePageAware: Lifetime-based allocations (enabled / short-lived regions): Threshold = 0.50s, 2 stack traces (0 evicted) LifetimeBasedRegion: 80 allocated (20320 pages), 80 freed (20320 pages) in lifetime region. )")); } TEST_F(LifetimeBasedAllocatorTest, PrintInPbTxt) { GenerateInterestingAllocs(); std::string buffer(1024 * 1024, '\0'); Printer printer(&*buffer.begin(), buffer.size()); { absl::base_internal::SpinLockHolder h(&pageheap_lock); PbtxtRegion region(&printer, kTop); lifetime_allocator_.PrintInPbtxt(&region); } buffer.erase(printer.SpaceRequired()); auto canonicalize = [](std::string* s) { *s = absl::StrReplaceAll(*s, {{"\n", " "}}); absl::RemoveExtraAsciiWhitespace(s); }; canonicalize(&buffer); std::string expected(R"( lifetime_based_allocator_stats { enabled: true counterfactual: false threshold_ms: 500 num_predicted_short_lived: 80 num_predicted_long_lived: 30 num_expired: 0 num_overestimated: 20 database_size: 2 database_evicted_count: 0 lifetime_region_allocated: 80 lifetime_region_allocated_pages: 20320 lifetime_region_freed: 80 lifetime_region_freed_pages: 20320})"); canonicalize(&expected); EXPECT_THAT(buffer, StrEq(expected)); } INSTANTIATE_TEST_SUITE_P( LifetimeTests, ParameterizedLifetimeBasedAllocatorTest, testing::Values( LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kCounterfactual, LifetimePredictionOptions::Strategy::kPredictedLifetimeRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kEnabled, LifetimePredictionOptions::Strategy::kAlwaysShortLivedRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold), LifetimePredictionOptions( LifetimePredictionOptions::Mode::kCounterfactual, LifetimePredictionOptions::Strategy::kAlwaysShortLivedRegions, LifetimeBasedAllocatorTest::kLifetimeThreshold)), [](const testing::TestParamInfo<LifetimePredictionOptions>& info) { return absl::StrFormat( "%s_%s", ((info.index >= 2) ? "always_regions" : "lifetime_regions"), ((info.index % 2 == 0) ? "enabled" : "counterfactual")); }); } // namespace } // namespace tcmalloc_internal } // namespace tcmalloc <|endoftext|>
<commit_before> #include <vector> #include "geometry/permutation.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" using principia::si::Metre; using principia::testing_utilities::AlmostEquals; using testing::Eq; namespace principia { namespace geometry { class PermutationTest : public testing::Test { protected: struct World; typedef OrthogonalMap<World, World> Orth; typedef Permutation<World, World> Perm; typedef R3Element<quantities::Length> R3; void SetUp() override { vector_ = Vector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); bivector_ = Bivector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); trivector_ = Trivector<quantities::Length, World>(4.0 * Metre); } Vector<quantities::Length, World> vector_; Bivector<quantities::Length, World> bivector_; Trivector<quantities::Length, World> trivector_; }; TEST_F(PermutationTest, Identity) { EXPECT_THAT(Perm::Identity()(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, XYZ) { EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, YZX) { EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, ZXY) { EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, XZY) { EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, ZYX) { EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, YXZ) { EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, Determinant) { Perm xyz(Perm::XYZ); Perm yzx(Perm::YZX); Perm zxy(Perm::ZXY); Perm xzy(Perm::XZY); Perm zyx(Perm::ZYX); Perm yxz(Perm::YXZ); EXPECT_TRUE(xyz.Determinant().Positive()); EXPECT_TRUE(yzx.Determinant().Positive()); EXPECT_TRUE(zxy.Determinant().Positive()); EXPECT_TRUE(xzy.Determinant().Negative()); EXPECT_TRUE(zyx.Determinant().Negative()); EXPECT_TRUE(yxz.Determinant().Negative()); } TEST_F(PermutationTest, AppliedToVector) { EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, AppliedToBivector) { EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(), Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre})); } TEST_F(PermutationTest, AppliedToTrivector) { EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(), Eq(4.0 * Metre)); EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(), Eq(-4.0 * Metre)); } TEST_F(PermutationTest, Inverse) { EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, Forget) { EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(), AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2)); EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(), AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4)); EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(), AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2)); } TEST_F(PermutationTest, Compose) { std::vector<Perm> all = {Perm(Perm::XYZ),Perm(Perm::YZX),Perm(Perm::ZXY), Perm(Perm::XZY),Perm(Perm::ZYX),Perm(Perm::YXZ)}; for (const Perm& p1 : all) { Orth const o1 = p1.Forget(); for (const Perm& p2 : all) { Orth const o2 = p2.Forget(); Perm const p12 = p1 * p2; Orth const o12 = o1 * o2; EXPECT_THAT(p12(vector_), AlmostEquals(o12(vector_), 20)); } } } } // namespace geometry } // namespace principia <commit_msg>Moar tests.<commit_after> #include <vector> #include "geometry/permutation.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/si.hpp" #include "testing_utilities/almost_equals.hpp" using principia::si::Metre; using principia::testing_utilities::AlmostEquals; using testing::Eq; namespace principia { namespace geometry { class PermutationTest : public testing::Test { protected: struct World; typedef OrthogonalMap<World, World> Orth; typedef Permutation<World, World> Perm; typedef R3Element<quantities::Length> R3; void SetUp() override { vector_ = Vector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); bivector_ = Bivector<quantities::Length, World>( R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre)); trivector_ = Trivector<quantities::Length, World>(4.0 * Metre); } Vector<quantities::Length, World> vector_; Bivector<quantities::Length, World> bivector_; Trivector<quantities::Length, World> trivector_; }; TEST_F(PermutationTest, Identity) { EXPECT_THAT(Perm::Identity()(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, XYZ) { EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, YZX) { EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, ZXY) { EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, XZY) { EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()), Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre})); } TEST_F(PermutationTest, ZYX) { EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()), Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre})); } TEST_F(PermutationTest, YXZ) { EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, Determinant) { Perm xyz(Perm::XYZ); Perm yzx(Perm::YZX); Perm zxy(Perm::ZXY); Perm xzy(Perm::XZY); Perm zyx(Perm::ZYX); Perm yxz(Perm::YXZ); EXPECT_TRUE(xyz.Determinant().Positive()); EXPECT_TRUE(yzx.Determinant().Positive()); EXPECT_TRUE(zxy.Determinant().Positive()); EXPECT_TRUE(xzy.Determinant().Negative()); EXPECT_TRUE(zyx.Determinant().Negative()); EXPECT_TRUE(yxz.Determinant().Negative()); } TEST_F(PermutationTest, AppliedToVector) { EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); } TEST_F(PermutationTest, AppliedToBivector) { EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(), Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre})); } TEST_F(PermutationTest, AppliedToTrivector) { EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(), Eq(4.0 * Metre)); EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(), Eq(-4.0 * Metre)); } TEST_F(PermutationTest, Inverse) { EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre})); std::vector<Perm> all = {Perm(Perm::XYZ),Perm(Perm::YZX),Perm(Perm::ZXY), Perm(Perm::XZY),Perm(Perm::ZYX),Perm(Perm::YXZ)}; for (const Perm& p : all) { Perm const identity = p * p.Inverse(); EXPECT_THAT(identity(vector_), Eq(vector_)); } } TEST_F(PermutationTest, Forget) { EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(), Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre})); EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(), Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre})); EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(), Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre})); EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(), AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2)); EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(), AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4)); EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(), AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2)); } TEST_F(PermutationTest, Compose) { std::vector<Perm> all = {Perm(Perm::XYZ),Perm(Perm::YZX),Perm(Perm::ZXY), Perm(Perm::XZY),Perm(Perm::ZYX),Perm(Perm::YXZ)}; for (const Perm& p1 : all) { Orth const o1 = p1.Forget(); for (const Perm& p2 : all) { Orth const o2 = p2.Forget(); Perm const p12 = p1 * p2; Orth const o12 = o1 * o2; EXPECT_THAT(p12(vector_), AlmostEquals(o12(vector_), 20)); } } } } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>#include "LibraryPanel.h" #include "LibraryPage.h" #include <wx/notebook.h> #include <easyanim.h> #include <easymesh.h> #include <easyscale9.h> #include <easyparticle3d.h> #include <easyparticle2d.h> #include <easyejoy2d.h> #include <easyterrain2d.h> #include <easytexture.h> #include <easyicon.h> #include <easyshadow.h> #include <easysketch.h> #include <easytext.h> namespace ecomplex { LibraryPanel::LibraryPanel(wxWindow* parent) : d2d::LibraryPanel(parent) { wxWindow* nb = GetNotebook(); AddPage(new d2d::LibraryImagePage(nb)); AddPage(new LibraryPage(nb)); AddPage(new libanim::LibraryPage(nb)); AddPage(new escale9::LibraryPage(nb)); AddPage(new etext::LibraryPage(nb)); AddPage(new d2d::LibraryFontBlankPage(nb)); AddPage(new emesh::LibraryPage(nb)); AddPage(new d2d::LibraryScriptsPage(nb)); AddPage(new d2d::LibraryFontPage(nb)); AddPage(new eparticle3d::LibraryPage(nb)); AddPage(new eparticle2d::LibraryPage(nb)); AddPage(new eejoy2d::LibraryPage(nb)); AddPage(new eterrain2d::LibraryPage(nb)); AddPage(new etexture::LibraryPage(nb)); AddPage(new eicon::LibraryPage(nb)); AddPage(new eshadow::LibraryPage(nb)); AddPage(new libsketch::LibraryPage(nb)); } } // ecomplex<commit_msg>[REMOVED] ecomplex library里不用的<commit_after>#include "LibraryPanel.h" #include "LibraryPage.h" #include <wx/notebook.h> #include <easyanim.h> #include <easymesh.h> #include <easyscale9.h> #include <easyparticle3d.h> #include <easyparticle2d.h> #include <easyejoy2d.h> #include <easyterrain2d.h> #include <easytexture.h> #include <easyicon.h> #include <easyshadow.h> #include <easysketch.h> #include <easytext.h> namespace ecomplex { LibraryPanel::LibraryPanel(wxWindow* parent) : d2d::LibraryPanel(parent) { wxWindow* nb = GetNotebook(); AddPage(new d2d::LibraryImagePage(nb)); AddPage(new LibraryPage(nb)); AddPage(new libanim::LibraryPage(nb)); AddPage(new escale9::LibraryPage(nb)); AddPage(new etext::LibraryPage(nb)); // AddPage(new d2d::LibraryFontBlankPage(nb)); AddPage(new emesh::LibraryPage(nb)); AddPage(new d2d::LibraryScriptsPage(nb)); // AddPage(new d2d::LibraryFontPage(nb)); AddPage(new eparticle3d::LibraryPage(nb)); AddPage(new eparticle2d::LibraryPage(nb)); AddPage(new eejoy2d::LibraryPage(nb)); AddPage(new eterrain2d::LibraryPage(nb)); AddPage(new etexture::LibraryPage(nb)); AddPage(new eicon::LibraryPage(nb)); AddPage(new eshadow::LibraryPage(nb)); AddPage(new libsketch::LibraryPage(nb)); } } // ecomplex<|endoftext|>
<commit_before><commit_msg>Fix how we calculate workarea size (_NET_WORKAREA gives width/height).<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/process_watcher.h" #include <errno.h> #include <signal.h> #include <sys/event.h> #include <sys/types.h> #include <sys/wait.h> #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "base/time.h" namespace { // Reap |child| process. // This call blocks until completion. void BlockingReap(pid_t child) { const pid_t result = HANDLE_EINTR(waitpid(child, NULL, 0)); if (result == -1) { PLOG(ERROR) << "waitpid(" << child << ")"; NOTREACHED(); } } // Waits for |timeout| seconds for the given |child| to exit and reap it. // If the child doesn't exit within a couple of seconds, kill it. void WaitForChildToDie(pid_t child, unsigned timeout) { int kq = HANDLE_EINTR(kqueue()); file_util::ScopedFD auto_close(&kq); if (kq == -1) { PLOG(ERROR) << "Failed to create kqueue"; return; } struct kevent event_to_add = {0}; EV_SET(&event_to_add, child, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); // Register interest with kqueue. int result = HANDLE_EINTR(kevent(kq, &event_to_add, 1, NULL, 0, NULL)); if (result == -1 && errno == ESRCH) { // A "No Such Process" error is fine, the process may have died already // and been reaped by someone else. But make sure that it was/is reaped. // Don't report an error in case it was already reaped. HANDLE_EINTR(waitpid(child, NULL, WNOHANG)); return; } if (result == -1) { PLOG(ERROR) << "Failed to register event to listen for death of pid " << child; return; } struct kevent event = {0}; DCHECK(timeout != 0); int num_processes_that_died = -1; using base::Time; using base::TimeDelta; // We need to keep track of the elapsed time - if kevent() returns // EINTR in the middle of blocking call we want to make up what's left // of the timeout. TimeDelta time_left = TimeDelta::FromSeconds(timeout); Time wakeup = Time::Now() + time_left; while(time_left.InMilliseconds() > 0) { const struct timespec timeout = time_left.ToTimeSpec(); num_processes_that_died = kevent(kq, NULL, 0, &event, 1, &timeout); if (num_processes_that_died >= 0) break; if (num_processes_that_died == -1 && errno == EINTR) { time_left = wakeup - Time::Now(); continue; } // If we got here, kevent() must have returned -1. PLOG(ERROR) << "kevent() failed"; break; } if (num_processes_that_died == -1) { PLOG(ERROR) << "kevent failed"; return; } if (num_processes_that_died == 1) { if (event.fflags & NOTE_EXIT && event.ident == static_cast<uintptr_t>(child)) { // Process died, it's safe to make a blocking call here since the // kqueue() notification occurs when the process is already zombified. BlockingReap(child); return; } else { PLOG(ERROR) << "kevent() returned unexpected result - ke.fflags =" << event.fflags << " ke.ident =" << event.ident << " while listening for pid=" << child; } } // If we got here the child is still alive so kill it... if (kill(child, SIGKILL) == 0) { // SIGKILL is uncatchable. Since the signal was delivered, we can // just wait for the process to die now in a blocking manner. BlockingReap(child); } else { PLOG(ERROR) << "While waiting for " << child << " to terminate we" << " failed to deliver a SIGKILL signal"; } } } // namespace void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process) { WaitForChildToDie(process, 2); } <commit_msg>Kernel zombie death race!<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/process_watcher.h" #include <errno.h> #include <signal.h> #include <sys/event.h> #include <sys/types.h> #include <sys/wait.h> #include "base/eintr_wrapper.h" #include "base/file_util.h" #include "base/time.h" namespace { const int kWaitBeforeKillSeconds = 2; // Reap |child| process. This call blocks until completion. void BlockingReap(pid_t child) { const pid_t result = HANDLE_EINTR(waitpid(child, NULL, 0)); if (result == -1) { PLOG(ERROR) << "waitpid(" << child << ", NULL, 0)"; } } // Waits for |timeout| seconds for the given |child| to exit and reap it. If // the child doesn't exit within the time specified, kills it. // // This function takes two approaches: first, it tries to use kqueue to // observe when the process exits. kevent can monitor a kqueue with a // timeout, so this method is preferred to wait for a specified period of // time. Once the kqueue indicates the process has exited, waitpid will reap // the exited child. If the kqueue doesn't provide an exit event notification, // before the timeout expires, or if the kqueue fails or misbehaves, the // process will be mercilessly killed and reaped. // // A child process passed to this function may be in one of several states: // running, terminated and not yet reaped, and (apparently, and unfortunately) // terminated and already reaped. Normally, a process will at least have been // asked to exit before this function is called, but this is not required. // If a process is terminating and unreaped, there may be a window between the // time that kqueue will no longer recognize it and when it becomes an actual // zombie that a non-blocking (WNOHANG) waitpid can reap. This condition is // detected when kqueue indicates that the process is not running and a // non-blocking waitpid fails to reap the process but indicates that it is // still running. In this event, a blocking attempt to reap the process // collects the known-dying child, preventing zombies from congregating. // // In the event that the kqueue misbehaves entirely, as it might under a // EMFILE condition ("too many open files", or out of file descriptors), this // function will forcibly kill and reap the child without delay. This // eliminates another potential zombie vector. (If you're out of file // descriptors, you're probably deep into something else, but that doesn't // mean that zombies be allowed to kick you while you're down.) // // The fact that this function seemingly can be called to wait on a child // that's not only already terminated but already reaped is a bit of a // problem: a reaped child's pid can be reclaimed and may refer to a distinct // process in that case. The fact that this function can seemingly be called // to wait on a process that's not even a child is also a problem: kqueue will // work in that case, but waitpid won't, and killing a non-child might not be // the best approach. void WaitForChildToDie(pid_t child, int timeout) { DCHECK(child > 0); DCHECK(timeout > 0); // DON'T ADD ANY EARLY RETURNS TO THIS FUNCTION without ensuring that // |child| has been reaped. Specifically, even if a kqueue, kevent, or other // call fails, this function should fall back to the last resort of trying // to kill and reap the process. Not observing this rule will resurrect // zombies. int result; int kq = HANDLE_EINTR(kqueue()); if (kq == -1) { PLOG(ERROR) << "kqueue()"; } else { file_util::ScopedFD auto_close_kq(&kq); struct kevent change = {0}; EV_SET(&change, child, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); result = HANDLE_EINTR(kevent(kq, &change, 1, NULL, 0, NULL)); if (result == -1) { if (errno != ESRCH) { PLOG(ERROR) << "kevent (setup " << child << ")"; } else { // At this point, one of the following has occurred: // 1. The process has died but has not yet been reaped. // 2. The process has died and has already been reaped. // 3. The process is in the process of dying. It's no longer // kqueueable, but it may not be waitable yet either. Mark calls // this case the "zombie death race". result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG)); if (result != 0) { // A positive result indicates case 1. waitpid succeeded and reaped // the child. A result of -1 indicates case 2. The child has already // been reaped. In both of these cases, no further action is // necessary. return; } // |result| is 0, indicating case 3. The process will be waitable in // short order. Fall back out of the kqueue code to kill it (for good // measure) and reap it. } } else { // Keep track of the elapsed time to be able to restart kevent if it's // interrupted. base::TimeDelta remaining_delta = base::TimeDelta::FromSeconds(timeout); base::Time deadline = base::Time::Now() + remaining_delta; result = -1; struct kevent event = {0}; while (remaining_delta.InMilliseconds() > 0) { const struct timespec remaining_timespec = remaining_delta.ToTimeSpec(); result = kevent(kq, NULL, 0, &event, 1, &remaining_timespec); if (result == -1 && errno == EINTR) { remaining_delta = deadline - base::Time::Now(); result = 0; } else { break; } } if (result == -1) { PLOG(ERROR) << "kevent (wait " << child << ")"; } else if (result > 1) { LOG(ERROR) << "kevent (wait " << child << "): unexpected result " << result; } else if (result == 1) { if ((event.fflags & NOTE_EXIT) && (event.ident == static_cast<uintptr_t>(child))) { // The process is dead or dying. This won't block for long, if at // all. BlockingReap(child); return; } else { LOG(ERROR) << "kevent (wait " << child << "): unexpected event: fflags=" << event.fflags << ", ident=" << event.ident; } } } } // The child is still alive, or is very freshly dead. Be sure by sending it // a signal. This is safe even if it's freshly dead, because it will be a // zombie (or on the way to zombiedom) and kill will return 0 even if the // signal is not delivered to a live process. result = kill(child, SIGKILL); if (result == -1) { PLOG(ERROR) << "kill(" << child << ", SIGKILL)"; } else { // The child is definitely on the way out now. BlockingReap won't need to // wait for long, if at all. BlockingReap(child); } } } // namespace void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process) { WaitForChildToDie(process, kWaitBeforeKillSeconds); } <|endoftext|>
<commit_before>/* * Copyright 2011-2018 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "bgfx_p.h" #include "nvapi.h" namespace bgfx { /* * NVAPI * * Reference: * http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/index.html * https://github.com/jNizM/AHK_NVIDIA_NvAPI/blob/master/info/NvAPI_IDs.txt */ struct NvPhysicalGpuHandle; #define NVAPI_MAX_PHYSICAL_GPUS 64 #if BX_PLATFORM_WINDOWS # define NVAPICALL __cdecl #else # define NVAPICALL #endif // BX_PLATFORM_WINDOWS enum NvApiStatus { NVAPI_OK = 0, NVAPI_ERROR = -1, }; struct NvMemoryInfoV2 { NvMemoryInfoV2() : version(sizeof(NvMemoryInfoV2) | (2 << 16) ) { } uint32_t version; uint32_t dedicatedVideoMemory; uint32_t availableDedicatedVideoMemory; uint32_t systemVideoMemory; uint32_t sharedSystemMemory; uint32_t curAvailableDedicatedVideoMemory; }; typedef void* (NVAPICALL* PFN_NVAPI_QUERYINTERFACE)(uint32_t _functionOffset); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_INITIALIZE)(); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_UNLOAD)(); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_ENUMPHYSICALGPUS)(NvPhysicalGpuHandle* _handle[NVAPI_MAX_PHYSICAL_GPUS], uint32_t* _gpuCount); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETMEMORYINFO)(NvPhysicalGpuHandle* _handle, NvMemoryInfoV2* _memoryInfo); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETFULLNAME)(NvPhysicalGpuHandle* _physicalGpu, char _name[64]); #define NVAPI_INITIALIZE UINT32_C(0x0150e828) #define NVAPI_UNLOAD UINT32_C(0xd22bdd7e) #define NVAPI_ENUMPHYSICALGPUS UINT32_C(0xe5ac921f) #define NVAPI_GPUGETMEMORYINFO UINT32_C(0x07f9b368) #define NVAPI_GPUGETFULLNAME UINT32_C(0xceee8e9f) #define NVAPI_MULTIDRAWINSTANCEDINDIRECT UINT32_C(0xd4e26bbf) #define NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT UINT32_C(0x59e890f9) static PFN_NVAPI_QUERYINTERFACE nvApiQueryInterface; static PFN_NVAPI_INITIALIZE nvApiInitialize; static PFN_NVAPI_UNLOAD nvApiUnload; static PFN_NVAPI_ENUMPHYSICALGPUS nvApiEnumPhysicalGPUs; static PFN_NVAPI_GPUGETMEMORYINFO nvApiGpuGetMemoryInfo; static PFN_NVAPI_GPUGETFULLNAME nvApiGpuGetFullName; /* * NVIDIA Aftermath * * Reference: * https://developer.nvidia.com/nvidia-aftermath */ typedef int32_t (*PFN_NVAFTERMATH_DX12_INITIALIZE)(int32_t _version, int32_t _flags, const ID3D12Device* _device); typedef int32_t (*PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)(const ID3D12CommandList* _commandList, NvAftermathContextHandle** _outContextHandle); typedef int32_t (*PFN_NVAFTERMATH_RELEASECONTEXTHANDLE)(const NvAftermathContextHandle* _contextHandle); typedef int32_t (*PFN_NVAFTERMATH_SETEVENTMARKER)(const NvAftermathContextHandle* _contextHandle, const void* _markerData, uint32_t _markerSize); typedef int32_t (*PFN_NVAFTERMATH_GETDATA)(uint32_t _numContexts, const NvAftermathContextHandle** _contextHandles, void* _outContextData); typedef int32_t (*PFN_NVAFTERMATH_GETDEVICESTATUS)(void* _outStatus); typedef int32_t (*PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION)(void* _outPageFaultInformation); static PFN_NVAFTERMATH_DX12_INITIALIZE nvAftermathDx12Initialize; static PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE nvAftermathDx12CreateContextHandle; static PFN_NVAFTERMATH_RELEASECONTEXTHANDLE nvAftermathReleaseContextHandle; static PFN_NVAFTERMATH_SETEVENTMARKER nvAftermathSetEventMarker; static PFN_NVAFTERMATH_GETDATA nvAftermathGetData; static PFN_NVAFTERMATH_GETDEVICESTATUS nvAftermathGetDeviceStatus; static PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION nvAftermathGetPageFaultInformation; NvApi::NvApi() : m_nvApiDll(NULL) , m_nvGpu(NULL) , m_nvAftermathDll(NULL) , m_aftermathHandle(NULL) { } void NvApi::init() { m_nvGpu = NULL; m_nvApiDll = bx::dlopen( "nvapi" #if BX_ARCH_64BIT "64" #endif // BX_ARCH_32BIT ".dll" ); if (NULL != m_nvApiDll) { nvApiQueryInterface = (PFN_NVAPI_QUERYINTERFACE)bx::dlsym(m_nvApiDll, "nvapi_QueryInterface"); bool initialized = NULL != nvApiQueryInterface; if (initialized) { nvApiInitialize = (PFN_NVAPI_INITIALIZE )nvApiQueryInterface(NVAPI_INITIALIZE); nvApiUnload = (PFN_NVAPI_UNLOAD )nvApiQueryInterface(NVAPI_UNLOAD); nvApiEnumPhysicalGPUs = (PFN_NVAPI_ENUMPHYSICALGPUS )nvApiQueryInterface(NVAPI_ENUMPHYSICALGPUS); nvApiGpuGetMemoryInfo = (PFN_NVAPI_GPUGETMEMORYINFO )nvApiQueryInterface(NVAPI_GPUGETMEMORYINFO); nvApiGpuGetFullName = (PFN_NVAPI_GPUGETFULLNAME )nvApiQueryInterface(NVAPI_GPUGETFULLNAME); nvApiD3D11MultiDrawInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINSTANCEDINDIRECT); nvApiD3D11MultiDrawIndexedInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT); initialized = true && NULL != nvApiInitialize && NULL != nvApiUnload && NULL != nvApiEnumPhysicalGPUs && NULL != nvApiGpuGetMemoryInfo && NULL != nvApiGpuGetFullName && NVAPI_OK == nvApiInitialize() ; if (initialized) { NvPhysicalGpuHandle* physicalGpus[NVAPI_MAX_PHYSICAL_GPUS]; uint32_t numGpus = 0; nvApiEnumPhysicalGPUs(physicalGpus, &numGpus); initialized = 0 < numGpus; if (initialized) { m_nvGpu = physicalGpus[0]; } char name[64]; nvApiGpuGetFullName(m_nvGpu, name); BX_TRACE("%s", name); } initialized = NULL != m_nvGpu; if (!initialized) { nvApiUnload(); } } if (!initialized) { bx::dlclose(m_nvApiDll); m_nvApiDll = NULL; } BX_WARN(!initialized, "NVAPI supported."); } } void NvApi::shutdown() { if (NULL != m_nvGpu) { nvApiUnload(); m_nvGpu = NULL; } if (NULL != m_nvApiDll) { bx::dlclose(m_nvApiDll); m_nvApiDll = NULL; } shutdownAftermath(); } void NvApi::getMemoryInfo(int64_t& _gpuMemoryUsed, int64_t& _gpuMemoryMax) { if (NULL != m_nvGpu) { NvMemoryInfoV2 memInfo; NvApiStatus status = nvApiGpuGetMemoryInfo(m_nvGpu, &memInfo); if (NVAPI_OK == status) { _gpuMemoryMax = 1024 * int64_t(memInfo.availableDedicatedVideoMemory); _gpuMemoryUsed = 1024 * int64_t(memInfo.availableDedicatedVideoMemory - memInfo.curAvailableDedicatedVideoMemory); // BX_TRACE(" dedicatedVideoMemory: %d KiB", memInfo.dedicatedVideoMemory); // BX_TRACE(" availableDedicatedVideoMemory: %d KiB", memInfo.availableDedicatedVideoMemory); // BX_TRACE(" systemVideoMemory: %d KiB", memInfo.systemVideoMemory); // BX_TRACE(" sharedSystemMemory: %d KiB", memInfo.sharedSystemMemory); // BX_TRACE("curAvailableDedicatedVideoMemory: %d KiB", memInfo.curAvailableDedicatedVideoMemory); } } else { _gpuMemoryMax = -INT64_MAX; _gpuMemoryUsed = -INT64_MAX; } } bool NvApi::initAftermath(const ID3D12Device* _device, const ID3D12CommandList* _commandList) { m_nvAftermathDll = bx::dlopen( "GFSDK_Aftermath_Lib." #if BX_ARCH_32BIT "x86" #else "x64" #endif // BX_ARCH_32BIT ".dll" ); if (NULL != m_nvAftermathDll) { nvAftermathDx12Initialize = (PFN_NVAFTERMATH_DX12_INITIALIZE )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_Initialize"); nvAftermathDx12CreateContextHandle = (PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_CreateContextHandle"); nvAftermathReleaseContextHandle = (PFN_NVAFTERMATH_RELEASECONTEXTHANDLE )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_ReleaseContextHandle"); nvAftermathSetEventMarker = (PFN_NVAFTERMATH_SETEVENTMARKER )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_SetEventMarker"); nvAftermathGetData = (PFN_NVAFTERMATH_GETDATA )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetData"); nvAftermathGetDeviceStatus = (PFN_NVAFTERMATH_GETDEVICESTATUS )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetDeviceStatus"); nvAftermathGetPageFaultInformation = (PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetPageFaultInformation"); bool initialized = true && NULL != nvAftermathDx12Initialize && NULL != nvAftermathDx12CreateContextHandle && NULL != nvAftermathReleaseContextHandle && NULL != nvAftermathSetEventMarker && NULL != nvAftermathGetData && NULL != nvAftermathGetDeviceStatus && NULL != nvAftermathGetPageFaultInformation ; if (initialized) { int32_t result; result = nvAftermathDx12Initialize(0x13, 1, _device); if (1 == result) { result = nvAftermathDx12CreateContextHandle(_commandList, &m_aftermathHandle); BX_WARN(1 == result, "%x", result); if (1 == result) { return true; } } } shutdownAftermath(); } return false; } void NvApi::shutdownAftermath() { if (NULL != m_nvAftermathDll) { if (NULL != m_aftermathHandle) { nvAftermathReleaseContextHandle(m_aftermathHandle); m_aftermathHandle = NULL; } bx::dlclose(m_nvAftermathDll); m_nvAftermathDll = NULL; } } #define NVA_CHECK(_call) \ BX_MACRO_BLOCK_BEGIN \ int32_t __result__ = _call; \ BX_CHECK(1 == __result__, #_call " FAILED 0x%08x\n", __result__); \ BX_MACRO_BLOCK_END void NvApi::setMarker(const bx::StringView& _marker) { if (NULL != m_aftermathHandle) { NVA_CHECK(nvAftermathSetEventMarker(m_aftermathHandle, _marker.getPtr(), _marker.getLength() ) ); } } } // namespace bgfx <commit_msg>Cleanup.<commit_after>/* * Copyright 2011-2018 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "bgfx_p.h" #include "nvapi.h" namespace bgfx { /* * NVAPI * * Reference: * http://docs.nvidia.com/gameworks/content/gameworkslibrary/coresdk/nvapi/index.html * https://github.com/jNizM/AHK_NVIDIA_NvAPI/blob/master/info/NvAPI_IDs.txt */ struct NvPhysicalGpuHandle; #define NVAPI_MAX_PHYSICAL_GPUS 64 #if BX_PLATFORM_WINDOWS # define NVAPICALL __cdecl #else # define NVAPICALL #endif // BX_PLATFORM_WINDOWS enum NvApiStatus { NVAPI_OK = 0, NVAPI_ERROR = -1, }; struct NvMemoryInfoV2 { NvMemoryInfoV2() : version(sizeof(NvMemoryInfoV2) | (2 << 16) ) { } uint32_t version; uint32_t dedicatedVideoMemory; uint32_t availableDedicatedVideoMemory; uint32_t systemVideoMemory; uint32_t sharedSystemMemory; uint32_t curAvailableDedicatedVideoMemory; }; typedef void* (NVAPICALL* PFN_NVAPI_QUERYINTERFACE)(uint32_t _functionOffset); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_INITIALIZE)(); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_UNLOAD)(); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_ENUMPHYSICALGPUS)(NvPhysicalGpuHandle* _handle[NVAPI_MAX_PHYSICAL_GPUS], uint32_t* _gpuCount); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETMEMORYINFO)(NvPhysicalGpuHandle* _handle, NvMemoryInfoV2* _memoryInfo); typedef NvApiStatus (NVAPICALL* PFN_NVAPI_GPUGETFULLNAME)(NvPhysicalGpuHandle* _physicalGpu, char _name[64]); #define NVAPI_INITIALIZE UINT32_C(0x0150e828) #define NVAPI_UNLOAD UINT32_C(0xd22bdd7e) #define NVAPI_ENUMPHYSICALGPUS UINT32_C(0xe5ac921f) #define NVAPI_GPUGETMEMORYINFO UINT32_C(0x07f9b368) #define NVAPI_GPUGETFULLNAME UINT32_C(0xceee8e9f) #define NVAPI_MULTIDRAWINSTANCEDINDIRECT UINT32_C(0xd4e26bbf) #define NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT UINT32_C(0x59e890f9) static PFN_NVAPI_QUERYINTERFACE nvApiQueryInterface; static PFN_NVAPI_INITIALIZE nvApiInitialize; static PFN_NVAPI_UNLOAD nvApiUnload; static PFN_NVAPI_ENUMPHYSICALGPUS nvApiEnumPhysicalGPUs; static PFN_NVAPI_GPUGETMEMORYINFO nvApiGpuGetMemoryInfo; static PFN_NVAPI_GPUGETFULLNAME nvApiGpuGetFullName; /* * NVIDIA Aftermath * * Reference: * https://developer.nvidia.com/nvidia-aftermath */ typedef int32_t (*PFN_NVAFTERMATH_DX12_INITIALIZE)(int32_t _version, int32_t _flags, const ID3D12Device* _device); typedef int32_t (*PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)(const ID3D12CommandList* _commandList, NvAftermathContextHandle** _outContextHandle); typedef int32_t (*PFN_NVAFTERMATH_RELEASECONTEXTHANDLE)(const NvAftermathContextHandle* _contextHandle); typedef int32_t (*PFN_NVAFTERMATH_SETEVENTMARKER)(const NvAftermathContextHandle* _contextHandle, const void* _markerData, uint32_t _markerSize); typedef int32_t (*PFN_NVAFTERMATH_GETDATA)(uint32_t _numContexts, const NvAftermathContextHandle** _contextHandles, void* _outContextData); typedef int32_t (*PFN_NVAFTERMATH_GETDEVICESTATUS)(void* _outStatus); typedef int32_t (*PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION)(void* _outPageFaultInformation); static PFN_NVAFTERMATH_DX12_INITIALIZE nvAftermathDx12Initialize; static PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE nvAftermathDx12CreateContextHandle; static PFN_NVAFTERMATH_RELEASECONTEXTHANDLE nvAftermathReleaseContextHandle; static PFN_NVAFTERMATH_SETEVENTMARKER nvAftermathSetEventMarker; static PFN_NVAFTERMATH_GETDATA nvAftermathGetData; static PFN_NVAFTERMATH_GETDEVICESTATUS nvAftermathGetDeviceStatus; static PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION nvAftermathGetPageFaultInformation; NvApi::NvApi() : m_nvApiDll(NULL) , m_nvGpu(NULL) , m_nvAftermathDll(NULL) , m_aftermathHandle(NULL) { } void NvApi::init() { m_nvGpu = NULL; m_nvApiDll = bx::dlopen( "nvapi" #if BX_ARCH_64BIT "64" #endif // BX_ARCH_32BIT ".dll" ); if (NULL != m_nvApiDll) { nvApiQueryInterface = (PFN_NVAPI_QUERYINTERFACE)bx::dlsym(m_nvApiDll, "nvapi_QueryInterface"); bool initialized = NULL != nvApiQueryInterface; if (initialized) { nvApiInitialize = (PFN_NVAPI_INITIALIZE )nvApiQueryInterface(NVAPI_INITIALIZE); nvApiUnload = (PFN_NVAPI_UNLOAD )nvApiQueryInterface(NVAPI_UNLOAD); nvApiEnumPhysicalGPUs = (PFN_NVAPI_ENUMPHYSICALGPUS)nvApiQueryInterface(NVAPI_ENUMPHYSICALGPUS); nvApiGpuGetMemoryInfo = (PFN_NVAPI_GPUGETMEMORYINFO)nvApiQueryInterface(NVAPI_GPUGETMEMORYINFO); nvApiGpuGetFullName = (PFN_NVAPI_GPUGETFULLNAME )nvApiQueryInterface(NVAPI_GPUGETFULLNAME); nvApiD3D11MultiDrawInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINSTANCEDINDIRECT); nvApiD3D11MultiDrawIndexedInstancedIndirect = (PFN_NVAPI_MULTIDRAWINDIRECT)nvApiQueryInterface(NVAPI_MULTIDRAWINDEXEDINSTANCEDINDIRECT); initialized = true && NULL != nvApiInitialize && NULL != nvApiUnload && NULL != nvApiEnumPhysicalGPUs && NULL != nvApiGpuGetMemoryInfo && NULL != nvApiGpuGetFullName && NVAPI_OK == nvApiInitialize() ; if (initialized) { NvPhysicalGpuHandle* physicalGpus[NVAPI_MAX_PHYSICAL_GPUS]; uint32_t numGpus = 0; nvApiEnumPhysicalGPUs(physicalGpus, &numGpus); initialized = 0 < numGpus; if (initialized) { m_nvGpu = physicalGpus[0]; } char name[64]; nvApiGpuGetFullName(m_nvGpu, name); BX_TRACE("%s", name); } initialized = NULL != m_nvGpu; if (!initialized) { nvApiUnload(); } } if (!initialized) { bx::dlclose(m_nvApiDll); m_nvApiDll = NULL; } BX_WARN(!initialized, "NVAPI supported."); } } void NvApi::shutdown() { if (NULL != m_nvGpu) { nvApiUnload(); m_nvGpu = NULL; } if (NULL != m_nvApiDll) { bx::dlclose(m_nvApiDll); m_nvApiDll = NULL; } shutdownAftermath(); } void NvApi::getMemoryInfo(int64_t& _gpuMemoryUsed, int64_t& _gpuMemoryMax) { if (NULL != m_nvGpu) { NvMemoryInfoV2 memInfo; NvApiStatus status = nvApiGpuGetMemoryInfo(m_nvGpu, &memInfo); if (NVAPI_OK == status) { _gpuMemoryMax = 1024 * int64_t(memInfo.availableDedicatedVideoMemory); _gpuMemoryUsed = 1024 * int64_t(memInfo.availableDedicatedVideoMemory - memInfo.curAvailableDedicatedVideoMemory); // BX_TRACE(" dedicatedVideoMemory: %d KiB", memInfo.dedicatedVideoMemory); // BX_TRACE(" availableDedicatedVideoMemory: %d KiB", memInfo.availableDedicatedVideoMemory); // BX_TRACE(" systemVideoMemory: %d KiB", memInfo.systemVideoMemory); // BX_TRACE(" sharedSystemMemory: %d KiB", memInfo.sharedSystemMemory); // BX_TRACE("curAvailableDedicatedVideoMemory: %d KiB", memInfo.curAvailableDedicatedVideoMemory); } } else { _gpuMemoryMax = -INT64_MAX; _gpuMemoryUsed = -INT64_MAX; } } bool NvApi::initAftermath(const ID3D12Device* _device, const ID3D12CommandList* _commandList) { m_nvAftermathDll = bx::dlopen( "GFSDK_Aftermath_Lib." #if BX_ARCH_32BIT "x86" #else "x64" #endif // BX_ARCH_32BIT ".dll" ); if (NULL != m_nvAftermathDll) { nvAftermathDx12Initialize = (PFN_NVAFTERMATH_DX12_INITIALIZE )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_Initialize"); nvAftermathDx12CreateContextHandle = (PFN_NVAFTERMATH_DX12_CREATECONTEXTHANDLE)bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_DX12_CreateContextHandle"); nvAftermathReleaseContextHandle = (PFN_NVAFTERMATH_RELEASECONTEXTHANDLE )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_ReleaseContextHandle"); nvAftermathSetEventMarker = (PFN_NVAFTERMATH_SETEVENTMARKER )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_SetEventMarker"); nvAftermathGetData = (PFN_NVAFTERMATH_GETDATA )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetData"); nvAftermathGetDeviceStatus = (PFN_NVAFTERMATH_GETDEVICESTATUS )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetDeviceStatus"); nvAftermathGetPageFaultInformation = (PFN_NVAFTERMATH_GETPAGEFAULTINFORMATION )bx::dlsym(m_nvAftermathDll, "GFSDK_Aftermath_GetPageFaultInformation"); bool initialized = true && NULL != nvAftermathDx12Initialize && NULL != nvAftermathDx12CreateContextHandle && NULL != nvAftermathReleaseContextHandle && NULL != nvAftermathSetEventMarker && NULL != nvAftermathGetData && NULL != nvAftermathGetDeviceStatus && NULL != nvAftermathGetPageFaultInformation ; if (initialized) { int32_t result; result = nvAftermathDx12Initialize(0x13, 1, _device); if (1 == result) { result = nvAftermathDx12CreateContextHandle(_commandList, &m_aftermathHandle); BX_WARN(1 == result, "%x", result); if (1 == result) { return true; } } } shutdownAftermath(); } return false; } void NvApi::shutdownAftermath() { if (NULL != m_nvAftermathDll) { if (NULL != m_aftermathHandle) { nvAftermathReleaseContextHandle(m_aftermathHandle); m_aftermathHandle = NULL; } bx::dlclose(m_nvAftermathDll); m_nvAftermathDll = NULL; } } #define NVA_CHECK(_call) \ BX_MACRO_BLOCK_BEGIN \ int32_t __result__ = _call; \ BX_CHECK(1 == __result__, #_call " FAILED 0x%08x\n", __result__); \ BX_MACRO_BLOCK_END void NvApi::setMarker(const bx::StringView& _marker) { if (NULL != m_aftermathHandle) { NVA_CHECK(nvAftermathSetEventMarker(m_aftermathHandle, _marker.getPtr(), _marker.getLength() ) ); } } } // namespace bgfx <|endoftext|>
<commit_before>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.7 1998-06-04 17:57:10 gtucker Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->GetNodeList() ); tGridListIter<tEdge> eiter( g->GetEdgeList() ); tListIter<tTriangle> titer( g->GetTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->GetNodeList()->getSize(); int nedges = g->GetEdgeList()->getSize(); int ntri = g->GetTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->GetEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->GetCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); CreateAndOpenFile( &qofs, ".q" ); } template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->GetNodeList() ); tSubNode *cn; int nActiveNodes = g->GetNodeList()->getActiveSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; qofs << " " << time << "\n " << nActiveNodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; if( cn->getDownstrmNbr() ) netofs << cn->getDownstrmNbr()->getID() << endl; slpofs << cn->getSlope() << endl; qofs << cn->getQ() << endl; } } <commit_msg>changed capitalization on get/set fns also changed output of q to all nodes, not just active ones<commit_after>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.8 1998-06-04 21:25:57 gtucker Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->getNodeList() ); tGridListIter<tEdge> eiter( g->getEdgeList() ); tListIter<tTriangle> titer( g->getTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->getNodeList()->getSize(); int nedges = g->getEdgeList()->getSize(); int ntri = g->getTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->getEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->getCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); CreateAndOpenFile( &qofs, ".q" ); } //TODO: should output boundary points as well so they'll map up with nodes // for plotting. Means changing getSlope so it returns zero if flowedg // undefined template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->getNodeList() ); tSubNode *cn; int nActiveNodes = g->getNodeList()->getActiveSize(); int nnodes = g->getNodeList()->getSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; qofs << " " << time << "\n " << nnodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; if( cn->getDownstrmNbr() ) netofs << cn->getDownstrmNbr()->getID() << endl; slpofs << cn->getSlope() << endl; } for( cn = ni.FirstP(); !(ni.AtEnd()); cn = ni.NextP() ) qofs << cn->getQ() << endl; } <|endoftext|>
<commit_before>#include "GameObject.h" #include "Engine.h" #include "Objects\LevelGrid.h" #include "Scenes\GameplayScene.h" USING_NS_CC; GameObject::GameObject(Type type) : _direction(Direction::UP), _sprite(nullptr), _engine(Engine::getInstance()), _type(type), _isPassable(true) { } GameObject::~GameObject() { _sprite = nullptr; _engine = nullptr; if (!_isPassable) removeFromPassableLayer(_position); } bool GameObject::init() { return Node::init(); } GameObject::Direction GameObject::getGridDirection() { return _direction; } void GameObject::setGridDirection(Direction direction) { _direction = direction; setGridDirection(_sprite, direction); } Pos2 GameObject::getGridPosition() const { return _position; } void GameObject::setGridPosition(const Pos2& p) { auto prevPos = _position; _position = p; setGridPosition(_sprite, p); if (!_isPassable) updatePassableLayer(p, prevPos); } void GameObject::setGridPosition(int x, int y) { setGridPosition(Pos2(x, y)); } Pos2 GameObject::getGridPosition(const Node* node) { return Pos2(node->getPosition() / TILE_SIZE); } void GameObject::setGridPosition(Node* node, const Pos2& p) { node->setPosition(Vec2(p.x, p.y) * TILE_SIZE + Vec2::ONE * TILE_SIZE / 2); } void GameObject::setGridPosition(Node* node, int x, int y) { setGridPosition(node, Pos2(x, y)); } void GameObject::setGridDirection(Node* node, Direction direction) { node->setRotation(directionToRotation(direction)); } Sprite* GameObject::getSprite() { return _sprite; } void GameObject::setSprite(Sprite* sprite) { if (_sprite != nullptr && _sprite->getParent() == this) this->removeChild(_sprite); _sprite = sprite; this->addChild(_sprite); } Pos2 GameObject::directionToOffset(Direction direction) { switch (direction) { case Direction::DOWN: return Pos2(0, -1); case Direction::UP: return Pos2(0, +1); case Direction::LEFT: return Pos2(-1, 0); case Direction::RIGHT: return Pos2(+1, 0); } return Pos2(0, 0); } GameObject::Direction GameObject::offsetToDirection(Pos2 offset) { offset.normalize(); if (offset == Pos2(0, -1)) return Direction::DOWN; if (offset == Pos2(0, +1)) return Direction::UP; if (offset == Pos2(-1, 0)) return Direction::LEFT; if (offset == Pos2(+1, 0)) return Direction::RIGHT; throw std::logic_error("Can not convert offset " + offset.toString() + " to direction!"); } float GameObject::directionToRotation(Direction direction) { switch (direction) { case Direction::UP: return 0.0f; case Direction::DOWN: return 180.0f; case Direction::LEFT: return -90.0f; case Direction::RIGHT: return 90.0f; } return 0.0f; } void GameObject::updatePassableLayer(const Pos2& pos, const Pos2& prevPos) { auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>(); if (scene == nullptr) return; auto grid = scene->getGrid(); grid->setDynamicPassable(prevPos, PassableValue::PASSABLE); grid->setDynamicPassable(pos, PassableValue::INPASSABLE); } void GameObject::removeFromPassableLayer(const Pos2& pos) { auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>(); if (scene == nullptr) return; auto grid = scene->getGrid(); grid->setDynamicPassable(pos, PassableValue::PASSABLE); }<commit_msg>Added missing consts<commit_after>#include "GameObject.h" #include "Engine.h" #include "Objects\LevelGrid.h" #include "Scenes\GameplayScene.h" USING_NS_CC; GameObject::GameObject(Type type) : _direction(Direction::UP), _sprite(nullptr), _engine(Engine::getInstance()), _type(type), _isPassable(true) { } GameObject::~GameObject() { _sprite = nullptr; _engine = nullptr; if (!_isPassable) removeFromPassableLayer(_position); } bool GameObject::init() { return Node::init(); } GameObject::Direction GameObject::getGridDirection() const { return _direction; } void GameObject::setGridDirection(Direction direction) { _direction = direction; setGridDirection(_sprite, direction); } Pos2 GameObject::getGridPosition() const { return _position; } void GameObject::setGridPosition(const Pos2& p) { auto prevPos = _position; _position = p; setGridPosition(_sprite, p); if (!_isPassable) updatePassableLayer(p, prevPos); } void GameObject::setGridPosition(int x, int y) { setGridPosition(Pos2(x, y)); } Pos2 GameObject::getGridPosition(const Node* node) { return Pos2(node->getPosition() / TILE_SIZE); } void GameObject::setGridPosition(Node* node, const Pos2& p) { node->setPosition(Vec2(p.x, p.y) * TILE_SIZE + Vec2::ONE * TILE_SIZE / 2); } void GameObject::setGridPosition(Node* node, int x, int y) { setGridPosition(node, Pos2(x, y)); } void GameObject::setGridDirection(Node* node, Direction direction) { node->setRotation(directionToRotation(direction)); } Sprite* GameObject::getSprite() const { return _sprite; } void GameObject::setSprite(Sprite* sprite) { if (_sprite != nullptr && _sprite->getParent() == this) this->removeChild(_sprite); _sprite = sprite; this->addChild(_sprite); } Pos2 GameObject::directionToOffset(Direction direction) { switch (direction) { case Direction::DOWN: return Pos2(0, -1); case Direction::UP: return Pos2(0, +1); case Direction::LEFT: return Pos2(-1, 0); case Direction::RIGHT: return Pos2(+1, 0); } return Pos2(0, 0); } GameObject::Direction GameObject::offsetToDirection(Pos2 offset) { offset.normalize(); if (offset == Pos2(0, -1)) return Direction::DOWN; if (offset == Pos2(0, +1)) return Direction::UP; if (offset == Pos2(-1, 0)) return Direction::LEFT; if (offset == Pos2(+1, 0)) return Direction::RIGHT; throw std::logic_error("Can not convert offset " + offset.toString() + " to direction!"); } float GameObject::directionToRotation(Direction direction) { switch (direction) { case Direction::UP: return 0.0f; case Direction::DOWN: return 180.0f; case Direction::LEFT: return -90.0f; case Direction::RIGHT: return 90.0f; } return 0.0f; } void GameObject::updatePassableLayer(const Pos2& pos, const Pos2& prevPos) { auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>(); if (scene == nullptr) return; auto grid = scene->getGrid(); grid->setDynamicPassable(prevPos, PassableValue::PASSABLE); grid->setDynamicPassable(pos, PassableValue::INPASSABLE); } void GameObject::removeFromPassableLayer(const Pos2& pos) { auto scene = Engine::getInstance()->getCurrentScene<GameplayScene>(); if (scene == nullptr) return; auto grid = scene->getGrid(); grid->setDynamicPassable(pos, PassableValue::PASSABLE); }<|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 <stdint.h> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/internal/types.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace space_to_depth { // This file has two implementation of SpaceToDepth. Note that SpaceToDepth // only works on 4D tensors. enum KernelType { kReference, kGenericOptimized, }; constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); auto data_type = output->type; TF_LITE_ENSURE(context, data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 || data_type == kTfLiteInt8 || data_type == kTfLiteInt32 || data_type == kTfLiteInt64); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); const int block_size = params->block_size; const int input_height = input->dims->data[1]; const int input_width = input->dims->data[2]; int output_height = input_height / block_size; int output_width = input_width / block_size; TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size); TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = output_height; output_size->data[2] = output_width; output_size->data[3] = input->dims->data[3] * block_size * block_size; return context->ResizeTensor(context, output, output_size); } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); #define TF_LITE_SPACE_TO_DEPTH(type, scalar) \ tflite::SpaceToDepthParams op_params; \ op_params.block_size = params->block_size; \ type::SpaceToDepth(op_params, GetTensorShape(input), \ GetTensorData<scalar>(input), GetTensorShape(output), \ GetTensorData<scalar>(output)) switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, float); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, float); } break; case kTfLiteUInt8: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, uint8_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, uint8_t); } break; case kTfLiteInt8: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int8_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int8_t); } break; case kTfLiteInt32: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int32_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int32_t); } break; case kTfLiteInt64: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int64_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int64_t); } break; default: context->ReportError(context, "Type '%s' not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } #undef TF_LITE_SPACE_TO_DEPTH return kTfLiteOk; } } // namespace space_to_depth TfLiteRegistration* Register_SPACE_TO_DEPTH_REF() { static TfLiteRegistration r = { nullptr, nullptr, space_to_depth::Prepare, space_to_depth::Eval<space_to_depth::kReference>}; return &r; } TfLiteRegistration* Register_SPACE_TO_DEPTH_GENERIC_OPT() { static TfLiteRegistration r = { nullptr, nullptr, space_to_depth::Prepare, space_to_depth::Eval<space_to_depth::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_SPACE_TO_DEPTH() { return Register_SPACE_TO_DEPTH_GENERIC_OPT(); } } // namespace builtin } // namespace ops } // namespace tflite <commit_msg>Prevent one more div by 0 in TFLite<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 <stdint.h> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/internal/types.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace space_to_depth { // This file has two implementation of SpaceToDepth. Note that SpaceToDepth // only works on 4D tensors. enum KernelType { kReference, kGenericOptimized, }; constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); auto data_type = output->type; TF_LITE_ENSURE(context, data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 || data_type == kTfLiteInt8 || data_type == kTfLiteInt32 || data_type == kTfLiteInt64); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); const int block_size = params->block_size; TF_LITE_ENSURE(context, block_size > 0); const int input_height = input->dims->data[1]; const int input_width = input->dims->data[2]; int output_height = input_height / block_size; int output_width = input_width / block_size; TF_LITE_ENSURE_EQ(context, input_height, output_height * block_size); TF_LITE_ENSURE_EQ(context, input_width, output_width * block_size); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = input->dims->data[0]; output_size->data[1] = output_height; output_size->data[2] = output_width; output_size->data[3] = input->dims->data[3] * block_size * block_size; return context->ResizeTensor(context, output, output_size); } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteSpaceToDepthParams*>(node->builtin_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); #define TF_LITE_SPACE_TO_DEPTH(type, scalar) \ tflite::SpaceToDepthParams op_params; \ op_params.block_size = params->block_size; \ type::SpaceToDepth(op_params, GetTensorShape(input), \ GetTensorData<scalar>(input), GetTensorShape(output), \ GetTensorData<scalar>(output)) switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, float); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, float); } break; case kTfLiteUInt8: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, uint8_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, uint8_t); } break; case kTfLiteInt8: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int8_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int8_t); } break; case kTfLiteInt32: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int32_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int32_t); } break; case kTfLiteInt64: if (kernel_type == kReference) { TF_LITE_SPACE_TO_DEPTH(reference_ops, int64_t); } else { TF_LITE_SPACE_TO_DEPTH(optimized_ops, int64_t); } break; default: context->ReportError(context, "Type '%s' not currently supported.", TfLiteTypeGetName(input->type)); return kTfLiteError; } #undef TF_LITE_SPACE_TO_DEPTH return kTfLiteOk; } } // namespace space_to_depth TfLiteRegistration* Register_SPACE_TO_DEPTH_REF() { static TfLiteRegistration r = { nullptr, nullptr, space_to_depth::Prepare, space_to_depth::Eval<space_to_depth::kReference>}; return &r; } TfLiteRegistration* Register_SPACE_TO_DEPTH_GENERIC_OPT() { static TfLiteRegistration r = { nullptr, nullptr, space_to_depth::Prepare, space_to_depth::Eval<space_to_depth::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_SPACE_TO_DEPTH() { return Register_SPACE_TO_DEPTH_GENERIC_OPT(); } } // namespace builtin } // namespace ops } // namespace tflite <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_VERBOSE); ofSetLogLevel("ofThread", OF_LOG_ERROR); ofEnableAlphaBlending(); doDrawInfo = true; targetWidth = 640; targetHeight = 480; #if defined(TARGET_OPENGLES) consoleListener.setup(this); omxCameraSettings.width = targetWidth; omxCameraSettings.height = targetHeight; omxCameraSettings.framerate = 15; omxCameraSettings.enableTexture = true; videoGrabber.setup(omxCameraSettings); filterCollection.setup(); ofSetVerticalSync(false); #else videoGrabber.setDeviceID(0); videoGrabber.setDesiredFrameRate(30); videoGrabber.setup(targetWidth, targetHeight); ofSetVerticalSync(true); #endif doShader = true; shader.load("shaderExample"); fbo.allocate(targetWidth, targetHeight); fbo.begin(); ofClear(0, 0, 0, 0); fbo.end(); // selfberry colorGifEncoder.setup(targetWidth, targetHeight, .2, 256); ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved); videoTexture.allocate(targetWidth, targetHeight, GL_RGB); bufferDir = "buffer"; timeZero = ofGetElapsedTimeMicros(); frameNumber = 0; slotRecording = 255; slotAmount = 4; if (dirSRC.doesDirectoryExist(bufferDir)) { dirSRC.removeDirectory(bufferDir, true); } if (!dirSRC.doesDirectoryExist("slot1")) { dirSRC.createDirectory("slot1"); } if (!dirSRC.doesDirectoryExist("slot2")) { dirSRC.createDirectory("slot2"); } if (!dirSRC.doesDirectoryExist("slot3")) { dirSRC.createDirectory("slot3"); } if (!dirSRC.doesDirectoryExist("slot4")) { dirSRC.createDirectory("slot4"); } if (!dirSRC.doesDirectoryExist("tmp")) { dirSRC.createDirectory("tmp"); } dirSRC.createDirectory(bufferDir); indexSavedPhoto = 0; isRecording = false; amountOfFrames = 10; maxFrames = 10; if (settings.loadFile("settings.xml") == false) { ofLog() << "XML ERROR, possibly quit"; } settings.pushTag("settings"); /*if (settings.getValue("log", 1) == 0) { ofLogLevel(OF_LOG_SILENT); } fps = settings.getValue("fps", 15); maxFrames = settings.getValue("frameAmount", 15); bufferDir = settings.getValue("bufferDir", "buffer"); outputDir = settings.getValue("outputDir", "output"); if (settings.getValue("fullScreen", 0) == 1) { ofToggleFullscreen(); }*/ slotDir = "slot"; for (int i = 0; i < settings.getNumTags("slot"); i++) { settings.pushTag("slot", i); videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0)); settings.popTag(); } lastSpot = 0; currentDisplaySlot = 2; bkgLayer.loadImage("ui.png"); } //-------------------------------------------------------------- void ofApp::update() { #if defined(TARGET_OPENGLES) #else videoGrabber.update(); #endif if (!doShader ) { ofLogNotice("update() !doShader return"); return; } if (!videoGrabber.isFrameNew()) { ofLogNotice("update() !videoGrabber.isFrameNew return"); return; } //ofLogNotice("update() fbo begin"); fbo.begin(); ofClear(1, 1, 0, 0); shader.begin(); shader.setUniform1f("time", ofGetElapsedTimef()); shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight()); #if defined(TARGET_OPENGLES) shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID()); videoGrabber.draw(); #else shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1? videoGrabber.draw(0, 0); #endif shader.end(); fbo.end(); //ofLogNotice("update() fbo end"); if (isRecording == true) { ofLogNotice("update() rec"); dirSRC.createDirectory(bufferDir); dirSRC.listDir(bufferDir); recordedFramesAmount = dirSRC.size(); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); if (recordedFramesAmount == maxFrames) { isRecording = false; indexSavedPhoto = 0; ofLogNotice("update() stop recording"); } else { if (videoGrabber.isFrameNew()) { ofLogNotice("update() isFrameNew"); string filename; if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto); if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto); if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto); // fbo to pixels fbo.readToPixels(pix); fbo.draw(0, 0, targetWidth, targetHeight); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); //pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR); savedImage.setFromPixels(pix); savedImage.setImageType(OF_IMAGE_COLOR); switch (currentDisplaySlot) { case 2: savedImage.saveImage("slot2//" + filename + ".tga"); break; case 3: savedImage.saveImage("slot3//" + filename + ".tga"); break; case 4: savedImage.saveImage("slot4//" + filename + ".tga"); break; } savedImage.saveImage(bufferDir + "//" + filename + ".tga"); //omxCameraSettings.width, omxCameraSettings.height // add frame to gif encoder colorGifEncoder.addFrame( pix.getPixels(), targetWidth, targetHeight, pix.getBitsPerPixel()/*, .1f duration */ ); recordedFramesAmount++; pix.clear(); savedImage.clear(); indexSavedPhoto++; if (indexSavedPhoto == amountOfFrames) { ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames)); isRecording = false; indexSavedPhoto = 0; saveGif(); } } } } for (i = 1; i < slotAmount; i++) { videoGrid[i].loadFrameNumber(frameNumber); } frameNumber++; if (frameNumber == maxFrames) { frameNumber = 0; } } void ofApp::saveGif() { string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); ofLogNotice("saveGif: " + fileName); colorGifEncoder.save("gif//" + fileName + ".gif"); ofLogNotice("saveGif end"); } void ofApp::onGifSaved(string & fileName) { cout << "gif saved as " << fileName << endl; ofLogNotice("onGifSaved: " + fileName); colorGifEncoder.reset(); ofLogNotice("onGifSaved reset"); } //-------------------------------------------------------------- void ofApp::draw() { ofClear(0, 0, 0, 0); stringstream info; info << "APP FPS: " << ofGetFrameRate() << "\n"; info << "SHADER ENABLED: " << doShader << "\n"; if (doShader) { #if defined(TARGET_OPENGLES) fbo.draw(330, 13); #else videoGrabber.draw(330, 13); #endif } else { #if defined(TARGET_OPENGLES) videoGrabber.draw(); info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n"; info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n"; #else videoGrabber.draw(0, 0); #endif } for (int i = 1; i < slotAmount; i++) { videoGrid[i].draw(); } info << "\n"; info << "VERT: changement de filtre" << "\n"; info << "ROUGE: enregistrer" << "\n"; bkgLayer.draw(0, 0); if (doDrawInfo) { ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { //ofLog(OF_LOG_VERBOSE, "%c keyPressed", key); ofLogNotice("PRESSED KEY: " + ofToString(key)); /*RED 13 10 WHITE 127 126 YELLOW 54 GREEN 357 65 BLUE 50*/ switch (key) { case 65: case 357: #if defined(TARGET_OPENGLES) videoGrabber.setImageFilter(filterCollection.getNextFilter()); #endif break; case 10: case 13: if (!isRecording) { isRecording = true; indexSavedPhoto = 0; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 2; bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); } break; case 126: doDrawInfo = !doDrawInfo; break; case 50: case 359: doShader = !doShader; break; } } #if defined(TARGET_OPENGLES) void ofApp::onCharacterReceived(KeyListenerEventData& e) { keyPressed((int)e.character); } #endif <commit_msg>creation dossier gif<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_VERBOSE); ofSetLogLevel("ofThread", OF_LOG_ERROR); ofEnableAlphaBlending(); doDrawInfo = true; targetWidth = 640; targetHeight = 480; #if defined(TARGET_OPENGLES) consoleListener.setup(this); omxCameraSettings.width = targetWidth; omxCameraSettings.height = targetHeight; omxCameraSettings.framerate = 15; omxCameraSettings.enableTexture = true; videoGrabber.setup(omxCameraSettings); filterCollection.setup(); ofSetVerticalSync(false); #else videoGrabber.setDeviceID(0); videoGrabber.setDesiredFrameRate(30); videoGrabber.setup(targetWidth, targetHeight); ofSetVerticalSync(true); #endif doShader = true; shader.load("shaderExample"); fbo.allocate(targetWidth, targetHeight); fbo.begin(); ofClear(0, 0, 0, 0); fbo.end(); // selfberry colorGifEncoder.setup(targetWidth, targetHeight, .2, 256); ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved); videoTexture.allocate(targetWidth, targetHeight, GL_RGB); bufferDir = "buffer"; timeZero = ofGetElapsedTimeMicros(); frameNumber = 0; slotRecording = 255; slotAmount = 4; if (dirSRC.doesDirectoryExist(bufferDir)) { dirSRC.removeDirectory(bufferDir, true); } if (!dirSRC.doesDirectoryExist("slot1")) { dirSRC.createDirectory("slot1"); } if (!dirSRC.doesDirectoryExist("slot2")) { dirSRC.createDirectory("slot2"); } if (!dirSRC.doesDirectoryExist("slot3")) { dirSRC.createDirectory("slot3"); } if (!dirSRC.doesDirectoryExist("slot4")) { dirSRC.createDirectory("slot4"); } if (!dirSRC.doesDirectoryExist("tmp")) { dirSRC.createDirectory("tmp"); } if (!dirSRC.doesDirectoryExist("gif")) { dirSRC.createDirectory("gif"); } dirSRC.createDirectory(bufferDir); indexSavedPhoto = 0; isRecording = false; amountOfFrames = 10; maxFrames = 10; if (settings.loadFile("settings.xml") == false) { ofLog() << "XML ERROR, possibly quit"; } settings.pushTag("settings"); /*if (settings.getValue("log", 1) == 0) { ofLogLevel(OF_LOG_SILENT); } fps = settings.getValue("fps", 15); maxFrames = settings.getValue("frameAmount", 15); bufferDir = settings.getValue("bufferDir", "buffer"); outputDir = settings.getValue("outputDir", "output"); if (settings.getValue("fullScreen", 0) == 1) { ofToggleFullscreen(); }*/ slotDir = "slot"; for (int i = 0; i < settings.getNumTags("slot"); i++) { settings.pushTag("slot", i); videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0)); settings.popTag(); } lastSpot = 0; currentDisplaySlot = 2; bkgLayer.loadImage("ui.png"); } //-------------------------------------------------------------- void ofApp::update() { #if defined(TARGET_OPENGLES) #else videoGrabber.update(); #endif if (!doShader ) { ofLogNotice("update() !doShader return"); return; } if (!videoGrabber.isFrameNew()) { ofLogNotice("update() !videoGrabber.isFrameNew return"); return; } //ofLogNotice("update() fbo begin"); fbo.begin(); ofClear(1, 1, 0, 0); shader.begin(); shader.setUniform1f("time", ofGetElapsedTimef()); shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight()); #if defined(TARGET_OPENGLES) shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID()); videoGrabber.draw(); #else shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1? videoGrabber.draw(0, 0); #endif shader.end(); fbo.end(); //ofLogNotice("update() fbo end"); if (isRecording == true) { ofLogNotice("update() rec"); dirSRC.createDirectory(bufferDir); dirSRC.listDir(bufferDir); recordedFramesAmount = dirSRC.size(); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); if (recordedFramesAmount == maxFrames) { isRecording = false; indexSavedPhoto = 0; ofLogNotice("update() stop recording"); } else { if (videoGrabber.isFrameNew()) { ofLogNotice("update() isFrameNew"); string filename; if (indexSavedPhoto < 10) filename = "seq00" + ofToString(indexSavedPhoto); if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "seq0" + ofToString(indexSavedPhoto); if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "seq" + ofToString(indexSavedPhoto); // fbo to pixels fbo.readToPixels(pix); fbo.draw(0, 0, targetWidth, targetHeight); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); //pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR); savedImage.setFromPixels(pix); savedImage.setImageType(OF_IMAGE_COLOR); switch (currentDisplaySlot) { case 2: savedImage.saveImage("slot2//" + filename + ".tga"); break; case 3: savedImage.saveImage("slot3//" + filename + ".tga"); break; case 4: savedImage.saveImage("slot4//" + filename + ".tga"); break; } ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot)); savedImage.saveImage(bufferDir + "//" + filename + ".tga"); //omxCameraSettings.width, omxCameraSettings.height // add frame to gif encoder colorGifEncoder.addFrame( pix.getPixels(), targetWidth, targetHeight, pix.getBitsPerPixel()/*, .1f duration */ ); recordedFramesAmount++; pix.clear(); savedImage.clear(); indexSavedPhoto++; if (indexSavedPhoto == amountOfFrames) { ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames)); isRecording = false; indexSavedPhoto = 0; saveGif(); } } } } for (i = 1; i < slotAmount; i++) { videoGrid[i].loadFrameNumber(frameNumber); } frameNumber++; if (frameNumber == maxFrames) { frameNumber = 0; } } void ofApp::saveGif() { string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); ofLogNotice("saveGif: " + fileName); colorGifEncoder.save("gif//" + fileName + ".gif"); ofLogNotice("saveGif end"); } void ofApp::onGifSaved(string & fileName) { cout << "gif saved as " << fileName << endl; ofLogNotice("onGifSaved: " + fileName); colorGifEncoder.reset(); ofLogNotice("onGifSaved reset"); } //-------------------------------------------------------------- void ofApp::draw() { ofClear(0, 0, 0, 0); stringstream info; info << "APP FPS: " << ofGetFrameRate() << "\n"; info << "SHADER ENABLED: " << doShader << "\n"; if (doShader) { #if defined(TARGET_OPENGLES) fbo.draw(330, 13); #else videoGrabber.draw(330, 13); #endif } else { #if defined(TARGET_OPENGLES) videoGrabber.draw(); info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n"; info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n"; #else videoGrabber.draw(0, 0); #endif } for (int i = 1; i < slotAmount; i++) { videoGrid[i].draw(); } info << "\n"; info << "VERT: changement de filtre" << "\n"; info << "ROUGE: enregistrer" << "\n"; bkgLayer.draw(0, 0); if (doDrawInfo) { ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { //ofLog(OF_LOG_VERBOSE, "%c keyPressed", key); ofLogNotice("PRESSED KEY: " + ofToString(key)); /*RED 13 10 WHITE 127 126 YELLOW 54 GREEN 357 65 BLUE 50*/ switch (key) { case 65: case 357: #if defined(TARGET_OPENGLES) videoGrabber.setImageFilter(filterCollection.getNextFilter()); #endif break; case 10: case 13: if (!isRecording) { isRecording = true; indexSavedPhoto = 0; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 2; bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); } break; case 126: doDrawInfo = !doDrawInfo; break; case 50: case 359: doShader = !doShader; break; } } #if defined(TARGET_OPENGLES) void ofApp::onCharacterReceived(KeyListenerEventData& e) { keyPressed((int)e.character); } #endif <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief イグナイター・アプリケーション・クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "main.hpp" #include "core/glcore.hpp" #include "utils/i_scene.hpp" #include "utils/director.hpp" #include "widgets/widget.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_null.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_filer.hpp" #include "widgets/widget_terminal.hpp" #include "widgets/widget_list.hpp" #include "widgets/widget_view.hpp" #include "widgets/widget_utils.hpp" #include "interlock.hpp" #include "root_menu.hpp" #include "ign_client_tcp.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief Ignitor アプリケーション・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class ignitor : public utils::i_scene { utils::director<core>& director_; interlock interlock_; root_menu root_menu_; /// asio::io_service io_service_; net::ign_client_tcp client_; uint32_t delay_client_; bool connect_client_; bool start_client_; std::string ip_; uint32_t exit_loop_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ignitor(utils::director<core>& d) : director_(d), interlock_(), root_menu_(d, client_, interlock_), /// io_service_(), /// client_(io_service_), client_(), delay_client_(60), connect_client_(false), start_client_(false), ip_(), exit_loop_(60) { } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() { root_menu_.initialize(); #if 0 director_.at().exit_func_ = [=]() { std::cout << "Recive EXIT" << std::endl; if(exit_loop_ > 0) { --exit_loop_; } return exit_loop_ == 0; }; #endif } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { root_menu_.update(); gui::widget_director& wd = director_.at().widget_director_; if(start_client_) { if(client_.probe()) { client_.service(); } } else { bool cn = root_menu_.get_target_connect(); if(!connect_client_ && cn) { // 接続が有効になった connect_client_ = cn; delay_client_ = 60; } if(delay_client_ > 0) { --delay_client_; if(delay_client_ == 0) { auto ip = root_menu_.get_target_ip(); if(!ip.empty() && ip_ != ip) { ip_ = ip; client_.start(ip_, 23); start_client_ = true; } } } } /// io_service_.run(); #if 0 #if 0 // Drag & Drop されたファイル gl::core& core = gl::core::get_instance(); int id = core.get_recv_files_id(); if(drop_file_id_ != id) { drop_file_id_ = id; const utils::strings& ss = core.get_recv_files_path(); if(!ss.empty()) { std::string path = ss[0]; if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) { load_ctx_->get_local_param().select_file_func_(path); } } } #endif #endif wd.update(); } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() { director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void destroy() { } }; } <commit_msg>update: kikusui manage<commit_after>#pragma once //=====================================================================// /*! @file @brief イグナイター・アプリケーション・クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "main.hpp" #include "core/glcore.hpp" #include "utils/i_scene.hpp" #include "utils/director.hpp" #include "widgets/widget.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_null.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_filer.hpp" #include "widgets/widget_terminal.hpp" #include "widgets/widget_list.hpp" #include "widgets/widget_view.hpp" #include "widgets/widget_utils.hpp" #include "interlock.hpp" #include "root_menu.hpp" #include "ign_client_tcp.hpp" namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief Ignitor アプリケーション・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class ignitor : public utils::i_scene { utils::director<core>& director_; interlock interlock_; root_menu root_menu_; /// asio::io_service io_service_; net::ign_client_tcp client_; uint32_t delay_client_; bool connect_client_; bool start_client_; std::string ip_; uint32_t exit_loop_; bool root_menu_exit_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ignitor(utils::director<core>& d) : director_(d), interlock_(), root_menu_(d, client_, interlock_), /// io_service_(), /// client_(io_service_), client_(), delay_client_(60), connect_client_(false), start_client_(false), ip_(), exit_loop_(60), root_menu_exit_(false) { } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() { root_menu_.initialize(); director_.at().exit_func_ = [=]() { if(!root_menu_exit_) { root_menu_.exit(); root_menu_exit_ = true; } // std::cout << "Recive EXIT" << std::endl; if(exit_loop_ > 0) { --exit_loop_; } return exit_loop_ == 0; }; } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { root_menu_.update(); gui::widget_director& wd = director_.at().widget_director_; if(start_client_) { if(client_.probe()) { client_.service(); } } else { bool cn = root_menu_.get_target_connect(); if(!connect_client_ && cn) { // 接続が有効になった connect_client_ = cn; delay_client_ = 60; } if(delay_client_ > 0) { --delay_client_; if(delay_client_ == 0) { auto ip = root_menu_.get_target_ip(); if(!ip.empty() && ip_ != ip) { ip_ = ip; client_.start(ip_, 23); start_client_ = true; } } } } /// io_service_.run(); #if 0 #if 0 // Drag & Drop されたファイル gl::core& core = gl::core::get_instance(); int id = core.get_recv_files_id(); if(drop_file_id_ != id) { drop_file_id_ = id; const utils::strings& ss = core.get_recv_files_path(); if(!ss.empty()) { std::string path = ss[0]; if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) { load_ctx_->get_local_param().select_file_func_(path); } } } #endif #endif wd.update(); } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() { director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void destroy() { } }; } <|endoftext|>
<commit_before>// // SettingsMVC.cpp // MultitouchPadOsc is released under the MIT License. // // Copyright (c) 2011 - 2012, Paul Vollmer http://www.wrong-entertainment.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "SettingsMVC.h" SettingsMVC::SettingsMVC(){} void SettingsMVC::init(ofTrueTypeFont font) { checkboxOscArray.init(font, "OSC array xysa", FONT_POSITION_X, 160); checkboxFrame.init(font, "Frame active", FONT_POSITION_X, 180); //checkboxTimestamp.init(vera, "timestamp active", 60, 170, defXmlPadTimestamp); checkboxPosition.init(font, "X-, Y-Position active", FONT_POSITION_X, 200); //checkboxVelocity.init(vera, "x-, y-velocity active", 60, 200, defXmlPadVelocity); //checkboxMaxis.init(vera, "minor-, major-axis active", 60, 215, defXmlPadMaxis); checkboxSize.init(font, "Size active", FONT_POSITION_X, 220); checkboxAngle.init(font, "Angle active", FONT_POSITION_X, 240); } void SettingsMVC::getXml(ofxXmlDefaultSettings xml) { /* OSC variables */ oscHost = xml.getAttribute("osc", "host", "127.0.0.1", 0); oscPort = xml.getAttribute("osc", "port", 12345, 0); /* Trackpad variables */ oscTouchpadDevicename = xml.getValue("pad:devicename", "mtpadosc"); checkboxOscArray.status = xml.getValue("pad:array", false, 0); //oscArrayActive = xml.getValue("pad:array", false, 0); checkboxFrame.status = xml.getValue("pad:frame", false, 0); //checkboxTimestamp.status = xml.getValue("pad:timestamp", false, 0); checkboxPosition.status = xml.getValue("pad:position", false, 0); //checkboxVelocity.status = xml.getValue("pad:velocity", false, 0); checkboxSize.status = xml.getValue("pad:size", false, 0); //checkboxMaxis.status = xml.getValue("pad:maxis", false, 0); checkboxAngle.status = xml.getValue("pad:angle", false, 0); } void SettingsMVC::addXml(ofxXmlDefaultSettings xml) { /* OSC variables */ oscHost = "127.0.0.1"; oscPort = 12345; xml.addAttribute("osc", "host", oscHost, 0); xml.addAttribute("osc", "post", oscPort, 0); /* Trackpad variables */ oscTouchpadDevicename = "mtpad"; checkboxOscArray.status = false; checkboxFrame.status = false; //checkboxTimestamp.status = false; checkboxPosition.status = true; //checkboxVelocity.status = false; checkboxSize.status = true; //checkboxMaxis.status = false; checkboxAngle.status = true; xml.addTag("pad"); xml.pushTag("pad", 0); xml.addValue("devicename", oscTouchpadDevicename); xml.addValue("array", checkboxOscArray.status); xml.addValue("frame", checkboxFrame.status); //xml.addValue("timestamp", checkboxTimestamp.status); xml.addValue("position", checkboxPosition.status); //xml.addValue("velocity", checkboxVelocity.status); xml.addValue("size", checkboxSize.status); //xml.addValue("maxis", checkboxMaxis.status); xml.addValue("angle", checkboxAngle.status); xml.popTag(); } void SettingsMVC::setXml(ofxXmlDefaultSettings xml) { xml.pushRoot(); xml.setAttribute("osc", "host", oscHost, 0); xml.setAttribute("osc", "port", oscPort, 0); xml.setValue("pad:devicename", oscTouchpadDevicename, 0); xml.setValue("pad:array", checkboxOscArray.status, 0); xml.setValue("pad:frame", checkboxFrame.status, 0); //xml.setValue("pad:timestamp", checkboxTimestamp.status, 0); xml.setValue("pad:position", checkboxPosition.status, 0); //xml.setValue("pad:velocity", checkboxVelocity.status, 0); xml.setValue("pad:size", checkboxSize.status, 0); //xml.setValue("pad:maxis", checkboxMaxis.status, 0); xml.setValue("pad:angle", checkboxAngle.status, 0); xml.popRoot(); } void SettingsMVC::log(){ ofLog() << "XML: osc:host = " << oscHost; ofLog() << "XML: osc:port = " << oscPort; ofLog() << "pad:devicename = " << oscTouchpadDevicename; ofLog() << "pad:array = " << checkboxOscArray.status; ofLog() << "pad:frame = " << checkboxFrame.status; //ofLog() << "pad:timestamp = " << checkboxTimestamp.status; ofLog() << "pad:position = " << checkboxPosition.status; //ofLog() << "pad:velocity = " << checkboxVelocity.status; ofLog() << "pad:size = " << checkboxSize.status; //ofLog() << "pad:maxis = " << checkboxMaxis.status; ofLog() << "pad:angle = " << checkboxAngle.status; } void SettingsMVC::draw(ofTrueTypeFont font, ofxMultiTouchPad & pad) { /* ground */ ofEnableAlphaBlending(); ofSetColor(0, 150); ofFill(); ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40); ofDisableAlphaBlending(); ofSetColor(COLOR_LIGHT_GREY); ofFill(); /* Osc Main Settings */ font.drawString("OSC Main Settings", FONT_POSITION_X, 50); ofLine(FONT_POSITION_X, 60, ofGetWidth()-FONT_POSITION_X, 60); // Host: xxx.xxx.xxx.xxx Port: xxxx, Devicename font.drawString("Host: ", FONT_POSITION_X, 80); font.drawString("Port: ", 190, 80); font.drawString("Devicename: ", FONT_POSITION_X, 100); /* OSC Message Settings */ font.drawString("OSC Message Settings", FONT_POSITION_X, 140); ofLine(FONT_POSITION_X, 150, ofGetWidth()-FONT_POSITION_X, 150); checkboxOscArray.display(); checkboxFrame.display(); //cbTimestamp.display(); checkboxPosition.display(); //cbVelocity.display(); //cbMaxis.display(); checkboxSize.display(); checkboxAngle.display(); // shortcuts font.drawString("'cmd a'", 190, 170); font.drawString("'cmd s'", 190, 190); font.drawString("'cmd d'", 190, 210); font.drawString("'cmd f'", 190, 230); font.drawString("'cmd g'", 190, 250); /* Settings information */ font.drawString("Settings Information", FONT_POSITION_X, 290); ofLine(FONT_POSITION_X, 300, ofGetWidth()-FONT_POSITION_X, 300); font.drawString("Number of Touchpoints: "+ofToString(pad.getTouchCount()), 15, 320); font.drawString("Number of Devices: "+ofToString(pad.getNumDevices()), 15, 340); font.drawString("To open the settings xml, press key 'cmd x'", FONT_POSITION_X, 380); } void SettingsMVC::mousePressed(int x, int y) { cout << "ViewerSettings mousePressed()"; /* Check boxes */ checkboxOscArray.pressed(x, y); checkboxFrame.pressed(x, y); //cbTimestamp.pressed(x, y); checkboxPosition.pressed(x, y); //cbVelocity.pressed(x, y); //cbMaxis.pressed(x, y); checkboxSize.pressed(x, y); checkboxAngle.pressed(x, y); } void SettingsMVC::keyPressed(int key, bool cmdKeyPressed) { if (cmdKeyPressed == true) { switch (key) { /* OSC array */ case 'a': checkboxOscArray.status = !checkboxOscArray.status; break; /* OSC frame */ case 's': checkboxFrame.status = !checkboxFrame.status; // TODO: //console.addString("Shortcut padFrame: " + ofToString(xmlPadFrame), true); break; /* OSC timestamp */ /*case '3': if (settings.padTimestamp == 0) { settings.padTimestamp = 1; } else { settings.padTimestamp = 0; } cbTimestamp.status = settings.padTimestamp; cout << "Shortcut padTimestamp: " << settings.padTimestamp << endl; break;*/ /* OSC position */ case 'd': checkboxPosition.status = !checkboxPosition.status; // TODO: //console.addString("Shortcut padPosition: " + ofToString(xmlPadPosition), true); break; /* OSC velocity */ /*case '5': if (settings.padVelocity == 0) { settings.padVelocity = 1; } else { settings.padVelocity = 0; } cbVelocity.status = settings.padVelocity; cout << "Shortcut padVelocity: " << settings.padVelocity << endl; break;*/ /* OSC maxis */ /*case '4': if (settings.padMaxis == 0) { settings.padMaxis = 1; } else { settings.padMaxis = 0; } cbMaxis.status = settings.padMaxis; cout << "Shortcut padMaxis: " << settings.padMaxis << endl; break;*/ /* OSC maxis */ case 'f': checkboxSize.status = !checkboxSize.status; // TODO: //console.addString("Shortcut padSize: " + ofToString(xmlPadSize), true); break; /* OSC angle */ case 'g': checkboxAngle.status = !checkboxAngle.status; // TODO: //console.addString("Shortcut padAngle: " + ofToString(xmlPadAngle), true); break; default: break; } } // End if cmdKeyPressed } <commit_msg>uncomment console out at mousePressed<commit_after>// // SettingsMVC.cpp // MultitouchPadOsc is released under the MIT License. // // Copyright (c) 2011 - 2012, Paul Vollmer http://www.wrong-entertainment.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "SettingsMVC.h" SettingsMVC::SettingsMVC(){} void SettingsMVC::init(ofTrueTypeFont font) { checkboxOscArray.init(font, "OSC array xysa", FONT_POSITION_X, 160); checkboxFrame.init(font, "Frame active", FONT_POSITION_X, 180); //checkboxTimestamp.init(vera, "timestamp active", 60, 170, defXmlPadTimestamp); checkboxPosition.init(font, "X-, Y-Position active", FONT_POSITION_X, 200); //checkboxVelocity.init(vera, "x-, y-velocity active", 60, 200, defXmlPadVelocity); //checkboxMaxis.init(vera, "minor-, major-axis active", 60, 215, defXmlPadMaxis); checkboxSize.init(font, "Size active", FONT_POSITION_X, 220); checkboxAngle.init(font, "Angle active", FONT_POSITION_X, 240); } void SettingsMVC::getXml(ofxXmlDefaultSettings xml) { /* OSC variables */ oscHost = xml.getAttribute("osc", "host", "127.0.0.1", 0); oscPort = xml.getAttribute("osc", "port", 12345, 0); /* Trackpad variables */ oscTouchpadDevicename = xml.getValue("pad:devicename", "mtpadosc"); checkboxOscArray.status = xml.getValue("pad:array", false, 0); //oscArrayActive = xml.getValue("pad:array", false, 0); checkboxFrame.status = xml.getValue("pad:frame", false, 0); //checkboxTimestamp.status = xml.getValue("pad:timestamp", false, 0); checkboxPosition.status = xml.getValue("pad:position", false, 0); //checkboxVelocity.status = xml.getValue("pad:velocity", false, 0); checkboxSize.status = xml.getValue("pad:size", false, 0); //checkboxMaxis.status = xml.getValue("pad:maxis", false, 0); checkboxAngle.status = xml.getValue("pad:angle", false, 0); } void SettingsMVC::addXml(ofxXmlDefaultSettings xml) { /* OSC variables */ oscHost = "127.0.0.1"; oscPort = 12345; xml.addAttribute("osc", "host", oscHost, 0); xml.addAttribute("osc", "post", oscPort, 0); /* Trackpad variables */ oscTouchpadDevicename = "mtpad"; checkboxOscArray.status = false; checkboxFrame.status = false; //checkboxTimestamp.status = false; checkboxPosition.status = true; //checkboxVelocity.status = false; checkboxSize.status = true; //checkboxMaxis.status = false; checkboxAngle.status = true; xml.addTag("pad"); xml.pushTag("pad", 0); xml.addValue("devicename", oscTouchpadDevicename); xml.addValue("array", checkboxOscArray.status); xml.addValue("frame", checkboxFrame.status); //xml.addValue("timestamp", checkboxTimestamp.status); xml.addValue("position", checkboxPosition.status); //xml.addValue("velocity", checkboxVelocity.status); xml.addValue("size", checkboxSize.status); //xml.addValue("maxis", checkboxMaxis.status); xml.addValue("angle", checkboxAngle.status); xml.popTag(); } void SettingsMVC::setXml(ofxXmlDefaultSettings xml) { xml.pushRoot(); xml.setAttribute("osc", "host", oscHost, 0); xml.setAttribute("osc", "port", oscPort, 0); xml.setValue("pad:devicename", oscTouchpadDevicename, 0); xml.setValue("pad:array", checkboxOscArray.status, 0); xml.setValue("pad:frame", checkboxFrame.status, 0); //xml.setValue("pad:timestamp", checkboxTimestamp.status, 0); xml.setValue("pad:position", checkboxPosition.status, 0); //xml.setValue("pad:velocity", checkboxVelocity.status, 0); xml.setValue("pad:size", checkboxSize.status, 0); //xml.setValue("pad:maxis", checkboxMaxis.status, 0); xml.setValue("pad:angle", checkboxAngle.status, 0); xml.popRoot(); } void SettingsMVC::log(){ ofLog() << "XML: osc:host = " << oscHost; ofLog() << "XML: osc:port = " << oscPort; ofLog() << "pad:devicename = " << oscTouchpadDevicename; ofLog() << "pad:array = " << checkboxOscArray.status; ofLog() << "pad:frame = " << checkboxFrame.status; //ofLog() << "pad:timestamp = " << checkboxTimestamp.status; ofLog() << "pad:position = " << checkboxPosition.status; //ofLog() << "pad:velocity = " << checkboxVelocity.status; ofLog() << "pad:size = " << checkboxSize.status; //ofLog() << "pad:maxis = " << checkboxMaxis.status; ofLog() << "pad:angle = " << checkboxAngle.status; } void SettingsMVC::draw(ofTrueTypeFont font, ofxMultiTouchPad & pad) { /* ground */ ofEnableAlphaBlending(); ofSetColor(0, 150); ofFill(); ofRect(10, 30, ofGetWidth()-20, ofGetHeight()-40); ofDisableAlphaBlending(); ofSetColor(COLOR_LIGHT_GREY); ofFill(); /* Osc Main Settings */ font.drawString("OSC Main Settings", FONT_POSITION_X, 50); ofLine(FONT_POSITION_X, 60, ofGetWidth()-FONT_POSITION_X, 60); // Host: xxx.xxx.xxx.xxx Port: xxxx, Devicename font.drawString("Host: ", FONT_POSITION_X, 80); font.drawString("Port: ", 190, 80); font.drawString("Devicename: ", FONT_POSITION_X, 100); /* OSC Message Settings */ font.drawString("OSC Message Settings", FONT_POSITION_X, 140); ofLine(FONT_POSITION_X, 150, ofGetWidth()-FONT_POSITION_X, 150); checkboxOscArray.display(); checkboxFrame.display(); //cbTimestamp.display(); checkboxPosition.display(); //cbVelocity.display(); //cbMaxis.display(); checkboxSize.display(); checkboxAngle.display(); // shortcuts font.drawString("'cmd a'", 190, 170); font.drawString("'cmd s'", 190, 190); font.drawString("'cmd d'", 190, 210); font.drawString("'cmd f'", 190, 230); font.drawString("'cmd g'", 190, 250); /* Settings information */ font.drawString("Settings Information", FONT_POSITION_X, 290); ofLine(FONT_POSITION_X, 300, ofGetWidth()-FONT_POSITION_X, 300); font.drawString("Number of Touchpoints: "+ofToString(pad.getTouchCount()), 15, 320); font.drawString("Number of Devices: "+ofToString(pad.getNumDevices()), 15, 340); font.drawString("To open the settings xml, press key 'cmd x'", FONT_POSITION_X, 380); } void SettingsMVC::mousePressed(int x, int y) { //cout << "ViewerSettings mousePressed()" << endl; /* Check boxes */ checkboxOscArray.pressed(x, y); checkboxFrame.pressed(x, y); //cbTimestamp.pressed(x, y); checkboxPosition.pressed(x, y); //cbVelocity.pressed(x, y); //cbMaxis.pressed(x, y); checkboxSize.pressed(x, y); checkboxAngle.pressed(x, y); } void SettingsMVC::keyPressed(int key, bool cmdKeyPressed) { if (cmdKeyPressed == true) { switch (key) { /* OSC array */ case 'a': checkboxOscArray.status = !checkboxOscArray.status; break; /* OSC frame */ case 's': checkboxFrame.status = !checkboxFrame.status; // TODO: //console.addString("Shortcut padFrame: " + ofToString(xmlPadFrame), true); break; /* OSC timestamp */ /*case '3': if (settings.padTimestamp == 0) { settings.padTimestamp = 1; } else { settings.padTimestamp = 0; } cbTimestamp.status = settings.padTimestamp; cout << "Shortcut padTimestamp: " << settings.padTimestamp << endl; break;*/ /* OSC position */ case 'd': checkboxPosition.status = !checkboxPosition.status; // TODO: //console.addString("Shortcut padPosition: " + ofToString(xmlPadPosition), true); break; /* OSC velocity */ /*case '5': if (settings.padVelocity == 0) { settings.padVelocity = 1; } else { settings.padVelocity = 0; } cbVelocity.status = settings.padVelocity; cout << "Shortcut padVelocity: " << settings.padVelocity << endl; break;*/ /* OSC maxis */ /*case '4': if (settings.padMaxis == 0) { settings.padMaxis = 1; } else { settings.padMaxis = 0; } cbMaxis.status = settings.padMaxis; cout << "Shortcut padMaxis: " << settings.padMaxis << endl; break;*/ /* OSC maxis */ case 'f': checkboxSize.status = !checkboxSize.status; // TODO: //console.addString("Shortcut padSize: " + ofToString(xmlPadSize), true); break; /* OSC angle */ case 'g': checkboxAngle.status = !checkboxAngle.status; // TODO: //console.addString("Shortcut padAngle: " + ofToString(xmlPadAngle), true); break; default: break; } } // End if cmdKeyPressed } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CoreDelegateImpl.h" #include <GameCore/Core.h> #include <GameCore/Render/IRenderer.h> #include <GameCore/Render/HardwareBufferManagerBase.h> #include <GameCore/Input/inputsystem.h> #include <GameCore/Render/OpenGL/GlUitlities.h> #include <GameCore/Render/TextureManager.h> // for test #include <GL/glew.h> #include <GL/GL.h> #include <GL/GLU.h> #define BUFFER_OFFSET(i) ((char *)NULL + (i)) #include <time.h> #include <Math/Matrix4.h> using namespace SDK; #pragma comment(lib, "opengl32.lib") #if defined(_DEBUG) # pragma comment(lib, "glew32d.lib") #else # pragma comment(lib, "glew32.lib") #endif #include <GameCore/Applications/ApplicationBase.h> #include <GameCore/Render/MeshSystem.h> #include <GameCore/Render/MaterialManager.h> #include <GameCore/Systems/TransformationsSystem.h> #include <GameCore/Render/ShaderSystem.h> #include <GameCore/EntityManager.h> #include <GameCore/Render/LightsController.h> #include <GameCore/Render/ScopedLightSwitch.h> #include <GameCore/PropertyElement.h> #include <GameCore/Resources/ResourceManager.h> #include <GameCore/Render/ShaderCompiler.h> namespace Game { EntityHandle entity_handler; void CoreDelegateImpl::LoadModel() { //E:\Git_Projects\SupportSDK\Samples\Resources\Models\Box.obj //loaded_mesh = Render::g_mesh_system.Load("Resources\\Models\\Box.obj", Render::BufferUsageFormat::Static, Render::BufferUsageFormat::Static); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); loaded_mesh = p_load_manager->GetHandleToResource<Render::Mesh>("Nanosuit"); auto mesh_handler = Render::g_mesh_system.CreateInstance(loaded_mesh); auto trans_handler = g_transforms_system.CreateInstance(); auto p_transform = g_transforms_system.GetInstance(trans_handler); entity_handler = g_entity_manager.CreateEntity(); g_entity_manager.AddComponent<Render::MeshComponent>(entity_handler, mesh_handler); g_entity_manager.AddComponent<Transform>(entity_handler, trans_handler); // test getting of entity and component auto entity = g_entity_manager.GetEntity(entity_handler); Render::MaterialHandle material_handle = p_load_manager->GetHandleToResource<Render::Material>("Nanosuit_material"); auto p_material = Render::g_material_mgr.AccessMaterial(material_handle); Render::g_mesh_system.AddMaterialTo(mesh_handler, material_handle); } void CoreDelegateImpl::CreateMesh() { auto p_renderer = Core::GetRenderer(); auto p_mgr = p_renderer->GetHardwareBufferMgr(); } void CoreDelegateImpl::OnCreate() { InputSystem::Instance().AddSubscriber(&m_input_subs); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); p_load_manager->LoadResourceSet("..\\..\\Resources\\ResourceSets\\render_testing.res"); LoadModel(); CreateMesh(); auto& world = Core::GetApplication()->GetWorld(); auto& camera = world.GetCamera(); camera.LookAt({ 0,-5,-15 }, { -10,-2,0 }); world.GetFrustum().SetFOV(60 * Math::DEG2RAD); } void CoreDelegateImpl::OnTerminate() { InputSystem::Instance().RemoveSubscriber(&m_input_subs); auto p_renderer = Core::GetRenderer(); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].indices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].indices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].vertices); g_entity_manager.RemoveEntity(entity_handler); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); p_load_manager->UnloadSet(p_load_manager->GetHandleToSet("render_testing")); } void CoreDelegateImpl::Update(float i_elapsed_time) { } void CoreDelegateImpl::Draw() { } } // Game<commit_msg>[Samples] Maintenance<commit_after>#include "stdafx.h" #include "CoreDelegateImpl.h" #include <GameCore/Core.h> #include <GameCore/Render/IRenderer.h> #include <GameCore/Render/HardwareBufferManagerBase.h> #include <GameCore/Input/inputsystem.h> #include <GameCore/Render/OpenGL/GlUitlities.h> #include <GameCore/Render/TextureManager.h> // for test #include <GL/glew.h> #include <GL/GL.h> #include <GL/GLU.h> #define BUFFER_OFFSET(i) ((char *)NULL + (i)) #include <time.h> #include <Math/Matrix4.h> using namespace SDK; #pragma comment(lib, "opengl32.lib") #if defined(_DEBUG) # pragma comment(lib, "glew32d.lib") #else # pragma comment(lib, "glew32.lib") #endif #include <GameCore/Applications/ApplicationBase.h> #include <GameCore/Render/MeshSystem.h> #include <GameCore/Render/MaterialManager.h> #include <GameCore/Systems/TransformationsSystem.h> #include <GameCore/Render/ShaderSystem.h> #include <GameCore/EntityManager.h> #include <GameCore/Render/LightsController.h> #include <GameCore/Render/ScopedLightSwitch.h> #include <GameCore/PropertyElement.h> #include <GameCore/Resources/ResourceManager.h> #include <GameCore/Render/ShaderCompiler.h> namespace Game { EntityHandle entity_handler; void CoreDelegateImpl::LoadModel() { //E:\Git_Projects\SupportSDK\Samples\Resources\Models\Box.obj //loaded_mesh = Render::g_mesh_system.Load("Resources\\Models\\Box.obj", Render::BufferUsageFormat::Static, Render::BufferUsageFormat::Static); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); loaded_mesh = p_load_manager->GetHandleToResource<Render::Mesh>("SimpleBox"); auto mesh_handler = Render::g_mesh_system.CreateInstance(loaded_mesh); auto trans_handler = g_transforms_system.CreateInstance(); auto p_transform = g_transforms_system.GetInstance(trans_handler); entity_handler = g_entity_manager.CreateEntity(); g_entity_manager.AddComponent<Render::MeshComponent>(entity_handler, mesh_handler); g_entity_manager.AddComponent<Transform>(entity_handler, trans_handler); // test getting of entity and component auto entity = g_entity_manager.GetEntity(entity_handler); Render::MaterialHandle material_handle = p_load_manager->GetHandleToResource<Render::Material>("Sample_material"); auto p_material = Render::g_material_mgr.AccessMaterial(material_handle); Render::g_mesh_system.AddMaterialTo(mesh_handler, material_handle); } void CoreDelegateImpl::CreateMesh() { auto p_renderer = Core::GetRenderer(); auto p_mgr = p_renderer->GetHardwareBufferMgr(); } void CoreDelegateImpl::OnCreate() { InputSystem::Instance().AddSubscriber(&m_input_subs); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); p_load_manager->LoadResourceSet("..\\..\\Resources\\ResourceSets\\render_testing.res"); LoadModel(); CreateMesh(); auto& world = Core::GetApplication()->GetWorld(); auto& camera = world.GetCamera(); camera.LookAt({ 0,-5,-15 }, { -10,-2,0 }); world.GetFrustum().SetFOV(60 * Math::DEG2RAD); } void CoreDelegateImpl::OnTerminate() { InputSystem::Instance().RemoveSubscriber(&m_input_subs); auto p_renderer = Core::GetRenderer(); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].indices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[0].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].vertices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].indices); p_renderer->GetHardwareBufferMgr()->DestroyBuffer(batch[1].vertices); g_entity_manager.RemoveEntity(entity_handler); auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>(); p_load_manager->UnloadSet(p_load_manager->GetHandleToSet("render_testing")); } void CoreDelegateImpl::Update(float i_elapsed_time) { } void CoreDelegateImpl::Draw() { } } // Game<|endoftext|>
<commit_before>#include <ontology/olink.h> /******************************************************************************** * Print out the link information ********************************************************************************/ void Olink::printLink(){ if (valued){ cout << "\t\tLink Name: " << name << " Nodes (" << start_node << "," << end_node << ") V: " << value << "\n"; } else { cout << "\t\tLink Name: " << name << " Nodes (" << start_node << "," << end_node << ")\n"; } } /******************************************************************************** * Constructor function with no info ********************************************************************************/ Olink::Olink(){ valued = false; } /******************************************************************************** * Constructor function with all info ********************************************************************************/ Olink::Olink(string n_name, int node1, int node2){ name = n_name; start_node = node1; end_node = node2; valued = false; } /******************************************************************************** * Set the name of the link ********************************************************************************/ void Olink::setName(string n_name){ name = n_name; } /******************************************************************************** * Set the starting node of the link ********************************************************************************/ void Olink::setStart(int node_id){ start_node = node_id; } /******************************************************************************** * Set the ending node of the link ********************************************************************************/ void Olink::setEnd(int node_id){ end_node = node_id; } /******************************************************************************** * Set all the information of the node ********************************************************************************/ void Olink::setInfo(string n_name, int node1, int node2){ name = n_name; start_node = node1; end_node = node2; } /******************************************************************************** * Set all the information of the node ********************************************************************************/ void Olink::setInfo2(string n_name, int node2){ name = n_name; end_node = node2; } /******************************************************************************** * Set the value of the node, and set the valued parameter to be true ********************************************************************************/ void Olink::setValue(int v){ value = v; valued = true; } /******************************************************************************** * Return the id of the start node of the link ********************************************************************************/ int Olink::getStart(){ return start_node; } /******************************************************************************** * Return the id of the end node of the link ********************************************************************************/ int Olink::getEnd(){ return end_node; } /******************************************************************************** * Return the name of the link ********************************************************************************/ string Olink::getName(){ return name; } /******************************************************************************** * Does the link have a value associated with it? ********************************************************************************/ bool Olink::isValued(){ return valued; } /******************************************************************************** * Return the value of the link ********************************************************************************/ int Olink::getValue(){ return value; } <commit_msg>Refactored olink.cpp<commit_after>#include <ontology/olink.h> /******************************************************************************** * Print out the link information ********************************************************************************/ void Olink::printLink() const { if( _is_valued ) { std::cerr << "\t\tLink Name: " << _name << " Nodes (" << _start_node << "," << _end_node << ") V: " << _value << std::endl; } else { std::cerr << "\t\tLink Name: " << _name << " Nodes (" << _start_node << "," << _end_node << ")" << std::endl; } } /******************************************************************************** * Constructor function with no info ********************************************************************************/ Olink::Olink() { _is_valued = false; } /******************************************************************************** * Constructor function with all info ********************************************************************************/ Olink::Olink( std::string const & name, int const & node1, int const & node2 ) { _name = name; _start_node = node1; _end_node = node2; _is_valued = false; } /******************************************************************************** * Set the name of the link ********************************************************************************/ void Olink::setName( std::string const & name ) { _name = name; } /******************************************************************************** * Set the starting node of the link ********************************************************************************/ void Olink::setStart( int const & node_id ) { _start_node = node_id; } /******************************************************************************** * Set the ending node of the link ********************************************************************************/ void Olink::setEnd( int const & node_id ) { _end_node = node_id; } /******************************************************************************** * Set all the information of the node ********************************************************************************/ void Olink::setInfo( std::string const & name, int const & node1, int const & node2 ) { _name = name; _start_node = node1; _end_node = node2; } /******************************************************************************** * Set all the information of the node ********************************************************************************/ void Olink::setInfo2( std::string const & name, int const & node2 ) { _name = name; _end_node = node2; } /******************************************************************************** * Set the value of the node, and set the valued parameter to be true ********************************************************************************/ void Olink::setValue( int const & value ) { _value = value; _is_valued = true; } /******************************************************************************** * Return the id of the start node of the link ********************************************************************************/ int const & Olink::getStart() const { return _start_node; } /******************************************************************************** * Return the id of the end node of the link ********************************************************************************/ int const & Olink::getEnd() const { return _end_node; } /******************************************************************************** * Return the name of the link ********************************************************************************/ std::string const & Olink::getName() const { return _name; } /******************************************************************************** * Does the link have a value associated with it? ********************************************************************************/ bool const & Olink::isValued() const { return _is_valued; } /******************************************************************************** * Return the value of the link ********************************************************************************/ int const & Olink::getValue() const { return _value; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 * Hugo Stefan Kaus Puhlmann <hugopuhlmann@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "TableMatrix.h" #include "Table.h" namespace rty { TableMatrix::TableMatrix(int l, int c) : rows(l), cols(c) { mat = new Table*[l]; for(int i = 0; i < l; i++) mat[i] = new Table[c]; ngrupos = 0; int table_num = 0; for(int i = 0; i < l; i++) { for(int j = 0; j < c; j++) mat[i][j].num = table_num++; } } htl::vector<Table*> TableMatrix::getTableGroup(unsigned int s) { htl::vector<Table*> vec; vec.reserve(s + s%Table::MAX_OCCUPANTS / Table::MAX_OCCUPANTS); if(s == 0) return vec; if(s <= 2) { for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(mat[i][j].free == mat[i][j].MAX_OCCUPANTS) { vec.push_back(&mat[i][j]); break; } } if(!vec.empty()) break; } } if(s > 2) { for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { vec = findAround(i, j, s); if(!vec.empty()) break; } if(!vec.empty()) break; } } for(htl::vector<Table*>::iterator it = vec.begin(); it != vec.end(); it++) { (*it)->free -= (*it)->MAX_OCCUPANTS - s%2; s -= (*it)->MAX_OCCUPANTS - s%2; } return vec; } htl::vector<Table*> TableMatrix::findAround(int row, int column, int n) { htl::vector<Table*> tab; for (int i = 0; i + row < rows; ++i) { if(mat[i + row][column].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[i + row][column]); if(int(tab.size()) >= n/Table::MAX_OCCUPANTS) return tab; } } for (int i = -1; i + row > 0; --i) { if(mat[i + row][column].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[i + row][column]); if(int(tab.size()) >= n/Table::MAX_OCCUPANTS) return tab; } else break; } for (int i = 1; i + column < cols; ++i) { if(mat[row][column + i].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[row][column + i]); if(int(tab.size()) >= n/Table::MAX_OCCUPANTS) return tab; } else break; } for (int i = -1; i + column > 0; i--) { if(mat[row][column + i].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[row][column + i]); if(int(tab.size()) >= n/Table::MAX_OCCUPANTS) return tab; } else break; } tab.clear(); return tab; } }<commit_msg>fixing a problem with odd numer of clients<commit_after>/* * Copyright (c) 2010 * Hugo Stefan Kaus Puhlmann <hugopuhlmann@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "TableMatrix.h" #include "Table.h" namespace rty { TableMatrix::TableMatrix(int l, int c) : rows(l), cols(c) { mat = new Table*[l]; for(int i = 0; i < l; i++) mat[i] = new Table[c]; ngrupos = 0; int table_num = 0; for(int i = 0; i < l; i++) { for(int j = 0; j < c; j++) mat[i][j].num = table_num++; } } htl::vector<Table*> TableMatrix::getTableGroup(unsigned int s) { htl::vector<Table*> vec; vec.reserve(s + s%Table::MAX_OCCUPANTS / Table::MAX_OCCUPANTS); if(s == 0) return vec; if(s <= 2) { for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(mat[i][j].free == mat[i][j].MAX_OCCUPANTS) { vec.push_back(&mat[i][j]); break; } } if(!vec.empty()) break; } } if(s > 2) { for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { vec = findAround(i, j, s); if(!vec.empty()) break; } if(!vec.empty()) break; } } for(htl::vector<Table*>::iterator it = vec.begin(); it != vec.end(); it++) { (*it)->free -= (*it)->MAX_OCCUPANTS - s%2; s -= (*it)->MAX_OCCUPANTS - s%2; } return vec; } htl::vector<Table*> TableMatrix::findAround(int row, int column, int n) { htl::vector<Table*> tab; for (int i = 0; i + row < rows; ++i) { if(mat[i + row][column].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[i + row][column]); if(int(tab.size()) >= (n + n%Table::MAX_OCCUPANTS)/Table::MAX_OCCUPANTS) return tab; } } for (int i = -1; i + row > 0; --i) { if(mat[i + row][column].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[i + row][column]); if(int(tab.size()) >= (n + n%Table::MAX_OCCUPANTS)/Table::MAX_OCCUPANTS) return tab; } else break; } for (int i = 1; i + column < cols; ++i) { if(mat[row][column + i].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[row][column + i]); if(int(tab.size()) >= (n + n%Table::MAX_OCCUPANTS)/Table::MAX_OCCUPANTS) return tab; } else break; } for (int i = -1; i + column > 0; i--) { if(mat[row][column + i].free == Table::MAX_OCCUPANTS) { tab.push_back(&mat[row][column + i]); if(int(tab.size()) >= (n + n%Table::MAX_OCCUPANTS)/Table::MAX_OCCUPANTS) return tab; } else break; } tab.clear(); return tab; } }<|endoftext|>
<commit_before>#include <sstream> #include <fcntl.h> #include "Array.h" #include "ObjectIO.h" #include "VM.h" namespace magpie { using std::ostream; gc<BufferObject> asBuffer(gc<Object> obj) { return static_cast<BufferObject*>(&(*obj)); } gc<FileObject> asFile(gc<Object> obj) { return static_cast<FileObject*>(&(*obj)); } gc<StreamObject> asStream(gc<Object> obj) { return static_cast<StreamObject*>(&(*obj)); } FSTask::FSTask(gc<Fiber> fiber) : Task(fiber) { fs_.data = this; } FSTask::~FSTask() { uv_fs_req_cleanup(&fs_); } void FSTask::kill() { uv_cancel(reinterpret_cast<uv_req_t*>(&fs_)); } FSReadTask::FSReadTask(gc<Fiber> fiber, int bufferSize) : FSTask(fiber) { buffer_ = BufferObject::create(bufferSize); } void FSReadTask::reach() { FSTask::reach(); buffer_.reach(); } HandleTask::HandleTask(gc<Fiber> fiber, uv_handle_t* handle) : Task(fiber), handle_(handle) { handle_->data = this; } HandleTask::~HandleTask() { delete handle_; } void HandleTask::kill() { uv_unref(handle_); delete handle_; handle_ = NULL; } gc<BufferObject> BufferObject::create(int count) { // Allocate enough memory for the buffer and its data. void* mem = Memory::allocate(sizeof(BufferObject) + sizeof(unsigned char) * (count - 1)); // Construct it by calling global placement new. gc<BufferObject> buffer = ::new(mem) BufferObject(count); // Fill with zero. for (int i = 0; i < count; i++) { buffer->bytes_[i] = 0; } return buffer; } gc<ClassObject> BufferObject::getClass(VM& vm) const { return vm.bufferClass(); } gc<String> BufferObject::toString() const { if (count_ == 0) return String::create("[buffer]"); gc<String> result = String::create("[buffer"); if (count_ <= 8) { // Small buffer, so show the whole contents. for (int i = 0; i < count_; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } } else { // Long buffer, so just shows the first and last few octets. for (int i = 0; i < 4; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } result = String::format("%s ...", result->cString()); for (int i = count_ - 4; i < count_; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } } return String::format("%s]", result->cString()); } void BufferObject::truncate(int count) { ASSERT(count <= count_, "Cannot truncate to a larger size."); count_ = count; } static void openFileCallback(uv_fs_t* handle) { // TODO(bob): Handle errors! Task* task = static_cast<Task*>(handle->data); // Note that the file descriptor is returned in [result] and not [file]. task->complete(new FileObject(handle->result)); } void FileObject::open(gc<Fiber> fiber, gc<String> path) { FSTask* task = new FSTask(fiber); // TODO(bob): Make this configurable. int flags = O_RDONLY; // TODO(bob): Make this configurable when creating a file. int mode = 0; uv_fs_open(task->loop(), task->request(), path->cString(), flags, mode, openFileCallback); } static void getSizeCallback(uv_fs_t* handle) { // TODO(bob): Handle errors! Task* task = static_cast<Task*>(handle->data); uv_statbuf_t* statbuf = static_cast<uv_statbuf_t*>(handle->ptr); task->complete(new IntObject(statbuf->st_size)); } void FileObject::getSize(gc<Fiber> fiber) { FSTask* task = new FSTask(fiber); uv_fs_fstat(task->loop(), task->request(), file_, getSizeCallback); } // TODO(bob): Stream-based code. Saving it for later. /* static uv_buf_t allocateCallback(uv_handle_t *handle, size_t suggested_size) { printf("Alloc %ld\n", suggested_size); // TODO(bob): Don't use malloc() here. return uv_buf_init((char*) malloc(suggested_size), suggested_size); } static void readCallback(uv_stream_t *stream, ssize_t nread, uv_buf_t buf) { // TODO(bob): Implement me! printf("Read %ld bytes\n", nread); } */ static void readBytesCallback(uv_fs_t *request) { // TODO(bob): Handle errors! FSReadTask* task = reinterpret_cast<FSReadTask*>(request->data); gc<Object> result = task->buffer(); if (request->result != 0) { // Trim the buffer to the actually read size. task->buffer()->truncate(request->result); } else { // If we read when at EOF, return done. result = task->fiber()->vm().getBuiltIn(BUILT_IN_DONE); } task->complete(result); } void FileObject::readBytes(gc<Fiber> fiber, int size) { FSReadTask* task = new FSReadTask(fiber, size); // TODO(bob): Check result. uv_fs_read(task->loop(), task->request(), file_, task->buffer()->data(), task->buffer()->count(), -1, readBytesCallback); // TODO(bob): Use this for the streaming methods: /* // TODO(bob): What if you call read on the same file multiple times? // Should the pipe be reused? // Get a pipe to the file. uv_pipe_t* pipe = tasks_.createPipe(fiber); uv_pipe_init(loop_, pipe, 0); uv_pipe_open(pipe, file->file()); // TODO(bob): Check result. uv_read_start(reinterpret_cast<uv_stream_t*>(pipe), allocateCallback, readCallback); */ } static void closeFileCallback(uv_fs_t* handle) { Task* task = static_cast<Task*>(handle->data); // Close returns nothing. task->complete(NULL); } void FileObject::close(gc<Fiber> fiber) { ASSERT(isOpen_, "IO library should not call close on a closed file."); // Mark the file closed immediately so other fibers can't try to use it. isOpen_ = false; FSTask* task = new FSTask(fiber); uv_fs_close(task->loop(), task->request(), file_, closeFileCallback); } gc<ClassObject> FileObject::getClass(VM& vm) const { return vm.fileClass(); } gc<String> FileObject::toString() const { // TODO(bob): Include some kind of ID or something here. return String::create("[file]"); } void FileObject::reach() { // TODO(bob): How should we handle file_ here? } gc<ClassObject> StreamObject::getClass(VM& vm) const { return vm.streamClass(); } gc<String> StreamObject::toString() const { // TODO(bob): Include some kind of ID or something here. return String::create("[stream]"); } } <commit_msg>Add TODO.<commit_after>#include <sstream> #include <fcntl.h> #include "Array.h" #include "ObjectIO.h" #include "VM.h" namespace magpie { using std::ostream; gc<BufferObject> asBuffer(gc<Object> obj) { return static_cast<BufferObject*>(&(*obj)); } gc<FileObject> asFile(gc<Object> obj) { return static_cast<FileObject*>(&(*obj)); } gc<StreamObject> asStream(gc<Object> obj) { return static_cast<StreamObject*>(&(*obj)); } FSTask::FSTask(gc<Fiber> fiber) : Task(fiber) { fs_.data = this; } FSTask::~FSTask() { uv_fs_req_cleanup(&fs_); } void FSTask::kill() { uv_cancel(reinterpret_cast<uv_req_t*>(&fs_)); } FSReadTask::FSReadTask(gc<Fiber> fiber, int bufferSize) : FSTask(fiber) { buffer_ = BufferObject::create(bufferSize); } void FSReadTask::reach() { FSTask::reach(); buffer_.reach(); } HandleTask::HandleTask(gc<Fiber> fiber, uv_handle_t* handle) : Task(fiber), handle_(handle) { handle_->data = this; } HandleTask::~HandleTask() { delete handle_; } void HandleTask::kill() { uv_unref(handle_); delete handle_; handle_ = NULL; } gc<BufferObject> BufferObject::create(int count) { // Allocate enough memory for the buffer and its data. void* mem = Memory::allocate(sizeof(BufferObject) + sizeof(unsigned char) * (count - 1)); // Construct it by calling global placement new. gc<BufferObject> buffer = ::new(mem) BufferObject(count); // Fill with zero. for (int i = 0; i < count; i++) { buffer->bytes_[i] = 0; } return buffer; } gc<ClassObject> BufferObject::getClass(VM& vm) const { return vm.bufferClass(); } gc<String> BufferObject::toString() const { if (count_ == 0) return String::create("[buffer]"); gc<String> result = String::create("[buffer"); if (count_ <= 8) { // Small buffer, so show the whole contents. for (int i = 0; i < count_; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } } else { // Long buffer, so just shows the first and last few octets. for (int i = 0; i < 4; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } result = String::format("%s ...", result->cString()); for (int i = count_ - 4; i < count_; i++) { result = String::format("%s %02x", result->cString(), bytes_[i]); } } return String::format("%s]", result->cString()); } void BufferObject::truncate(int count) { ASSERT(count <= count_, "Cannot truncate to a larger size."); count_ = count; } static void openFileCallback(uv_fs_t* handle) { // TODO(bob): Handle errors! Task* task = static_cast<Task*>(handle->data); // Note that the file descriptor is returned in [result] and not [file]. task->complete(new FileObject(handle->result)); } void FileObject::open(gc<Fiber> fiber, gc<String> path) { FSTask* task = new FSTask(fiber); // TODO(bob): Make this configurable. int flags = O_RDONLY; // TODO(bob): Make this configurable when creating a file. int mode = 0; uv_fs_open(task->loop(), task->request(), path->cString(), flags, mode, openFileCallback); } static void getSizeCallback(uv_fs_t* handle) { // TODO(bob): Handle errors! Task* task = static_cast<Task*>(handle->data); // TODO(bob): Use handle.statbuf after upgrading to latest libuv where // that's public. uv_statbuf_t* statbuf = static_cast<uv_statbuf_t*>(handle->ptr); task->complete(new IntObject(statbuf->st_size)); } void FileObject::getSize(gc<Fiber> fiber) { FSTask* task = new FSTask(fiber); uv_fs_fstat(task->loop(), task->request(), file_, getSizeCallback); } // TODO(bob): Stream-based code. Saving it for later. /* static uv_buf_t allocateCallback(uv_handle_t *handle, size_t suggested_size) { printf("Alloc %ld\n", suggested_size); // TODO(bob): Don't use malloc() here. return uv_buf_init((char*) malloc(suggested_size), suggested_size); } static void readCallback(uv_stream_t *stream, ssize_t nread, uv_buf_t buf) { // TODO(bob): Implement me! printf("Read %ld bytes\n", nread); } */ static void readBytesCallback(uv_fs_t *request) { // TODO(bob): Handle errors! FSReadTask* task = reinterpret_cast<FSReadTask*>(request->data); gc<Object> result = task->buffer(); if (request->result != 0) { // Trim the buffer to the actually read size. task->buffer()->truncate(request->result); } else { // If we read when at EOF, return done. result = task->fiber()->vm().getBuiltIn(BUILT_IN_DONE); } task->complete(result); } void FileObject::readBytes(gc<Fiber> fiber, int size) { FSReadTask* task = new FSReadTask(fiber, size); // TODO(bob): Check result. uv_fs_read(task->loop(), task->request(), file_, task->buffer()->data(), task->buffer()->count(), -1, readBytesCallback); // TODO(bob): Use this for the streaming methods: /* // TODO(bob): What if you call read on the same file multiple times? // Should the pipe be reused? // Get a pipe to the file. uv_pipe_t* pipe = tasks_.createPipe(fiber); uv_pipe_init(loop_, pipe, 0); uv_pipe_open(pipe, file->file()); // TODO(bob): Check result. uv_read_start(reinterpret_cast<uv_stream_t*>(pipe), allocateCallback, readCallback); */ } static void closeFileCallback(uv_fs_t* handle) { Task* task = static_cast<Task*>(handle->data); // Close returns nothing. task->complete(NULL); } void FileObject::close(gc<Fiber> fiber) { ASSERT(isOpen_, "IO library should not call close on a closed file."); // Mark the file closed immediately so other fibers can't try to use it. isOpen_ = false; FSTask* task = new FSTask(fiber); uv_fs_close(task->loop(), task->request(), file_, closeFileCallback); } gc<ClassObject> FileObject::getClass(VM& vm) const { return vm.fileClass(); } gc<String> FileObject::toString() const { // TODO(bob): Include some kind of ID or something here. return String::create("[file]"); } void FileObject::reach() { // TODO(bob): How should we handle file_ here? } gc<ClassObject> StreamObject::getClass(VM& vm) const { return vm.streamClass(); } gc<String> StreamObject::toString() const { // TODO(bob): Include some kind of ID or something here. return String::create("[stream]"); } } <|endoftext|>
<commit_before>/* * * Copyright 2019 gRPC authors. * * 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 <benchmark/benchmark.h> #include <grpc/grpc.h> #include <condition_variable> #include <mutex> #include "src/core/lib/iomgr/executor/threadpool.h" #include "test/cpp/microbenchmarks/helpers.h" #include "test/cpp/util/test_config.h" namespace grpc { namespace testing { // This helper class allows a thread to block for a pre-specified number of // actions. BlockingCounter has an initial non-negative count on initialization. // Each call to DecrementCount will decrease the count by 1. When making a call // to Wait, if the count is greater than 0, the thread will be blocked, until // the count reaches 0. class BlockingCounter { public: BlockingCounter(int count) : count_(count) {} void DecrementCount() { std::lock_guard<std::mutex> l(mu_); count_--; if (count_ == 0) cv_.notify_all(); } void Wait() { std::unique_lock<std::mutex> l(mu_); while (count_ > 0) { cv_.wait(l); } } private: int count_; std::mutex mu_; std::condition_variable cv_; }; // This is a functor/closure class for threadpool microbenchmark. // This functor (closure) class will add another functor into pool if the // number passed in (num_add) is greater than 0. Otherwise, it will decrement // the counter to indicate that task is finished. This functor will suicide at // the end, therefore, no need for caller to do clean-ups. class AddAnotherFunctor : public grpc_experimental_completion_queue_functor { public: AddAnotherFunctor(grpc_core::ThreadPool* pool, BlockingCounter* counter, int num_add) : pool_(pool), counter_(counter), num_add_(num_add) { functor_run = &AddAnotherFunctor::Run; internal_next = this; internal_success = 0; } // When the functor gets to run in thread pool, it will take itself as first // argument and internal_success as second one. static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<AddAnotherFunctor*>(cb); if (--callback->num_add_ > 0) { callback->pool_->Add(new AddAnotherFunctor( callback->pool_, callback->counter_, callback->num_add_)); } else { callback->counter_->DecrementCount(); } // Suicides. delete callback; } private: grpc_core::ThreadPool* pool_; BlockingCounter* counter_; int num_add_; }; void ThreadPoolAddAnotherHelper(benchmark::State& state, int concurrent_functor) { const int num_iterations = state.range(0); const int num_threads = state.range(1); // Number of adds done by each closure. const int num_add = num_iterations / concurrent_functor; grpc_core::ThreadPool pool(num_threads); while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(concurrent_functor); for (int i = 0; i < concurrent_functor; ++i) { pool.Add(new AddAnotherFunctor(&pool, &counter, num_add)); } counter.Wait(); } state.SetItemsProcessed(state.iterations()); } static void BM_ThreadPool1AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 1); } // First pair is range for number of iterations (num_iterations). // Second pair is range for thread pool size (num_threads). BENCHMARK(BM_ThreadPool1AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool4AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 4); } BENCHMARK(BM_ThreadPool4AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool8AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 8); } BENCHMARK(BM_ThreadPool8AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool16AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 16); } BENCHMARK(BM_ThreadPool16AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool32AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 32); } BENCHMARK(BM_ThreadPool32AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool64AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 64); } BENCHMARK(BM_ThreadPool64AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool128AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 128); } BENCHMARK(BM_ThreadPool128AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool512AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 512); } BENCHMARK(BM_ThreadPool512AddAnother)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool2048AddAnother(benchmark::State& state) { ThreadPoolAddAnotherHelper(state, 2048); } BENCHMARK(BM_ThreadPool2048AddAnother)->RangePair(524288, 524288, 1, 1024); // A functor class that will delete self on end of running. class SuicideFunctorForAdd : public grpc_experimental_completion_queue_functor { public: SuicideFunctorForAdd(BlockingCounter* counter) : counter_(counter) { functor_run = &SuicideFunctorForAdd::Run; internal_next = this; internal_success = 0; } static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { // On running, the first argument would be itself. auto* callback = static_cast<SuicideFunctorForAdd*>(cb); callback->counter_->DecrementCount(); delete callback; } private: BlockingCounter* counter_; }; // Performs the scenario of external thread(s) adding closures into pool. static void BM_ThreadPoolExternalAdd(benchmark::State& state) { static grpc_core::ThreadPool* external_add_pool = nullptr; // Setup for each run of test. if (state.thread_index == 0) { const int num_threads = state.range(1); external_add_pool = grpc_core::New<grpc_core::ThreadPool>(num_threads); } const int num_iterations = state.range(0) / state.threads; while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(num_iterations); for (int i = 0; i < num_iterations; ++i) { external_add_pool->Add(new SuicideFunctorForAdd(&counter)); } counter.Wait(); } // Teardown at the end of each test run. if (state.thread_index == 0) { state.SetItemsProcessed(state.range(0)); grpc_core::Delete(external_add_pool); } } BENCHMARK(BM_ThreadPoolExternalAdd) // First pair is range for number of iterations (num_iterations). // Second pair is range for thread pool size (num_threads). ->RangePair(524288, 524288, 1, 1024) ->ThreadRange(1, 256); // Concurrent external thread(s) up to 256 // Functor (closure) that adds itself into pool repeatedly. By adding self, the // overhead would be low and can measure the time of add more accurately. class AddSelfFunctor : public grpc_experimental_completion_queue_functor { public: AddSelfFunctor(grpc_core::ThreadPool* pool, BlockingCounter* counter, int num_add) : pool_(pool), counter_(counter), num_add_(num_add) { functor_run = &AddSelfFunctor::Run; internal_next = this; internal_success = 0; } // When the functor gets to run in thread pool, it will take itself as first // argument and internal_success as second one. static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<AddSelfFunctor*>(cb); if (--callback->num_add_ > 0) { callback->pool_->Add(cb); } else { callback->counter_->DecrementCount(); // Suicides. delete callback; } } private: grpc_core::ThreadPool* pool_; BlockingCounter* counter_; int num_add_; }; void ThreadPoolAddSelfHelper(benchmark::State& state, int concurrent_functor) { const int num_iterations = state.range(0); const int num_threads = state.range(1); // Number of adds done by each closure. const int num_add = num_iterations / concurrent_functor; grpc_core::ThreadPool pool(num_threads); while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(concurrent_functor); for (int i = 0; i < concurrent_functor; ++i) { pool.Add(new AddSelfFunctor(&pool, &counter, num_add)); } counter.Wait(); } state.SetItemsProcessed(state.iterations()); } static void BM_ThreadPool1AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 1); } // First pair is range for number of iterations (num_iterations). // Second pair is range for thread pool size (num_threads). BENCHMARK(BM_ThreadPool1AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool4AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 4); } BENCHMARK(BM_ThreadPool4AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool8AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 8); } BENCHMARK(BM_ThreadPool8AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool16AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 16); } BENCHMARK(BM_ThreadPool16AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool32AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 32); } BENCHMARK(BM_ThreadPool32AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool64AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 64); } BENCHMARK(BM_ThreadPool64AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool128AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 128); } BENCHMARK(BM_ThreadPool128AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool512AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 512); } BENCHMARK(BM_ThreadPool512AddSelf)->RangePair(524288, 524288, 1, 1024); static void BM_ThreadPool2048AddSelf(benchmark::State& state) { ThreadPoolAddSelfHelper(state, 2048); } BENCHMARK(BM_ThreadPool2048AddSelf)->RangePair(524288, 524288, 1, 1024); #if defined(__GNUC__) && !defined(SWIG) #if defined(__i386__) || defined(__x86_64__) #define CACHELINE_SIZE 64 #elif defined(__powerpc64__) #define CACHELINE_SIZE 128 #elif defined(__aarch64__) #define CACHELINE_SIZE 64 #elif defined(__arm__) #if defined(__ARM_ARCH_5T__) #define CACHELINE_SIZE 32 #elif defined(__ARM_ARCH_7A__) #define CACHELINE_SIZE 64 #endif #endif #ifndef CACHELINE_SIZE #define CACHELINE_SIZE 64 #endif #endif // A functor (closure) that simulates closures with small but non-trivial amount // of work. class ShortWorkFunctorForAdd : public grpc_experimental_completion_queue_functor { public: BlockingCounter* counter_; ShortWorkFunctorForAdd() { functor_run = &ShortWorkFunctorForAdd::Run; internal_next = this; internal_success = 0; val_ = 0; } static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<ShortWorkFunctorForAdd*>(cb); // Uses pad to avoid compiler complaining unused variable error. callback->pad[0] = 0; for (int i = 0; i < 1000; ++i) { callback->val_++; } callback->counter_->DecrementCount(); } private: char pad[CACHELINE_SIZE]; volatile int val_; }; // Simulates workloads where many short running callbacks are added to the // threadpool. The callbacks are not enough to keep all the workers busy // continuously so the number of workers running changes overtime. // // In effect this tests how well the threadpool avoids spurious wakeups. static void BM_SpikyLoad(benchmark::State& state) { const int num_threads = state.range(0); const int kNumSpikes = 1000; const int batch_size = 3 * num_threads; std::vector<ShortWorkFunctorForAdd> work_vector(batch_size); while (state.KeepRunningBatch(kNumSpikes * batch_size)) { grpc_core::ThreadPool pool(num_threads); for (int i = 0; i != kNumSpikes; ++i) { BlockingCounter counter(batch_size); for (auto& w : work_vector) { w.counter_ = &counter; pool.Add(&w); } counter.Wait(); } } state.SetItemsProcessed(state.iterations() * batch_size); } BENCHMARK(BM_SpikyLoad)->Arg(1)->Arg(2)->Arg(4)->Arg(8)->Arg(16); } // namespace testing } // namespace grpc // Some distros have RunSpecifiedBenchmarks under the benchmark namespace, // and others do not. This allows us to support both modes. namespace benchmark { void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); } } // namespace benchmark int main(int argc, char* argv[]) { LibraryInitializer libInit; ::benchmark::Initialize(&argc, argv); ::grpc::testing::InitTest(&argc, &argv, false); benchmark::RunTheBenchmarksNamespaced(); return 0; } <commit_msg>Use Template<commit_after>/* * * Copyright 2019 gRPC authors. * * 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 <benchmark/benchmark.h> #include <grpc/grpc.h> #include <condition_variable> #include <mutex> #include "src/core/lib/iomgr/executor/threadpool.h" #include "test/cpp/microbenchmarks/helpers.h" #include "test/cpp/util/test_config.h" namespace grpc { namespace testing { // This helper class allows a thread to block for a pre-specified number of // actions. BlockingCounter has an initial non-negative count on initialization. // Each call to DecrementCount will decrease the count by 1. When making a call // to Wait, if the count is greater than 0, the thread will be blocked, until // the count reaches 0. class BlockingCounter { public: BlockingCounter(int count) : count_(count) {} void DecrementCount() { std::lock_guard<std::mutex> l(mu_); count_--; if (count_ == 0) cv_.notify_all(); } void Wait() { std::unique_lock<std::mutex> l(mu_); while (count_ > 0) { cv_.wait(l); } } private: int count_; std::mutex mu_; std::condition_variable cv_; }; // This is a functor/closure class for threadpool microbenchmark. // This functor (closure) class will add another functor into pool if the // number passed in (num_add) is greater than 0. Otherwise, it will decrement // the counter to indicate that task is finished. This functor will suicide at // the end, therefore, no need for caller to do clean-ups. class AddAnotherFunctor : public grpc_experimental_completion_queue_functor { public: AddAnotherFunctor(grpc_core::ThreadPool* pool, BlockingCounter* counter, int num_add) : pool_(pool), counter_(counter), num_add_(num_add) { functor_run = &AddAnotherFunctor::Run; internal_next = this; internal_success = 0; } // When the functor gets to run in thread pool, it will take itself as first // argument and internal_success as second one. static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<AddAnotherFunctor*>(cb); if (--callback->num_add_ > 0) { callback->pool_->Add(new AddAnotherFunctor( callback->pool_, callback->counter_, callback->num_add_)); } else { callback->counter_->DecrementCount(); } // Suicides. delete callback; } private: grpc_core::ThreadPool* pool_; BlockingCounter* counter_; int num_add_; }; template <int kConcurrentFunctor> static void ThreadPoolAddAnother(benchmark::State& state) { const int num_iterations = state.range(0); const int num_threads = state.range(1); // Number of adds done by each closure. const int num_add = num_iterations / kConcurrentFunctor; grpc_core::ThreadPool pool(num_threads); while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(kConcurrentFunctor); for (int i = 0; i < kConcurrentFunctor; ++i) { pool.Add(new AddAnotherFunctor(&pool, &counter, num_add)); } counter.Wait(); } state.SetItemsProcessed(state.iterations()); } // First pair of arguments is range for number of iterations (num_iterations). // Second pair of arguments is range for thread pool size (num_threads). BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 1)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 4)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 8)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 16) ->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 32) ->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 64) ->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 128) ->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 512) ->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddAnother, 2048) ->RangePair(524288, 524288, 1, 1024); // A functor class that will delete self on end of running. class SuicideFunctorForAdd : public grpc_experimental_completion_queue_functor { public: SuicideFunctorForAdd(BlockingCounter* counter) : counter_(counter) { functor_run = &SuicideFunctorForAdd::Run; internal_next = this; internal_success = 0; } static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { // On running, the first argument would be itself. auto* callback = static_cast<SuicideFunctorForAdd*>(cb); callback->counter_->DecrementCount(); delete callback; } private: BlockingCounter* counter_; }; // Performs the scenario of external thread(s) adding closures into pool. static void BM_ThreadPoolExternalAdd(benchmark::State& state) { static grpc_core::ThreadPool* external_add_pool = nullptr; // Setup for each run of test. if (state.thread_index == 0) { const int num_threads = state.range(1); external_add_pool = grpc_core::New<grpc_core::ThreadPool>(num_threads); } const int num_iterations = state.range(0) / state.threads; while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(num_iterations); for (int i = 0; i < num_iterations; ++i) { external_add_pool->Add(new SuicideFunctorForAdd(&counter)); } counter.Wait(); } // Teardown at the end of each test run. if (state.thread_index == 0) { state.SetItemsProcessed(state.range(0)); grpc_core::Delete(external_add_pool); } } BENCHMARK(BM_ThreadPoolExternalAdd) // First pair is range for number of iterations (num_iterations). // Second pair is range for thread pool size (num_threads). ->RangePair(524288, 524288, 1, 1024) ->ThreadRange(1, 256); // Concurrent external thread(s) up to 256 // Functor (closure) that adds itself into pool repeatedly. By adding self, the // overhead would be low and can measure the time of add more accurately. class AddSelfFunctor : public grpc_experimental_completion_queue_functor { public: AddSelfFunctor(grpc_core::ThreadPool* pool, BlockingCounter* counter, int num_add) : pool_(pool), counter_(counter), num_add_(num_add) { functor_run = &AddSelfFunctor::Run; internal_next = this; internal_success = 0; } // When the functor gets to run in thread pool, it will take itself as first // argument and internal_success as second one. static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<AddSelfFunctor*>(cb); if (--callback->num_add_ > 0) { callback->pool_->Add(cb); } else { callback->counter_->DecrementCount(); // Suicides. delete callback; } } private: grpc_core::ThreadPool* pool_; BlockingCounter* counter_; int num_add_; }; template <int kConcurrentFunctor> static void ThreadPoolAddSelf(benchmark::State& state) { const int num_iterations = state.range(0); const int num_threads = state.range(1); // Number of adds done by each closure. const int num_add = num_iterations / kConcurrentFunctor; grpc_core::ThreadPool pool(num_threads); while (state.KeepRunningBatch(num_iterations)) { BlockingCounter counter(kConcurrentFunctor); for (int i = 0; i < kConcurrentFunctor; ++i) { pool.Add(new AddSelfFunctor(&pool, &counter, num_add)); } counter.Wait(); } state.SetItemsProcessed(state.iterations()); } // First pair of arguments is range for number of iterations (num_iterations). // Second pair of arguments is range for thread pool size (num_threads). BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 1)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 4)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 8)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 16)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 32)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 64)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 128)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 512)->RangePair(524288, 524288, 1, 1024); BENCHMARK_TEMPLATE(ThreadPoolAddSelf, 2048)->RangePair(524288, 524288, 1, 1024); #if defined(__GNUC__) && !defined(SWIG) #if defined(__i386__) || defined(__x86_64__) #define CACHELINE_SIZE 64 #elif defined(__powerpc64__) #define CACHELINE_SIZE 128 #elif defined(__aarch64__) #define CACHELINE_SIZE 64 #elif defined(__arm__) #if defined(__ARM_ARCH_5T__) #define CACHELINE_SIZE 32 #elif defined(__ARM_ARCH_7A__) #define CACHELINE_SIZE 64 #endif #endif #ifndef CACHELINE_SIZE #define CACHELINE_SIZE 64 #endif #endif // A functor (closure) that simulates closures with small but non-trivial amount // of work. class ShortWorkFunctorForAdd : public grpc_experimental_completion_queue_functor { public: BlockingCounter* counter_; ShortWorkFunctorForAdd() { functor_run = &ShortWorkFunctorForAdd::Run; internal_next = this; internal_success = 0; val_ = 0; } static void Run(grpc_experimental_completion_queue_functor* cb, int ok) { auto* callback = static_cast<ShortWorkFunctorForAdd*>(cb); // Uses pad to avoid compiler complaining unused variable error. callback->pad[0] = 0; for (int i = 0; i < 1000; ++i) { callback->val_++; } callback->counter_->DecrementCount(); } private: char pad[CACHELINE_SIZE]; volatile int val_; }; // Simulates workloads where many short running callbacks are added to the // threadpool. The callbacks are not enough to keep all the workers busy // continuously so the number of workers running changes overtime. // // In effect this tests how well the threadpool avoids spurious wakeups. static void BM_SpikyLoad(benchmark::State& state) { const int num_threads = state.range(0); const int kNumSpikes = 1000; const int batch_size = 3 * num_threads; std::vector<ShortWorkFunctorForAdd> work_vector(batch_size); while (state.KeepRunningBatch(kNumSpikes * batch_size)) { grpc_core::ThreadPool pool(num_threads); for (int i = 0; i != kNumSpikes; ++i) { BlockingCounter counter(batch_size); for (auto& w : work_vector) { w.counter_ = &counter; pool.Add(&w); } counter.Wait(); } } state.SetItemsProcessed(state.iterations() * batch_size); } BENCHMARK(BM_SpikyLoad)->Arg(1)->Arg(2)->Arg(4)->Arg(8)->Arg(16); } // namespace testing } // namespace grpc // Some distros have RunSpecifiedBenchmarks under the benchmark namespace, // and others do not. This allows us to support both modes. namespace benchmark { void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); } } // namespace benchmark int main(int argc, char* argv[]) { LibraryInitializer libInit; ::benchmark::Initialize(&argc, argv); ::grpc::testing::InitTest(&argc, &argv, false); benchmark::RunTheBenchmarksNamespaced(); return 0; } <|endoftext|>
<commit_before><commit_msg>remove depends on set container<commit_after><|endoftext|>
<commit_before>#pragma once #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" // libraries #include "nlohmann/json.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 0; bool swapLeftRightCam = false; std::string boardName, boardRev; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; // TODO(sachin): Do I need to add something for IR projector NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics); }; } // namespace dai <commit_msg>Added some headers file<commit_after>#pragma once #include <string> #include <unordered_map> #include <vector> #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraInfo.hpp" #include "depthai-shared/common/Extrinsics.hpp" #include "depthai-shared/common/Point3f.hpp" #include "depthai-shared/common/StereoRectification.hpp" // libraries #include "nlohmann/json.hpp" namespace dai { /** * EepromData structure * * Contains the Calibration and Board data stored on device */ struct EepromData { uint32_t version = 0; bool swapLeftRightCam = false; std::string boardName, boardRev; std::unordered_map<CameraBoardSocket, CameraInfo> cameraData; StereoRectification stereoRectificationData; Extrinsics imuExtrinsics; // TODO(sachin): Do I need to add something for IR projector NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics); }; } // namespace dai <|endoftext|>
<commit_before>/// /// @file print.cpp /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <print.hpp> #include <primecount-internal.hpp> #include <int128.hpp> #include <stdint.h> #include <iostream> #include <iomanip> #include <string> using namespace std; namespace { bool print_status_ = false; bool print_variables_ = false; } namespace primecount { void set_print_status(bool print_status) { #ifdef HAVE_MPI print_status_ = print_status && is_mpi_master_proc(); #else print_status_ = print_status; #endif } void set_print_variables(bool print_variables) { #ifdef HAVE_MPI print_variables_ = print_variables && is_mpi_master_proc(); #else print_variables_ = print_variables; #endif } bool print_result() { #ifdef HAVE_MPI return !print_variables() && is_mpi_master_proc(); #else return !print_variables(); #endif } void print_threads(int threads) { #ifdef HAVE_MPI cout << "processes = " << mpi_num_procs() << endl; cout << "threads = " << mpi_num_procs() << " * " << validate_threads(threads) << endl; #else cout << "threads = " << validate_threads(threads) << endl; #endif } bool print_status() { return print_status_; } bool print_variables() { return print_variables_; } void print(const string& str) { if (print_status()) cout << str << endl; } void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads) { if (print_variables()) { cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << c << endl; cout << "alpha = " << fixed << setprecision(3) << alpha << endl; print_threads(threads); } } void print(maxint_t x, int64_t y, int threads) { if (print_variables()) { maxint_t z = x / y; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl; print_threads(threads); cout << endl; } } void print(maxint_t x, int64_t y, int64_t c, int threads) { if (print_variables()) { maxint_t z = x / y; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << c << endl; cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl; print_threads(threads); cout << endl; } } void print(const string& res_str, maxint_t res, double time) { if (print_status()) { cout << "\r" << string(50,' ') << "\r"; cout << "Status: 100%" << endl; cout << res_str << " = " << res << endl; print_seconds(get_wtime() - time); } } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } } // namespace <commit_msg>Fix printing variables<commit_after>/// /// @file print.cpp /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <print.hpp> #include <primecount-internal.hpp> #include <int128.hpp> #include <stdint.h> #include <iostream> #include <iomanip> #include <string> using namespace std; namespace { bool print_status_ = false; bool print_variables_ = false; } namespace primecount { void set_print_status(bool print_status) { #ifdef HAVE_MPI print_status_ = print_status && is_mpi_master_proc(); #else print_status_ = print_status; #endif } void set_print_variables(bool print_variables) { #ifdef HAVE_MPI print_variables_ = print_variables && is_mpi_master_proc(); #else print_variables_ = print_variables; #endif } bool print_result() { #ifdef HAVE_MPI return !print_variables() && is_mpi_master_proc(); #else return !print_variables(); #endif } void print_threads(int threads) { #ifdef HAVE_MPI cout << "processes = " << mpi_num_procs() << endl; cout << "threads = " << mpi_num_procs() << " * " << validate_threads(threads) << endl; #else cout << "threads = " << validate_threads(threads) << endl; #endif } bool print_status() { return print_status_; } bool print_variables() { return print_variables_; } void print(const string& str) { if (print_status()) cout << str << endl; } void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads) { if (print_status()) { cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << c << endl; cout << "alpha = " << fixed << setprecision(3) << alpha << endl; print_threads(threads); } } void print(maxint_t x, int64_t y, int threads) { if (print_variables()) { maxint_t z = x / y; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl; print_threads(threads); cout << endl; } } void print(maxint_t x, int64_t y, int64_t c, int threads) { if (print_variables()) { maxint_t z = x / y; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << c << endl; cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl; print_threads(threads); cout << endl; } } void print(const string& res_str, maxint_t res, double time) { if (print_status()) { cout << "\r" << string(50,' ') << "\r"; cout << "Status: 100%" << endl; cout << res_str << " = " << res << endl; print_seconds(get_wtime() - time); } } void print_seconds(double seconds) { cout << "Seconds: " << fixed << setprecision(3) << seconds << endl; } } // namespace <|endoftext|>
<commit_before>#ifndef OPENGM_PARAMETERS #define OPENGM_PARAMETERS namespace opengm{ template<class T,class I> class Parameters{ public: typedef T ValueType; typedef I IndexType; Parameters(const IndexType numberOfParameters=0) : params_(numberOfParameters){ } ValueType getParameter(const size_t pi)const{ OPENGM_ASSERT_OP(pi,<,params_.size()); return params_[pi]; } ValueType setParameter(const size_t pi,const ValueType value){ OPENGM_ASSERT_OP(pi,<,params_.size()); params_[pi]=value; } ValueType operator[](const size_t pi)const{ return getParameter(pi); } size_t numberOfParameters()const{ return params_.size(); } private: std::vector<ValueType> params_; }; } #endif /* OPENGM_PARAMETERS */<commit_msg>fix bug in parameters<commit_after>#ifndef OPENGM_PARAMETERS #define OPENGM_PARAMETERS namespace opengm{ template<class T,class I> class Parameters{ public: typedef T ValueType; typedef I IndexType; Parameters(const IndexType numberOfParameters=0) : params_(numberOfParameters){ } ValueType getParameter(const size_t pi)const{ OPENGM_ASSERT_OP(pi,<,params_.size()); return params_[pi]; } void setParameter(const size_t pi,const ValueType value){ OPENGM_ASSERT_OP(pi,<,params_.size()); params_[pi]=value; } ValueType operator[](const size_t pi)const{ return getParameter(pi); } size_t numberOfParameters()const{ return params_.size(); } private: std::vector<ValueType> params_; }; } #endif /* OPENGM_PARAMETERS */<|endoftext|>
<commit_before>#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "mkl_cblas.h" #include "sgemm_wrapper.h" #include "benchmarks.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } // extern "C" #endif int main(int, char **) { std::vector<std::chrono::duration<double,std::milli>> duration_vector_1; std::vector<std::chrono::duration<double,std::milli>> duration_vector_2; float a = 3, b = 3; #if 1 bool run_mkl = false; bool run_tiramisu = false; const char* env_mkl = std::getenv("RUN_REF"); if ((env_mkl != NULL) && (env_mkl[0] == '1')) run_mkl = true; const char* env_tira = std::getenv("RUN_TIRAMISU"); if ((env_tira != NULL) && (env_tira[0] == '1')) run_tiramisu = true; #else bool run_mkl = true; bool run_tiramisu = true; #endif int sizes[27][4], D = 1060 * 1060; /************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/ sizes[0][0] = 4096; sizes[0][1] = 4096; sizes[0][2] = 4096; sizes[0][3] = 65536 * 4096; sizes[1][0] = 128; sizes[1][1] = 128; sizes[1][2] = 128; sizes[1][3] = 128; sizes[2][0] = 512; sizes[2][1] = 512; sizes[2][2] = 512; sizes[2][3] = 1024; sizes[3][0] = 1024; sizes[3][1] = 1024; sizes[3][2] = 1024; sizes[3][3] = 1024 * 1024; sizes[4][0] = 128; sizes[4][1] = 128; sizes[4][2] = 256; sizes[4][3] = D; sizes[5][0] = 2048; sizes[5][1] = 2048; sizes[5][2] = 2048; sizes[5][3] = D; sizes[6][0] = 2048; sizes[6][1] = 2048; sizes[6][2] = 1024; sizes[6][3] = D; sizes[7][0] = 1024; sizes[7][1] = 1024; sizes[7][2] = 2048; sizes[7][3] = D; sizes[8][0] = 1024; sizes[8][1] = 1024; sizes[8][2] = 512; sizes[8][3] = D; sizes[9][0] = 512; sizes[9][1] = 512; sizes[9][2] = 1024; sizes[9][3] = D; sizes[10][0] = 512; sizes[10][1] = 512; sizes[10][2] = 256; sizes[10][3] = D; sizes[11][0] = 128; sizes[11][1] = 128; sizes[11][2] = 2048; sizes[11][3] = D; sizes[12][0] = 256; sizes[12][1] = 256; sizes[12][2] = 256; sizes[12][3] = D; sizes[13][0] = 128; sizes[13][1] = 128; sizes[13][2] = 512; sizes[13][3] = D; sizes[14][0] = 128; sizes[14][1] = 128; sizes[14][2] = 1024; sizes[14][3] = D; sizes[15][0] = 128; sizes[15][1] = 128; sizes[15][2] = 64; sizes[15][3] = D; /************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/ sizes[16][0] = 1060; sizes[16][1] = 1060; sizes[16][2] = 1060; sizes[16][3] = D; sizes[17][0] = 4; sizes[17][1] = 4; sizes[17][2] = 4; sizes[17][3] = D; sizes[18][0] = 8; sizes[18][1] = 8; sizes[18][2] = 4; sizes[18][3] = D; sizes[19][0] = 16; sizes[19][1] = 16; sizes[19][2] = 4; sizes[19][3] = D; sizes[20][0] = 16; sizes[20][1] = 16; sizes[20][2] = 16; sizes[20][3] = D; sizes[21][0] = 8; sizes[21][1] = 8; sizes[21][2] = 16; sizes[21][3] = D; int p, q; if (SIZE_IS_MULTIPLE_OF_TILE) { p = 1; q = 16; } else { p = 16; q = 22; } for (int j = p; j < q; j++) { int local_N = sizes[j][0]; int local_M = sizes[j][1]; int local_K = sizes[j][2]; int local_size = sizes[j][3]; Halide::Buffer<int> SIZES(3, "SIZES"); Halide::Buffer<float> alpha(1, "alpha"); Halide::Buffer<float> beta(1, "beta"); Halide::Buffer<float> A(local_N, local_K, "A"); Halide::Buffer<float> B(local_K, local_M, "B"); Halide::Buffer<float> C(local_N, local_M, "C"); Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl"); SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K; alpha(0) = a; beta(0) = b; init_buffer(A, (float)1); init_buffer(B, (float)1); init_buffer(C, (float)1); init_buffer(C_mkl, (float)1); // Calling MKL { long long int lda, ldb, ldc; long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc; CBLAS_LAYOUT layout = CblasRowMajor; CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans; long long int ma, na, mb, nb; if( transA == CblasNoTrans ) { rmaxa = local_M + 1; cmaxa = local_K; ma = local_M; na = local_K; } else { rmaxa = local_K + 1; cmaxa = local_M; ma = local_K; na = local_M; } if( transB == CblasNoTrans ) { rmaxb = local_K + 1; cmaxb = local_N; mb = local_K; nb = local_N; } else { rmaxb = local_N + 1; cmaxb = local_K; mb = local_N; nb = local_K; } rmaxc = local_M + 1; cmaxc = local_N; if (layout == CblasRowMajor) { lda=cmaxa; ldb=cmaxb; ldc=cmaxc; } else { lda=rmaxa; ldb=rmaxb; ldc=rmaxc; } for (int i = 0; i < NB_TESTS; i++) { init_buffer(C_mkl, (float)1); auto start1 = std::chrono::high_resolution_clock::now(); if (run_mkl == true) cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc); auto end1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration1 = end1 - start1; duration_vector_1.push_back(duration1); } } for (int i = 0; i < NB_TESTS; i++) { init_buffer(C, (float)1); auto start2 = std::chrono::high_resolution_clock::now(); if (run_tiramisu == true) sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer()); auto end2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration2 = end2 - start2; duration_vector_2.push_back(duration2); } print_time("performance_CPU.csv", "sgemm", {"MKL", "Tiramisu"}, {median(duration_vector_1), median(duration_vector_2)}); if (CHECK_CORRECTNESS) if (run_mkl == 1 && run_tiramisu == 1) { compare_buffers("sgemm", C, C_mkl); } if (PRINT_OUTPUT) { std::cout << "Tiramisu sgemm " << std::endl; print_buffer(C); std::cout << "MKL sgemm " << std::endl; print_buffer(C_mkl); } } return 0; } <commit_msg>Update sgemm_wrapper.cpp<commit_after>#include "Halide.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #include "mkl_cblas.h" #include "sgemm_wrapper.h" #include "benchmarks.h" #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } // extern "C" #endif int main(int, char **) { std::vector<std::chrono::duration<double,std::milli>> duration_vector_1; std::vector<std::chrono::duration<double,std::milli>> duration_vector_2; float a = 3, b = 3; #if 1 bool run_mkl = false; bool run_tiramisu = false; const char* env_mkl = std::getenv("RUN_REF"); if ((env_mkl != NULL) && (env_mkl[0] == '1')) run_mkl = true; const char* env_tira = std::getenv("RUN_TIRAMISU"); if ((env_tira != NULL) && (env_tira[0] == '1')) run_tiramisu = true; #else bool run_mkl = true; bool run_tiramisu = true; #endif int sizes[27][4], D = 1060 * 1060; /************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/ sizes[0][0] = 4096; sizes[0][1] = 4096; sizes[0][2] = 4096; sizes[0][3] = 65536 * 4096; sizes[1][0] = 128; sizes[1][1] = 128; sizes[1][2] = 128; sizes[1][3] = 128; sizes[2][0] = 512; sizes[2][1] = 512; sizes[2][2] = 512; sizes[2][3] = 1024; sizes[3][0] = 1024; sizes[3][1] = 1024; sizes[3][2] = 1024; sizes[3][3] = 1024 * 1024; sizes[4][0] = 128; sizes[4][1] = 128; sizes[4][2] = 256; sizes[4][3] = D; sizes[5][0] = 2048; sizes[5][1] = 2048; sizes[5][2] = 2048; sizes[5][3] = D; sizes[6][0] = 2048; sizes[6][1] = 2048; sizes[6][2] = 1024; sizes[6][3] = D; sizes[7][0] = 1024; sizes[7][1] = 1024; sizes[7][2] = 2048; sizes[7][3] = D; sizes[8][0] = 1024; sizes[8][1] = 1024; sizes[8][2] = 512; sizes[8][3] = D; sizes[9][0] = 512; sizes[9][1] = 512; sizes[9][2] = 1024; sizes[9][3] = D; sizes[10][0] = 512; sizes[10][1] = 512; sizes[10][2] = 256; sizes[10][3] = D; sizes[11][0] = 128; sizes[11][1] = 128; sizes[11][2] = 2048; sizes[11][3] = D; sizes[12][0] = 256; sizes[12][1] = 256; sizes[12][2] = 256; sizes[12][3] = D; sizes[13][0] = 128; sizes[13][1] = 128; sizes[13][2] = 512; sizes[13][3] = D; sizes[14][0] = 128; sizes[14][1] = 128; sizes[14][2] = 1024; sizes[14][3] = D; sizes[15][0] = 128; sizes[15][1] = 128; sizes[15][2] = 64; sizes[15][3] = D; /************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/ sizes[16][0] = 1060; sizes[16][1] = 1060; sizes[16][2] = 1060; sizes[16][3] = D; sizes[17][0] = 4; sizes[17][1] = 4; sizes[17][2] = 4; sizes[17][3] = D; sizes[18][0] = 8; sizes[18][1] = 8; sizes[18][2] = 4; sizes[18][3] = D; sizes[19][0] = 16; sizes[19][1] = 16; sizes[19][2] = 4; sizes[19][3] = D; sizes[20][0] = 16; sizes[20][1] = 16; sizes[20][2] = 16; sizes[20][3] = D; sizes[21][0] = 8; sizes[21][1] = 8; sizes[21][2] = 16; sizes[21][3] = D; int p, q; if (SIZE_IS_MULTIPLE_OF_TILE) { p = 0; q = 16; } else { p = 16; q = 22; } for (int j = p; j < q; j++) { int local_N = sizes[j][0]; int local_M = sizes[j][1]; int local_K = sizes[j][2]; int local_size = sizes[j][3]; Halide::Buffer<int> SIZES(3, "SIZES"); Halide::Buffer<float> alpha(1, "alpha"); Halide::Buffer<float> beta(1, "beta"); Halide::Buffer<float> A(local_N, local_K, "A"); Halide::Buffer<float> B(local_K, local_M, "B"); Halide::Buffer<float> C(local_N, local_M, "C"); Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl"); SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K; alpha(0) = a; beta(0) = b; init_buffer(A, (float)1); init_buffer(B, (float)1); init_buffer(C, (float)1); init_buffer(C_mkl, (float)1); // Calling MKL { long long int lda, ldb, ldc; long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc; CBLAS_LAYOUT layout = CblasRowMajor; CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans; long long int ma, na, mb, nb; if( transA == CblasNoTrans ) { rmaxa = local_M + 1; cmaxa = local_K; ma = local_M; na = local_K; } else { rmaxa = local_K + 1; cmaxa = local_M; ma = local_K; na = local_M; } if( transB == CblasNoTrans ) { rmaxb = local_K + 1; cmaxb = local_N; mb = local_K; nb = local_N; } else { rmaxb = local_N + 1; cmaxb = local_K; mb = local_N; nb = local_K; } rmaxc = local_M + 1; cmaxc = local_N; if (layout == CblasRowMajor) { lda=cmaxa; ldb=cmaxb; ldc=cmaxc; } else { lda=rmaxa; ldb=rmaxb; ldc=rmaxc; } for (int i = 0; i < NB_TESTS; i++) { init_buffer(C_mkl, (float)1); auto start1 = std::chrono::high_resolution_clock::now(); if (run_mkl == true) cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc); auto end1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration1 = end1 - start1; duration_vector_1.push_back(duration1); } } for (int i = 0; i < NB_TESTS; i++) { init_buffer(C, (float)1); auto start2 = std::chrono::high_resolution_clock::now(); if (run_tiramisu == true) sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer()); auto end2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration2 = end2 - start2; duration_vector_2.push_back(duration2); } print_time("performance_CPU.csv", "sgemm", {"MKL", "Tiramisu"}, {median(duration_vector_1), median(duration_vector_2)}); if (CHECK_CORRECTNESS) if (run_mkl == 1 && run_tiramisu == 1) { compare_buffers("sgemm", C, C_mkl); } if (PRINT_OUTPUT) { std::cout << "Tiramisu sgemm " << std::endl; print_buffer(C); std::cout << "MKL sgemm " << std::endl; print_buffer(C_mkl); } } return 0; } <|endoftext|>
<commit_before>#include <af/seq.h> #include <af/array.h> #include <af/data.h> #include "error.hpp" namespace af { AFAPI int end = -1; AFAPI seq span(af_span); void seq::init(double begin, double end, double step) { this->s.begin = begin; this->s.end = end; this->s.step = step; if(step != 0) { // Not Span size = fabs((end - begin) / step) + 1; } else { size = 0; } } #ifndef signbit // wtf windows?! inline int signbit(double x) { if (x < 0) return -1; return 0; } #endif seq::~seq() { } seq::seq(double n): m_gfor(false) { if (n < 0) { init(n + 1, 0, 1); // seq(-4) = -3, -2, -1, 0 } else { init(0, n - 1, 1); } } seq::seq(const af_seq& s_): m_gfor(false) { init(s_.begin, s_.end, s_.step); } seq& seq::operator=(const af_seq& s_) { init(s_.begin, s_.end, s_.step); return *this; } seq::seq(double begin, double end, double step): m_gfor(false) { if(begin == -1 && end <= -1) { step = 0; // end } if (step == 0) { if (begin != end) // Span AF_THROW_MSG("Invalid step size", AF_ERR_INVALID_ARG); } if (end >= 0 && begin >= 0 && signbit(end-begin) != signbit(step)) AF_THROW_MSG("Sequence is invalid", AF_ERR_INVALID_ARG); //AF_THROW("step must match direction of sequence"); init(begin, end, step); } seq::seq(seq other, bool is_gfor): m_gfor(is_gfor) { this->s = other.s; this->size = other.size; } seq::operator array() const { dim_type diff = s.end - s.begin; dim_type len = (int)((diff + abs(s.step) * (signbit(diff) == 0 ? 1 : -1)) / s.step); array tmp = (m_gfor) ? range(1, 1, 1, len) : range(len); array res = s.begin + s.step * tmp; return res; } } <commit_msg>BUGFIX: Fixed bug in seq to array casting inside gfor<commit_after>#include <af/seq.h> #include <af/array.h> #include <af/data.h> #include "error.hpp" namespace af { AFAPI int end = -1; AFAPI seq span(af_span); void seq::init(double begin, double end, double step) { this->s.begin = begin; this->s.end = end; this->s.step = step; if(step != 0) { // Not Span size = fabs((end - begin) / step) + 1; } else { size = 0; } } #ifndef signbit // wtf windows?! inline int signbit(double x) { if (x < 0) return -1; return 0; } #endif seq::~seq() { } seq::seq(double n): m_gfor(false) { if (n < 0) { init(n + 1, 0, 1); // seq(-4) = -3, -2, -1, 0 } else { init(0, n - 1, 1); } } seq::seq(const af_seq& s_): m_gfor(false) { init(s_.begin, s_.end, s_.step); } seq& seq::operator=(const af_seq& s_) { init(s_.begin, s_.end, s_.step); return *this; } seq::seq(double begin, double end, double step): m_gfor(false) { if(begin == -1 && end <= -1) { step = 0; // end } if (step == 0) { if (begin != end) // Span AF_THROW_MSG("Invalid step size", AF_ERR_INVALID_ARG); } if (end >= 0 && begin >= 0 && signbit(end-begin) != signbit(step)) AF_THROW_MSG("Sequence is invalid", AF_ERR_INVALID_ARG); //AF_THROW("step must match direction of sequence"); init(begin, end, step); } seq::seq(seq other, bool is_gfor): m_gfor(is_gfor) { this->s = other.s; this->size = other.size; } seq::operator array() const { dim_type diff = s.end - s.begin; dim_type len = (int)((diff + abs(s.step) * (signbit(diff) == 0 ? 1 : -1)) / s.step); array tmp = (m_gfor) ? range(1, 1, 1, len, 3) : range(len); array res = s.begin + s.step * tmp; return res; } } <|endoftext|>
<commit_before>#include "factory.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #ifdef USE_I420 #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #endif namespace gg { IVideoSource * Factory::_sources[2] = { NULL, NULL }; IVideoSource * Factory::connect(enum Device type) { #ifdef USE_I420 std::string device_id = ""; #ifndef USE_EPIPHANSDK throw VideoSourceError("I420 colour space supported only with EpiphanSDK"); #endif #else int device_id = -1; // default value makes no sense #endif switch (type) { case DVI2PCIeDuo_DVI: #ifdef USE_I420 #ifdef USE_EPIPHANSDK #ifdef EpiphanSDK_DVI device_id = EpiphanSDK_DVI; #else throw DeviceNotFound("EpiphanSDK_DVI macro not defined"); #endif #endif #ifdef USE_LIBVLC device_id = ""; // TODO #endif #else device_id = 0; // always /dev/video0 #endif break; case DVI2PCIeDuo_SDI: #ifdef USE_I420 #ifdef USE_EPIPHANSDK #ifdef EpiphanSDK_SDI device_id = EpiphanSDK_SDI; #else throw DeviceNotFound("EpiphanSDK_SDI macro not defined"); #endif #endif #ifdef USE_LIBVLC device_id = ""; // TODO #endif #else device_id = 1; // always /dev/video1 #endif break; default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type] == NULL) { IVideoSource * src = nullptr; #ifdef USE_I420 #ifdef USE_EPIPHANSDK try { src = new VideoSourceEpiphanSDK(device_id, V2U_GRABFRAME_FORMAT_I420); } catch (VideoSourceError & e) { throw DeviceNotFound(e.what()); } #endif #ifdef USE_LIBVLC try { src = new VideoSourceVLC(device_id); } catch (VideoSourceError & e) { throw DeviceNotFound(e.what()); } #endif #else #ifdef USE_OPENCV src = new VideoSourceOpenCV(device_id); #else std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not supported"); throw VideoSourceError(msg); #endif // USE_OPENCV #endif // check querying frame dimensions int width = -1, height = -1; if (not src->get_frame_dimensions(width, height)) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frame dimensions."); throw DeviceOffline(error); } // check meaningful frame dimensions if (width <= 0 or height <= 0) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" returns meaningless frame dimensions."); throw DeviceOffline(error); } // check querying frames #ifdef USE_I420 VideoFrame_I420 frame; #else VideoFrame_BGRA frame; #endif if (not src->get_frame(frame)) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frames."); throw DeviceOffline(error); } // if no exception raised up to here, glory be to GiftGrab _sources[(int) type] = src; } return _sources[(int) type]; } void Factory::disconnect(enum Device type) { switch (type) { case DVI2PCIeDuo_DVI: case DVI2PCIeDuo_SDI: break; // everything up to here is recognised default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type]) { delete _sources[(int) type]; _sources[(int) type] = NULL; } } IVideoTarget * Factory::writer(Storage type) { switch (type) { case File_XviD: #ifdef USE_OPENCV return new VideoTargetOpenCV("XVID"); #endif // USE_OPENCV case File_HEVC: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("HEVC"); #else // nop, see default below #endif case File_VP9: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("VP9"); #else // nop, see default below #endif default: std::string msg; msg.append("Video target type ") .append(std::to_string(type)) .append(" not supported"); throw VideoTargetError(msg); } } } <commit_msg>Issue #83: factory constructing VLC video source with /dev/video* path for Epiphan<commit_after>#include "factory.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #ifdef USE_I420 #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #endif namespace gg { IVideoSource * Factory::_sources[2] = { NULL, NULL }; IVideoSource * Factory::connect(enum Device type) { #ifdef USE_I420 std::string device_id = ""; #ifndef USE_EPIPHANSDK throw VideoSourceError("I420 colour space supported only with EpiphanSDK"); #endif #else int device_id = -1; // default value makes no sense #endif switch (type) { case DVI2PCIeDuo_DVI: #ifdef USE_I420 #ifdef USE_EPIPHANSDK #ifdef EpiphanSDK_DVI device_id = EpiphanSDK_DVI; #else throw DeviceNotFound("EpiphanSDK_DVI macro not defined"); #endif #endif #ifdef USE_LIBVLC device_id = "v4l2:///dev/video0"; // always /dev/video0 #endif #else device_id = 0; // always /dev/video0 #endif break; case DVI2PCIeDuo_SDI: #ifdef USE_I420 #ifdef USE_EPIPHANSDK #ifdef EpiphanSDK_SDI device_id = EpiphanSDK_SDI; #else throw DeviceNotFound("EpiphanSDK_SDI macro not defined"); #endif #endif #ifdef USE_LIBVLC device_id = "v4l2:///dev/video1"; // always /dev/video1 #endif #else device_id = 1; // always /dev/video1 #endif break; default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type] == NULL) { IVideoSource * src = nullptr; #ifdef USE_I420 #ifdef USE_EPIPHANSDK try { src = new VideoSourceEpiphanSDK(device_id, V2U_GRABFRAME_FORMAT_I420); } catch (VideoSourceError & e) { throw DeviceNotFound(e.what()); } #endif #ifdef USE_LIBVLC try { src = new VideoSourceVLC(device_id); } catch (VideoSourceError & e) { throw DeviceNotFound(e.what()); } #endif #else #ifdef USE_OPENCV src = new VideoSourceOpenCV(device_id); #else std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not supported"); throw VideoSourceError(msg); #endif // USE_OPENCV #endif // check querying frame dimensions int width = -1, height = -1; if (not src->get_frame_dimensions(width, height)) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frame dimensions."); throw DeviceOffline(error); } // check meaningful frame dimensions if (width <= 0 or height <= 0) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" returns meaningless frame dimensions."); throw DeviceOffline(error); } // check querying frames #ifdef USE_I420 VideoFrame_I420 frame; #else VideoFrame_BGRA frame; #endif if (not src->get_frame(frame)) { std::string error; error.append("Device ") #ifdef USE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frames."); throw DeviceOffline(error); } // if no exception raised up to here, glory be to GiftGrab _sources[(int) type] = src; } return _sources[(int) type]; } void Factory::disconnect(enum Device type) { switch (type) { case DVI2PCIeDuo_DVI: case DVI2PCIeDuo_SDI: break; // everything up to here is recognised default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type]) { delete _sources[(int) type]; _sources[(int) type] = NULL; } } IVideoTarget * Factory::writer(Storage type) { switch (type) { case File_XviD: #ifdef USE_OPENCV return new VideoTargetOpenCV("XVID"); #endif // USE_OPENCV case File_HEVC: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("HEVC"); #else // nop, see default below #endif case File_VP9: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("VP9"); #else // nop, see default below #endif default: std::string msg; msg.append("Video target type ") .append(std::to_string(type)) .append(" not supported"); throw VideoTargetError(msg); } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/webdatabase/SQLTransactionCoordinator.h" #include "modules/webdatabase/DatabaseBackend.h" #include "modules/webdatabase/SQLTransactionBackend.h" #include "weborigin/DatabaseIdentifier.h" #include "weborigin/SecurityOrigin.h" #include "wtf/Deque.h" #include "wtf/HashMap.h" #include "wtf/HashSet.h" #include "wtf/RefPtr.h" namespace WebCore { static String getDatabaseIdentifier(SQLTransactionBackend* transaction) { DatabaseBackend* database = transaction->database(); ASSERT(database); return createDatabaseIdentifierFromSecurityOrigin(database->securityOrigin()); } SQLTransactionCoordinator::SQLTransactionCoordinator() : m_isShuttingDown(false) { } void SQLTransactionCoordinator::processPendingTransactions(CoordinationInfo& info) { if (info.activeWriteTransaction || info.pendingTransactions.isEmpty()) return; RefPtr<SQLTransactionBackend> firstPendingTransaction = info.pendingTransactions.first(); if (firstPendingTransaction->isReadOnly()) { do { firstPendingTransaction = info.pendingTransactions.takeFirst(); info.activeReadTransactions.add(firstPendingTransaction); firstPendingTransaction->lockAcquired(); } while (!info.pendingTransactions.isEmpty() && info.pendingTransactions.first()->isReadOnly()); } else if (info.activeReadTransactions.isEmpty()) { info.pendingTransactions.removeFirst(); info.activeWriteTransaction = firstPendingTransaction; firstPendingTransaction->lockAcquired(); } } void SQLTransactionCoordinator::acquireLock(SQLTransactionBackend* transaction) { ASSERT(!m_isShuttingDown); String dbIdentifier = getDatabaseIdentifier(transaction); CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.find(dbIdentifier); if (coordinationInfoIterator == m_coordinationInfoMap.end()) { // No pending transactions for this DB coordinationInfoIterator = m_coordinationInfoMap.add(dbIdentifier, CoordinationInfo()).iterator; } CoordinationInfo& info = coordinationInfoIterator->value; info.pendingTransactions.append(transaction); processPendingTransactions(info); } void SQLTransactionCoordinator::releaseLock(SQLTransactionBackend* transaction) { if (m_isShuttingDown) return; String dbIdentifier = getDatabaseIdentifier(transaction); CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.find(dbIdentifier); ASSERT(coordinationInfoIterator != m_coordinationInfoMap.end()); CoordinationInfo& info = coordinationInfoIterator->value; if (transaction->isReadOnly()) { ASSERT(info.activeReadTransactions.contains(transaction)); info.activeReadTransactions.remove(transaction); } else { ASSERT(info.activeWriteTransaction == transaction); info.activeWriteTransaction = 0; } processPendingTransactions(info); } void SQLTransactionCoordinator::shutdown() { // Prevent releaseLock() from accessing / changing the coordinationInfo // while we're shutting down. m_isShuttingDown = true; // Notify all transactions in progress that the database thread is shutting down for (CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.begin(); coordinationInfoIterator != m_coordinationInfoMap.end(); ++coordinationInfoIterator) { CoordinationInfo& info = coordinationInfoIterator->value; // Clean up transactions that have reached "lockAcquired": // Transaction phase 4 cleanup. See comment on "What happens if a // transaction is interrupted?" at the top of SQLTransactionBackend.cpp. if (info.activeWriteTransaction) info.activeWriteTransaction->notifyDatabaseThreadIsShuttingDown(); for (HashSet<RefPtr<SQLTransactionBackend> >::iterator activeReadTransactionsIterator = info.activeReadTransactions.begin(); activeReadTransactionsIterator != info.activeReadTransactions.end(); ++activeReadTransactionsIterator) { (*activeReadTransactionsIterator)->notifyDatabaseThreadIsShuttingDown(); } // Clean up transactions that have NOT reached "lockAcquired": // Transaction phase 3 cleanup. See comment on "What happens if a // transaction is interrupted?" at the top of SQLTransactionBackend.cpp. while (!info.pendingTransactions.isEmpty()) { RefPtr<SQLTransactionBackend> transaction = info.pendingTransactions.first(); transaction->notifyDatabaseThreadIsShuttingDown(); } } // Clean up all pending transactions for all databases m_coordinationInfoMap.clear(); } } // namespace WebCore <commit_msg>Revert one line of of r144760 to undo the following part of it...<commit_after>/* * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/webdatabase/SQLTransactionCoordinator.h" #include "modules/webdatabase/DatabaseBackend.h" #include "modules/webdatabase/SQLTransactionBackend.h" #include "wtf/Deque.h" #include "wtf/HashMap.h" #include "wtf/HashSet.h" #include "wtf/RefPtr.h" namespace WebCore { static String getDatabaseIdentifier(SQLTransactionBackend* transaction) { DatabaseBackend* database = transaction->database(); ASSERT(database); return database->stringIdentifier(); } SQLTransactionCoordinator::SQLTransactionCoordinator() : m_isShuttingDown(false) { } void SQLTransactionCoordinator::processPendingTransactions(CoordinationInfo& info) { if (info.activeWriteTransaction || info.pendingTransactions.isEmpty()) return; RefPtr<SQLTransactionBackend> firstPendingTransaction = info.pendingTransactions.first(); if (firstPendingTransaction->isReadOnly()) { do { firstPendingTransaction = info.pendingTransactions.takeFirst(); info.activeReadTransactions.add(firstPendingTransaction); firstPendingTransaction->lockAcquired(); } while (!info.pendingTransactions.isEmpty() && info.pendingTransactions.first()->isReadOnly()); } else if (info.activeReadTransactions.isEmpty()) { info.pendingTransactions.removeFirst(); info.activeWriteTransaction = firstPendingTransaction; firstPendingTransaction->lockAcquired(); } } void SQLTransactionCoordinator::acquireLock(SQLTransactionBackend* transaction) { ASSERT(!m_isShuttingDown); String dbIdentifier = getDatabaseIdentifier(transaction); CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.find(dbIdentifier); if (coordinationInfoIterator == m_coordinationInfoMap.end()) { // No pending transactions for this DB coordinationInfoIterator = m_coordinationInfoMap.add(dbIdentifier, CoordinationInfo()).iterator; } CoordinationInfo& info = coordinationInfoIterator->value; info.pendingTransactions.append(transaction); processPendingTransactions(info); } void SQLTransactionCoordinator::releaseLock(SQLTransactionBackend* transaction) { if (m_isShuttingDown) return; String dbIdentifier = getDatabaseIdentifier(transaction); CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.find(dbIdentifier); ASSERT(coordinationInfoIterator != m_coordinationInfoMap.end()); CoordinationInfo& info = coordinationInfoIterator->value; if (transaction->isReadOnly()) { ASSERT(info.activeReadTransactions.contains(transaction)); info.activeReadTransactions.remove(transaction); } else { ASSERT(info.activeWriteTransaction == transaction); info.activeWriteTransaction = 0; } processPendingTransactions(info); } void SQLTransactionCoordinator::shutdown() { // Prevent releaseLock() from accessing / changing the coordinationInfo // while we're shutting down. m_isShuttingDown = true; // Notify all transactions in progress that the database thread is shutting down for (CoordinationInfoMap::iterator coordinationInfoIterator = m_coordinationInfoMap.begin(); coordinationInfoIterator != m_coordinationInfoMap.end(); ++coordinationInfoIterator) { CoordinationInfo& info = coordinationInfoIterator->value; // Clean up transactions that have reached "lockAcquired": // Transaction phase 4 cleanup. See comment on "What happens if a // transaction is interrupted?" at the top of SQLTransactionBackend.cpp. if (info.activeWriteTransaction) info.activeWriteTransaction->notifyDatabaseThreadIsShuttingDown(); for (HashSet<RefPtr<SQLTransactionBackend> >::iterator activeReadTransactionsIterator = info.activeReadTransactions.begin(); activeReadTransactionsIterator != info.activeReadTransactions.end(); ++activeReadTransactionsIterator) { (*activeReadTransactionsIterator)->notifyDatabaseThreadIsShuttingDown(); } // Clean up transactions that have NOT reached "lockAcquired": // Transaction phase 3 cleanup. See comment on "What happens if a // transaction is interrupted?" at the top of SQLTransactionBackend.cpp. while (!info.pendingTransactions.isEmpty()) { RefPtr<SQLTransactionBackend> transaction = info.pendingTransactions.first(); transaction->notifyDatabaseThreadIsShuttingDown(); } } // Clean up all pending transactions for all databases m_coordinationInfoMap.clear(); } } // namespace WebCore <|endoftext|>
<commit_before>/************************************************************************* * * TIGHTDB CONFIDENTIAL * __________________ * * [2011] - [2012] TightDB Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of TightDB Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to TightDB Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from TightDB Incorporated. * **************************************************************************/ #ifndef __TIGHTDB_QUERY_HPP #define __TIGHTDB_QUERY_HPP #include <string> #include <algorithm> #include <vector> #include <stdio.h> #include <limits.h> #if defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) #include "win32/pthread/pthread.h" #else #include <pthread.h> #endif namespace tightdb { // Pre-declarations class ParentNode; class Table; class TableView; const size_t MAX_THREADS = 128; class Query { public: Query(); Query(const Query& copy); // FIXME: Try to remove this ~Query(); // Conditions: int and bool Query& equal(size_t column_ndx, int64_t value); Query& equal(size_t column_ndx, bool value); Query& not_equal(size_t column_ndx, int64_t value); Query& greater(size_t column_ndx, int64_t value); Query& greater_equal(size_t column_ndx, int64_t value); Query& less(size_t column_ndx, int64_t value); Query& less_equal(size_t column_ndx, int64_t value); Query& between(size_t column_ndx, int64_t from, int64_t to); // Conditions: strings Query& equal(size_t column_ndx, const char* value, bool caseSensitive=true); Query& begins_with(size_t column_ndx, const char* value, bool caseSensitive=true); Query& ends_with(size_t column_ndx, const char* value, bool caseSensitive=true); Query& contains(size_t column_ndx, const char* value, bool caseSensitive=true); Query& not_equal(size_t column_ndx, const char* value, bool caseSensitive=true); // Grouping void group(); void end_group(); void subtable(size_t column); void parent(); void Or(); // Searching size_t find_next(Table& table, size_t lastmatch=-1); TableView find_all(Table& table, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)); void find_all(Table& table, TableView& tv, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)); // Aggregates int64_t sum(const Table& table, size_t column, size_t* resultcount = NULL, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; int64_t maximum(const Table& table, size_t column, size_t* resultcount=NULL, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; int64_t minimum(const Table& table, size_t column, size_t* resultcount=NULL, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; double average(const Table& table, size_t column_ndx, size_t* resultcount = NULL, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; size_t count(const Table& table, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; // Deletion size_t remove(Table& table, size_t start = 0, size_t end = size_t(-1), size_t limit = size_t(-1)) const; // Multi-threading void FindAllMulti(Table& table, TableView& tv, size_t start = 0, size_t end = size_t(-1)); int SetThreads(unsigned int threadcount); std::string Verify(); std::string error_code; protected: friend class XQueryAccessorInt; friend class XQueryAccessorString; void Init(const Table& table) const; size_t FindInternal(const Table& table, size_t start = 0, size_t end = size_t(-1)) const; void UpdatePointers(ParentNode* p, ParentNode** newnode); static bool comp(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b); static void* query_thread(void* arg); struct thread_state { pthread_mutex_t result_mutex; pthread_cond_t completed_cond; pthread_mutex_t completed_mutex; pthread_mutex_t jobs_mutex; pthread_cond_t jobs_cond; size_t next_job; size_t end_job; size_t done_job; size_t count; ParentNode *node; Table *table; std::vector<size_t> results; std::vector<std::pair<size_t, size_t> > chunks; } ts; pthread_t threads[MAX_THREADS]; mutable std::vector<ParentNode*> first; std::vector<ParentNode**> update; std::vector<ParentNode**> update_override; std::vector<ParentNode**> subtables; private: size_t m_threadcount; }; } #endif // __TIGHTDB_QUERY_HPP <commit_msg>Minor style fixes in query.hpp<commit_after>/************************************************************************* * * TIGHTDB CONFIDENTIAL * __________________ * * [2011] - [2012] TightDB Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of TightDB Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to TightDB Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from TightDB Incorporated. * **************************************************************************/ #ifndef __TIGHTDB_QUERY_HPP #define __TIGHTDB_QUERY_HPP #include <string> #include <algorithm> #include <vector> #include <stdio.h> #include <limits.h> #if defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) #include "win32/pthread/pthread.h" #else #include <pthread.h> #endif namespace tightdb { // Pre-declarations class ParentNode; class Table; class TableView; const size_t MAX_THREADS = 128; class Query { public: Query(); Query(const Query& copy); // FIXME: Try to remove this ~Query(); // Conditions: int and bool Query& equal(size_t column_ndx, int64_t value); Query& equal(size_t column_ndx, bool value); Query& not_equal(size_t column_ndx, int64_t value); Query& greater(size_t column_ndx, int64_t value); Query& greater_equal(size_t column_ndx, int64_t value); Query& less(size_t column_ndx, int64_t value); Query& less_equal(size_t column_ndx, int64_t value); Query& between(size_t column_ndx, int64_t from, int64_t to); // Conditions: strings Query& equal(size_t column_ndx, const char* value, bool caseSensitive=true); Query& begins_with(size_t column_ndx, const char* value, bool caseSensitive=true); Query& ends_with(size_t column_ndx, const char* value, bool caseSensitive=true); Query& contains(size_t column_ndx, const char* value, bool caseSensitive=true); Query& not_equal(size_t column_ndx, const char* value, bool caseSensitive=true); // Grouping void group(); void end_group(); void subtable(size_t column); void parent(); void Or(); // Searching size_t find_next(Table& table, size_t lastmatch=-1); TableView find_all(Table& table, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)); void find_all(Table& table, TableView& tv, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)); // Aggregates int64_t sum(const Table& table, size_t column, size_t* resultcount=NULL, size_t start=0, size_t end = size_t(-1), size_t limit=size_t(-1)) const; int64_t maximum(const Table& table, size_t column, size_t* resultcount=NULL, size_t start=0, size_t end = size_t(-1), size_t limit=size_t(-1)) const; int64_t minimum(const Table& table, size_t column, size_t* resultcount=NULL, size_t start=0, size_t end = size_t(-1), size_t limit=size_t(-1)) const; double average(const Table& table, size_t column_ndx, size_t* resultcount=NULL, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)) const; size_t count(const Table& table, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)) const; // Deletion size_t remove(Table& table, size_t start=0, size_t end=size_t(-1), size_t limit=size_t(-1)) const; // Multi-threading void FindAllMulti(Table& table, TableView& tv, size_t start=0, size_t end=size_t(-1)); int SetThreads(unsigned int threadcount); std::string Verify(); std::string error_code; protected: friend class XQueryAccessorInt; friend class XQueryAccessorString; void Init(const Table& table) const; size_t FindInternal(const Table& table, size_t start=0, size_t end=size_t(-1)) const; void UpdatePointers(ParentNode* p, ParentNode** newnode); static bool comp(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b); static void* query_thread(void* arg); struct thread_state { pthread_mutex_t result_mutex; pthread_cond_t completed_cond; pthread_mutex_t completed_mutex; pthread_mutex_t jobs_mutex; pthread_cond_t jobs_cond; size_t next_job; size_t end_job; size_t done_job; size_t count; ParentNode* node; Table* table; std::vector<size_t> results; std::vector<std::pair<size_t, size_t> > chunks; } ts; pthread_t threads[MAX_THREADS]; mutable std::vector<ParentNode*> first; std::vector<ParentNode**> update; std::vector<ParentNode**> update_override; std::vector<ParentNode**> subtables; private: size_t m_threadcount; }; } #endif // __TIGHTDB_QUERY_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 <QtTest/QtTest> #include <QtCore> #include "contextpropertyinfo.h" #include "infobackend.h" QMap <QString, ContextProviderInfo> providerMap; QMap <QString, QString> typeMap; QMap <QString, QString> docMap; /* Mocked infobackend */ InfoBackend* currentBackend = NULL; InfoBackend* InfoBackend::instance(const QString &backendName) { if (currentBackend) return currentBackend; else { currentBackend = new InfoBackend(); return currentBackend; } } QString InfoBackend::typeForKey(QString key) const { if (typeMap.contains(key)) return typeMap.value(key); else return QString(); } QString InfoBackend::docForKey(QString key) const { if (docMap.contains(key)) return docMap.value(key); else return QString(); } bool InfoBackend::keyDeclared(QString key) const { if (typeMap.contains(key)) return true; else return false; } const QList<ContextProviderInfo> InfoBackend::listProviders(QString key) { QList<ContextProviderInfo> lst; if (providerMap.contains(key)) lst << providerMap.value(key, ContextProviderInfo("", "")); return lst; } void InfoBackend::connectNotify(const char *signal) { } void InfoBackend::disconnectNotify(const char *signal) { } void InfoBackend::fireKeysChanged(const QStringList& keys) { emit keysChanged(keys); } void InfoBackend::fireKeysAdded(const QStringList& keys) { emit keysAdded(keys); } void InfoBackend::fireKeysRemoved(const QStringList& keys) { emit keysRemoved(keys); } void InfoBackend::fireKeyChanged(const QString& key) { emit keyChanged(key); } /* ContextRegistryInfoUnitTest */ class ContextPropertyInfoUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void key(); void doc(); void type(); void exists(); void declared(); void provided(); void providerDBusName(); void providerDBusType(); void plugin(); void constructionString(); void typeChanged(); void providerChanged(); void providedChanged(); void pluginChanged(); void dbusTypeChanged(); }; void ContextPropertyInfoUnitTest::initTestCase() { providerMap.clear(); ContextProviderInfo info1("contextkit-dbus", "system:org.freedesktop.ContextKit.contextd"); providerMap.insert("Battery.Charging", info1); ContextProviderInfo info2("contextkit-dbus", "session:com.nokia.musicplayer"); providerMap.insert("Media.NowPlaying", info2); typeMap.clear(); typeMap.insert("Battery.Charging", "TRUTH"); typeMap.insert("Media.NowPlaying", "STRING"); docMap.clear(); docMap.insert("Battery.Charging", "Battery.Charging doc"); docMap.insert("Media.NowPlaying", "Media.NowPlaying doc"); } void ContextPropertyInfoUnitTest::key() { ContextPropertyInfo p("Battery.Charging"); QCOMPARE(p.key(), QString("Battery.Charging")); } void ContextPropertyInfoUnitTest::doc() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.doc(), QString("Battery.Charging doc")); QCOMPARE(p2.doc(), QString("Media.NowPlaying doc")); QCOMPARE(p3.doc(), QString()); } void ContextPropertyInfoUnitTest::type() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.type(), QString("TRUTH")); QCOMPARE(p2.type(), QString("STRING")); QCOMPARE(p3.type(), QString()); } void ContextPropertyInfoUnitTest::exists() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.exists(), true); QCOMPARE(p2.exists(), true); QCOMPARE(p3.exists(), false); } void ContextPropertyInfoUnitTest::declared() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.declared(), true); QCOMPARE(p2.declared(), true); QCOMPARE(p3.declared(), false); } void ContextPropertyInfoUnitTest::provided() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.provided(), true); QCOMPARE(p2.provided(), true); QCOMPARE(p3.provided(), false); } void ContextPropertyInfoUnitTest::providerDBusName() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer")); QCOMPARE(p3.providerDBusName(), QString()); } void ContextPropertyInfoUnitTest::providerDBusType() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus); QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus); QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus); } void ContextPropertyInfoUnitTest::plugin() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.plugin(), QString("contextkit-dbus")); QCOMPARE(p2.plugin(), QString("contextkit-dbus")); QCOMPARE(p3.plugin(), QString()); } void ContextPropertyInfoUnitTest::constructionString() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer")); QCOMPARE(p3.constructionString(), QString()); } void ContextPropertyInfoUnitTest::typeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(typeChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); typeMap.insert("Battery.Charging", "INT"); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("INT")); } void ContextPropertyInfoUnitTest::providerChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providerChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); ContextProviderInfo info("contextkit-dbus", "system:org.freedesktop.ContextKit.robot"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("org.freedesktop.ContextKit.robot")); } void ContextPropertyInfoUnitTest::providedChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providedChanged(bool))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); providerMap.remove("Battery.Charging"); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toBool(), false); } void ContextPropertyInfoUnitTest::pluginChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy1(&p, SIGNAL(pluginChanged(QString, QString))); QSignalSpy spy2(&p, SIGNAL(providerChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy1.count(), 1); spy1.takeFirst(); QCOMPARE(spy2.count(), 1); spy2.takeFirst(); ContextProviderInfo info("test.so", "secret:something"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy1.count(), 1); QList<QVariant> args1 = spy1.takeFirst(); QCOMPARE(args1.at(0).toString(), QString("test.so")); QCOMPARE(args1.at(1).toString(), QString("secret:something")); QCOMPARE(spy2.count(), 1); QList<QVariant> args2 = spy2.takeFirst(); QCOMPARE(args2.at(0).toString(), QString("")); } void ContextPropertyInfoUnitTest::dbusTypeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providerDBusTypeChanged(QDBusConnection::BusType))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); ContextProviderInfo info("contextkit-dbus", "session:org.freedesktop.ContextKit.contextd"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); } #include "contextpropertyinfounittest.moc" QTEST_MAIN(ContextPropertyInfoUnitTest); <commit_msg>Text ::providers() in ContextPropertyInfo.<commit_after>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 <QtTest/QtTest> #include <QtCore> #include "contextpropertyinfo.h" #include "infobackend.h" QMap <QString, ContextProviderInfo> providerMap; QMap <QString, QString> typeMap; QMap <QString, QString> docMap; /* Mocked infobackend */ InfoBackend* currentBackend = NULL; InfoBackend* InfoBackend::instance(const QString &backendName) { if (currentBackend) return currentBackend; else { currentBackend = new InfoBackend(); return currentBackend; } } QString InfoBackend::typeForKey(QString key) const { if (typeMap.contains(key)) return typeMap.value(key); else return QString(); } QString InfoBackend::docForKey(QString key) const { if (docMap.contains(key)) return docMap.value(key); else return QString(); } bool InfoBackend::keyDeclared(QString key) const { if (typeMap.contains(key)) return true; else return false; } const QList<ContextProviderInfo> InfoBackend::listProviders(QString key) { QList<ContextProviderInfo> lst; if (providerMap.contains(key)) lst << providerMap.value(key, ContextProviderInfo("", "")); return lst; } void InfoBackend::connectNotify(const char *signal) { } void InfoBackend::disconnectNotify(const char *signal) { } void InfoBackend::fireKeysChanged(const QStringList& keys) { emit keysChanged(keys); } void InfoBackend::fireKeysAdded(const QStringList& keys) { emit keysAdded(keys); } void InfoBackend::fireKeysRemoved(const QStringList& keys) { emit keysRemoved(keys); } void InfoBackend::fireKeyChanged(const QString& key) { emit keyChanged(key); } /* ContextRegistryInfoUnitTest */ class ContextPropertyInfoUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void key(); void doc(); void type(); void exists(); void declared(); void provided(); void providers(); void providerDBusName(); void providerDBusType(); void plugin(); void constructionString(); void typeChanged(); void providerChanged(); void providedChanged(); void pluginChanged(); void dbusTypeChanged(); }; void ContextPropertyInfoUnitTest::initTestCase() { providerMap.clear(); ContextProviderInfo info1("contextkit-dbus", "system:org.freedesktop.ContextKit.contextd"); providerMap.insert("Battery.Charging", info1); ContextProviderInfo info2("contextkit-dbus", "session:com.nokia.musicplayer"); providerMap.insert("Media.NowPlaying", info2); typeMap.clear(); typeMap.insert("Battery.Charging", "TRUTH"); typeMap.insert("Media.NowPlaying", "STRING"); docMap.clear(); docMap.insert("Battery.Charging", "Battery.Charging doc"); docMap.insert("Media.NowPlaying", "Media.NowPlaying doc"); } void ContextPropertyInfoUnitTest::key() { ContextPropertyInfo p("Battery.Charging"); QCOMPARE(p.key(), QString("Battery.Charging")); } void ContextPropertyInfoUnitTest::doc() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.doc(), QString("Battery.Charging doc")); QCOMPARE(p2.doc(), QString("Media.NowPlaying doc")); QCOMPARE(p3.doc(), QString()); } void ContextPropertyInfoUnitTest::type() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.type(), QString("TRUTH")); QCOMPARE(p2.type(), QString("STRING")); QCOMPARE(p3.type(), QString()); } void ContextPropertyInfoUnitTest::exists() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.exists(), true); QCOMPARE(p2.exists(), true); QCOMPARE(p3.exists(), false); } void ContextPropertyInfoUnitTest::declared() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.declared(), true); QCOMPARE(p2.declared(), true); QCOMPARE(p3.declared(), false); } void ContextPropertyInfoUnitTest::provided() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.provided(), true); QCOMPARE(p2.provided(), true); QCOMPARE(p3.provided(), false); } void ContextPropertyInfoUnitTest::providerDBusName() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusName(), QString("org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.providerDBusName(), QString("com.nokia.musicplayer")); QCOMPARE(p3.providerDBusName(), QString()); } void ContextPropertyInfoUnitTest::providers() { ContextPropertyInfo p("Battery.Charging"); QList<ContextProviderInfo> providers = p.providers(); QCOMPARE(providers.size(), 1); QCOMPARE(providers.at(0).plugin, QString("contextkit-dbus")); QCOMPARE(providers.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd")); } void ContextPropertyInfoUnitTest::providerDBusType() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.providerDBusType(), QDBusConnection::SystemBus); QCOMPARE(p2.providerDBusType(), QDBusConnection::SessionBus); QCOMPARE(p3.providerDBusType(), QDBusConnection::SessionBus); } void ContextPropertyInfoUnitTest::plugin() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.plugin(), QString("contextkit-dbus")); QCOMPARE(p2.plugin(), QString("contextkit-dbus")); QCOMPARE(p3.plugin(), QString()); } void ContextPropertyInfoUnitTest::constructionString() { ContextPropertyInfo p1("Battery.Charging"); ContextPropertyInfo p2("Media.NowPlaying"); ContextPropertyInfo p3("Does.Not.Exist"); QCOMPARE(p1.constructionString(), QString("system:org.freedesktop.ContextKit.contextd")); QCOMPARE(p2.constructionString(), QString("session:com.nokia.musicplayer")); QCOMPARE(p3.constructionString(), QString()); } void ContextPropertyInfoUnitTest::typeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(typeChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); typeMap.insert("Battery.Charging", "INT"); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("INT")); } void ContextPropertyInfoUnitTest::providerChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providerChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); ContextProviderInfo info("contextkit-dbus", "system:org.freedesktop.ContextKit.robot"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), QString("org.freedesktop.ContextKit.robot")); } void ContextPropertyInfoUnitTest::providedChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providedChanged(bool))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); providerMap.remove("Battery.Charging"); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toBool(), false); } void ContextPropertyInfoUnitTest::pluginChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy1(&p, SIGNAL(pluginChanged(QString, QString))); QSignalSpy spy2(&p, SIGNAL(providerChanged(QString))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy1.count(), 1); spy1.takeFirst(); QCOMPARE(spy2.count(), 1); spy2.takeFirst(); ContextProviderInfo info("test.so", "secret:something"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy1.count(), 1); QList<QVariant> args1 = spy1.takeFirst(); QCOMPARE(args1.at(0).toString(), QString("test.so")); QCOMPARE(args1.at(1).toString(), QString("secret:something")); QCOMPARE(spy2.count(), 1); QList<QVariant> args2 = spy2.takeFirst(); QCOMPARE(args2.at(0).toString(), QString("")); } void ContextPropertyInfoUnitTest::dbusTypeChanged() { ContextPropertyInfo p("Battery.Charging"); QSignalSpy spy(&p, SIGNAL(providerDBusTypeChanged(QDBusConnection::BusType))); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); spy.takeFirst(); ContextProviderInfo info("contextkit-dbus", "session:org.freedesktop.ContextKit.contextd"); providerMap.insert("Battery.Charging", info); currentBackend->fireKeyChanged(QString("Battery.Charging")); QCOMPARE(spy.count(), 1); } #include "contextpropertyinfounittest.moc" QTEST_MAIN(ContextPropertyInfoUnitTest); <|endoftext|>
<commit_before><commit_msg>Replace `#include` line with a forward declaration.<commit_after><|endoftext|>
<commit_before>/** * @file raw_time.cpp * */ #include "raw_time.h" #include <mutex> static std::mutex formatMutex; using namespace himan; raw_time::raw_time(const boost::posix_time::ptime& ptime) { itsDateTime = ptime; } raw_time::raw_time(const std::string& theDateTime, const std::string& theTimeMask) { if (theTimeMask == "%Y-%m-%d %H:%M:%S") { FromSQLTime(theDateTime); } else if (theTimeMask == "%Y%m%d%H%M") { FromDatabaseTime(theDateTime); } else { std::stringstream s(theDateTime); { std::lock_guard<std::mutex> lock(formatMutex); s.imbue(std::locale(s.getloc(), new boost::posix_time::time_input_facet(theTimeMask.c_str()))); } s >> itsDateTime; } if (Empty()) { throw std::runtime_error(ClassName() + ": Unable to create time from '" + theDateTime + "' with mask '" + theTimeMask + "'"); } } raw_time::raw_time(const raw_time& other) : itsDateTime(other.itsDateTime) { } raw_time& raw_time::operator=(const raw_time& other) { itsDateTime = other.itsDateTime; return *this; } bool raw_time::operator==(const raw_time& other) const { if (this == &other) { return true; } return (itsDateTime == other.itsDateTime); } bool raw_time::operator!=(const raw_time& other) const { return !(*this == other); } bool raw_time::operator<(const raw_time& other) const { return itsDateTime < other.itsDateTime; } bool raw_time::operator>(const raw_time& other) const { return itsDateTime > other.itsDateTime; } bool raw_time::operator>=(const raw_time& other) const { return itsDateTime >= other.itsDateTime; } bool raw_time::operator<=(const raw_time& other) const { return itsDateTime <= other.itsDateTime; } raw_time::operator std::string() const { return ToDatabaseTime(); } raw_time raw_time::operator+(const time_duration& adjustment) const { return raw_time(itsDateTime + boost::posix_time::minutes(adjustment.Minutes())); } raw_time raw_time::operator-(const time_duration& adjustment) const { return raw_time(itsDateTime - boost::posix_time::minutes(adjustment.Minutes())); } raw_time& raw_time::operator+=(const time_duration& adjustment) { itsDateTime += boost::posix_time::minutes(adjustment.Minutes()); return *this; } raw_time& raw_time::operator-=(const time_duration& adjustment) { itsDateTime -= boost::posix_time::minutes(adjustment.Minutes()); return *this; } time_duration raw_time::operator-(const raw_time& other) const { return time_duration(itsDateTime - other.itsDateTime); } std::string raw_time::String(const std::string& theTimeMask) const { if (Empty()) { return "not_a_date_time"; } if (theTimeMask == "%Y-%m-%d %H:%M:%S") { return ToSQLTime(); } else if (theTimeMask == "%Y%m%d%H%M") { return ToDatabaseTime(); } return FormatTime(theTimeMask); } std::string raw_time::FormatTime(const std::string& theTimeMask) const { std::stringstream s; // https://stackoverflow.com/questions/11121454/c-why-is-my-date-parsing-not-threadsafe { std::lock_guard<std::mutex> lock(formatMutex); s.imbue(std::locale(s.getloc(), new boost::posix_time::time_facet(theTimeMask.c_str()))); } s << itsDateTime; s.flush(); return s.str(); } void raw_time::Adjust(HPTimeResolution timeResolution, int theValue) { using namespace boost; if (timeResolution == kHourResolution) { posix_time::hours adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else if (timeResolution == kMinuteResolution) { posix_time::minutes adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else if (timeResolution == kYearResolution) { boost::gregorian::years adjustment(theValue); itsDateTime += adjustment; if (String("%m%d") == "0229") { itsDateTime += gregorian::date_duration(-1); } } else if (timeResolution == kDayResolution) { gregorian::days adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else { throw std::runtime_error( ClassName() + ": Invalid time adjustment unit: " + std::to_string(static_cast<int>(timeResolution)) + "'"); } } bool raw_time::Empty() const { return (itsDateTime == boost::posix_time::not_a_date_time); } bool raw_time::IsLeapYear() const { return boost::gregorian::gregorian_calendar::is_leap_year(itsDateTime.date().year()); } std::ostream& raw_time::Write(std::ostream& file) const { file << "<" << ClassName() << ">" << std::endl; file << "__itsDateTime__ " << FormatTime("%Y-%m-%d %H:%M:%S") << std::endl; return file; } std::string raw_time::ToDatabaseTime() const { const auto& date = itsDateTime.date(); const auto& time = itsDateTime.time_of_day(); char fmt[13]; if (snprintf(fmt, 13, "%04d%02u%02u%02u%02u", static_cast<int>(date.year()), static_cast<int>(date.month()), static_cast<int>(date.day()), static_cast<int>(time.hours()), static_cast<int>(time.minutes())) < 0) { himan::Abort(); } return std::string(fmt); } void raw_time::FromDatabaseTime(const std::string& databaseTime) { const auto year = static_cast<unsigned short>(stoi(databaseTime.substr(0, 4))); const auto month = static_cast<unsigned short>(stoi(databaseTime.substr(4, 2))); const auto day = static_cast<unsigned short>(stoi(databaseTime.substr(6, 2))); const auto hour = static_cast<unsigned short>(stoi(databaseTime.substr(8, 2))); const auto minute = static_cast<unsigned short>(stoi(databaseTime.substr(10, 2))); using namespace boost; itsDateTime = posix_time::ptime(gregorian::date(year, month, day), posix_time::time_duration(hour, minute, 0, 0)); } std::string raw_time::ToSQLTime() const { const auto& date = itsDateTime.date(); const auto& time = itsDateTime.time_of_day(); char fmt[20]; if (snprintf(fmt, 20, "%04d-%02u-%02u %02u:%02u:%02u", static_cast<int>(date.year()), static_cast<int>(date.month()), static_cast<int>(date.day()), static_cast<int>(time.hours()), static_cast<int>(time.minutes()), static_cast<int>(time.seconds())) < 0) { himan::Abort(); } return std::string(fmt); } void raw_time::FromSQLTime(const std::string& SQLTime) { itsDateTime = boost::posix_time::time_from_string(SQLTime); } <commit_msg>Produce stack trace on erroneus datetime formatting<commit_after>/** * @file raw_time.cpp * */ #include "raw_time.h" #include <mutex> static std::mutex formatMutex; using namespace himan; raw_time::raw_time(const boost::posix_time::ptime& ptime) { itsDateTime = ptime; } raw_time::raw_time(const std::string& theDateTime, const std::string& theTimeMask) { if (theTimeMask == "%Y-%m-%d %H:%M:%S") { FromSQLTime(theDateTime); } else if (theTimeMask == "%Y%m%d%H%M") { FromDatabaseTime(theDateTime); } else { std::stringstream s(theDateTime); { std::lock_guard<std::mutex> lock(formatMutex); s.imbue(std::locale(s.getloc(), new boost::posix_time::time_input_facet(theTimeMask.c_str()))); } s >> itsDateTime; } if (Empty()) { throw std::runtime_error(ClassName() + ": Unable to create time from '" + theDateTime + "' with mask '" + theTimeMask + "'"); } } raw_time::raw_time(const raw_time& other) : itsDateTime(other.itsDateTime) { } raw_time& raw_time::operator=(const raw_time& other) { itsDateTime = other.itsDateTime; return *this; } bool raw_time::operator==(const raw_time& other) const { if (this == &other) { return true; } return (itsDateTime == other.itsDateTime); } bool raw_time::operator!=(const raw_time& other) const { return !(*this == other); } bool raw_time::operator<(const raw_time& other) const { return itsDateTime < other.itsDateTime; } bool raw_time::operator>(const raw_time& other) const { return itsDateTime > other.itsDateTime; } bool raw_time::operator>=(const raw_time& other) const { return itsDateTime >= other.itsDateTime; } bool raw_time::operator<=(const raw_time& other) const { return itsDateTime <= other.itsDateTime; } raw_time::operator std::string() const { return ToDatabaseTime(); } raw_time raw_time::operator+(const time_duration& adjustment) const { return raw_time(itsDateTime + boost::posix_time::minutes(adjustment.Minutes())); } raw_time raw_time::operator-(const time_duration& adjustment) const { return raw_time(itsDateTime - boost::posix_time::minutes(adjustment.Minutes())); } raw_time& raw_time::operator+=(const time_duration& adjustment) { itsDateTime += boost::posix_time::minutes(adjustment.Minutes()); return *this; } raw_time& raw_time::operator-=(const time_duration& adjustment) { itsDateTime -= boost::posix_time::minutes(adjustment.Minutes()); return *this; } time_duration raw_time::operator-(const raw_time& other) const { return time_duration(itsDateTime - other.itsDateTime); } std::string raw_time::String(const std::string& theTimeMask) const { if (Empty()) { return "not_a_date_time"; } if (theTimeMask == "%Y-%m-%d %H:%M:%S") { return ToSQLTime(); } else if (theTimeMask == "%Y%m%d%H%M") { return ToDatabaseTime(); } return FormatTime(theTimeMask); } std::string raw_time::FormatTime(const std::string& theTimeMask) const { std::stringstream s; // https://stackoverflow.com/questions/11121454/c-why-is-my-date-parsing-not-threadsafe { std::lock_guard<std::mutex> lock(formatMutex); s.imbue(std::locale(s.getloc(), new boost::posix_time::time_facet(theTimeMask.c_str()))); } try { s << itsDateTime; } catch (const std::out_of_range& e) { std::cerr << e.what(); himan::Abort(); } s.flush(); return s.str(); } void raw_time::Adjust(HPTimeResolution timeResolution, int theValue) { using namespace boost; if (timeResolution == kHourResolution) { posix_time::hours adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else if (timeResolution == kMinuteResolution) { posix_time::minutes adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else if (timeResolution == kYearResolution) { boost::gregorian::years adjustment(theValue); itsDateTime += adjustment; if (String("%m%d") == "0229") { itsDateTime += gregorian::date_duration(-1); } } else if (timeResolution == kDayResolution) { gregorian::days adjustment(theValue); itsDateTime = itsDateTime + adjustment; } else { throw std::runtime_error( ClassName() + ": Invalid time adjustment unit: " + std::to_string(static_cast<int>(timeResolution)) + "'"); } } bool raw_time::Empty() const { return (itsDateTime == boost::posix_time::not_a_date_time); } bool raw_time::IsLeapYear() const { return boost::gregorian::gregorian_calendar::is_leap_year(itsDateTime.date().year()); } std::ostream& raw_time::Write(std::ostream& file) const { file << "<" << ClassName() << ">" << std::endl; file << "__itsDateTime__ " << FormatTime("%Y-%m-%d %H:%M:%S") << std::endl; return file; } std::string raw_time::ToDatabaseTime() const { const auto& date = itsDateTime.date(); const auto& time = itsDateTime.time_of_day(); char fmt[13]; if (snprintf(fmt, 13, "%04d%02u%02u%02u%02u", static_cast<int>(date.year()), static_cast<int>(date.month()), static_cast<int>(date.day()), static_cast<int>(time.hours()), static_cast<int>(time.minutes())) < 0) { himan::Abort(); } return std::string(fmt); } void raw_time::FromDatabaseTime(const std::string& databaseTime) { const auto year = static_cast<unsigned short>(stoi(databaseTime.substr(0, 4))); const auto month = static_cast<unsigned short>(stoi(databaseTime.substr(4, 2))); const auto day = static_cast<unsigned short>(stoi(databaseTime.substr(6, 2))); const auto hour = static_cast<unsigned short>(stoi(databaseTime.substr(8, 2))); const auto minute = static_cast<unsigned short>(stoi(databaseTime.substr(10, 2))); using namespace boost; itsDateTime = posix_time::ptime(gregorian::date(year, month, day), posix_time::time_duration(hour, minute, 0, 0)); } std::string raw_time::ToSQLTime() const { const auto& date = itsDateTime.date(); const auto& time = itsDateTime.time_of_day(); char fmt[20]; if (snprintf(fmt, 20, "%04d-%02u-%02u %02u:%02u:%02u", static_cast<int>(date.year()), static_cast<int>(date.month()), static_cast<int>(date.day()), static_cast<int>(time.hours()), static_cast<int>(time.minutes()), static_cast<int>(time.seconds())) < 0) { himan::Abort(); } return std::string(fmt); } void raw_time::FromSQLTime(const std::string& SQLTime) { itsDateTime = boost::posix_time::time_from_string(SQLTime); } <|endoftext|>
<commit_before>// Copyright 2022 Google LLC // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <vector> #include "hwy/aligned_allocator.h" #include "hwy/base.h" #include "hwy/print.h" // clang-format off #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "hwy/contrib/algo/find_test.cc" #include "hwy/foreach_target.h" #include "hwy/contrib/algo/find-inl.h" #include "hwy/tests/test_util-inl.h" // clang-format on // If your project requires C++14 or later, you can ignore this and pass lambdas // directly to FindIf, without requiring an lvalue as we do here for C++11. #if __cplusplus < 201402L #define HWY_GENERIC_LAMBDA 0 #else #define HWY_GENERIC_LAMBDA 1 #endif HWY_BEFORE_NAMESPACE(); namespace hwy { namespace HWY_NAMESPACE { // Returns random number in [-8, 8) - we use knowledge of the range to Find() // values we know are not present. template <typename T> T Random(RandomState& rng) { const int32_t bits = static_cast<int32_t>(Random32(&rng)) & 1023; const double val = (bits - 512) / 64.0; // Clamp negative to zero for unsigned types. return static_cast<T>(HWY_MAX(hwy::LowestValue<T>(), val)); } // In C++14, we can instead define these as generic lambdas next to where they // are invoked. #if !HWY_GENERIC_LAMBDA class GreaterThan { public: GreaterThan(float val) : val_(val) {} template <class D, class V> Mask<D> operator()(D d, V v) const { return Gt(v, Set(d, static_cast<TFromD<D>>(val_))); } private: float val_; }; #endif // !HWY_GENERIC_LAMBDA // Invokes Test (e.g. TestFind) with all arg combinations. template <class Test> struct ForeachCountAndMisalign { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) const { RandomState rng; const size_t N = Lanes(d); const size_t misalignments[3] = {0, N / 4, 3 * N / 5}; // Find() checks 8 vectors at a time, so we want to cover a fairly large // range without oversampling (checking every possible count). std::vector<size_t> counts(AdjustedReps(512)); for (size_t& count : counts) { count = rng() % (16 * N + 1); } counts[0] = 0; // ensure we test count=0. for (size_t count : counts) { for (size_t m : misalignments) { Test()(d, count, m, rng); } } } }; struct TestFind { template <class D> void operator()(D d, size_t count, size_t misalign, RandomState& rng) { using T = TFromD<D>; // Must allocate at least one even if count is zero. AlignedFreeUniquePtr<T[]> storage = AllocateAligned<T>(HWY_MAX(1, misalign + count)); T* in = storage.get() + misalign; for (size_t i = 0; i < count; ++i) { in[i] = Random<T>(rng); } // For each position, search for that element (which we know is there) for (size_t pos = 0; pos < count; ++pos) { const size_t actual = Find(d, in[pos], in, count); // We may have found an earlier occurrence of the same value; ensure the // value is the same, and that it is the first. if (!IsEqual(in[pos], in[actual])) { fprintf(stderr, "%s count %d, found %.15f at %d but wanted %.15f\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), static_cast<double>(in[actual]), static_cast<int>(actual), static_cast<double>(in[pos])); HWY_ASSERT(false); } for (size_t i = 0; i < actual; ++i) { if (IsEqual(in[i], in[pos])) { fprintf(stderr, "%s count %d, found %f at %d but Find returned %d\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), static_cast<double>(in[i]), static_cast<int>(i), static_cast<int>(actual)); HWY_ASSERT(false); } } } // Also search for values we know not to be present (out of range) HWY_ASSERT_EQ(count, Find(d, T{9}, in, count)); HWY_ASSERT_EQ(count, Find(d, static_cast<T>(-9), in, count)); } }; void TestAllFind() { ForAllTypes(ForPartialVectors<ForeachCountAndMisalign<TestFind>>()); } struct TestFindIf { template <class D> void operator()(D d, size_t count, size_t misalign, RandomState& rng) { using T = TFromD<D>; // Must allocate at least one even if count is zero. AlignedFreeUniquePtr<T[]> storage = AllocateAligned<T>(HWY_MAX(1, misalign + count)); T* in = storage.get() + misalign; for (size_t i = 0; i < count; ++i) { in[i] = Random<T>(rng); HWY_ASSERT(in[i] < 8 && (!hwy::IsSigned<T>() || in[i] >= -8)); } bool found_any = false; bool not_found_any = false; // unsigned T would be promoted to signed and compare greater than any // negative val, whereas Set() would just cast to an unsigned value and the // comparison remains unsigned, so avoid negative numbers there. const int min_val = IsSigned<T>() ? -9 : 0; // Includes out-of-range value 9 to test the not-found path. for (int val = min_val; val <= 9; ++val) { #if HWY_GENERIC_LAMBDA const auto greater = [val](const auto d, const auto v) HWY_ATTR { return Gt(v, Set(d, static_cast<T>(val))); }; #else const GreaterThan greater(val); #endif const size_t actual = FindIf(d, in, count, greater); found_any |= actual < count; not_found_any |= actual == count; // Convert returned iterator to index. const size_t expected = static_cast<size_t>( std::find_if(in, in + count, [val](T x) { return x > val; }) - in); if (expected != actual) { fprintf(stderr, "%s count %d val %d, expected %d actual %d\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), val, static_cast<int>(expected), static_cast<int>(actual)); hwy::detail::PrintArray(hwy::detail::MakeTypeInfo<T>(), "in", in, count, 0, count); HWY_ASSERT(false); } } // We will always not-find something due to val=9. HWY_ASSERT(not_found_any); // We'll find something unless the input is empty or {0} - because 0 > i // is false for all i=[0,9]. if (count != 0 && in[0] != 0) { HWY_ASSERT(found_any); } } }; void TestAllFindIf() { ForAllTypes(ForPartialVectors<ForeachCountAndMisalign<TestFindIf>>()); } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace hwy HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace hwy { HWY_BEFORE_TEST(FindTest); HWY_EXPORT_AND_TEST_P(FindTest, TestAllFind); HWY_EXPORT_AND_TEST_P(FindTest, TestAllFindIf); } // namespace hwy #endif <commit_msg>fix warning (cast)<commit_after>// Copyright 2022 Google LLC // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <vector> #include "hwy/aligned_allocator.h" #include "hwy/base.h" #include "hwy/print.h" // clang-format off #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "hwy/contrib/algo/find_test.cc" #include "hwy/foreach_target.h" #include "hwy/contrib/algo/find-inl.h" #include "hwy/tests/test_util-inl.h" // clang-format on // If your project requires C++14 or later, you can ignore this and pass lambdas // directly to FindIf, without requiring an lvalue as we do here for C++11. #if __cplusplus < 201402L #define HWY_GENERIC_LAMBDA 0 #else #define HWY_GENERIC_LAMBDA 1 #endif HWY_BEFORE_NAMESPACE(); namespace hwy { namespace HWY_NAMESPACE { // Returns random number in [-8, 8) - we use knowledge of the range to Find() // values we know are not present. template <typename T> T Random(RandomState& rng) { const int32_t bits = static_cast<int32_t>(Random32(&rng)) & 1023; const double val = (bits - 512) / 64.0; // Clamp negative to zero for unsigned types. return static_cast<T>(HWY_MAX(hwy::LowestValue<T>(), val)); } // In C++14, we can instead define these as generic lambdas next to where they // are invoked. #if !HWY_GENERIC_LAMBDA class GreaterThan { public: GreaterThan(float val) : val_(val) {} template <class D, class V> Mask<D> operator()(D d, V v) const { return Gt(v, Set(d, static_cast<TFromD<D>>(val_))); } private: float val_; }; #endif // !HWY_GENERIC_LAMBDA // Invokes Test (e.g. TestFind) with all arg combinations. template <class Test> struct ForeachCountAndMisalign { template <typename T, class D> HWY_NOINLINE void operator()(T /*unused*/, D d) const { RandomState rng; const size_t N = Lanes(d); const size_t misalignments[3] = {0, N / 4, 3 * N / 5}; // Find() checks 8 vectors at a time, so we want to cover a fairly large // range without oversampling (checking every possible count). std::vector<size_t> counts(AdjustedReps(512)); for (size_t& count : counts) { count = rng() % (16 * N + 1); } counts[0] = 0; // ensure we test count=0. for (size_t count : counts) { for (size_t m : misalignments) { Test()(d, count, m, rng); } } } }; struct TestFind { template <class D> void operator()(D d, size_t count, size_t misalign, RandomState& rng) { using T = TFromD<D>; // Must allocate at least one even if count is zero. AlignedFreeUniquePtr<T[]> storage = AllocateAligned<T>(HWY_MAX(1, misalign + count)); T* in = storage.get() + misalign; for (size_t i = 0; i < count; ++i) { in[i] = Random<T>(rng); } // For each position, search for that element (which we know is there) for (size_t pos = 0; pos < count; ++pos) { const size_t actual = Find(d, in[pos], in, count); // We may have found an earlier occurrence of the same value; ensure the // value is the same, and that it is the first. if (!IsEqual(in[pos], in[actual])) { fprintf(stderr, "%s count %d, found %.15f at %d but wanted %.15f\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), static_cast<double>(in[actual]), static_cast<int>(actual), static_cast<double>(in[pos])); HWY_ASSERT(false); } for (size_t i = 0; i < actual; ++i) { if (IsEqual(in[i], in[pos])) { fprintf(stderr, "%s count %d, found %f at %d but Find returned %d\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), static_cast<double>(in[i]), static_cast<int>(i), static_cast<int>(actual)); HWY_ASSERT(false); } } } // Also search for values we know not to be present (out of range) HWY_ASSERT_EQ(count, Find(d, T{9}, in, count)); HWY_ASSERT_EQ(count, Find(d, static_cast<T>(-9), in, count)); } }; void TestAllFind() { ForAllTypes(ForPartialVectors<ForeachCountAndMisalign<TestFind>>()); } struct TestFindIf { template <class D> void operator()(D d, size_t count, size_t misalign, RandomState& rng) { using T = TFromD<D>; // Must allocate at least one even if count is zero. AlignedFreeUniquePtr<T[]> storage = AllocateAligned<T>(HWY_MAX(1, misalign + count)); T* in = storage.get() + misalign; for (size_t i = 0; i < count; ++i) { in[i] = Random<T>(rng); HWY_ASSERT(in[i] < 8 && (!hwy::IsSigned<T>() || in[i] >= -8)); } bool found_any = false; bool not_found_any = false; // unsigned T would be promoted to signed and compare greater than any // negative val, whereas Set() would just cast to an unsigned value and the // comparison remains unsigned, so avoid negative numbers there. const int min_val = IsSigned<T>() ? -9 : 0; // Includes out-of-range value 9 to test the not-found path. for (int val = min_val; val <= 9; ++val) { #if HWY_GENERIC_LAMBDA const auto greater = [val](const auto d, const auto v) HWY_ATTR { return Gt(v, Set(d, static_cast<T>(val))); }; #else const GreaterThan greater(val); #endif const size_t actual = FindIf(d, in, count, greater); found_any |= actual < count; not_found_any |= actual == count; const auto pos = std::find_if( in, in + count, [val](T x) { return x > static_cast<T>(val); }); // Convert returned iterator to index. const size_t expected = static_cast<size_t>(pos - in); if (expected != actual) { fprintf(stderr, "%s count %d val %d, expected %d actual %d\n", hwy::TypeName(T(), Lanes(d)).c_str(), static_cast<int>(count), val, static_cast<int>(expected), static_cast<int>(actual)); hwy::detail::PrintArray(hwy::detail::MakeTypeInfo<T>(), "in", in, count, 0, count); HWY_ASSERT(false); } } // We will always not-find something due to val=9. HWY_ASSERT(not_found_any); // We'll find something unless the input is empty or {0} - because 0 > i // is false for all i=[0,9]. if (count != 0 && in[0] != 0) { HWY_ASSERT(found_any); } } }; void TestAllFindIf() { ForAllTypes(ForPartialVectors<ForeachCountAndMisalign<TestFindIf>>()); } // NOLINTNEXTLINE(google-readability-namespace-comments) } // namespace HWY_NAMESPACE } // namespace hwy HWY_AFTER_NAMESPACE(); #if HWY_ONCE namespace hwy { HWY_BEFORE_TEST(FindTest); HWY_EXPORT_AND_TEST_P(FindTest, TestAllFind); HWY_EXPORT_AND_TEST_P(FindTest, TestAllFindIf); } // namespace hwy #endif <|endoftext|>
<commit_before>// Copyright (c) 2011, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // POSIX #include <netinet/in.h> #include <signal.h> #include <sys/socket.h> // Google Log #include <glog/logging.h> // po6 #include <po6/net/location.h> // HyperDex #include <hyperdex/network_constants.h> // HyperDaemon #include "datalayer.h" #include "logical.h" #include "network_worker.h" #include "replication_manager.h" #include "searches.h" using hyperdex::entityid; using hyperdex::network_msgtype; using hyperdex::network_returncode; hyperdaemon :: network_worker :: network_worker(datalayer* data, logical* comm, searches* ssss, replication_manager* repl) : m_continue(true) , m_data(data) , m_comm(comm) , m_ssss(ssss) , m_repl(repl) { } hyperdaemon :: network_worker :: ~network_worker() { if (m_continue) { m_continue = false; LOG(INFO) << "Network worker object not cleanly shutdown."; } } void hyperdaemon :: network_worker :: run() { sigset_t ss; if (sigfillset(&ss) < 0) { PLOG(ERROR) << "sigfillset"; return; } if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) { PLOG(ERROR) << "pthread_sigmask"; return; } entityid from; entityid to; network_msgtype type; e::buffer msg; uint32_t nonce; while (m_continue && m_comm->recv(&from, &to, &type, &msg)) { try { if (type == hyperdex::REQ_GET) { e::buffer key; std::vector<e::buffer> value; uint64_t version; e::unpacker up(msg.unpack()); up >> nonce; up.leftovers(&key); network_returncode result; switch (m_data->get(to.get_region(), key, &value, &version)) { case hyperdisk::SUCCESS: result = hyperdex::NET_SUCCESS; break; case hyperdisk::NOTFOUND: result = hyperdex::NET_NOTFOUND; break; case hyperdisk::WRONGARITY: result = hyperdex::NET_WRONGARITY; break; case hyperdisk::MISSINGDISK: LOG(ERROR) << "GET caused a MISSINGDISK at the data layer."; result = hyperdex::NET_SERVERERROR; break; case hyperdisk::HASHFULL: case hyperdisk::DATAFULL: case hyperdisk::SEARCHFULL: case hyperdisk::SYNCFAILED: case hyperdisk::DROPFAILED: default: LOG(ERROR) << "GET returned unacceptable error code."; result = hyperdex::NET_SERVERERROR; break; } msg.clear(); msg.pack() << nonce << static_cast<uint16_t>(result) << value; m_comm->send(to, from, hyperdex::RESP_GET, msg); } else if (type == hyperdex::REQ_PUT) { e::buffer key; std::vector<e::buffer> value; msg.unpack() >> nonce >> key >> value; m_repl->client_put(from, to.get_region(), nonce, key, value); } else if (type == hyperdex::REQ_DEL) { e::buffer key; e::unpacker up(msg.unpack()); up >> nonce; up.leftovers(&key); m_repl->client_del(from, to.get_region(), nonce, key); } else if (type == hyperdex::REQ_UPDATE) { e::buffer key; e::bitfield value_mask(0); // This will resize on unpack std::vector<e::buffer> value; msg.unpack() >> nonce >> key >> value_mask >> value; m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value); } else if (type == hyperdex::REQ_SEARCH_START) { hyperdex::search s; msg.unpack() >> nonce >> s; m_ssss->start(from, nonce, to.get_region(), s); } else if (type == hyperdex::REQ_SEARCH_NEXT) { msg.unpack() >> nonce; m_ssss->next(from, nonce); } else if (type == hyperdex::REQ_SEARCH_STOP) { msg.unpack() >> nonce; m_ssss->stop(from, nonce); } else if (type == hyperdex::CHAIN_PUT) { e::buffer key; std::vector<e::buffer> value; uint64_t version; uint8_t fresh; msg.unpack() >> version >> fresh >> key >> value; m_repl->chain_put(from, to, version, fresh == 1, key, value); } else if (type == hyperdex::CHAIN_DEL) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_del(from, to, version, key); } else if (type == hyperdex::CHAIN_PENDING) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_pending(from, to, version, key); } else if (type == hyperdex::CHAIN_SUBSPACE) { uint64_t version; e::buffer key; std::vector<e::buffer> value; uint64_t nextpoint; msg.unpack() >> version >> key >> value >> nextpoint; m_repl->chain_subspace(from, to, version, key, value, nextpoint); } else if (type == hyperdex::CHAIN_ACK) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_ack(from, to, version, key); } else if (type == hyperdex::XFER_MORE) { m_repl->region_transfer(from, to); } else if (type == hyperdex::XFER_DONE) { m_repl->region_transfer_done(from, to); } else if (type == hyperdex::XFER_DATA) { uint64_t xfer_num; uint8_t op; uint64_t version; e::buffer key; std::vector<e::buffer> value; msg.unpack() >> xfer_num >> op >> version >> key >> value; m_repl->region_transfer(from, to.subspace, xfer_num, op == 1, version, key, value); } else { LOG(INFO) << "Message of unknown type received."; } } catch (std::out_of_range& e) { // Unpack error } } } void hyperdaemon :: network_worker :: shutdown() { // TODO: This is not the proper shutdown method. Proper shutdown is a // two-stage process, and requires global coordination. m_continue = false; } <commit_msg>Trickle data when handling network messages.<commit_after>// Copyright (c) 2011, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // POSIX #include <netinet/in.h> #include <signal.h> #include <sys/socket.h> // Google Log #include <glog/logging.h> // po6 #include <po6/net/location.h> // HyperDex #include <hyperdex/network_constants.h> // HyperDaemon #include "datalayer.h" #include "logical.h" #include "network_worker.h" #include "replication_manager.h" #include "searches.h" using hyperdex::entityid; using hyperdex::network_msgtype; using hyperdex::network_returncode; hyperdaemon :: network_worker :: network_worker(datalayer* data, logical* comm, searches* ssss, replication_manager* repl) : m_continue(true) , m_data(data) , m_comm(comm) , m_ssss(ssss) , m_repl(repl) { } hyperdaemon :: network_worker :: ~network_worker() { if (m_continue) { m_continue = false; LOG(INFO) << "Network worker object not cleanly shutdown."; } } void hyperdaemon :: network_worker :: run() { sigset_t ss; if (sigfillset(&ss) < 0) { PLOG(ERROR) << "sigfillset"; return; } if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) { PLOG(ERROR) << "pthread_sigmask"; return; } entityid from; entityid to; network_msgtype type; e::buffer msg; uint32_t nonce; while (m_continue && m_comm->recv(&from, &to, &type, &msg)) { try { if (type == hyperdex::REQ_GET) { e::buffer key; std::vector<e::buffer> value; uint64_t version; e::unpacker up(msg.unpack()); up >> nonce; up.leftovers(&key); network_returncode result; switch (m_data->get(to.get_region(), key, &value, &version)) { case hyperdisk::SUCCESS: result = hyperdex::NET_SUCCESS; break; case hyperdisk::NOTFOUND: result = hyperdex::NET_NOTFOUND; break; case hyperdisk::WRONGARITY: result = hyperdex::NET_WRONGARITY; break; case hyperdisk::MISSINGDISK: LOG(ERROR) << "GET caused a MISSINGDISK at the data layer."; result = hyperdex::NET_SERVERERROR; break; case hyperdisk::HASHFULL: case hyperdisk::DATAFULL: case hyperdisk::SEARCHFULL: case hyperdisk::SYNCFAILED: case hyperdisk::DROPFAILED: default: LOG(ERROR) << "GET returned unacceptable error code."; result = hyperdex::NET_SERVERERROR; break; } msg.clear(); msg.pack() << nonce << static_cast<uint16_t>(result) << value; m_comm->send(to, from, hyperdex::RESP_GET, msg); } else if (type == hyperdex::REQ_PUT) { e::buffer key; std::vector<e::buffer> value; msg.unpack() >> nonce >> key >> value; m_repl->client_put(from, to.get_region(), nonce, key, value); } else if (type == hyperdex::REQ_DEL) { e::buffer key; e::unpacker up(msg.unpack()); up >> nonce; up.leftovers(&key); m_repl->client_del(from, to.get_region(), nonce, key); } else if (type == hyperdex::REQ_UPDATE) { e::buffer key; e::bitfield value_mask(0); // This will resize on unpack std::vector<e::buffer> value; msg.unpack() >> nonce >> key >> value_mask >> value; m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value); } else if (type == hyperdex::REQ_SEARCH_START) { hyperdex::search s; msg.unpack() >> nonce >> s; m_ssss->start(from, nonce, to.get_region(), s); } else if (type == hyperdex::REQ_SEARCH_NEXT) { msg.unpack() >> nonce; m_ssss->next(from, nonce); } else if (type == hyperdex::REQ_SEARCH_STOP) { msg.unpack() >> nonce; m_ssss->stop(from, nonce); } else if (type == hyperdex::CHAIN_PUT) { e::buffer key; std::vector<e::buffer> value; uint64_t version; uint8_t fresh; msg.unpack() >> version >> fresh >> key >> value; m_repl->chain_put(from, to, version, fresh == 1, key, value); } else if (type == hyperdex::CHAIN_DEL) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_del(from, to, version, key); } else if (type == hyperdex::CHAIN_PENDING) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_pending(from, to, version, key); } else if (type == hyperdex::CHAIN_SUBSPACE) { uint64_t version; e::buffer key; std::vector<e::buffer> value; uint64_t nextpoint; msg.unpack() >> version >> key >> value >> nextpoint; m_repl->chain_subspace(from, to, version, key, value, nextpoint); } else if (type == hyperdex::CHAIN_ACK) { e::buffer key; uint64_t version; msg.unpack() >> version >> key; m_repl->chain_ack(from, to, version, key); } else if (type == hyperdex::XFER_MORE) { m_repl->region_transfer(from, to); } else if (type == hyperdex::XFER_DONE) { m_repl->region_transfer_done(from, to); } else if (type == hyperdex::XFER_DATA) { uint64_t xfer_num; uint8_t op; uint64_t version; e::buffer key; std::vector<e::buffer> value; msg.unpack() >> xfer_num >> op >> version >> key >> value; m_repl->region_transfer(from, to.subspace, xfer_num, op == 1, version, key, value); } else { LOG(INFO) << "Message of unknown type received."; } m_data->trickle(to.get_region()); } catch (std::out_of_range& e) { // Unpack error } } } void hyperdaemon :: network_worker :: shutdown() { // TODO: This is not the proper shutdown method. Proper shutdown is a // two-stage process, and requires global coordination. m_continue = false; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/video/video.hpp> #include <pthread.h> #include <geometry_msgs/Point.h> static const std::string RGB_WINDOW_NAME = "RGB image"; static const std::string DEPTH_WINDOW_NAME = "Depth image"; class SearchTomato { public: SearchTomato() : found_flag(false) , tick_count(0) , last_tick_count(0) , not_founding_count(0) , kf(6, 4, 0, CV_32F) , state(6, 1, CV_32F) { init_set_kalman(kf); } ~SearchTomato() {} bool searchTomatoPoint(const cv::Mat& capture_rgb, cv::Point& tomato_point) { cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1); std::vector<cv::Rect> tomato_boxs; // reset transition matrix of kalman filter. tick_count = cv::getTickCount(); double d_time = (tick_count - last_tick_count) / cv::getTickFrequency(); // d_time: infinitesimal difference of time. kf.transitionMatrix.at<float>(2) = d_time; // x = x + dt*vx kf.transitionMatrix.at<float>(9) = d_time; // y = y + dt*vy last_tick_count = tick_count; // image processing and seach box for tomato imageProcessing(capture_rgb, binary_mat); imshow(DEPTH_WINDOW_NAME, binary_mat); searchTomatoBox(binary_mat, tomato_boxs); printf("search box num is %lu", tomato_boxs.size()); if (tomato_boxs.size() > 0) { not_founding_count = 0; if (!found_flag) { resetKalman(); found_flag = true; } else applyKalman(tomato_boxs); } else if (++not_founding_count > 10) { not_founding_count = 10; found_flag = false; } // set point of tomato state = kf.predict(); tomato_point.x = state.at<float>(0); tomato_point.y = state.at<float>(1); return found_flag; } private: void init_set_kalman(cv::KalmanFilter& kf) { // transition state matrix(A). think for [x, y, vx, vy, width, height]. identiry mean state is static. cv::setIdentity(kf.transitionMatrix); // NOTE: set state of speed at each step! // measurement matrix(H). mean look to only [x, y, width, height]. kf.measurementMatrix = cv::Mat::zeros(4, 6, CV_32F); kf.measurementMatrix.at<float>(0) = 1.0f; kf.measurementMatrix.at<float>(7) = 1.0f; kf.measurementMatrix.at<float>(16) = 1.0f; kf.measurementMatrix.at<float>(23) = 1.0f; // process noise covariance matrix(Q). all state have noise is 5e-2; cv::setIdentity(kf.processNoiseCov, cv::Scalar(5e-2)); } void imageProcessing(const cv::Mat& rgb, cv::Mat& binary_mat) { cv::Mat blur, hsv; cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 3.0, 3.0); cv::cvtColor(blur, hsv, CV_BGR2HSV); redFilter(hsv, binary_mat); cv::erode(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 3); cv::dilate(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 5); cv::erode(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 3); } void redFilter(cv::Mat& hsv, cv::Mat& binary_mat) { int a, x, y; for(y = 0; y < hsv.rows; y++) { for(x = 0; x < hsv.cols; x++) { a = hsv.step*y+(x*3); if((hsv.data[a] <= 5 || hsv.data[a] >= 175) && hsv.data[a+1] >= 50 && hsv.data[a+2] >= 50 ) binary_mat.at<unsigned char>(y,x) = 255; else binary_mat.at<unsigned char>(y,x) = 0; } } } void searchTomatoBox(cv::Mat& binary_mat, std::vector<cv::Rect>& tomato_boxs) { std::vector<std::vector<cv::Point> > contours; cv::findContours(binary_mat, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); findMatchTomato(contours, tomato_boxs); } void findMatchTomato(std::vector<std::vector<cv::Point> >& contours, std::vector<cv::Rect>& tomato_boxs) { cv::Rect bounding_box; for (unsigned int i = 0; i < contours.size(); i++) { bounding_box = cv::boundingRect(contours[i]); float ratio_balance = (float)bounding_box.width / (float)bounding_box.height; if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance; // delete mismach. that is smaller or spier if (bounding_box.area() >= 500 && bounding_box.area() < 2*cv::contourArea(contours[i]) && ratio_balance > 0.4f) tomato_boxs.push_back(bounding_box); } } void applyKalman(std::vector<cv::Rect>& tomato_boxs) { cv::Mat meas(4, 1, CV_32F); int i = findIndexPlausible(tomato_boxs); meas.at<float>(0) = tomato_boxs[i].x + tomato_boxs[i].width/2; meas.at<float>(1) = tomato_boxs[i].y + tomato_boxs[i].height/2; meas.at<float>(2) = tomato_boxs[i].width; meas.at<float>(3) = tomato_boxs[i].height; kf.correct(meas); } int findIndexPlausible(std::vector<cv::Rect>& tomato_boxs) { int index = 0; unsigned int worst_non_likelihood = 0xffff; unsigned int non_likelihood; for (int i = 0; i < tomato_boxs.size(); i++) { state = kf.predict(); non_likelihood = 0; non_likelihood += abs(tomato_boxs[i].x - state.at<float>(0)); non_likelihood += abs(tomato_boxs[i].y - state.at<float>(1)); non_likelihood += abs(tomato_boxs[i].width - state.at<float>(4)); non_likelihood += abs(tomato_boxs[i].height - state.at<float>(5)); if (worst_non_likelihood > non_likelihood) { worst_non_likelihood = non_likelihood; index = i; } } return index; } void resetKalman() { kf.errorCovPre.at<float>(0) = 1; // px kf.errorCovPre.at<float>(7) = 1; // px kf.errorCovPre.at<float>(14) = 1; kf.errorCovPre.at<float>(21) = 1; kf.errorCovPre.at<float>(28) = 1; // px kf.errorCovPre.at<float>(35) = 1; // px } bool found_flag; long tick_count, last_tick_count; // count while running. unsigned int not_founding_count; cv::KalmanFilter kf; cv::Mat state; }; class ImageConverter { private: ros::NodeHandle nh; ros::Publisher point_pub; image_transport::ImageTransport it; image_transport::Subscriber rgb_sub; image_transport::Subscriber depth_sub; cv_bridge::CvImageConstPtr rgb_ptr; cv_bridge::CvImageConstPtr depth_ptr; SearchTomato searchTomatoObj; cv::Point tomato_point; bool found_flag; geometry_msgs::Point pub_msg; public: ImageConverter() : it(nh) , searchTomatoObj() , tomato_point(-1, -1) , found_flag(false) { // subscrive to input video feed. point_pub = nh.advertise<geometry_msgs::Point>("tomato_point", 1); rgb_sub = it.subscribe("/camera/rgb/image_raw", 1, &ImageConverter::rgbCb, this); depth_sub = it.subscribe("/camera/depth_registered/image_raw", 1, &ImageConverter::depthCb, this); } ~ImageConverter() {} /** * search tomato function. * get rgb image, and search tomato. * will tomato_point have data. * * @author Yusuke Doi */ void rgbCb(const sensor_msgs::ImageConstPtr& msg) { // get rgb image on kinect try { rgb_ptr = cv_bridge::toCvShare(msg, "bgr8"); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception by rgb: %s", e.what()); } cv::Mat buf = rgb_ptr->image.clone(); // search tomato if (found_flag = searchTomatoObj.searchTomatoPoint(rgb_ptr->image, tomato_point)) cv::circle(buf, tomato_point, 2, CV_RGB(0, 255, 0), -1); cv::imshow(RGB_WINDOW_NAME, buf); cv::waitKey(100); } void depthCb(const sensor_msgs::ImageConstPtr& msg) { try { depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception by depth: %s", e.what()); } //testShowDepth(depth_ptr->image); if (found_flag) { printf("depth is %u", depth_ptr->image.at<uint16_t>(tomato_point)); // pub_msg.x = tomato_point.x; // pub_msg.y = tomato_point.y; // pub_msg.z = depth_ptr->image.at<uint16_t>(tomato_point); pub_msg.x = depth_ptr->image.at<uint16_t>(tomato_point); pub_msg.y = tomato_point.x; pub_msg.z = -tomato_point.y; point_pub.publish(pub_msg); } cv::waitKey(100); } void testShowDepth(const cv::Mat& depth) { static std::vector<uint16_t> m_gamma(2048); static bool firstFlag(false); if (!firstFlag) { for(unsigned int i = 0; i < 2048; i++) { float v = i/2048.0; v = std::pow(v, 3) * 6; m_gamma[i] = v*6*256; } firstFlag = true; } int i; cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1); cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3); cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX); for (i = 0; i < depth.rows * depth.cols; i++) { int y = (int)(i / depth.cols); int x = (int)(i % depth.cols); int pval = m_gamma[buf.at<uint16_t>(i)]; int lb = pval & 0xff; switch(pval >> 8) { case 0: output.at<cv::Vec3b>(y,x)[2] = 255; output.at<cv::Vec3b>(y,x)[1] = 255-lb; output.at<cv::Vec3b>(y,x)[0] = 255-lb; break; case 1: output.at<cv::Vec3b>(y,x)[2] = 255; output.at<cv::Vec3b>(y,x)[1] = lb; output.at<cv::Vec3b>(y,x)[0] = 0; break; case 2: output.at<cv::Vec3b>(y,x)[2] = 255-lb; output.at<cv::Vec3b>(y,x)[1] = 255; output.at<cv::Vec3b>(y,x)[0] = 0; break; case 3: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 255; output.at<cv::Vec3b>(y,x)[0] = lb; break; case 4: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 255-lb; output.at<cv::Vec3b>(y,x)[0] = 255; break; case 5: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 0; output.at<cv::Vec3b>(y,x)[0] = 255-lb; break; default: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 0; output.at<cv::Vec3b>(y,x)[0] = 0; break; } } imshow(DEPTH_WINDOW_NAME, output); } }; int main(int argc, char** argv) { ros::init(argc, argv, "kinect_tomato_search_node"); ImageConverter ic; cv::namedWindow(RGB_WINDOW_NAME); cv::namedWindow(DEPTH_WINDOW_NAME); ros::spin(); cv::destroyWindow(RGB_WINDOW_NAME); cv::destroyWindow(DEPTH_WINDOW_NAME); return 0; } <commit_msg>Fix verbose code @kinect_tomato_searcher<commit_after>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/video/video.hpp> #include <pthread.h> #include <geometry_msgs/Point.h> static const std::string RGB_WINDOW_NAME = "RGB image"; static const std::string DEPTH_WINDOW_NAME = "Depth image"; class SearchTomato { public: SearchTomato() : found_flag(false) , tick_count(0) , last_tick_count(0) , not_founding_count(0) , kf(6, 4, 0, CV_32F) , state(6, 1, CV_32F) { init_set_kalman(kf); } ~SearchTomato() {} bool searchTomatoPoint(const cv::Mat& capture_rgb, cv::Point& tomato_point) { cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1); std::vector<cv::Rect> tomato_boxs; // reset transition matrix of kalman filter. tick_count = cv::getTickCount(); double d_time = (tick_count - last_tick_count) / cv::getTickFrequency(); // d_time: infinitesimal difference of time. kf.transitionMatrix.at<float>(2) = d_time; // x = x + dt*vx kf.transitionMatrix.at<float>(9) = d_time; // y = y + dt*vy last_tick_count = tick_count; // image processing and seach box for tomato imageProcessing(capture_rgb, binary_mat); imshow(DEPTH_WINDOW_NAME, binary_mat); searchTomatoBox(binary_mat, tomato_boxs); printf("search box num is %lu", tomato_boxs.size()); if (tomato_boxs.size() > 0) { not_founding_count = 0; if (!found_flag) { resetKalman(); found_flag = true; } else applyKalman(tomato_boxs); } else if (++not_founding_count > 10) { not_founding_count = 10; found_flag = false; } // set point of tomato state = kf.predict(); tomato_point.x = state.at<float>(0); tomato_point.y = state.at<float>(1); return found_flag; } private: void init_set_kalman(cv::KalmanFilter& kf) { // transition state matrix(A). think for [x, y, vx, vy, width, height]. identiry mean state is static. cv::setIdentity(kf.transitionMatrix); // NOTE: set state of speed at each step! // measurement matrix(H). mean look to only [x, y, width, height]. kf.measurementMatrix = cv::Mat::zeros(4, 6, CV_32F); kf.measurementMatrix.at<float>(0) = 1.0f; kf.measurementMatrix.at<float>(7) = 1.0f; kf.measurementMatrix.at<float>(16) = 1.0f; kf.measurementMatrix.at<float>(23) = 1.0f; // process noise covariance matrix(Q). all state have noise is 5e-2; cv::setIdentity(kf.processNoiseCov, cv::Scalar(5e-2)); } void imageProcessing(const cv::Mat& rgb, cv::Mat& binary_mat) { cv::Mat blur, hsv; cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 3.0, 3.0); cv::cvtColor(blur, hsv, CV_BGR2HSV); redFilter(hsv, binary_mat); cv::erode(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 3); cv::dilate(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 5); cv::erode(binary_mat, binary_mat, cv::Mat(), cv::Point(-1, -1), 3); } void redFilter(cv::Mat& hsv, cv::Mat& binary_mat) { int a, x, y; for(y = 0; y < hsv.rows; y++) { for(x = 0; x < hsv.cols; x++) { a = hsv.step*y+(x*3); if((hsv.data[a] <= 5 || hsv.data[a] >= 175) && hsv.data[a+1] >= 50 && hsv.data[a+2] >= 50 ) binary_mat.at<unsigned char>(y,x) = 255; else binary_mat.at<unsigned char>(y,x) = 0; } } } void searchTomatoBox(cv::Mat& binary_mat, std::vector<cv::Rect>& tomato_boxs) { std::vector<std::vector<cv::Point> > contours; cv::findContours(binary_mat, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); findMatchTomato(contours, tomato_boxs); } void findMatchTomato(std::vector<std::vector<cv::Point> >& contours, std::vector<cv::Rect>& tomato_boxs) { cv::Rect bounding_box; for (unsigned int i = 0; i < contours.size(); i++) { bounding_box = cv::boundingRect(contours[i]); float ratio_balance = (float)bounding_box.width / (float)bounding_box.height; if (ratio_balance > 1.0f) ratio_balance = 1.0f / ratio_balance; // delete mismach. that is smaller or spier if (bounding_box.area() >= 500 && bounding_box.area() < 2*cv::contourArea(contours[i]) && ratio_balance > 0.4f) tomato_boxs.push_back(bounding_box); } } void applyKalman(std::vector<cv::Rect>& tomato_boxs) { cv::Mat meas(4, 1, CV_32F); int i = findIndexPlausible(tomato_boxs); meas.at<float>(0) = tomato_boxs[i].x + tomato_boxs[i].width/2; meas.at<float>(1) = tomato_boxs[i].y + tomato_boxs[i].height/2; meas.at<float>(2) = tomato_boxs[i].width; meas.at<float>(3) = tomato_boxs[i].height; kf.correct(meas); } int findIndexPlausible(std::vector<cv::Rect>& tomato_boxs) { int index = 0; unsigned int worst_non_likelihood = 0xffff; unsigned int non_likelihood; for (int i = 0; i < tomato_boxs.size(); i++) { state = kf.predict(); non_likelihood = 0; non_likelihood += abs(tomato_boxs[i].x - state.at<float>(0)); non_likelihood += abs(tomato_boxs[i].y - state.at<float>(1)); non_likelihood += abs(tomato_boxs[i].width - state.at<float>(4)); non_likelihood += abs(tomato_boxs[i].height - state.at<float>(5)); if (worst_non_likelihood > non_likelihood) { worst_non_likelihood = non_likelihood; index = i; } } return index; } void resetKalman() { // kf.errorCovPre.at<float>(0) = 1; // px // kf.errorCovPre.at<float>(7) = 1; // px // kf.errorCovPre.at<float>(14) = 1; // kf.errorCovPre.at<float>(21) = 1; // kf.errorCovPre.at<float>(28) = 1; // px // kf.errorCovPre.at<float>(35) = 1; // px for (int i=0; i<6; i++) kf.errorCovPre.at<float>(i*7) = 1; } bool found_flag; long tick_count, last_tick_count; // count while running. unsigned int not_founding_count; cv::KalmanFilter kf; cv::Mat state; }; class ImageConverter { private: ros::NodeHandle nh; ros::Publisher point_pub; image_transport::ImageTransport it; image_transport::Subscriber rgb_sub; image_transport::Subscriber depth_sub; cv_bridge::CvImageConstPtr rgb_ptr; cv_bridge::CvImageConstPtr depth_ptr; SearchTomato searchTomatoObj; cv::Point tomato_point; bool found_flag; geometry_msgs::Point pub_msg; public: ImageConverter() : it(nh) , searchTomatoObj() , tomato_point(-1, -1) , found_flag(false) { // subscrive to input video feed. point_pub = nh.advertise<geometry_msgs::Point>("tomato_point", 1); rgb_sub = it.subscribe("/camera/rgb/image_raw", 1, &ImageConverter::rgbCb, this); depth_sub = it.subscribe("/camera/depth_registered/image_raw", 1, &ImageConverter::depthCb, this); } ~ImageConverter() {} /** * search tomato function. * get rgb image, and search tomato. * will tomato_point have data. * * @author Yusuke Doi */ void rgbCb(const sensor_msgs::ImageConstPtr& msg) { // get rgb image on kinect try { rgb_ptr = cv_bridge::toCvShare(msg, "bgr8"); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception by rgb: %s", e.what()); } cv::Mat buf = rgb_ptr->image.clone(); // search tomato if (found_flag = searchTomatoObj.searchTomatoPoint(rgb_ptr->image, tomato_point)) cv::circle(buf, tomato_point, 2, CV_RGB(0, 255, 0), -1); cv::imshow(RGB_WINDOW_NAME, buf); cv::waitKey(100); } void depthCb(const sensor_msgs::ImageConstPtr& msg) { try { depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception by depth: %s", e.what()); } //testShowDepth(depth_ptr->image); if (found_flag) { printf("depth is %u", depth_ptr->image.at<uint16_t>(tomato_point)); // pub_msg.x = tomato_point.x; // pub_msg.y = tomato_point.y; // pub_msg.z = depth_ptr->image.at<uint16_t>(tomato_point); pub_msg.x = depth_ptr->image.at<uint16_t>(tomato_point); pub_msg.y = tomato_point.x; pub_msg.z = -tomato_point.y; point_pub.publish(pub_msg); } cv::waitKey(100); } void testShowDepth(const cv::Mat& depth) { static std::vector<uint16_t> m_gamma(2048); static bool firstFlag(false); if (!firstFlag) { for(unsigned int i = 0; i < 2048; i++) { float v = i/2048.0; v = std::pow(v, 3) * 6; m_gamma[i] = v*6*256; } firstFlag = true; } int i; cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1); cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3); cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX); for (i = 0; i < depth.rows * depth.cols; i++) { int y = (int)(i / depth.cols); int x = (int)(i % depth.cols); int pval = m_gamma[buf.at<uint16_t>(i)]; int lb = pval & 0xff; switch(pval >> 8) { case 0: output.at<cv::Vec3b>(y,x)[2] = 255; output.at<cv::Vec3b>(y,x)[1] = 255-lb; output.at<cv::Vec3b>(y,x)[0] = 255-lb; break; case 1: output.at<cv::Vec3b>(y,x)[2] = 255; output.at<cv::Vec3b>(y,x)[1] = lb; output.at<cv::Vec3b>(y,x)[0] = 0; break; case 2: output.at<cv::Vec3b>(y,x)[2] = 255-lb; output.at<cv::Vec3b>(y,x)[1] = 255; output.at<cv::Vec3b>(y,x)[0] = 0; break; case 3: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 255; output.at<cv::Vec3b>(y,x)[0] = lb; break; case 4: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 255-lb; output.at<cv::Vec3b>(y,x)[0] = 255; break; case 5: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 0; output.at<cv::Vec3b>(y,x)[0] = 255-lb; break; default: output.at<cv::Vec3b>(y,x)[2] = 0; output.at<cv::Vec3b>(y,x)[1] = 0; output.at<cv::Vec3b>(y,x)[0] = 0; break; } } imshow(DEPTH_WINDOW_NAME, output); } }; int main(int argc, char** argv) { ros::init(argc, argv, "kinect_tomato_search_node"); ImageConverter ic; cv::namedWindow(RGB_WINDOW_NAME); cv::namedWindow(DEPTH_WINDOW_NAME); ros::spin(); cv::destroyWindow(RGB_WINDOW_NAME); cv::destroyWindow(DEPTH_WINDOW_NAME); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Vanadium Labs LLC * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Vanadium Labs LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL VANADIUM LABS 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. * * Author: Michael Ferguson, Helen Oleynikova */ #include <ros/ros.h> #include <tf/tf.h> #include <actionlib/server/simple_action_server.h> #include <turtlebot_arm_block_manipulation/PickAndPlaceAction.h> #include <moveit/move_group_interface/move_group_interface.h> #include <geometry_msgs/PoseArray.h> namespace turtlebot_arm_block_manipulation { class PickAndPlaceServer { private: ros::NodeHandle nh_; actionlib::SimpleActionServer<turtlebot_arm_block_manipulation::PickAndPlaceAction> as_; std::string action_name_; turtlebot_arm_block_manipulation::PickAndPlaceFeedback feedback_; turtlebot_arm_block_manipulation::PickAndPlaceResult result_; turtlebot_arm_block_manipulation::PickAndPlaceGoalConstPtr goal_; ros::Publisher target_pose_pub_; ros::Subscriber pick_and_place_sub_; // Move groups to control arm and gripper with MoveIt! moveit::planning_interface::MoveGroupInterface arm_; moveit::planning_interface::MoveGroupInterface gripper_; // Parameters from goal std::string arm_link; double gripper_open; double gripper_closed; double z_up; public: PickAndPlaceServer(const std::string name) : nh_("~"), as_(name, false), action_name_(name), arm_("pincher_arm"), gripper_("pincher_gripper") { // Register the goal and feedback callbacks as_.registerGoalCallback(boost::bind(&PickAndPlaceServer::goalCB, this)); as_.registerPreemptCallback(boost::bind(&PickAndPlaceServer::preemptCB, this)); as_.start(); target_pose_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("/target_pose", 1, true); } void goalCB() { ROS_INFO("[pick and place] Received goal!"); goal_ = as_.acceptNewGoal(); arm_link = goal_->frame; gripper_open = goal_->gripper_open; gripper_closed = goal_->gripper_closed; z_up = goal_->z_up; arm_.setPoseReferenceFrame(arm_link); // Allow some leeway in position (meters) and orientation (radians) arm_.setGoalPositionTolerance(0.001); arm_.setGoalOrientationTolerance(0.1); // Allow replanning to increase the odds of a solution arm_.allowReplanning(true); if (goal_->topic.length() < 1) { pickAndPlace(goal_->pickup_pose, goal_->place_pose); } else { pick_and_place_sub_ = nh_.subscribe(goal_->topic, 1, &PickAndPlaceServer::sendGoalFromTopic, this); } } void sendGoalFromTopic(const geometry_msgs::PoseArrayConstPtr& msg) { ROS_INFO("[pick and place] Got goal from topic! %s", goal_->topic.c_str()); pickAndPlace(msg->poses[0], msg->poses[1]); pick_and_place_sub_.shutdown(); } void preemptCB() { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted as_.setPreempted(); } void pickAndPlace(const geometry_msgs::Pose& start_pose, const geometry_msgs::Pose& end_pose) { ROS_INFO("[pick and place] Picking. Also placing."); geometry_msgs::Pose target; /* open gripper */ if (setGripper(gripper_open) == false) return; /* hover over */ target = start_pose; target.position.z = z_up; if (moveArmTo(target) == false) return; /* go down */ target.position.z = start_pose.position.z - 0.01; //TODO: subtracting 10mm to grab block closer to base if (moveArmTo(target) == false) return; /* close gripper */ if (setGripper(gripper_closed) == false) return; ros::Duration(0.8).sleep(); // ensure that gripper properly grasp the cube before lifting the arm /* go up */ target.position.z = z_up; if (moveArmTo(target) == false) return; /* hover over */ target = end_pose; target.position.z = z_up; if (moveArmTo(target) == false) return; /* go down */ target.position.z = end_pose.position.z; if (moveArmTo(target) == false) return; /* open gripper */ if (setGripper(gripper_open) == false) return; ros::Duration(0.6).sleep(); // ensure that gripper properly release the cube before lifting the arm /* go up */ target.position.z = z_up; if (moveArmTo(target) == false) return; /* move out of camera's view */ target.position.z = z_up; if (moveArmTo("pose_navigation_alternate") == false) return; as_.setSucceeded(result_); } private: /** * Move arm to a named configuration, normally described in the robot semantic description SRDF file. * @param target Named target to achieve * @return True of success, false otherwise */ bool moveArmTo(const std::string& target) { ROS_DEBUG("[pick and place] Move arm to '%s' position", target.c_str()); if (arm_.setNamedTarget(target) == false) { ROS_ERROR("[pick and place] Set named target '%s' failed", target.c_str()); return false; } moveit::planning_interface::MoveItErrorCode result = arm_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Move to target failed (error %d)", result.val); as_.setAborted(result_); return false; } } /** * Move arm to a target pose. Only position coordinates are taken into account; the * orientation is calculated according to the direction and distance to the target. * @param target Pose target to achieve * @return True of success, false otherwise */ bool moveArmTo(const geometry_msgs::Pose& target) { int attempts = 0; ROS_DEBUG("[pick and place] Move arm to [%.2f, %.2f, %.2f, %.2f]", target.position.x, target.position.y, target.position.z, tf::getYaw(target.orientation)); while (attempts < 5) { geometry_msgs::PoseStamped modiff_target; modiff_target.header.frame_id = arm_link; modiff_target.pose = target; double x = modiff_target.pose.position.x; double y = modiff_target.pose.position.y; double z = modiff_target.pose.position.z; double d = sqrt(x*x + y*y); if (d > 0.3) { // Maximum reachable distance by the arm is 30 cm ROS_ERROR("Target pose out of reach [%f > %f]", d, 0.3); as_.setAborted(result_); return false; } // Pitch is 90 (vertical) at 10 cm from the arm base; the farther the target is, the closer to horizontal // we point the gripper. Yaw is the direction to the target. We also try some random variations of both to // increase the chances of successful planning. double rp = M_PI_2 - std::asin((d - 0.1)/0.205); // 0.205 = arm's max reach - vertical pitch distance + ε double ry = std::atan2(y, x); tf::Quaternion q = tf::createQuaternionFromRPY(0.0, attempts*fRand(-0.05, +0.05) + rp, attempts*fRand(-0.05, +0.05) + ry); tf::quaternionTFToMsg(q, modiff_target.pose.orientation); // Slightly increase z proportionally to pitch to avoid hitting the table with the lower gripper corner ROS_DEBUG("z increase: %f + %f", modiff_target.pose.position.z, std::abs(std::cos(rp))/50.0); modiff_target.pose.position.z += std::abs(std::cos(rp))/50.0; ROS_DEBUG("Set pose target [%.2f, %.2f, %.2f] [d: %.2f, p: %.2f, y: %.2f]", x, y, z, d, rp, ry); target_pose_pub_.publish(modiff_target); if (arm_.setPoseTarget(modiff_target) == false) { ROS_ERROR("Set pose target [%.2f, %.2f, %.2f, %.2f] failed", modiff_target.pose.position.x, modiff_target.pose.position.y, modiff_target.pose.position.z, tf::getYaw(modiff_target.pose.orientation)); as_.setAborted(result_); return false; } moveit::planning_interface::MoveItErrorCode result = arm_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Move to target failed (error %d) at attempt %d", result.val, attempts + 1); } attempts++; } ROS_ERROR("[pick and place] Move to target failed after %d attempts", attempts); as_.setAborted(result_); return false; } /** * Set gripper opening. * @param opening Physical opening of the gripper, in meters * @return True of success, false otherwise */ bool setGripper(float opening) { ROS_DEBUG("[pick and place] Set gripper opening to %f", opening); if (gripper_.setJointValueTarget("gripper_joint", opening) == false) { ROS_ERROR("[pick and place] Set gripper opening to %f failed", opening); return false; } moveit::planning_interface::MoveItErrorCode result = gripper_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Set gripper opening failed (error %d)", result.val); as_.setAborted(result_); return false; } } float fRand(float min, float max) { return ((float(rand()) / float(RAND_MAX)) * (max - min)) + min; } }; }; int main(int argc, char** argv) { ros::init(argc, argv, "pick_and_place_action_server"); turtlebot_block_manipulation::PickAndPlaceServer server("pick_and_place"); ros::spin(); return 0; } <commit_msg>Fix namespace<commit_after>/* * Copyright (c) 2011, Vanadium Labs LLC * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Vanadium Labs LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL VANADIUM LABS 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. * * Author: Michael Ferguson, Helen Oleynikova */ #include <ros/ros.h> #include <tf/tf.h> #include <actionlib/server/simple_action_server.h> #include <turtlebot_arm_block_manipulation/PickAndPlaceAction.h> #include <moveit/move_group_interface/move_group_interface.h> #include <geometry_msgs/PoseArray.h> namespace turtlebot_arm_block_manipulation { class PickAndPlaceServer { private: ros::NodeHandle nh_; actionlib::SimpleActionServer<turtlebot_arm_block_manipulation::PickAndPlaceAction> as_; std::string action_name_; turtlebot_arm_block_manipulation::PickAndPlaceFeedback feedback_; turtlebot_arm_block_manipulation::PickAndPlaceResult result_; turtlebot_arm_block_manipulation::PickAndPlaceGoalConstPtr goal_; ros::Publisher target_pose_pub_; ros::Subscriber pick_and_place_sub_; // Move groups to control arm and gripper with MoveIt! moveit::planning_interface::MoveGroupInterface arm_; moveit::planning_interface::MoveGroupInterface gripper_; // Parameters from goal std::string arm_link; double gripper_open; double gripper_closed; double z_up; public: PickAndPlaceServer(const std::string name) : nh_("~"), as_(name, false), action_name_(name), arm_("pincher_arm"), gripper_("pincher_gripper") { // Register the goal and feedback callbacks as_.registerGoalCallback(boost::bind(&PickAndPlaceServer::goalCB, this)); as_.registerPreemptCallback(boost::bind(&PickAndPlaceServer::preemptCB, this)); as_.start(); target_pose_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("/target_pose", 1, true); } void goalCB() { ROS_INFO("[pick and place] Received goal!"); goal_ = as_.acceptNewGoal(); arm_link = goal_->frame; gripper_open = goal_->gripper_open; gripper_closed = goal_->gripper_closed; z_up = goal_->z_up; arm_.setPoseReferenceFrame(arm_link); // Allow some leeway in position (meters) and orientation (radians) arm_.setGoalPositionTolerance(0.001); arm_.setGoalOrientationTolerance(0.1); // Allow replanning to increase the odds of a solution arm_.allowReplanning(true); if (goal_->topic.length() < 1) { pickAndPlace(goal_->pickup_pose, goal_->place_pose); } else { pick_and_place_sub_ = nh_.subscribe(goal_->topic, 1, &PickAndPlaceServer::sendGoalFromTopic, this); } } void sendGoalFromTopic(const geometry_msgs::PoseArrayConstPtr& msg) { ROS_INFO("[pick and place] Got goal from topic! %s", goal_->topic.c_str()); pickAndPlace(msg->poses[0], msg->poses[1]); pick_and_place_sub_.shutdown(); } void preemptCB() { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted as_.setPreempted(); } void pickAndPlace(const geometry_msgs::Pose& start_pose, const geometry_msgs::Pose& end_pose) { ROS_INFO("[pick and place] Picking. Also placing."); geometry_msgs::Pose target; /* open gripper */ if (setGripper(gripper_open) == false) return; /* hover over */ target = start_pose; target.position.z = z_up; if (moveArmTo(target) == false) return; /* go down */ target.position.z = start_pose.position.z - 0.01; //TODO: subtracting 10mm to grab block closer to base if (moveArmTo(target) == false) return; /* close gripper */ if (setGripper(gripper_closed) == false) return; ros::Duration(0.8).sleep(); // ensure that gripper properly grasp the cube before lifting the arm /* go up */ target.position.z = z_up; if (moveArmTo(target) == false) return; /* hover over */ target = end_pose; target.position.z = z_up; if (moveArmTo(target) == false) return; /* go down */ target.position.z = end_pose.position.z; if (moveArmTo(target) == false) return; /* open gripper */ if (setGripper(gripper_open) == false) return; ros::Duration(0.6).sleep(); // ensure that gripper properly release the cube before lifting the arm /* go up */ target.position.z = z_up; if (moveArmTo(target) == false) return; /* move out of camera's view */ target.position.z = z_up; if (moveArmTo("pose_navigation_alternate") == false) return; as_.setSucceeded(result_); } private: /** * Move arm to a named configuration, normally described in the robot semantic description SRDF file. * @param target Named target to achieve * @return True of success, false otherwise */ bool moveArmTo(const std::string& target) { ROS_DEBUG("[pick and place] Move arm to '%s' position", target.c_str()); if (arm_.setNamedTarget(target) == false) { ROS_ERROR("[pick and place] Set named target '%s' failed", target.c_str()); return false; } moveit::planning_interface::MoveItErrorCode result = arm_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Move to target failed (error %d)", result.val); as_.setAborted(result_); return false; } } /** * Move arm to a target pose. Only position coordinates are taken into account; the * orientation is calculated according to the direction and distance to the target. * @param target Pose target to achieve * @return True of success, false otherwise */ bool moveArmTo(const geometry_msgs::Pose& target) { int attempts = 0; ROS_DEBUG("[pick and place] Move arm to [%.2f, %.2f, %.2f, %.2f]", target.position.x, target.position.y, target.position.z, tf::getYaw(target.orientation)); while (attempts < 5) { geometry_msgs::PoseStamped modiff_target; modiff_target.header.frame_id = arm_link; modiff_target.pose = target; double x = modiff_target.pose.position.x; double y = modiff_target.pose.position.y; double z = modiff_target.pose.position.z; double d = sqrt(x*x + y*y); if (d > 0.3) { // Maximum reachable distance by the arm is 30 cm ROS_ERROR("Target pose out of reach [%f > %f]", d, 0.3); as_.setAborted(result_); return false; } // Pitch is 90 (vertical) at 10 cm from the arm base; the farther the target is, the closer to horizontal // we point the gripper. Yaw is the direction to the target. We also try some random variations of both to // increase the chances of successful planning. double rp = M_PI_2 - std::asin((d - 0.1)/0.205); // 0.205 = arm's max reach - vertical pitch distance + ε double ry = std::atan2(y, x); tf::Quaternion q = tf::createQuaternionFromRPY(0.0, attempts*fRand(-0.05, +0.05) + rp, attempts*fRand(-0.05, +0.05) + ry); tf::quaternionTFToMsg(q, modiff_target.pose.orientation); // Slightly increase z proportionally to pitch to avoid hitting the table with the lower gripper corner ROS_DEBUG("z increase: %f + %f", modiff_target.pose.position.z, std::abs(std::cos(rp))/50.0); modiff_target.pose.position.z += std::abs(std::cos(rp))/50.0; ROS_DEBUG("Set pose target [%.2f, %.2f, %.2f] [d: %.2f, p: %.2f, y: %.2f]", x, y, z, d, rp, ry); target_pose_pub_.publish(modiff_target); if (arm_.setPoseTarget(modiff_target) == false) { ROS_ERROR("Set pose target [%.2f, %.2f, %.2f, %.2f] failed", modiff_target.pose.position.x, modiff_target.pose.position.y, modiff_target.pose.position.z, tf::getYaw(modiff_target.pose.orientation)); as_.setAborted(result_); return false; } moveit::planning_interface::MoveItErrorCode result = arm_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Move to target failed (error %d) at attempt %d", result.val, attempts + 1); } attempts++; } ROS_ERROR("[pick and place] Move to target failed after %d attempts", attempts); as_.setAborted(result_); return false; } /** * Set gripper opening. * @param opening Physical opening of the gripper, in meters * @return True of success, false otherwise */ bool setGripper(float opening) { ROS_DEBUG("[pick and place] Set gripper opening to %f", opening); if (gripper_.setJointValueTarget("gripper_joint", opening) == false) { ROS_ERROR("[pick and place] Set gripper opening to %f failed", opening); return false; } moveit::planning_interface::MoveItErrorCode result = gripper_.move(); if (bool(result) == true) { return true; } else { ROS_ERROR("[pick and place] Set gripper opening failed (error %d)", result.val); as_.setAborted(result_); return false; } } float fRand(float min, float max) { return ((float(rand()) / float(RAND_MAX)) * (max - min)) + min; } }; }; int main(int argc, char** argv) { ros::init(argc, argv, "pick_and_place_action_server"); turtlebot_arm_block_manipulation::PickAndPlaceServer server("pick_and_place"); ros::spin(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. Some parts of this code are derived from ITK. See ITKCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // The following example illustrates how to segment very large images // using the \doxygen{otb}{StreamingImageToOGRLayerSegmentationFilter}. This filter is // templated over the segmentation filter that will be used to segment each tile // of the input image. In this example we will use the \doxygen{otb}{MeanShiftVectorImageFilter}. // The labeled output image of each tile is then vectorized (using a filter based on GDALPolygonize) // and stored into a \doxygen{otb}{ogr}{Layer} within the \doxygen{otb}{ogr}{DataSource} // set as input. Finally a fusion filter, \doxygen{otb}{OGRDataSourceStreamStitchingFilter}, is used to merge polygons // at tile border. // // Let's take a look at the code. // First we include all the needed headers // Software Guide : EndLatex #include <iostream> // Software Guide : BeginCodeSnippet #include "otbStreamingImageToOGRLayerSegmentationFilter.h" #include "otbMeanShiftVectorImageFilter.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRDataSourceStreamStitchingFilter.h" // Software Guide : EndCodeSnippet #include "otbVectorImage.h" #include "otbImageFileReader.h" int main(int argc, char *argv[]) { if (argc != 13) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage maskImage outputVec layerName TileDimension" << "spatialRadius rangeRadius minObjectSize filterSmallObj minSize" << "SimplifyFlag Tolerance" << std::endl; return EXIT_FAILURE; } const char * imageName = argv[1]; const char * maskName = argv[2]; const char * dataSourceName = argv[3]; const char * layerName = argv[4]; const unsigned int tileSize = atoi(argv[5]); const unsigned int spatialRadius = atoi(argv[6]); const double rangeRadius = atof(argv[7]); const unsigned int minimumObjectSize = atoi(argv[8]); const bool filterSmallObj = atoi(argv[9]); const unsigned int minSize = atoi(argv[10]); const bool simplify = atoi(argv[11]); const double tolerance = atof(argv[12]); const std::string fieldName("DN"); // Software Guide : BeginLatex // // We now declare the image and pixel types used as input of the MeanShiftFilter. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef unsigned int LabelPixelType; const unsigned int Dimension = 2; typedef otb::VectorImage<InputPixelType, Dimension> ImageType; typedef otb::Image<LabelPixelType, Dimension> LabelImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then the mean shift segmentation filter is declared using the Image type declared previsouly. // The StreamingVectorizedSegmentation is templated over the mean shift filter, the input image type and the output vector data type // Software Guide : EndLatex // Software Guide : BeginCodeSnippet //typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> MeanShiftImageFilterType; typedef otb::MeanShiftVectorImageFilter <ImageType, ImageType, LabelImageType> SegmentationFilterType; typedef otb::StreamingImageToOGRLayerSegmentationFilter<ImageType, SegmentationFilterType> StreamingVectorizedSegmentationType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finaly we define a Reader on the input image and a mask reader. // All pixels in the mask with a value of 0 will not be considered suitable for vectorization. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<LabelImageType> MaskReaderType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we have declared all type needed for the pipeline, we instantiate the different filters, // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); MaskReaderType::Pointer maskReader = MaskReaderType::New(); StreamingVectorizedSegmentationType::Pointer filter = StreamingVectorizedSegmentationType::New(); // Software Guide : EndCodeSnippet reader->SetFileName(imageName); reader->UpdateOutputInformation(); maskReader->SetFileName(maskName); maskReader->UpdateOutputInformation(); // Software Guide : BeginLatex // // The instanciation of the DataSource is slightly different as usual. // In fact the \code{New()} method on a \doxygen{otb}{ogr}{DataSource} can be called with or without parameters. // Without parameters, the \code{New()} method instanciate a "Memory" DataSource, which means all the data are stored in memory. // This is not useful in case of large scale segmentation as it will result in millions of polygons kept in memory ... // However the \code{New()} method can also take a filename (\code{std::String}) parameter. Then either the file already exists // and the corresponding ogr driver is used to open the file, or it doesn't exists and then it is created. // Here we used a non existing filename to create a new file in writing mode. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet otb::ogr::DataSource::Pointer ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::write); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we will create the layer inside the DataSource that will // hold the polygons from the vectorized segmentation. First, we // need to retrieve the spatial reference from the input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OGRSpatialReference oSRS(reader->GetOutput()->GetProjectionRef().c_str()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now, we can create the layer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet otb::ogr::Layer ogrLayer = ogrDS->CreateLayer(layerName,&oSRS,wkbMultiPolygon,NULL); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Last, we need to create a field inside the layer that will hold // the identifier of the polygons. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OGRFieldDefn ogrField(fieldName.c_str(),OFTInteger); ogrLayer.CreateField(ogrField,true); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we set the parameters to the segmentation filter.The \doxygen{otb}{MeanShiftVectorImageFilter} // required three parameters, the spatial radius, the range radius and the minimum object size. // We use the \code{GetSegmentationFilter()} method on the \doxygen{otb}{StreamingVectorizedSegmentation} // to get a pointer to the segmentation filter. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->GetSegmentationFilter()->SetSpatialRadius(spatialRadius); filter->GetSegmentationFilter()->SetRangeRadius(rangeRadius); filter->GetSegmentationFilter()->SetMinimumRegionSize(minimumObjectSize); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then we set parameters to the \doxygen{otb}{StreamingVectorizedSegmentation} filter. // These parameters are : // \begin{itemize} // \item tile size : use \code{SetTileDimensionTiledStreaming()} for square tile or \code{SetNumberOfLinesStrippedStreaming()} // for Strip. // \item field name : name of the field that will contained the label values. (default is "DN"). // \item start label : first label. Each polygons have a unique label (incremented by one). // \item option to filter small polygons (default to false). // \item minimum object size : in case filter small polygons option is True // \item simplify option : simplification of polygon vertex (default to false).This can reduced very efficiently the size // of the output file with no real impact on the results. // \item simplification tolerance // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->GetStreamer()->SetTileDimensionTiledStreaming(tileSize); filter->SetFieldName(fieldName); filter->SetStartLabel(1); filter->SetFilterSmallObject(filterSmallObj); filter->SetMinimumObjectSize(minSize); filter->SetSimplify(simplify); filter->SetSimplificationTolerance(tolerance); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally we connect the pipeline // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(reader->GetOutput()); filter->SetInputMask(maskReader->GetOutput()); filter->SetOGRLayer(ogrLayer); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And call the \code{Initialize()} method (needed to create the output layer in the datasource) // before calling the \code{Update()} method. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->Initialize(); filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The segmentation is done, but as it works tile by tile, we need to fusion polygons at tile border. // We use the \doxygen{otb}{OGRDataSourceStreamStitchingFilter}. This filter uses a simple fusion strategy. // Polygons that have the largest intersection over a tile are fusioned. Each polygon can be fusioned // only once per tile border (row and column). // Let's look at the code for fusioning. // As usual we declared and instanciate the \doxygen{otb}{OGRDataSourceStreamStitchingFilter}. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::OGRDataSourceStreamStitchingFilter<ImageType> FusionFilterType; FusionFilterType::Pointer fusionFilter = FusionFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Next we set the input image and the input \doxygen{otb}{ogr}{DataSource}. // The image is internally used in the filter to compute coordinates of streaming tiles. // The DataSource is the one containing the segmentation results. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->SetInput(reader->GetOutput()); fusionFilter->SetOGRDataSource(ogrDS); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We set the name of the layer containing segmentation results which is the same that we used // for the \doxygen{otb}{StreamingVectorizedSegmentation} filter. We also set the size of the // tile used, which may be different from the one we set in the \doxygen{otb}{StreamingVectorizedSegmentation} filter // but can be retrieved using the \code{GetStreamSize()} method. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->SetStreamSize(filter->GetStreamSize()); fusionFilter->SetLayerName(layerName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Finally we call the \code{GenerateData()} method to launch the processing. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->GenerateData(); // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <commit_msg>DOC: Adapting software guide example following API change<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. Some parts of this code are derived from ITK. See ITKCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // The following example illustrates how to segment very large images // using the \doxygen{otb}{StreamingImageToOGRLayerSegmentationFilter}. This filter is // templated over the segmentation filter that will be used to segment each tile // of the input image. In this example we will use the \doxygen{otb}{MeanShiftVectorImageFilter}. // The labeled output image of each tile is then vectorized (using a filter based on GDALPolygonize) // and stored into a \doxygen{otb}{ogr}{Layer} within the \doxygen{otb}{ogr}{DataSource} // set as input. Finally a fusion filter, \doxygen{otb}{OGRLayerStreamStitchingFilter}, is used to merge polygons // at tile border. // // Let's take a look at the code. // First we include all the needed headers // Software Guide : EndLatex #include <iostream> // Software Guide : BeginCodeSnippet #include "otbStreamingImageToOGRLayerSegmentationFilter.h" #include "otbMeanShiftVectorImageFilter.h" #include "otbOGRDataSourceWrapper.h" #include "otbOGRLayerStreamStitchingFilter.h" // Software Guide : EndCodeSnippet #include "otbVectorImage.h" #include "otbImageFileReader.h" int main(int argc, char *argv[]) { if (argc != 13) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage maskImage outputVec layerName TileDimension" << "spatialRadius rangeRadius minObjectSize filterSmallObj minSize" << "SimplifyFlag Tolerance" << std::endl; return EXIT_FAILURE; } const char * imageName = argv[1]; const char * maskName = argv[2]; const char * dataSourceName = argv[3]; const char * layerName = argv[4]; const unsigned int tileSize = atoi(argv[5]); const unsigned int spatialRadius = atoi(argv[6]); const double rangeRadius = atof(argv[7]); const unsigned int minimumObjectSize = atoi(argv[8]); const bool filterSmallObj = atoi(argv[9]); const unsigned int minSize = atoi(argv[10]); const bool simplify = atoi(argv[11]); const double tolerance = atof(argv[12]); const std::string fieldName("DN"); // Software Guide : BeginLatex // // We now declare the image and pixel types used as input of the MeanShiftFilter. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef float InputPixelType; typedef unsigned int LabelPixelType; const unsigned int Dimension = 2; typedef otb::VectorImage<InputPixelType, Dimension> ImageType; typedef otb::Image<LabelPixelType, Dimension> LabelImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then the mean shift segmentation filter is declared using the Image type declared previsouly. // The StreamingVectorizedSegmentation is templated over the mean shift filter, the input image type and the output vector data type // Software Guide : EndLatex // Software Guide : BeginCodeSnippet //typedef otb::MeanShiftSmoothingImageFilter<ImageType, ImageType> MeanShiftImageFilterType; typedef otb::MeanShiftVectorImageFilter <ImageType, ImageType, LabelImageType> SegmentationFilterType; typedef otb::StreamingImageToOGRLayerSegmentationFilter<ImageType, SegmentationFilterType> StreamingVectorizedSegmentationType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finaly we define a Reader on the input image and a mask reader. // All pixels in the mask with a value of 0 will not be considered suitable for vectorization. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<LabelImageType> MaskReaderType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we have declared all type needed for the pipeline, we instantiate the different filters, // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); MaskReaderType::Pointer maskReader = MaskReaderType::New(); StreamingVectorizedSegmentationType::Pointer filter = StreamingVectorizedSegmentationType::New(); // Software Guide : EndCodeSnippet reader->SetFileName(imageName); reader->UpdateOutputInformation(); maskReader->SetFileName(maskName); maskReader->UpdateOutputInformation(); // Software Guide : BeginLatex // // The instanciation of the DataSource is slightly different as usual. // In fact the \code{New()} method on a \doxygen{otb}{ogr}{DataSource} can be called with or without parameters. // Without parameters, the \code{New()} method instanciate a "Memory" DataSource, which means all the data are stored in memory. // This is not useful in case of large scale segmentation as it will result in millions of polygons kept in memory ... // However the \code{New()} method can also take a filename (\code{std::String}) parameter. Then either the file already exists // and the corresponding ogr driver is used to open the file, or it doesn't exists and then it is created. // Here we used a non existing filename to create a new file in writing mode. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet otb::ogr::DataSource::Pointer ogrDS = otb::ogr::DataSource::New(dataSourceName, otb::ogr::DataSource::Modes::write); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we will create the layer inside the DataSource that will // hold the polygons from the vectorized segmentation. First, we // need to retrieve the spatial reference from the input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OGRSpatialReference oSRS(reader->GetOutput()->GetProjectionRef().c_str()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now, we can create the layer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet otb::ogr::Layer ogrLayer = ogrDS->CreateLayer(layerName,&oSRS,wkbMultiPolygon,NULL); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Last, we need to create a field inside the layer that will hold // the identifier of the polygons. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OGRFieldDefn ogrField(fieldName.c_str(),OFTInteger); ogrLayer.CreateField(ogrField,true); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we set the parameters to the segmentation filter.The \doxygen{otb}{MeanShiftVectorImageFilter} // required three parameters, the spatial radius, the range radius and the minimum object size. // We use the \code{GetSegmentationFilter()} method on the \doxygen{otb}{StreamingVectorizedSegmentation} // to get a pointer to the segmentation filter. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->GetSegmentationFilter()->SetSpatialRadius(spatialRadius); filter->GetSegmentationFilter()->SetRangeRadius(rangeRadius); filter->GetSegmentationFilter()->SetMinimumRegionSize(minimumObjectSize); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then we set parameters to the \doxygen{otb}{StreamingVectorizedSegmentation} filter. // These parameters are : // \begin{itemize} // \item tile size : use \code{SetTileDimensionTiledStreaming()} for square tile or \code{SetNumberOfLinesStrippedStreaming()} // for Strip. // \item field name : name of the field that will contained the label values. (default is "DN"). // \item start label : first label. Each polygons have a unique label (incremented by one). // \item option to filter small polygons (default to false). // \item minimum object size : in case filter small polygons option is True // \item simplify option : simplification of polygon vertex (default to false).This can reduced very efficiently the size // of the output file with no real impact on the results. // \item simplification tolerance // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->GetStreamer()->SetTileDimensionTiledStreaming(tileSize); filter->SetFieldName(fieldName); filter->SetStartLabel(1); filter->SetFilterSmallObject(filterSmallObj); filter->SetMinimumObjectSize(minSize); filter->SetSimplify(simplify); filter->SetSimplificationTolerance(tolerance); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally we connect the pipeline // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(reader->GetOutput()); filter->SetInputMask(maskReader->GetOutput()); filter->SetOGRLayer(ogrLayer); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And call the \code{Initialize()} method (needed to create the output layer in the datasource) // before calling the \code{Update()} method. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->Initialize(); filter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The segmentation is done, but as it works tile by tile, we need to fusion polygons at tile border. // We use the \doxygen{otb}{OGRLayerStreamStitchingFilter}. This filter uses a simple fusion strategy. // Polygons that have the largest intersection over a tile are fusioned. Each polygon can be fusioned // only once per tile border (row and column). // Let's look at the code for fusioning. // As usual we declared and instanciate the \doxygen{otb}{OGRLayerStreamStitchingFilter}. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::OGRLayerStreamStitchingFilter<ImageType> FusionFilterType; FusionFilterType::Pointer fusionFilter = FusionFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Next we set the input image and the input \doxygen{otb}{ogr}{Layer}. // The image is internally used in the filter to compute coordinates of streaming tiles. // The DataSource is the one containing the segmentation results. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->SetInput(reader->GetOutput()); fusionFilter->SetOGRLayer(ogrLayer); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We set the size of the tile used, // which may be different from the one we set in the // \doxygen{otb}{StreamingVectorizedSegmentation} filter but can be // retrieved using the \code{GetStreamSize()} method. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->SetStreamSize(filter->GetStreamSize()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Finally we call the \code{GenerateData()} method to launch the processing. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet fusionFilter->GenerateData(); // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//***************************************************************************** // // Copyright 2015 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //***************************************************************************** #include "pch.h" #include "UncompressedAudioSampleProvider.h" using namespace FFmpegInterop; // Minimum duration for uncompressed audio samples (50 ms) const LONGLONG MINAUDIOSAMPLEDURATION = 500000; UncompressedAudioSampleProvider::UncompressedAudioSampleProvider( FFmpegReader^ reader, AVFormatContext* avFormatCtx, AVCodecContext* avCodecCtx) : UncompressedSampleProvider(reader, avFormatCtx, avCodecCtx) , m_pSwrCtx(nullptr) { } HRESULT UncompressedAudioSampleProvider::AllocateResources() { HRESULT hr = S_OK; hr = UncompressedSampleProvider::AllocateResources(); if (SUCCEEDED(hr)) { // Set default channel layout when the value is unknown (0) int64 inChannelLayout = m_pAvCodecCtx->channel_layout ? m_pAvCodecCtx->channel_layout : av_get_default_channel_layout(m_pAvCodecCtx->channels); int64 outChannelLayout = av_get_default_channel_layout(m_pAvCodecCtx->channels); // Set up resampler to convert any PCM format (e.g. AV_SAMPLE_FMT_FLTP) to AV_SAMPLE_FMT_S16 PCM format that is expected by Media Element. // Additional logic can be added to avoid resampling PCM data that is already in AV_SAMPLE_FMT_S16_PCM. m_pSwrCtx = swr_alloc_set_opts( NULL, outChannelLayout, AV_SAMPLE_FMT_S16, m_pAvCodecCtx->sample_rate, inChannelLayout, m_pAvCodecCtx->sample_fmt, m_pAvCodecCtx->sample_rate, 0, NULL); if (!m_pSwrCtx) { hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { if (swr_init(m_pSwrCtx) < 0) { hr = E_FAIL; } } return hr; } UncompressedAudioSampleProvider::~UncompressedAudioSampleProvider() { if (m_pAvFrame) { av_frame_free(&m_pAvFrame); } // Free swr_free(&m_pSwrCtx); } HRESULT UncompressedAudioSampleProvider::WriteAVPacketToStream(DataWriter^ dataWriter, AVPacket* avPacket) { // Because each packet can contain multiple frames, we have already written the packet to the stream // during the decode stage. return S_OK; } HRESULT UncompressedAudioSampleProvider::ProcessDecodedFrame(DataWriter^ dataWriter) { // Resample uncompressed frame to AV_SAMPLE_FMT_S16 PCM format that is expected by Media Element uint8_t *resampledData = nullptr; unsigned int aBufferSize = av_samples_alloc(&resampledData, NULL, m_pAvFrame->channels, m_pAvFrame->nb_samples, AV_SAMPLE_FMT_S16, 0); int resampledDataSize = swr_convert(m_pSwrCtx, &resampledData, aBufferSize, (const uint8_t **)m_pAvFrame->extended_data, m_pAvFrame->nb_samples); auto aBuffer = ref new Platform::Array<uint8_t>(resampledData, min(aBufferSize, (unsigned int)(resampledDataSize * m_pAvFrame->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)))); dataWriter->WriteBytes(aBuffer); av_freep(&resampledData); av_frame_unref(m_pAvFrame); av_frame_free(&m_pAvFrame); return S_OK; } MediaStreamSample^ UncompressedAudioSampleProvider::GetNextSample() { // Similar to GetNextSample in MediaSampleProvider, // but we concatenate samples until reaching a minimum duration DebugMessage(L"GetNextSample\n"); HRESULT hr = S_OK; MediaStreamSample^ sample; DataWriter^ dataWriter = ref new DataWriter(); LONGLONG finalPts = -1; LONGLONG finalDur = 0; do { LONGLONG pts = 0; LONGLONG dur = 0; hr = GetNextPacket(dataWriter, pts, dur); if (finalPts == -1) { finalPts = pts; } finalDur += dur; } while (SUCCEEDED(hr) && finalDur < MINAUDIOSAMPLEDURATION); if (finalDur > 0) { sample = MediaStreamSample::CreateFromBuffer(dataWriter->DetachBuffer(), { finalPts }); sample->Duration = { finalDur }; } return sample; } <commit_msg>finalPts and finalDur should not be updated on failure<commit_after>//***************************************************************************** // // Copyright 2015 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //***************************************************************************** #include "pch.h" #include "UncompressedAudioSampleProvider.h" using namespace FFmpegInterop; // Minimum duration for uncompressed audio samples (50 ms) const LONGLONG MINAUDIOSAMPLEDURATION = 500000; UncompressedAudioSampleProvider::UncompressedAudioSampleProvider( FFmpegReader^ reader, AVFormatContext* avFormatCtx, AVCodecContext* avCodecCtx) : UncompressedSampleProvider(reader, avFormatCtx, avCodecCtx) , m_pSwrCtx(nullptr) { } HRESULT UncompressedAudioSampleProvider::AllocateResources() { HRESULT hr = S_OK; hr = UncompressedSampleProvider::AllocateResources(); if (SUCCEEDED(hr)) { // Set default channel layout when the value is unknown (0) int64 inChannelLayout = m_pAvCodecCtx->channel_layout ? m_pAvCodecCtx->channel_layout : av_get_default_channel_layout(m_pAvCodecCtx->channels); int64 outChannelLayout = av_get_default_channel_layout(m_pAvCodecCtx->channels); // Set up resampler to convert any PCM format (e.g. AV_SAMPLE_FMT_FLTP) to AV_SAMPLE_FMT_S16 PCM format that is expected by Media Element. // Additional logic can be added to avoid resampling PCM data that is already in AV_SAMPLE_FMT_S16_PCM. m_pSwrCtx = swr_alloc_set_opts( NULL, outChannelLayout, AV_SAMPLE_FMT_S16, m_pAvCodecCtx->sample_rate, inChannelLayout, m_pAvCodecCtx->sample_fmt, m_pAvCodecCtx->sample_rate, 0, NULL); if (!m_pSwrCtx) { hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { if (swr_init(m_pSwrCtx) < 0) { hr = E_FAIL; } } return hr; } UncompressedAudioSampleProvider::~UncompressedAudioSampleProvider() { if (m_pAvFrame) { av_frame_free(&m_pAvFrame); } // Free swr_free(&m_pSwrCtx); } HRESULT UncompressedAudioSampleProvider::WriteAVPacketToStream(DataWriter^ dataWriter, AVPacket* avPacket) { // Because each packet can contain multiple frames, we have already written the packet to the stream // during the decode stage. return S_OK; } HRESULT UncompressedAudioSampleProvider::ProcessDecodedFrame(DataWriter^ dataWriter) { // Resample uncompressed frame to AV_SAMPLE_FMT_S16 PCM format that is expected by Media Element uint8_t *resampledData = nullptr; unsigned int aBufferSize = av_samples_alloc(&resampledData, NULL, m_pAvFrame->channels, m_pAvFrame->nb_samples, AV_SAMPLE_FMT_S16, 0); int resampledDataSize = swr_convert(m_pSwrCtx, &resampledData, aBufferSize, (const uint8_t **)m_pAvFrame->extended_data, m_pAvFrame->nb_samples); auto aBuffer = ref new Platform::Array<uint8_t>(resampledData, min(aBufferSize, (unsigned int)(resampledDataSize * m_pAvFrame->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)))); dataWriter->WriteBytes(aBuffer); av_freep(&resampledData); av_frame_unref(m_pAvFrame); av_frame_free(&m_pAvFrame); return S_OK; } MediaStreamSample^ UncompressedAudioSampleProvider::GetNextSample() { // Similar to GetNextSample in MediaSampleProvider, // but we concatenate samples until reaching a minimum duration DebugMessage(L"GetNextSample\n"); HRESULT hr = S_OK; MediaStreamSample^ sample; DataWriter^ dataWriter = ref new DataWriter(); LONGLONG finalPts = -1; LONGLONG finalDur = 0; do { LONGLONG pts = 0; LONGLONG dur = 0; hr = GetNextPacket(dataWriter, pts, dur); if (SUCCEEDED(hr)) { if (finalPts == -1) { finalPts = pts; } finalDur += dur; } } while (SUCCEEDED(hr) && finalDur < MINAUDIOSAMPLEDURATION); if (finalDur > 0) { sample = MediaStreamSample::CreateFromBuffer(dataWriter->DetachBuffer(), { finalPts }); sample->Duration = { finalDur }; } return sample; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord_mtx[l][i]-coordm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hca(i,j) += ((coord_mtx[l][i] - coordm(i))* (coord_mtx[l][j] - coordm(j))- (sum-1.0e0)*hca(i,j)/sum)/(sum-1.0e0); } } } /* correlation matrix double cstdev[3*COORDIM]; for (int i=0; i<(3*COORDIM); ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(coord_mtx[l][i]); #ifdef DEBUG std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << coordm[i] << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; #endif cstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hca(i,j) / (cstdev[i]*cstdev[j]); */ for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hca(i,j) != hca(j,i)) std::cout << i << " " << j << " " << hca(i,j) << " ERROR" << std::endl;; arma::vec eigval = arma::zeros<arma::mat>(3*COORDIM); arma::mat eigvec = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; #ifdef DEBUG std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; #endif } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); #ifdef DEBUG std::cout << hca * hcai ; #endif // and so on ... arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); coordm.fill(0.0e0); sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord_mtx[l][i]-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param_mtx[l][i]-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm(i))* (param_mtx[l][j] - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } /* correlation matrix double pstdev[PARAMDIM]; for (int i=0; i<PARAMDIM; ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); #ifdef DEBUG std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << paramm(i) << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; #endif pstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<PARAMDIM; ++j) hcap(i,j) = hcap(i,j) / (cstdev[i]*pstdev[j]); */ arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif arma::mat k = arma::zeros<arma::mat>((3*COORDIM)-PARAMDIM); /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM)-PARAMDIM; ++i) { double v = 0.0e0; for (int ki=0; ki<(3*COORDIM); ++ki) k(i) = eigvec(i,ki)*coordm[ki]; for (int j=0; j<(3*COORDIM); ++j) v += (eigvec(i,j)/sqrt(eigval(i))) + k(i); chi2 += (v*v); } std::cout << "Chi2: " << chi2 << std::endl; //test back arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord_mtx[l][k]; pc[i](fabs(p - param_mtx[l][i])/(fabs(p + param_mtx[l][i])/2.0)); } } for (int i=0; i<PARAMDIM; ++i) { std::cout << pc[i].mean() << " " << pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <commit_msg>chi2 first test implementation<commit_after>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord_mtx[l][i]-coordm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hca(i,j) += ((coord_mtx[l][i] - coordm(i))* (coord_mtx[l][j] - coordm(j))- (sum-1.0e0)*hca(i,j)/sum)/(sum-1.0e0); } } } /* correlation matrix double cstdev[3*COORDIM]; for (int i=0; i<(3*COORDIM); ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(coord_mtx[l][i]); #ifdef DEBUG std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << coordm[i] << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; #endif cstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hca(i,j) / (cstdev[i]*cstdev[j]); */ for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hca(i,j) != hca(j,i)) std::cout << i << " " << j << " " << hca(i,j) << " ERROR" << std::endl;; arma::vec eigval = arma::zeros<arma::mat>(3*COORDIM); arma::mat eigvec = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; #ifdef DEBUG std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; #endif } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); #ifdef DEBUG std::cout << hca * hcai ; #endif // and so on ... arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); coordm.fill(0.0e0); sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord_mtx[l][i]-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param_mtx[l][i]-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm(i))* (param_mtx[l][j] - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } /* correlation matrix double pstdev[PARAMDIM]; for (int i=0; i<PARAMDIM; ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); #ifdef DEBUG std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << paramm(i) << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; #endif pstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<PARAMDIM; ++j) hcap(i,j) = hcap(i,j) / (cstdev[i]*pstdev[j]); */ arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif arma::mat a = arma::zeros<arma::mat>((3*COORDIM),(3*COORDIM)); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) a(i,j) = eigvec(i,j)/sqrt(eigval(i)); arma::mat k = arma::zeros<arma::mat>(3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) k(i) += a(i,j)*coordm(j); //test back arma::running_stat<double> chi2stats; arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord_mtx[l][k]; pc[i](fabs(p - param_mtx[l][i])/(fabs(p + param_mtx[l][i])/2.0)); } /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM)-PARAMDIM; ++i) { double v = k(i); for (int j=0; j<(3*COORDIM); ++j) v += a(i,j) * coord_mtx[l][j]; chi2 += (v*v); } chi2stats(chi2); } std::cout << "chi2 mean = " << chi2stats.mean() << std::endl; std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl; std::cout << "chi2 min = " << chi2stats.min() << std::endl; std::cout << "chi2 max = " << chi2stats.max() << std::endl; for (int i=0; i<PARAMDIM; ++i) { std::cout << pc[i].mean() << " " << pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <|endoftext|>
<commit_before>/******************************************************************************* * tests/api/operations_test.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/api/dia_base.hpp> #include <c7a/net/endpoint.hpp> #include <c7a/core/job_manager.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/reduce_node.hpp> #include <c7a/api/sum_node.hpp> #include <c7a/api/bootstrap.hpp> #include <algorithm> #include <random> #include "gtest/gtest.h" using namespace c7a::core; using namespace c7a::net; TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) { using c7a::Context; Context ctx; std::vector<std::string> self = { "127.0.0.1:1234" }; ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self)); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(1000, 10000); size_t generate_size = distribution(generator); auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { return std::stoi(line); }, generate_size); size_t writer_size = 0; input.WriteToFileSystem("test1.out", [&writer_size](const int& item) { //file contains ints between 1 and 15 //fails if wrong integer is generated EXPECT_GE(item, 1); EXPECT_GE(16, item); writer_size++; return std::to_string(item); }); ASSERT_EQ(generate_size, writer_size); } TEST(Operations, ReadAndAllGatherElementsCorrect) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::vector<int> out_vec; integers.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_EQ(element, i++); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, MapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> double_elements = [](int in) { return (double) 2 * in; }; auto doubled = integers.Map(double_elements); std::vector<double> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FlatMapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto flatmap_double = [](int in, auto emit) { emit((double) 2 * in); emit((double) 2 * (in + 16)); }; auto doubled = integers.FlatMap(flatmap_double); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 32, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FilterResultsCorrectly) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> even = [](int in) { return (in % 2 == 0); }; auto doubled = integers.Filter(even); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 8, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_ReduceModulo2CorrectResults) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto modulo_two = [](int in) { return (in / 2); }; auto add_function = [](int in1, int in2) { return in1 + in2; }; auto reduced = integers.ReduceBy(modulo_two, add_function); std::vector<int> out_vec; std::cout << "starting" << std::endl; reduced.AllGather(&out_vec); std::cout << "testing" << std::endl; std::sort(out_vec.begin(), out_vec.end()); std::cout << "["; for (int element : out_vec) { std::cout << element << ","; } std::cout<<"]"<<std::endl; int i = 1; for (int element : out_vec) { ASSERT_EQ(element, 56 + (8 * i++)); } ASSERT_EQ((size_t) 2, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::uniform_int_distribution<int> distribution2(1000, 10000); size_t generate_size = distribution2(generator); std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) { auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { return std::stoi(line); }, generate_size); auto ones = input.Map([](int){ return 1; }); auto add_function = [](int in1, int in2) { return in1 + in2; }; ASSERT_EQ((int) generate_size, ones.Sum(add_function)); }; c7a::ExecuteThreads(workers, port_base, start_func); } /******************************************************************************/ <commit_msg>add print statement to see where jenkins dies<commit_after>/******************************************************************************* * tests/api/operations_test.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/api/dia_base.hpp> #include <c7a/net/endpoint.hpp> #include <c7a/core/job_manager.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/reduce_node.hpp> #include <c7a/api/sum_node.hpp> #include <c7a/api/bootstrap.hpp> #include <algorithm> #include <random> #include "gtest/gtest.h" using namespace c7a::core; using namespace c7a::net; TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) { using c7a::Context; Context ctx; std::vector<std::string> self = { "127.0.0.1:1234" }; ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self)); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(1000, 10000); size_t generate_size = distribution(generator); auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { std::cout << line << std::endl; return std::stoi(line); }, generate_size); size_t writer_size = 0; input.WriteToFileSystem("test1.out", [&writer_size](const int& item) { //file contains ints between 1 and 15 //fails if wrong integer is generated EXPECT_GE(item, 1); EXPECT_GE(16, item); writer_size++; return std::to_string(item); }); ASSERT_EQ(generate_size, writer_size); } TEST(Operations, ReadAndAllGatherElementsCorrect) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::vector<int> out_vec; integers.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_EQ(element, i++); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, MapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> double_elements = [](int in) { return (double) 2 * in; }; auto doubled = integers.Map(double_elements); std::vector<double> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 16, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FlatMapResultsCorrectChangingType) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto flatmap_double = [](int in, auto emit) { emit((double) 2 * in); emit((double) 2 * (in + 16)); }; auto doubled = integers.FlatMap(flatmap_double); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 32, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, FilterResultsCorrectly) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); std::function<double(int)> even = [](int in) { return (in % 2 == 0); }; auto doubled = integers.Filter(even); std::vector<int> out_vec; doubled.AllGather(&out_vec); std::sort(out_vec.begin(), out_vec.end()); int i = 1; for (int element : out_vec) { ASSERT_DOUBLE_EQ(element, (i++ * 2)); } ASSERT_EQ((size_t) 8, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_ReduceModulo2CorrectResults) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) { auto integers = ReadLines( ctx, "test1", [](const std::string& line) { return std::stoi(line); }); auto modulo_two = [](int in) { return (in / 2); }; auto add_function = [](int in1, int in2) { return in1 + in2; }; auto reduced = integers.ReduceBy(modulo_two, add_function); std::vector<int> out_vec; std::cout << "starting" << std::endl; reduced.AllGather(&out_vec); std::cout << "testing" << std::endl; std::sort(out_vec.begin(), out_vec.end()); std::cout << "["; for (int element : out_vec) { std::cout << element << ","; } std::cout<<"]"<<std::endl; int i = 1; for (int element : out_vec) { ASSERT_EQ(element, 56 + (8 * i++)); } ASSERT_EQ((size_t) 2, out_vec.size()); }; c7a::ExecuteThreads(workers, port_base, start_func); } TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) { std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(2, 4); size_t workers = distribution(generator); size_t port_base = 8080; std::uniform_int_distribution<int> distribution2(1000, 10000); size_t generate_size = distribution2(generator); std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) { auto input = GenerateFromFile( ctx, "test1", [](const std::string& line) { return std::stoi(line); }, generate_size); auto ones = input.Map([](int){ return 1; }); auto add_function = [](int in1, int in2) { return in1 + in2; }; ASSERT_EQ((int) generate_size, ones.Sum(add_function)); }; c7a::ExecuteThreads(workers, port_base, start_func); } /******************************************************************************/ <|endoftext|>
<commit_before>/* Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com> Copyright (C) 2010 Collabora Ltd. @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qgsttest.h" #include <QGst/Object> #include <QGst/Message> #include <QGst/Pipeline> #include <QGst/ElementFactory> #include <QGst/UriHandler> #include <QGst/StreamVolume> class RefPointerTest : public QGstTest { Q_OBJECT private Q_SLOTS: void refTest1(); void refTest2(); void dynamicCastTest(); void dynamicCastDownObjectTest(); void dynamicCastUpObjectTest(); void dynamicCastObjectToIfaceTest(); void dynamicCastIfaceToObjectTest(); void cppWrappersTest(); void messageDynamicCastTest(); void equalityTest(); }; void RefPointerTest::refTest1() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); gst_object_sink(bin); QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin, false); QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1); } void RefPointerTest::refTest2() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); gst_object_sink(bin); { QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin); QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 2); { QGst::ObjectPtr object2 = object; QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 3); } } QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1); gst_object_unref(bin); } void RefPointerTest::dynamicCastTest() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); gst_object_sink(bin); { QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin); QVERIFY(!object.dynamicCast<QGlib::Object>().isNull()); } { QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin)); QVERIFY(!object.dynamicCast<QGst::Object>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastDownObjectTest() { GstObject *bin = GST_OBJECT(gst_object_ref(gst_bin_new(NULL))); gst_object_sink(bin); { QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin)); QVERIFY(!object.dynamicCast<QGst::Object>().isNull()); QVERIFY(!object.dynamicCast<QGst::Bin>().isNull()); QVERIFY(object.dynamicCast<QGst::Pipeline>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastUpObjectTest() { GstBin *bin = GST_BIN(gst_object_ref(gst_bin_new(NULL))); gst_object_sink(bin); { QGst::BinPtr object = QGst::BinPtr::wrap(bin); QVERIFY(!object.dynamicCast<QGst::Element>().isNull()); QVERIFY(!object.dynamicCast<QGlib::Object>().isNull()); QVERIFY(!object.dynamicCast<QGst::ChildProxy>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastObjectToIfaceTest() { QGst::ElementPtr e = QGst::ElementFactory::make("fakesrc"); QGst::UriHandlerPtr u = e.dynamicCast<QGst::UriHandler>(); QVERIFY(u.isNull()); e = QGst::ElementFactory::make("filesrc"); u = e.dynamicCast<QGst::UriHandler>(); QVERIFY(!u.isNull()); } void RefPointerTest::dynamicCastIfaceToObjectTest() { GstElement *e = gst_element_factory_make("filesrc", NULL); gst_object_ref_sink(e); QGst::UriHandlerPtr u = QGst::UriHandlerPtr::wrap(GST_URI_HANDLER(e), false); QVERIFY(!u.isNull()); QVERIFY(!u.dynamicCast<QGst::Element>().isNull()); } void RefPointerTest::cppWrappersTest() { QGst::ElementPtr e = QGst::ElementFactory::make("playbin2"); QVERIFY(!e.isNull()); { QGst::PipelinePtr pipeline = e.dynamicCast<QGst::Pipeline>(); QVERIFY(!pipeline.isNull()); //the C++ wrappers must be the same QCOMPARE(static_cast<QGlib::RefCountedObject*>(pipeline.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::ChildProxyPtr proxy = e.dynamicCast<QGst::ChildProxy>(); QVERIFY(!proxy.isNull()); //the C++ wrappers must be the same QCOMPARE(static_cast<QGlib::RefCountedObject*>(proxy.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { //new wrap() should give the same C++ instance GstElement *gobj = e; QGst::ElementPtr e2 = QGst::ElementPtr::wrap(gobj); QCOMPARE(static_cast<QGlib::RefCountedObject*>(e2.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::StreamVolumePtr sv = e.dynamicCast<QGst::StreamVolume>(); QVERIFY(!sv.isNull()); //now the C++ wrapper must not be the same, since Pipeline does not inherit StreamVolume QVERIFY(static_cast<QGlib::RefCountedObject*>(sv.operator->()) != static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::MessagePtr msg = QGst::ApplicationMessage::create(e); QGst::MessagePtr msg2 = msg; QCOMPARE(static_cast<QGlib::RefCountedObject*>(msg.operator->()), static_cast<QGlib::RefCountedObject*>(msg2.operator->())); QVERIFY(msg2 == msg); QGst::MessagePtr msg3 = QGst::MessagePtr::wrap(msg2); QVERIFY(static_cast<QGlib::RefCountedObject*>(msg3.operator->()) != static_cast<QGlib::RefCountedObject*>(msg2.operator->())); QVERIFY(msg3 == msg2); } } void RefPointerTest::messageDynamicCastTest() { QGst::BinPtr bin = QGst::Bin::create(); QGst::MessagePtr msg = QGst::ApplicationMessage::create(bin); QVERIFY(!msg.isNull()); QVERIFY(!msg.dynamicCast<QGst::ApplicationMessage>().isNull()); QVERIFY(msg.dynamicCast<QGst::EosMessage>().isNull()); } void RefPointerTest::equalityTest() { QGst::BinPtr bin = QGst::Bin::create(); QGst::ElementPtr element = bin; QVERIFY(element == bin); QVERIFY(bin == element); QVERIFY(bin == bin); GstElement *e = element; QVERIFY(e == element); QVERIFY(element == e); QVERIFY(bin == e); QVERIFY(e == bin); e++; QVERIFY(e != element); QVERIFY(element != e); QVERIFY(bin != e); QVERIFY(e != bin); e = NULL; QVERIFY(e != element); QVERIFY(element != e); QVERIFY(bin != e); QVERIFY(e != bin); element.clear(); QVERIFY(element != bin); QVERIFY(bin != element); QVERIFY(e == element); QVERIFY(element == e); bin.clear(); QVERIFY(element == bin); QVERIFY(bin == element); QVERIFY(bin == bin); QVERIFY(bin == e); QVERIFY(e == bin); } QTEST_APPLESS_MAIN(RefPointerTest) #include "moc_qgsttest.cpp" #include "refpointertest.moc" <commit_msg>tests/auto/refpointertest.cpp gst_object_sink was removed.<commit_after>/* Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com> Copyright (C) 2010 Collabora Ltd. @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk> 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qgsttest.h" #include <QGst/Object> #include <QGst/Message> #include <QGst/Pipeline> #include <QGst/ElementFactory> #include <QGst/UriHandler> #include <QGst/StreamVolume> class RefPointerTest : public QGstTest { Q_OBJECT private Q_SLOTS: void refTest1(); void refTest2(); void dynamicCastTest(); void dynamicCastDownObjectTest(); void dynamicCastUpObjectTest(); void dynamicCastObjectToIfaceTest(); void dynamicCastIfaceToObjectTest(); void cppWrappersTest(); void messageDynamicCastTest(); void equalityTest(); }; void RefPointerTest::refTest1() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); gst_object_sink(bin); QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin, false); QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1); } void RefPointerTest::refTest2() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); { QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin); QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 2); { QGst::ObjectPtr object2 = object; QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 3); } } QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1); gst_object_unref(bin); } void RefPointerTest::dynamicCastTest() { GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL)))); { QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin); QVERIFY(!object.dynamicCast<QGlib::Object>().isNull()); } { QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin)); QVERIFY(!object.dynamicCast<QGst::Object>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastDownObjectTest() { GstObject *bin = GST_OBJECT(gst_object_ref(gst_bin_new(NULL))); { QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin)); QVERIFY(!object.dynamicCast<QGst::Object>().isNull()); QVERIFY(!object.dynamicCast<QGst::Bin>().isNull()); QVERIFY(object.dynamicCast<QGst::Pipeline>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastUpObjectTest() { GstBin *bin = GST_BIN(gst_object_ref(gst_bin_new(NULL))); { QGst::BinPtr object = QGst::BinPtr::wrap(bin); QVERIFY(!object.dynamicCast<QGst::Element>().isNull()); QVERIFY(!object.dynamicCast<QGlib::Object>().isNull()); QVERIFY(!object.dynamicCast<QGst::ChildProxy>().isNull()); } gst_object_unref(bin); } void RefPointerTest::dynamicCastObjectToIfaceTest() { QGst::ElementPtr e = QGst::ElementFactory::make("fakesrc"); QGst::UriHandlerPtr u = e.dynamicCast<QGst::UriHandler>(); QVERIFY(u.isNull()); e = QGst::ElementFactory::make("filesrc"); u = e.dynamicCast<QGst::UriHandler>(); QVERIFY(!u.isNull()); } void RefPointerTest::dynamicCastIfaceToObjectTest() { GstElement *e = gst_element_factory_make("filesrc", NULL); gst_object_ref_sink(e); QGst::UriHandlerPtr u = QGst::UriHandlerPtr::wrap(GST_URI_HANDLER(e), false); QVERIFY(!u.isNull()); QVERIFY(!u.dynamicCast<QGst::Element>().isNull()); } void RefPointerTest::cppWrappersTest() { QGst::ElementPtr e = QGst::ElementFactory::make("playbin2"); QVERIFY(!e.isNull()); { QGst::PipelinePtr pipeline = e.dynamicCast<QGst::Pipeline>(); QVERIFY(!pipeline.isNull()); //the C++ wrappers must be the same QCOMPARE(static_cast<QGlib::RefCountedObject*>(pipeline.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::ChildProxyPtr proxy = e.dynamicCast<QGst::ChildProxy>(); QVERIFY(!proxy.isNull()); //the C++ wrappers must be the same QCOMPARE(static_cast<QGlib::RefCountedObject*>(proxy.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { //new wrap() should give the same C++ instance GstElement *gobj = e; QGst::ElementPtr e2 = QGst::ElementPtr::wrap(gobj); QCOMPARE(static_cast<QGlib::RefCountedObject*>(e2.operator->()), static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::StreamVolumePtr sv = e.dynamicCast<QGst::StreamVolume>(); QVERIFY(!sv.isNull()); //now the C++ wrapper must not be the same, since Pipeline does not inherit StreamVolume QVERIFY(static_cast<QGlib::RefCountedObject*>(sv.operator->()) != static_cast<QGlib::RefCountedObject*>(e.operator->())); } { QGst::MessagePtr msg = QGst::ApplicationMessage::create(e); QGst::MessagePtr msg2 = msg; QCOMPARE(static_cast<QGlib::RefCountedObject*>(msg.operator->()), static_cast<QGlib::RefCountedObject*>(msg2.operator->())); QVERIFY(msg2 == msg); QGst::MessagePtr msg3 = QGst::MessagePtr::wrap(msg2); QVERIFY(static_cast<QGlib::RefCountedObject*>(msg3.operator->()) != static_cast<QGlib::RefCountedObject*>(msg2.operator->())); QVERIFY(msg3 == msg2); } } void RefPointerTest::messageDynamicCastTest() { QGst::BinPtr bin = QGst::Bin::create(); QGst::MessagePtr msg = QGst::ApplicationMessage::create(bin); QVERIFY(!msg.isNull()); QVERIFY(!msg.dynamicCast<QGst::ApplicationMessage>().isNull()); QVERIFY(msg.dynamicCast<QGst::EosMessage>().isNull()); } void RefPointerTest::equalityTest() { QGst::BinPtr bin = QGst::Bin::create(); QGst::ElementPtr element = bin; QVERIFY(element == bin); QVERIFY(bin == element); QVERIFY(bin == bin); GstElement *e = element; QVERIFY(e == element); QVERIFY(element == e); QVERIFY(bin == e); QVERIFY(e == bin); e++; QVERIFY(e != element); QVERIFY(element != e); QVERIFY(bin != e); QVERIFY(e != bin); e = NULL; QVERIFY(e != element); QVERIFY(element != e); QVERIFY(bin != e); QVERIFY(e != bin); element.clear(); QVERIFY(element != bin); QVERIFY(bin != element); QVERIFY(e == element); QVERIFY(element == e); bin.clear(); QVERIFY(element == bin); QVERIFY(bin == element); QVERIFY(bin == bin); QVERIFY(bin == e); QVERIFY(e == bin); } QTEST_APPLESS_MAIN(RefPointerTest) #include "moc_qgsttest.cpp" #include "refpointertest.moc" <|endoftext|>
<commit_before>#include "core/connection.hpp" // boost #include <boost/test/unit_test.hpp> /** * Example test cases for core connections. * These this test shows how connections are used in general. * Tests for special cases are below. */ BOOST_AUTO_TEST_CASE(examples) { //test trivial connection of two objects auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter // this connection has no parameter and returns and int. auto one_plus_one = connect(give_one, increment); BOOST_CHECK(one_plus_one() == 2); //test chained connection, //take connection from above and add a new connectable as a sink. auto two_plus_one = connect(one_plus_one, increment); BOOST_CHECK(two_plus_one() == 3); //connections can have both, parameters and return values: { // connection of two anonymous nodes, takes and returns an int. auto plus_two = connect ( [](int i) ->int {return i+1;}, [](int i) ->int {return i+1;} ); BOOST_CHECK(plus_two(1) == 3); } //this is completely equivalent to: { auto plus_two = connect(increment, increment); BOOST_CHECK(plus_two(1) == 3); } } // test cases for different pairs of parameter and result types BOOST_AUTO_TEST_CASE(parameter_result_pairs) { // this variable is captures by lambdas // to check if lambdas without return values work. int capture_ref = 0; auto write_param = [&](int i){ capture_ref = i; }; auto increment = [](int i) -> int {return i+1;}; // this connection takes a parameter and returns void // An int is transmitted as payload between source and sink. auto write_increment = connect(increment, write_param); write_increment(0); BOOST_CHECK(capture_ref == 1); auto do_nothing = [](){}; auto set_two = [&](){ capture_ref = 2; }; // This connection takes no parameter, and returns void // There is also no payload between source and sink. auto set_one_connection = connect(do_nothing, set_two); set_one_connection(); BOOST_CHECK(capture_ref == 2); // This connection takes no paramter and returns and int. // An int is transmitted as payload between source and sink. auto give_one = [](){return 1;}; BOOST_CHECK(connect(give_one, increment)() == 2); // This connection takes no paramter and returns and int. // There is also no payload between source and sink. BOOST_CHECK(connect(do_nothing, give_one)() == 1); // This connection takes no paramter and returns and void. // There is also no payload between source and sink. auto write_nine = [&](){ capture_ref = 9; }; connect(do_nothing, write_nine)(); BOOST_CHECK(capture_ref == 9); } <commit_msg>added last tests for connection<commit_after>#include "core/connection.hpp" // boost #include <boost/test/unit_test.hpp> /** * Example test cases for core connections. * These this test shows how connections are used in general. * Tests for special cases are below. */ BOOST_AUTO_TEST_CASE(examples) { //test trivial connection of two objects auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter // this connection has no parameter and returns and int. auto one_plus_one = connect(give_one, increment); BOOST_CHECK(one_plus_one() == 2); //test chained connection, //take connection from above and add a new connectable as a sink. auto two_plus_one = connect(one_plus_one, increment); BOOST_CHECK(two_plus_one() == 3); //connections can have both, parameters and return values: { // connection of two anonymous nodes, takes and returns an int. auto plus_two = connect ( [](int i) ->int {return i+1;}, [](int i) ->int {return i+1;} ); BOOST_CHECK(plus_two(1) == 3); } //this is completely equivalent to: { auto plus_two = connect(increment, increment); BOOST_CHECK(plus_two(1) == 3); } } // test cases for different pairs of parameter and result types BOOST_AUTO_TEST_CASE(parameter_result_pairs) { // this variable is captures by lambdas // to check if lambdas without return values work. int capture_ref = 0; //named differnt sources and sinks to make tests more readable auto write_param = [&](int i){ capture_ref = i; }; auto increment = [](int i) -> int {return i+1;}; auto give_one = [](){return 1;}; auto give_three = [](){return 3;}; auto do_nothing = [](){}; auto ignore_in = [](int i){}; auto increment_ref = [&](){ capture_ref++; }; // param int, payload int, result int auto plus_two = connect(increment, increment); BOOST_CHECK_EQUAL(plus_two(1), 3); // param int, payload int, result void // this connection takes a parameter and returns void // An int is transmitted as payload between source and sink. auto write_increment = connect(increment, write_param); write_increment(0); BOOST_CHECK_EQUAL(capture_ref,1); // param int, payload void, result int auto ignore_input_return1 = connect(ignore_in, give_one); BOOST_CHECK_EQUAL(ignore_input_return1(99), 1); // param int, payload void, result void connect(ignore_in, increment_ref)(99); BOOST_CHECK_EQUAL(capture_ref, 2); // param void, payload int, result int // This connection takes no paramter and returns an int. // An int is transmitted as payload between source and sink. BOOST_CHECK_EQUAL(connect(give_one, increment)(), 2); // param void, payload int, result void connect(give_three, write_param)(); BOOST_CHECK_EQUAL(capture_ref, 3); // param void, payload void, result int // This connection takes no paramter and returns and int. // There is also no payload between source and sink. BOOST_CHECK_EQUAL(connect(do_nothing, give_one)(),1); // param void, payload void, result void // This connection takes no parameter, and returns void // There is also no payload between source and sink. connect(do_nothing, increment_ref)(); BOOST_CHECK_EQUAL(capture_ref, 4); } <|endoftext|>
<commit_before>#include <iostream> #include <cassert> #include <random> #include <tuple> #include <map> #include <vector> #include <algorithm> #include <memory> #include <google/profiler.h> #include <boost/timer.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <apr_mmap.h> #include <apr_general.h> #include "akumuli.h" #include "page.h" #include "storage.h" #include "sequencer.h" using namespace Akumuli; using namespace std; const int NUM_ITERATIONS = 100*1000*1000; int main(int cnt, const char** args) { aku_initialize(nullptr); { std::cout << "Sequencer perf-test, ordered timestamps" << std::endl; // Patience sort perf-test boost::timer timer; size_t ix_merged = 0; Sequencer seq(nullptr, {0, 10000, 0}); for (int ix = 0u; ix < NUM_ITERATIONS; ix++) { TimeSeriesValue value({(uint64_t)ix}, ix & 0xFF, (aku_EntryOffset)ix, 8); int status = 0; int lock = 0; tie(status, lock) = seq.add(value); if (lock % 2 == 1) { CursorResult results[0x10000]; BufferedCursor cursor(results, 0x10000); Caller caller; seq.merge(caller, &cursor); for (size_t i = 0; i < cursor.count; i++) { if (cursor.results_buffer[i].data_offset != ix_merged) { // report error std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl; return -1; } ix_merged++; } } if (ix % 1000000 == 0) { std::cout << ix << " " << timer.elapsed() << "s" << std::endl; timer.restart(); } } } { std::cout << "Sequencer perf-test, unordered timestamps" << std::endl; // Patience sort perf-test boost::timer timer; size_t ix_merged = 0; const int buffer_size = 10000; int buffer[buffer_size]; int buffer_ix = buffer_size; Sequencer seq(nullptr, {10000}); for (int ix = 0u; ix < NUM_ITERATIONS; ix++) { buffer_ix--; buffer[buffer_ix] = ix; if (buffer_ix == 0) { buffer_ix = buffer_size; for(auto ixx: buffer) { TimeSeriesValue value({(uint64_t)ixx}, ixx & 0xFF, (aku_EntryOffset)ixx, 8); int status = 0; int lock = 0; tie(status, lock) = seq.add(value); if (lock % 2 == 1) { CursorResult results[0x10000]; BufferedCursor cursor(results, 0x10000); Caller caller; seq.merge(caller, &cursor); for (size_t i = 0; i < cursor.count; i++) { if (cursor.results_buffer[i].data_offset != ix_merged) { // report error std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl; return -1; } ix_merged++; } } } } if (ix % 1000000 == 0) { std::cout << ix << " " << timer.elapsed() << "s" << std::endl; timer.restart(); } } } return 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include <cassert> #include <random> #include <tuple> #include <map> #include <vector> #include <algorithm> #include <memory> #include <boost/timer.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <apr_mmap.h> #include <apr_general.h> #include "akumuli.h" #include "page.h" #include "storage.h" #include "sequencer.h" using namespace Akumuli; using namespace std; const int NUM_ITERATIONS = 100*1000*1000; int main(int cnt, const char** args) { aku_initialize(nullptr); { std::cout << "Sequencer perf-test, ordered timestamps" << std::endl; // Patience sort perf-test boost::timer timer; size_t ix_merged = 0; Sequencer seq(nullptr, {0, 10000, 0}); for (int ix = 0u; ix < NUM_ITERATIONS; ix++) { TimeSeriesValue value({(uint64_t)ix}, ix & 0xFF, (aku_EntryOffset)ix, 8); int status = 0; int lock = 0; tie(status, lock) = seq.add(value); if (lock % 2 == 1) { CursorResult results[0x10000]; BufferedCursor cursor(results, 0x10000); Caller caller; seq.merge(caller, &cursor); for (size_t i = 0; i < cursor.count; i++) { if (cursor.results_buffer[i].data_offset != ix_merged) { // report error std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl; return -1; } ix_merged++; } } if (ix % 1000000 == 0) { std::cout << ix << " " << timer.elapsed() << "s" << std::endl; timer.restart(); } } } { std::cout << "Sequencer perf-test, unordered timestamps" << std::endl; // Patience sort perf-test boost::timer timer; size_t ix_merged = 0; const int buffer_size = 10000; int buffer[buffer_size]; int buffer_ix = buffer_size; Sequencer seq(nullptr, {10000}); for (int ix = 0u; ix < NUM_ITERATIONS; ix++) { buffer_ix--; buffer[buffer_ix] = ix; if (buffer_ix == 0) { buffer_ix = buffer_size; for(auto ixx: buffer) { TimeSeriesValue value({(uint64_t)ixx}, ixx & 0xFF, (aku_EntryOffset)ixx, 8); int status = 0; int lock = 0; tie(status, lock) = seq.add(value); if (lock % 2 == 1) { CursorResult results[0x10000]; BufferedCursor cursor(results, 0x10000); Caller caller; seq.merge(caller, &cursor); for (size_t i = 0; i < cursor.count; i++) { if (cursor.results_buffer[i].data_offset != ix_merged) { // report error std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl; return -1; } ix_merged++; } } } } if (ix % 1000000 == 0) { std::cout << ix << " " << timer.elapsed() << "s" << std::endl; timer.restart(); } } } return 0; } <|endoftext|>
<commit_before>#include <libcryptosec/ECDSAKeyPair.h> #include <libcryptosec/ec/Curve.h> #include <libcryptosec/ec/BrainpoolCurveFactory.h> #include <fstream> #include "gtest.h" #include <stdio.h> class BrainpoolEcTest : public ::testing::Test { protected: virtual void SetUp() { } void testHardcodedCurve(BrainpoolCurveFactory::CurveName curveName){ const Curve * curve = BrainpoolCurveFactory::getCurve(curveName); ECDSAKeyPair keypair (*curve); std::string pem = keypair.getPemEncoded(); EXPECT_TRUE(pem.size() > 0); //TODO melhorar testes da chave fazendo assinatura } void testKeyPairFromFile(fstream &file){ if(file.is_open()){ /* Read file into ByteArray*/ file.seekg (0, file.end); int length = file.tellg(); file.seekg (0, file.beg); unsigned char * memblock = new unsigned char [length]; file.read ((char*)memblock, length); file.close(); ByteArray b(memblock, length); delete[] memblock; /*Do crypto*/ ECDSAKeyPair keypair(b); std::string pem = keypair.getPemEncoded(); EXPECT_TRUE(pem.size() > 0); //TODO melhorar testes da chave fazendo assinatura } else { FAIL(); } } }; TEST_F(BrainpoolEcTest, HardcodedBpTestBP160r1){ testHardcodedCurve(BrainpoolCurveFactory::BP160r1); } //TEST_F(BrainpoolEcTest, HardcodedBpTestBP160t1){ // // testHardcodedCurve(BrainpoolCurveFactory::BP160t1); // //} TEST_F(BrainpoolEcTest, HardcodedBpTestBP192r1){ testHardcodedCurve(BrainpoolCurveFactory::BP192r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP192t1){ testHardcodedCurve(BrainpoolCurveFactory::BP192t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP224r1){ testHardcodedCurve(BrainpoolCurveFactory::BP224r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP224t1){ testHardcodedCurve(BrainpoolCurveFactory::BP224t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP256r1){ testHardcodedCurve(BrainpoolCurveFactory::BP256r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP256t1){ testHardcodedCurve(BrainpoolCurveFactory::BP256t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP320r1){ testHardcodedCurve(BrainpoolCurveFactory::BP320r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP320t1){ testHardcodedCurve(BrainpoolCurveFactory::BP320t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP384r1){ testHardcodedCurve(BrainpoolCurveFactory::BP384r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP384t1){ testHardcodedCurve(BrainpoolCurveFactory::BP384t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP512r1){ testHardcodedCurve(BrainpoolCurveFactory::BP512r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP512t1){ testHardcodedCurve(BrainpoolCurveFactory::BP512t1); } TEST_F(BrainpoolEcTest, DerFormatedTestBp160r1){ std::fstream file("files/BP160r1", ios::in|ios::binary|ios::ate); testKeyPairFromFile(file); } TEST_F(BrainpoolEcTest, DerFormatedTestBp512r1){ std::fstream file("files/BP512r1", ios::in|ios::binary|ios::ate); testKeyPairFromFile(file); } <commit_msg>Remocao do comentario no teste P160t1<commit_after>#include <libcryptosec/ECDSAKeyPair.h> #include <libcryptosec/ec/Curve.h> #include <libcryptosec/ec/BrainpoolCurveFactory.h> #include <fstream> #include "gtest.h" #include <stdio.h> class BrainpoolEcTest : public ::testing::Test { protected: virtual void SetUp() { } void testHardcodedCurve(BrainpoolCurveFactory::CurveName curveName){ const Curve * curve = BrainpoolCurveFactory::getCurve(curveName); ECDSAKeyPair keypair (*curve); std::string pem = keypair.getPemEncoded(); EXPECT_TRUE(pem.size() > 0); //TODO melhorar testes da chave fazendo assinatura } void testKeyPairFromFile(fstream &file){ if(file.is_open()){ /* Read file into ByteArray*/ file.seekg (0, file.end); int length = file.tellg(); file.seekg (0, file.beg); unsigned char * memblock = new unsigned char [length]; file.read ((char*)memblock, length); file.close(); ByteArray b(memblock, length); delete[] memblock; /*Do crypto*/ ECDSAKeyPair keypair(b); std::string pem = keypair.getPemEncoded(); EXPECT_TRUE(pem.size() > 0); //TODO melhorar testes da chave fazendo assinatura } else { FAIL(); } } }; TEST_F(BrainpoolEcTest, HardcodedBpTestBP160r1){ testHardcodedCurve(BrainpoolCurveFactory::BP160r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP160t1){ testHardcodedCurve(BrainpoolCurveFactory::BP160t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP192r1){ testHardcodedCurve(BrainpoolCurveFactory::BP192r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP192t1){ testHardcodedCurve(BrainpoolCurveFactory::BP192t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP224r1){ testHardcodedCurve(BrainpoolCurveFactory::BP224r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP224t1){ testHardcodedCurve(BrainpoolCurveFactory::BP224t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP256r1){ testHardcodedCurve(BrainpoolCurveFactory::BP256r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP256t1){ testHardcodedCurve(BrainpoolCurveFactory::BP256t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP320r1){ testHardcodedCurve(BrainpoolCurveFactory::BP320r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP320t1){ testHardcodedCurve(BrainpoolCurveFactory::BP320t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP384r1){ testHardcodedCurve(BrainpoolCurveFactory::BP384r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP384t1){ testHardcodedCurve(BrainpoolCurveFactory::BP384t1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP512r1){ testHardcodedCurve(BrainpoolCurveFactory::BP512r1); } TEST_F(BrainpoolEcTest, HardcodedBpTestBP512t1){ testHardcodedCurve(BrainpoolCurveFactory::BP512t1); } TEST_F(BrainpoolEcTest, DerFormatedTestBp160r1){ std::fstream file("files/BP160r1", ios::in|ios::binary|ios::ate); testKeyPairFromFile(file); } TEST_F(BrainpoolEcTest, DerFormatedTestBp512r1){ std::fstream file("files/BP512r1", ios::in|ios::binary|ios::ate); testKeyPairFromFile(file); } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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. */ /* HIT_START * BUILD: %t %s test_common.cpp NVCC_OPTIONS -std=c++11 * RUN: %t * HIT_END */ #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string> using namespace std; //./hipEnvVar -c -d 0 -h //putenv("SomeVariable=SomeValue"); //putenv("export HIP_VISIBLE_DEVICES=0,1,2,3"); int getDeviceNumber(){ FILE *in; char buff[512]; string str; if(!(in = popen("./hipEnvVar -c", "r"))){ return 1; } fgets(buff, sizeof(buff), in); pclose(in); return atoi(buff); } int getDevicePCIBusNum(int deviceID){ FILE *in; char buff[512]; string str = "./hipEnvVar -d "; str += std::to_string(deviceID); if(!(in = popen(str.c_str(), "r"))){ return 1; } fgets(buff, sizeof(buff), in); pclose(in); return atoi(buff); } int main() { unsetenv("HIP_VISIBLE_DEVICES"); unsetenv("CUDA_VISIBLE_DEVICES"); //collect the device pci bus ID for all devices int totalDeviceNum = getDeviceNumber(); std::cout << "The total number of available devices is " << totalDeviceNum<< std::endl <<"Valid index range is 0 - "<<totalDeviceNum-1<<std::endl; std::vector<int> devPCINum; for (int i = 0; i < totalDeviceNum ; i++) { devPCINum.push_back(getDevicePCIBusNum(i)); std::cout <<"The collected device PCI Bus ID of Device "<<i<<" is " << getDevicePCIBusNum(i) << std::endl; } //select each of the available devices to be the target device, //query the returned device pci bus number, check if match the database for (int i = 0; i < totalDeviceNum ; i++) { setenv("HIP_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1); setenv("CUDA_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1); //cout<<"HIP_VISIBLE_DEVICES is "<<i<<" data in vector is "<<devPCINum[i]<<endl; //std::cout <<"Returned pci number is"<< getDevicePCIBusNum(0) << std::endl; if (devPCINum[i] != getDevicePCIBusNum(0)) { std::cout << "The returned PciBusID is not correct" << std::endl; exit(-1); } else { continue; } } //check when set an invalid device number setenv("HIP_VISIBLE_DEVICES","1000,0,1",1); setenv("CUDA_VISIBLE_DEVICES","1000,0,1",1); assert(getDeviceNumber() == 0); if(totalDeviceNum > 2){ setenv("HIP_VISIBLE_DEVICES","0,1,1000,2",1); setenv("CUDA_VISIBLE_DEVICES","0,1,1000,2",1); assert(getDeviceNumber() == 2); setenv("HIP_VISIBLE_DEVICES","0,1,2",1); setenv("CUDA_VISIBLE_DEVICES","0,1,2",1); assert(getDeviceNumber() == 3); // test if CUDA_VISIBLE_DEVICES will be accepted by the runtime unsetenv("HIP_VISIBLE_DEVICES"); unsetenv("CUDA_VISIBLE_DEVICES"); setenv("CUDA_VISIBLE_DEVICES","0,1,2",1); assert(getDeviceNumber() == 3); } setenv("HIP_VISIBLE_DEVICES","-100,0,1",1); setenv("CUDA_VISIBLE_DEVICES","-100,0,1",1); assert(getDeviceNumber() == 0); std::cout << "PASSED" << std::endl; return 0; } <commit_msg>change hipEnvVarDriver to reduce communications to hipEnvVar<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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. */ /* HIT_START * BUILD: %t %s test_common.cpp NVCC_OPTIONS -std=c++11 * RUN: %t * HIT_END */ #include <iostream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string> #include <hip_runtime.h> using namespace std; int getDeviceNumber(){ FILE *in; char buff[512]; string str; if(!(in = popen("./hipEnvVar -c", "r"))){ return 1; } fgets(buff, sizeof(buff), in); pclose(in); return atoi(buff); } // Query the current device ID remotely to hipEnvVar int getDevicePCIBusNumRemote(int deviceID){ FILE *in; char buff[512]; string str = "./hipEnvVar -d "; str += std::to_string(deviceID); if(!(in = popen(str.c_str(), "r"))){ return 1; } fgets(buff, sizeof(buff), in); pclose(in); return atoi(buff); } // Query the current device ID locally int getDevicePCIBusNum(int deviceID){ hipSetDevice(deviceID); hipDeviceProp_t devProp; hipGetDeviceProperties(&devProp, deviceID); if (devProp.major < 1) { printf("%d does not support HIP\n", deviceID); return -1; } return devProp.pciBusID; } int main() { unsetenv("HIP_VISIBLE_DEVICES"); unsetenv("CUDA_VISIBLE_DEVICES"); //collect the device pci bus ID for all devices int totalDeviceNum = getDeviceNumber(); std::cout << "The total number of available devices is " << totalDeviceNum<< std::endl <<"Valid index range is 0 - "<<totalDeviceNum-1<<std::endl; std::vector<int> devPCINum; for (int i = 0; i < totalDeviceNum ; i++) { devPCINum.push_back(getDevicePCIBusNum(i)); std::cout <<"The collected device PCI Bus ID of Device "<<i<<" is " << getDevicePCIBusNum(i) << std::endl; } //select each of the available devices to be the target device, //query the returned device pci bus number, check if match the database for (int i = 0; i < totalDeviceNum ; i++) { setenv("HIP_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1); setenv("CUDA_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1); if (devPCINum[i] != getDevicePCIBusNumRemote(0)) { std::cout << "The returned PciBusID is not correct"<< std::endl; std::cout << "Expected "<< devPCINum[i] << ", but get " << getDevicePCIBusNum << endl; exit(-1); } else { continue; } } //check when set an invalid device number setenv("HIP_VISIBLE_DEVICES","1000,0,1",1); setenv("CUDA_VISIBLE_DEVICES","1000,0,1",1); assert(getDeviceNumber() == 0); if(totalDeviceNum > 2){ setenv("HIP_VISIBLE_DEVICES","0,1,1000,2",1); setenv("CUDA_VISIBLE_DEVICES","0,1,1000,2",1); assert(getDeviceNumber() == 2); setenv("HIP_VISIBLE_DEVICES","0,1,2",1); setenv("CUDA_VISIBLE_DEVICES","0,1,2",1); assert(getDeviceNumber() == 3); // test if CUDA_VISIBLE_DEVICES will be accepted by the runtime unsetenv("HIP_VISIBLE_DEVICES"); unsetenv("CUDA_VISIBLE_DEVICES"); setenv("CUDA_VISIBLE_DEVICES","0,1,2",1); assert(getDeviceNumber() == 3); } setenv("HIP_VISIBLE_DEVICES","-100,0,1",1); setenv("CUDA_VISIBLE_DEVICES","-100,0,1",1); assert(getDeviceNumber() == 0); std::cout << "PASSED" << std::endl; return 0; } <|endoftext|>
<commit_before>#include "main.h" //just an example int main() { ustring addre; addre.fromString(string("BM-2cUwUoj9YKoxsZMKT7C5N46tC1KTdUQZpH")); //just a test address PubAddr address; bool loaded = address.loadAddr(addre); BitMRC bitmrc; bitmrc.start(); if(loaded) bitmrc.getPubKey(address); while (1) { printf("Select a command: "); char command[256]; scanf("%s", command); if (!strcmp("quit", command)) break; else if (!strcmp("send", command)) { if (bitmrc.PrivAddresses.size() == 0) { printf("No private address\n"); continue; } if (bitmrc.PubAddresses.size() == 0) { printf("No public address\n"); continue; } for (int i = 0; i < bitmrc.PubAddresses.size(); i++) { printf("[%d] Public key: %s Ready: %s\n", i, bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True"); } printf("Select destination address: "); int des; scanf("%d", &des); if (des < 0 || des >= bitmrc.PubAddresses.size()) { printf("Incorrect selection\n"); continue; } for (int i = 0; i < bitmrc.PrivAddresses.size(); i++) { printf("[%d] Private key: %s\n", i, bitmrc.PrivAddresses[i].getAddress().c_str()); } printf("Select from address: "); int fro; scanf("%d", &fro); if (fro < 0 || fro >= bitmrc.PubAddresses.size()) { printf("Incorrect selection\n"); continue; } ustring msg; printf("Message to send:\n"); scanf("%s", command); msg.fromString(command); bitmrc.sendMessage(msg, bitmrc.PubAddresses[des], bitmrc.PrivAddresses[fro]); //maybe this should be done in another thread printf("Message sent\n"); } else if (!strcmp("address", command)) { scanf("%s", command); if (!strcmp("generate", command)) { scanf("%s", command); if (!strcmp("deterministic", command)) { scanf("%s", command); ustring pass; pass.fromString(command); bitmrc.generateDeterministicAddr(pass, 1); //cant print it because this function wont show the results } else if (!strcmp("random", command)) { Addr privateAddr; privateAddr.generateRandom(); bitmrc.saveAddr(privateAddr); printf("Generated %s\n", privateAddr.getAddress().c_str()); } } else if (!strcmp("public", command)) { scanf("%s", command); ustring addre; addre.fromString(string(command)); PubAddr address; bool loaded = address.loadAddr(addre); if (loaded) { printf("Asking public key!\n"); bitmrc.getPubKey(address); printf("Asked! check publickey for news on that address!\n"); } else printf("Address not correct!\n"); } } else if (!strcmp("check", command)) { scanf("%s", command); if (!strcmp("message", command)) { //this should be done asynchronous because this will stuck this thread if no message is incoming BitMRC::message mess = bitmrc.new_messages.pop(); printf("New message:\nFrom: %s\nTo: %s\nMessage:\n%s\n", mess.from.c_str(), mess.to.c_str(), mess.info.c_str()); } else if (!strcmp("connections", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_nodes); for (int i = 0; i < bitmrc.Nodes.size(); i++) { if (bitmrc.Nodes[i]->state == 2) { printf("Node: %s:%s Connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str()); } else if (bitmrc.Nodes[i]->state == 0) { printf("Node: %s:%s Not connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str()); } } mlock.unlock(); } else if (!strcmp("privatekey", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_priv); if (bitmrc.PrivAddresses.size() == 0) printf("No private key\n"); for (int i = 0; i < bitmrc.PrivAddresses.size(); i++) { printf("Private key: %s\n", bitmrc.PrivAddresses[i].getAddress().c_str()); } mlock.unlock(); } else if (!strcmp("publickey", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_pub); if (bitmrc.PubAddresses.size() == 0) printf("No public key\n"); for (int i = 0; i < bitmrc.PubAddresses.size(); i++) { printf("Public key: %s Ready: %s\n", bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True"); } mlock.unlock(); } } printf("\n"); } return 0; }<commit_msg>changed main.cpp<commit_after>#include "main.h" //just an example int main() { ustring addre; addre.fromString(string("BM-2cUwUoj9YKoxsZMKT7C5N46tC1KTdUQZpH")); //just a test address PubAddr address; bool loaded = address.loadAddr(addre); BitMRC bitmrc; bitmrc.start(); if(loaded) bitmrc.getPubKey(address); while (1) { printf("Select a command (help): "); char command[256]; scanf("%s", command); if (!strcmp("quit", command)) break; else if (!strcmp("send", command)) { if (bitmrc.PrivAddresses.size() == 0) { printf("No private address\n"); continue; } if (bitmrc.PubAddresses.size() == 0) { printf("No public address\n"); continue; } for (int i = 0; i < bitmrc.PubAddresses.size(); i++) { printf("[%d] Public key: %s Ready: %s\n", i, bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True"); } printf("Select destination address: "); int des; scanf("%d", &des); if (des < 0 || des >= bitmrc.PubAddresses.size()) { printf("Incorrect selection\n"); continue; } for (int i = 0; i < bitmrc.PrivAddresses.size(); i++) { printf("[%d] Private key: %s\n", i, bitmrc.PrivAddresses[i].getAddress().c_str()); } printf("Select from address: "); int fro; scanf("%d", &fro); if (fro < 0 || fro >= bitmrc.PubAddresses.size()) { printf("Incorrect selection\n"); continue; } ustring msg; printf("Message to send:\n"); scanf("%s", command); msg.fromString(command); bitmrc.sendMessage(msg, bitmrc.PubAddresses[des], bitmrc.PrivAddresses[fro]); //maybe this should be done in another thread printf("Message sent\n"); } else if (!strcmp("address", command)) { scanf("%s", command); if (!strcmp("generate", command)) { scanf("%s", command); if (!strcmp("deterministic", command)) { printf("Passphrase: "); scanf("%s", command); ustring pass; pass.fromString(command); bitmrc.generateDeterministicAddr(pass, 1); //cant print it because this function wont show the results } else if (!strcmp("random", command)) { Addr privateAddr; privateAddr.generateRandom(); bitmrc.saveAddr(privateAddr); printf("Generated %s\n", privateAddr.getAddress().c_str()); } } else if (!strcmp("public", command)) { printf("Insert a public address: "); scanf("%s", command); ustring addre; addre.fromString(string(command)); PubAddr address; bool loaded = address.loadAddr(addre); if (loaded) { printf("Asking public key!\n"); bitmrc.getPubKey(address); printf("Asked! check publickey for news on that address!\n"); } else printf("Address not correct!\n"); } } else if (!strcmp("check", command)) { scanf("%s", command); if (!strcmp("message", command)) { //this should be done asynchronous because this will stuck this thread if no message is incoming BitMRC::message mess = bitmrc.new_messages.pop(); printf("New message:\nFrom: %s\nTo: %s\nMessage:\n%s\n", mess.from.c_str(), mess.to.c_str(), mess.info.c_str()); } else if (!strcmp("connections", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_nodes); for (int i = 0; i < bitmrc.Nodes.size(); i++) { if (bitmrc.Nodes[i]->state == 2) { printf("Node: %s:%s Connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str()); } else if (bitmrc.Nodes[i]->state == 0) { printf("Node: %s:%s Not connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str()); } } mlock.unlock(); } else if (!strcmp("privatekey", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_priv); if (bitmrc.PrivAddresses.size() == 0) printf("No private key\n"); for (int i = 0; i < bitmrc.PrivAddresses.size(); i++) { printf("Private key: %s\n", bitmrc.PrivAddresses[i].getAddress().c_str()); } mlock.unlock(); } else if (!strcmp("publickey", command)) { std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_pub); if (bitmrc.PubAddresses.size() == 0) printf("No public key\n"); for (int i = 0; i < bitmrc.PubAddresses.size(); i++) { printf("Public key: %s Ready: %s\n", bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True"); } mlock.unlock(); } } else if (!strcmp("help", command)) { printf("send: send a message\n"); printf("address generate random: generate a random address\n"); printf("address generate deterministic: generate a deterministic address\n"); printf("address public: add public key\n"); printf("check message: wait until a message is in the inbox and display it\n"); printf("check connections: display information about connection nodes\n"); printf("check privatekey: display all the private addresses\n"); printf("check publickey: display all the public addresses\n"); } printf("\n"); } return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #define CATCH_CONFIG_RUNNER #include "mfem.hpp" #include "catch.hpp" mfem::MPI_Session *GlobalMPISession; int main(int argc, char *argv[]) { // There must be exactly one instance. Catch::Session session; // Apply provided command line arguments. int r = session.applyCommandLine(argc, argv); if (r != 0) { return r; } #ifdef MFEM_USE_MPI mfem::MPI_Session mpi; GlobalMPISession = &mpi; // Force tests not tagged as [Parallel] to run only on MPI rank 0 if (mpi.WorldRank() > 0) { auto cfg = session.configData(); cfg.testsOrTags.push_back("[Parallel]"); session.useConfigData(cfg); } if (mpi.WorldSize() > 1 && mpi.Root()) { mfem::out << "WARNING: Only running the [Parallel] label on MPI ranks > 1." << std::endl; } #endif int result = session.run(); return result; } <commit_msg>guard GlobalMPISession<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #define CATCH_CONFIG_RUNNER #include "mfem.hpp" #include "catch.hpp" #ifdef MFEM_USE_MPI mfem::MPI_Session *GlobalMPISession; #endif int main(int argc, char *argv[]) { // There must be exactly one instance. Catch::Session session; // Apply provided command line arguments. int r = session.applyCommandLine(argc, argv); if (r != 0) { return r; } #ifdef MFEM_USE_MPI mfem::MPI_Session mpi; GlobalMPISession = &mpi; // Force tests not tagged as [Parallel] to run only on MPI rank 0 if (mpi.WorldRank() > 0) { auto cfg = session.configData(); cfg.testsOrTags.push_back("[Parallel]"); session.useConfigData(cfg); } if (mpi.WorldSize() > 1 && mpi.Root()) { mfem::out << "WARNING: Only running the [Parallel] label on MPI ranks > 1." << std::endl; } #endif int result = session.run(); return result; } <|endoftext|>
<commit_before>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <cstdlib> #include <cstring> #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> namespace thrill { namespace common { class FastString { public: FastString() : size_(0) { }; FastString(const FastString& in_str) { char* begin = new char[in_str.size_]; std::copy(in_str.data_, in_str.data_ + in_str.size_, begin); data_ = begin; size_ = in_str.size_; has_data_ = true; }; FastString(FastString&& other) : FastString(other.data_, other.size_, other.has_data_) { other.has_data_ = false; }; ~FastString() { if (has_data_) { delete[](data_); } }; static FastString Ref(const char* data, size_t size) { return FastString(data, size, false); } static FastString Ref(std::string::const_iterator data, size_t size) { return FastString(&(*data), size, false); } static FastString Take(const char* data, size_t size) { return FastString(data, size, true); } static FastString Copy(const char* data, size_t size) { char* mem = new char[size]; std::copy(data, data + size, mem); return FastString(mem, size, true); } static FastString Copy(const std::string& in_str) { return Copy(in_str.c_str(), in_str.size()); } const char* Data() const { return data_; } size_t Size() const { return size_; } FastString& operator = (const FastString& other) { if (has_data_) delete[] (data_); char* mem = new char[other.size_]; std::copy(other.data_, other.data_ + other.size_, mem); data_ = mem; size_ = other.size_; has_data_ = true; return *this; } FastString& operator = (FastString&& other) { if (has_data_) delete[] (data_); data_ = std::move(other.data_); size_ = other.Size(); has_data_ = other.has_data_; other.has_data_ = false; return *this; } bool operator == (std::string other) const { // REVIEW(an): use std::equal()! return std::equal(data_, data_ + size_, other.c_str(), other.c_str() + other.size()); } bool operator != (std::string other) const { return !(operator == (other)); } bool operator == (const FastString& other) const { return std::equal(data_, data_ + size_, other.data_, other.data_ + other.size_); } bool operator != (const FastString& other) const { return !(operator == (other)); } friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Data(), fs.Size()); } std::string ToString() const { return std::string(data_, size_); } protected: FastString(const char* data, size_t size, bool copy) : data_(data), size_(size), has_data_(copy) { }; const char* data_ = 0; size_t size_; bool has_data_ = false; }; } // namespace common namespace data { template<typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); char* outdata = new char[size]; ar.Read(outdata, size); return common::FastString::Take(outdata, size); } static const bool is_fixed_size = false; static const size_t fixed_size = 0; }; } //namespace data } // namespace thrill namespace std { //I am very sorry. template <> struct hash<thrill::common::FastString> { size_t operator ()(const thrill::common::FastString& fs) const { unsigned int hash = 0xDEADC0DE; for (size_t ctr = 0; ctr < fs.Size(); ctr++) { hash = ((hash << 5) + hash) + *(fs.Data() + ctr); /* hash * 33 + c */ } return hash; } }; } #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <commit_msg>use same hash function as g++ uses for std::string<commit_after>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <cstdlib> #include <cstring> #include <bits/functional_hash.h> #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> namespace thrill { namespace common { class FastString { public: /** * Default constructor for a FastString. * Doesn't do anything. */ FastString() : size_(0) { }; /** * */ FastString(const FastString& in_str) { char* begin = new char[in_str.size_]; std::copy(in_str.data_, in_str.data_ + in_str.size_, begin); data_ = begin; size_ = in_str.size_; has_data_ = true; }; FastString(FastString&& other) : FastString(other.data_, other.size_, other.has_data_) { other.has_data_ = false; }; ~FastString() { if (has_data_) { delete[](data_); } }; static FastString Ref(const char* data, size_t size) { return FastString(data, size, false); } static FastString Ref(std::string::const_iterator data, size_t size) { return FastString(&(*data), size, false); } static FastString Take(const char* data, size_t size) { return FastString(data, size, true); } static FastString Copy(const char* data, size_t size) { char* mem = new char[size]; std::copy(data, data + size, mem); return FastString(mem, size, true); } static FastString Copy(const std::string& in_str) { return Copy(in_str.c_str(), in_str.size()); } const char* Data() const { return data_; } size_t Size() const { return size_; } FastString& operator = (const FastString& other) { if (has_data_) delete[] (data_); char* mem = new char[other.size_]; std::copy(other.data_, other.data_ + other.size_, mem); data_ = mem; size_ = other.size_; has_data_ = true; return *this; } FastString& operator = (FastString&& other) { if (has_data_) delete[] (data_); data_ = std::move(other.data_); size_ = other.Size(); has_data_ = other.has_data_; other.has_data_ = false; return *this; } bool operator == (std::string other) const { // REVIEW(an): use std::equal()! return std::equal(data_, data_ + size_, other.c_str(), other.c_str() + other.size()); } bool operator != (std::string other) const { return !(operator == (other)); } bool operator == (const FastString& other) const { return std::equal(data_, data_ + size_, other.data_, other.data_ + other.size_); } bool operator != (const FastString& other) const { return !(operator == (other)); } friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Data(), fs.Size()); } std::string ToString() const { return std::string(data_, size_); } protected: FastString(const char* data, size_t size, bool copy) : data_(data), size_(size), has_data_(copy) { }; const char* data_ = 0; size_t size_; bool has_data_ = false; }; } // namespace common namespace data { template<typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); char* outdata = new char[size]; ar.Read(outdata, size); return common::FastString::Take(outdata, size); } static const bool is_fixed_size = false; static const size_t fixed_size = 0; }; } //namespace data } // namespace thrill namespace std { //I am very sorry. template <> struct hash<thrill::common::FastString> { size_t operator ()(const thrill::common::FastString& fs) const { //unsigned int hash = 0xDEADC0DE; return std::_Hash_impl::hash(fs.Data(), fs.Size()); // hash = ((hash << 5) + hash) + *(fs.Data() + ctr); /* hash * 33 + c */ //return hash; } }; } #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2007 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <iostream> #include <fstream> #include <gecode/flatzinc.hh> #include <gecode/flatzinc/logbrancher.hh> using namespace std; using namespace Gecode; int main(int argc, char** argv) { Support::Timer t_total; t_total.start(); FlatZinc::FlatZincOptions opt("Gecode/FlatZinc"); opt.parse(argc, argv); if (argc!=2 && argc!=3) { cerr << "Usage: " << argv[0] << " [options] <file>" << endl; cerr << " " << argv[0] << " -help for more information" << endl; exit(EXIT_FAILURE); } const char* filename = argv[1]; opt.name(filename); const char* logname = NULL; if (argc==3) { logname = argv[2]; } FlatZinc::Printer p; FlatZinc::FlatZincSpace* fg = NULL; try { FlatZinc::ParseResult pr; if (!strcmp(filename, "-")) { pr = FlatZinc::parseWithSymbols(cin, p); } else { pr = FlatZinc::parseWithSymbols(filename, p); } fg = pr.s; if (fg) { ifstream logstream; if (logname) { logstream.open(logname, ifstream::in); branch(*fg, pr.t, pr.a, logstream); opt.c_d(0); opt.a_d(0); } else { fg->createBranchers(fg->solveAnnotations(), opt.seed(), opt.decay(), false, std::cerr); fg->shrinkArrays(p); } if (opt.output()) { std::ofstream os(opt.output()); if (!os.good()) { std::cerr << "Could not open file " << opt.output() << " for output." << std::endl; exit(EXIT_FAILURE); } fg->run(os, p, opt, t_total); os.close(); } else { fg->run(std::cout, p, opt, t_total); } } else { exit(EXIT_FAILURE); } delete fg; } catch (FlatZinc::Error& e) { std::cerr << "Error: " << e.toString() << std::endl; return 1; } return 0; } // STATISTICS: flatzinc-any <commit_msg>Post original branchers after log brancher<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2007 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <iostream> #include <fstream> #include <gecode/flatzinc.hh> #include <gecode/flatzinc/logbrancher.hh> using namespace std; using namespace Gecode; int main(int argc, char** argv) { Support::Timer t_total; t_total.start(); FlatZinc::FlatZincOptions opt("Gecode/FlatZinc"); opt.parse(argc, argv); if (argc!=2 && argc!=3) { cerr << "Usage: " << argv[0] << " [options] <file>" << endl; cerr << " " << argv[0] << " -help for more information" << endl; exit(EXIT_FAILURE); } const char* filename = argv[1]; opt.name(filename); const char* logname = NULL; if (argc==3) { logname = argv[2]; } FlatZinc::Printer p; FlatZinc::FlatZincSpace* fg = NULL; try { FlatZinc::ParseResult pr; if (!strcmp(filename, "-")) { pr = FlatZinc::parseWithSymbols(cin, p); } else { pr = FlatZinc::parseWithSymbols(filename, p); } fg = pr.s; if (fg) { ifstream logstream; if (logname) { logstream.open(logname, ifstream::in); branch(*fg, pr.t, pr.a, logstream); opt.c_d(0); opt.a_d(0); } fg->createBranchers(fg->solveAnnotations(), opt.seed(), opt.decay(), false, std::cerr); if (logname==NULL) { fg->shrinkArrays(p); } if (opt.output()) { std::ofstream os(opt.output()); if (!os.good()) { std::cerr << "Could not open file " << opt.output() << " for output." << std::endl; exit(EXIT_FAILURE); } fg->run(os, p, opt, t_total); os.close(); } else { fg->run(std::cout, p, opt, t_total); } } else { exit(EXIT_FAILURE); } delete fg; } catch (FlatZinc::Error& e) { std::cerr << "Error: " << e.toString() << std::endl; return 1; } return 0; } // STATISTICS: flatzinc-any <|endoftext|>
<commit_before>#ifndef _TRACER_H #define _TRACER_H #include "stdafx.h" #define TRACER_ENABLED 1 #define HEAP 1 #define STACK 2 #define READ 1 #define WRITE 2 #define NOTE 3 #ifdef TRACER_ENABLED void tracer_dump(const string& x); void tracer_dump(const vector<string>& x); void tracer_dump(const map<string, string>& x); void tracer_dump(const vector<double>& x); void tracer_dump(const int &x); void tracer_dump(const float &x); void tracer_dump(const double &x); void tracer_dump(const char &x); void tracer_dump(const IntegerSet &x); void tracer_dump(const boost::regex &x); namespace freicore { namespace myrimatch { struct SpectraList; } } void tracer_dump(const freicore::myrimatch::SpectraList &x); #define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump"; tracer_dump(variable); cout << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << &(variable) << '\t' << type << '\t' << representation << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } // Reference a variable in an operation, do not dump all its info #define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << &(variable) << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' __FILE__ << '\t' << __LINE__ << '\n'; } // Start operation of a given name #define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } // End operation of a given name #define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_S2S(variable) lexical_cast<string>(variable) #else // !TRACER_ENABLED #define TRACER(variable, operation, heap, note) #define TRACER_R(variable, type, representation, operation, heap, note) #define TRACER_UNLINK(variable) #define TRACER_OP_START(name) #define TRACER_OP_END(name) #define TRACER_S2S(variable) #endif // TRACER_ENABLED #endif <commit_msg>Fixing missing tabs<commit_after>#ifndef _TRACER_H #define _TRACER_H #include "stdafx.h" #define TRACER_ENABLED 1 #define HEAP 1 #define STACK 2 #define READ 1 #define WRITE 2 #define NOTE 3 #ifdef TRACER_ENABLED void tracer_dump(const string& x); void tracer_dump(const vector<string>& x); void tracer_dump(const map<string, string>& x); void tracer_dump(const vector<double>& x); void tracer_dump(const int &x); void tracer_dump(const float &x); void tracer_dump(const double &x); void tracer_dump(const char &x); void tracer_dump(const IntegerSet &x); void tracer_dump(const boost::regex &x); namespace freicore { namespace myrimatch { struct SpectraList; } } void tracer_dump(const freicore::myrimatch::SpectraList &x); #define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t'; tracer_dump(variable); cout << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t' << &(variable) << '\t' << type << '\t' << representation << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } // Reference a variable in an operation, do not dump all its info #define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << '\t', << &(variable) << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' __FILE__ << '\t' << __LINE__ << '\n'; } // Start operation of a given name #define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } // End operation of a given name #define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; } #define TRACER_S2S(variable) lexical_cast<string>(variable) #else // !TRACER_ENABLED #define TRACER(variable, operation, heap, note) #define TRACER_R(variable, type, representation, operation, heap, note) #define TRACER_UNLINK(variable) #define TRACER_OP_START(name) #define TRACER_OP_END(name) #define TRACER_S2S(variable) #endif // TRACER_ENABLED #endif <|endoftext|>
<commit_before>// Licensed under the MIT License <http://opensource.org/licenses/MIT>. // SPDX-License-Identifier: MIT // Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #define CATCH_CONFIG_MAIN #include <catch.hpp> #define MAGIC_ENUM_RANGE 120 #include <magic_enum.hpp> #include <array> #include <string> #include <sstream> enum class Color { RED = -12, GREEN = 7, BLUE = 15 }; enum class Numbers : char { one = 10, two = 20, three = 30 }; enum Directions { Up = 85, Down = -42, Right = 119, Left = -119 }; enum number : unsigned long { one = 10, two = 20, three = 30 }; TEST_CASE("enum_cast") { SECTION("string") { #if defined(_MSC_VER) && _MSC_VER < 1920 # define constexpr // Visual Studio 2017 have bug with string_view constexpr compare. #endif constexpr auto cr = yae::enum_cast<Color>("RED"); REQUIRE(cr.value() == Color::RED); REQUIRE(yae::enum_cast<Color>("GREEN").value() == Color::GREEN); REQUIRE(yae::enum_cast<Color>("BLUE").value() == Color::BLUE); REQUIRE_FALSE(yae::enum_cast<Color>("None").has_value()); constexpr auto no = yae::enum_cast<Numbers>("one"); REQUIRE(no.value() == Numbers::one); REQUIRE(yae::enum_cast<Numbers>("two").value() == Numbers::two); REQUIRE(yae::enum_cast<Numbers>("three").value() == Numbers::three); REQUIRE_FALSE(yae::enum_cast<Numbers>("None").has_value()); constexpr auto dr = yae::enum_cast<Directions>("Right"); REQUIRE(yae::enum_cast<Directions>("Up").value() == Directions::Up); REQUIRE(yae::enum_cast<Directions>("Down").value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(yae::enum_cast<Directions>("Left").value() == Directions::Left); REQUIRE_FALSE(yae::enum_cast<Directions>("None").has_value()); constexpr auto nt = yae::enum_cast<number>("three"); REQUIRE(yae::enum_cast<number>("one").value() == number::one); REQUIRE(yae::enum_cast<number>("two").value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(yae::enum_cast<number>("None").has_value()); #undef constexpr } SECTION("string") { constexpr auto cr = yae::enum_cast<Color>(-12); REQUIRE(cr.value() == Color::RED); REQUIRE(yae::enum_cast<Color>(7).value() == Color::GREEN); REQUIRE(yae::enum_cast<Color>(15).value() == Color::BLUE); REQUIRE_FALSE(yae::enum_cast<Color>(0).has_value()); constexpr auto no = yae::enum_cast<Numbers>(10); REQUIRE(no.value() == Numbers::one); REQUIRE(yae::enum_cast<Numbers>(20).value() == Numbers::two); REQUIRE(yae::enum_cast<Numbers>(30).value() == Numbers::three); REQUIRE_FALSE(yae::enum_cast<Numbers>(0).has_value()); constexpr auto dr = yae::enum_cast<Directions>(119); REQUIRE(yae::enum_cast<Directions>(85).value() == Directions::Up); REQUIRE(yae::enum_cast<Directions>(-42).value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(yae::enum_cast<Directions>(-119).value() == Directions::Left); REQUIRE_FALSE(yae::enum_cast<Directions>(0).has_value()); constexpr auto nt = yae::enum_cast<number>(30); REQUIRE(yae::enum_cast<number>(10).value() == number::one); REQUIRE(yae::enum_cast<number>(20).value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(yae::enum_cast<number>(0).has_value()); } } TEST_CASE("enum_value") { constexpr auto cr = yae::enum_value<Color>(0); REQUIRE(cr == Color::RED); REQUIRE(yae::enum_value<Color>(1) == Color::GREEN); REQUIRE(yae::enum_value<Color>(2) == Color::BLUE); constexpr auto no = yae::enum_value<Numbers>(0); REQUIRE(no == Numbers::one); REQUIRE(yae::enum_value<Numbers>(1) == Numbers::two); REQUIRE(yae::enum_value<Numbers>(2) == Numbers::three); constexpr auto dr = yae::enum_value<Directions>(3); REQUIRE(yae::enum_value<Directions>(0) == Directions::Left); REQUIRE(yae::enum_value<Directions>(1) == Directions::Down); REQUIRE(yae::enum_value<Directions>(2) == Directions::Up); REQUIRE(dr == Directions::Right); constexpr auto nt = yae::enum_value<number>(2); REQUIRE(yae::enum_value<number>(0) == number::one); REQUIRE(yae::enum_value<number>(1) == number::two); REQUIRE(nt == number::three); } TEST_CASE("enum_values") { constexpr auto mge_s1 = yae::enum_values<Color>(); REQUIRE(mge_s1 == std::array<Color, 3>{Color::RED, Color::GREEN, Color::BLUE}); constexpr auto mge_s2 = yae::enum_values<Numbers>(); REQUIRE(mge_s2 == std::array<Numbers, 3>{Numbers::one, Numbers::two, Numbers::three}); constexpr auto mge_s3 = yae::enum_values<Directions>(); REQUIRE(mge_s3 == std::array<Directions, 4>{Directions::Left, Directions::Down, Directions::Up, Directions::Right}); constexpr auto mge_s4 = yae::enum_values<number>(); REQUIRE(mge_s4 == std::array<number, 3>{number::one, number::two, number::three}); } TEST_CASE("enum_count") { constexpr auto mge_s1 = yae::enum_count<Color>(); REQUIRE(mge_s1 == 3); constexpr auto mge_s2 = yae::enum_count<Numbers>(); REQUIRE(mge_s2 == 3); constexpr auto mge_s3 = yae::enum_count<Directions>(); REQUIRE(mge_s3 == 4); constexpr auto mge_s4 = yae::enum_count<number>(); REQUIRE(mge_s4 == 3); } TEST_CASE("enum_name") { constexpr Color cr = Color::RED; constexpr auto cr_name = yae::enum_name(cr); Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE}; REQUIRE(cr_name.value() == "RED"); REQUIRE(yae::enum_name(Color::BLUE).value() == "BLUE"); REQUIRE(yae::enum_name(cm[1]).value() == "GREEN"); REQUIRE_FALSE(yae::enum_name(static_cast<Color>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Color>(-MAGIC_ENUM_RANGE)).has_value()); constexpr Numbers no = Numbers::one; constexpr auto no_name = yae::enum_name(no); REQUIRE(no_name.value() == "one"); REQUIRE(yae::enum_name(Numbers::two).value() == "two"); REQUIRE(yae::enum_name(Numbers::three).value() == "three"); REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(-MAGIC_ENUM_RANGE)).has_value()); constexpr Directions dr = Directions::Right; constexpr auto dr_name = yae::enum_name(dr); REQUIRE(yae::enum_name(Directions::Up).value() == "Up"); REQUIRE(yae::enum_name(Directions::Down).value() == "Down"); REQUIRE(dr_name.value() == "Right"); REQUIRE(yae::enum_name(Directions::Left).value() == "Left"); REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(-MAGIC_ENUM_RANGE)).has_value()); constexpr number nt = number::three; constexpr auto nt_name = yae::enum_name(nt); REQUIRE(yae::enum_name(number::one).value() == "one"); REQUIRE(yae::enum_name(number::two).value() == "two"); REQUIRE(nt_name.value() == "three"); REQUIRE_FALSE(yae::enum_name(static_cast<number>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<number>(-MAGIC_ENUM_RANGE)).has_value()); } TEST_CASE("enum_names") { constexpr auto mge_s1 = yae::enum_names<Color>(); REQUIRE(mge_s1 == std::array<std::string_view, 3>{"RED", "GREEN", "BLUE"}); constexpr auto mge_s2 = yae::enum_names<Numbers>(); REQUIRE(mge_s2 == std::array<std::string_view, 3>{"one", "two", "three"}); constexpr auto mge_s3 = yae::enum_names<Directions>(); REQUIRE(mge_s3 == std::array<std::string_view, 4>{"Left", "Down", "Up", "Right"}); constexpr auto mge_s4 = yae::enum_names<number>(); REQUIRE(mge_s4 == std::array<std::string_view, 3>{"one", "two", "three"}); } TEST_CASE("operator<<") { auto test_ostream = [](auto e, std::string_view name) { using namespace yae::ops; std::stringstream ss; ss << e; REQUIRE(ss.str() == name); }; test_ostream(Color::RED, "RED"); test_ostream(Color::GREEN, "GREEN"); test_ostream(Color::BLUE, "BLUE"); test_ostream((Color)0, ""); test_ostream(Numbers::one, "one"); test_ostream(Numbers::two, "two"); test_ostream(Numbers::three, "three"); test_ostream((Numbers)0, ""); test_ostream(Directions::Up, "Up"); test_ostream(Directions::Down, "Down"); test_ostream(Directions::Right, "Right"); test_ostream(Directions::Left, "Left"); test_ostream((Directions)0, ""); test_ostream(number::one, "one"); test_ostream(number::two, "two"); test_ostream(number::three, "three"); test_ostream((number)0, ""); } <commit_msg>fix warnings<commit_after>// Licensed under the MIT License <http://opensource.org/licenses/MIT>. // SPDX-License-Identifier: MIT // Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #define CATCH_CONFIG_MAIN #include <catch.hpp> #define MAGIC_ENUM_RANGE 120 #include <magic_enum.hpp> #include <array> #include <string_view> #include <sstream> enum class Color { RED = -12, GREEN = 7, BLUE = 15 }; enum class Numbers : char { one = 10, two = 20, three = 30 }; enum Directions { Up = 85, Down = -42, Right = 119, Left = -119 }; enum number : unsigned long { one = 10, two = 20, three = 30 }; TEST_CASE("enum_cast") { SECTION("string") { #if defined(_MSC_VER) && _MSC_VER < 1920 # define constexpr // Visual Studio 2017 have bug with string_view constexpr compare. #endif constexpr auto cr = yae::enum_cast<Color>("RED"); REQUIRE(cr.value() == Color::RED); REQUIRE(yae::enum_cast<Color>("GREEN").value() == Color::GREEN); REQUIRE(yae::enum_cast<Color>("BLUE").value() == Color::BLUE); REQUIRE_FALSE(yae::enum_cast<Color>("None").has_value()); constexpr auto no = yae::enum_cast<Numbers>("one"); REQUIRE(no.value() == Numbers::one); REQUIRE(yae::enum_cast<Numbers>("two").value() == Numbers::two); REQUIRE(yae::enum_cast<Numbers>("three").value() == Numbers::three); REQUIRE_FALSE(yae::enum_cast<Numbers>("None").has_value()); constexpr auto dr = yae::enum_cast<Directions>("Right"); REQUIRE(yae::enum_cast<Directions>("Up").value() == Directions::Up); REQUIRE(yae::enum_cast<Directions>("Down").value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(yae::enum_cast<Directions>("Left").value() == Directions::Left); REQUIRE_FALSE(yae::enum_cast<Directions>("None").has_value()); constexpr auto nt = yae::enum_cast<number>("three"); REQUIRE(yae::enum_cast<number>("one").value() == number::one); REQUIRE(yae::enum_cast<number>("two").value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(yae::enum_cast<number>("None").has_value()); #undef constexpr } SECTION("integer") { constexpr auto cr = yae::enum_cast<Color>(-12); REQUIRE(cr.value() == Color::RED); REQUIRE(yae::enum_cast<Color>(7).value() == Color::GREEN); REQUIRE(yae::enum_cast<Color>(15).value() == Color::BLUE); REQUIRE_FALSE(yae::enum_cast<Color>(0).has_value()); constexpr auto no = yae::enum_cast<Numbers>(10); REQUIRE(no.value() == Numbers::one); REQUIRE(yae::enum_cast<Numbers>(20).value() == Numbers::two); REQUIRE(yae::enum_cast<Numbers>(30).value() == Numbers::three); REQUIRE_FALSE(yae::enum_cast<Numbers>(0).has_value()); constexpr auto dr = yae::enum_cast<Directions>(119); REQUIRE(yae::enum_cast<Directions>(85).value() == Directions::Up); REQUIRE(yae::enum_cast<Directions>(-42).value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(yae::enum_cast<Directions>(-119).value() == Directions::Left); REQUIRE_FALSE(yae::enum_cast<Directions>(0).has_value()); constexpr auto nt = yae::enum_cast<number>(30); REQUIRE(yae::enum_cast<number>(10).value() == number::one); REQUIRE(yae::enum_cast<number>(20).value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(yae::enum_cast<number>(0).has_value()); } } TEST_CASE("enum_value") { constexpr auto cr = yae::enum_value<Color>(0); REQUIRE(cr == Color::RED); REQUIRE(yae::enum_value<Color>(1) == Color::GREEN); REQUIRE(yae::enum_value<Color>(2) == Color::BLUE); constexpr auto no = yae::enum_value<Numbers>(0); REQUIRE(no == Numbers::one); REQUIRE(yae::enum_value<Numbers>(1) == Numbers::two); REQUIRE(yae::enum_value<Numbers>(2) == Numbers::three); constexpr auto dr = yae::enum_value<Directions>(3); REQUIRE(yae::enum_value<Directions>(0) == Directions::Left); REQUIRE(yae::enum_value<Directions>(1) == Directions::Down); REQUIRE(yae::enum_value<Directions>(2) == Directions::Up); REQUIRE(dr == Directions::Right); constexpr auto nt = yae::enum_value<number>(2); REQUIRE(yae::enum_value<number>(0) == number::one); REQUIRE(yae::enum_value<number>(1) == number::two); REQUIRE(nt == number::three); } TEST_CASE("enum_values") { constexpr auto s1 = yae::enum_values<Color>(); REQUIRE(s1 == std::array<Color, 3>{{Color::RED, Color::GREEN, Color::BLUE}}); constexpr auto s2 = yae::enum_values<Numbers>(); REQUIRE(s2 == std::array<Numbers, 3>{{Numbers::one, Numbers::two, Numbers::three}}); constexpr auto s3 = yae::enum_values<Directions>(); REQUIRE(s3 == std::array<Directions, 4>{{Directions::Left, Directions::Down, Directions::Up, Directions::Right}}); constexpr auto s4 = yae::enum_values<number>(); REQUIRE(s4 == std::array<number, 3>{{number::one, number::two, number::three}}); } TEST_CASE("enum_count") { constexpr auto s1 = yae::enum_count<Color>(); REQUIRE(s1 == 3); constexpr auto s2 = yae::enum_count<Numbers>(); REQUIRE(s2 == 3); constexpr auto s3 = yae::enum_count<Directions>(); REQUIRE(s3 == 4); constexpr auto s4 = yae::enum_count<number>(); REQUIRE(s4 == 3); } TEST_CASE("enum_name") { constexpr Color cr = Color::RED; constexpr auto cr_name = yae::enum_name(cr); Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE}; REQUIRE(cr_name.value() == "RED"); REQUIRE(yae::enum_name(Color::BLUE).value() == "BLUE"); REQUIRE(yae::enum_name(cm[1]).value() == "GREEN"); REQUIRE_FALSE(yae::enum_name(static_cast<Color>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Color>(-MAGIC_ENUM_RANGE)).has_value()); constexpr Numbers no = Numbers::one; constexpr auto no_name = yae::enum_name(no); REQUIRE(no_name.value() == "one"); REQUIRE(yae::enum_name(Numbers::two).value() == "two"); REQUIRE(yae::enum_name(Numbers::three).value() == "three"); REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(-MAGIC_ENUM_RANGE)).has_value()); constexpr Directions dr = Directions::Right; constexpr auto dr_name = yae::enum_name(dr); REQUIRE(yae::enum_name(Directions::Up).value() == "Up"); REQUIRE(yae::enum_name(Directions::Down).value() == "Down"); REQUIRE(dr_name.value() == "Right"); REQUIRE(yae::enum_name(Directions::Left).value() == "Left"); REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(-MAGIC_ENUM_RANGE)).has_value()); constexpr number nt = number::three; constexpr auto nt_name = yae::enum_name(nt); REQUIRE(yae::enum_name(number::one).value() == "one"); REQUIRE(yae::enum_name(number::two).value() == "two"); REQUIRE(nt_name.value() == "three"); REQUIRE_FALSE(yae::enum_name(static_cast<number>(MAGIC_ENUM_RANGE)).has_value()); REQUIRE_FALSE(yae::enum_name(static_cast<number>(-MAGIC_ENUM_RANGE)).has_value()); } TEST_CASE("enum_names") { constexpr auto s1 = yae::enum_names<Color>(); REQUIRE(s1 == std::array<std::string_view, 3>{{"RED", "GREEN", "BLUE"}}); constexpr auto s2 = yae::enum_names<Numbers>(); REQUIRE(s2 == std::array<std::string_view, 3>{{"one", "two", "three"}}); constexpr auto s3 = yae::enum_names<Directions>(); REQUIRE(s3 == std::array<std::string_view, 4>{{"Left", "Down", "Up", "Right"}}); constexpr auto s4 = yae::enum_names<number>(); REQUIRE(s4 == std::array<std::string_view, 3>{{"one", "two", "three"}}); } TEST_CASE("operator<<") { auto test_ostream = [](auto e, std::string_view name) { using namespace yae::ops; std::stringstream ss; ss << e; REQUIRE(ss.str() == name); }; test_ostream(Color::RED, "RED"); test_ostream(Color::GREEN, "GREEN"); test_ostream(Color::BLUE, "BLUE"); test_ostream((Color)0, ""); test_ostream(Numbers::one, "one"); test_ostream(Numbers::two, "two"); test_ostream(Numbers::three, "three"); test_ostream((Numbers)0, ""); test_ostream(Directions::Up, "Up"); test_ostream(Directions::Down, "Down"); test_ostream(Directions::Right, "Right"); test_ostream(Directions::Left, "Left"); test_ostream((Directions)0, ""); test_ostream(number::one, "one"); test_ostream(number::two, "two"); test_ostream(number::three, "three"); test_ostream((number)0, ""); } <|endoftext|>
<commit_before>/*============================================================================== Program: 3D Slicer Copyright (c) 2010 Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // Qt includes #include <QDebug> #include <QMap> #include <QSharedPointer> #include <QStringList> #include <QVector> // IGTLIO includes #include "qIGTLIOConnectorModel.h" #include "vtkIGTLIOLogic.h" #include "vtkIGTLIOConnector.h" //------------------------------------------------------------------------------ qIGTLIOConnectorModel::qIGTLIOConnectorModel(QObject *vparent) :QAbstractItemModel(vparent) { HeaderLabels = QStringList() << "Name" << "Type" << "Status" << "Hostname" << "Port"; } //------------------------------------------------------------------------------ qIGTLIOConnectorModel::~qIGTLIOConnectorModel() { } //----------------------------------------------------------------------------- int qIGTLIOConnectorModel::columnCount(const QModelIndex& parent) const { return HeaderLabels.size(); } //----------------------------------------------------------------------------- int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const { if (parent.column() > 0) return 0; // only topnode has children if (!parent.isValid()) { if (!Logic) { std::cout << "WARNING in: int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const: Logic is a NULL object! Returning 0." << std::endl; return 0; } return Logic->GetNumberOfConnectors(); } return 0; } //------------------------------------------------------------------------------ QVariant qIGTLIOConnectorModel::data(const QModelIndex &index, int role) const { if (role!=Qt::DisplayRole) return QVariant(); vtkIGTLIOConnector* cnode = this->getNodeFromIndex(index); if (!cnode) { return QVariant(); } switch (index.column()) { case qIGTLIOConnectorModel::NameColumn: { return QString::fromStdString(cnode->GetName()); break; } case qIGTLIOConnectorModel::TypeColumn: { Q_ASSERT(cnode->GetType() < vtkIGTLIOConnector::NUM_TYPE); return QString::fromStdString(vtkIGTLIOConnector::ConnectorTypeStr[cnode->GetType()]); break; } case qIGTLIOConnectorModel::StatusColumn: { Q_ASSERT(cnode->GetState() < vtkIGTLIOConnector::NUM_STATE); return QString::fromStdString(vtkIGTLIOConnector::ConnectorStateStr[cnode->GetState()]); break; } case qIGTLIOConnectorModel::HostnameColumn: { if (cnode->GetType() == vtkIGTLIOConnector::TYPE_CLIENT) { return QString::fromStdString(cnode->GetServerHostname()); } else { return QString("--"); } break; } case qIGTLIOConnectorModel::PortColumn: { return QString("%1").arg(cnode->GetServerPort()); break; } default: break; } return QVariant(); } //----------------------------------------------------------------------------- Qt::ItemFlags qIGTLIOConnectorModel::flags(const QModelIndex &index) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } //----------------------------------------------------------------------------- QVariant qIGTLIOConnectorModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { return HeaderLabels[section]; } return QVariant(); } //----------------------------------------------------------------------------- QModelIndex qIGTLIOConnectorModel::index(int row, int column, const QModelIndex &parent) const { if (row < Logic->GetNumberOfConnectors()) { return createIndex(row, column, Logic->GetConnector(row)); } return QModelIndex(); } //----------------------------------------------------------------------------- QModelIndex qIGTLIOConnectorModel::parent(const QModelIndex &index) const { return QModelIndex(); } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::resetModel() { this->beginResetModel(); this->endResetModel(); } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::setLogic(vtkIGTLIOLogicPointer logic) { foreach(int evendId, QList<int>() << vtkIGTLIOLogic::ConnectionAddedEvent << vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent) { qvtkReconnect(this->Logic, logic, evendId, this, SLOT(onConnectionEvent(vtkObject*, unsigned long, void*, void* ))); } this->Logic = logic; } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::ReconnectConnector(vtkIGTLIOConnector* oldConnector, vtkIGTLIOConnector* newConnector) { foreach(int evendId, QList<int>() << vtkIGTLIOConnector::ConnectedEvent << vtkIGTLIOConnector::DisconnectedEvent << vtkIGTLIOConnector::ActivatedEvent << vtkIGTLIOConnector::DeactivatedEvent) { qvtkReconnect(oldConnector, newConnector, evendId, this, SLOT(onConnectorEvent(vtkObject*, unsigned long, void*, void* ))); } } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::onConnectionEvent(vtkObject* caller, unsigned long event, void * , void* connector ) { if (event==vtkIGTLIOLogic::ConnectionAddedEvent) { // std::cout << "on add connected event" << std::endl; vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector); this->ReconnectConnector(NULL, c); this->resetModel(); } if (event==vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent) { // std::cout << "on remove connected event" << std::endl; vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector); this->ReconnectConnector(c, NULL); this->resetModel(); } } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::onConnectorEvent(vtkObject* caller, unsigned long event , void*, void* connector ) { emit dataChanged(QModelIndex(), QModelIndex()); } //----------------------------------------------------------------------------- vtkIGTLIOConnector* qIGTLIOConnectorModel::getNodeFromIndex(const QModelIndex &index) const { if (!index.isValid()) return NULL; return static_cast<vtkIGTLIOConnector*>(index.internalPointer()); } <commit_msg>BUG: Fixed crash of qIGTLIOClientWidget constructor<commit_after>/*============================================================================== Program: 3D Slicer Copyright (c) 2010 Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // Qt includes #include <QDebug> #include <QMap> #include <QSharedPointer> #include <QStringList> #include <QVector> // IGTLIO includes #include "qIGTLIOConnectorModel.h" #include "vtkIGTLIOLogic.h" #include "vtkIGTLIOConnector.h" //------------------------------------------------------------------------------ qIGTLIOConnectorModel::qIGTLIOConnectorModel(QObject *vparent) :QAbstractItemModel(vparent) { HeaderLabels = QStringList() << "Name" << "Type" << "Status" << "Hostname" << "Port"; } //------------------------------------------------------------------------------ qIGTLIOConnectorModel::~qIGTLIOConnectorModel() { } //----------------------------------------------------------------------------- int qIGTLIOConnectorModel::columnCount(const QModelIndex& parent) const { return HeaderLabels.size(); } //----------------------------------------------------------------------------- int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const { if (parent.column() > 0) return 0; // only topnode has children if (!parent.isValid()) { if (!Logic) { std::cout << "WARNING in: int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const: Logic is a NULL object! Returning 0." << std::endl; return 0; } return Logic->GetNumberOfConnectors(); } return 0; } //------------------------------------------------------------------------------ QVariant qIGTLIOConnectorModel::data(const QModelIndex &index, int role) const { if (role!=Qt::DisplayRole) return QVariant(); vtkIGTLIOConnector* cnode = this->getNodeFromIndex(index); if (!cnode) { return QVariant(); } switch (index.column()) { case qIGTLIOConnectorModel::NameColumn: { return QString::fromStdString(cnode->GetName()); break; } case qIGTLIOConnectorModel::TypeColumn: { Q_ASSERT(cnode->GetType() < vtkIGTLIOConnector::NUM_TYPE); return QString::fromStdString(vtkIGTLIOConnector::ConnectorTypeStr[cnode->GetType()]); break; } case qIGTLIOConnectorModel::StatusColumn: { Q_ASSERT(cnode->GetState() < vtkIGTLIOConnector::NUM_STATE); return QString::fromStdString(vtkIGTLIOConnector::ConnectorStateStr[cnode->GetState()]); break; } case qIGTLIOConnectorModel::HostnameColumn: { if (cnode->GetType() == vtkIGTLIOConnector::TYPE_CLIENT) { return QString::fromStdString(cnode->GetServerHostname()); } else { return QString("--"); } break; } case qIGTLIOConnectorModel::PortColumn: { return QString("%1").arg(cnode->GetServerPort()); break; } default: break; } return QVariant(); } //----------------------------------------------------------------------------- Qt::ItemFlags qIGTLIOConnectorModel::flags(const QModelIndex &index) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } //----------------------------------------------------------------------------- QVariant qIGTLIOConnectorModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { return HeaderLabels[section]; } return QVariant(); } //----------------------------------------------------------------------------- QModelIndex qIGTLIOConnectorModel::index(int row, int column, const QModelIndex &parent) const { if (!Logic) { return QModelIndex(); } if (row >= Logic->GetNumberOfConnectors()) { return QModelIndex(); } return createIndex(row, column, Logic->GetConnector(row)); } //----------------------------------------------------------------------------- QModelIndex qIGTLIOConnectorModel::parent(const QModelIndex &index) const { return QModelIndex(); } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::resetModel() { this->beginResetModel(); this->endResetModel(); } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::setLogic(vtkIGTLIOLogicPointer logic) { foreach(int evendId, QList<int>() << vtkIGTLIOLogic::ConnectionAddedEvent << vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent) { qvtkReconnect(this->Logic, logic, evendId, this, SLOT(onConnectionEvent(vtkObject*, unsigned long, void*, void* ))); } this->Logic = logic; } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::ReconnectConnector(vtkIGTLIOConnector* oldConnector, vtkIGTLIOConnector* newConnector) { foreach(int evendId, QList<int>() << vtkIGTLIOConnector::ConnectedEvent << vtkIGTLIOConnector::DisconnectedEvent << vtkIGTLIOConnector::ActivatedEvent << vtkIGTLIOConnector::DeactivatedEvent) { qvtkReconnect(oldConnector, newConnector, evendId, this, SLOT(onConnectorEvent(vtkObject*, unsigned long, void*, void* ))); } } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::onConnectionEvent(vtkObject* caller, unsigned long event, void * , void* connector ) { if (event==vtkIGTLIOLogic::ConnectionAddedEvent) { // std::cout << "on add connected event" << std::endl; vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector); this->ReconnectConnector(NULL, c); this->resetModel(); } if (event==vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent) { // std::cout << "on remove connected event" << std::endl; vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector); this->ReconnectConnector(c, NULL); this->resetModel(); } } //----------------------------------------------------------------------------- void qIGTLIOConnectorModel::onConnectorEvent(vtkObject* caller, unsigned long event , void*, void* connector ) { emit dataChanged(QModelIndex(), QModelIndex()); } //----------------------------------------------------------------------------- vtkIGTLIOConnector* qIGTLIOConnectorModel::getNodeFromIndex(const QModelIndex &index) const { if (!index.isValid()) return NULL; return static_cast<vtkIGTLIOConnector*>(index.internalPointer()); } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_FUNCTIONS_COMPARISON_LESS_HPP #define BOOST_BRIGAND_FUNCTIONS_COMPARISON_LESS_HPP #include <brigand/types/bool.hpp> namespace brigand { template <typename A, typename B> struct less : bool_ < (A::value < B::value) > {}; } #endif <commit_msg>Delete less.hpp<commit_after><|endoftext|>
<commit_before>#pragma once #include <string> #include <sstream> #include <cassert> #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "But/Log/Backend/toString.hpp" #include "But/Log/Backend/typeString.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toString() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ template<unsigned ArgumentsCount, unsigned MaxSegments> class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * ${TN} - prints type of N-th argument, using typeString() function and ADL. * ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!). * ${VN} - the same as $N. * ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). */ constexpr explicit Parsed(char const* format): ps_{ detail::parse<MaxSegments>(format) }, format_{format} { } constexpr auto inputFormat() const { return format_; } //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // TODO: will not work with static_assert... static constexpr auto expectedArguments() { return ArgumentsCount; } static constexpr auto maxSegments() { return MaxSegments; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); assert( expectedArguments() == detail::argumentsCount(ps_) ); std::ostringstream os; for(auto i=0u; i<ps_.count_; ++i) formatBlock(os, ps_.segments_[i], args...); return os.str(); } private: template<typename F> std::string processArgument(F&& /*f*/, const unsigned /*pos*/) const { assert(!"this overload is never really called"); std::terminate(); } template<typename F, typename Head> std::string processArgument(F&& f, const unsigned pos, Head const& head) const { (void)pos; assert( pos == 0u && "format is not alligned with arguments" ); return f(head); } template<typename F, typename Head, typename ...Tail> std::string processArgument(F&& f, const unsigned pos, Head const& head, Tail const& ...tail) const { if( pos == 0u ) return f(head); return processArgument( std::forward<F>(f), pos-1u, tail... ); } template<typename ...Args> std::string getArgumentType(const unsigned pos, Args const& ...args) const { using Log::Backend::typeString; return processArgument( [](auto& e) { return typeString(e); }, pos, args... ); } template<typename ...Args> std::string getArgumentValue(const unsigned pos, Args const& ...args) const { using Log::Backend::toString; return processArgument( [](auto& e) { return toString(e); }, pos, args... ); } template<typename ...Args> void formatBlock(std::ostringstream& os, detail::State const& state, Args const& ...args) const { switch(state.type_) { case detail::State::Type::String: os.write( state.begin_, state.end_ - state.begin_ ); return; case detail::State::Type::Value: os << getArgumentValue(state.referencedArgument_, args...); return; case detail::State::Type::TypeName: os << getArgumentType(state.referencedArgument_, args...); return; } assert(!"missing type handle"); } const detail::ParserState<MaxSegments> ps_; char const* format_; }; } } <commit_msg>comment update - it's not a TODO<commit_after>#pragma once #include <string> #include <sstream> #include <cassert> #include "detail/parse.hpp" #include "detail/argumentsCount.hpp" #include "But/Log/Backend/toString.hpp" #include "But/Log/Backend/typeString.hpp" namespace But { namespace Format { /** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message. * @note format of the parameter is defined by its type, via toString() function. it * is not specified for a given type usage. this way formatting for a given parameters * is always constant. */ template<unsigned ArgumentsCount, unsigned MaxSegments> class Parsed final { public: /** @brief parses input format and constructs the object. * @param format - format is a string with positional arguments, in a form: * $N - expands to N-th argument. * ${N} - the same as $N. * ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!). * ${TN} - prints type of N-th argument, using typeString() function and ADL. * ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!). * ${VN} - the same as $N. * ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!). * $$ - liternal '$' character. * @note all numbers are 0-based (i.e. 1st argument has index 0). */ constexpr explicit Parsed(char const* format): ps_{ detail::parse<MaxSegments>(format) }, format_{format} { } constexpr auto inputFormat() const { return format_; } //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // note: would not work with static_assert... static constexpr auto expectedArguments() { return ArgumentsCount; } static constexpr auto maxSegments() { return MaxSegments; } template<typename ...Args> std::string format(Args const& ...args) const { static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" ); assert( expectedArguments() == detail::argumentsCount(ps_) ); std::ostringstream os; for(auto i=0u; i<ps_.count_; ++i) formatBlock(os, ps_.segments_[i], args...); return os.str(); } private: template<typename F> std::string processArgument(F&& /*f*/, const unsigned /*pos*/) const { assert(!"this overload is never really called"); std::terminate(); } template<typename F, typename Head> std::string processArgument(F&& f, const unsigned pos, Head const& head) const { (void)pos; assert( pos == 0u && "format is not alligned with arguments" ); return f(head); } template<typename F, typename Head, typename ...Tail> std::string processArgument(F&& f, const unsigned pos, Head const& head, Tail const& ...tail) const { if( pos == 0u ) return f(head); return processArgument( std::forward<F>(f), pos-1u, tail... ); } template<typename ...Args> std::string getArgumentType(const unsigned pos, Args const& ...args) const { using Log::Backend::typeString; return processArgument( [](auto& e) { return typeString(e); }, pos, args... ); } template<typename ...Args> std::string getArgumentValue(const unsigned pos, Args const& ...args) const { using Log::Backend::toString; return processArgument( [](auto& e) { return toString(e); }, pos, args... ); } template<typename ...Args> void formatBlock(std::ostringstream& os, detail::State const& state, Args const& ...args) const { switch(state.type_) { case detail::State::Type::String: os.write( state.begin_, state.end_ - state.begin_ ); return; case detail::State::Type::Value: os << getArgumentValue(state.referencedArgument_, args...); return; case detail::State::Type::TypeName: os << getArgumentType(state.referencedArgument_, args...); return; } assert(!"missing type handle"); } const detail::ParserState<MaxSegments> ps_; char const* format_; }; } } <|endoftext|>
<commit_before>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Copyright (c) 2012, Matthew Renaud // All rights reserved. // // Licensed under the FreeBSD license. See LICENSE file for details. // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #ifndef MRR_UNISTD_HXX_ #define MRR_UNISTD_HXX_ #include <unistd.h> //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace mrr { namespace posix { //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ssize_t read(int fildes, void* buf, size_t nbyte) { ssize_t numbytes = 0; // Loop while the read function is interupted. Set errno in the loop // to make sure that another system call has not set it. do { errno = 0; numbytes = ::read(fildes, buf, nbyte); } while (numbytes == -1 && errno == EINTR); return numbytes; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ssize_t write(int fildes, void const* buf, size_t nbyte) { // Loop while the write function is interupted. Set errno in the loop // to make sure that another system call has not set it. ssize_t numbytes = 0; do { errno = 0; numbytes = ::write(fildes, buf, nbyte); } while (numbytes == -1 && errno == EINTR); return numbytes; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int close(int fd) { int ret_val; do { errno = 0; ret_val = ::close(fd); } while(ret_val == -1 && errno != EINTR); return ret_val; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- } // namespace posix } // namespace mrr //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #endif // #ifndef MRR_UNISTD_HXX_ <commit_msg>Fixed errno != EINTR error inside close() for unistd.hxx<commit_after>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Copyright (c) 2012, Matthew Renaud // All rights reserved. // // Licensed under the FreeBSD license. See LICENSE file for details. // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #ifndef MRR_UNISTD_HXX_ #define MRR_UNISTD_HXX_ #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace mrr { namespace posix { //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int myopen(char const* pathname, int flags) { int ret_val; do { errno = 0; ret_val = ::open(pathname, flags); } while(ret_val == -1 && errno == EINTR); return ret_val; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ssize_t read(int fildes, void* buf, size_t nbyte) { ssize_t numbytes = 0; // Loop while the read function is interupted. Set errno in the loop // to make sure that another system call has not set it. do { errno = 0; numbytes = ::read(fildes, buf, nbyte); } while (numbytes == -1 && errno == EINTR); return numbytes; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ssize_t write(int fildes, void const* buf, size_t nbyte) { // Loop while the write function is interupted. Set errno in the loop // to make sure that another system call has not set it. ssize_t numbytes = 0; do { errno = 0; numbytes = ::write(fildes, buf, nbyte); } while (numbytes == -1 && errno == EINTR); return numbytes; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int close(int fd) { int ret_val; do { errno = 0; ret_val = ::close(fd); } while(ret_val == -1 && errno == EINTR); return ret_val; } //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- } // namespace posix } // namespace mrr //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #endif // #ifndef MRR_UNISTD_HXX_ <|endoftext|>
<commit_before><commit_msg>Update Prime Factorization.cpp<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <vector> #include <string> #include "ros/ros.h" #include "std_msgs/MultiArrayLayout.h" #include "std_msgs/MultiArrayDimension.h" #include "std_msgs/Int8MultiArray.h" #include <fstream> #include <sstream> #include <unistd.h> using std::string; typedef std::vector < std::vector <int> > Matrix; #define DEBUG 1 int MATRIX_WIDTH = 200; int MATRIX_HEIGHT = 200; Matrix createVector(string f_s) { Matrix m; m.resize(MATRIX_HEIGHT, std::vector<int>(MATRIX_WIDTH, 0)); std::ifstream infile(f_s.c_str()); if (!infile.good()) { throw std::invalid_argument( "File does not exist!" ); } std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; float c; if (!(iss >> a >> b >> c)) {continue;} // error m[a][b] = (int) ((c*100)+100)*1.27; if (DEBUG) { std::cout << "LINE: " << a << ", " << b << ", " << c << " -> " << m[a][b] << std::endl; } } return m; } int main(int argc, char **argv) { ros::init(argc, argv, "arrayPublisher"); ros::NodeHandle n; ros::Publisher pub = n.advertise<std_msgs::Int8MultiArray>("/outer_layer", 400); char cwd[1024]; getcwd(cwd, sizeof(cwd)); string path(cwd); while (ros::ok()) { // some vectors of vectors here // TODO: ALEX PUT YOUR VECTOR HERE! Matrix matrix = createVector(path + "/share/Model-A.txt"); std_msgs::Int8MultiArray matrix_ma; matrix_ma.data.clear(); // linearise matrix std::vector< std::vector<int> >::iterator r; std::vector<int>::iterator c; for (r = matrix.begin(); r != matrix.end(); r++) { for (c = r->begin(); c != r->end(); c++) { matrix_ma.data.push_back(*c); } } pub.publish(matrix_ma); ROS_INFO("TEST: Outer layer has been published"); ros::spinOnce(); sleep(1); } } <commit_msg>Test publisher: 8Int -> 32Int<commit_after>#include <stdio.h> #include <stdlib.h> #include <vector> #include <string> #include "ros/ros.h" #include "std_msgs/MultiArrayLayout.h" #include "std_msgs/MultiArrayDimension.h" #include "std_msgs/Int32MultiArray.h" #include <fstream> #include <sstream> #include <unistd.h> using std::string; typedef std::vector < std::vector <int> > Matrix; #define DEBUG 1 int MATRIX_WIDTH = 200; int MATRIX_HEIGHT = 200; Matrix createVector(string f_s) { Matrix m; m.resize(MATRIX_HEIGHT, std::vector<int>(MATRIX_WIDTH, 0)); std::ifstream infile(f_s.c_str()); if (!infile.good()) { throw std::invalid_argument( "File does not exist!" ); } std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int a, b; float c; if (!(iss >> a >> b >> c)) {continue;} // error m[a][b] = (int) ((c*100)+100)*1.27; if (DEBUG) { std::cout << "LINE: " << a << ", " << b << ", " << c << " -> " << m[a][b] << std::endl; } } return m; } int main(int argc, char **argv) { ros::init(argc, argv, "arrayPublisher"); ros::NodeHandle n; ros::Publisher pub = n.advertise<std_msgs::Int32MultiArray>("/outer_layer", 400); char cwd[1024]; getcwd(cwd, sizeof(cwd)); string path(cwd); while (ros::ok()) { // some vectors of vectors here // TODO: ALEX PUT YOUR VECTOR HERE! Matrix matrix = createVector(path + "/share/Model-A.txt"); std_msgs::Int32MultiArray matrix_ma; matrix_ma.data.clear(); // linearise matrix std::vector< std::vector<int> >::iterator r; std::vector<int>::iterator c; for (r = matrix.begin(); r != matrix.end(); r++) { for (c = r->begin(); c != r->end(); c++) { matrix_ma.data.push_back(*c); } } pub.publish(matrix_ma); ROS_INFO("TEST: Outer layer has been published"); ros::spinOnce(); sleep(5); } } <|endoftext|>
<commit_before>#include "RegisterGlobals.hpp" void noob::register_globals(asIScriptEngine* script_engine) { noob::globals& g = noob::globals::get_instance(); int r; r = script_engine->RegisterGlobalFunction("shape_handle sphere_shape(float)", asMETHOD(noob::globals, sphere_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle box_shape(float, float, float)", asMETHOD(noob::globals, box_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle cylinder_shape(float, float)", asMETHOD(noob::globals, cylinder_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle cone_shape(float, float)", asMETHOD(noob::globals, cone_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle hull_shape(const vector_vec3& in)", asMETHOD(noob::globals, hull_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle static_trimesh_shape(const basic_mesh& in)", asMETHOD(noob::globals, static_trimesh_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("mesh_handle add_mesh(const basic_mesh& in)", asMETHOD(noob::globals, add_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("model_handle model_by_shape(const shape_handle)", asMETHOD(noob::globals, model_by_shape), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0); r = script_engine->RegisterGlobalFunction("scaled_model sphere_model(float)", asMETHOD(noob::globals, sphere_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model box_model(float, float, float)", asMETHOD(noob::globals, box_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model cylinder_model(float, float)", asMETHOD(noob::globals, cylinder_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model cone_model(float, float)", asMETHOD(noob::globals, cone_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model model_from_mesh(const basic_mesh& in)", asMETHOD(noob::globals, model_from_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0); r = script_engine->RegisterGlobalFunction("animated_model_handle animated_model(const string& in)", asMETHOD(noob::globals, animated_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("skeleton_handle skeleton(const string& in)", asMETHOD(noob::globals, skeleton), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("light_handle set_light(const light& in, const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("light_handle get_light(const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("reflectance_handle set_reflectance(const reflectance& in, const string& in)", asMETHOD(noob::globals, set_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("reflectance_handle get_reflectance(const string& in)", asMETHOD(noob::globals, get_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_shader(const basic_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::basic_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_shader(const triplanar_gradmap_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::triplanar_gradient_map_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shader_handle get_shader(const string& in)", asMETHOD(noob::globals, get_shader), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_actor_blueprints(const actor_blueprints& in, const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("actor_blueprints_handle get_actor_blueprints(const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); } <commit_msg>Tweak<commit_after>#include "RegisterGlobals.hpp" void noob::register_globals(asIScriptEngine* script_engine) { noob::globals& g = noob::globals::get_instance(); int r; r = script_engine->RegisterGlobalFunction("shape_handle sphere_shape(float)", asMETHOD(noob::globals, sphere_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle box_shape(float, float, float)", asMETHOD(noob::globals, box_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle cylinder_shape(float, float)", asMETHOD(noob::globals, cylinder_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle cone_shape(float, float)", asMETHOD(noob::globals, cone_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle hull_shape(const vector_vec3& in)", asMETHOD(noob::globals, hull_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shape_handle static_trimesh_shape(const basic_mesh& in)", asMETHOD(noob::globals, static_trimesh_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("mesh_handle add_mesh(const basic_mesh& in)", asMETHOD(noob::globals, add_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("model_handle model_by_shape(const shape_handle)", asMETHOD(noob::globals, model_by_shape), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0); r = script_engine->RegisterGlobalFunction("scaled_model sphere_model(float)", asMETHOD(noob::globals, sphere_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model box_model(float, float, float)", asMETHOD(noob::globals, box_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model cylinder_model(float, float)", asMETHOD(noob::globals, cylinder_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model cone_model(float, float)", asMETHOD(noob::globals, cone_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("scaled_model model_from_mesh(const basic_mesh& in)", asMETHOD(noob::globals, model_from_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0); r = script_engine->RegisterGlobalFunction("animated_model_handle animated_model(const string& in)", asMETHOD(noob::globals, animated_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); // r = script_engine->RegisterGlobalFunction("skeleton_handle skeleton(const string& in)", asMETHOD(noob::globals, skeleton), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("light_handle set_light(const light& in, const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("light_handle get_light(const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("reflectance_handle set_reflectance(const reflectance& in, const string& in)", asMETHOD(noob::globals, set_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("reflectance_handle get_reflectance(const string& in)", asMETHOD(noob::globals, get_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_shader(const basic_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::basic_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_shader(const triplanar_gradmap_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::triplanar_gradient_map_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("shader_handle get_shader(const string& in)", asMETHOD(noob::globals, get_shader), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("void set_actor_blueprints(const actor_blueprints& in, const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); r = script_engine->RegisterGlobalFunction("actor_blueprints_handle get_actor_blueprints(const string& in)", asMETHOD(noob::globals, get_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 ); } <|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include <array> #include <stdexcept> #include <android/input.h> #include "InputSystemAndroid.hpp" #include "GamepadDeviceAndroid.hpp" #include "../../core/android/EngineAndroid.hpp" #include "../../core/Window.hpp" namespace ouzel::input::android { InputSystem::InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback): input::InputSystem(initCallback), keyboardDevice(std::make_unique<KeyboardDevice>(*this, getNextDeviceId())), mouseDevice(std::make_unique<MouseDevice>(*this, getNextDeviceId())), touchpadDevice(std::make_unique<TouchpadDevice>(*this, getNextDeviceId(), true)) { auto engineAndroid = static_cast<ouzel::android::Engine*>(engine); javaVm = engineAndroid->getJavaVm(); void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); inputDeviceClass = static_cast<jclass>(jniEnv->NewGlobalRef(jniEnv->FindClass("android/view/InputDevice"))); getDeviceIdsMethod = jniEnv->GetStaticMethodID(inputDeviceClass, "getDeviceIds", "()[I"); jclass motionEventClass = jniEnv->FindClass("android/view/MotionEvent"); getActionMethod = jniEnv->GetMethodID(motionEventClass, "getAction", "()I"); getPointerIdMethod = jniEnv->GetMethodID(motionEventClass, "getPointerId", "(I)I"); getToolTypeMethod = jniEnv->GetMethodID(motionEventClass, "getToolType", "(I)I"); getXMethod = jniEnv->GetMethodID(motionEventClass, "getX", "(I)F"); getYMethod = jniEnv->GetMethodID(motionEventClass, "getY", "(I)F"); getPressureMethod = jniEnv->GetMethodID(motionEventClass, "getPressure", "(I)F"); getAxisValueMethod = jniEnv->GetMethodID(motionEventClass, "getAxisValue", "(I)F"); getButtonStateMethod = jniEnv->GetMethodID(motionEventClass, "getButtonState", "()I"); } InputSystem::~InputSystem() { void* jniEnvPointer; if (javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6) == JNI_OK) { auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); if (inputDeviceClass) jniEnv->DeleteGlobalRef(inputDeviceClass); } } void InputSystem::executeCommand(const Command& command) { switch (command.type) { case Command::Type::startDeviceDiscovery: break; case Command::Type::stopDeviceDiscovery: break; case Command::Type::setPlayerIndex: { break; } case Command::Type::setVibration: { break; } case Command::Type::showVirtualKeyboard: break; case Command::Type::hideVirtualKeyboard: break; default: break; } } jboolean InputSystem::handleTouchEvent(jobject event) { void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); const jint action = jniEnv->CallIntMethod(event, getActionMethod); switch (action & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_DOWN: // first touch { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_POINTER_DOWN: // touches beyond the first { const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, pointerIndex); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex); touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_MOVE: { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y)) mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchMove(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_UP: // first touch { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_POINTER_UP: // touches beyond the first { const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex); touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_CANCEL: { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y)) mouseDevice->handleButtonRelease(Mouse::Button::left, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchCancel(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } } return false; } jboolean InputSystem::handleGenericMotionEvent(jobject event) { void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); const jint action = jniEnv->CallIntMethod(event, getActionMethod); const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); switch (action & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_HOVER_MOVE: { if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } break; } case AMOTION_EVENT_ACTION_SCROLL: { const jfloat scrollX = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_HSCROLL); const jfloat scrollY = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_VSCROLL); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mouseDevice->handleScroll(Vector2F(scrollX, scrollY), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } break; } } return false; } bool InputSystem::updateButtonState(jint newButtonState, jint x, jint y) { bool result = false; constexpr std::array<std::pair<jint, Mouse::Button>, 5> buttons = {{ {AMOTION_EVENT_BUTTON_PRIMARY, Mouse::Button::left}, {AMOTION_EVENT_BUTTON_SECONDARY, Mouse::Button::right}, {AMOTION_EVENT_BUTTON_TERTIARY, Mouse::Button::middle}, {AMOTION_EVENT_BUTTON_BACK, Mouse::Button::x1}, {AMOTION_EVENT_BUTTON_FORWARD, Mouse::Button::x2} }}; for (const auto& button : buttons) { if ((newButtonState & button.first) != (buttonState & button.first)) { if (newButtonState & button.first) mouseDevice->handleButtonPress(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); else mouseDevice->handleButtonRelease(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); result = true; } } buttonState = newButtonState; return result; } } <commit_msg>Fix spacing<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include <array> #include <stdexcept> #include <android/input.h> #include "InputSystemAndroid.hpp" #include "GamepadDeviceAndroid.hpp" #include "../../core/android/EngineAndroid.hpp" #include "../../core/Window.hpp" namespace ouzel::input::android { InputSystem::InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback): input::InputSystem(initCallback), keyboardDevice(std::make_unique<KeyboardDevice>(*this, getNextDeviceId())), mouseDevice(std::make_unique<MouseDevice>(*this, getNextDeviceId())), touchpadDevice(std::make_unique<TouchpadDevice>(*this, getNextDeviceId(), true)) { auto engineAndroid = static_cast<ouzel::android::Engine*>(engine); javaVm = engineAndroid->getJavaVm(); void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); inputDeviceClass = static_cast<jclass>(jniEnv->NewGlobalRef(jniEnv->FindClass("android/view/InputDevice"))); getDeviceIdsMethod = jniEnv->GetStaticMethodID(inputDeviceClass, "getDeviceIds", "()[I"); jclass motionEventClass = jniEnv->FindClass("android/view/MotionEvent"); getActionMethod = jniEnv->GetMethodID(motionEventClass, "getAction", "()I"); getPointerIdMethod = jniEnv->GetMethodID(motionEventClass, "getPointerId", "(I)I"); getToolTypeMethod = jniEnv->GetMethodID(motionEventClass, "getToolType", "(I)I"); getXMethod = jniEnv->GetMethodID(motionEventClass, "getX", "(I)F"); getYMethod = jniEnv->GetMethodID(motionEventClass, "getY", "(I)F"); getPressureMethod = jniEnv->GetMethodID(motionEventClass, "getPressure", "(I)F"); getAxisValueMethod = jniEnv->GetMethodID(motionEventClass, "getAxisValue", "(I)F"); getButtonStateMethod = jniEnv->GetMethodID(motionEventClass, "getButtonState", "()I"); } InputSystem::~InputSystem() { void* jniEnvPointer; if (javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6) == JNI_OK) { auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); if (inputDeviceClass) jniEnv->DeleteGlobalRef(inputDeviceClass); } } void InputSystem::executeCommand(const Command& command) { switch (command.type) { case Command::Type::startDeviceDiscovery: break; case Command::Type::stopDeviceDiscovery: break; case Command::Type::setPlayerIndex: { break; } case Command::Type::setVibration: { break; } case Command::Type::showVirtualKeyboard: break; case Command::Type::hideVirtualKeyboard: break; default: break; } } jboolean InputSystem::handleTouchEvent(jobject event) { void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); const jint action = jniEnv->CallIntMethod(event, getActionMethod); switch (action & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_DOWN: // first touch { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_POINTER_DOWN: // touches beyond the first { const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, pointerIndex); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex); touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_MOVE: { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y)) mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchMove(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_UP: // first touch { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_POINTER_UP: // touches beyond the first { const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y); else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex); touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } case AMOTION_EVENT_ACTION_CANCEL: { const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y)) mouseDevice->handleButtonRelease(Mouse::Button::left, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0); const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0); touchpadDevice->handleTouchCancel(static_cast<std::uint64_t>(pointerId), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)), pressure); return true; } break; } } return false; } jboolean InputSystem::handleGenericMotionEvent(jobject event) { void* jniEnvPointer; jint result; if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK) throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment"); auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer); const jint action = jniEnv->CallIntMethod(event, getActionMethod); const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0); const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0); const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0); switch (action & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_HOVER_MOVE: { if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } break; } case AMOTION_EVENT_ACTION_SCROLL: { const jfloat scrollX = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_HSCROLL); const jfloat scrollY = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_VSCROLL); if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mouseDevice->handleScroll(Vector2F(scrollX, scrollY), engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); return true; } break; } } return false; } bool InputSystem::updateButtonState(jint newButtonState, jint x, jint y) { bool result = false; constexpr std::array<std::pair<jint, Mouse::Button>, 5> buttons = {{ {AMOTION_EVENT_BUTTON_PRIMARY, Mouse::Button::left}, {AMOTION_EVENT_BUTTON_SECONDARY, Mouse::Button::right}, {AMOTION_EVENT_BUTTON_TERTIARY, Mouse::Button::middle}, {AMOTION_EVENT_BUTTON_BACK, Mouse::Button::x1}, {AMOTION_EVENT_BUTTON_FORWARD, Mouse::Button::x2} }}; for (const auto& button : buttons) { if ((newButtonState & button.first) != (buttonState & button.first)) { if (newButtonState & button.first) mouseDevice->handleButtonPress(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); else mouseDevice->handleButtonRelease(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y))); result = true; } } buttonState = newButtonState; return result; } } <|endoftext|>
<commit_before> #include "E_ConnectivityAccessor.h" #include "E_TriangleAccessor.h" #include "../Mesh/E_Mesh.h" #include <E_Geometry/E_Triangle.h> #include <E_Geometry/E_Vec3.h> #include <Rendering/Mesh/VertexAttributeAccessors.h> #include <EScript/Basics.h> #include <EScript/StdObjects.h> namespace E_Rendering{ //! (static) EScript::Type * E_ConnectivityAccessor::getTypeObject() { // E_ConnectivityAccessor ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_ConnectivityAccessor::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_ConnectivityAccessor::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering::MeshUtils; //! [ESF] ConnectivityAccessor Rendering.MeshUtils.ConnectivityAccessor.create(Mesh,name) ES_FUN(typeObject,"create",1,1,ConnectivityAccessor::create( parameter[0].to<Rendering::Mesh*>(rt))) //! [ESMF] Geometry::Vec3 ConnectivityAccessor.getVertex(vIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getVertex",1,1, thisObj->getVertex(parameter[0].to<uint32_t>(rt))) //! [ESMF] Array ConnectivityAccessor.getTriangle(tIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getTriangle",1,1, { auto tri = thisObj->getTriangle(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); arr->pushBack(EScript::create(std::get<0>(tri))); arr->pushBack(EScript::create(std::get<1>(tri))); arr->pushBack(EScript::create(std::get<2>(tri))); return arr; }) //! [ESMF] Number ConnectivityAccessor.getCorner(vIndex, tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCorner",2,2, thisObj->getCorner(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getVertexCorner(vIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getVertexCorner",1,1, thisObj->getVertexCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getTriangleCorner(tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getTriangleCorner",1,1, thisObj->getTriangleCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getCornerVertex(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerVertex",1,1, thisObj->getCornerVertex(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getCornerTriangle(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerTriangle",1,1, thisObj->getCornerTriangle(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getNextVertexCorner(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getNextVertexCorner",1,1, thisObj->getNextVertexCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getNextTriangleCorner(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getNextTriangleCorner",1,1, thisObj->getNextTriangleCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Array ConnectivityAccessor.getVertexAdjacentTriangles(vIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentTriangles",1,1, { auto tri = thisObj->getVertexAdjacentTriangles(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); for(auto t : tri) arr->pushBack(EScript::create(t)); return arr; }) //! [ESMF] Array ConnectivityAccessor.getAdjacentTriangles(tIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getAdjacentTriangles",1,1, { auto tri = thisObj->getAdjacentTriangles(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); for(auto t : tri) arr->pushBack(EScript::create(t)); return arr; }) //! [ESMF] Number ConnectivityAccessor.isBorderEdge(vIndex1, vIndex2) ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderEdge",2,2, thisObj->isBorderEdge(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.isBorderTriangle(tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderTriangle",2,2, thisObj->isBorderTriangle(parameter[0].to<uint32_t>(rt))) } } <commit_msg>added binding for getVertexAdjacentVertices<commit_after> #include "E_ConnectivityAccessor.h" #include "E_TriangleAccessor.h" #include "../Mesh/E_Mesh.h" #include <E_Geometry/E_Triangle.h> #include <E_Geometry/E_Vec3.h> #include <Rendering/Mesh/VertexAttributeAccessors.h> #include <EScript/Basics.h> #include <EScript/StdObjects.h> namespace E_Rendering{ //! (static) EScript::Type * E_ConnectivityAccessor::getTypeObject() { // E_ConnectivityAccessor ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_ConnectivityAccessor::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_ConnectivityAccessor::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering::MeshUtils; //! [ESF] ConnectivityAccessor Rendering.MeshUtils.ConnectivityAccessor.create(Mesh,name) ES_FUN(typeObject,"create",1,1,ConnectivityAccessor::create( parameter[0].to<Rendering::Mesh*>(rt))) //! [ESMF] Geometry::Vec3 ConnectivityAccessor.getVertex(vIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getVertex",1,1, thisObj->getVertex(parameter[0].to<uint32_t>(rt))) //! [ESMF] Array ConnectivityAccessor.getTriangle(tIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getTriangle",1,1, { auto tri = thisObj->getTriangle(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); arr->pushBack(EScript::create(std::get<0>(tri))); arr->pushBack(EScript::create(std::get<1>(tri))); arr->pushBack(EScript::create(std::get<2>(tri))); return arr; }) //! [ESMF] Number ConnectivityAccessor.getCorner(vIndex, tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCorner",2,2, thisObj->getCorner(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getVertexCorner(vIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getVertexCorner",1,1, thisObj->getVertexCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getTriangleCorner(tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getTriangleCorner",1,1, thisObj->getTriangleCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getCornerVertex(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerVertex",1,1, thisObj->getCornerVertex(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getCornerTriangle(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerTriangle",1,1, thisObj->getCornerTriangle(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getNextVertexCorner(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getNextVertexCorner",1,1, thisObj->getNextVertexCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.getNextTriangleCorner(cIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"getNextTriangleCorner",1,1, thisObj->getNextTriangleCorner(parameter[0].to<uint32_t>(rt))) //! [ESMF] Array ConnectivityAccessor.getVertexAdjacentTriangles(vIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentTriangles",1,1, { auto tri = thisObj->getVertexAdjacentTriangles(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); for(auto t : tri) arr->pushBack(EScript::create(t)); return arr; }) //! [ESMF] Array ConnectivityAccessor.getVertexAdjacentVertices(vIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentVertices",1,1, { auto verts = thisObj->getVertexAdjacentVertices(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); for(auto v : verts) arr->pushBack(EScript::create(v)); return arr; }) //! [ESMF] Array ConnectivityAccessor.getAdjacentTriangles(tIndex) ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getAdjacentTriangles",1,1, { auto tri = thisObj->getAdjacentTriangles(parameter[0].to<uint32_t>(rt)); auto arr = EScript::Array::create(); for(auto t : tri) arr->pushBack(EScript::create(t)); return arr; }) //! [ESMF] Number ConnectivityAccessor.isBorderEdge(vIndex1, vIndex2) ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderEdge",2,2, thisObj->isBorderEdge(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt))) //! [ESMF] Number ConnectivityAccessor.isBorderTriangle(tIndex) ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderTriangle",1,1, thisObj->isBorderTriangle(parameter[0].to<uint32_t>(rt))) } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkGeometricJacobianDeterminantImageFilter_hxx #define _itkGeometricJacobianDeterminantImageFilter_hxx #include "itkGeometricJacobianDeterminantImageFilter.h" #include "itkContinuousIndex.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkNeighborhoodAlgorithm.h" #include "itkProgressReporter.h" #include "itkVectorCastImageFilter.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "vnl/vnl_cross.h" namespace itk { template <typename TInputImage, typename TRealType, typename TOutputImage> GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::GeometricJacobianDeterminantImageFilter() { this->m_Interpolator = ITK_NULLPTR; this->m_UndisplacedVolume = 0.0; } template <typename TInputImage, typename TRealType, typename TOutputImage> void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::GenerateInputRequestedRegion() throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output InputImagePointer inputPtr = const_cast< InputImageType * >( this->GetInput() ); OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) { return; } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion = inputPtr->GetRequestedRegion(); this->m_NeighborhoodRadius.Fill( 1 ); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius( this->m_NeighborhoodRadius ); // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) ) { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion( inputRequestedRegion ); // build an exception InvalidRequestedRegionError e( __FILE__, __LINE__ ); e.SetLocation( ITK_LOCATION ); e.SetDescription( "Requested region is outside the largest possible region." ); e.SetDataObject( inputPtr ); throw e; } } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::BeforeThreadedGenerateData() { /** If the input needs casting to a real-valued vector type, create the appropriate image and set the m_RealValuedInputImage pointer to this image. Otherwise just point to the input image. */ if ( typeid( typename InputImageType::PixelType ) != typeid( RealVectorType ) ) { typename VectorCastImageFilter<TInputImage, RealVectorImageType>::Pointer caster = VectorCastImageFilter<TInputImage, RealVectorImageType>::New(); caster->SetInput( this->GetInput() ); caster->Update(); this->m_RealValuedInputImage = caster->GetOutput(); } else { this->m_RealValuedInputImage = dynamic_cast<const RealVectorImageType *>( this->GetInput() ); } this->m_Interpolator = InterpolatorType::New(); this->m_Interpolator->SetInputImage( this->m_RealValuedInputImage ); PointType origin( 0.0 ); if( ImageDimension == 2 ) { this->InitializeTriangularDeltaPoints(); PointType pointA = origin + this->m_DeltaTriangularPointA; PointType pointB = origin + this->m_DeltaTriangularPointB; PointType pointC = origin + this->m_DeltaTriangularPointC; this->m_UndisplacedVolume = this->CalculateTriangularArea( pointA, pointB, pointC ); } else if( ImageDimension == 3 ) { this->InitializeTetrahedralDeltaPoints(); PointType pointA = origin + this->m_DeltaTetrahedralPointA; PointType pointB = origin + this->m_DeltaTetrahedralPointB; PointType pointC = origin + this->m_DeltaTetrahedralPointC; PointType pointD = origin + this->m_DeltaTetrahedralPointD; this->m_UndisplacedVolume = this->CalculateTetrahedralVolume( pointA, pointB, pointC, pointD ); } else { itkExceptionMacro( "Computations are only valid for ImageDimension = 2 or 3" ); } } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::InitializeTetrahedralDeltaPoints() { // cf http://en.wikipedia.org/wiki/Tetrahedron#Formulas_for_a_regular_tetrahedron typename InputImageType::PointType originPoint; ContinuousIndex<RealType, ImageDimension> cidx; cidx.Fill( 0.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, originPoint ); typename InputImageType::PointType deltaPoint; cidx[0] = 0.5; cidx[1] = 0.0; cidx[2] = -0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointA = deltaPoint - originPoint; cidx[0] = -0.5; cidx[1] = 0.0; cidx[2] = -0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointB = deltaPoint - originPoint; cidx[0] = 0.0; cidx[1] = 0.5; cidx[2] = 0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointC = deltaPoint - originPoint; cidx[0] = 0.0; cidx[1] = -0.5; cidx[2] = 0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointD = deltaPoint - originPoint; } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::InitializeTriangularDeltaPoints() { typename InputImageType::PointType originPoint; ContinuousIndex<RealType, ImageDimension> cidx; cidx.Fill( 0.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, originPoint ); typename InputImageType::PointType deltaPoint; cidx[0] = 0.0; cidx[1] = 0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointA = deltaPoint - originPoint; cidx[0] = -0.5; cidx[1] = -0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointB = deltaPoint - originPoint; cidx[0] = 0.5; cidx[1] = -0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointC = deltaPoint - originPoint; } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId ) { ZeroFluxNeumannBoundaryCondition<RealVectorImageType> nbc; ConstNeighborhoodIteratorType bit; ImageRegionIteratorWithIndex<TOutputImage> it; typename OutputImageType::Pointer outputPtr = this->GetOutput(); // Find the data-set boundary "faces" typename NeighborhoodAlgorithm:: ImageBoundaryFacesCalculator<RealVectorImageType>::FaceListType faceList; NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<RealVectorImageType> bC; faceList = bC( dynamic_cast<const RealVectorImageType *> ( this->m_RealValuedInputImage.GetPointer() ), outputRegionForThread, this->m_NeighborhoodRadius ); typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<RealVectorImageType>:: FaceListType::iterator fit; // Support progress methods/callbacks ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); // Process each of the data set faces. The iterator is reinitialized on each // face so that it can determine whether or not to check for boundary // conditions. for ( fit = faceList.begin(); fit != faceList.end(); ++fit ) { bit = ConstNeighborhoodIteratorType( this->m_NeighborhoodRadius, dynamic_cast<const RealVectorImageType *> ( m_RealValuedInputImage.GetPointer() ), *fit ); it = ImageRegionIteratorWithIndex<TOutputImage>( outputPtr, *fit ); bit.OverrideBoundaryCondition( &nbc ); bit.GoToBegin(); while ( ! bit.IsAtEnd() ) { typename InputImageType::IndexType index = it.GetIndex(); PointType imagePoint; outputPtr->TransformIndexToPhysicalPoint( index, imagePoint ); RealType displacedVolume = 0.0; if( ImageDimension == 2 ) { typename InterpolatorType::PointType pointA; pointA.CastFrom( imagePoint + this->m_DeltaTriangularPointA ); typename InterpolatorType::PointType pointB; pointB.CastFrom( imagePoint + this->m_DeltaTriangularPointB ); typename InterpolatorType::PointType pointC; pointC.CastFrom( imagePoint + this->m_DeltaTriangularPointC ); PointType displacedPointA = pointA + this->m_Interpolator->Evaluate( pointA ); PointType displacedPointB = pointB + this->m_Interpolator->Evaluate( pointB ); PointType displacedPointC = pointC + this->m_Interpolator->Evaluate( pointC ); displacedVolume = this->CalculateTriangularArea( displacedPointA, displacedPointB, displacedPointC ); } else if( ImageDimension == 3 ) { typename InterpolatorType::PointType pointA; pointA.CastFrom( imagePoint + this->m_DeltaTetrahedralPointA ); typename InterpolatorType::PointType pointB; pointB.CastFrom( imagePoint + this->m_DeltaTetrahedralPointB ); typename InterpolatorType::PointType pointC; pointC.CastFrom( imagePoint + this->m_DeltaTetrahedralPointC ); typename InterpolatorType::PointType pointD; pointD.CastFrom( imagePoint + this->m_DeltaTetrahedralPointD ); PointType displacedPointA = pointA + this->m_Interpolator->Evaluate( pointA ); PointType displacedPointB = pointB + this->m_Interpolator->Evaluate( pointB ); PointType displacedPointC = pointC + this->m_Interpolator->Evaluate( pointC ); PointType displacedPointD = pointD + this->m_Interpolator->Evaluate( pointD ); displacedVolume = this->CalculateTetrahedralVolume( displacedPointA, displacedPointB, displacedPointC, displacedPointD ); } RealType volumeDifferential = displacedVolume / this->m_UndisplacedVolume; it.Set( volumeDifferential ); ++bit; ++it; progress.CompletedPixel(); } } } template< typename TInputImage, typename TRealType, typename TOutputImage > typename GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage >::RealType GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::CalculateTetrahedralVolume( PointType a, PointType b, PointType c, PointType d ) { vnl_vector_ref<double> ad = ( a - d ).GetVnlVector(); vnl_vector_ref<double> bd = ( b - d ).GetVnlVector(); vnl_vector_ref<double> cd = ( c - d ).GetVnlVector(); vnl_vector<double> bdxcd = vnl_cross_3d( bd, cd ); RealType volume = vnl_math_abs( ad[0] * bdxcd[0] + ad[1] * bdxcd[1] + ad[2] * bdxcd[2] ) / 6.0; return volume; } template< typename TInputImage, typename TRealType, typename TOutputImage > typename GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage >::RealType GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::CalculateTriangularArea( PointType a, PointType b, PointType c ) { RealVectorType ab = ( a - b ); RealVectorType ac = ( a - c ); RealType area = 0.5 * vnl_math_abs( ab[0] * ac[1] - ac[0] * ab[1] ); return area; } template <typename TInputImage, typename TRealType, typename TOutputImage> void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf(os,indent); os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; } } // end namespace itk #endif <commit_msg>BUG: wrong vnl_vector type causing problems on Centos7.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkGeometricJacobianDeterminantImageFilter_hxx #define _itkGeometricJacobianDeterminantImageFilter_hxx #include "itkGeometricJacobianDeterminantImageFilter.h" #include "itkContinuousIndex.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkNeighborhoodAlgorithm.h" #include "itkProgressReporter.h" #include "itkVectorCastImageFilter.h" #include "itkZeroFluxNeumannBoundaryCondition.h" #include "vnl/vnl_cross.h" namespace itk { template <typename TInputImage, typename TRealType, typename TOutputImage> GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::GeometricJacobianDeterminantImageFilter() { this->m_Interpolator = ITK_NULLPTR; this->m_UndisplacedVolume = 0.0; } template <typename TInputImage, typename TRealType, typename TOutputImage> void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::GenerateInputRequestedRegion() throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input and output InputImagePointer inputPtr = const_cast< InputImageType * >( this->GetInput() ); OutputImagePointer outputPtr = this->GetOutput(); if ( !inputPtr || !outputPtr ) { return; } // get a copy of the input requested region (should equal the output // requested region) typename TInputImage::RegionType inputRequestedRegion; inputRequestedRegion = inputPtr->GetRequestedRegion(); this->m_NeighborhoodRadius.Fill( 1 ); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius( this->m_NeighborhoodRadius ); // crop the input requested region at the input's largest possible region if ( inputRequestedRegion.Crop( inputPtr->GetLargestPossibleRegion() ) ) { inputPtr->SetRequestedRegion( inputRequestedRegion ); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion( inputRequestedRegion ); // build an exception InvalidRequestedRegionError e( __FILE__, __LINE__ ); e.SetLocation( ITK_LOCATION ); e.SetDescription( "Requested region is outside the largest possible region." ); e.SetDataObject( inputPtr ); throw e; } } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::BeforeThreadedGenerateData() { /** If the input needs casting to a real-valued vector type, create the appropriate image and set the m_RealValuedInputImage pointer to this image. Otherwise just point to the input image. */ if ( typeid( typename InputImageType::PixelType ) != typeid( RealVectorType ) ) { typename VectorCastImageFilter<TInputImage, RealVectorImageType>::Pointer caster = VectorCastImageFilter<TInputImage, RealVectorImageType>::New(); caster->SetInput( this->GetInput() ); caster->Update(); this->m_RealValuedInputImage = caster->GetOutput(); } else { this->m_RealValuedInputImage = dynamic_cast<const RealVectorImageType *>( this->GetInput() ); } this->m_Interpolator = InterpolatorType::New(); this->m_Interpolator->SetInputImage( this->m_RealValuedInputImage ); PointType origin( 0.0 ); if( ImageDimension == 2 ) { this->InitializeTriangularDeltaPoints(); PointType pointA = origin + this->m_DeltaTriangularPointA; PointType pointB = origin + this->m_DeltaTriangularPointB; PointType pointC = origin + this->m_DeltaTriangularPointC; this->m_UndisplacedVolume = this->CalculateTriangularArea( pointA, pointB, pointC ); } else if( ImageDimension == 3 ) { this->InitializeTetrahedralDeltaPoints(); PointType pointA = origin + this->m_DeltaTetrahedralPointA; PointType pointB = origin + this->m_DeltaTetrahedralPointB; PointType pointC = origin + this->m_DeltaTetrahedralPointC; PointType pointD = origin + this->m_DeltaTetrahedralPointD; this->m_UndisplacedVolume = this->CalculateTetrahedralVolume( pointA, pointB, pointC, pointD ); } else { itkExceptionMacro( "Computations are only valid for ImageDimension = 2 or 3" ); } } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::InitializeTetrahedralDeltaPoints() { // cf http://en.wikipedia.org/wiki/Tetrahedron#Formulas_for_a_regular_tetrahedron typename InputImageType::PointType originPoint; ContinuousIndex<RealType, ImageDimension> cidx; cidx.Fill( 0.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, originPoint ); typename InputImageType::PointType deltaPoint; cidx[0] = 0.5; cidx[1] = 0.0; cidx[2] = -0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointA = deltaPoint - originPoint; cidx[0] = -0.5; cidx[1] = 0.0; cidx[2] = -0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointB = deltaPoint - originPoint; cidx[0] = 0.0; cidx[1] = 0.5; cidx[2] = 0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointC = deltaPoint - originPoint; cidx[0] = 0.0; cidx[1] = -0.5; cidx[2] = 0.5 / std::sqrt( 2.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTetrahedralPointD = deltaPoint - originPoint; } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::InitializeTriangularDeltaPoints() { typename InputImageType::PointType originPoint; ContinuousIndex<RealType, ImageDimension> cidx; cidx.Fill( 0.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, originPoint ); typename InputImageType::PointType deltaPoint; cidx[0] = 0.0; cidx[1] = 0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointA = deltaPoint - originPoint; cidx[0] = -0.5; cidx[1] = -0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointB = deltaPoint - originPoint; cidx[0] = 0.5; cidx[1] = -0.25 * std::sqrt( 3.0 ); this->m_RealValuedInputImage->TransformContinuousIndexToPhysicalPoint( cidx, deltaPoint ); this->m_DeltaTriangularPointC = deltaPoint - originPoint; } template< typename TInputImage, typename TRealType, typename TOutputImage > void GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::ThreadedGenerateData( const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId ) { ZeroFluxNeumannBoundaryCondition<RealVectorImageType> nbc; ConstNeighborhoodIteratorType bit; ImageRegionIteratorWithIndex<TOutputImage> it; typename OutputImageType::Pointer outputPtr = this->GetOutput(); // Find the data-set boundary "faces" typename NeighborhoodAlgorithm:: ImageBoundaryFacesCalculator<RealVectorImageType>::FaceListType faceList; NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<RealVectorImageType> bC; faceList = bC( dynamic_cast<const RealVectorImageType *> ( this->m_RealValuedInputImage.GetPointer() ), outputRegionForThread, this->m_NeighborhoodRadius ); typename NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<RealVectorImageType>:: FaceListType::iterator fit; // Support progress methods/callbacks ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); // Process each of the data set faces. The iterator is reinitialized on each // face so that it can determine whether or not to check for boundary // conditions. for ( fit = faceList.begin(); fit != faceList.end(); ++fit ) { bit = ConstNeighborhoodIteratorType( this->m_NeighborhoodRadius, dynamic_cast<const RealVectorImageType *> ( m_RealValuedInputImage.GetPointer() ), *fit ); it = ImageRegionIteratorWithIndex<TOutputImage>( outputPtr, *fit ); bit.OverrideBoundaryCondition( &nbc ); bit.GoToBegin(); while ( ! bit.IsAtEnd() ) { typename InputImageType::IndexType index = it.GetIndex(); PointType imagePoint; outputPtr->TransformIndexToPhysicalPoint( index, imagePoint ); RealType displacedVolume = 0.0; if( ImageDimension == 2 ) { typename InterpolatorType::PointType pointA; pointA.CastFrom( imagePoint + this->m_DeltaTriangularPointA ); typename InterpolatorType::PointType pointB; pointB.CastFrom( imagePoint + this->m_DeltaTriangularPointB ); typename InterpolatorType::PointType pointC; pointC.CastFrom( imagePoint + this->m_DeltaTriangularPointC ); PointType displacedPointA = pointA + this->m_Interpolator->Evaluate( pointA ); PointType displacedPointB = pointB + this->m_Interpolator->Evaluate( pointB ); PointType displacedPointC = pointC + this->m_Interpolator->Evaluate( pointC ); displacedVolume = this->CalculateTriangularArea( displacedPointA, displacedPointB, displacedPointC ); } else if( ImageDimension == 3 ) { typename InterpolatorType::PointType pointA; pointA.CastFrom( imagePoint + this->m_DeltaTetrahedralPointA ); typename InterpolatorType::PointType pointB; pointB.CastFrom( imagePoint + this->m_DeltaTetrahedralPointB ); typename InterpolatorType::PointType pointC; pointC.CastFrom( imagePoint + this->m_DeltaTetrahedralPointC ); typename InterpolatorType::PointType pointD; pointD.CastFrom( imagePoint + this->m_DeltaTetrahedralPointD ); PointType displacedPointA = pointA + this->m_Interpolator->Evaluate( pointA ); PointType displacedPointB = pointB + this->m_Interpolator->Evaluate( pointB ); PointType displacedPointC = pointC + this->m_Interpolator->Evaluate( pointC ); PointType displacedPointD = pointD + this->m_Interpolator->Evaluate( pointD ); displacedVolume = this->CalculateTetrahedralVolume( displacedPointA, displacedPointB, displacedPointC, displacedPointD ); } RealType volumeDifferential = displacedVolume / ( this->m_UndisplacedVolume ); it.Set( volumeDifferential ); ++bit; ++it; progress.CompletedPixel(); } } } template< typename TInputImage, typename TRealType, typename TOutputImage > typename GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage >::RealType GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::CalculateTetrahedralVolume( PointType a, PointType b, PointType c, PointType d ) { vnl_vector<double> ad = ( a - d ).GetVnlVector(); vnl_vector<double> bd = ( b - d ).GetVnlVector(); vnl_vector<double> cd = ( c - d ).GetVnlVector(); vnl_vector<double> bdxcd = vnl_cross_3d( bd, cd ); RealType volume = vnl_math_abs( ad[0] * bdxcd[0] + ad[1] * bdxcd[1] + ad[2] * bdxcd[2] ) / 6.0; return volume; } template< typename TInputImage, typename TRealType, typename TOutputImage > typename GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage >::RealType GeometricJacobianDeterminantImageFilter< TInputImage, TRealType, TOutputImage > ::CalculateTriangularArea( PointType a, PointType b, PointType c ) { RealVectorType ab = ( a - b ); RealVectorType ac = ( a - c ); RealType area = 0.5 * vnl_math_abs( ab[0] * ac[1] - ac[0] * ab[1] ); return area; } template <typename TInputImage, typename TRealType, typename TOutputImage> void GeometricJacobianDeterminantImageFilter<TInputImage, TRealType, TOutputImage> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf(os,indent); os << indent << "m_RealValuedInputImage = " << m_RealValuedInputImage.GetPointer() << std::endl; } } // end namespace itk #endif <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/gbdt.h> #include <vespa/eval/eval/vm_forest.h> #include <vespa/eval/eval/llvm/deinline_forest.h> #include <vespa/eval/eval/llvm/compiled_function.h> #include <vespa/eval/eval/function.h> #include <vespa/vespalib/util/benchmark_timer.h> #include <vespa/vespalib/util/stringfmt.h> #include "model.cpp" using namespace vespalib::eval; using namespace vespalib::eval::nodes; using namespace vespalib::eval::gbdt; //----------------------------------------------------------------------------- struct CompileStrategy { virtual const char *name() const = 0; virtual const char *code_name() const = 0; virtual CompiledFunction compile(const Function &function) const = 0; bool is_same(const CompileStrategy &rhs) const { return (this == &rhs); } virtual ~CompileStrategy() {} }; struct NullStrategy : CompileStrategy { virtual const char *name() const { return "none"; } virtual const char *code_name() const { return "Optimize::none"; } virtual CompiledFunction compile(const Function &function) const { return CompiledFunction(function, PassParams::ARRAY, Optimize::none); } }; NullStrategy none; struct VMForestStrategy : CompileStrategy { virtual const char *name() const { return "vm-forest"; } virtual const char *code_name() const { return "VMForest::optimize_chain"; } virtual CompiledFunction compile(const Function &function) const { return CompiledFunction(function, PassParams::ARRAY, VMForest::optimize_chain); } }; VMForestStrategy vm_forest; struct DeinlineForestStrategy : CompileStrategy { virtual const char *name() const { return "deinline-forest"; } virtual const char *code_name() const { return "DeinlineForest::optimize_chain"; } virtual CompiledFunction compile(const Function &function) const { return CompiledFunction(function, PassParams::ARRAY, DeinlineForest::optimize_chain); } }; DeinlineForestStrategy deinline_forest; //----------------------------------------------------------------------------- struct Option { size_t id; const CompileStrategy &strategy; bool is_same(const Option &rhs) const { return strategy.is_same(rhs.strategy); } const char *name() const { return strategy.name(); } CompiledFunction compile(const Function &function) const { return strategy.compile(function); } const char *code_name() const { return strategy.code_name(); } }; std::vector<Option> all_options({{0, none},{1, vm_forest}}); //----------------------------------------------------------------------------- struct Result { double us; size_t opt_idx; bool operator<(const Result &rhs) { return (us < rhs.us); } }; struct Segment { double min; Option option; vespalib::string build() const { return vespalib::make_string("{%g, %zu}", min, option.id); } }; struct Plan { std::vector<Segment> segments; void add(const Segment &seg) { if (segments.empty()) { segments.push_back(seg); } else { if (!segments.back().option.is_same(seg.option)) { segments.push_back(seg); } } } vespalib::string build() const { vespalib::string plan; plan.append("{"); for (size_t i = 0; i < segments.size(); ++i) { if (i > 0) { plan.append(", "); } plan += segments[i].build(); } plan.append("}"); return plan; } }; //----------------------------------------------------------------------------- bool crop(const std::vector<Option> &options, const Option &opt, size_t &end) { for (size_t i = 0; i < end; ++i) { if (options[i].is_same(opt)) { end = i; return true; } } return false; } std::vector<Option> keep_contested(const std::vector<Option> &a, const std::vector<Option> &b) { size_t end = b.size(); std::vector<Option> ret; for (size_t i = 0; (i < a.size()) && (end > 0); ++i) { if (crop(b, a[i], end)) { ret.push_back(a[i]); } } return ret; } std::vector<Option> find_order(const ForestParams &params, const std::vector<Option> &options, size_t num_trees) { std::vector<Result> results; Function forest = make_forest(params, num_trees); for (size_t i = 0; i < options.size(); ++i) { CompiledFunction compiled_function = options[i].compile(forest); std::vector<double> inputs(compiled_function.num_params(), 0.5); results.push_back({compiled_function.estimate_cost_us(inputs), i}); fprintf(stderr, " %20s@%6zu: %16g us (inputs: %zu)\n", options[i].name(), num_trees, results.back().us, inputs.size()); } std::sort(results.begin(), results.end()); std::vector<Option> ret; for (auto result: results) { ret.push_back(options[result.opt_idx]); } return ret; } double expected_path(const ForestParams &params, size_t num_trees) { return ForestStats(extract_trees(make_forest(params, num_trees).root())).total_expected_path_length; } void explore_segment(const ForestParams &params, const std::vector<Option> &min_order, const std::vector<Option> &max_order, size_t min_trees, size_t max_trees, Plan &plan_out) { assert(min_trees != max_trees); std::vector<Option> options = keep_contested(min_order, max_order); assert(!options.empty()); if (options.size() == 1) { plan_out.add(Segment{expected_path(params, min_trees), options[0]}); } else { if ((max_trees - min_trees) == 1) { plan_out.add(Segment{expected_path(params, min_trees), min_order[0]}); plan_out.add(Segment{expected_path(params, max_trees), max_order[0]}); } else { size_t num_trees = (min_trees + max_trees) / 2; std::vector<Option> order = find_order(params, options, num_trees); explore_segment(params, min_order, order, min_trees, num_trees, plan_out); explore_segment(params, order, max_order, num_trees, max_trees, plan_out); } } } Plan find_plan(const ForestParams &params, std::initializer_list<size_t> limits) { Plan plan; auto num_trees = limits.begin(); size_t min_trees = *num_trees++; std::vector<Option> min_order = find_order(params, all_options, min_trees); while (num_trees != limits.end()) { size_t max_trees = *num_trees++; std::vector<Option> max_order = find_order(params, all_options, max_trees); explore_segment(params, min_order, max_order, min_trees, max_trees, plan); std::swap(min_trees, max_trees); std::swap(min_order, max_order); } return plan; } //----------------------------------------------------------------------------- void dump_options(const std::vector<Option> &options) { fprintf(stdout, "std::vector<Optimize::Chain> options({"); for (size_t i = 0; i < options.size(); ++i) { if (i > 0) { fprintf(stdout, ", "); } fprintf(stdout, "%s", options[i].code_name()); } fprintf(stdout, "});\n"); fflush(stdout); } void dump_param_values(const char *name, const std::vector<size_t> &values) { fprintf(stdout, "std::vector<size_t> %s({", name); for (size_t i = 0; i < values.size(); ++i) { if (i > 0) { fprintf(stdout, ", "); } fprintf(stdout, "%zu", values[i]); } fprintf(stdout, "});\n"); fflush(stdout); } void dump_plan(const ForestParams &params, const Plan &plan) { fprintf(stdout, "{{%zu, %zu}, %s}", params.less_percent, params.tree_size, plan.build().c_str()); } //----------------------------------------------------------------------------- TEST("find optimization plans") { std::vector<size_t> less_percent_values({90, 100}); std::vector<size_t> tree_size_values( {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 88, 96, 104, 112, 120, 128}); dump_options(all_options); dump_param_values("less_percent_values", less_percent_values); dump_param_values("tree_size_values", tree_size_values); size_t num_plans = 0; fprintf(stdout, "std::map<Params,Plan> plan_repo({"); for (size_t less_percent: less_percent_values) { for (size_t tree_size: tree_size_values) { ForestParams params(1234u, less_percent, tree_size); fprintf(stdout, "%s\n", (num_plans++ == 0) ? "" : ","); fflush(stdout); fprintf(stdout, " "); Plan plan = find_plan(params, {8, 512}); dump_plan(params, plan); } } fprintf(stdout, "});\n"); } //----------------------------------------------------------------------------- TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>also log lazy time/factor in explore benchmark<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/gbdt.h> #include <vespa/eval/eval/vm_forest.h> #include <vespa/eval/eval/llvm/deinline_forest.h> #include <vespa/eval/eval/llvm/compiled_function.h> #include <vespa/eval/eval/function.h> #include <vespa/vespalib/util/benchmark_timer.h> #include <vespa/vespalib/util/stringfmt.h> #include "model.cpp" using namespace vespalib::eval; using namespace vespalib::eval::nodes; using namespace vespalib::eval::gbdt; double budget = 2.0; //----------------------------------------------------------------------------- struct CompileStrategy { virtual const char *name() const = 0; virtual const char *code_name() const = 0; virtual CompiledFunction compile(const Function &function) const = 0; virtual CompiledFunction compile_lazy(const Function &function) const = 0; bool is_same(const CompileStrategy &rhs) const { return (this == &rhs); } virtual ~CompileStrategy() {} }; struct NullStrategy : CompileStrategy { const char *name() const override { return "none"; } const char *code_name() const override { return "Optimize::none"; } CompiledFunction compile(const Function &function) const override { return CompiledFunction(function, PassParams::ARRAY, Optimize::none); } CompiledFunction compile_lazy(const Function &function) const override { return CompiledFunction(function, PassParams::LAZY, Optimize::none); } }; NullStrategy none; struct VMForestStrategy : CompileStrategy { const char *name() const override { return "vm-forest"; } const char *code_name() const override { return "VMForest::optimize_chain"; } CompiledFunction compile(const Function &function) const override { return CompiledFunction(function, PassParams::ARRAY, VMForest::optimize_chain); } CompiledFunction compile_lazy(const Function &function) const override { return CompiledFunction(function, PassParams::LAZY, VMForest::optimize_chain); } }; VMForestStrategy vm_forest; struct DeinlineForestStrategy : CompileStrategy { const char *name() const override { return "deinline-forest"; } const char *code_name() const override { return "DeinlineForest::optimize_chain"; } CompiledFunction compile(const Function &function) const override { return CompiledFunction(function, PassParams::ARRAY, DeinlineForest::optimize_chain); } CompiledFunction compile_lazy(const Function &function) const override { return CompiledFunction(function, PassParams::LAZY, DeinlineForest::optimize_chain); } }; DeinlineForestStrategy deinline_forest; //----------------------------------------------------------------------------- struct Option { size_t id; const CompileStrategy &strategy; bool is_same(const Option &rhs) const { return strategy.is_same(rhs.strategy); } const char *name() const { return strategy.name(); } CompiledFunction compile(const Function &function) const { return strategy.compile(function); } CompiledFunction compile_lazy(const Function &function) const { return strategy.compile_lazy(function); } const char *code_name() const { return strategy.code_name(); } }; std::vector<Option> all_options({{0, none},{1, vm_forest}}); //----------------------------------------------------------------------------- struct Result { double us; size_t opt_idx; bool operator<(const Result &rhs) { return (us < rhs.us); } }; struct Segment { double min; Option option; vespalib::string build() const { return vespalib::make_string("{%g, %zu}", min, option.id); } }; struct Plan { std::vector<Segment> segments; void add(const Segment &seg) { if (segments.empty()) { segments.push_back(seg); } else { if (!segments.back().option.is_same(seg.option)) { segments.push_back(seg); } } } vespalib::string build() const { vespalib::string plan; plan.append("{"); for (size_t i = 0; i < segments.size(); ++i) { if (i > 0) { plan.append(", "); } plan += segments[i].build(); } plan.append("}"); return plan; } }; //----------------------------------------------------------------------------- bool crop(const std::vector<Option> &options, const Option &opt, size_t &end) { for (size_t i = 0; i < end; ++i) { if (options[i].is_same(opt)) { end = i; return true; } } return false; } std::vector<Option> keep_contested(const std::vector<Option> &a, const std::vector<Option> &b) { size_t end = b.size(); std::vector<Option> ret; for (size_t i = 0; (i < a.size()) && (end > 0); ++i) { if (crop(b, a[i], end)) { ret.push_back(a[i]); } } return ret; } std::vector<Option> find_order(const ForestParams &params, const std::vector<Option> &options, size_t num_trees) { std::vector<Result> results; Function forest = make_forest(params, num_trees); for (size_t i = 0; i < options.size(); ++i) { CompiledFunction compiled_function = options[i].compile(forest); CompiledFunction compiled_function_lazy = options[i].compile_lazy(forest); std::vector<double> inputs(compiled_function.num_params(), 0.5); results.push_back({compiled_function.estimate_cost_us(inputs, budget), i}); double lazy_time = compiled_function_lazy.estimate_cost_us(inputs, budget); double lazy_factor = lazy_time / results.back().us; fprintf(stderr, " %20s@%6zu: %16g us (inputs: %zu) [lazy: %g us, factor: %g]\n", options[i].name(), num_trees, results.back().us, inputs.size(), lazy_time, lazy_factor); } std::sort(results.begin(), results.end()); std::vector<Option> ret; for (auto result: results) { ret.push_back(options[result.opt_idx]); } return ret; } double expected_path(const ForestParams &params, size_t num_trees) { return ForestStats(extract_trees(make_forest(params, num_trees).root())).total_expected_path_length; } void explore_segment(const ForestParams &params, const std::vector<Option> &min_order, const std::vector<Option> &max_order, size_t min_trees, size_t max_trees, Plan &plan_out) { assert(min_trees != max_trees); std::vector<Option> options = keep_contested(min_order, max_order); assert(!options.empty()); if (options.size() == 1) { plan_out.add(Segment{expected_path(params, min_trees), options[0]}); } else { if ((max_trees - min_trees) == 1) { plan_out.add(Segment{expected_path(params, min_trees), min_order[0]}); plan_out.add(Segment{expected_path(params, max_trees), max_order[0]}); } else { size_t num_trees = (min_trees + max_trees) / 2; std::vector<Option> order = find_order(params, options, num_trees); explore_segment(params, min_order, order, min_trees, num_trees, plan_out); explore_segment(params, order, max_order, num_trees, max_trees, plan_out); } } } Plan find_plan(const ForestParams &params, std::initializer_list<size_t> limits) { Plan plan; auto num_trees = limits.begin(); size_t min_trees = *num_trees++; std::vector<Option> min_order = find_order(params, all_options, min_trees); while (num_trees != limits.end()) { size_t max_trees = *num_trees++; std::vector<Option> max_order = find_order(params, all_options, max_trees); explore_segment(params, min_order, max_order, min_trees, max_trees, plan); std::swap(min_trees, max_trees); std::swap(min_order, max_order); } return plan; } //----------------------------------------------------------------------------- void dump_options(const std::vector<Option> &options) { fprintf(stdout, "std::vector<Optimize::Chain> options({"); for (size_t i = 0; i < options.size(); ++i) { if (i > 0) { fprintf(stdout, ", "); } fprintf(stdout, "%s", options[i].code_name()); } fprintf(stdout, "});\n"); fflush(stdout); } void dump_param_values(const char *name, const std::vector<size_t> &values) { fprintf(stdout, "std::vector<size_t> %s({", name); for (size_t i = 0; i < values.size(); ++i) { if (i > 0) { fprintf(stdout, ", "); } fprintf(stdout, "%zu", values[i]); } fprintf(stdout, "});\n"); fflush(stdout); } void dump_plan(const ForestParams &params, const Plan &plan) { fprintf(stdout, "{{%zu, %zu}, %s}", params.less_percent, params.tree_size, plan.build().c_str()); } //----------------------------------------------------------------------------- TEST("find optimization plans") { std::vector<size_t> less_percent_values({90, 100}); std::vector<size_t> tree_size_values( {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 88, 96, 104, 112, 120, 128}); dump_options(all_options); dump_param_values("less_percent_values", less_percent_values); dump_param_values("tree_size_values", tree_size_values); size_t num_plans = 0; fprintf(stdout, "std::map<Params,Plan> plan_repo({"); for (size_t less_percent: less_percent_values) { for (size_t tree_size: tree_size_values) { ForestParams params(1234u, less_percent, tree_size); fprintf(stdout, "%s\n", (num_plans++ == 0) ? "" : ","); fflush(stdout); fprintf(stdout, " "); Plan plan = find_plan(params, {8, 512}); dump_plan(params, plan); } } fprintf(stdout, "});\n"); } //----------------------------------------------------------------------------- TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>#include "basicopenglview.h" // this version demonstrates using the mouse to inout some points and draw lines between them BasicOpenGLView::BasicOpenGLView(QWidget *parent) : QGLWidget(parent), polygons(QVector< QVector<QVector3D> >()) { clearon = false; mousedown = false; lastpt = -1; csv = NULL; // represents an unselected vertex //polygons = QVector< QVector<QVector3D> >(); srand (time(NULL)); newPoly(); qDebug() << "NEW HERE"; } void BasicOpenGLView::initializeGL() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // white glShadeModel( GL_FLAT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPointSize(5); } void BasicOpenGLView::resizeGL(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,GLdouble(width),0,GLdouble(height),-10.0,10.0); //glOrtho(-(GLdouble)width/2.0, (GLdouble)width/2.0, -(GLdouble)height/2.0, (GLdouble)height/2.0, -10.0,10.0); glMatrixMode(GL_MODELVIEW); // qDebug()<< "resize\n"; } void BasicOpenGLView::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); drawFigure(); //QGLWidget::swapBuffers(); } void BasicOpenGLView::mousePressEvent(QMouseEvent *e) { if (mousedown) return; mousedown = true; csv = NULL; if (e->button() == Qt::RightButton) addPoint( e->x(), height()-e->y() ); if (e->button() == Qt::LeftButton) movePoint(e->x(), height()-e->y() ); update(); } void BasicOpenGLView::mouseMoveEvent(QMouseEvent *e) { if (mousedown) movePoint(e->x(), height()-e->y()); update(); } void BasicOpenGLView::mouseReleaseEvent(QMouseEvent *e) { // finished move point movePoint(e->x(), height()-e->y()); mousedown = false; update(); } void BasicOpenGLView::movePoint(int x, int y) { if (mousedown) { if (csv == NULL) // If no vertex selected select(x, y); // Look for vertex selected if (csv != NULL) { // If vertex selected csv->setX(x); csv->setY(y); } } } void BasicOpenGLView::addPoint(int x, int y) { int i; for (i = 0; i < polygons.size(); i++) { if ( polygons.at(i).size() > 0 && ( (polygons.at(i).at(0).x()-RADIUS) < x && (polygons.at(i).at(0).x()+RADIUS) > x ) && ( (polygons.at(i).at(0).y()-RADIUS) < y && (polygons.at(i).at(0).y()+RADIUS) > y ) ) { newPoly(); return; } } polygons.last().append(QVector3D(x, y, 1)); } void BasicOpenGLView::select(int x, int y) { int i, j; for (i = 0; i < polygons.size(); i++) { for (j = 0; j < polygons.at(i).size(); j++) { if ( ( (polygons.at(i).at(j).x()-RADIUS) < x && (polygons.at(i).at(j).x()+RADIUS) > x ) && ( (polygons.at(i).at(j).y()-RADIUS) < y && (polygons.at(i).at(j).y()+RADIUS) > y ) ) { csv = &(polygons[i][j]); } } } } void BasicOpenGLView::clearme() { //for (int i = 0; i < polygons.size(); i++) // polygons.at(i).clear(); // THIS IS NOT A DEEP CLEAR, FIX THIS polygons.clear(); polyColors.clear(); newPoly(); update(); } void BasicOpenGLView::drawCircle(double radius, double xcen, double ycen, bool line) { GLint i; static GLfloat circcoords[100][2]; // qDebug()<<"drawing circle "<< radius SEP xcen SEP ycen NL; for(i=0;i<100;i++) { circcoords[i][0]=radius*cos(i*2*M_PI/100.0)+xcen; circcoords[i][1]=radius*sin(i*2*M_PI/100.0)+ycen; } if (line) glBegin(GL_LINES); else glBegin(GL_POLYGON); for(i=0;i<100;i++) glVertex2fv(&circcoords[i][0]); glEnd(); } void BasicOpenGLView::drawLine(double x0, double y0, double x1, double y1 ) { glBegin(GL_LINES); glVertex2f(x0, y0); glVertex2f(x1, y1); glEnd(); } void BasicOpenGLView::drawFigure() { // draw a line between each pair of points int x0,x1,y0,y1,i,j, firstX, firstY; int numPolys = polygons.size(); for (i = 0; i < numPolys; i++) { if (polygons.at(i).size() <= 1) ; else { firstX = polygons.at(i).at(0).x(); firstY = polygons.at(i).at(0).y(); x0 = firstX; y0 = firstY; glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 1; j < polygons.at(i).size(); j++) { x1 = polygons.at(i).at(j).x(); y1 = polygons.at(i).at(j).y(); drawLine(x0, y0, x1, y1); x0 = x1; y0 = y1; } // If this is a closed polygon, draw the last line if (i != (numPolys - 1)) drawLine(x1, y1, firstX, firstY); } glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 0; j < polygons.at(i).size(); j++) drawCircle( (double)RADIUS, polygons.at(i).at(j).x(), polygons.at(i).at(j).y(), false); } } void BasicOpenGLView::newPoly() { polygons.append(QVector<QVector3D>()); polyColors.append(QVector<double>(3)); polyColors.last()[0] = ((double) rand() / (RAND_MAX)); polyColors.last()[1] = ((double) rand() / (RAND_MAX)); polyColors.last()[2] = ((double) rand() / (RAND_MAX)); update(); } <commit_msg>Master branch gets ahead<commit_after>#include "basicopenglview.h" // this version demonstrates using the mouse to inout some points and draw lines between them BasicOpenGLView::BasicOpenGLView(QWidget *parent) : QGLWidget(parent), polygons(QVector< QVector<QVector3D> >()) { clearon = false; mousedown = false; lastpt = -1; csv = NULL; // represents an unselected vertex //polygons = QVector< QVector<QVector3D> >(); srand (time(NULL)); newPoly(); qDebug() << "NEW HERE"; qDebug() << "Move Master Along, separate from pointer branch"; } void BasicOpenGLView::initializeGL() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // white glShadeModel( GL_FLAT ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPointSize(5); } void BasicOpenGLView::resizeGL(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,GLdouble(width),0,GLdouble(height),-10.0,10.0); //glOrtho(-(GLdouble)width/2.0, (GLdouble)width/2.0, -(GLdouble)height/2.0, (GLdouble)height/2.0, -10.0,10.0); glMatrixMode(GL_MODELVIEW); // qDebug()<< "resize\n"; } void BasicOpenGLView::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); drawFigure(); //QGLWidget::swapBuffers(); } void BasicOpenGLView::mousePressEvent(QMouseEvent *e) { if (mousedown) return; mousedown = true; csv = NULL; if (e->button() == Qt::RightButton) addPoint( e->x(), height()-e->y() ); if (e->button() == Qt::LeftButton) movePoint(e->x(), height()-e->y() ); update(); } void BasicOpenGLView::mouseMoveEvent(QMouseEvent *e) { if (mousedown) movePoint(e->x(), height()-e->y()); update(); } void BasicOpenGLView::mouseReleaseEvent(QMouseEvent *e) { // finished move point movePoint(e->x(), height()-e->y()); mousedown = false; update(); } void BasicOpenGLView::movePoint(int x, int y) { if (mousedown) { if (csv == NULL) // If no vertex selected select(x, y); // Look for vertex selected if (csv != NULL) { // If vertex selected csv->setX(x); csv->setY(y); } } } void BasicOpenGLView::addPoint(int x, int y) { int i; for (i = 0; i < polygons.size(); i++) { if ( polygons.at(i).size() > 0 && ( (polygons.at(i).at(0).x()-RADIUS) < x && (polygons.at(i).at(0).x()+RADIUS) > x ) && ( (polygons.at(i).at(0).y()-RADIUS) < y && (polygons.at(i).at(0).y()+RADIUS) > y ) ) { newPoly(); return; } } polygons.last().append(QVector3D(x, y, 1)); } void BasicOpenGLView::select(int x, int y) { int i, j; for (i = 0; i < polygons.size(); i++) { for (j = 0; j < polygons.at(i).size(); j++) { if ( ( (polygons.at(i).at(j).x()-RADIUS) < x && (polygons.at(i).at(j).x()+RADIUS) > x ) && ( (polygons.at(i).at(j).y()-RADIUS) < y && (polygons.at(i).at(j).y()+RADIUS) > y ) ) { csv = &(polygons[i][j]); } } } } void BasicOpenGLView::clearme() { //for (int i = 0; i < polygons.size(); i++) // polygons.at(i).clear(); // THIS IS NOT A DEEP CLEAR, FIX THIS polygons.clear(); polyColors.clear(); newPoly(); update(); } void BasicOpenGLView::drawCircle(double radius, double xcen, double ycen, bool line) { GLint i; static GLfloat circcoords[100][2]; // qDebug()<<"drawing circle "<< radius SEP xcen SEP ycen NL; for(i=0;i<100;i++) { circcoords[i][0]=radius*cos(i*2*M_PI/100.0)+xcen; circcoords[i][1]=radius*sin(i*2*M_PI/100.0)+ycen; } if (line) glBegin(GL_LINES); else glBegin(GL_POLYGON); for(i=0;i<100;i++) glVertex2fv(&circcoords[i][0]); glEnd(); } void BasicOpenGLView::drawLine(double x0, double y0, double x1, double y1 ) { glBegin(GL_LINES); glVertex2f(x0, y0); glVertex2f(x1, y1); glEnd(); } void BasicOpenGLView::drawFigure() { // draw a line between each pair of points int x0,x1,y0,y1,i,j, firstX, firstY; int numPolys = polygons.size(); for (i = 0; i < numPolys; i++) { if (polygons.at(i).size() <= 1) ; else { firstX = polygons.at(i).at(0).x(); firstY = polygons.at(i).at(0).y(); x0 = firstX; y0 = firstY; glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 1; j < polygons.at(i).size(); j++) { x1 = polygons.at(i).at(j).x(); y1 = polygons.at(i).at(j).y(); drawLine(x0, y0, x1, y1); x0 = x1; y0 = y1; } // If this is a closed polygon, draw the last line if (i != (numPolys - 1)) drawLine(x1, y1, firstX, firstY); } glColor3f(polyColors[i][0], polyColors[i][1], polyColors[i][2]); for (j = 0; j < polygons.at(i).size(); j++) drawCircle( (double)RADIUS, polygons.at(i).at(j).x(), polygons.at(i).at(j).y(), false); } } void BasicOpenGLView::newPoly() { polygons.append(QVector<QVector3D>()); polyColors.append(QVector<double>(3)); polyColors.last()[0] = ((double) rand() / (RAND_MAX)); polyColors.last()[1] = ((double) rand() / (RAND_MAX)); polyColors.last()[2] = ((double) rand() / (RAND_MAX)); update(); } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <genecis/container/array.h> #include <genecis/signal/sample_rate.h> #include <genecis/signal/fourier_transform.h> using namespace genecis::container ; using namespace genecis::signal ; using namespace std ; double sinc( double x ) { double result = 1 ; if( x != 0 ) result = sin(x) / x ; return result ; } template<class Cplx, class Real> void convert_real( const Cplx& input, Real& output ) { typedef typename Cplx::size_type size_type ; size_type s( input.size() ) ; for(size_type i=0; i<s; ++i) output(i) = std::abs(input(i)) ; } int main() { typedef double value_type ; typedef complex<value_type> complex_num ; typedef array<complex_num> container_cplx ; typedef array<value_type> container_real ; typedef size_t size_type ; size_type N = 10 ; value_type sig[10] ; for(size_type i=0; i<N; ++i) { sig[i] = (i<5) ? 1 : 0 ; } container_real input( sig, N ) ; container_real impulse ; container_cplx output ; fourier_transform::discrete( input, output ) ; cout << "input signal:" << input << endl ; cout << "dft signal:" << output << endl ; fourier_transform::inverse( output, impulse ) ; cout << "inverse dft signal:" << impulse << endl ; } <commit_msg>Updated test for output testing.<commit_after>#include <ctime> #include <cstdlib> #include <genecis/container/array.h> #include <genecis/signal/sample_rate.h> #include <genecis/signal/fourier_transform.h> using namespace genecis::container ; using namespace genecis::signal ; using namespace std ; double sinc( double x ) { double result = 1 ; if( x != 0 ) result = sin(x) / x ; return result ; } template<class Cplx, class Real> void convert_real( const Cplx& input, Real& output ) { typedef typename Cplx::size_type size_type ; size_type s( input.size() ) ; for(size_type i=0; i<s; ++i) output(i) = std::abs(input(i)) ; } int main() { typedef double value_type ; typedef complex<value_type> complex_num ; typedef array<complex_num> container_cplx ; typedef array<value_type> container_real ; typedef size_t size_type ; size_type N = 100 ; value_type sig[100] ; srand(time(0)) ; for(size_type i=0; i<N; ++i) { sig[i] = std::sin(30*2*M_PI*i/100) + rand()%2 - 1/2 ; } container_real input( sig, N ) ; container_real impulse ; container_cplx output ; fourier_transform::discrete( input, output ) ; impulse.resize( N ) ; convert_real( output, impulse ) ; cout << "real dft sig:" << impulse << endl ; cout << "input signal:" << input << endl ; // cout << "dft signal:" << output << endl ; // // fourier_transform::inverse( output, impulse ) ; // cout << "inverse dft signal:" << impulse << endl ; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreCompositorChain.h" #include "OgreCompositionTechnique.h" #include "OgreCompositorInstance.h" #include "OgreCompositionTargetPass.h" #include "OgreCompositionPass.h" #include "OgreViewport.h" #include "OgreCamera.h" #include "OgreRenderTarget.h" #include "OgreLogManager.h" #include "OgreCompositorManager.h" #include "OgreSceneManager.h" #include "OgreRenderQueueInvocation.h" namespace Ogre { CompositorChain::CompositorChain(Viewport *vp): mViewport(vp), mOriginalScene(0), mDirty(true), mAnyCompositorsEnabled(false) { mOldClearEveryFrameBuffers = mViewport->getClearBuffers(); assert(mViewport); } //----------------------------------------------------------------------- CompositorChain::~CompositorChain() { destroyResources(); } //----------------------------------------------------------------------- void CompositorChain::destroyResources(void) { clearCompiledState(); if (mViewport) { removeAllCompositors(); /// Destroy "original scene" compositor instance if (mOriginalScene) { mViewport->getTarget()->removeListener(this); mOriginalScene->getTechnique()->destroyInstance(mOriginalScene); mOriginalScene = 0; } mViewport = 0; } } //----------------------------------------------------------------------- CompositorInstance* CompositorChain::addCompositor(CompositorPtr filter, size_t addPosition, size_t technique) { // Init on demand if (!mOriginalScene) { mViewport->getTarget()->addListener(this); /// Create base "original scene" compositor CompositorPtr base = CompositorManager::getSingleton().load("Ogre/Scene", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); mOriginalScene = base->getSupportedTechnique(0)->createInstance(this); } filter->touch(); if(technique >= filter->getNumSupportedTechniques()) { /// Warn user LogManager::getSingleton().logMessage( "CompositorChain: Compositor " + filter->getName() + " has no supported techniques.", LML_CRITICAL ); return 0; } CompositionTechnique *tech = filter->getSupportedTechnique(technique); CompositorInstance *t = tech->createInstance(this); if(addPosition == LAST) addPosition = mInstances.size(); else assert(addPosition <= mInstances.size() && "Index out of bounds."); mInstances.insert(mInstances.begin()+addPosition, t); mDirty = true; mAnyCompositorsEnabled = true; return t; } //----------------------------------------------------------------------- void CompositorChain::removeCompositor(size_t index) { assert (index < mInstances.size() && "Index out of bounds."); Instances::iterator i = mInstances.begin() + index; (*i)->getTechnique()->destroyInstance(*i); mInstances.erase(i); mDirty = true; } //----------------------------------------------------------------------- size_t CompositorChain::getNumCompositors() { return mInstances.size(); } //----------------------------------------------------------------------- void CompositorChain::removeAllCompositors() { Instances::iterator i, iend; iend = mInstances.end(); for (i = mInstances.begin(); i != iend; ++i) { (*i)->getTechnique()->destroyInstance(*i); } mInstances.clear(); mDirty = true; } //----------------------------------------------------------------------- void CompositorChain::_removeInstance(CompositorInstance *i) { mInstances.erase(std::find(mInstances.begin(), mInstances.end(), i)); i->getTechnique()->destroyInstance(i); } //----------------------------------------------------------------------- void CompositorChain::_queuedOperation(CompositorInstance::RenderSystemOperation* op) { mRenderSystemOperations.push_back(op); } //----------------------------------------------------------------------- CompositorInstance *CompositorChain::getCompositor(size_t index) { assert (index < mInstances.size() && "Index out of bounds."); return mInstances[index]; } //----------------------------------------------------------------------- CompositorChain::InstanceIterator CompositorChain::getCompositors() { return InstanceIterator(mInstances.begin(), mInstances.end()); } //----------------------------------------------------------------------- void CompositorChain::setCompositorEnabled(size_t position, bool state) { getCompositor(position)->setEnabled(state); } //----------------------------------------------------------------------- void CompositorChain::preRenderTargetUpdate(const RenderTargetEvent& evt) { /// Compile if state is dirty if(mDirty) _compile(); // Do nothing if no compositors enabled if (!mAnyCompositorsEnabled) { return; } /// Update dependent render targets; this is done in the preRenderTarget /// and not the preViewportUpdate for a reason: at this time, the /// target Rendertarget will not yet have been set as current. /// ( RenderSystem::setViewport(...) ) if it would have been, the rendering /// order would be screwed up and problems would arise with copying rendertextures. Camera *cam = mViewport->getCamera(); /// Iterate over compiled state CompositorInstance::CompiledState::iterator i; for(i=mCompiledState.begin(); i!=mCompiledState.end(); ++i) { /// Skip if this is a target that should only be initialised initially if(i->onlyInitial && i->hasBeenRendered) continue; i->hasBeenRendered = true; /// Setup and render preTargetOperation(*i, i->target->getViewport(0), cam); i->target->update(); postTargetOperation(*i, i->target->getViewport(0), cam); } } //----------------------------------------------------------------------- void CompositorChain::preViewportUpdate(const RenderTargetViewportEvent& evt) { // Only set up if there is at least one compositor enabled, and it's this viewport if(evt.source != mViewport || !mAnyCompositorsEnabled) return; // set original scene details from viewport CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0); CompositionTargetPass* passParent = pass->getParent(); if (pass->getClearBuffers() != mViewport->getClearBuffers() || pass->getClearColour() != mViewport->getBackgroundColour() || passParent->getVisibilityMask() != mViewport->getVisibilityMask() || passParent->getMaterialScheme() != mViewport->getMaterialScheme() || passParent->getShadowsEnabled() != mViewport->getShadowsEnabled()) { // recompile if viewport settings are different pass->setClearBuffers(mViewport->getClearBuffers()); pass->setClearColour(mViewport->getBackgroundColour()); passParent->setVisibilityMask(mViewport->getVisibilityMask()); passParent->setMaterialScheme(mViewport->getMaterialScheme()); passParent->setShadowsEnabled(mViewport->getShadowsEnabled()); _compile(); } Camera *cam = mViewport->getCamera(); /// Prepare for output operation preTargetOperation(mOutputOperation, mViewport, cam); } //----------------------------------------------------------------------- void CompositorChain::preTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) { SceneManager *sm = cam->getSceneManager(); /// Set up render target listener mOurListener.setOperation(&op, sm, sm->getDestinationRenderSystem()); mOurListener.notifyViewport(vp); /// Register it sm->addRenderQueueListener(&mOurListener); /// Set visiblity mask mOldVisibilityMask = sm->getVisibilityMask(); sm->setVisibilityMask(op.visibilityMask); /// Set whether we find visibles mOldFindVisibleObjects = sm->getFindVisibleObjects(); sm->setFindVisibleObjects(op.findVisibleObjects); /// Set LOD bias level mOldLodBias = cam->getLodBias(); cam->setLodBias(cam->getLodBias() * op.lodBias); /// Set material scheme mOldMaterialScheme = vp->getMaterialScheme(); vp->setMaterialScheme(op.materialScheme); /// Set shadows enabled mOldShadowsEnabled = vp->getShadowsEnabled(); vp->setShadowsEnabled(op.shadowsEnabled); /// XXX TODO //vp->setClearEveryFrame( true ); //vp->setOverlaysEnabled( false ); //vp->setBackgroundColour( op.clearColour ); } //----------------------------------------------------------------------- void CompositorChain::postTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) { SceneManager *sm = cam->getSceneManager(); /// Unregister our listener sm->removeRenderQueueListener(&mOurListener); /// Restore default scene and camera settings sm->setVisibilityMask(mOldVisibilityMask); sm->setFindVisibleObjects(mOldFindVisibleObjects); cam->setLodBias(mOldLodBias); vp->setMaterialScheme(mOldMaterialScheme); vp->setShadowsEnabled(mOldShadowsEnabled); } //----------------------------------------------------------------------- void CompositorChain::postViewportUpdate(const RenderTargetViewportEvent& evt) { // Only tidy up if there is at least one compositor enabled, and it's this viewport if(evt.source != mViewport || !mAnyCompositorsEnabled) return; postTargetOperation(mOutputOperation, mViewport, mViewport->getCamera()); } //----------------------------------------------------------------------- void CompositorChain::viewportRemoved(const RenderTargetViewportEvent& evt) { // check this is the viewport we're attached to (multi-viewport targets) if (evt.source == mViewport) { // this chain is now orphaned // can't delete it since held from outside, but release all resources being used destroyResources(); } } //----------------------------------------------------------------------- void CompositorChain::clearCompiledState() { for (RenderSystemOperations::iterator i = mRenderSystemOperations.begin(); i != mRenderSystemOperations.end(); ++i) { OGRE_DELETE *i; } mRenderSystemOperations.clear(); /// Clear compiled state mCompiledState.clear(); mOutputOperation = CompositorInstance::TargetOperation(0); } //----------------------------------------------------------------------- void CompositorChain::_compile() { clearCompiledState(); bool compositorsEnabled = false; /// Set previous CompositorInstance for each compositor in the list CompositorInstance *lastComposition = mOriginalScene; mOriginalScene->mPreviousInstance = 0; CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0); pass->setClearBuffers(mViewport->getClearBuffers()); pass->setClearColour(mViewport->getBackgroundColour()); for(Instances::iterator i=mInstances.begin(); i!=mInstances.end(); ++i) { if((*i)->getEnabled()) { compositorsEnabled = true; (*i)->mPreviousInstance = lastComposition; lastComposition = (*i); } } /// Compile misc targets lastComposition->_compileTargetOperations(mCompiledState); /// Final target viewport (0) mOutputOperation.renderSystemOperations.clear(); lastComposition->_compileOutputOperation(mOutputOperation); // Deal with viewport settings if (compositorsEnabled != mAnyCompositorsEnabled) { mAnyCompositorsEnabled = compositorsEnabled; if (mAnyCompositorsEnabled) { // Save old viewport clearing options mOldClearEveryFrameBuffers = mViewport->getClearBuffers(); // Don't clear anything every frame since we have our own clear ops mViewport->setClearEveryFrame(false); } else { // Reset clearing options mViewport->setClearEveryFrame(mOldClearEveryFrameBuffers > 0, mOldClearEveryFrameBuffers); } } mDirty = false; } //----------------------------------------------------------------------- void CompositorChain::_markDirty() { mDirty = true; } //----------------------------------------------------------------------- Viewport *CompositorChain::getViewport() { return mViewport; } //--------------------------------------------------------------------- void CompositorChain::_notifyViewport(Viewport* vp) { mViewport = vp; } //----------------------------------------------------------------------- void CompositorChain::RQListener::renderQueueStarted(uint8 id, const String& invocation, bool& skipThisQueue) { // Skip when not matching viewport // shadows update is nested within main viewport update if (mSceneManager->getCurrentViewport() != mViewport) return; flushUpTo(id); /// If noone wants to render this queue, skip it /// Don't skip the OVERLAY queue because that's handled seperately if(!mOperation->renderQueues.test(id) && id!=RENDER_QUEUE_OVERLAY) { skipThisQueue = true; } } //----------------------------------------------------------------------- void CompositorChain::RQListener::renderQueueEnded(uint8 id, const String& invocation, bool& repeatThisQueue) { } //----------------------------------------------------------------------- void CompositorChain::RQListener::setOperation(CompositorInstance::TargetOperation *op,SceneManager *sm,RenderSystem *rs) { mOperation = op; mSceneManager = sm; mRenderSystem = rs; currentOp = op->renderSystemOperations.begin(); lastOp = op->renderSystemOperations.end(); } //----------------------------------------------------------------------- void CompositorChain::RQListener::flushUpTo(uint8 id) { /// Process all RenderSystemOperations up to and including render queue id. /// Including, because the operations for RenderQueueGroup x should be executed /// at the beginning of the RenderQueueGroup render for x. while(currentOp != lastOp && currentOp->first <= id) { currentOp->second->execute(mSceneManager, mRenderSystem); ++currentOp; } } //----------------------------------------------------------------------- } <commit_msg>Patch 2690400: default material scheme when compiling compositors, so that quad materials get assigned correctly<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreCompositorChain.h" #include "OgreCompositionTechnique.h" #include "OgreCompositorInstance.h" #include "OgreCompositionTargetPass.h" #include "OgreCompositionPass.h" #include "OgreViewport.h" #include "OgreCamera.h" #include "OgreRenderTarget.h" #include "OgreLogManager.h" #include "OgreCompositorManager.h" #include "OgreSceneManager.h" #include "OgreRenderQueueInvocation.h" #include "OgreMaterialManager.h" namespace Ogre { CompositorChain::CompositorChain(Viewport *vp): mViewport(vp), mOriginalScene(0), mDirty(true), mAnyCompositorsEnabled(false) { mOldClearEveryFrameBuffers = mViewport->getClearBuffers(); assert(mViewport); } //----------------------------------------------------------------------- CompositorChain::~CompositorChain() { destroyResources(); } //----------------------------------------------------------------------- void CompositorChain::destroyResources(void) { clearCompiledState(); if (mViewport) { removeAllCompositors(); /// Destroy "original scene" compositor instance if (mOriginalScene) { mViewport->getTarget()->removeListener(this); mOriginalScene->getTechnique()->destroyInstance(mOriginalScene); mOriginalScene = 0; } mViewport = 0; } } //----------------------------------------------------------------------- CompositorInstance* CompositorChain::addCompositor(CompositorPtr filter, size_t addPosition, size_t technique) { // Init on demand if (!mOriginalScene) { mViewport->getTarget()->addListener(this); /// Create base "original scene" compositor CompositorPtr base = CompositorManager::getSingleton().load("Ogre/Scene", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); mOriginalScene = base->getSupportedTechnique(0)->createInstance(this); } filter->touch(); if(technique >= filter->getNumSupportedTechniques()) { /// Warn user LogManager::getSingleton().logMessage( "CompositorChain: Compositor " + filter->getName() + " has no supported techniques.", LML_CRITICAL ); return 0; } CompositionTechnique *tech = filter->getSupportedTechnique(technique); CompositorInstance *t = tech->createInstance(this); if(addPosition == LAST) addPosition = mInstances.size(); else assert(addPosition <= mInstances.size() && "Index out of bounds."); mInstances.insert(mInstances.begin()+addPosition, t); mDirty = true; mAnyCompositorsEnabled = true; return t; } //----------------------------------------------------------------------- void CompositorChain::removeCompositor(size_t index) { assert (index < mInstances.size() && "Index out of bounds."); Instances::iterator i = mInstances.begin() + index; (*i)->getTechnique()->destroyInstance(*i); mInstances.erase(i); mDirty = true; } //----------------------------------------------------------------------- size_t CompositorChain::getNumCompositors() { return mInstances.size(); } //----------------------------------------------------------------------- void CompositorChain::removeAllCompositors() { Instances::iterator i, iend; iend = mInstances.end(); for (i = mInstances.begin(); i != iend; ++i) { (*i)->getTechnique()->destroyInstance(*i); } mInstances.clear(); mDirty = true; } //----------------------------------------------------------------------- void CompositorChain::_removeInstance(CompositorInstance *i) { mInstances.erase(std::find(mInstances.begin(), mInstances.end(), i)); i->getTechnique()->destroyInstance(i); } //----------------------------------------------------------------------- void CompositorChain::_queuedOperation(CompositorInstance::RenderSystemOperation* op) { mRenderSystemOperations.push_back(op); } //----------------------------------------------------------------------- CompositorInstance *CompositorChain::getCompositor(size_t index) { assert (index < mInstances.size() && "Index out of bounds."); return mInstances[index]; } //----------------------------------------------------------------------- CompositorChain::InstanceIterator CompositorChain::getCompositors() { return InstanceIterator(mInstances.begin(), mInstances.end()); } //----------------------------------------------------------------------- void CompositorChain::setCompositorEnabled(size_t position, bool state) { getCompositor(position)->setEnabled(state); } //----------------------------------------------------------------------- void CompositorChain::preRenderTargetUpdate(const RenderTargetEvent& evt) { /// Compile if state is dirty if(mDirty) _compile(); // Do nothing if no compositors enabled if (!mAnyCompositorsEnabled) { return; } /// Update dependent render targets; this is done in the preRenderTarget /// and not the preViewportUpdate for a reason: at this time, the /// target Rendertarget will not yet have been set as current. /// ( RenderSystem::setViewport(...) ) if it would have been, the rendering /// order would be screwed up and problems would arise with copying rendertextures. Camera *cam = mViewport->getCamera(); /// Iterate over compiled state CompositorInstance::CompiledState::iterator i; for(i=mCompiledState.begin(); i!=mCompiledState.end(); ++i) { /// Skip if this is a target that should only be initialised initially if(i->onlyInitial && i->hasBeenRendered) continue; i->hasBeenRendered = true; /// Setup and render preTargetOperation(*i, i->target->getViewport(0), cam); i->target->update(); postTargetOperation(*i, i->target->getViewport(0), cam); } } //----------------------------------------------------------------------- void CompositorChain::preViewportUpdate(const RenderTargetViewportEvent& evt) { // Only set up if there is at least one compositor enabled, and it's this viewport if(evt.source != mViewport || !mAnyCompositorsEnabled) return; // set original scene details from viewport CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0); CompositionTargetPass* passParent = pass->getParent(); if (pass->getClearBuffers() != mViewport->getClearBuffers() || pass->getClearColour() != mViewport->getBackgroundColour() || passParent->getVisibilityMask() != mViewport->getVisibilityMask() || passParent->getMaterialScheme() != mViewport->getMaterialScheme() || passParent->getShadowsEnabled() != mViewport->getShadowsEnabled()) { // recompile if viewport settings are different pass->setClearBuffers(mViewport->getClearBuffers()); pass->setClearColour(mViewport->getBackgroundColour()); passParent->setVisibilityMask(mViewport->getVisibilityMask()); passParent->setMaterialScheme(mViewport->getMaterialScheme()); passParent->setShadowsEnabled(mViewport->getShadowsEnabled()); _compile(); } Camera *cam = mViewport->getCamera(); /// Prepare for output operation preTargetOperation(mOutputOperation, mViewport, cam); } //----------------------------------------------------------------------- void CompositorChain::preTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) { SceneManager *sm = cam->getSceneManager(); /// Set up render target listener mOurListener.setOperation(&op, sm, sm->getDestinationRenderSystem()); mOurListener.notifyViewport(vp); /// Register it sm->addRenderQueueListener(&mOurListener); /// Set visiblity mask mOldVisibilityMask = sm->getVisibilityMask(); sm->setVisibilityMask(op.visibilityMask); /// Set whether we find visibles mOldFindVisibleObjects = sm->getFindVisibleObjects(); sm->setFindVisibleObjects(op.findVisibleObjects); /// Set LOD bias level mOldLodBias = cam->getLodBias(); cam->setLodBias(cam->getLodBias() * op.lodBias); /// Set material scheme mOldMaterialScheme = vp->getMaterialScheme(); vp->setMaterialScheme(op.materialScheme); /// Set shadows enabled mOldShadowsEnabled = vp->getShadowsEnabled(); vp->setShadowsEnabled(op.shadowsEnabled); /// XXX TODO //vp->setClearEveryFrame( true ); //vp->setOverlaysEnabled( false ); //vp->setBackgroundColour( op.clearColour ); } //----------------------------------------------------------------------- void CompositorChain::postTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) { SceneManager *sm = cam->getSceneManager(); /// Unregister our listener sm->removeRenderQueueListener(&mOurListener); /// Restore default scene and camera settings sm->setVisibilityMask(mOldVisibilityMask); sm->setFindVisibleObjects(mOldFindVisibleObjects); cam->setLodBias(mOldLodBias); vp->setMaterialScheme(mOldMaterialScheme); vp->setShadowsEnabled(mOldShadowsEnabled); } //----------------------------------------------------------------------- void CompositorChain::postViewportUpdate(const RenderTargetViewportEvent& evt) { // Only tidy up if there is at least one compositor enabled, and it's this viewport if(evt.source != mViewport || !mAnyCompositorsEnabled) return; postTargetOperation(mOutputOperation, mViewport, mViewport->getCamera()); } //----------------------------------------------------------------------- void CompositorChain::viewportRemoved(const RenderTargetViewportEvent& evt) { // check this is the viewport we're attached to (multi-viewport targets) if (evt.source == mViewport) { // this chain is now orphaned // can't delete it since held from outside, but release all resources being used destroyResources(); } } //----------------------------------------------------------------------- void CompositorChain::clearCompiledState() { for (RenderSystemOperations::iterator i = mRenderSystemOperations.begin(); i != mRenderSystemOperations.end(); ++i) { OGRE_DELETE *i; } mRenderSystemOperations.clear(); /// Clear compiled state mCompiledState.clear(); mOutputOperation = CompositorInstance::TargetOperation(0); } //----------------------------------------------------------------------- void CompositorChain::_compile() { clearCompiledState(); bool compositorsEnabled = false; // force default scheme so materials for compositor quads will determined correctly MaterialManager& matMgr = MaterialManager::getSingleton(); String prevMaterialScheme = matMgr.getActiveScheme(); matMgr.setActiveScheme(MaterialManager::DEFAULT_SCHEME_NAME); /// Set previous CompositorInstance for each compositor in the list CompositorInstance *lastComposition = mOriginalScene; mOriginalScene->mPreviousInstance = 0; CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPass(0); pass->setClearBuffers(mViewport->getClearBuffers()); pass->setClearColour(mViewport->getBackgroundColour()); for(Instances::iterator i=mInstances.begin(); i!=mInstances.end(); ++i) { if((*i)->getEnabled()) { compositorsEnabled = true; (*i)->mPreviousInstance = lastComposition; lastComposition = (*i); } } /// Compile misc targets lastComposition->_compileTargetOperations(mCompiledState); /// Final target viewport (0) mOutputOperation.renderSystemOperations.clear(); lastComposition->_compileOutputOperation(mOutputOperation); // Deal with viewport settings if (compositorsEnabled != mAnyCompositorsEnabled) { mAnyCompositorsEnabled = compositorsEnabled; if (mAnyCompositorsEnabled) { // Save old viewport clearing options mOldClearEveryFrameBuffers = mViewport->getClearBuffers(); // Don't clear anything every frame since we have our own clear ops mViewport->setClearEveryFrame(false); } else { // Reset clearing options mViewport->setClearEveryFrame(mOldClearEveryFrameBuffers > 0, mOldClearEveryFrameBuffers); } } // restore material scheme matMgr.setActiveScheme(prevMaterialScheme); mDirty = false; } //----------------------------------------------------------------------- void CompositorChain::_markDirty() { mDirty = true; } //----------------------------------------------------------------------- Viewport *CompositorChain::getViewport() { return mViewport; } //--------------------------------------------------------------------- void CompositorChain::_notifyViewport(Viewport* vp) { mViewport = vp; } //----------------------------------------------------------------------- void CompositorChain::RQListener::renderQueueStarted(uint8 id, const String& invocation, bool& skipThisQueue) { // Skip when not matching viewport // shadows update is nested within main viewport update if (mSceneManager->getCurrentViewport() != mViewport) return; flushUpTo(id); /// If noone wants to render this queue, skip it /// Don't skip the OVERLAY queue because that's handled seperately if(!mOperation->renderQueues.test(id) && id!=RENDER_QUEUE_OVERLAY) { skipThisQueue = true; } } //----------------------------------------------------------------------- void CompositorChain::RQListener::renderQueueEnded(uint8 id, const String& invocation, bool& repeatThisQueue) { } //----------------------------------------------------------------------- void CompositorChain::RQListener::setOperation(CompositorInstance::TargetOperation *op,SceneManager *sm,RenderSystem *rs) { mOperation = op; mSceneManager = sm; mRenderSystem = rs; currentOp = op->renderSystemOperations.begin(); lastOp = op->renderSystemOperations.end(); } //----------------------------------------------------------------------- void CompositorChain::RQListener::flushUpTo(uint8 id) { /// Process all RenderSystemOperations up to and including render queue id. /// Including, because the operations for RenderQueueGroup x should be executed /// at the beginning of the RenderQueueGroup render for x. while(currentOp != lastOp && currentOp->first <= id) { currentOp->second->execute(mSceneManager, mRenderSystem); ++currentOp; } } //----------------------------------------------------------------------- } <|endoftext|>
<commit_before>#include <vector> #include "toml.h" #include <random> #include <iostream> #include <cmath> #include "xoroshiro128plus.h" #include "statistics.h" #include "properties.h" inline void metropolis_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& delta_dist, std::uniform_real_distribution<double>& real_dist, double beta){ int L = lattice.size(); int i_plus, j_plus, i_minus, j_minus; int n0, n1, n2, n3; double sigma_old, sigma_new; double delta_E, p_accept; N_ATTEMPTED_FLIPS += L*L; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ delta_E = 0.0; i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; //neighboring angles n0 = lattice[i_plus][j]; n1 = lattice[i_minus][j]; n2 = lattice[i][j_plus]; n3 = lattice[i][j_minus]; //delta_E = E(sigma_new) - E(sigma) sigma_old = lattice[i][j]; sigma_new = sigma_old - delta_dist(gen); //E(sigma_new) delta_E += (-cos(sigma_new - n0)); delta_E += (-cos(sigma_new - n1)); delta_E += (-cos(sigma_new - n2)); delta_E += (-cos(sigma_new - n3)); //-E(sigma_old) delta_E -= (-cos(sigma_old - n0)); delta_E -= (-cos(sigma_old - n1)); delta_E -= (-cos(sigma_old - n2)); delta_E -= (-cos(sigma_old - n3)); if (delta_E <= 0){ //good change lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; }else{ p_accept = exp(-beta*delta_E); if (p_accept > real_dist(gen)){ lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; } } } } }; inline void microcanonical_sweep(std::vector<std::vector<double> >& lattice){ }; inline void cluster_sweep(){}; /////////////////////// //Standard metropolis// /////////////////////// void metropolis(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, double delta){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2*M_PI); std::uniform_real_distribution<double> delta_dist(-delta/2.0, delta/2.0); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize std::cout << lattice[0][0] << std::endl; for (int n=0; n<n_steps_therm; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); std::cout << lattice[0][0] << std::endl; } //production run for (int n=0; n<n_steps_prod; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); if (n%outfreq == 0){ } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } } }; <commit_msg>fixed error<commit_after>#include <vector> #include "toml.h" #include <random> #include <iostream> #include <cmath> #include "xoroshiro128plus.h" #include "statistics.h" #include "properties.h" inline void metropolis_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& delta_dist, std::uniform_real_distribution<double>& real_dist, double beta){ int L = lattice.size(); int i_plus, j_plus, i_minus, j_minus; std::vector<double> nb_angles = {0.0, 0.0, 0.0, 0.0}; double sigma_old, sigma_new; double delta_E, p_accept; N_ATTEMPTED_FLIPS += L*L; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ delta_E = 0.0; i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; //neighboring angles nb_angles[0] = lattice[i_plus][j]; nb_angles[1] = lattice[i_minus][j]; nb_angles[2] = lattice[i][j_plus]; nb_angles[3] = lattice[i][j_minus]; //delta_E = E(sigma_new) - E(sigma) sigma_old = lattice[i][j]; sigma_new = sigma_old - delta_dist(gen); for (int nb=0; nb<4; nb++){ delta_E += cos(sigma_old - nb_angles[nb]) - cos(sigma_new - nb_angles[nb]); } if (delta_E <= 0){ //good change lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; }else{ p_accept = exp(-beta*delta_E); if (p_accept > real_dist(gen)){ lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; } } } } }; inline void microcanonical_sweep(std::vector<std::vector<double> >& lattice){ int L = lattice.size(); int i_plus, j_plus, i_minus, j_minus; int n0, n1, n2, n3; std::vector<double> Vx; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; //neighboring angles } } }; inline void cluster_sweep(){}; /////////////////////// //Standard metropolis// /////////////////////// void metropolis(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, double delta){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2*M_PI); std::uniform_real_distribution<double> delta_dist(-delta/2.0, delta/2.0); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize std::cout << lattice[0][0] << std::endl; for (int n=0; n<n_steps_therm; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); std::cout << lattice[0][0] << std::endl; } //production run for (int n=0; n<n_steps_prod; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); if (n%outfreq == 0){ } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } } }; <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Rene Brun 18/05/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFileCacheRead : a cache when reading files over the network // // // // A caching system to speed up network I/O, i.e. when there is // // no operating system caching support (like the buffer cache for // // local disk I/O). The cache makes sure that every I/O is done with // // a (large) fixed length buffer thereby avoiding many small I/O's. // // Currently the read cache system is used by the classes TNetFile, // // TXNetFile and TWebFile (via TFile::ReadBuffers()). // // // // When processing TTree, TChain, a specialized class TTreeCache that // // derives from this class is automatically created. // // // ////////////////////////////////////////////////////////////////////////// #include "TEnv.h" #include "TFile.h" #include "TFileCacheRead.h" #include "TFileCacheWrite.h" #include "TMath.h" #include "TXNetFile.h" ClassImp(TFileCacheRead) //______________________________________________________________________________ TFileCacheRead::TFileCacheRead() : TObject() { // Default Constructor. fBufferSizeMin = 0; fBufferSize = 0; fBufferLen = 0; fNseek = 0; fNtot = 0; fNb = 0; fSeekSize = 0; fSeek = 0; fSeekIndex = 0; fSeekSort = 0; fPos = 0; fSeekLen = 0; fSeekSortLen = 0; fSeekPos = 0; fLen = 0; fFile = 0; fBuffer = 0; fIsSorted = kFALSE; fIsTransferred = kFALSE; fAsyncReading = kFALSE; } //_____________________________________________________________________________ TFileCacheRead::TFileCacheRead(TFile *file, Int_t buffersize) : TObject() { // Creates a TFileCacheRead data structure. if (buffersize <=10000) fBufferSize = 100000; else fBufferSize = buffersize; fBufferSizeMin = fBufferSize; fBufferLen = 0; fNseek = 0; fNtot = 0; fNb = 0; fSeekSize = 10000; fSeek = new Long64_t[fSeekSize]; fSeekIndex = new Int_t[fSeekSize]; fSeekSort = new Long64_t[fSeekSize]; fPos = new Long64_t[fSeekSize]; fSeekLen = new Int_t[fSeekSize]; fSeekSortLen = new Int_t[fSeekSize]; fSeekPos = new Int_t[fSeekSize]; fLen = new Int_t[fSeekSize]; fFile = file; fBuffer = 0; fAsyncReading = gEnv->GetValue("TFile.AsyncReading", 1); if (fAsyncReading) { // Check if asynchronous reading is supported by this TFile specialization fAsyncReading = kFALSE; if (file && !(file->ReadBufferAsync(0, 0))) fAsyncReading = kTRUE; } if (!fAsyncReading) { // we use sync primitives, hence we need the local buffer fBuffer = new char[fBufferSize]; } fIsSorted = kFALSE; fIsTransferred = kFALSE; if (file) file->SetCacheRead(this); } //_____________________________________________________________________________ TFileCacheRead::~TFileCacheRead() { // Destructor. delete [] fSeek; delete [] fSeekIndex; delete [] fSeekSort; delete [] fPos; delete [] fSeekLen; delete [] fSeekSortLen; delete [] fSeekPos; delete [] fLen; delete [] fBuffer; } //_____________________________________________________________________________ void TFileCacheRead::Prefetch(Long64_t pos, Int_t len) { // Add block of length len at position pos in the list of blocks to // be prefetched. If pos <= 0 the current blocks (if any) are reset. fIsSorted = kFALSE; fIsTransferred = kFALSE; if (pos <= 0) { fNseek = 0; fNtot = 0; return; } if (fNseek >= fSeekSize) { //reallocate buffers fSeekSize *= 2; Long64_t *aSeek = new Long64_t[fSeekSize]; Int_t *aSeekIndex = new Int_t[fSeekSize]; Long64_t *aSeekSort = new Long64_t[fSeekSize]; Long64_t *aPos = new Long64_t[fSeekSize]; Int_t *aSeekLen = new Int_t[fSeekSize]; Int_t *aSeekSortLen = new Int_t[fSeekSize]; Int_t *aSeekPos = new Int_t[fSeekSize]; Int_t *aLen = new Int_t[fSeekSize]; for (Int_t i=0;i<fNseek;i++) { aSeek[i] = fSeek[i]; aSeekIndex[i] = fSeekIndex[i]; aSeekSort[i] = fSeekSort[i]; aPos[i] = fPos[i]; aSeekLen[i] = fSeekLen[i]; aSeekSortLen[i] = fSeekSortLen[i]; aSeekPos[i] = fSeekPos[i]; aLen[i] = fLen[i]; } delete [] fSeek; delete [] fSeekIndex; delete [] fSeekSort; delete [] fPos; delete [] fSeekLen; delete [] fSeekSortLen; delete [] fSeekPos; delete [] fLen; fSeek = aSeek; fSeekIndex = aSeekIndex; fSeekSort = aSeekSort; fPos = aPos; fSeekLen = aSeekLen; fSeekSortLen = aSeekSortLen; fSeekPos = aSeekPos; fLen = aLen; } fSeek[fNseek] = pos; fSeekLen[fNseek] = len; fNseek++; fNtot += len; } //_____________________________________________________________________________ void TFileCacheRead::Print(Option_t *option) const { // Print class internal structure. TString opt = option; opt.ToLower(); printf("Number of blocks: %d, total size : %d\n",fNseek,fNtot); if (!opt.Contains("a")) return; for (Int_t i=0;i<fNseek;i++) { if (fIsSorted && !opt.Contains("s")) { printf("block: %5d, from: %lld to %lld, len=%d bytes\n",i,fSeekSort[i],fSeekSort[i]+fSeekSortLen[i],fSeekSortLen[i]); } else { printf("block: %5d, from: %lld to %lld, len=%d bytes\n",i,fSeek[i],fSeek[i]+fSeekLen[i],fSeekLen[i]); } } printf ("Number of long buffers = %d\n",fNb); for (Int_t j=0;j<fNb;j++) { printf("fPos[%d]=%lld, fLen=%d\n",j,fPos[j],fLen[j]); } } //_____________________________________________________________________________ Int_t TFileCacheRead::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer, // otherwise need to make a normal read from file. Returns -1 in case of // read error, 0 in case not in cache, 1 in case read from cache. Int_t loc = 0; return ReadBufferExt(buf, pos, len, loc); } //_____________________________________________________________________________ Int_t TFileCacheRead::ReadBufferExt(char *buf, Long64_t pos, Int_t len, Int_t &loc) { // Base function for ReadBuffer. Also gives out the position // of the block in the internal buffer. This helps TTreeCacheUnzip to avoid // doing twice the binary search if (fNseek > 0 && !fIsSorted) { Sort(); // If ReadBufferAsync is not supported by this implementation... if (!fAsyncReading) { // Then we use the vectored read to read everything now if (fFile->ReadBuffers(fBuffer,fPos,fLen,fNb)) { return -1; } fIsTransferred = kTRUE; } else { // In any case, we'll start to request the chunks. // This implementation simply reads all the chunks in advance // in the async way. // Use the async readv instead of single reads fFile->ReadBuffers(0, 0, 0, 0); //Clear the XrdClient cache if (fFile->ReadBuffers(0,fPos,fLen,fNb)) { return -1; } fIsTransferred = kTRUE; } } // in case we are writing and reading to/from this file, we much check // if this buffer is in the write cache (not yet written to the file) if (TFileCacheWrite *cachew = fFile->GetCacheWrite()) { if (cachew->ReadBuffer(buf,pos,len) == 0) { fFile->Seek(pos+len); return 1; } } // If asynchronous reading is supported by this implementation... if (fAsyncReading) { Int_t retval; loc = (Int_t)TMath::BinarySearch(fNseek,fSeekSort,pos); // Now we dont have to look for it in the local buffer // if it's async, we expect that the communication library // will handle it more efficiently than we can do here // We use the internal list just to notify if the list is to be reconstructed if (loc >= 0 && loc < fNseek && pos == fSeekSort[loc]) { // Block found, the caller will get it if (buf) { fFile->Seek(pos); if (fFile->ReadBuffer(buf, len)) { return -1; } fFile->Seek(pos+len); } retval = 1; } else { // Block not found in the list, we report it as a miss retval = 0; } if (gDebug > 0) Info("ReadBuffer","pos=%lld, len=%d, retval=%d", pos, len, retval); return retval; } else { loc = (Int_t)TMath::BinarySearch(fNseek,fSeekSort,pos); if (loc >= 0 && loc <fNseek && pos == fSeekSort[loc]) { if (buf) { memcpy(buf,&fBuffer[fSeekPos[loc]],len); fFile->Seek(pos+len); } return 1; } } return 0; } //_____________________________________________________________________________ void TFileCacheRead::SetFile(TFile *file) { // Set the file using this cache and reset the current blocks (if any). fFile = file; if (fAsyncReading) { // If asynchronous reading is not supported by this TFile specialization // we use sync primitives, hence we need the local buffer if (file && file->ReadBufferAsync(0, 0)) { fAsyncReading = kFALSE; fBuffer = new char[fBufferSize]; } } Prefetch(0,0); } //_____________________________________________________________________________ void TFileCacheRead::Sort() { // Sort buffers to be prefetched in increasing order of positions. // Merge consecutive blocks if necessary. if (!fNseek) return; TMath::Sort(fNseek,fSeek,fSeekIndex,kFALSE); Int_t i; Int_t nb = 0; for (i=0;i<fNseek;i++) { Int_t ind = fSeekIndex[i]; fSeekSort[i] = fSeek[ind]; fSeekSortLen[i] = fSeekLen[ind]; } if (fNtot > fBufferSizeMin) { fBufferSize = fNtot + 100; delete [] fBuffer; fBuffer = 0; // If ReadBufferAsync is not supported by this implementation // it means that we are using sync primitives, hence we need the local buffer if (!fAsyncReading) fBuffer = new char[fBufferSize]; } fPos[0] = fSeekSort[0]; fLen[0] = fSeekSortLen[0]; fSeekPos[0] = 0; for (i=1;i<fNseek;i++) { fSeekPos[i] = fSeekPos[i-1] + fSeekSortLen[i-1]; if ((fSeekSort[i] != fSeekSort[i-1]+fSeekSortLen[i-1]) || (fLen[nb] > 2000000)) { nb++; fPos[nb] = fSeekSort[i]; fLen[nb] = fSeekSortLen[i]; } else { fLen[nb] += fSeekSortLen[i]; } } fNb = nb+1; fIsSorted = kTRUE; } <commit_msg>correct coding style.<commit_after>// @(#)root/io:$Id$ // Author: Rene Brun 18/05/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFileCacheRead : a cache when reading files over the network // // // // A caching system to speed up network I/O, i.e. when there is // // no operating system caching support (like the buffer cache for // // local disk I/O). The cache makes sure that every I/O is done with // // a (large) fixed length buffer thereby avoiding many small I/O's. // // Currently the read cache system is used by the classes TNetFile, // // TXNetFile and TWebFile (via TFile::ReadBuffers()). // // // // When processing TTree, TChain, a specialized class TTreeCache that // // derives from this class is automatically created. // // // ////////////////////////////////////////////////////////////////////////// #include "TEnv.h" #include "TFile.h" #include "TFileCacheRead.h" #include "TFileCacheWrite.h" #include "TMath.h" #include "TXNetFile.h" ClassImp(TFileCacheRead) //______________________________________________________________________________ TFileCacheRead::TFileCacheRead() : TObject() { // Default Constructor. fBufferSizeMin = 0; fBufferSize = 0; fBufferLen = 0; fNseek = 0; fNtot = 0; fNb = 0; fSeekSize = 0; fSeek = 0; fSeekIndex = 0; fSeekSort = 0; fPos = 0; fSeekLen = 0; fSeekSortLen = 0; fSeekPos = 0; fLen = 0; fFile = 0; fBuffer = 0; fIsSorted = kFALSE; fIsTransferred = kFALSE; fAsyncReading = kFALSE; } //_____________________________________________________________________________ TFileCacheRead::TFileCacheRead(TFile *file, Int_t buffersize) : TObject() { // Creates a TFileCacheRead data structure. if (buffersize <=10000) fBufferSize = 100000; else fBufferSize = buffersize; fBufferSizeMin = fBufferSize; fBufferLen = 0; fNseek = 0; fNtot = 0; fNb = 0; fSeekSize = 10000; fSeek = new Long64_t[fSeekSize]; fSeekIndex = new Int_t[fSeekSize]; fSeekSort = new Long64_t[fSeekSize]; fPos = new Long64_t[fSeekSize]; fSeekLen = new Int_t[fSeekSize]; fSeekSortLen = new Int_t[fSeekSize]; fSeekPos = new Int_t[fSeekSize]; fLen = new Int_t[fSeekSize]; fFile = file; fBuffer = 0; fAsyncReading = gEnv->GetValue("TFile.AsyncReading", 1); if (fAsyncReading) { // Check if asynchronous reading is supported by this TFile specialization fAsyncReading = kFALSE; if (file && !(file->ReadBufferAsync(0, 0))) fAsyncReading = kTRUE; } if (!fAsyncReading) { // we use sync primitives, hence we need the local buffer fBuffer = new char[fBufferSize]; } fIsSorted = kFALSE; fIsTransferred = kFALSE; if (file) file->SetCacheRead(this); } //_____________________________________________________________________________ TFileCacheRead::~TFileCacheRead() { // Destructor. delete [] fSeek; delete [] fSeekIndex; delete [] fSeekSort; delete [] fPos; delete [] fSeekLen; delete [] fSeekSortLen; delete [] fSeekPos; delete [] fLen; delete [] fBuffer; } //_____________________________________________________________________________ void TFileCacheRead::Prefetch(Long64_t pos, Int_t len) { // Add block of length len at position pos in the list of blocks to // be prefetched. If pos <= 0 the current blocks (if any) are reset. fIsSorted = kFALSE; fIsTransferred = kFALSE; if (pos <= 0) { fNseek = 0; fNtot = 0; return; } if (fNseek >= fSeekSize) { //reallocate buffers fSeekSize *= 2; Long64_t *aSeek = new Long64_t[fSeekSize]; Int_t *aSeekIndex = new Int_t[fSeekSize]; Long64_t *aSeekSort = new Long64_t[fSeekSize]; Long64_t *aPos = new Long64_t[fSeekSize]; Int_t *aSeekLen = new Int_t[fSeekSize]; Int_t *aSeekSortLen = new Int_t[fSeekSize]; Int_t *aSeekPos = new Int_t[fSeekSize]; Int_t *aLen = new Int_t[fSeekSize]; for (Int_t i=0;i<fNseek;i++) { aSeek[i] = fSeek[i]; aSeekIndex[i] = fSeekIndex[i]; aSeekSort[i] = fSeekSort[i]; aPos[i] = fPos[i]; aSeekLen[i] = fSeekLen[i]; aSeekSortLen[i] = fSeekSortLen[i]; aSeekPos[i] = fSeekPos[i]; aLen[i] = fLen[i]; } delete [] fSeek; delete [] fSeekIndex; delete [] fSeekSort; delete [] fPos; delete [] fSeekLen; delete [] fSeekSortLen; delete [] fSeekPos; delete [] fLen; fSeek = aSeek; fSeekIndex = aSeekIndex; fSeekSort = aSeekSort; fPos = aPos; fSeekLen = aSeekLen; fSeekSortLen = aSeekSortLen; fSeekPos = aSeekPos; fLen = aLen; } fSeek[fNseek] = pos; fSeekLen[fNseek] = len; fNseek++; fNtot += len; } //_____________________________________________________________________________ void TFileCacheRead::Print(Option_t *option) const { // Print class internal structure. TString opt = option; opt.ToLower(); printf("Number of blocks: %d, total size : %d\n",fNseek,fNtot); if (!opt.Contains("a")) return; for (Int_t i=0;i<fNseek;i++) { if (fIsSorted && !opt.Contains("s")) { printf("block: %5d, from: %lld to %lld, len=%d bytes\n",i,fSeekSort[i],fSeekSort[i]+fSeekSortLen[i],fSeekSortLen[i]); } else { printf("block: %5d, from: %lld to %lld, len=%d bytes\n",i,fSeek[i],fSeek[i]+fSeekLen[i],fSeekLen[i]); } } printf ("Number of long buffers = %d\n",fNb); for (Int_t j=0;j<fNb;j++) { printf("fPos[%d]=%lld, fLen=%d\n",j,fPos[j],fLen[j]); } } //_____________________________________________________________________________ Int_t TFileCacheRead::ReadBuffer(char *buf, Long64_t pos, Int_t len) { // Read buffer at position pos. // If pos is in the list of prefetched blocks read from fBuffer, // otherwise need to make a normal read from file. Returns -1 in case of // read error, 0 in case not in cache, 1 in case read from cache. Int_t loc = 0; return ReadBufferExt(buf, pos, len, loc); } //_____________________________________________________________________________ Int_t TFileCacheRead::ReadBufferExt(char *buf, Long64_t pos, Int_t len, Int_t &loc) { // Base function for ReadBuffer. Also gives out the position // of the block in the internal buffer. This helps TTreeCacheUnzip to avoid // doing twice the binary search if (fNseek > 0 && !fIsSorted) { Sort(); // If ReadBufferAsync is not supported by this implementation... if (!fAsyncReading) { // Then we use the vectored read to read everything now if (fFile->ReadBuffers(fBuffer,fPos,fLen,fNb)) { return -1; } fIsTransferred = kTRUE; } else { // In any case, we'll start to request the chunks. // This implementation simply reads all the chunks in advance // in the async way. // Use the async readv instead of single reads fFile->ReadBuffers(0, 0, 0, 0); //Clear the XrdClient cache if (fFile->ReadBuffers(0,fPos,fLen,fNb)) { return -1; } fIsTransferred = kTRUE; } } // in case we are writing and reading to/from this file, we much check // if this buffer is in the write cache (not yet written to the file) if (TFileCacheWrite *cachew = fFile->GetCacheWrite()) { if (cachew->ReadBuffer(buf,pos,len) == 0) { fFile->Seek(pos+len); return 1; } } // If asynchronous reading is supported by this implementation... if (fAsyncReading) { Int_t retval; loc = (Int_t)TMath::BinarySearch(fNseek,fSeekSort,pos); // Now we dont have to look for it in the local buffer // if it's async, we expect that the communication library // will handle it more efficiently than we can do here // We use the internal list just to notify if the list is to be reconstructed if (loc >= 0 && loc < fNseek && pos == fSeekSort[loc]) { // Block found, the caller will get it if (buf) { fFile->Seek(pos); if (fFile->ReadBuffer(buf, len)) { return -1; } fFile->Seek(pos+len); } retval = 1; } else { // Block not found in the list, we report it as a miss retval = 0; } if (gDebug > 0) Info("ReadBuffer","pos=%lld, len=%d, retval=%d", pos, len, retval); return retval; } else { loc = (Int_t)TMath::BinarySearch(fNseek,fSeekSort,pos); if (loc >= 0 && loc <fNseek && pos == fSeekSort[loc]) { if (buf) { memcpy(buf,&fBuffer[fSeekPos[loc]],len); fFile->Seek(pos+len); } return 1; } } return 0; } //_____________________________________________________________________________ void TFileCacheRead::SetFile(TFile *file) { // Set the file using this cache and reset the current blocks (if any). fFile = file; if (fAsyncReading) { // If asynchronous reading is not supported by this TFile specialization // we use sync primitives, hence we need the local buffer if (file && file->ReadBufferAsync(0, 0)) { fAsyncReading = kFALSE; fBuffer = new char[fBufferSize]; } } Prefetch(0,0); } //_____________________________________________________________________________ void TFileCacheRead::Sort() { // Sort buffers to be prefetched in increasing order of positions. // Merge consecutive blocks if necessary. if (!fNseek) return; TMath::Sort(fNseek,fSeek,fSeekIndex,kFALSE); Int_t i; Int_t nb = 0; for (i=0;i<fNseek;i++) { Int_t ind = fSeekIndex[i]; fSeekSort[i] = fSeek[ind]; fSeekSortLen[i] = fSeekLen[ind]; } if (fNtot > fBufferSizeMin) { fBufferSize = fNtot + 100; delete [] fBuffer; fBuffer = 0; // If ReadBufferAsync is not supported by this implementation // it means that we are using sync primitives, hence we need the local buffer if (!fAsyncReading) fBuffer = new char[fBufferSize]; } fPos[0] = fSeekSort[0]; fLen[0] = fSeekSortLen[0]; fSeekPos[0] = 0; for (i=1;i<fNseek;i++) { fSeekPos[i] = fSeekPos[i-1] + fSeekSortLen[i-1]; if ((fSeekSort[i] != fSeekSort[i-1]+fSeekSortLen[i-1]) || (fLen[nb] > 2000000)) { nb++; fPos[nb] = fSeekSort[i]; fLen[nb] = fSeekSortLen[i]; } else { fLen[nb] += fSeekSortLen[i]; } } fNb = nb+1; fIsSorted = kTRUE; } <|endoftext|>
<commit_before>#include "Hotkeys.h" #include "Actions.h" std::map<const std::string, unsigned int> hotkeysMap = std::map<const std::string, unsigned int>(); std::map<const unsigned int, Hotkey*> hotkey = std::map<const unsigned int, Hotkey*>(); void InitHotkeysMap() { hotkeysMap["space"] = VK_SPACE; hotkeysMap[","] = VK_OEM_COMMA; hotkeysMap["."] = VK_OEM_PERIOD; } Hotkey::Hotkey(const std::string action_name, const std::string key_name, const std::string alt_str, const std::string control_str, const std::string shift_str, const std::string win_str) { key = GetKeyCode(key_name); alt = IsKeyUsed(alt_str); control = IsKeyUsed(control_str); shift = IsKeyUsed(shift_str); win = IsKeyUsed(win_str); /*id = key + (alt ? 1000 * MOD_ALT : 0) + (control ? 10000 * MOD_CONTROL : 0) + (shift ? 100000 * MOD_SHIFT : 0) + (win ? 1000000 * MOD_WIN : 0);*/ Action = GetAction(action_name); } Hotkey::~Hotkey() { /* nothing to do */ } void (*Hotkey::GetAction(const std::string action_name))(void) { switch (actionsMap[action_name]) { case eActionPlayPause: return &PlayPause; case eActionPreviousTrack: return &PreviousTrack; case eActionNextTrack: return &NextTrack; default: return 0; } } unsigned int Hotkey::GetKeyCode(const std::string key_name) { return hotkeysMap[key_name]; } bool Hotkey::IsKeyUsed(const std::string key_str) { return (key_str == std::string("true")); } void Hotkey::PerformAction() { if(Action > 0) Action(); }<commit_msg>Added more hotkeys<commit_after>#include "Hotkeys.h" #include "Actions.h" std::map<const std::string, unsigned int> hotkeysMap = std::map<const std::string, unsigned int>(); std::map<const unsigned int, Hotkey*> hotkey = std::map<const unsigned int, Hotkey*>(); void InitHotkeysMap() { char str[4]; for (int i = 0; i < 4; i++) str[i] = '\0'; // add 0-9 for (unsigned int i = 0x30; i < 0x3A; i++) { str[0] = i; hotkeysMap[std::string(str)] = i; } // add A-Z for (unsigned int i = 0x41; i < 0x5A; i++) { str[0] = i; hotkeysMap[std::string(str)] = i; } // add a-z unsigned int j = 0x61; for (unsigned int i = 0x41; i < 0x5A; i++) { str[0] = j++; hotkeysMap[std::string(str)] = i; } str[0] = 'F'; j = 0x31; // add F1-F9 for (unsigned int i = 0x70; i < 0x79; i++) { str[1] = j++; hotkeysMap[std::string(str)] = i; } str[1] = '1'; j = 0x30; // add F10-F19 for (unsigned int i = 0x79; i < 0x83; i++) { str[2] = j++; hotkeysMap[std::string(str)] = i; } str[1] = '2'; j = 0x30; // add F20-F24 for (unsigned int i = 0x83; i < 0x88; i++) { str[2] = j++; hotkeysMap[std::string(str)] = i; } hotkeysMap["Spacebar"] = VK_SPACE; hotkeysMap["Backspace"] = VK_BACK; hotkeysMap["Tab"] = VK_TAB; hotkeysMap["Escape"] = VK_ESCAPE; hotkeysMap["PageUp"] = VK_PRIOR; hotkeysMap["PageDown"] = VK_NEXT; hotkeysMap["End"] = VK_END; hotkeysMap["Home"] = VK_HOME; hotkeysMap["Left"] = VK_LEFT; hotkeysMap["Up"] = VK_UP; hotkeysMap["Right"] = VK_RIGHT; hotkeysMap["Down"] = VK_DOWN; hotkeysMap["Insert"] = VK_INSERT; hotkeysMap["Delete"] = VK_DELETE; hotkeysMap["PrintScreen"] = VK_SNAPSHOT; hotkeysMap["Pause"] = VK_PAUSE; hotkeysMap["NumLock"] = VK_NUMLOCK; hotkeysMap["-"] = VK_SUBTRACT; hotkeysMap["="] = VK_ADD; hotkeysMap["/"] = VK_DIVIDE; hotkeysMap[","] = VK_OEM_COMMA; hotkeysMap["."] = VK_OEM_PERIOD; } Hotkey::Hotkey(const std::string action_name, const std::string key_name, const std::string alt_str, const std::string control_str, const std::string shift_str, const std::string win_str) { key = GetKeyCode(key_name); alt = IsKeyUsed(alt_str); control = IsKeyUsed(control_str); shift = IsKeyUsed(shift_str); win = IsKeyUsed(win_str); /*id = key + (alt ? 1000 * MOD_ALT : 0) + (control ? 10000 * MOD_CONTROL : 0) + (shift ? 100000 * MOD_SHIFT : 0) + (win ? 1000000 * MOD_WIN : 0);*/ Action = GetAction(action_name); } Hotkey::~Hotkey() { /* nothing to do */ } void (*Hotkey::GetAction(const std::string action_name))(void) { switch (actionsMap[action_name]) { case eActionPlayPause: return &PlayPause; case eActionPreviousTrack: return &PreviousTrack; case eActionNextTrack: return &NextTrack; default: return 0; } } unsigned int Hotkey::GetKeyCode(const std::string key_name) { return hotkeysMap[key_name]; } bool Hotkey::IsKeyUsed(const std::string key_str) { return (key_str == std::string("true")); } void Hotkey::PerformAction() { if(Action > 0) Action(); }<|endoftext|>
<commit_before>/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file JPetTaskIO.cpp */ #include "./JPetOptionsGenerator/JPetOptionsGeneratorTools.h" #include "./JPetCommonTools/JPetCommonTools.h" #include "./JPetTreeHeader/JPetTreeHeader.h" #include "./JPetUserTask/JPetUserTask.h" #include "./JPetTask/JPetTask.h" #include "./JPetData/JPetData.h" #include "./JPetLoggerInclude.h" #include "JPetTaskIOTools.h" #include "JPetTaskIO.h" #include "./version.h" #include <cassert> #include <memory> JPetTaskIO::JPetTaskIO(const char* name, const char* in_file_type, const char* out_file_type): JPetTask(name), fTaskInfo(in_file_type, out_file_type, "", false) { if (std::string(out_file_type).empty()) { fIsOutput = false; } if (std::string(in_file_type).empty()) { fIsInput = false; } } JPetTaskIO::~JPetTaskIO() {} bool JPetTaskIO::init(const JPetParams& params) { using namespace jpet_options_tools; setParams(params); auto opts = fParams.getOptions(); bool isOK = false; std::string inputFilename; std::string outFileFullPath; bool resetOutputPath = false; std::tie(isOK, inputFilename, outFileFullPath, resetOutputPath) = setInputAndOutputFile(opts); fTaskInfo.fOutFileFullPath = outFileFullPath; fTaskInfo.fResetOutputPath = resetOutputPath; auto subTaskName = getFirstSubTaskName(); if (!isOK) { ERROR("Some error occured in setInputAndOutputFile, subtask name:" + subTaskName); return false; } if (isInput()) { if (!createInputObjects(inputFilename.c_str())) { ERROR("createInputObjects with the input file:" + inputFilename); ERROR("Subtask name:" + subTaskName); return false; } } if (isOutput()) { if (!createOutputObjects(outFileFullPath.c_str())) { ERROR("createOutputObjects with the output file:" + outFileFullPath); ERROR("Subtask name:" + subTaskName); return false; } } return true; } bool JPetTaskIO::run(const JPetDataInterface&) { using namespace jpet_options_tools; if (fSubTasks.empty()) { ERROR("No subTask set"); return false; } if (isInput()) { if (!fInputHandler) { ERROR("No inputHandler set"); return false; } } for (const auto& pTask : fSubTasks) { auto subTaskName = pTask->getName(); auto ok = pTask->init(fParams); if (!ok) { WARNING("In init() of:" + subTaskName + ". run() and terminate() of this task will be skipped."); continue; } if (isInput()) { assert(fInputHandler); bool isOK = fInputHandler->setEntryRange(fParams.getOptions()); if (!isOK) { ERROR("Some error occured in setEntryRange"); return false; } auto lastEvent = fInputHandler->getLastEntryNumber(); assert(lastEvent >= 0); do { if (isProgressBar(fParams.getOptions())) { displayProgressBar(subTaskName, fInputHandler->getCurrentEntryNumber(), lastEvent); } JPetData event(fInputHandler->getEntry()); ok = pTask->run(event); if (!ok) { ERROR("In run() of:" + subTaskName + ". "); } if (isOutput()) { if (!fOutputHandler->writeEventToFile(pTask.get())) { ERROR("Some problems occured, while writing the event to file."); return false; } } } while (fInputHandler->nextEntry()); } else { JPetDataInterface dummyEvent; pTask->run(dummyEvent); } JPetParams subTaskParams; ok = pTask->terminate(subTaskParams); if (!ok) { ERROR("In terminate() of:" + subTaskName + ". "); return false; } fParams = mergeWithExtraParams(fParams, subTaskParams); } return true; } bool JPetTaskIO::terminate(JPetParams& output_params) { auto subTaskName = getFirstSubTaskName(); if (isOutput()) { auto newOpts = JPetTaskIOTools::setOutputOptions(fParams, fTaskInfo.fResetOutputPath, fTaskInfo.fOutFileFullPath); output_params = JPetParams(newOpts, fParams.getParamManagerAsShared()); } else { output_params = fParams; } if (isOutput()) { if (!fHeader) { ERROR("Tree header is not set,"); ERROR("Subtask name:" + subTaskName); return false; } if (!fStatistics.get()) { ERROR("Statistics container with histograms is not set."); ERROR("Subtask name:" + subTaskName); return false; } fOutputHandler->saveAndCloseOutput(getParamManager(), fHeader, fStatistics.get(), fSubTasksStatistics); } if (isInput()) { if (!fInputHandler) { ERROR("fInputHandler set to null."); ERROR("Subtask name:" + subTaskName); return false; } fInputHandler->closeInput(); } return true; } void JPetTaskIO::addSubTask(std::unique_ptr<JPetTaskInterface> subTask) { if (dynamic_cast<JPetUserTask*>(subTask.get()) == nullptr) { ERROR("JPetTaskIO currently only allows JPetUserTask as subtask"); } fSubTasks.push_back(std::move(subTask)); } void JPetTaskIO::displayProgressBar(std::string taskName, int currentEventNumber, int numberOfEvents) const { return fProgressBar.display(taskName, currentEventNumber, numberOfEvents); } /** * @brief Currently this method passes "stopIteration_bool" option from subTask to fParams if present. */ JPetParams JPetTaskIO::mergeWithExtraParams(const JPetParams& oldParams, const JPetParams& extraParams) const { using namespace jpet_options_tools; using namespace jpet_options_generator_tools; auto oldOpts = oldParams.getOptions(); auto extraOpts = extraParams.getOptions(); // @todo this is hardcoded and should be moved somewhere. const std::string stopIterationOptName = "stopIteration_bool"; if (isOptionSet(extraOpts, stopIterationOptName)) { oldOpts[stopIterationOptName] = getOptionValue(extraOpts, stopIterationOptName); } return JPetParams(oldOpts, oldParams.getParamManagerAsShared()); } void JPetTaskIO::setParams(const JPetParams& opts) { fParams = opts; } JPetParams JPetTaskIO::getParams() const { return fParams; } bool JPetTaskIO::isOutput() const { return fIsOutput; } bool JPetTaskIO::isInput() const { return fIsInput; } /** * @return (isOK, inputFile, outputFileFullPath, isResetOutputPath) based on provided options. * If isOK is set to false, that means that an error has occured. */ std::tuple<bool, std::string, std::string, bool> JPetTaskIO::setInputAndOutputFile(const OptsStrAny opts) const { // We cannot remove this method completely and leave the one from JPetTaskIOTools, because it is overloaded in JPetScopeLoader class. return JPetTaskIOTools::setInputAndOutputFile(opts, fTaskInfo.fResetOutputPath, fTaskInfo.fInFileType, fTaskInfo.fOutFileType); } bool JPetTaskIO::createInputObjects(const char* inputFilename) { fInputHandler = jpet_common_tools::make_unique<JPetInputHandler>(); return fInputHandler->openInput(inputFilename, fParams); } bool JPetTaskIO::createOutputObjects(const char* outputFilename) { if (!isOutput()) { ERROR("isOutput set to false and you are trying to createOutputObjects"); return false; } fOutputHandler = jpet_common_tools::make_unique<JPetOutputHandler>(outputFilename); if (!fOutputHandler) { ERROR("OutputHandler is not set, cannot creat output file."); return false; } using namespace jpet_options_tools; auto options = fParams.getOptions(); if (FileTypeChecker::getInputFileType(options) == FileTypeChecker::kHldRoot || FileTypeChecker::getInputFileType(options) == FileTypeChecker::kMCGeant ) { fHeader = new JPetTreeHeader(getRunNumber(options)); fHeader->setFrameworkVersion(FRAMEWORK_VERSION); fHeader->setFrameworkRevision(FRAMEWORK_REVISION); // add general info to the Tree header fHeader->setBaseFileName(getInputFile(options).c_str()); } else { if (isInput()) { // read the header from the previous analysis stage fHeader = fInputHandler->getHeaderClone(); } else { ERROR("We are trying to load Tree Header from the input file, and no input is set."); return false; } } fStatistics = jpet_common_tools::make_unique<JPetStatistics>(); // add info about this module to the processing stages' history in Tree header for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) { auto task = dynamic_cast<JPetUserTask*>((*fSubTask).get()); fHeader->addStageInfo(task->getName(), "", 0, JPetCommonTools::getTimeString()); } if (!fSubTasks.empty()) { int i = 0; for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) { auto task = dynamic_cast<JPetUserTask*>(fSubTask->get()); std::string subtaskStatisticsName = task->getName() + std::string(" subtask ") + std::to_string(i) + std::string(" stats"); fSubTasksStatistics[subtaskStatisticsName] = std::move(jpet_common_tools::make_unique<JPetStatistics>(*fStatistics)); task->setStatistics(fSubTasksStatistics[subtaskStatisticsName].get()); i++; } } else { WARNING("the subTask does not exist, so JPetStatistics not passed to it"); } return true; } const JPetParamBank& JPetTaskIO::getParamBank() { DEBUG("from JPetTaskIO"); auto paramManager = fParams.getParamManager(); assert(paramManager); return paramManager->getParamBank(); } JPetParamManager& JPetTaskIO::getParamManager() { DEBUG("JPetTaskIO"); auto paramManager = fParams.getParamManager(); static JPetParamManager NullManager(true); if (paramManager) { DEBUG("JPetParamManger returning normal parammanager"); return *paramManager; } else { DEBUG("JPetParamManger returning NullManager "); return NullManager; } } std::string JPetTaskIO::getFirstSubTaskName() const { std::string subTaskName; auto subtasks = getSubTasks(); if (subtasks.size() > 0) { auto subTask = subtasks[0]; if (subTask) { subTaskName = subTask->getName(); } } return subTaskName; } <commit_msg>Small refactoring of JPetTaskIO<commit_after>/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file JPetTaskIO.cpp */ #include "./JPetOptionsGenerator/JPetOptionsGeneratorTools.h" #include "./JPetCommonTools/JPetCommonTools.h" #include "./JPetTreeHeader/JPetTreeHeader.h" #include "./JPetUserTask/JPetUserTask.h" #include "./JPetTask/JPetTask.h" #include "./JPetData/JPetData.h" #include "./JPetLoggerInclude.h" #include "JPetTaskIOTools.h" #include "JPetTaskIO.h" #include "./version.h" #include <cassert> #include <memory> JPetTaskIO::JPetTaskIO(const char* name, const char* in_file_type, const char* out_file_type): JPetTask(name), fTaskInfo(in_file_type, out_file_type, "", false) { if (std::string(out_file_type).empty()) { fIsOutput = false; } if (std::string(in_file_type).empty()) { fIsInput = false; } } JPetTaskIO::~JPetTaskIO() {} bool JPetTaskIO::init(const JPetParams& params) { using namespace jpet_options_tools; setParams(params); auto opts = fParams.getOptions(); bool isOK = false; std::string inputFilename; std::string outFileFullPath; bool resetOutputPath = false; std::tie(isOK, inputFilename, outFileFullPath, resetOutputPath) = setInputAndOutputFile(opts); fTaskInfo.fOutFileFullPath = outFileFullPath; fTaskInfo.fResetOutputPath = resetOutputPath; auto subTaskName = getFirstSubTaskName(); if (!isOK) { ERROR("Some error occured in setInputAndOutputFile, subtask name:" + subTaskName); return false; } if (isInput()) { if (!createInputObjects(inputFilename.c_str())) { ERROR("createInputObjects with the input file:" + inputFilename); ERROR("Subtask name:" + subTaskName); return false; } } if (isOutput()) { if (!createOutputObjects(outFileFullPath.c_str())) { ERROR("createOutputObjects with the output file:" + outFileFullPath); ERROR("Subtask name:" + subTaskName); return false; } } return true; } bool JPetTaskIO::run(const JPetDataInterface&) { using namespace jpet_options_tools; if (fSubTasks.empty()) { ERROR("No subTask set"); return false; } if (isInput()) { if (!fInputHandler) { ERROR("No inputHandler set"); return false; } } for (const auto& pTask : fSubTasks) { auto subTaskName = pTask->getName(); bool isOK = false; isOK = pTask->init(fParams); if (!isOK) { WARNING("In init() of:" + subTaskName + ". run() and terminate() of this task will be skipped."); continue; } if (isInput()) { assert(fInputHandler); bool isProgressBarOn = isProgressBar(fParams.getOptions()); isOK = fInputHandler->setEntryRange(fParams.getOptions()); if (!isOK) { ERROR("Some error occured in setEntryRange"); return false; } auto lastEvent = fInputHandler->getLastEntryNumber(); assert(lastEvent >= 0); do { if (isProgressBarOn) { displayProgressBar(subTaskName, fInputHandler->getCurrentEntryNumber(), lastEvent); } JPetData event(fInputHandler->getEntry()); isOK = pTask->run(event); if (!isOK) { ERROR("In run() of:" + subTaskName + ". "); } if (isOutput()) { if (!fOutputHandler->writeEventToFile(pTask.get())) { ERROR("Some problems occured, while writing the event to file."); return false; } } } while (fInputHandler->nextEntry()); } else { JPetDataInterface dummyEvent; pTask->run(dummyEvent); } JPetParams subTaskParams; isOK = pTask->terminate(subTaskParams); if (!isOK) { ERROR("In terminate() of:" + subTaskName + ". "); return false; } fParams = mergeWithExtraParams(fParams, subTaskParams); } return true; } bool JPetTaskIO::terminate(JPetParams& output_params) { auto subTaskName = getFirstSubTaskName(); if (isOutput()) { auto newOpts = JPetTaskIOTools::setOutputOptions(fParams, fTaskInfo.fResetOutputPath, fTaskInfo.fOutFileFullPath); output_params = JPetParams(newOpts, fParams.getParamManagerAsShared()); } else { output_params = fParams; } if (isOutput()) { if (!fHeader) { ERROR("Tree header is not set,"); ERROR("Subtask name:" + subTaskName); return false; } if (!fStatistics.get()) { ERROR("Statistics container with histograms is not set."); ERROR("Subtask name:" + subTaskName); return false; } fOutputHandler->saveAndCloseOutput(getParamManager(), fHeader, fStatistics.get(), fSubTasksStatistics); } if (isInput()) { if (!fInputHandler) { ERROR("fInputHandler set to null."); ERROR("Subtask name:" + subTaskName); return false; } fInputHandler->closeInput(); } return true; } void JPetTaskIO::addSubTask(std::unique_ptr<JPetTaskInterface> subTask) { if (dynamic_cast<JPetUserTask*>(subTask.get()) == nullptr) { ERROR("JPetTaskIO currently only allows JPetUserTask as subtask"); } fSubTasks.push_back(std::move(subTask)); } void JPetTaskIO::displayProgressBar(std::string taskName, int currentEventNumber, int numberOfEvents) const { return fProgressBar.display(taskName, currentEventNumber, numberOfEvents); } /** * @brief Currently this method passes "stopIteration_bool" option from subTask to fParams if present. */ JPetParams JPetTaskIO::mergeWithExtraParams(const JPetParams& oldParams, const JPetParams& extraParams) const { using namespace jpet_options_tools; using namespace jpet_options_generator_tools; auto oldOpts = oldParams.getOptions(); auto extraOpts = extraParams.getOptions(); // @todo this is hardcoded and should be moved somewhere. const std::string stopIterationOptName = "stopIteration_bool"; if (isOptionSet(extraOpts, stopIterationOptName)) { oldOpts[stopIterationOptName] = getOptionValue(extraOpts, stopIterationOptName); } return JPetParams(oldOpts, oldParams.getParamManagerAsShared()); } void JPetTaskIO::setParams(const JPetParams& opts) { fParams = opts; } JPetParams JPetTaskIO::getParams() const { return fParams; } bool JPetTaskIO::isOutput() const { return fIsOutput; } bool JPetTaskIO::isInput() const { return fIsInput; } /** * @return (isOK, inputFile, outputFileFullPath, isResetOutputPath) based on provided options. * If isOK is set to false, that means that an error has occured. */ std::tuple<bool, std::string, std::string, bool> JPetTaskIO::setInputAndOutputFile(const OptsStrAny opts) const { // We cannot remove this method completely and leave the one from JPetTaskIOTools, because it is overloaded in JPetScopeLoader class. return JPetTaskIOTools::setInputAndOutputFile(opts, fTaskInfo.fResetOutputPath, fTaskInfo.fInFileType, fTaskInfo.fOutFileType); } bool JPetTaskIO::createInputObjects(const char* inputFilename) { fInputHandler = jpet_common_tools::make_unique<JPetInputHandler>(); return fInputHandler->openInput(inputFilename, fParams); } bool JPetTaskIO::createOutputObjects(const char* outputFilename) { if (!isOutput()) { ERROR("isOutput set to false and you are trying to createOutputObjects"); return false; } fOutputHandler = jpet_common_tools::make_unique<JPetOutputHandler>(outputFilename); if (!fOutputHandler) { ERROR("OutputHandler is not set, cannot creat output file."); return false; } using namespace jpet_options_tools; auto options = fParams.getOptions(); if (FileTypeChecker::getInputFileType(options) == FileTypeChecker::kHldRoot || FileTypeChecker::getInputFileType(options) == FileTypeChecker::kMCGeant ) { fHeader = new JPetTreeHeader(getRunNumber(options)); fHeader->setFrameworkVersion(FRAMEWORK_VERSION); fHeader->setFrameworkRevision(FRAMEWORK_REVISION); // add general info to the Tree header fHeader->setBaseFileName(getInputFile(options).c_str()); } else { if (isInput()) { // read the header from the previous analysis stage fHeader = fInputHandler->getHeaderClone(); } else { ERROR("We are trying to load Tree Header from the input file, and no input is set."); return false; } } fStatistics = jpet_common_tools::make_unique<JPetStatistics>(); // add info about this module to the processing stages' history in Tree header for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) { auto task = dynamic_cast<JPetUserTask*>((*fSubTask).get()); fHeader->addStageInfo(task->getName(), "", 0, JPetCommonTools::getTimeString()); } if (!fSubTasks.empty()) { int i = 0; for (auto fSubTask = fSubTasks.begin(); fSubTask != fSubTasks.end(); fSubTask++) { auto task = dynamic_cast<JPetUserTask*>(fSubTask->get()); std::string subtaskStatisticsName = task->getName() + std::string(" subtask ") + std::to_string(i) + std::string(" stats"); fSubTasksStatistics[subtaskStatisticsName] = std::move(jpet_common_tools::make_unique<JPetStatistics>(*fStatistics)); task->setStatistics(fSubTasksStatistics[subtaskStatisticsName].get()); i++; } } else { WARNING("the subTask does not exist, so JPetStatistics not passed to it"); } return true; } const JPetParamBank& JPetTaskIO::getParamBank() { DEBUG("from JPetTaskIO"); auto paramManager = fParams.getParamManager(); assert(paramManager); return paramManager->getParamBank(); } JPetParamManager& JPetTaskIO::getParamManager() { DEBUG("JPetTaskIO"); auto paramManager = fParams.getParamManager(); static JPetParamManager NullManager(true); if (paramManager) { DEBUG("JPetParamManger returning normal parammanager"); return *paramManager; } else { DEBUG("JPetParamManger returning NullManager "); return NullManager; } } std::string JPetTaskIO::getFirstSubTaskName() const { std::string subTaskName; auto subtasks = getSubTasks(); if (subtasks.size() > 0) { auto subTask = subtasks[0]; if (subTask) { subTaskName = subTask->getName(); } } return subTaskName; } <|endoftext|>
<commit_before>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> #include "sound.h" TC_NAMESPACE_BEGIN constexpr int n = 100; constexpr real room_size = 10.0_f; constexpr real dx = room_size / n; constexpr real c = 340; constexpr real alpha = 0.0001; Array2D<real> p, q, r; void advance(real dt) { std::swap(p.data, q.data); std::swap(q.data, r.data); r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { real laplacian_p = inv_dx2 * (p[i - 1][j] + p[i][j - 1] + p[i + 1][j] + p[i][j + 1] - 4 * p[i][j]); real laplacian_q = inv_dx2 * (q[i - 1][j] + q[i][j - 1] + q[i + 1][j] + q[i][j + 1] - 4 * q[i][j]); r[i][j] = 2 * q[i][j] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j] - c * alpha * dt * laplacian_p; } } } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector2i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); FILE *f = fopen("data/wave.txt", "r"); WaveFile wav_file("output.wav"); dt = 1_f / 44100; TC_P(dt); for (int T = 0; T < 1000; T++) { for (int i = 0; i < 2000; i++) { real left, right; fscanf(f, "%f%f", &left, &right); advance(dt); r[n / 4][n / 2] = (left + right) / 65536.0; t += dt; wav_file.add_sound(dt, r[n / 4 + 4][n / 2]); // wav_file.add_sound(dt, std::sin(t * 10000)); } for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); if (T % 100 == 0) wav_file.flush(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <commit_msg>Changed to 3D<commit_after>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> #include "sound.h" TC_NAMESPACE_BEGIN constexpr int n = 30; constexpr real room_size = 10.0_f; constexpr real dx = room_size / n; constexpr real c = 340; constexpr real alpha = 0.001; Array3D<real> p, q, r; void advance(real dt) { std::swap(p.data, q.data); std::swap(q.data, r.data); r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { for (int k = 1; k < n - 1; k++) { real laplacian_p = inv_dx2 * (p[i - 1][j][k] + p[i][j - 1][k] + p[i + 1][j][k] + p[i][j + 1][k] + p[i][j][k + 1] + p[i][j][k - 1] - 6 * p[i][j][k]); real laplacian_q = inv_dx2 * (q[i - 1][j][k] + q[i][j - 1][k] + q[i + 1][j][k] + q[i][j + 1][k] + q[i][j][k + 1] + q[i][j][k - 1] - 6 * q[i][j][k]); r[i][j][k] = 2 * q[i][j][k] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j][k] - c * alpha * dt * laplacian_p; } } } } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector3i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); FILE *f = fopen("data/wave.txt", "r"); WaveFile wav_file("output.wav"); dt = 1_f / 44100; TC_P(dt); r[n / 2][n / 2][n / 2] = 1; for (int T = 0; T < 1000; T++) { for (int i = 0; i < 5; i++) { real left, right; fscanf(f, "%f%f", &left, &right); advance(dt); // r[n / 4][n / 2] = (left + right) / 65536.0; t += dt; wav_file.add_sound(dt, r[n / 4 + 4][n / 2][n / 2]); // wav_file.add_sound(dt, std::sin(t * 10000)); } for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale][n / 2]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); if (T % 100 == 0) wav_file.flush(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <iostream> #include <vector> #include <algorithm> // Google Test #include <gtest/gtest.h> // HIP API #include <hip/hip_runtime.h> // hipCUB API #include <hipcub.hpp> #include "test_utils.hpp" #define HIP_CHECK(error) \ ASSERT_EQ(static_cast<hipError_t>(error),hipSuccess) // Params for tests template< class InputType, class OutputType = InputType > struct DeviceReduceParams { using input_type = InputType; using output_type = OutputType; }; // --------------------------------------------------------- // Test for reduction ops taking single input value // --------------------------------------------------------- template<class Params> class HipcubDeviceReduceTests : public ::testing::Test { public: using input_type = typename Params::input_type; using output_type = typename Params::output_type; #ifdef HIPCUB_CUB_API const bool debug_synchronous = false; #else const bool debug_synchronous = !false; #endif }; typedef ::testing::Types< // ----------------------------------------------------------------------- // // ----------------------------------------------------------------------- DeviceReduceParams<int>, DeviceReduceParams<unsigned long>, DeviceReduceParams<short>, DeviceReduceParams<int> > HipcubDeviceReduceTestsParams; std::vector<size_t> get_sizes() { std::vector<size_t> sizes = { 1, 10, 53, 211, 1024, 2048, 5096, 34567, (1 << 17) - 1220 }; const std::vector<size_t> random_sizes = test_utils::get_random_data<size_t>(2, 1, 16384); sizes.insert(sizes.end(), random_sizes.begin(), random_sizes.end()); std::sort(sizes.begin(), sizes.end()); return sizes; } TYPED_TEST_CASE(HipcubDeviceReduceTests, HipcubDeviceReduceTestsParams); TYPED_TEST(HipcubDeviceReduceTests, Reduce) { using T = typename TestFixture::input_type; using U = typename TestFixture::output_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 100); std::vector<U> output(1, 0); T * d_input; U * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(U))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Calculate expected results on host U expected = std::accumulate(input.begin(), input.end(), 0); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::Sum( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::Sum( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(U), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected auto diff = std::max<U>(std::abs(0.01f * expected), U(0.01f)); if(std::is_integral<U>::value) diff = 0; ASSERT_NEAR(output[0], expected, diff); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceMinimum) { using T = typename TestFixture::input_type; using U = typename TestFixture::output_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 100); std::vector<U> output(1, 0); T * d_input; U * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(U))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); hipcub::Min min_op; // Calculate expected results on host U expected = std::accumulate( input.begin(), input.end(), std::numeric_limits<U>::max(), min_op ); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::Min( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::Min( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(U), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0], expected); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceArgMinimum) { using T = typename TestFixture::input_type; using Iterator = typename hipcub::ArgIndexInputIterator<T*, int>; using key_value = typename Iterator::value_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 200); std::vector<key_value> output(1); T * d_input; key_value * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_value))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); const key_value max(1, std::numeric_limits<T>::max()); // Calculate expected results on host Iterator x(input.data()); key_value expected = std::accumulate(x, x + size, max, hipcub::ArgMin()); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::ArgMin( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::ArgMin( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(key_value), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0].key, expected.key); ASSERT_EQ(output[0].value, expected.value); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceArgMaximum) { using T = typename TestFixture::input_type; using Iterator = typename hipcub::ArgIndexInputIterator<T*, int>; using key_value = typename Iterator::value_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, -100, 100); std::vector<key_value> output(1); T * d_input; key_value * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_value))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); const key_value max(1, std::numeric_limits<T>::lowest()); // Calculate expected results on host Iterator x(input.data()); key_value expected = std::accumulate(x, x + size, max, hipcub::ArgMax()); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::ArgMax( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::ArgMax( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(key_value), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0].key, expected.key); ASSERT_EQ(output[0].value, expected.value); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } <commit_msg>Remove integer conversion warning<commit_after>// MIT License // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <iostream> #include <vector> #include <algorithm> // Google Test #include <gtest/gtest.h> // HIP API #include <hip/hip_runtime.h> // hipCUB API #include <hipcub.hpp> #include "test_utils.hpp" #define HIP_CHECK(error) \ ASSERT_EQ(static_cast<hipError_t>(error),hipSuccess) // Params for tests template< class InputType, class OutputType = InputType > struct DeviceReduceParams { using input_type = InputType; using output_type = OutputType; }; // --------------------------------------------------------- // Test for reduction ops taking single input value // --------------------------------------------------------- template<class Params> class HipcubDeviceReduceTests : public ::testing::Test { public: using input_type = typename Params::input_type; using output_type = typename Params::output_type; #ifdef HIPCUB_CUB_API const bool debug_synchronous = false; #else const bool debug_synchronous = !false; #endif }; typedef ::testing::Types< // ----------------------------------------------------------------------- // // ----------------------------------------------------------------------- DeviceReduceParams<int>, DeviceReduceParams<unsigned long>, DeviceReduceParams<short>, DeviceReduceParams<int> > HipcubDeviceReduceTestsParams; std::vector<size_t> get_sizes() { std::vector<size_t> sizes = { 1, 10, 53, 211, 1024, 2048, 5096, 34567, (1 << 17) - 1220 }; const std::vector<size_t> random_sizes = test_utils::get_random_data<size_t>(2, 1, 16384); sizes.insert(sizes.end(), random_sizes.begin(), random_sizes.end()); std::sort(sizes.begin(), sizes.end()); return sizes; } TYPED_TEST_CASE(HipcubDeviceReduceTests, HipcubDeviceReduceTestsParams); TYPED_TEST(HipcubDeviceReduceTests, Reduce) { using T = typename TestFixture::input_type; using U = typename TestFixture::output_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 100); std::vector<U> output(1, 0); T * d_input; U * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(U))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Calculate expected results on host U expected = std::accumulate(input.begin(), input.end(), 0); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::Sum( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::Sum( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(U), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected auto diff = std::max<U>(std::abs(0.01f * expected), U(0.01f)); if(std::is_integral<U>::value) diff = 0; ASSERT_NEAR(output[0], expected, diff); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceMinimum) { using T = typename TestFixture::input_type; using U = typename TestFixture::output_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 100); std::vector<U> output(1, 0); T * d_input; U * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(U))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); hipcub::Min min_op; // Calculate expected results on host U expected = std::accumulate( input.begin(), input.end(), std::numeric_limits<U>::max(), min_op ); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::Min( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::Min( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(U), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0], expected); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceArgMinimum) { using T = typename TestFixture::input_type; using Iterator = typename hipcub::ArgIndexInputIterator<T*, int>; using key_value = typename Iterator::value_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, 1, 200); std::vector<key_value> output(1); T * d_input; key_value * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_value))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); const key_value max(1, std::numeric_limits<T>::max()); // Calculate expected results on host Iterator x(input.data()); key_value expected = std::accumulate(x, x + size, max, hipcub::ArgMin()); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::ArgMin( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::ArgMin( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(key_value), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0].key, expected.key); ASSERT_EQ(output[0].value, expected.value); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } TYPED_TEST(HipcubDeviceReduceTests, ReduceArgMaximum) { using T = typename TestFixture::input_type; using Iterator = typename hipcub::ArgIndexInputIterator<T*, int>; using key_value = typename Iterator::value_type; const bool debug_synchronous = TestFixture::debug_synchronous; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { // HIP hipStream_t stream = 0; // default HIP_CHECK(hipStreamCreate(&stream)); SCOPED_TRACE(testing::Message() << "with size = " << size); // Generate data std::vector<T> input = test_utils::get_random_data<T>(size, T(-100), T(100)); std::vector<key_value> output(1); T * d_input; key_value * d_output; HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_value))); HIP_CHECK( hipMemcpy( d_input, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); const key_value max(1, std::numeric_limits<T>::lowest()); // Calculate expected results on host Iterator x(input.data()); key_value expected = std::accumulate(x, x + size, max, hipcub::ArgMax()); // temp storage size_t temp_storage_size_bytes; void * d_temp_storage = nullptr; // Get size of d_temp_storage HIP_CHECK( hipcub::DeviceReduce::ArgMax( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); // temp_storage_size_bytes must be >0 ASSERT_GT(temp_storage_size_bytes, 0U); // allocate temporary storage HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes)); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Run HIP_CHECK( hipcub::DeviceReduce::ArgMax( d_temp_storage, temp_storage_size_bytes, d_input, d_output, input.size(), stream, debug_synchronous ) ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Copy output to host HIP_CHECK( hipMemcpy( output.data(), d_output, output.size() * sizeof(key_value), hipMemcpyDeviceToHost ) ); HIP_CHECK(hipDeviceSynchronize()); HIP_CHECK(hipStreamSynchronize(stream)); // Check if output values are as expected ASSERT_EQ(output[0].key, expected.key); ASSERT_EQ(output[0].value, expected.value); hipFree(d_input); hipFree(d_output); hipFree(d_temp_storage); // HIP stream HIP_CHECK(hipStreamDestroy(stream)); } } <|endoftext|>
<commit_before>//===- MapFile.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -Map option. It shows lists in order and // hierarchically the output sections, input sections, input files and // symbol: // // Address Size Align Out In Symbol // 00201000 00000015 4 .text // 00201000 0000000e 4 test.o:(.text) // 0020100e 00000000 0 local // 00201005 00000000 0 f(int) // //===----------------------------------------------------------------------===// #include "MapFile.h" #include "InputFiles.h" #include "LinkerScript.h" #include "OutputSections.h" #include "Strings.h" #include "SymbolTable.h" #include "Threads.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; using namespace lld; using namespace lld::elf; typedef DenseMap<const SectionBase *, SmallVector<DefinedRegular *, 4>> SymbolMapTy; // Print out the first three columns of a line. static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size, uint64_t Align) { int W = Config->Is64 ? 16 : 8; OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align); } static std::string indent(int Depth) { return std::string(Depth * 8, ' '); } // Returns a list of all symbols that we want to print out. template <class ELFT> static std::vector<DefinedRegular *> getSymbols() { std::vector<DefinedRegular *> V; for (ObjFile<ELFT> *File : ObjFile<ELFT>::Instances) for (SymbolBody *B : File->getSymbols()) if (B->File == File && !B->isSection()) if (auto *Sym = dyn_cast<DefinedRegular>(B)) if (Sym->Section && Sym->Section->Live) V.push_back(Sym); return V; } // Returns a map from sections to their symbols. static SymbolMapTy getSectionSyms(ArrayRef<DefinedRegular *> Syms) { SymbolMapTy Ret; for (DefinedRegular *S : Syms) Ret[S->Section].push_back(S); // Sort symbols by address. We want to print out symbols in the // order in the output file rather than the order they appeared // in the input files. for (auto &It : Ret) { SmallVectorImpl<DefinedRegular *> &V = It.second; std::sort(V.begin(), V.end(), [](DefinedRegular *A, DefinedRegular *B) { return A->getVA() < B->getVA(); }); } return Ret; } // Construct a map from symbols to their stringified representations. // Demangling symbols (which is what toString() does) is slow, so // we do that in batch using parallel-for. template <class ELFT> static DenseMap<DefinedRegular *, std::string> getSymbolStrings(ArrayRef<DefinedRegular *> Syms) { std::vector<std::string> Str(Syms.size()); parallelForEachN(0, Syms.size(), [&](size_t I) { raw_string_ostream OS(Str[I]); writeHeader(OS, Syms[I]->getVA(), Syms[I]->template getSize<ELFT>(), 0); OS << indent(2) << toString(*Syms[I]); }); DenseMap<DefinedRegular *, std::string> Ret; for (size_t I = 0, E = Syms.size(); I < E; ++I) Ret[Syms[I]] = std::move(Str[I]); return Ret; } template <class ELFT> void elf::writeMapFile() { if (Config->MapFile.empty()) return; // Open a map file for writing. std::error_code EC; raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None); if (EC) { error("cannot open " + Config->MapFile + ": " + EC.message()); return; } // Collect symbol info that we want to print out. std::vector<DefinedRegular *> Syms = getSymbols<ELFT>(); SymbolMapTy SectionSyms = getSectionSyms(Syms); DenseMap<DefinedRegular *, std::string> SymStr = getSymbolStrings<ELFT>(Syms); // Print out the header line. int W = ELFT::Is64Bits ? 16 : 8; OS << left_justify("Address", W) << ' ' << left_justify("Size", W) << " Align Out In Symbol\n"; // Print out file contents. for (OutputSection *OSec : OutputSections) { writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment); OS << OSec->Name << '\n'; // Dump symbols for each input section. for (BaseCommand *Base : OSec->Commands) { auto *ISD = dyn_cast<InputSectionDescription>(Base); if (!ISD) continue; for (InputSection *IS : ISD->Sections) { writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(), IS->Alignment); OS << indent(1) << toString(IS) << '\n'; for (DefinedRegular *Sym : SectionSyms[IS]) OS << SymStr[Sym] << '\n'; } } } } template void elf::writeMapFile<ELF32LE>(); template void elf::writeMapFile<ELF32BE>(); template void elf::writeMapFile<ELF64LE>(); template void elf::writeMapFile<ELF64BE>(); <commit_msg>Simplify. NFC.<commit_after>//===- MapFile.cpp --------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -Map option. It shows lists in order and // hierarchically the output sections, input sections, input files and // symbol: // // Address Size Align Out In Symbol // 00201000 00000015 4 .text // 00201000 0000000e 4 test.o:(.text) // 0020100e 00000000 0 local // 00201005 00000000 0 f(int) // //===----------------------------------------------------------------------===// #include "MapFile.h" #include "InputFiles.h" #include "LinkerScript.h" #include "OutputSections.h" #include "Strings.h" #include "SymbolTable.h" #include "Threads.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::object; using namespace lld; using namespace lld::elf; typedef DenseMap<const SectionBase *, SmallVector<DefinedRegular *, 4>> SymbolMapTy; // Print out the first three columns of a line. static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size, uint64_t Align) { int W = Config->Is64 ? 16 : 8; OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align); } static std::string indent(int Depth) { return std::string(Depth * 8, ' '); } // Returns a list of all symbols that we want to print out. template <class ELFT> static std::vector<DefinedRegular *> getSymbols() { std::vector<DefinedRegular *> V; for (ObjFile<ELFT> *File : ObjFile<ELFT>::Instances) for (SymbolBody *B : File->getSymbols()) if (auto *DR = dyn_cast<DefinedRegular>(B)) if (DR->File == File && !DR->isSection() && DR->Section && DR->Section->Live) V.push_back(DR); return V; } // Returns a map from sections to their symbols. static SymbolMapTy getSectionSyms(ArrayRef<DefinedRegular *> Syms) { SymbolMapTy Ret; for (DefinedRegular *S : Syms) Ret[S->Section].push_back(S); // Sort symbols by address. We want to print out symbols in the // order in the output file rather than the order they appeared // in the input files. for (auto &It : Ret) { SmallVectorImpl<DefinedRegular *> &V = It.second; std::sort(V.begin(), V.end(), [](DefinedRegular *A, DefinedRegular *B) { return A->getVA() < B->getVA(); }); } return Ret; } // Construct a map from symbols to their stringified representations. // Demangling symbols (which is what toString() does) is slow, so // we do that in batch using parallel-for. template <class ELFT> static DenseMap<DefinedRegular *, std::string> getSymbolStrings(ArrayRef<DefinedRegular *> Syms) { std::vector<std::string> Str(Syms.size()); parallelForEachN(0, Syms.size(), [&](size_t I) { raw_string_ostream OS(Str[I]); writeHeader(OS, Syms[I]->getVA(), Syms[I]->template getSize<ELFT>(), 0); OS << indent(2) << toString(*Syms[I]); }); DenseMap<DefinedRegular *, std::string> Ret; for (size_t I = 0, E = Syms.size(); I < E; ++I) Ret[Syms[I]] = std::move(Str[I]); return Ret; } template <class ELFT> void elf::writeMapFile() { if (Config->MapFile.empty()) return; // Open a map file for writing. std::error_code EC; raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None); if (EC) { error("cannot open " + Config->MapFile + ": " + EC.message()); return; } // Collect symbol info that we want to print out. std::vector<DefinedRegular *> Syms = getSymbols<ELFT>(); SymbolMapTy SectionSyms = getSectionSyms(Syms); DenseMap<DefinedRegular *, std::string> SymStr = getSymbolStrings<ELFT>(Syms); // Print out the header line. int W = ELFT::Is64Bits ? 16 : 8; OS << left_justify("Address", W) << ' ' << left_justify("Size", W) << " Align Out In Symbol\n"; // Print out file contents. for (OutputSection *OSec : OutputSections) { writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment); OS << OSec->Name << '\n'; // Dump symbols for each input section. for (BaseCommand *Base : OSec->Commands) { auto *ISD = dyn_cast<InputSectionDescription>(Base); if (!ISD) continue; for (InputSection *IS : ISD->Sections) { writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(), IS->Alignment); OS << indent(1) << toString(IS) << '\n'; for (DefinedRegular *Sym : SectionSyms[IS]) OS << SymStr[Sym] << '\n'; } } } } template void elf::writeMapFile<ELF32LE>(); template void elf::writeMapFile<ELF32BE>(); template void elf::writeMapFile<ELF64LE>(); template void elf::writeMapFile<ELF64BE>(); <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkTestingMacros.h" #include "mitkPointSetStatisticsCalculator.h" #include "itkImage.h" #include "mitkExtendedLabelStatisticsImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include <itkImageRegionConstIterator.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIteratorWithIndex.h> #include <itkImageRegionIteratorWithIndex.h> //#include <QtCore> /** * \brief Test class for mitkPointSetStatisticsCalculator */ class mitkImageStatisticsTextureAnalysisTestClass { public: typedef itk::Image<unsigned short,3 >ImageType; typedef ImageType::Pointer pointerOfImage; typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType; typedef LabelStatisticsFilterType::Pointer labelStatisticsFilterPointer; //typedef itk::ImageRegionConstIteratorWithIndex<MaskImageType> MaskImageIteratorType; //typedef itk::ImageRegionConstIteratorWithIndex <ImageType> InputImageIndexIteratorType; static ImageType::Pointer CreatingTestLabelImage() { //InputImageIndexIteratorType labelIterator2; ImageType::Pointer image = ImageType :: New(); ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; start[2] = 0; size[0] = 2; size[1] = 2; size[2] = 2; ImageType:: RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions(region); image->Allocate(); image->FillBuffer(1.0); return image; } static ImageType::Pointer CreatingTestImage() { //InputImageIndexIteratorType labelIterator2; ImageType::Pointer image = ImageType :: New(); ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; start[2] = 0; size[0] = 2; size[1] = 2; size[2] = 2; ImageType:: RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions(region); image->Allocate(); image->FillBuffer(3.0); //for( labelIterator2.GoToBegin(); !labelIterator2.IsAtEnd(); ++labelIterator2) // { // } for(unsigned int r = 0; r < 1; r++) { for(unsigned int c = 0; c < 2; c++) { for(unsigned int l = 0; l < 2; l++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; pixelIndex[2] = l; image->SetPixel(pixelIndex, 2.0); } } } return image; } static LabelStatisticsFilterType::Pointer TestInstantiation(ImageType::Pointer image, ImageType::Pointer maskImage) { // typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType; LabelStatisticsFilterType::Pointer labelStatisticsFilter; labelStatisticsFilter = LabelStatisticsFilterType::New(); labelStatisticsFilter->SetInput( image ); labelStatisticsFilter->SetLabelInput( maskImage ); labelStatisticsFilter->SetLabelInput( maskImage ); labelStatisticsFilter->Update(); //typename StatisticsFilterType::Pointer statisticsFilter = StatisticsFilterType::New(); // mitk::PointSetStatisticsCalculator::Pointer myPointSetStatisticsCalculator = mitk::PointSetStatisticsCalculator::New(); // MITK_TEST_CONDITION_REQUIRED(myPointSetStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1."); return labelStatisticsFilter; } static void TestTrueFalse(LabelStatisticsFilterType::Pointer labelStatisticsFilter, double expectedSkewness, double expectedKurtosis) { // let's create an object of our class MITK_TEST_CONDITION(labelStatisticsFilter->GetSkewness( 1 ) == expectedSkewness,"expectedSkewness: " << expectedSkewness << " actual Value: " << labelStatisticsFilter->GetSkewness( 1 ) ); MITK_TEST_CONDITION(labelStatisticsFilter->GetKurtosis( 1 ) == expectedKurtosis,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << labelStatisticsFilter->GetKurtosis( 1 ) ); } }; int mitkImageStatisticsTextureAnalysisTest(int, char* []) { // always start with this! MITK_TEST_BEGIN("mitkImageStatisticsTextureAnalysisTest") mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage label = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestLabelImage(); mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage(); itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>:: Pointer writer1 = itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>::New(); // writer->SetImageIO(nrrdImageIO); writer1->SetFileName("C:\\Users\\tmueller\\Documents\\TestPics\\SeedsFG_TEST1.nrrd"); writer1->SetInput(label); writer1->Update(); itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>:: Pointer writer = itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>::New(); // writer->SetImageIO(nrrdImageIO); writer->SetFileName("C:\\Users\\tmueller\\Documents\\TestPics\\SeedsFG_TEST2.nrrd"); writer->SetInput(image); writer->Update(); mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image,label); mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 1); // superImage = CreateSuperImage(); // superImage1 = CreateSuperImage(); // superImage2 = CreateSuperImage(); // superImage3 = CreateSuperImage(); //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage, 2334.33, 2332.3); //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage1, 2312334.33, 43434.0); //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage2, 123223.8, 2332.3); //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage3, 2312334.33, 2332.3); MITK_TEST_END() } <commit_msg>add some new tests for the imageStatisticsCalculator<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStandardFileLocations.h" #include "mitkTestingMacros.h" #include "mitkPointSetStatisticsCalculator.h" #include "itkImage.h" #include "mitkExtendedLabelStatisticsImageFilter.h" #include "mitkExtendedStatisticsImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include <itkImageRegionConstIterator.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIteratorWithIndex.h> #include <itkImageRegionIteratorWithIndex.h> //#include <QtCore> /** * \brief Test class for mitkPointSetStatisticsCalculator */ class mitkImageStatisticsTextureAnalysisTestClass { public: typedef itk::Image<unsigned short,3 >ImageType; typedef ImageType::Pointer pointerOfImage; typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType; typedef LabelStatisticsFilterType::Pointer labelStatisticsFilterPointer; typedef itk::ExtendedStatisticsImageFilter< ImageType > StatisticsFilterType; typedef StatisticsFilterType::Pointer StatisticsFilterPointer; static ImageType::Pointer CreatingTestLabelImage() { ImageType::Pointer image = ImageType :: New(); ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; start[2] = 0; size[0] = 100; size[1] = 100; size[2] = 100; ImageType:: RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions(region); image->Allocate(); image->FillBuffer(1.0); return image; } static ImageType::Pointer CreatingTestImage() { ImageType::Pointer image = ImageType :: New(); ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; start[2] = 0; size[0] = 100; size[1] = 100; size[2] = 100; ImageType:: RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions(region); image->Allocate(); image->FillBuffer(3.0); for(unsigned int r = 0; r < 50; r++) { for(unsigned int c = 0; c < 100; c++) { for(unsigned int l = 0; l < 100; l++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; pixelIndex[2] = l; image->SetPixel(pixelIndex, 2.0); } } } return image; } static ImageType::Pointer CreatingTestImage2() { ImageType::Pointer image = ImageType :: New(); ImageType::IndexType start; ImageType::SizeType size; start[0] = 0; start[1] = 0; start[2] = 0; size[0] = 100; size[1] = 100; size[2] = 100; ImageType:: RegionType region; region.SetSize( size ); region.SetIndex( start ); image->SetRegions(region); image->Allocate(); image->FillBuffer(3.0); for(unsigned int r = 0; r < 50; r++) { for(unsigned int c = 0; c < 50; c++) { for(unsigned int l = 0; l < 100; l++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; pixelIndex[2] = l; image->SetPixel(pixelIndex, 2.0); } } } return image; } static LabelStatisticsFilterType::Pointer TestInstantiation(ImageType::Pointer image, ImageType::Pointer maskImage) { LabelStatisticsFilterType::Pointer labelStatisticsFilter; labelStatisticsFilter = LabelStatisticsFilterType::New(); labelStatisticsFilter->SetInput( image ); labelStatisticsFilter->SetLabelInput( maskImage ); labelStatisticsFilter->Update(); return labelStatisticsFilter; } static StatisticsFilterType::Pointer TestInstantiation2(ImageType::Pointer image ) { StatisticsFilterType::Pointer StatisticsFilter; StatisticsFilter = StatisticsFilterType::New(); StatisticsFilter->SetInput( image ); StatisticsFilter->Update(); return StatisticsFilter; } static void TestTrueFalse(LabelStatisticsFilterType::Pointer labelStatisticsFilter, double expectedSkewness, double expectedKurtosis) { // let's create an object of our class bool isSkewsnessLowerlimitCorrect = labelStatisticsFilter->GetSkewness( 1 )- expectedKurtosis+ std::pow(10,-3) <= expectedSkewness; bool isSkewsnessUpperlimitCorrect = labelStatisticsFilter->GetSkewness( 1 )+ expectedKurtosis+ std::pow(10,-3) >= expectedSkewness; MITK_TEST_CONDITION( isSkewsnessLowerlimitCorrect && isSkewsnessUpperlimitCorrect,"expectedSkewness: " << expectedSkewness << " actual Value: " << labelStatisticsFilter->GetSkewness( 1 ) ); bool isKurtosisUpperlimitCorrect = labelStatisticsFilter->GetKurtosis( 1 ) <= expectedKurtosis+ std::pow(10,-3); bool isKurtosisLowerlimitCorrect = expectedKurtosis- std::pow(10,-3) <= labelStatisticsFilter->GetKurtosis( 1 ); MITK_TEST_CONDITION( isKurtosisUpperlimitCorrect && isKurtosisLowerlimitCorrect,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << labelStatisticsFilter->GetKurtosis( 1 ) ); } static void TestTrueFalse2(StatisticsFilterType::Pointer StatisticsFilter, double expectedSkewness, double expectedKurtosis) { // let's create an object of our class bool isSkewsnessLowerlimitCorrect = StatisticsFilter->GetSkewness()- expectedKurtosis+ std::pow(10,-3) <= expectedSkewness; bool isSkewsnessUpperlimitCorrect = StatisticsFilter->GetSkewness()+ expectedKurtosis+ std::pow(10,-3) >= expectedSkewness; MITK_TEST_CONDITION( isSkewsnessLowerlimitCorrect && isSkewsnessUpperlimitCorrect,"expectedSkewness: " << expectedSkewness << " actual Value: " << StatisticsFilter->GetSkewness() ); bool isKurtosisUpperlimitCorrect = StatisticsFilter->GetKurtosis() <= expectedKurtosis+ std::pow(10,-3); bool isKurtosisLowerlimitCorrect = expectedKurtosis- std::pow(10,-3) <= StatisticsFilter->GetKurtosis(); MITK_TEST_CONDITION( isKurtosisUpperlimitCorrect && isKurtosisLowerlimitCorrect,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << StatisticsFilter->GetKurtosis() ); } }; int mitkImageStatisticsTextureAnalysisTest(int, char* []) { // always start with this! MITK_TEST_BEGIN("mitkImageStatisticsTextureAnalysisTest") mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage label = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestLabelImage(); mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage(); mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image2 = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage2(); mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image,label); mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 0.999998); mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter2= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image2,label); mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter2, -1.1547, 2.33333); mitkImageStatisticsTextureAnalysisTestClass::StatisticsFilterPointer mitkFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation2( image); mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 0.999998); mitkImageStatisticsTextureAnalysisTestClass::StatisticsFilterPointer mitkFilter2= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation2( image2); mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter2, -1.1547, 2.33333); MITK_TEST_END() } <|endoftext|>
<commit_before>#include <sstream> using std::ostringstream; #include "shared_read_write_remote_classifier.h" #include "log.h" namespace HybridProtocol_PPMOSI_SS { SharedReadWriteRemoteClassifier::SharedReadWriteRemoteClassifier() : Classifier() , _saved_mode(Mode::PRIVATE) {} SharedReadWriteRemoteClassifier::~SharedReadWriteRemoteClassifier() {} Mode::Type SharedReadWriteRemoteClassifier::getMode(tile_id_t sharer) { return _saved_mode; } void SharedReadWriteRemoteClassifier::updateMode(tile_id_t sender, ShmemMsg* shmem_msg, DirectoryEntry* directory_entry, BufferedReq* buffered_req) { if (_saved_mode == Mode::REMOTE_LINE) return; if (!IS_BLOCKING_REQ(shmem_msg->getType())) return; tile_id_t sharer = sender; UInt32 num_sharers = directory_entry->getNumSharers(); DirectoryState::Type dstate = directory_entry->getDirectoryBlockInfo()->getDState(); ShmemMsg::Type req_type = shmem_msg->getType(); // For new cache lines if (num_sharers == 0) return; // For private cache lines if ( (num_sharers == 1) && (directory_entry->hasSharer(sharer)) ) return; // If state is MODIFIED or OWNED, there has been a write to it, so return in REMOTE mode if ( (dstate == DirectoryState::MODIFIED) || (dstate == DirectoryState::OWNED) ) { _saved_mode = Mode::REMOTE_LINE; return; } // Now, line is in SHARED or EXCLUSIVE state // For read-only cache lines if (req_type == ShmemMsg::UNIFIED_READ_REQ) return; // Set the line in remote mode _saved_mode = Mode::REMOTE_LINE; } } <commit_msg>[adaptive protocol] Updated the shared_read_write_remote classifier<commit_after>#include "shared_read_write_remote_classifier.h" #include "log.h" namespace HybridProtocol_PPMOSI_SS { SharedReadWriteRemoteClassifier::SharedReadWriteRemoteClassifier() : Classifier() , _saved_mode(Mode::PRIVATE) {} SharedReadWriteRemoteClassifier::~SharedReadWriteRemoteClassifier() {} Mode::Type SharedReadWriteRemoteClassifier::getMode(tile_id_t sharer) { return _saved_mode; } void SharedReadWriteRemoteClassifier::updateMode(tile_id_t sender, ShmemMsg* shmem_msg, DirectoryEntry* directory_entry, BufferedReq* buffered_req) { // Uni-directional classification change from PRIVATE -> REMOTE_LINE, never reverts back if (_saved_mode == Mode::REMOTE_LINE) return; // Special code for WB_REPLY if ( (shmem_msg->getType() == ShmemMsg::WB_REPLY) || (shmem_msg->getType() == ShmemMsg::FLUSH_REQ) ) { tile_id_t requester = buffered_req ? buffered_req->getShmemMsg()->getRequester() : INVALID_TILE_ID; if ((requester != INVALID_TILE_ID) && shmem_msg->isCacheLineDirty()) { LOG_ASSERT_ERROR(requester != sender, "Requester(%i), Sender(%i)", requester, sender); _saved_mode = Mode::REMOTE_LINE; } return; } if (!IS_BLOCKING_REQ(shmem_msg->getType())) return; tile_id_t sharer = sender; UInt32 num_sharers = directory_entry->getNumSharers(); DirectoryState::Type dstate = directory_entry->getDirectoryBlockInfo()->getDState(); ShmemMsg::Type req_type = shmem_msg->getType(); // For new cache lines if (num_sharers == 0) return; // For private cache lines if ( (num_sharers == 1) && (directory_entry->hasSharer(sharer)) ) return; // If state is MODIFIED or OWNED, there has been a write to it, so return in REMOTE mode if ( (dstate == DirectoryState::MODIFIED) || (dstate == DirectoryState::OWNED) ) { _saved_mode = Mode::REMOTE_LINE; return; } // Now, line is in SHARED or EXCLUSIVE state // For read-only cache lines if (req_type == ShmemMsg::UNIFIED_READ_REQ) return; // Set the line in remote mode _saved_mode = Mode::REMOTE_LINE; } } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "VersionControlQuery.h" #include "../query_framework/QueryRegistry.h" #include "ModelBase/src/nodes/Node.h" #include "ModelBase/src/model/TreeManager.h" #include "FilePersistence/src/simple/SimpleTextFileStore.h" #include "FilePersistence/src/version_control/GitRepository.h" #include "FilePersistence/src/version_control/History.h" #include "ModelBase/src/nodes/Node.h" #include "OOModel/src/elements/StatementItem.h" using namespace FilePersistence; namespace InformationScripting { const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"}; const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"}; const QStringList VersionControlQuery::NODES_ARGUMENTS_NAMES{"nodes"}; const QStringList VersionControlQuery::IN_ARGUMENT_NAMES{"in"}; Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet input) { Model::TreeManager* treeManager = target()->manager(); // get GitRepository QString path{"projects/" + treeManager->name()}; if (!GitRepository::repositoryExists(path)) return {"No repository found"}; GitRepository repository{path}; TupleSet result; auto commitIdRange = repository.revisions(); auto adaptedRangeOptional = commitsToConsider(commitIdRange); if (!adaptedRangeOptional) return adaptedRangeOptional.errors()[0]; commitIdRange = adaptedRangeOptional.value(); QList<Model::Node*> nodesToLookAt; bool considerLocalCommitsOnly = arguments_.isArgumentSet(ArgumentParser::LOCAL_SCOPE_ARGUMENT_NAMES[0]) && arguments_.scope(this) == ArgumentParser::Scope::Local; if (considerLocalCommitsOnly) nodesToLookAt << target(); else if (arguments_.scope(this) == ArgumentParser::Scope::Input) for (const auto& astTuple : input.tuples("ast")) nodesToLookAt << static_cast<Model::Node*>(astTuple["ast"]); bool outputNodesOnly = arguments_.isArgumentSet(NODES_ARGUMENTS_NAMES[0]); auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1])); for (int i = commitIdRange.size() - 1; i > 0; --i) { QString oldCommitId = commitIdRange[i]; QString newCommitId = commitIdRange[i - 1]; Diff diff = repository.diff(oldCommitId, newCommitId); auto changes = diff.changes(); if (!outputNodesOnly) addCommitMetaInformation(result, repository.getCommitInformation(newCommitId)); for (auto change : changes.values()) { // We ignore structure only changes since a node with a structure only change, // has a child which was deleted or added or modified, and this child will appear in the final representation. if (change->isFake() || change->onlyStructureChange()) continue; auto id = change->nodeId(); if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id))) { Model::Node* changedNode = nullptr; if (auto statement = node->firstAncestorOfType(typeMatcher)) changedNode = statement; else // The node is hopefully higher up in the node hierarchy thus we take it as is. changedNode = node; auto ancestorIt = std::find_if(nodesToLookAt.begin(), nodesToLookAt.end(), [changedNode](Model::Node* n) { return n->isAncestorOf(changedNode); }); if (nodesToLookAt.isEmpty() || ancestorIt != nodesToLookAt.end()) { // If we have input or local node(s) only return the information of the input nodes and not the children: if (!nodesToLookAt.isEmpty()) changedNode = *ancestorIt; if (outputNodesOnly) result.add({{"ast", changedNode}}); else result.add({"change", {{"id", newCommitId}, {"ast", changedNode}}}); } } } } return result; } void VersionControlQuery::registerDefaultQueries() { QueryRegistry::registerQuery<VersionControlQuery>("changes", std::vector<ArgumentRule>{{ArgumentRule::AtMostOneOf, {{COUNT_ARGUMENT_NAMES[1], ArgumentValue::IsSet}, {IN_ARGUMENT_NAMES[0], ArgumentValue::IsSet}}}}); } VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args, std::vector<ArgumentRule> argumentRules) : LinearQuery{target}, arguments_{{ {COUNT_ARGUMENT_NAMES, "The amount of revisions to look at", COUNT_ARGUMENT_NAMES[1], "10"}, {NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"}, QCommandLineOption{NODES_ARGUMENTS_NAMES}, {IN_ARGUMENT_NAMES, "Specific commits to look at, either a single one or a range with ..", IN_ARGUMENT_NAMES[0]} }, args, true} { for (const auto& rule : argumentRules) rule.check(arguments_); } void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata) { ts.add({"commit", {{"id", metadata.sha1_}, {"message", metadata.message_}, {"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")}, {"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_}, {"author", metadata.author_.name_ + " " + metadata.author_.eMail_}}}); } Optional<QList<QString>> VersionControlQuery::commitsToConsider(const QStringList& commitIdRange) const { if (arguments_.isArgumentSet(IN_ARGUMENT_NAMES[0])) { auto commitRange = arguments_.argument(IN_ARGUMENT_NAMES[0]).split(".."); QString startCommit = commitRange[0]; auto startIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [startCommit](QString sha1) { return sha1.startsWith(startCommit); }); if (startIt == commitIdRange.end()) return {QString{"%1 is not a commit id that exists in this repository."}.arg(startCommit)}; QStringList::const_iterator endIt; if (commitRange.size() > 1) { QString endCommit = commitRange[1]; endIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [endCommit](QString sha1) { return sha1.startsWith(endCommit); }); if (endIt == commitIdRange.end()) return {QString{"%1 is not a commit id that exists in this repository."}.arg(endCommit)}; } else { endIt = startIt + 1; } QStringList result; // We always need one more than the actual end since we compare on two commits: for (auto it = startIt; it != endIt + 1; ++it) result.append(*it); return result; } else { QString countArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]); bool converts = false; const int CHANGE_COUNT = countArgument.toInt(&converts); if (converts) return commitIdRange.mid(0, std::min(commitIdRange.size(), CHANGE_COUNT + 1)); else if (countArgument != "all") return {"Invalid count argument"}; else return commitIdRange; } } } <commit_msg>start work on improving changes query<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "VersionControlQuery.h" #include "../query_framework/QueryRegistry.h" #include "ModelBase/src/nodes/Node.h" #include "ModelBase/src/model/TreeManager.h" #include "FilePersistence/src/simple/SimpleTextFileStore.h" #include "FilePersistence/src/version_control/GitRepository.h" #include "FilePersistence/src/version_control/History.h" #include "ModelBase/src/nodes/Node.h" #include "OOModel/src/elements/StatementItem.h" using namespace FilePersistence; namespace InformationScripting { const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"}; const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"}; const QStringList VersionControlQuery::NODES_ARGUMENTS_NAMES{"nodes"}; const QStringList VersionControlQuery::IN_ARGUMENT_NAMES{"in"}; Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet input) { Model::TreeManager* treeManager = target()->manager(); // get GitRepository QString path{"projects/" + treeManager->name()}; if (!GitRepository::repositoryExists(path)) return {"No repository found"}; GitRepository repository{path}; TupleSet result; auto commitIdRange = repository.revisions(); auto adaptedRangeOptional = commitsToConsider(commitIdRange); if (!adaptedRangeOptional) return adaptedRangeOptional.errors()[0]; commitIdRange = adaptedRangeOptional.value(); QList<Model::Node*> nodesToLookAt; bool considerLocalCommitsOnly = arguments_.isArgumentSet(ArgumentParser::LOCAL_SCOPE_ARGUMENT_NAMES[0]) && arguments_.scope(this) == ArgumentParser::Scope::Local; if (considerLocalCommitsOnly) nodesToLookAt << target(); else if (arguments_.scope(this) == ArgumentParser::Scope::Input) for (const auto& astTuple : input.tuples("ast")) nodesToLookAt << static_cast<Model::Node*>(astTuple["ast"]); bool outputNodesOnly = arguments_.isArgumentSet(NODES_ARGUMENTS_NAMES[0]); auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1])); for (int i = commitIdRange.size() - 1; i > 0; --i) { QString oldCommitId = commitIdRange[i]; QString newCommitId = commitIdRange[i - 1]; Diff diff = repository.diff(oldCommitId, newCommitId); auto changes = diff.changes(); if (!outputNodesOnly) addCommitMetaInformation(result, repository.getCommitInformation(newCommitId)); for (auto change : changes.values()) { // We ignore structure only changes since a node with a structure only change, // has a child which was deleted or added or modified, and this child will appear in the final representation. if (change->isFake() || change->onlyStructureChange()) continue; auto id = change->nodeId(); if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id))) { Model::Node* changedNode = nullptr; if (auto statement = node->firstAncestorOfType(typeMatcher)) changedNode = statement; else // The node is hopefully higher up in the node hierarchy thus we take it as is. changedNode = node; auto ancestorIt = std::find_if(nodesToLookAt.begin(), nodesToLookAt.end(), [changedNode](Model::Node* n) { return n->isAncestorOf(changedNode); }); if (nodesToLookAt.isEmpty() || ancestorIt != nodesToLookAt.end()) { // If we have input or local node(s) only return the information of the input nodes and not the children: if (!nodesToLookAt.isEmpty()) changedNode = *ancestorIt; if (outputNodesOnly) { result.add({{"ast", changedNode}}); switch (change->type()) { case ChangeType::Deletion: result.add({"color", {{"ast", changedNode}, {"color", QString{"red"}}}}); break; case ChangeType::Insertion: result.add({"color", {{"ast", changedNode}, {"color", QString{"blue"}}}}); break; case ChangeType::Move: result.add({"color", {{"ast", changedNode}, {"color", QString{"yellow"}}}}); break; case ChangeType::Stationary: result.add({"color", {{"ast", changedNode}, {"color", QString{"black"}}}}); break; case ChangeType::Unclassified: result.add({"color", {{"ast", changedNode}, {"color", QString{"white"}}}}); break; } } else result.add({"change", {{"id", newCommitId}, {"ast", changedNode}}}); } } } } return result; } void VersionControlQuery::registerDefaultQueries() { QueryRegistry::registerQuery<VersionControlQuery>("changes", std::vector<ArgumentRule>{{ArgumentRule::AtMostOneOf, {{COUNT_ARGUMENT_NAMES[1], ArgumentValue::IsSet}, {IN_ARGUMENT_NAMES[0], ArgumentValue::IsSet}}}}); } VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args, std::vector<ArgumentRule> argumentRules) : LinearQuery{target}, arguments_{{ {COUNT_ARGUMENT_NAMES, "The amount of revisions to look at", COUNT_ARGUMENT_NAMES[1], "10"}, {NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"}, QCommandLineOption{NODES_ARGUMENTS_NAMES}, {IN_ARGUMENT_NAMES, "Specific commits to look at, either a single one or a range with ..", IN_ARGUMENT_NAMES[0]} }, args, true} { for (const auto& rule : argumentRules) rule.check(arguments_); } void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata) { ts.add({"commit", {{"id", metadata.sha1_}, {"message", metadata.message_}, {"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")}, {"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_}, {"author", metadata.author_.name_ + " " + metadata.author_.eMail_}}}); } Optional<QList<QString>> VersionControlQuery::commitsToConsider(const QStringList& commitIdRange) const { if (arguments_.isArgumentSet(IN_ARGUMENT_NAMES[0])) { auto commitRange = arguments_.argument(IN_ARGUMENT_NAMES[0]).split(".."); QString startCommit = commitRange[0]; auto startIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [startCommit](QString sha1) { return sha1.startsWith(startCommit); }); if (startIt == commitIdRange.end()) return {QString{"%1 is not a commit id that exists in this repository."}.arg(startCommit)}; QStringList::const_iterator endIt; if (commitRange.size() > 1) { QString endCommit = commitRange[1]; endIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [endCommit](QString sha1) { return sha1.startsWith(endCommit); }); if (endIt == commitIdRange.end()) return {QString{"%1 is not a commit id that exists in this repository."}.arg(endCommit)}; } else { endIt = startIt + 1; } QStringList result; // We always need one more than the actual end since we compare on two commits: for (auto it = startIt; it != endIt + 1; ++it) result.append(*it); return result; } else { QString countArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]); bool converts = false; const int CHANGE_COUNT = countArgument.toInt(&converts); if (converts) return commitIdRange.mid(0, std::min(commitIdRange.size(), CHANGE_COUNT + 1)); else if (countArgument != "all") return {"Invalid count argument"}; else return commitIdRange; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: canvasfont.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-11-26 17:11:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <canvas/debug.hxx> #ifndef INCLUDED_RTL_MATH_HXX #include <rtl/math.hxx> #endif #ifndef _BGFX_NUMERIC_FTOOLS_HXX #include <basegfx/numeric/ftools.hxx> #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #include "outdevprovider.hxx" #include "canvasfont.hxx" #include "textlayout.hxx" using namespace ::com::sun::star; using namespace ::drafts::com::sun::star; namespace vclcanvas { CanvasFont::CanvasFont( const rendering::FontRequest& rFontRequest, const uno::Sequence< beans::PropertyValue >& rExtraFontProperties, const geometry::Matrix2D& rFontMatrix, const OutDevProviderSharedPtr& rDevice ) : CanvasFont_Base( m_aMutex ), maFont( Font( rFontRequest.FontDescription.FamilyName, rFontRequest.FontDescription.StyleName, Size( 0, ::basegfx::fround(rFontRequest.CellSize) ) ) ), maFontRequest( rFontRequest ), mpRefDevice( rDevice ) { CHECK_AND_THROW( mpRefDevice.get(), "CanvasFont::CanvasFont(): Invalid ref device" ); maFont->SetAlign( ALIGN_BASELINE ); maFont->SetCharSet( (rFontRequest.FontDescription.IsSymbolFont==com::sun::star::util::TriState_YES) ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE ); maFont->SetVertical( (rFontRequest.FontDescription.IsVertical==com::sun::star::util::TriState_YES) ? TRUE : FALSE ); // TODO(F2): improve panose->vclenum conversion maFont->SetWeight( static_cast<FontWeight>(rFontRequest.FontDescription.FontDescription.Weight) ); maFont->SetItalic( (rFontRequest.FontDescription.FontDescription.Letterform<=8) ? ITALIC_NONE : ITALIC_NORMAL ); // adjust to stretched font if( !::rtl::math::approxEqual( rFontMatrix.m00, rFontMatrix.m11) ) { const OutputDevice& rOutDev( mpRefDevice->getOutDev() ); const Size aSize = rOutDev.GetFontMetric( *maFont ).GetSize(); const double fDividend( rFontMatrix.m10 + rFontMatrix.m11 ); double fStretch = (rFontMatrix.m00 + rFontMatrix.m01); if( !::basegfx::fTools::equalZero( fDividend) ) fStretch /= fDividend; const long nNewWidth = ::basegfx::fround( aSize.Width() * fStretch ); maFont->SetWidth( nNewWidth ); } } CanvasFont::~CanvasFont() { } void SAL_CALL CanvasFont::disposing() { tools::LocalGuard aGuard; mpRefDevice.reset(); } uno::Reference< rendering::XTextLayout > SAL_CALL CanvasFont::createTextLayout( const rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; if( !mpRefDevice.get() ) return uno::Reference< rendering::XTextLayout >(); // we're disposed return new TextLayout( aText, nDirection, nRandomSeed, ImplRef( this ), mpRefDevice ); } rendering::FontRequest SAL_CALL CanvasFont::getFontRequest( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; return maFontRequest; } rendering::FontMetrics SAL_CALL CanvasFont::getFontMetrics( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return rendering::FontMetrics(); } uno::Sequence< double > SAL_CALL CanvasFont::getAvailableSizes( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return uno::Sequence< double >(); } uno::Sequence< beans::PropertyValue > SAL_CALL CanvasFont::getExtraFontProperties( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return uno::Sequence< beans::PropertyValue >(); } #define SERVICE_NAME "drafts.com.sun.star.rendering.CanvasFont" ::rtl::OUString SAL_CALL CanvasFont::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CANVASFONT_IMPLEMENTATION_NAME ) ); } sal_Bool SAL_CALL CanvasFont::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException ) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) ); } uno::Sequence< ::rtl::OUString > SAL_CALL CanvasFont::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) ); return aRet; } ::Font CanvasFont::getVCLFont() const { return *maFont; } } <commit_msg>INTEGRATION: CWS presfixes01 (1.3.10); FILE MERGED 2005/02/16 11:14:06 fs 1.3.10.1: #i42558# drafts.com.sun.star.drawing/rendering/geometry moved to com.sun.star.*<commit_after>/************************************************************************* * * $RCSfile: canvasfont.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-10 11:58:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <canvas/debug.hxx> #ifndef INCLUDED_RTL_MATH_HXX #include <rtl/math.hxx> #endif #ifndef _BGFX_NUMERIC_FTOOLS_HXX #include <basegfx/numeric/ftools.hxx> #endif #ifndef _SV_METRIC_HXX #include <vcl/metric.hxx> #endif #include "outdevprovider.hxx" #include "canvasfont.hxx" #include "textlayout.hxx" using namespace ::com::sun::star; namespace vclcanvas { CanvasFont::CanvasFont( const rendering::FontRequest& rFontRequest, const uno::Sequence< beans::PropertyValue >& rExtraFontProperties, const geometry::Matrix2D& rFontMatrix, const OutDevProviderSharedPtr& rDevice ) : CanvasFont_Base( m_aMutex ), maFont( Font( rFontRequest.FontDescription.FamilyName, rFontRequest.FontDescription.StyleName, Size( 0, ::basegfx::fround(rFontRequest.CellSize) ) ) ), maFontRequest( rFontRequest ), mpRefDevice( rDevice ) { CHECK_AND_THROW( mpRefDevice.get(), "CanvasFont::CanvasFont(): Invalid ref device" ); maFont->SetAlign( ALIGN_BASELINE ); maFont->SetCharSet( (rFontRequest.FontDescription.IsSymbolFont==com::sun::star::util::TriState_YES) ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE ); maFont->SetVertical( (rFontRequest.FontDescription.IsVertical==com::sun::star::util::TriState_YES) ? TRUE : FALSE ); // TODO(F2): improve panose->vclenum conversion maFont->SetWeight( static_cast<FontWeight>(rFontRequest.FontDescription.FontDescription.Weight) ); maFont->SetItalic( (rFontRequest.FontDescription.FontDescription.Letterform<=8) ? ITALIC_NONE : ITALIC_NORMAL ); // adjust to stretched font if( !::rtl::math::approxEqual( rFontMatrix.m00, rFontMatrix.m11) ) { const OutputDevice& rOutDev( mpRefDevice->getOutDev() ); const Size aSize = rOutDev.GetFontMetric( *maFont ).GetSize(); const double fDividend( rFontMatrix.m10 + rFontMatrix.m11 ); double fStretch = (rFontMatrix.m00 + rFontMatrix.m01); if( !::basegfx::fTools::equalZero( fDividend) ) fStretch /= fDividend; const long nNewWidth = ::basegfx::fround( aSize.Width() * fStretch ); maFont->SetWidth( nNewWidth ); } } CanvasFont::~CanvasFont() { } void SAL_CALL CanvasFont::disposing() { tools::LocalGuard aGuard; mpRefDevice.reset(); } uno::Reference< rendering::XTextLayout > SAL_CALL CanvasFont::createTextLayout( const rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; if( !mpRefDevice.get() ) return uno::Reference< rendering::XTextLayout >(); // we're disposed return new TextLayout( aText, nDirection, nRandomSeed, ImplRef( this ), mpRefDevice ); } rendering::FontRequest SAL_CALL CanvasFont::getFontRequest( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; return maFontRequest; } rendering::FontMetrics SAL_CALL CanvasFont::getFontMetrics( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return rendering::FontMetrics(); } uno::Sequence< double > SAL_CALL CanvasFont::getAvailableSizes( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return uno::Sequence< double >(); } uno::Sequence< beans::PropertyValue > SAL_CALL CanvasFont::getExtraFontProperties( ) throw (uno::RuntimeException) { tools::LocalGuard aGuard; // TODO(F1) return uno::Sequence< beans::PropertyValue >(); } #define SERVICE_NAME "com.sun.star.rendering.CanvasFont" ::rtl::OUString SAL_CALL CanvasFont::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CANVASFONT_IMPLEMENTATION_NAME ) ); } sal_Bool SAL_CALL CanvasFont::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException ) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) ); } uno::Sequence< ::rtl::OUString > SAL_CALL CanvasFont::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) ); return aRet; } ::Font CanvasFont::getVCLFont() const { return *maFont; } } <|endoftext|>
<commit_before>#include <iostream> #include "EightQueens.h" namespace EightQueensProblem { bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned ) {//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't. } bool EightQueensSolver::isLegal( bool chessBoard[8][8] ) {//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal. int count;//Number of queens encountered in a given row/column/diagonal. //Check the rows. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this row, the board isn't legal so return false. return false; } } } //Check the columns. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[i][j] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this column, the board isn't legal so return false. return false; } } } //Check the diagonals. } static void printBoard( bool chessBoard[8][8] ) {//Prints out chessBoard to standard output. //Go through each element one by one and print - for empty and * for queen. for( int i = 0; i < 8; i++ ) { for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Queen space std::cout << "*"; } else {//Empty space std::cout << "-"; } //Print a space after the character, but not if it's the last one since only want spaces between characters. if( j < 7 ) { std::cout << " "; } } //Print an endline after the current line. std::cout << std::endl; } } <commit_msg>Did a little bit for the isLegal method.<commit_after>#include <iostream> #include "EightQueens.h" namespace EightQueensProblem { bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned ) {//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't. } bool EightQueensSolver::isLegal( bool chessBoard[8][8] ) {//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal. int count;//Number of queens encountered in a given row/column/diagonal. //Check the rows. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this row, the board isn't legal so return false. return false; } } } //Check the columns. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[i][j] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this column, the board isn't legal so return false. return false; } } } //Check the diagonals. for( int i } static void printBoard( bool chessBoard[8][8] ) {//Prints out chessBoard to standard output. //Go through each element one by one and print - for empty and * for queen. for( int i = 0; i < 8; i++ ) { for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Queen space std::cout << "*"; } else {//Empty space std::cout << "-"; } //Print a space after the character, but not if it's the last one since only want spaces between characters. if( j < 7 ) { std::cout << " "; } } //Print an endline after the current line. std::cout << std::endl; } } <|endoftext|>
<commit_before>#include "window.h" namespace thirdsengine { namespace graphics { Window *Window::instance = NULL; Window::Window(const char *title, int width, int height) { instance = this; m_Title = title; m_Width = width; m_Height = height; m_Closed = false; if (!init()) { glfwTerminate(); } for (int i = 0; i < MAX_KEYS; i++) m_Keys[i] = false; for (int i = 0; i < MAX_BUTTONS; i++) m_Buttons[i] = false; } Window::~Window() { glfwTerminate(); } bool Window::init() { if (!glfwInit()) { std::cout << "GLFW could not initialise!" << std::endl; return false; } m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL); if (!m_Window) { std::cout << "Failed to create window!" << std::endl; return false; } glfwMakeContextCurrent(m_Window); if (glewInit() != GLEW_OK) { std::cout << "GLEW could not initialise!" << std::endl; return false; } std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl; glfwSetWindowSizeCallback( m_Window, callbackResize); glfwSetKeyCallback( m_Window, callbackKey); glfwSetMouseButtonCallback( m_Window, callbackMouseButton); glfwSetCursorPosCallback( m_Window, callbackMouseMove); return true; } void Window::clear() const { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Window::update() { glfwPollEvents(); glfwGetFramebufferSize(m_Window, &m_Width, &m_Height); glViewport(0, 0, m_Width, m_Height); glfwSwapBuffers(m_Window); } bool Window::closed() const { return glfwWindowShouldClose(m_Window) != 0; } void Window::callbackResize(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void Window::callbackKey(GLFWwindow *window, int key, int scancode, int action, int mods) { instance->m_Keys[key] = (action != GLFW_RELEASE); } void Window::callbackMouseButton(GLFWwindow *window, int button, int action, int mods) { instance->m_Buttons[button] = (action != GLFW_RELEASE); } void Window::callbackMouseMove(GLFWwindow *window, double xpos, double ypos) { instance->m_MouseX = xpos; instance->m_MouseY = ypos; } bool Window::keyPressed(unsigned int keycode) const { if (keycode >= MAX_KEYS) return false; return m_Keys[keycode]; } bool Window::mouseButtonPressed(unsigned int button) const { if (button >= MAX_BUTTONS) return false; return m_Buttons[button]; } double Window::mouseX() const { return m_MouseX; } double Window::mouseY() const { return m_MouseY; } } }<commit_msg>Catch OpenGL errors<commit_after>#include "window.h" namespace thirdsengine { namespace graphics { Window *Window::instance = NULL; Window::Window(const char *title, int width, int height) { instance = this; m_Title = title; m_Width = width; m_Height = height; m_Closed = false; if (!init()) { glfwTerminate(); } for (int i = 0; i < MAX_KEYS; i++) m_Keys[i] = false; for (int i = 0; i < MAX_BUTTONS; i++) m_Buttons[i] = false; } Window::~Window() { glfwTerminate(); } bool Window::init() { if (!glfwInit()) { std::cout << "GLFW could not initialise!" << std::endl; return false; } m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL); if (!m_Window) { std::cout << "Failed to create window!" << std::endl; return false; } glfwMakeContextCurrent(m_Window); if (glewInit() != GLEW_OK) { std::cout << "GLEW could not initialise!" << std::endl; return false; } std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl; glfwSetWindowSizeCallback( m_Window, callbackResize); glfwSetKeyCallback( m_Window, callbackKey); glfwSetMouseButtonCallback( m_Window, callbackMouseButton); glfwSetCursorPosCallback( m_Window, callbackMouseMove); return true; } void Window::clear() const { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Window::update() { GLenum error = glGetError(); if (error != GL_NO_ERROR) std::cout << "OpenGL error code " << error << std::endl; glfwPollEvents(); glfwGetFramebufferSize(m_Window, &m_Width, &m_Height); glViewport(0, 0, m_Width, m_Height); glfwSwapBuffers(m_Window); } bool Window::closed() const { return glfwWindowShouldClose(m_Window) != 0; } void Window::callbackResize(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void Window::callbackKey(GLFWwindow *window, int key, int scancode, int action, int mods) { instance->m_Keys[key] = (action != GLFW_RELEASE); } void Window::callbackMouseButton(GLFWwindow *window, int button, int action, int mods) { instance->m_Buttons[button] = (action != GLFW_RELEASE); } void Window::callbackMouseMove(GLFWwindow *window, double xpos, double ypos) { instance->m_MouseX = xpos; instance->m_MouseY = ypos; } bool Window::keyPressed(unsigned int keycode) const { if (keycode >= MAX_KEYS) return false; return m_Keys[keycode]; } bool Window::mouseButtonPressed(unsigned int button) const { if (button >= MAX_BUTTONS) return false; return m_Buttons[button]; } double Window::mouseX() const { return m_MouseX; } double Window::mouseY() const { return m_MouseY; } } }<|endoftext|>
<commit_before>#include "Models_Manager.h" Models_Manager::Models_Manager() { //TODO more elegant solution, AKA method for creating models // triangle game object Transform t1 = Transform( Vector3(0, 0, 0), Vector3(1, 1, 1), Quaternion() ); Triangle* triangle = new Triangle(t1, Color::RED); triangle->SetProgram(Shader_Manager::GetShader("colorShader")); triangle->Create(); gameModelList["triangle"] = triangle; Transform t2 = Transform( Vector3(0, 0, 0), Vector3(0.5, 0.5, 1), Quaternion(1.0, 0.5, 0.5, 0.5) ); Quad* quad = new Quad(t2, Color::RED); quad->SetProgram(Shader_Manager::GetShader("colorShader")); quad->Create(); gameModelList["quad"] = quad; } Models_Manager::~Models_Manager() { // iterate through map for (auto model : gameModelList) { delete model.second; } gameModelList.clear(); } void Models_Manager::DeleteModel(const std::string& gameModelName) { IGameObject* model = gameModelList[gameModelName]; model->Destroy(); gameModelList.erase(gameModelName); } const IGameObject& Models_Manager::GetModel(const std::string& gameModelName) { return (*gameModelList.at(gameModelName)); } void Models_Manager::Update() { // iterate through model list and Update for (auto model : gameModelList) { model.second->Update(); } } void Models_Manager::Draw() { // iterate through model list and Draw for (auto model : gameModelList) { model.second->Draw(); } }<commit_msg>Demo: Mountain range<commit_after>#include "Models_Manager.h" Models_Manager::Models_Manager() { Triangle* triangle1 = new Triangle(Transform( Vector3(-25, 25, 0), Vector3(0.5, 0.5, 1), Quaternion()), Color::Darken(Color::GREEN, 0.3)); triangle1->SetProgram(Shader_Manager::GetShader("colorShader")); triangle1->Create(); gameModelList["triangle1"] = triangle1; Triangle* triangle2 = new Triangle(Transform( Vector3(25, 25, 50), Vector3(1, 1, 1), Quaternion()), Color::Darken(Color::GREEN, 0.3)); triangle2->SetProgram(Shader_Manager::GetShader("colorShader")); triangle2->Create(); gameModelList["triangle2"] = triangle2; Quad* quad1 = new Quad(Transform( Vector3(0, 0, -100), Vector3(2, 0.25, 1), Quaternion()), Color::HSV(0.45, 0.60, 0.20)); quad1->SetProgram(Shader_Manager::GetShader("colorShader")); quad1->Create(); gameModelList["quad1"] = quad1; } Models_Manager::~Models_Manager() { // iterate through map for (auto model : gameModelList) { delete model.second; } gameModelList.clear(); } void Models_Manager::DeleteModel(const std::string& gameModelName) { IGameObject* model = gameModelList[gameModelName]; model->Destroy(); gameModelList.erase(gameModelName); } const IGameObject& Models_Manager::GetModel(const std::string& gameModelName) { return (*gameModelList.at(gameModelName)); } void Models_Manager::Update() { // iterate through model list and Update for (auto model : gameModelList) { model.second->Update(); } } void Models_Manager::Draw() { // iterate through model list and Draw for (auto model : gameModelList) { model.second->Draw(); } }<|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "ClangHelpers.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "CppExport/src/exporter/CppExporter.h" #include "CppExport/src/CodeUnit.h" namespace CppImport { QString ClangHelpers::spelling(clang::SourceRange sourceRange) const { clang::SourceLocation b = sourceManager_->getSpellingLoc(sourceRange.getBegin()); clang::SourceLocation e = clang::Lexer::getLocForEndOfToken(sourceManager_->getSpellingLoc(sourceRange.getEnd()), 0, *sourceManager_, preprocessor_->getLangOpts()); // this can help in preventing an uncaught exception due to questionable input //if (sourceManager_->getPresumedLoc(b).getFilename() != sourceManager_->getPresumedLoc(e).getFilename()) return ""; bool invalid = true; auto beginPtr = sourceManager_->getCharacterData(b, &invalid); Q_ASSERT(!invalid); auto endPtr = sourceManager_->getCharacterData(e, &invalid); Q_ASSERT(!invalid); auto length = endPtr - beginPtr; return 0 < length ? QString::fromStdString(std::string(beginPtr, endPtr - beginPtr)) : ""; } QString ClangHelpers::unexpandedSpelling(clang::SourceRange range) const { auto result = spelling(getUnexpandedRange(range)); while (result.startsWith("\\")) result = result.right(result.length() - 1); return result.trimmed(); } clang::SourceRange ClangHelpers::getUnexpandedRange(clang::SourceRange sourceRange) const { auto start = sourceRange.getBegin(); auto end = sourceRange.getEnd(); if (// start is a macro location and... start.isMacroID() && // start was expanded from a macro argument or... (sourceManager_->isMacroArgExpansion(start) || // start was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.) !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(start))))) start = sourceManager_->getImmediateExpansionRange(start).first; if (// end is a macro location and... end.isMacroID() && // end was expanded from a macro argument or... (sourceManager_->isMacroArgExpansion(end) || // end was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.) !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(end))))) end = sourceManager_->getImmediateExpansionRange(end).second; return clang::SourceRange{start, end}; } ClangHelpers::ClangHelpers(OOModel::Project* rootProject, QString rootProjectPath) : rootProject_{rootProject}, rootProjectPath_{rootProjectPath} {} clang::SourceLocation ClangHelpers::immediateMacroLocation(clang::SourceLocation location) const { // this code is an adaptation of clang::lexer::immediateMacroName if (location.isMacroID()) while (true) { auto fileID = sourceManager_->getFileID(location); auto sourceLocationEntry = &sourceManager_->getSLocEntry(fileID); if (!sourceLocationEntry->isExpansion()) break; auto expansion = sourceLocationEntry->getExpansion(); location = expansion.getExpansionLocStart(); if (!expansion.isMacroArgExpansion()) break; location = sourceManager_->getImmediateExpansionRange(location).first; auto spellingLocation = expansion.getSpellingLoc(); if (spellingLocation.isFileID()) break; auto macroFileID = sourceManager_->getFileID(location); if (sourceManager_->isInFileID(spellingLocation, macroFileID)) break; location = spellingLocation; } return location; } void ClangHelpers::immediateSpellingHistory(clang::SourceLocation location, QList<clang::SourceLocation>& result) const { result.append(location); auto next = sourceManager_->getImmediateSpellingLoc(location); if (next != location) immediateSpellingHistory(next, result); } QList<QString> ClangHelpers::argumentNames(const clang::MacroDirective* definition) const { QList<QString> result; for (auto i = definition->getMacroInfo()->arg_begin(); i != definition->getMacroInfo()->arg_end(); i++) result.append(QString::fromStdString((*i)->getName().str())); return result; } void ClangHelpers::deleteNode(Model::Node* node) { QList<Model::Node*> workList{node}; while (!workList.empty()) { auto current = workList.takeLast(); workList << current->children(); envisionToClangMap_.remove(current); } SAFE_DELETE(node); } QStringList ClangHelpers::folderNamesFromPath(QString path) { QStringList result; QDir dir{path}; while (dir.cdUp()) { if (dir.absolutePath() == rootProjectPath_) break; result.append(dir.dirName()); } result.removeLast(); return result; } void ClangHelpers::insertDeclarationInFolder(OOModel::Declaration* declaration, clang::SourceLocation location, OOModel::Declaration* parentNonFolderDeclaration) { auto inserter = [declaration](auto container) { if (auto castedDeclaration = DCast<OOModel::Field>(declaration)) container->fields()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::Class>(declaration)) container->classes()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::Method>(declaration)) container->methods()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::MetaDefinition>(declaration)) container->subDeclarations()->append(castedDeclaration); }; auto folder = folderForLocation(location, parentNonFolderDeclaration); if (auto container = DCast<OOModel::Project>(folder)) inserter(container); else if (auto container = DCast<OOModel::Module>(folder)) inserter(container); else Q_ASSERT(false); } QString ClangHelpers::presumedFilenameWithExtension(clang::SourceLocation location) const { auto presumedLocation = sourceManager_->getPresumedLoc(location); QDir dir{presumedLocation.getFilename()}; auto fileName = dir.absolutePath(); return fileName; } QString ClangHelpers::presumedFilenameWithoutExtension(clang::SourceLocation location) const { auto fileName = presumedFilenameWithExtension(location); return fileName.left(fileName.lastIndexOf(".")); } OOModel::Declaration* ClangHelpers::folderForLocation(clang::SourceLocation location, OOModel::Declaration* parentNonFolderDeclaration) { Q_ASSERT(parentNonFolderDeclaration); Q_ASSERT(DCast<OOModel::Module>(parentNonFolderDeclaration) || DCast<OOModel::Project>(parentNonFolderDeclaration)); auto currentFolder = parentNonFolderDeclaration; auto presumedLocation = sourceManager()->getPresumedLoc(location); auto folderNames = folderNamesFromPath(presumedLocation.getFilename()); while (!folderNames.empty()) { auto requestedFolderName = folderNames.takeLast(); auto moduleFound = false; Model::TypedList<OOModel::Module>* modules{}; if (auto currentProject = DCast<OOModel::Project>(currentFolder)) modules = currentProject->modules(); else if (auto currentModule = DCast<OOModel::Module>(currentFolder)) modules = currentModule->modules(); for (auto childFolder : *modules) if (childFolder->name() == requestedFolderName) { currentFolder = childFolder; moduleFound = true; break; } if (!moduleFound) { auto newFolder = new OOModel::Module{requestedFolderName, OOModel::Module::ModuleKind::Folder}; if (auto currentProject = DCast<OOModel::Project>(currentFolder)) currentProject->modules()->append(newFolder); else if (auto currentModule = DCast<OOModel::Module>(currentFolder)) currentModule->modules()->append(newFolder); currentFolder = newFolder; } } Q_ASSERT(DCast<OOModel::Module>(currentFolder) || DCast<OOModel::Project>(currentFolder)); return currentFolder; } OOModel::Project* ClangHelpers::projectForLocation(clang::SourceLocation location) { auto presumedLocation = sourceManager()->getPresumedLoc(location); auto parentName = projectNameFromPath(presumedLocation.getFilename()); if (!parentName.isEmpty()) { auto project = projectByName(parentName); if (!project) { project = new OOModel::Project{parentName}; rootProject_->projects()->append(project); projects_.insert(parentName, project); } return project; } return rootProject_; } QString ClangHelpers::projectNameFromPath(QString path) { QRegularExpression regex{rootProjectPath_ + "/(\\w+)/"}; auto m = regex.match(QDir{path}.absolutePath()); if (m.hasMatch()) return m.captured(1); return {}; } void ClangHelpers::attachDeclarationComments(clang::NamedDecl* namedDecl, Model::Node* receiver) const { if (auto commentForDeclaration = namedDecl->getASTContext().getRawCommentForDeclNoCache(namedDecl)) { auto compositeNode = DCast<Model::CompositeNode>(receiver); Q_ASSERT(compositeNode); for (Comment* clangComment : comments_) if (clangComment->rawComment() == commentForDeclaration && !clangComment->node()) { clangComment->setNode(compositeNode); if (compositeNode->comment()) { // This code is here for future reference, but we don't actually support this case at the moment. // It would be necessary to check if the lines we are about to attach already exist. return; auto commentNode = DCast<Comments::CommentNode>(compositeNode->comment()); Q_ASSERT(commentNode); commentNode->appendText(clangComment->text()); } else compositeNode->setComment(new Comments::CommentNode{clangComment->text()}); } } } void ClangHelpers::printMacroDefinitionForDebug(const clang::MacroDirective* macroDirective) const { qDebug() << "Macro in: " << presumedFilenameWithExtension(macroDirective->getMacroInfo()->getDefinitionLoc()); qDebug() << spelling(clang::SourceRange{macroDirective->getMacroInfo()->getDefinitionLoc(), macroDirective->getMacroInfo()->getDefinitionEndLoc()}); } void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, clang::SourceLocation location) { auto fullPath = presumedFilenameWithoutExtension(location); nodeToFilenameMap_ [node] = fullPath.right(fullPath.size() - rootProjectPath_.size() - 1); } void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, Model::Node* from) { auto it = nodeToFilenameMap_.find(from); Q_ASSERT(it != nodeToFilenameMap_.end()); nodeToFilenameMap_[node] = *it; } void ClangHelpers::exportMergeMapToJson(QString filename) { QHash<QString, QString> exportedMap; QList<CppExport::CodeUnit*> codeUnits; CppExport::CppExporter::units(rootProject_, codeUnits, exportedMap); QHash<QString, QString> generatedExportedMap; for (auto unit : codeUnits) { auto nodeFilename = nodeToFilenameMap_[unit->node()]; if (generatedExportedMap.contains(unit->name())) { if (generatedExportedMap.value(unit->name()) != nodeFilename) { qDebug() << unit->name() << "mapped at least twice with different values:"; qDebug() << "1: " << nodeFilename; qDebug() << "2: " << generatedExportedMap.value(unit->name()); Q_ASSERT(false); } } else if (unit->name() != nodeFilename) generatedExportedMap.insert(unit->name(), nodeFilename); } QFile file{filename}; file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out{&file}; out << "{\n"; out << "\t\"DependencyUnitMergeMap\" :\n"; out << "\t{\n"; for (auto it = generatedExportedMap.begin(); it != generatedExportedMap.end(); it++) if (it.key() != it.value()) out << "\t\t\"" << it.key() << "\" : \"" << it.value() << "\",\n"; out << "\t},\n"; out << "\t\"SeparateTemplateImplementationSet\" : [ ]\n"; out << "}"; file.close(); } } <commit_msg>do not automatically generate merge map entries for special code units<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "ClangHelpers.h" #include "OOModel/src/declarations/Project.h" #include "OOModel/src/declarations/MetaDefinition.h" #include "CppExport/src/exporter/CppExporter.h" #include "CppExport/src/CodeUnit.h" namespace CppImport { QString ClangHelpers::spelling(clang::SourceRange sourceRange) const { clang::SourceLocation b = sourceManager_->getSpellingLoc(sourceRange.getBegin()); clang::SourceLocation e = clang::Lexer::getLocForEndOfToken(sourceManager_->getSpellingLoc(sourceRange.getEnd()), 0, *sourceManager_, preprocessor_->getLangOpts()); // this can help in preventing an uncaught exception due to questionable input //if (sourceManager_->getPresumedLoc(b).getFilename() != sourceManager_->getPresumedLoc(e).getFilename()) return ""; bool invalid = true; auto beginPtr = sourceManager_->getCharacterData(b, &invalid); Q_ASSERT(!invalid); auto endPtr = sourceManager_->getCharacterData(e, &invalid); Q_ASSERT(!invalid); auto length = endPtr - beginPtr; return 0 < length ? QString::fromStdString(std::string(beginPtr, endPtr - beginPtr)) : ""; } QString ClangHelpers::unexpandedSpelling(clang::SourceRange range) const { auto result = spelling(getUnexpandedRange(range)); while (result.startsWith("\\")) result = result.right(result.length() - 1); return result.trimmed(); } clang::SourceRange ClangHelpers::getUnexpandedRange(clang::SourceRange sourceRange) const { auto start = sourceRange.getBegin(); auto end = sourceRange.getEnd(); if (// start is a macro location and... start.isMacroID() && // start was expanded from a macro argument or... (sourceManager_->isMacroArgExpansion(start) || // start was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.) !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(start))))) start = sourceManager_->getImmediateExpansionRange(start).first; if (// end is a macro location and... end.isMacroID() && // end was expanded from a macro argument or... (sourceManager_->isMacroArgExpansion(end) || // end was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.) !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(end))))) end = sourceManager_->getImmediateExpansionRange(end).second; return clang::SourceRange{start, end}; } ClangHelpers::ClangHelpers(OOModel::Project* rootProject, QString rootProjectPath) : rootProject_{rootProject}, rootProjectPath_{rootProjectPath} {} clang::SourceLocation ClangHelpers::immediateMacroLocation(clang::SourceLocation location) const { // this code is an adaptation of clang::lexer::immediateMacroName if (location.isMacroID()) while (true) { auto fileID = sourceManager_->getFileID(location); auto sourceLocationEntry = &sourceManager_->getSLocEntry(fileID); if (!sourceLocationEntry->isExpansion()) break; auto expansion = sourceLocationEntry->getExpansion(); location = expansion.getExpansionLocStart(); if (!expansion.isMacroArgExpansion()) break; location = sourceManager_->getImmediateExpansionRange(location).first; auto spellingLocation = expansion.getSpellingLoc(); if (spellingLocation.isFileID()) break; auto macroFileID = sourceManager_->getFileID(location); if (sourceManager_->isInFileID(spellingLocation, macroFileID)) break; location = spellingLocation; } return location; } void ClangHelpers::immediateSpellingHistory(clang::SourceLocation location, QList<clang::SourceLocation>& result) const { result.append(location); auto next = sourceManager_->getImmediateSpellingLoc(location); if (next != location) immediateSpellingHistory(next, result); } QList<QString> ClangHelpers::argumentNames(const clang::MacroDirective* definition) const { QList<QString> result; for (auto i = definition->getMacroInfo()->arg_begin(); i != definition->getMacroInfo()->arg_end(); i++) result.append(QString::fromStdString((*i)->getName().str())); return result; } void ClangHelpers::deleteNode(Model::Node* node) { QList<Model::Node*> workList{node}; while (!workList.empty()) { auto current = workList.takeLast(); workList << current->children(); envisionToClangMap_.remove(current); } SAFE_DELETE(node); } QStringList ClangHelpers::folderNamesFromPath(QString path) { QStringList result; QDir dir{path}; while (dir.cdUp()) { if (dir.absolutePath() == rootProjectPath_) break; result.append(dir.dirName()); } result.removeLast(); return result; } void ClangHelpers::insertDeclarationInFolder(OOModel::Declaration* declaration, clang::SourceLocation location, OOModel::Declaration* parentNonFolderDeclaration) { auto inserter = [declaration](auto container) { if (auto castedDeclaration = DCast<OOModel::Field>(declaration)) container->fields()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::Class>(declaration)) container->classes()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::Method>(declaration)) container->methods()->append(castedDeclaration); else if (auto castedDeclaration = DCast<OOModel::MetaDefinition>(declaration)) container->subDeclarations()->append(castedDeclaration); }; auto folder = folderForLocation(location, parentNonFolderDeclaration); if (auto container = DCast<OOModel::Project>(folder)) inserter(container); else if (auto container = DCast<OOModel::Module>(folder)) inserter(container); else Q_ASSERT(false); } QString ClangHelpers::presumedFilenameWithExtension(clang::SourceLocation location) const { auto presumedLocation = sourceManager_->getPresumedLoc(location); QDir dir{presumedLocation.getFilename()}; auto fileName = dir.absolutePath(); return fileName; } QString ClangHelpers::presumedFilenameWithoutExtension(clang::SourceLocation location) const { auto fileName = presumedFilenameWithExtension(location); return fileName.left(fileName.lastIndexOf(".")); } OOModel::Declaration* ClangHelpers::folderForLocation(clang::SourceLocation location, OOModel::Declaration* parentNonFolderDeclaration) { Q_ASSERT(parentNonFolderDeclaration); Q_ASSERT(DCast<OOModel::Module>(parentNonFolderDeclaration) || DCast<OOModel::Project>(parentNonFolderDeclaration)); auto currentFolder = parentNonFolderDeclaration; auto presumedLocation = sourceManager()->getPresumedLoc(location); auto folderNames = folderNamesFromPath(presumedLocation.getFilename()); while (!folderNames.empty()) { auto requestedFolderName = folderNames.takeLast(); auto moduleFound = false; Model::TypedList<OOModel::Module>* modules{}; if (auto currentProject = DCast<OOModel::Project>(currentFolder)) modules = currentProject->modules(); else if (auto currentModule = DCast<OOModel::Module>(currentFolder)) modules = currentModule->modules(); for (auto childFolder : *modules) if (childFolder->name() == requestedFolderName) { currentFolder = childFolder; moduleFound = true; break; } if (!moduleFound) { auto newFolder = new OOModel::Module{requestedFolderName, OOModel::Module::ModuleKind::Folder}; if (auto currentProject = DCast<OOModel::Project>(currentFolder)) currentProject->modules()->append(newFolder); else if (auto currentModule = DCast<OOModel::Module>(currentFolder)) currentModule->modules()->append(newFolder); currentFolder = newFolder; } } Q_ASSERT(DCast<OOModel::Module>(currentFolder) || DCast<OOModel::Project>(currentFolder)); return currentFolder; } OOModel::Project* ClangHelpers::projectForLocation(clang::SourceLocation location) { auto presumedLocation = sourceManager()->getPresumedLoc(location); auto parentName = projectNameFromPath(presumedLocation.getFilename()); if (!parentName.isEmpty()) { auto project = projectByName(parentName); if (!project) { project = new OOModel::Project{parentName}; rootProject_->projects()->append(project); projects_.insert(parentName, project); } return project; } return rootProject_; } QString ClangHelpers::projectNameFromPath(QString path) { QRegularExpression regex{rootProjectPath_ + "/(\\w+)/"}; auto m = regex.match(QDir{path}.absolutePath()); if (m.hasMatch()) return m.captured(1); return {}; } void ClangHelpers::attachDeclarationComments(clang::NamedDecl* namedDecl, Model::Node* receiver) const { if (auto commentForDeclaration = namedDecl->getASTContext().getRawCommentForDeclNoCache(namedDecl)) { auto compositeNode = DCast<Model::CompositeNode>(receiver); Q_ASSERT(compositeNode); for (Comment* clangComment : comments_) if (clangComment->rawComment() == commentForDeclaration && !clangComment->node()) { clangComment->setNode(compositeNode); if (compositeNode->comment()) { // This code is here for future reference, but we don't actually support this case at the moment. // It would be necessary to check if the lines we are about to attach already exist. return; auto commentNode = DCast<Comments::CommentNode>(compositeNode->comment()); Q_ASSERT(commentNode); commentNode->appendText(clangComment->text()); } else compositeNode->setComment(new Comments::CommentNode{clangComment->text()}); } } } void ClangHelpers::printMacroDefinitionForDebug(const clang::MacroDirective* macroDirective) const { qDebug() << "Macro in: " << presumedFilenameWithExtension(macroDirective->getMacroInfo()->getDefinitionLoc()); qDebug() << spelling(clang::SourceRange{macroDirective->getMacroInfo()->getDefinitionLoc(), macroDirective->getMacroInfo()->getDefinitionEndLoc()}); } void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, clang::SourceLocation location) { auto fullPath = presumedFilenameWithoutExtension(location); nodeToFilenameMap_ [node] = fullPath.right(fullPath.size() - rootProjectPath_.size() - 1); } void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, Model::Node* from) { auto it = nodeToFilenameMap_.find(from); Q_ASSERT(it != nodeToFilenameMap_.end()); nodeToFilenameMap_[node] = *it; } void ClangHelpers::exportMergeMapToJson(QString filename) { QHash<QString, QString> exportedMap; QList<CppExport::CodeUnit*> codeUnits; CppExport::CppExporter::units(rootProject_, codeUnits, exportedMap); QHash<QString, QString> generatedExportedMap; for (auto unit : codeUnits) { // exportedMap contains only the special created code units (like external template instantiations that were // inside classes). These special code units should not appear in the exported merge map. if (exportedMap.contains(unit->name())) continue; auto nodeFilename = nodeToFilenameMap_[unit->node()]; if (generatedExportedMap.contains(unit->name())) { if (generatedExportedMap.value(unit->name()) != nodeFilename) { qDebug() << unit->name() << "mapped at least twice with different values:"; qDebug() << "1: " << nodeFilename; qDebug() << "2: " << generatedExportedMap.value(unit->name()); Q_ASSERT(false); } } else if (unit->name() != nodeFilename) generatedExportedMap.insert(unit->name(), nodeFilename); } QFile file{filename}; file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out{&file}; out << "{\n"; out << "\t\"DependencyUnitMergeMap\" :\n"; out << "\t{\n"; for (auto it = generatedExportedMap.begin(); it != generatedExportedMap.end(); it++) if (it.key() != it.value()) out << "\t\t\"" << it.key() << "\" : \"" << it.value() << "\",\n"; out << "\t},\n"; out << "\t\"SeparateTemplateImplementationSet\" : [ ]\n"; out << "}"; file.close(); } } <|endoftext|>
<commit_before><commit_msg>Bug fixes<commit_after><|endoftext|>
<commit_before>#include "network.h" #include <QDebug> Network::Network(QObject *parent) :QObject(parent) { my_socket = new QUdpSocket(this); my_socket->bind(QHostAddress::LocalHost, 1337); connect(my_socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagram())); } void Network::sendData(QImage image) { QByteArray q; QBuffer buffer(&q); buffer.open(QIODevice::WriteOnly); image.save(&buffer); my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337); } void Network::processPendingDatagram() { while (my_socket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(my_socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; my_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888); QImage recv_image; recv_image.loadFromData(datagram, "PNG"); if (recv_image.isNull()) // Check if the image was indeed received qDebug("The image is null. Something failed."); image = recv_image; } //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150); } QImage Network::get_image() { return image; } Network::~Network() { delete my_socket; } <commit_msg>network working<commit_after>#include "network.h" #include <QDebug> Network::Network(QObject *parent) :QObject(parent) { my_socket = new QUdpSocket(this); my_socket->bind(QHostAddress::LocalHost, 1337); connect(my_socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagram())); } void Network::sendData(QImage image) { QByteArray q; QBuffer buffer(&q); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337); } void Network::processPendingDatagram() { while (my_socket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(my_socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; my_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888); QImage recv_image; if (datagram.isNull()) qDebug("Ures a bejovo buzi!!"); else qDebug("datagram nem ures"); recv_image.loadFromData(datagram, "PNG"); if (recv_image.isNull()) // Check if the image was indeed received qDebug("The image is null. Something failed."); image = recv_image; } //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150); } QImage Network::get_image() { return image; } Network::~Network() { delete my_socket; } <|endoftext|>
<commit_before> TGraphErrors * MakeGraphSparse(TTree * tree, const Char_t * expr="mean-fdelta:run", const Char_t * cut="isTPC&&ptype==0&&theta>0"){ // Format of expr: Var:Error:Run // // Make a sparse draw of the variables // Format of expr : Var:Error:Run // const Int_t entries = tree->Draw(expr,cut,"goff"); Double_t *graphX, *graphY, *graphError; //check whether error argument exists in expr if(!tree->GetV3()){ graphX = tree->GetV2(); graphY = tree->GetV1(); } else{ graphX = tree->GetV3(); graphY = tree->GetV1(); graphError = tree->GetV2(); } // sort according to run number Int_t *index = new Int_t[entries]; TMath::Sort(entries,graphX,index,false); // define arrays for the new graph Double_t *tempArray = new Double_t[entries]; Double_t *xError = new Double_t[entries]; Double_t *yError = new Double_t[entries]; Int_t *vrun = new Int_t[entries]; Double_t count = 0.5; // evaluate arrays for the new graph accroding to the run-number Int_t icount=0; tempArray[index[0]] = count; xError[0] = 0; yError[0] = 0; if(tree->GetV3()) yError[index[0]] = graphError[index[0]]; vrun[0] = graphX[index[0]]; // loop the rest entries for(Int_t i=1;i<entries;i++){ xError[i] = 0; yError[i] = 0; if(tree->GetV3()) yError[i] = graphError[index[i]]; if(graphX[index[i]]==graphX[index[i-1]]) tempArray[index[i]] = count; else if((graphX[index[i]]!=graphX[index[i-1]])){ count++; icount++; tempArray[index[i]] = count; vrun[icount]=graphX[index[i]]; } } // count the number of xbins (run-wise) for the new graph const Int_t newNbins = int(count+0.5); Double_t *newBins = new Double_t[newNbins+1]; for(Int_t i=0; i<=count+1;i++){ newBins[i] = i; } // define and fill the new graph TGraphErrors *graphNew = new TGraphErrors(entries,tempArray,graphY,xError,yError); graphNew->GetXaxis()->Set(newNbins,newBins); // set the bins for the x-axis Char_t xName[50]; for(Int_t i=0;i<count;i++){ sprintf(xName,"%d",Int_t(vrun[i])); graphNew->GetXaxis()->SetBinLabel(i+1,xName); } graphNew->GetHistogram()->SetTitle(""); // memory clearing delete [] xError; delete [] yError; delete [] tempArray; delete [] index; delete [] newBins; delete [] vrun; return graphNew; } //------------------------------------------------------------------------------------------------ drawPerformanceT0QATrends(const char* inFile = "trending.root", const char* runType="pp") { // // gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetLabelSize(0.04,"x"); // open input file // TFile *file = TFile::Open(inFile); if(!file) return; file->cd(); TTree *tree = (TTree*)file->Get("trending"); if(!tree) return; int const entries = tree->GetEntries(); cout<<"number of entries "<<entries<<endl; TH1F *frame = new TH1F(); //const float norm_runs = 8.0; if(entries<8) const float norm_runs =10.0; else if(entries>=8&&entries<16) const float norm_runs =20.0; else const float norm_runs =50.0; int const canvas_width = int(((entries*1.0)/norm_runs)*2000.0); if(entries>50){ gStyle->SetTickLength(0.03*norm_runs/(entries*1.0),"Y"); gStyle->SetTitleYOffset((norm_runs/(entries*1.0))*0.8); gStyle->SetPadLeftMargin(0.1*norm_runs/(entries*1.0)); gStyle->SetPadRightMargin(0.1*norm_runs/(entries*1.0)); } //Define ranges of you trending plots double resolutionMin = 10, resolutionMax = 100; // OR A - OR C double oraplusorcMin = -100, oraplusorcMax = 100; // OR A + OR CA double oraMin = -100, oraMax = 100; // OR A double orcMin = -100, orcMax = 100; // OR C double amplMin =0, amplMax =3 ; // amplitude in each PMT double timeMin , timeMax ; // amplitude in each PMT //-----> add ranges of your new trending plot TCanvas *c1 = new TCanvas("can","can",canvas_width,500); c1->SetGridy(1); c1->SetGridx(1); c1->SetBottomMargin(0.17); /****** T0 ORA+ORC ******/ TGraphErrors *grSum = MakeGraphSparse(tree,"tzeroOrAPlusOrC:run",""); grSum->SetMarkerStyle(20); grSum->SetMarkerSize(1.0); grSum->SetMarkerColor(2); TGraphErrors *grORA = MakeGraphSparse(tree,"tzeroOrA:run",""); grORA->SetMarkerStyle(28); grORA->SetMarkerSize(1.0); grORA->SetMarkerColor(4); TGraphErrors *grORC = MakeGraphSparse(tree,"tzeroOrC:run",""); grORC->SetMarkerStyle(25); grORC->SetMarkerSize(1.0); grORC->SetMarkerColor(1); grSum->GetHistogram()->SetYTitle("mean [ps]"); grSum->GetHistogram()->SetTitle("T0 ORA, ORC and (ORA+ORC)/2"); grSum->GetHistogram()->SetMinimum(oraplusorcMin); grSum->GetHistogram()->SetMaximum(oraplusorcMax); grSum->Draw("AP"); grORA->Draw("psame"); grORC->Draw("psame"); TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);leg->SetColumnSeparation(1); leg->AddEntry(grORA,"ORA","p"); leg->AddEntry(grORC,"ORC","p"); leg->AddEntry(grSum,"(ORA+ORC)/2","p"); leg->Draw(); grSum->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrAPlusOrC_vs_run.gif"); /****** T0 Resolution ******/ TGraphErrors *gr = MakeGraphSparse(tree,"resolution:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetMinimum(resolutionMin); gr->GetHistogram()->SetMaximum(resolutionMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); gr->GetHistogram()->SetYTitle("sigma [ps]"); gr->GetHistogram()->SetTitle("T0 resolution (ORA -ORC)/2"); c1->SaveAs("sigmaResolutionT0_vs_run.gif"); /****** Mean T0 OR A ******/ /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrA:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetYTitle("mean [ps]"); gr->GetHistogram()->SetTitle("T0 OR A"); gr->GetHistogram()->SetMinimum(oraMin); gr->GetHistogram()->SetMaximum(oraMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrA_vs_run.gif"); */ /****** Mean T0 OR C ******/ /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrC:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetYTitle("mean [ps]"); gr->GetHistogram()->SetTitle("T0 OR C"); gr->GetHistogram()->SetMinimum(orcMin); gr->GetHistogram()->SetMaximum(orcMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrC_vs_run.gif"); */ /****** Mean Amplitude in PMT ******/ const int kNPMTs = 24; char name[200]; for(int ipmt=1;ipmt<=kNPMTs; ipmt++){ sprintf(name,"amplPMT%d:run",ipmt); gr = MakeGraphSparse(tree,name,""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(6); gr->GetHistogram()->SetYTitle("mean"); gr->GetHistogram()->SetTitle(Form("Amplitude PMT%d",ipmt)); int nRuns = gr->GetN(); double *y = gr->GetY(); double min = y[0]; double max = y[0]; for(int irun =1; irun<nRuns;irun++){ if(min > y[irun] & y[irun]>0) min = y[irun]; if(max < y[irun]) max = y[irun]; } // amplMin = min - 2; // amplMax = max + 2; gr->GetHistogram()->SetMinimum(amplMin); gr->GetHistogram()->SetMaximum(amplMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs(Form("meanAmplPMT%d_vs_run.gif",ipmt)); } /****** Mean Time in PMT ******/ for(int ipmt=1;ipmt<=kNPMTs; ipmt++){ sprintf(name,"timePMT%d:run",ipmt); gr = MakeGraphSparse(tree,name,""); sprintf(name,"timeDelayPMT%d:run",ipmt); TGraphErrors *grDelay = MakeGraphSparse(tree,name,""); //regular run int nRuns = gr->GetN(); double *y = gr->GetY(); double min = y[0]; double max = y[0]; for(int irun =1; irun<nRuns;irun++){ if(min > y[irun] && y[irun]>0) min = y[irun]; if(max < y[irun]) max = y[irun]; } //Delay // double *yDelay = grDelay->GetY(); // nRuns = grDelay->GetN(); // for(int irun =0; irun<nRuns;irun++){ // if(min > yDelay[irun] && yDelay[irun]>0) min = yDelay[irun]; // if(max < yDelay[irun]) max = yDelay[irun]; // } timeMin = min - 2; timeMax = max + 2; gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); grDelay->SetMarkerStyle(24); grDelay->SetMarkerSize(1.0); grDelay->SetMarkerColor(1); gr->GetHistogram()->SetYTitle("mean [channels]"); gr->GetHistogram()->SetTitle(Form("Time PMT%d",ipmt)); gr->GetHistogram()->SetMinimum(timeMin); gr->GetHistogram()->SetMaximum(timeMax); gr->GetXaxis()->LabelsOption("v"); gr->Draw("AP"); grDelay->Draw("Psame"); TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3); leg->AddEntry(gr,"mean time","p"); //leg->AddEntry(grDelay,"Time Delay OCDB","p"); leg->Draw(); c1->SaveAs(Form("meanTimePMT%d_vs_run.gif",ipmt)); } //-----> draw your new trending plot here } <commit_msg>set Yaxis range for CFD time trend<commit_after> TGraphErrors * MakeGraphSparse(TTree * tree, const Char_t * expr="mean-fdelta:run", const Char_t * cut="isTPC&&ptype==0&&theta>0"){ // Format of expr: Var:Error:Run // // Make a sparse draw of the variables // Format of expr : Var:Error:Run // const Int_t entries = tree->Draw(expr,cut,"goff"); Double_t *graphX, *graphY, *graphError; //check whether error argument exists in expr if(!tree->GetV3()){ graphX = tree->GetV2(); graphY = tree->GetV1(); } else{ graphX = tree->GetV3(); graphY = tree->GetV1(); graphError = tree->GetV2(); } // sort according to run number Int_t *index = new Int_t[entries]; TMath::Sort(entries,graphX,index,false); // define arrays for the new graph Double_t *tempArray = new Double_t[entries]; Double_t *xError = new Double_t[entries]; Double_t *yError = new Double_t[entries]; Int_t *vrun = new Int_t[entries]; Double_t count = 0.5; // evaluate arrays for the new graph accroding to the run-number Int_t icount=0; tempArray[index[0]] = count; xError[0] = 0; yError[0] = 0; if(tree->GetV3()) yError[index[0]] = graphError[index[0]]; vrun[0] = graphX[index[0]]; // loop the rest entries for(Int_t i=1;i<entries;i++){ xError[i] = 0; yError[i] = 0; if(tree->GetV3()) yError[i] = graphError[index[i]]; if(graphX[index[i]]==graphX[index[i-1]]) tempArray[index[i]] = count; else if((graphX[index[i]]!=graphX[index[i-1]])){ count++; icount++; tempArray[index[i]] = count; vrun[icount]=graphX[index[i]]; } } // count the number of xbins (run-wise) for the new graph const Int_t newNbins = int(count+0.5); Double_t *newBins = new Double_t[newNbins+1]; for(Int_t i=0; i<=count+1;i++){ newBins[i] = i; } // define and fill the new graph TGraphErrors *graphNew = new TGraphErrors(entries,tempArray,graphY,xError,yError); graphNew->GetXaxis()->Set(newNbins,newBins); // set the bins for the x-axis Char_t xName[50]; for(Int_t i=0;i<count;i++){ sprintf(xName,"%d",Int_t(vrun[i])); graphNew->GetXaxis()->SetBinLabel(i+1,xName); } graphNew->GetHistogram()->SetTitle(""); // memory clearing delete [] xError; delete [] yError; delete [] tempArray; delete [] index; delete [] newBins; delete [] vrun; return graphNew; } //------------------------------------------------------------------------------------------------ drawPerformanceT0QATrends(const char* inFile = "trending.root", const char* runType="pp") { // // gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetLabelSize(0.04,"x"); // open input file // TFile *file = TFile::Open(inFile); if(!file) return; file->cd(); TTree *tree = (TTree*)file->Get("trending"); if(!tree) return; int const entries = tree->GetEntries(); cout<<"number of entries "<<entries<<endl; TH1F *frame = new TH1F(); //const float norm_runs = 8.0; if(entries<8) const float norm_runs =10.0; else if(entries>=8&&entries<16) const float norm_runs =20.0; else const float norm_runs =50.0; int const canvas_width = int(((entries*1.0)/norm_runs)*2000.0); if(entries>50){ gStyle->SetTickLength(0.03*norm_runs/(entries*1.0),"Y"); gStyle->SetTitleYOffset((norm_runs/(entries*1.0))*0.8); gStyle->SetPadLeftMargin(0.1*norm_runs/(entries*1.0)); gStyle->SetPadRightMargin(0.1*norm_runs/(entries*1.0)); } //Define ranges of you trending plots double resolutionMin = 10, resolutionMax = 100; // OR A - OR C double oraplusorcMin = -100, oraplusorcMax = 100; // OR A + OR CA double oraMin = -100, oraMax = 100; // OR A double orcMin = -100, orcMax = 100; // OR C double amplMin =0, amplMax =3 ; // amplitude in each PMT double timeMin = 2900, timeMax =3300 ; // amplitude in each PMT //-----> add ranges of your new trending plot TCanvas *c1 = new TCanvas("can","can",canvas_width,500); c1->SetGridy(1); c1->SetGridx(1); c1->SetBottomMargin(0.17); /****** T0 ORA+ORC ******/ TGraphErrors *grSum = MakeGraphSparse(tree,"tzeroOrAPlusOrC:run",""); grSum->SetMarkerStyle(20); grSum->SetMarkerSize(1.0); grSum->SetMarkerColor(2); TGraphErrors *grORA = MakeGraphSparse(tree,"tzeroOrA:run",""); grORA->SetMarkerStyle(28); grORA->SetMarkerSize(1.0); grORA->SetMarkerColor(4); TGraphErrors *grORC = MakeGraphSparse(tree,"tzeroOrC:run",""); grORC->SetMarkerStyle(25); grORC->SetMarkerSize(1.0); grORC->SetMarkerColor(1); grSum->GetHistogram()->SetYTitle("mean [ps]"); grSum->GetHistogram()->SetTitle("T0 ORA, ORC and (ORA+ORC)/2"); grSum->GetHistogram()->SetMinimum(oraplusorcMin); grSum->GetHistogram()->SetMaximum(oraplusorcMax); grSum->Draw("AP"); grORA->Draw("psame"); grORC->Draw("psame"); TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);leg->SetColumnSeparation(1); leg->AddEntry(grORA,"ORA","p"); leg->AddEntry(grORC,"ORC","p"); leg->AddEntry(grSum,"(ORA+ORC)/2","p"); leg->Draw(); grSum->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrAPlusOrC_vs_run.gif"); /****** T0 Resolution ******/ TGraphErrors *gr = MakeGraphSparse(tree,"resolution:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetMinimum(resolutionMin); gr->GetHistogram()->SetMaximum(resolutionMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); gr->GetHistogram()->SetYTitle("sigma [ps]"); gr->GetHistogram()->SetTitle("T0 resolution (ORA -ORC)/2"); c1->SaveAs("sigmaResolutionT0_vs_run.gif"); /****** Mean T0 OR A ******/ /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrA:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetYTitle("mean [ps]"); gr->GetHistogram()->SetTitle("T0 OR A"); gr->GetHistogram()->SetMinimum(oraMin); gr->GetHistogram()->SetMaximum(oraMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrA_vs_run.gif"); */ /****** Mean T0 OR C ******/ /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrC:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetYTitle("mean [ps]"); gr->GetHistogram()->SetTitle("T0 OR C"); gr->GetHistogram()->SetMinimum(orcMin); gr->GetHistogram()->SetMaximum(orcMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrC_vs_run.gif"); */ /****** Mean Amplitude in PMT ******/ const int kNPMTs = 24; char name[200]; for(int ipmt=1;ipmt<=kNPMTs; ipmt++){ sprintf(name,"amplPMT%d:run",ipmt); gr = MakeGraphSparse(tree,name,""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(6); gr->GetHistogram()->SetYTitle("mean"); gr->GetHistogram()->SetTitle(Form("Amplitude PMT%d",ipmt)); int nRuns = gr->GetN(); double *y = gr->GetY(); double min = y[0]; double max = y[0]; for(int irun =1; irun<nRuns;irun++){ if(min > y[irun] & y[irun]>0) min = y[irun]; if(max < y[irun]) max = y[irun]; } // amplMin = min - 2; // amplMax = max + 2; gr->GetHistogram()->SetMinimum(amplMin); gr->GetHistogram()->SetMaximum(amplMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); c1->SaveAs(Form("meanAmplPMT%d_vs_run.gif",ipmt)); } /****** Mean Time in PMT ******/ for(int ipmt=1;ipmt<=kNPMTs; ipmt++){ sprintf(name,"timePMT%d:run",ipmt); gr = MakeGraphSparse(tree,name,""); sprintf(name,"timeDelayPMT%d:run",ipmt); TGraphErrors *grDelay = MakeGraphSparse(tree,name,""); //regular run int nRuns = gr->GetN(); double *y = gr->GetY(); double min = y[0]; double max = y[0]; for(int irun =1; irun<nRuns;irun++){ if(min > y[irun] && y[irun]>0) min = y[irun]; if(max < y[irun]) max = y[irun]; } //Delay // double *yDelay = grDelay->GetY(); // nRuns = grDelay->GetN(); // for(int irun =0; irun<nRuns;irun++){ // if(min > yDelay[irun] && yDelay[irun]>0) min = yDelay[irun]; // if(max < yDelay[irun]) max = yDelay[irun]; // } // timeMin = min - 2; // timeMax = max + 2; gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); grDelay->SetMarkerStyle(24); grDelay->SetMarkerSize(1.0); grDelay->SetMarkerColor(1); gr->GetHistogram()->SetYTitle("mean [channels]"); gr->GetHistogram()->SetTitle(Form("Time PMT%d",ipmt)); gr->GetHistogram()->SetMinimum(timeMin); gr->GetHistogram()->SetMaximum(timeMax); gr->GetXaxis()->LabelsOption("v"); gr->Draw("AP"); grDelay->Draw("Psame"); TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3); leg->AddEntry(gr,"mean time","p"); //leg->AddEntry(grDelay,"Time Delay OCDB","p"); leg->Draw(); c1->SaveAs(Form("meanTimePMT%d_vs_run.gif",ipmt)); } //-----> draw your new trending plot here } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkKitwareContourFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkKitwareContourFilter.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkContourValues.h" #include "vtkGridSynchronizedTemplates3D.h" #include "vtkImageData.h" #include "vtkMergePoints.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" #include "vtkRectilinearSynchronizedTemplates.h" #include "vtkScalarTree.h" #include "vtkStructuredGrid.h" #include "vtkSynchronizedTemplates2D.h" #include "vtkSynchronizedTemplates3D.h" #include <math.h> vtkCxxRevisionMacro(vtkKitwareContourFilter, "1.37"); vtkStandardNewMacro(vtkKitwareContourFilter); // Construct object with initial range (0,1) and single contour value // of 0.0. vtkKitwareContourFilter::vtkKitwareContourFilter() { this->ArrayComponent = 0; } vtkKitwareContourFilter::~vtkKitwareContourFilter() { } int vtkKitwareContourFilter::ComputeInputUpdateExtent( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkInformation* info = outputVector->GetInformationObject(0); vtkDataSet *output = vtkDataSet::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); if (!input || !output) { return 0; } int inputObjectType = input->GetDataObjectType(); if ( inputObjectType == VTK_STRUCTURED_POINTS || inputObjectType == VTK_IMAGE_DATA ) { int ext[6], dims[3], dim=0; ((vtkImageData *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { dims[j] = ext[2*j+1]-ext[2*j]; if ( dims[j] != 0 ) { dim++; } } if ((dim == 2) && (dims[2] == 0)) { vtkSynchronizedTemplates2D *syncTemp2D = vtkSynchronizedTemplates2D::New(); syncTemp2D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp2D->SetDebug(this->Debug); syncTemp2D->ComputeInputUpdateExtents(output); syncTemp2D->Delete(); return 1; } else if (dim == 3) { vtkSynchronizedTemplates3D *syncTemp3D = vtkSynchronizedTemplates3D::New(); syncTemp3D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp3D->SetDebug(this->Debug); syncTemp3D->SetComputeNormals (this->ComputeNormals); syncTemp3D->SetComputeGradients (this->ComputeGradients); syncTemp3D->SetComputeScalars (this->ComputeScalars); syncTemp3D->ComputeInputUpdateExtents(output); syncTemp3D->Delete(); return 1; } } if ( inputObjectType == VTK_STRUCTURED_GRID ) { int ext[6], dim=0; ((vtkStructuredGrid *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { if ( ( ext[2*j+1]-ext[2*j] ) != 0 ) { dim++; } } if (dim == 3) { vtkGridSynchronizedTemplates3D *gridTemp3D = vtkGridSynchronizedTemplates3D::New(); gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input)); gridTemp3D->SetComputeNormals (this->ComputeNormals); gridTemp3D->SetComputeGradients (this->ComputeGradients); gridTemp3D->SetComputeScalars (this->ComputeScalars); gridTemp3D->SetDebug(this->Debug); gridTemp3D->ComputeInputUpdateExtents(output); gridTemp3D->Delete(); return 1; } } if ( inputObjectType == VTK_RECTILINEAR_GRID ) { int ext[6], dim=0; ((vtkRectilinearGrid *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { if ( ( ext[2*j+1]-ext[2*j] ) != 0 ) { dim++; } } if (dim == 3) { vtkRectilinearSynchronizedTemplates *rTemp = vtkRectilinearSynchronizedTemplates::New(); rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input)); rTemp->SetComputeNormals (this->ComputeNormals); rTemp->SetComputeGradients (this->ComputeGradients); rTemp->SetComputeScalars (this->ComputeScalars); rTemp->SetDebug(this->Debug); rTemp->ComputeInputUpdateExtents(output); rTemp->Delete(); return 1; } } return this->Superclass::ComputeInputUpdateExtent(request, inputVector, outputVector); } // // General contouring filter. Handles arbitrary input. // int vtkKitwareContourFilter::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) {return 0;} vtkDataArray *inScalars; vtkIdType numCells; vtkDebugMacro(<< "Executing contour filter"); numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection); if ( ! inScalars || numCells < 1 ) { // vtkErrorMacro(<<"No data to contour"); return 0; } // If structured points and structured grid, use more efficient algorithms if ( input->GetDataObjectType() == VTK_STRUCTURED_POINTS || input->GetDataObjectType() == VTK_IMAGE_DATA ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } if ( dim >= 2 ) { this->StructuredPointsContour(dim, input); return 1; } } if ( input->GetDataObjectType() == VTK_STRUCTURED_GRID ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } // only do 3D structured grids (to be extended in the future) if ( dim == 3 ) { this->StructuredGridContour(dim, input); return 1; } } if ( input->GetDataObjectType() == VTK_RECTILINEAR_GRID ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } if ( dim == 3 ) { this->RectilinearGridContour(dim, input); return 1; } } // otherwise just use the normal one return this->Superclass::RequestData(request, inputVector, outputVector); } // // Special method handles structured points // void vtkKitwareContourFilter::StructuredPointsContour(int dim, vtkDataSet* input) { vtkPolyData *output; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 2 ) { vtkSynchronizedTemplates2D *syncTemp2D; int i; syncTemp2D = vtkSynchronizedTemplates2D::New(); syncTemp2D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp2D->SetDebug(this->Debug); syncTemp2D->SetNumberOfContours(numContours); syncTemp2D->SetArrayComponent(this->ArrayComponent); for (i=0; i < numContours; i++) { syncTemp2D->SetValue(i,values[i]); } syncTemp2D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(), thisOutput->GetUpdateNumberOfPieces(), thisOutput->GetUpdateGhostLevel()); syncTemp2D->SelectInputScalars(this->InputScalarsSelection); syncTemp2D->Update(); output = syncTemp2D->GetOutput(); output->Register(this); syncTemp2D->Delete(); } else { vtkSynchronizedTemplates3D *syncTemp3D; int i; syncTemp3D = vtkSynchronizedTemplates3D::New(); syncTemp3D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp3D->SetComputeNormals (this->ComputeNormals); syncTemp3D->SetComputeGradients (this->ComputeGradients); syncTemp3D->SetComputeScalars (this->ComputeScalars); syncTemp3D->SetDebug(this->Debug); syncTemp3D->SetNumberOfContours(numContours); syncTemp3D->SetArrayComponent(this->ArrayComponent); for (i=0; i < numContours; i++) { syncTemp3D->SetValue(i,values[i]); } syncTemp3D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(), thisOutput->GetUpdateNumberOfPieces(), thisOutput->GetUpdateGhostLevel()); syncTemp3D->SelectInputScalars(this->InputScalarsSelection); syncTemp3D->Update(); output = syncTemp3D->GetOutput(); output->Register(this); syncTemp3D->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } // // Special method handles structured grids // void vtkKitwareContourFilter::StructuredGridContour(int dim, vtkDataSet* input) { vtkPolyData *output = NULL; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 3 ) { vtkGridSynchronizedTemplates3D *gridTemp3D; int i; gridTemp3D = vtkGridSynchronizedTemplates3D::New(); gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input)); gridTemp3D->SetComputeNormals (this->ComputeNormals); gridTemp3D->SetComputeGradients (this->ComputeGradients); gridTemp3D->SetComputeScalars (this->ComputeScalars); gridTemp3D->SetDebug(this->Debug); gridTemp3D->SetNumberOfContours(numContours); for (i=0; i < numContours; i++) { gridTemp3D->SetValue(i,values[i]); } output = gridTemp3D->GetOutput(); output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces()); output->SetUpdatePiece(thisOutput->GetUpdatePiece()); output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel()); gridTemp3D->SelectInputScalars(this->InputScalarsSelection); gridTemp3D->Update(); output->Register(this); gridTemp3D->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } // // Special method handles rectilinear grids // void vtkKitwareContourFilter::RectilinearGridContour(int dim, vtkDataSet* input) { vtkPolyData *output = NULL; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 3 ) { vtkRectilinearSynchronizedTemplates *rTemp; int i; rTemp = vtkRectilinearSynchronizedTemplates::New(); rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input)); rTemp->SetComputeNormals (this->ComputeNormals); rTemp->SetComputeGradients (this->ComputeGradients); rTemp->SetComputeScalars (this->ComputeScalars); rTemp->SetDebug(this->Debug); rTemp->SetNumberOfContours(numContours); for (i=0; i < numContours; i++) { rTemp->SetValue(i,values[i]); } output = rTemp->GetOutput(); output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces()); output->SetUpdatePiece(thisOutput->GetUpdatePiece()); output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel()); rTemp->SelectInputScalars(this->InputScalarsSelection); rTemp->Update(); output->Register(this); rTemp->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } //---------------------------------------------------------------------------- void vtkKitwareContourFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "ArrayComponent: " << this->ArrayComponent << endl; } <commit_msg>BUG: Extremely subtle bug. The logic in ComputeInputUpdateExtent to choose which internal filter to use must match the logic in RequestData.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkKitwareContourFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkKitwareContourFilter.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkContourValues.h" #include "vtkGridSynchronizedTemplates3D.h" #include "vtkImageData.h" #include "vtkMergePoints.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" #include "vtkRectilinearSynchronizedTemplates.h" #include "vtkScalarTree.h" #include "vtkStructuredGrid.h" #include "vtkSynchronizedTemplates2D.h" #include "vtkSynchronizedTemplates3D.h" #include <math.h> vtkCxxRevisionMacro(vtkKitwareContourFilter, "1.38"); vtkStandardNewMacro(vtkKitwareContourFilter); // Construct object with initial range (0,1) and single contour value // of 0.0. vtkKitwareContourFilter::vtkKitwareContourFilter() { this->ArrayComponent = 0; } vtkKitwareContourFilter::~vtkKitwareContourFilter() { } int vtkKitwareContourFilter::ComputeInputUpdateExtent( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkInformation* info = outputVector->GetInformationObject(0); vtkDataSet *output = vtkDataSet::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); if (!input || !output) { return 0; } int inputObjectType = input->GetDataObjectType(); if ( inputObjectType == VTK_STRUCTURED_POINTS || inputObjectType == VTK_IMAGE_DATA ) { int ext[6], dims[3], dim=0; ((vtkImageData *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { dims[j] = ext[2*j+1]-ext[2*j]; if ( dims[j] != 0 ) { dim++; } } if (dim == 2) { vtkSynchronizedTemplates2D *syncTemp2D = vtkSynchronizedTemplates2D::New(); syncTemp2D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp2D->SetDebug(this->Debug); syncTemp2D->ComputeInputUpdateExtents(output); syncTemp2D->Delete(); return 1; } else if (dim == 3) { vtkSynchronizedTemplates3D *syncTemp3D = vtkSynchronizedTemplates3D::New(); syncTemp3D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp3D->SetDebug(this->Debug); syncTemp3D->SetComputeNormals (this->ComputeNormals); syncTemp3D->SetComputeGradients (this->ComputeGradients); syncTemp3D->SetComputeScalars (this->ComputeScalars); syncTemp3D->ComputeInputUpdateExtents(output); syncTemp3D->Delete(); return 1; } } if ( inputObjectType == VTK_STRUCTURED_GRID ) { int ext[6], dim=0; ((vtkStructuredGrid *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { if ( ( ext[2*j+1]-ext[2*j] ) != 0 ) { dim++; } } if (dim == 3) { vtkGridSynchronizedTemplates3D *gridTemp3D = vtkGridSynchronizedTemplates3D::New(); gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input)); gridTemp3D->SetComputeNormals (this->ComputeNormals); gridTemp3D->SetComputeGradients (this->ComputeGradients); gridTemp3D->SetComputeScalars (this->ComputeScalars); gridTemp3D->SetDebug(this->Debug); gridTemp3D->ComputeInputUpdateExtents(output); gridTemp3D->Delete(); return 1; } } if ( inputObjectType == VTK_RECTILINEAR_GRID ) { int ext[6], dim=0; ((vtkRectilinearGrid *)input)->GetWholeExtent(ext); for(int j=0; j<3; j++) { if ( ( ext[2*j+1]-ext[2*j] ) != 0 ) { dim++; } } if (dim == 3) { vtkRectilinearSynchronizedTemplates *rTemp = vtkRectilinearSynchronizedTemplates::New(); rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input)); rTemp->SetComputeNormals (this->ComputeNormals); rTemp->SetComputeGradients (this->ComputeGradients); rTemp->SetComputeScalars (this->ComputeScalars); rTemp->SetDebug(this->Debug); rTemp->ComputeInputUpdateExtents(output); rTemp->Delete(); return 1; } } return this->Superclass::ComputeInputUpdateExtent(request, inputVector, outputVector); } // // General contouring filter. Handles arbitrary input. // int vtkKitwareContourFilter::RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (!input) {return 0;} vtkDataArray *inScalars; vtkIdType numCells; vtkDebugMacro(<< "Executing contour filter"); numCells = input->GetNumberOfCells(); inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection); if ( ! inScalars || numCells < 1 ) { // vtkErrorMacro(<<"No data to contour"); return 0; } // If structured points and structured grid, use more efficient algorithms if ( input->GetDataObjectType() == VTK_STRUCTURED_POINTS || input->GetDataObjectType() == VTK_IMAGE_DATA ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } if ( dim >= 2 ) { this->StructuredPointsContour(dim, input); return 1; } } if ( input->GetDataObjectType() == VTK_STRUCTURED_GRID ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } // only do 3D structured grids (to be extended in the future) if ( dim == 3 ) { this->StructuredGridContour(dim, input); return 1; } } if ( input->GetDataObjectType() == VTK_RECTILINEAR_GRID ) { int dim = 3; int *uExt = input->GetUpdateExtent(); if (uExt[0] == uExt[1]) { --dim; } if (uExt[2] == uExt[3]) { --dim; } if (uExt[4] == uExt[5]) { --dim; } if ( dim == 3 ) { this->RectilinearGridContour(dim, input); return 1; } } // otherwise just use the normal one return this->Superclass::RequestData(request, inputVector, outputVector); } // // Special method handles structured points // void vtkKitwareContourFilter::StructuredPointsContour(int dim, vtkDataSet* input) { vtkPolyData *output; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 2 ) { vtkSynchronizedTemplates2D *syncTemp2D; int i; syncTemp2D = vtkSynchronizedTemplates2D::New(); syncTemp2D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp2D->SetDebug(this->Debug); syncTemp2D->SetNumberOfContours(numContours); syncTemp2D->SetArrayComponent(this->ArrayComponent); for (i=0; i < numContours; i++) { syncTemp2D->SetValue(i,values[i]); } syncTemp2D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(), thisOutput->GetUpdateNumberOfPieces(), thisOutput->GetUpdateGhostLevel()); syncTemp2D->SelectInputScalars(this->InputScalarsSelection); syncTemp2D->Update(); output = syncTemp2D->GetOutput(); output->Register(this); syncTemp2D->Delete(); } else { vtkSynchronizedTemplates3D *syncTemp3D; int i; syncTemp3D = vtkSynchronizedTemplates3D::New(); syncTemp3D->SetInput(vtkImageData::SafeDownCast(input)); syncTemp3D->SetComputeNormals (this->ComputeNormals); syncTemp3D->SetComputeGradients (this->ComputeGradients); syncTemp3D->SetComputeScalars (this->ComputeScalars); syncTemp3D->SetDebug(this->Debug); syncTemp3D->SetNumberOfContours(numContours); syncTemp3D->SetArrayComponent(this->ArrayComponent); for (i=0; i < numContours; i++) { syncTemp3D->SetValue(i,values[i]); } syncTemp3D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(), thisOutput->GetUpdateNumberOfPieces(), thisOutput->GetUpdateGhostLevel()); syncTemp3D->SelectInputScalars(this->InputScalarsSelection); syncTemp3D->Update(); output = syncTemp3D->GetOutput(); output->Register(this); syncTemp3D->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } // // Special method handles structured grids // void vtkKitwareContourFilter::StructuredGridContour(int dim, vtkDataSet* input) { vtkPolyData *output = NULL; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 3 ) { vtkGridSynchronizedTemplates3D *gridTemp3D; int i; gridTemp3D = vtkGridSynchronizedTemplates3D::New(); gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input)); gridTemp3D->SetComputeNormals (this->ComputeNormals); gridTemp3D->SetComputeGradients (this->ComputeGradients); gridTemp3D->SetComputeScalars (this->ComputeScalars); gridTemp3D->SetDebug(this->Debug); gridTemp3D->SetNumberOfContours(numContours); for (i=0; i < numContours; i++) { gridTemp3D->SetValue(i,values[i]); } output = gridTemp3D->GetOutput(); output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces()); output->SetUpdatePiece(thisOutput->GetUpdatePiece()); output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel()); gridTemp3D->SelectInputScalars(this->InputScalarsSelection); gridTemp3D->Update(); output->Register(this); gridTemp3D->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } // // Special method handles rectilinear grids // void vtkKitwareContourFilter::RectilinearGridContour(int dim, vtkDataSet* input) { vtkPolyData *output = NULL; vtkPolyData *thisOutput = this->GetOutput(); int numContours=this->ContourValues->GetNumberOfContours(); double *values=this->ContourValues->GetValues(); if ( dim == 3 ) { vtkRectilinearSynchronizedTemplates *rTemp; int i; rTemp = vtkRectilinearSynchronizedTemplates::New(); rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input)); rTemp->SetComputeNormals (this->ComputeNormals); rTemp->SetComputeGradients (this->ComputeGradients); rTemp->SetComputeScalars (this->ComputeScalars); rTemp->SetDebug(this->Debug); rTemp->SetNumberOfContours(numContours); for (i=0; i < numContours; i++) { rTemp->SetValue(i,values[i]); } output = rTemp->GetOutput(); output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces()); output->SetUpdatePiece(thisOutput->GetUpdatePiece()); output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel()); rTemp->SelectInputScalars(this->InputScalarsSelection); rTemp->Update(); output->Register(this); rTemp->Delete(); } thisOutput->CopyStructure(output); thisOutput->GetPointData()->ShallowCopy(output->GetPointData()); thisOutput->GetCellData()->ShallowCopy(output->GetCellData()); output->UnRegister(this); } //---------------------------------------------------------------------------- void vtkKitwareContourFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "ArrayComponent: " << this->ArrayComponent << endl; } <|endoftext|>
<commit_before>#include "Host.h" #include <math.h> // ceil static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number static const int DATA_PKT_SIZE = 1; // TODO: change this number Host::Host(CongestionAlg congestion_algorithm , Link &host_link) : my_link(host_link) { window_size = INITIAL_WINDOW_SIZE; congestion_alg = congestion_algorithm; my_link = host_link; packet_id = 0; unack_packets = 0; } void Host::addFlow(std::string dest, float data_size) { float temp_num_pkts = data_size / DATA_PKT_SIZE; int num_packets = (int) ceil(temp_num_pkts); std::queue<Packet> flow; for (int count = 0; count < num_packets; count++){ std::string pack_id = this->uuid + std::to_string(packet_id); Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1); flow.push(new_packet); packet_id++; } packet_queue.addQueue(flow); } void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event) { // Create queue of packets for host to make events out of addFlow(flow_event->destination, flow_event->data_size); // Create PacketEvents based on queue of packets based on // number of unacknowledged packets int num_events = window_size - unack_packets; int time_now = flow_event->eventTime(); // push PacketEvents onto eventheap for (int pck = 1; pck <= num_events; pck++) { Packet new_pack = packet_queue.pop(); time_now += float(new_pack.size) / throughput; PacketEvent packetEvent = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now); eventHeap.push(packetEvent); unack_packets++; } } void Host::giveEvent(std::unique_ptr<PacketEvent> new_event) { if (new_event->type == ackPacket) { Packet new_packet = new_event->packet; std::string source = new_event->source; float now = new_event->eventTime(); } } <commit_msg>passing host to Anish<commit_after>#include "Host.h" #include <math.h> // ceil static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number static const int DATA_PKT_SIZE = 1; // TODO: change this number Host::Host(CongestionAlg congestion_algorithm , Link &host_link) : my_link(host_link) { window_size = INITIAL_WINDOW_SIZE; congestion_alg = congestion_algorithm; my_link = host_link; packet_id = 0; unack_packets = 0; } void Host::addFlow(std::string dest, float data_size) { float temp_num_pkts = data_size / DATA_PKT_SIZE; int num_packets = (int) ceil(temp_num_pkts); std::queue<Packet> flow; for (int count = 0; count < num_packets; count++){ std::string pack_id = this->uuid + std::to_string(packet_id); Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1); flow.push(new_packet); packet_id++; } packet_queue.addQueue(flow); } void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event) { // Create queue of packets for host to make events out of addFlow(flow_event->destination, flow_event->data_size); // Create PacketEvents based on queue of packets based on // number of unacknowledged packets int num_events = window_size - unack_packets; int time_now = flow_event->eventTime(); // push PacketEvents onto eventheap for (int pck = 1; pck <= num_events; pck++) { Packet new_pack = packet_queue.pop(); time_now += float(new_pack.size) / throughput; PacketEvent packetEvent = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now); eventHeap.push(packetEvent); unack_packets++; } } void Host::giveEvent(std::unique_ptr<PacketEvent> new_event) { Packet pkt = new_event->packet; if (pkt.ack) { Packet new_packet = new_event->packet; std::string source = new_event->source; float now = new_event->eventTime(); } else if (<#condition#>) } <|endoftext|>
<commit_before>/* * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "hybrid_automaton/ForceTorqueSensor.h" namespace ha { HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor); ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT) { } ForceTorqueSensor::~ForceTorqueSensor() { } ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss) :Sensor(ss) { _port = ss._port; } ::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const { ::Eigen::Matrix3d frameRot = transform.block(0,0,3,3); ::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3)); ::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0)); ::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0)); forcePart = frameRot*forcePart; momentPart = frameRot*(momentPart - frameTrans.cross(forcePart)); Eigen::MatrixXd wrenchOut(6,1); wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2); wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2); return wrenchOut; } ::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const { //This is the F/T wrench from the hardware - It must be in EE frame ::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(DEFAULT_FT_PORT); ::Eigen::MatrixXd eeFrame = _system->getFramePose("EE"); //Transform FT wrench to world frame Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse()); //Transform FT wrench to given frame ftOut = transformWrench(forceTorque, _frame); return ftOut; } DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const { DescriptionTreeNode::Ptr tree = factory->createNode("Sensor"); tree->setAttribute<std::string>(std::string("type"), this->getType()); tree->setAttribute<int>(std::string("port"), _port); return tree; } void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha) { if (tree->getType() != "Sensor") { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!"); } tree->getAttribute<std::string>("type", _type, ""); tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT); if(_port > 2 || _port <0) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " " << "invalid - it must be between 0 and 2!"); } if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' " << "invalid - empty or not registered with HybridAutomaton!"); } _frame.resize(4,4); _frame.setIdentity(); if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame)) { HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in"); if(_frame.cols()!=4 || _frame.rows()!=4) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!"); } } _system = system; } } <commit_msg>tmp commit - still not working<commit_after>/* * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "hybrid_automaton/ForceTorqueSensor.h" namespace ha { HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor); ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT) { } ForceTorqueSensor::~ForceTorqueSensor() { } ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss) :Sensor(ss) { _port = ss._port; } ::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const { ::Eigen::Matrix3d frameRot = transform.block(0,0,3,3); ::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3)); ::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0)); ::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0)); forcePart = frameRot*forcePart; momentPart = frameRot*(momentPart - frameTrans.cross(forcePart)); Eigen::MatrixXd wrenchOut(6,1); wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2); wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2); return wrenchOut; } int k; ::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const { //This is the F/T wrench from the hardware - It must be in EE frame ::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(_port); ::Eigen::MatrixXd eeFrame = _system->getFramePose("EE"); //Transform FT wrench to world frame Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse()); //Transform FT wrench to given frame ftOut = transformWrench(ftOut, _frame); if((k++)%2000 == 0) HA_INFO("ForceTorqueSensor.getCurrentValue","ftout: "<<ftOut.transpose()); return ftOut; } DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const { DescriptionTreeNode::Ptr tree = factory->createNode("Sensor"); tree->setAttribute<std::string>(std::string("type"), this->getType()); tree->setAttribute<int>(std::string("port"), _port); return tree; } void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha) { if (tree->getType() != "Sensor") { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!"); } tree->getAttribute<std::string>("type", _type, ""); tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT); if(_port > 2 || _port <0) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " " << "invalid - it must be between 0 and 2!"); } if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' " << "invalid - empty or not registered with HybridAutomaton!"); } _frame.resize(4,4); _frame.setIdentity(); if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame)) { HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in"); if(_frame.cols()!=4 || _frame.rows()!=4) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!"); } } _system = system; } } <|endoftext|>
<commit_before>#include "GameController.h" #include "Tools/Debug/DebugRequest.h" #include <Representations/Infrastructure/Configuration.h> #include <PlatformInterface/Platform.h> GameController::GameController() : lastChestButtonEventCounter(0) { DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false); DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false); DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false); DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false); DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false); loadPlayerInfoFromFile(); } void GameController::loadPlayerInfoFromFile() { // load player.cfg naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration; if (config.hasKey("player", "NumOfPlayer")) { getPlayerInfo().numOfPlayers = config.getInt("player", "NumOfPlayer"); } else { std::cerr << "No number of players (NumOfPlayers) given" << std::endl; } if (config.hasKey("player", "PlayerNumber")) { getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber"); } else { std::cerr << "No player number (PlayerNumber) given" << std::endl; getPlayerInfo().playerNumber = 3; } if (config.hasKey("player", "TeamColor")) { getPlayerInfo().teamColor = PlayerInfo::teamColorFromString(config.getString("player", "TeamColor")); if (getPlayerInfo().teamColor == PlayerInfo::numOfTeamColor) { getPlayerInfo().teamColor = PlayerInfo::red; std::cerr << "Invalid team color (TeamColor) \"" << config.getString("player", "TeamColor") << "\" given" << std::endl; } } else { std::cerr << "No team color (TeamColor) given" << std::endl; getPlayerInfo().teamColor = PlayerInfo::red; } if (config.hasKey("player", "TeamNumber")) { getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber"); } else { std::cerr << "No team number (TeamNumber) given" << std::endl; getPlayerInfo().teamNumber = 0; } } // end loadPlayerInfoFromFile void GameController::readButtons() { // state change? if (getButtonData().eventCounter[ButtonData::Chest] > lastChestButtonEventCounter ) { lastChestButtonEventCounter = getButtonData().eventCounter[ButtonData::Chest]; switch (getPlayerInfo().gameState) { case PlayerInfo::inital : getPlayerInfo().gameState = PlayerInfo::penalized; break; case PlayerInfo::playing : getPlayerInfo().gameState = PlayerInfo::penalized; break; case PlayerInfo::penalized : getPlayerInfo().gameState = PlayerInfo::playing; break; default: break; } } // re-set team color or kickoff in initial if (getPlayerInfo().gameState == PlayerInfo::inital) { if (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] == 1 || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] == 1) { // switch team color PlayerInfo::TeamColor oldColor = getPlayerInfo().teamColor; if (oldColor == PlayerInfo::blue) { getPlayerInfo().teamColor = PlayerInfo::red; } else if (oldColor == PlayerInfo::red) { getPlayerInfo().teamColor = PlayerInfo::blue; } } if (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] == 1 || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] == 1) { // switch kickof team getPlayerInfo().ownKickOff = !getPlayerInfo().ownKickOff; } } // go back from penalized to initial both foot bumpers are pressed for over 30 frames else if (getPlayerInfo() .gameState == PlayerInfo::penalized && (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] > 30 || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] > 30 ) && (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] > 30 || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] > 30 ) ) { getPlayerInfo().gameState = PlayerInfo::inital; } } // end readButtons void GameController::readWLAN() { // TODO: WLAN GameController support } void GameController::execute() { PlayerInfo::GameState oldState = getPlayerInfo().gameState; PlayerInfo::TeamColor oldTeamColor = getPlayerInfo().teamColor; bool oldOwnKickOff = getPlayerInfo().ownKickOff; readButtons(); DEBUG_REQUEST("gamecontroller:initial", getPlayerInfo().gameState = PlayerInfo::inital; ); DEBUG_REQUEST("gamecontroller:ready", getPlayerInfo().gameState = PlayerInfo::ready; ); DEBUG_REQUEST("gamecontroller:set", getPlayerInfo().gameState = PlayerInfo::set; ); DEBUG_REQUEST("gamecontroller:play", getPlayerInfo().gameState = PlayerInfo::playing; ); DEBUG_REQUEST("gamecontroller:penalized", getPlayerInfo().gameState = PlayerInfo::penalized; ); } // end execute void GameController::updateLEDs() { // reset getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0; // show game state in torso switch (getPlayerInfo().gameState) { case PlayerInfo::ready : std::cout << "in ready" << std::endl; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0; break; case PlayerInfo::set : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0; break; case PlayerInfo::playing : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0; break; case PlayerInfo::penalized : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0; break; default: break; } // show team color on left foot if (getPlayerInfo().teamColor == PlayerInfo::red) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0; } else if (getPlayerInfo().teamColor == PlayerInfo::blue) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0; } // show kickoff state on right foot in initial, ready and set if (getPlayerInfo().gameState == PlayerInfo::inital || getPlayerInfo().gameState == PlayerInfo::ready || getPlayerInfo().gameState == PlayerInfo::set) { if (getPlayerInfo().ownKickOff) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0; } } } // end updateLEDs GameController::~GameController() { } <commit_msg>updateLEDs<commit_after>#include "GameController.h" #include "Tools/Debug/DebugRequest.h" #include <Representations/Infrastructure/Configuration.h> #include <PlatformInterface/Platform.h> GameController::GameController() : lastChestButtonEventCounter(0) { DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false); DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false); DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false); DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false); DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false); loadPlayerInfoFromFile(); } void GameController::loadPlayerInfoFromFile() { // load player.cfg naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration; if (config.hasKey("player", "NumOfPlayer")) { getPlayerInfo().numOfPlayers = config.getInt("player", "NumOfPlayer"); } else { std::cerr << "No number of players (NumOfPlayers) given" << std::endl; } if (config.hasKey("player", "PlayerNumber")) { getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber"); } else { std::cerr << "No player number (PlayerNumber) given" << std::endl; getPlayerInfo().playerNumber = 3; } if (config.hasKey("player", "TeamColor")) { getPlayerInfo().teamColor = PlayerInfo::teamColorFromString(config.getString("player", "TeamColor")); if (getPlayerInfo().teamColor == PlayerInfo::numOfTeamColor) { getPlayerInfo().teamColor = PlayerInfo::red; std::cerr << "Invalid team color (TeamColor) \"" << config.getString("player", "TeamColor") << "\" given" << std::endl; } } else { std::cerr << "No team color (TeamColor) given" << std::endl; getPlayerInfo().teamColor = PlayerInfo::red; } if (config.hasKey("player", "TeamNumber")) { getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber"); } else { std::cerr << "No team number (TeamNumber) given" << std::endl; getPlayerInfo().teamNumber = 0; } } // end loadPlayerInfoFromFile void GameController::readButtons() { // state change? if (getButtonData().eventCounter[ButtonData::Chest] > lastChestButtonEventCounter ) { lastChestButtonEventCounter = getButtonData().eventCounter[ButtonData::Chest]; switch (getPlayerInfo().gameState) { case PlayerInfo::inital : getPlayerInfo().gameState = PlayerInfo::penalized; break; case PlayerInfo::playing : getPlayerInfo().gameState = PlayerInfo::penalized; break; case PlayerInfo::penalized : getPlayerInfo().gameState = PlayerInfo::playing; break; default: break; } } // re-set team color or kickoff in initial if (getPlayerInfo().gameState == PlayerInfo::inital) { if (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] == 1 || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] == 1) { // switch team color PlayerInfo::TeamColor oldColor = getPlayerInfo().teamColor; if (oldColor == PlayerInfo::blue) { getPlayerInfo().teamColor = PlayerInfo::red; } else if (oldColor == PlayerInfo::red) { getPlayerInfo().teamColor = PlayerInfo::blue; } } if (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] == 1 || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] == 1) { // switch kickof team getPlayerInfo().ownKickOff = !getPlayerInfo().ownKickOff; } } // go back from penalized to initial both foot bumpers are pressed for over 30 frames else if (getPlayerInfo() .gameState == PlayerInfo::penalized && (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] > 30 || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] > 30 ) && (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] > 30 || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] > 30 ) ) { getPlayerInfo().gameState = PlayerInfo::inital; } } // end readButtons void GameController::readWLAN() { // TODO: WLAN GameController support } void GameController::execute() { PlayerInfo::GameState oldState = getPlayerInfo().gameState; PlayerInfo::TeamColor oldTeamColor = getPlayerInfo().teamColor; bool oldOwnKickOff = getPlayerInfo().ownKickOff; readButtons(); DEBUG_REQUEST("gamecontroller:initial", getPlayerInfo().gameState = PlayerInfo::inital; ); DEBUG_REQUEST("gamecontroller:ready", getPlayerInfo().gameState = PlayerInfo::ready; ); DEBUG_REQUEST("gamecontroller:set", getPlayerInfo().gameState = PlayerInfo::set; ); DEBUG_REQUEST("gamecontroller:play", getPlayerInfo().gameState = PlayerInfo::playing; ); DEBUG_REQUEST("gamecontroller:penalized", getPlayerInfo().gameState = PlayerInfo::penalized; ); if(oldState != getPlayerInfo().gameState || oldTeamColor != getPlayerInfo().teamColor || oldOwnKickOff != getPlayerInfo().ownKickOff || getPlayerInfo().gameState == PlayerInfo::inital) { updateLEDs(); } } // end execute void GameController::updateLEDs() { // reset getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0; // show game state in torso switch (getPlayerInfo().gameState) { case PlayerInfo::ready : std::cout << "in ready" << std::endl; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0; break; case PlayerInfo::set : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0; break; case PlayerInfo::playing : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0; break; case PlayerInfo::penalized : getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0; break; default: break; } // show team color on left foot if (getPlayerInfo().teamColor == PlayerInfo::red) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0; } else if (getPlayerInfo().teamColor == PlayerInfo::blue) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0; } // show kickoff state on right foot in initial, ready and set if (getPlayerInfo().gameState == PlayerInfo::inital || getPlayerInfo().gameState == PlayerInfo::ready || getPlayerInfo().gameState == PlayerInfo::set) { if (getPlayerInfo().ownKickOff) { getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0; getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0; } } } // end updateLEDs GameController::~GameController() { } <|endoftext|>
<commit_before>#include "../test.h" #include <QFile> #include "../../src/placement/constraint_updater.h" #include "../../src/graphics/qimage_drawer.h" TEST(Test_ConstraintUpdater, Draw) { int width = 512; int height = 256; auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height); ConstraintUpdater constraintUpdater(drawer, width, height); constraintUpdater.clear(); Eigen::Vector2i anchorPosition(100, 50); Eigen::Vector2i labelSize(62, 20); Eigen::Vector2i lastAnchorPosition(200, 70); Eigen::Vector2i lastLabelPosition(150, 120); Eigen::Vector2i lastLabelSize(60, 40); constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize, lastAnchorPosition, lastLabelPosition, lastLabelSize); drawer->image->save("constraints.png"); QFile expectedFile("expected-constraints.png"); ASSERT_TRUE(expectedFile.exists()) << "File 'expected-constraints.png' does not " "exists. Check 'constraints.png' and " "rename it if it is correct."; QImage expectedImage(expectedFile.fileName()); ASSERT_EQ(expectedImage.width(), drawer->image->width()); ASSERT_EQ(expectedImage.height(), drawer->image->height()); for (int y = 0; y < expectedImage.width(); ++y) for (int x = 0; x < expectedImage.width(); ++x) EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y)); } <commit_msg>Fix ConstraintUpdater test and add another test case.<commit_after>#include "../test.h" #include <QFile> #include "../../src/placement/constraint_updater.h" #include "../../src/graphics/qimage_drawer.h" TEST(Test_ConstraintUpdater, DrawWithConnectorShadows) { int width = 512; int height = 256; auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height); ConstraintUpdater constraintUpdater(drawer, width, height); constraintUpdater.setIsConnectorShadowEnabled(true); constraintUpdater.clear(); Eigen::Vector2i anchorPosition(100, 50); Eigen::Vector2i labelSize(62, 20); Eigen::Vector2i lastAnchorPosition(200, 70); Eigen::Vector2i lastLabelPosition(150, 120); Eigen::Vector2i lastLabelSize(60, 40); constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize, lastAnchorPosition, lastLabelPosition, lastLabelSize); drawer->image->save("constraints-with-connectors.png"); QFile expectedFile("expected-constraints-with-connectors.png"); ASSERT_TRUE(expectedFile.exists()) << "File 'expected-constraints.png' does not " "exists. Check 'constraints.png' and " "rename it if it is correct."; QImage expectedImage(expectedFile.fileName()); ASSERT_EQ(expectedImage.width(), drawer->image->width()); ASSERT_EQ(expectedImage.height(), drawer->image->height()); for (int y = 0; y < expectedImage.width(); ++y) for (int x = 0; x < expectedImage.width(); ++x) EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y)); } TEST(Test_ConstraintUpdater, DrawWithoutConnectorShadows) { int width = 512; int height = 256; auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height); ConstraintUpdater constraintUpdater(drawer, width, height); constraintUpdater.setIsConnectorShadowEnabled(false); constraintUpdater.clear(); Eigen::Vector2i anchorPosition(100, 50); Eigen::Vector2i labelSize(62, 20); Eigen::Vector2i lastAnchorPosition(200, 70); Eigen::Vector2i lastLabelPosition(150, 120); Eigen::Vector2i lastLabelSize(60, 40); constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize, lastAnchorPosition, lastLabelPosition, lastLabelSize); drawer->image->save("constraints-without-connectors.png"); QFile expectedFile("expected-constraints-without-connectors.png"); ASSERT_TRUE(expectedFile.exists()) << "File 'expected-constraints.png' does not " "exists. Check 'constraints.png' and " "rename it if it is correct."; QImage expectedImage(expectedFile.fileName()); ASSERT_EQ(expectedImage.width(), drawer->image->width()); ASSERT_EQ(expectedImage.height(), drawer->image->height()); for (int y = 0; y < expectedImage.width(); ++y) for (int x = 0; x < expectedImage.width(); ++x) EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y)); } <|endoftext|>
<commit_before> #include <irtkImage.h> #include <nr.h> #include <irtkModeFilter.h> #include <map> #ifdef WIN32 #include <time.h> #else #include <sys/time.h> #endif template <class VoxelType> irtkModeFilter<VoxelType>::irtkModeFilter() { // Default connectivity. this->_Connectivity = CONNECTIVITY_26; } template <class VoxelType> irtkModeFilter<VoxelType>::~irtkModeFilter(void) { } template <class VoxelType> bool irtkModeFilter<VoxelType>::RequiresBuffering(void) { return true; } template <class VoxelType> const char *irtkModeFilter<VoxelType>::NameOfClass() { return "irtkModeFilter"; } template <class VoxelType> void irtkModeFilter<VoxelType>::Initialize() { // Do the initial set up this->irtkImageToImage<VoxelType>::Initialize(); this->_offsets.Initialize(this->_input, this->_Connectivity); } template <class VoxelType> void irtkModeFilter<VoxelType>::Run() { int i, x, y, z, t, maskSize; VoxelType value; VoxelType *ptr2current, *ptr2offset; map<short, short> labelCount; map<short, short>::iterator iter; int ties, maxCount; short mode = 0; double inputMin, inputMax; int *tiedLabels; int randChoice; long ran2Seed; long ran2initialSeed; // Do the initial set up this->Initialize(); // Get ready for random stuff. time_t tv; tv = time(NULL); ran2Seed = tv; ran2initialSeed = -1 * ran2Seed; (void) ran2(&ran2initialSeed); this->_input->GetMinMaxAsDouble(&inputMin, &inputMax); tiedLabels = new int[(int) inputMax]; maskSize = this->_offsets.GetSize(); for (t = 0; t < this->_input->GetT(); t++) { for (z = 0; z < this->_input->GetZ(); z++) { for (y = 0; y < this->_input->GetY(); y++) { this->_output->Put(0, y, z, t, this->_input->Get(0, y, z, t)); } } for (z = 0; z < this->_input->GetZ(); z++) { for (x = 0; x < this->_input->GetX(); x++) { this->_output->Put(x, 0, z, t, this->_input->Get(x, 0, z, t)); } } for (y = 0; y < this->_input->GetY(); y++) { for (x = 0; x < this->_input->GetX(); x++) { this->_output->Put(x, y, 0, t, this->_input->Get(x, y, 0, t)); } } for (z = 1; z < this->_input->GetZ() - 1; z++) { for (y = 1; y < this->_input->GetY() - 1; y++) { for (x = 1; x < this->_input->GetX() - 1; x++) { labelCount.clear(); ptr2current = this->_input->GetPointerToVoxels(x, y, z, t); // Collect labels from neighbourhood. for (i = 0; i < maskSize; ++i) { ptr2offset = ptr2current + this->_offsets(i); labelCount[*ptr2offset]++; } // Seek modal label (but there may be ties for the mode) maxCount = 0; for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){ if (iter->second > maxCount){ maxCount = iter->second; mode = iter->first; } } ties = 0; for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){ if (iter->second == maxCount){ tiedLabels[ties] = iter->first; ++ties; } } if (ties > 1){ randChoice = (int) floor( ran2(&ran2Seed) * ties ); value = tiedLabels[ randChoice ]; } else { value = mode; } this->_output->Put(x, y, z, t, value); } } } } delete [] tiedLabels; // Do the final cleaning up this->Finalize(); } template class irtkModeFilter<irtkBytePixel>; template class irtkModeFilter<irtkGreyPixel>; <commit_msg>Replaced recipes ran2 function in irtkModeFilter.cc<commit_after> #include <irtkImage.h> #include <boost/random.hpp> #include <boost/random/uniform_int.hpp> #include <irtkModeFilter.h> #include <map> #ifdef WIN32 #include <time.h> #else #include <sys/time.h> #endif template <class VoxelType> irtkModeFilter<VoxelType>::irtkModeFilter() { // Default connectivity. this->_Connectivity = CONNECTIVITY_26; } template <class VoxelType> irtkModeFilter<VoxelType>::~irtkModeFilter(void) { } template <class VoxelType> bool irtkModeFilter<VoxelType>::RequiresBuffering(void) { return true; } template <class VoxelType> const char *irtkModeFilter<VoxelType>::NameOfClass() { return "irtkModeFilter"; } template <class VoxelType> void irtkModeFilter<VoxelType>::Initialize() { // Do the initial set up this->irtkImageToImage<VoxelType>::Initialize(); this->_offsets.Initialize(this->_input, this->_Connectivity); } template <class VoxelType> void irtkModeFilter<VoxelType>::Run() { int i, x, y, z, t, maskSize; VoxelType value; VoxelType *ptr2current, *ptr2offset; map<short, short> labelCount; map<short, short>::iterator iter; int ties, maxCount; short mode = 0; double inputMin, inputMax; int *tiedLabels; int randChoice; // Do the initial set up this->Initialize(); // Get ready for random stuff. long inSeed = time(NULL); boost::mt19937 rng; rng.seed(inSeed); boost::uniform_int<> ud(0, 1); boost::variate_generator<boost::mt19937&, boost::uniform_int<> > engine(rng, ud); (void) engine(); this->_input->GetMinMaxAsDouble(&inputMin, &inputMax); tiedLabels = new int[(int) inputMax]; maskSize = this->_offsets.GetSize(); for (t = 0; t < this->_input->GetT(); t++) { for (z = 0; z < this->_input->GetZ(); z++) { for (y = 0; y < this->_input->GetY(); y++) { this->_output->Put(0, y, z, t, this->_input->Get(0, y, z, t)); } } for (z = 0; z < this->_input->GetZ(); z++) { for (x = 0; x < this->_input->GetX(); x++) { this->_output->Put(x, 0, z, t, this->_input->Get(x, 0, z, t)); } } for (y = 0; y < this->_input->GetY(); y++) { for (x = 0; x < this->_input->GetX(); x++) { this->_output->Put(x, y, 0, t, this->_input->Get(x, y, 0, t)); } } for (z = 1; z < this->_input->GetZ() - 1; z++) { for (y = 1; y < this->_input->GetY() - 1; y++) { for (x = 1; x < this->_input->GetX() - 1; x++) { labelCount.clear(); ptr2current = this->_input->GetPointerToVoxels(x, y, z, t); // Collect labels from neighbourhood. for (i = 0; i < maskSize; ++i) { ptr2offset = ptr2current + this->_offsets(i); labelCount[*ptr2offset]++; } // Seek modal label (but there may be ties for the mode) maxCount = 0; for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){ if (iter->second > maxCount){ maxCount = iter->second; mode = iter->first; } } ties = 0; for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){ if (iter->second == maxCount){ tiedLabels[ties] = iter->first; ++ties; } } if (ties > 1){ randChoice = (int) floor( engine() * ties ); value = tiedLabels[ randChoice ]; } else { value = mode; } this->_output->Put(x, y, z, t, value); } } } } delete [] tiedLabels; // Do the final cleaning up this->Finalize(); } template class irtkModeFilter<irtkBytePixel>; template class irtkModeFilter<irtkGreyPixel>; <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ #define _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <type_traits> #include "../Format.h" namespace Stroika::Foundation::Cryptography::Digest { namespace Private_ { // Try to use simple constuction of result from argument if possible template <typename OUT_RESULT, typename IN_RESULT> constexpr OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<is_constructible_v<OUT_RESULT, IN_RESULT>, void>* = nullptr) { return OUT_RESULT (hashVal); // intentionally allow narrowing conversions (so () not {}) } // Else if both (IN AND OUT) values trivially copyable, use memcpy (and zero fill result as needed) template <typename OUT_RESULT, typename IN_RESULT> OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t< not is_constructible_v<OUT_RESULT, IN_RESULT> and (is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>), char>* = nullptr) { size_t mBytes2Copy = std::min (sizeof (OUT_RESULT), sizeof (IN_RESULT)); OUT_RESULT result{}; // zero initialize non-copied bits (@todo could just zero-fill end bits) DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wclass-memaccess\"") // memcpy only requires trivially_copyable, not is_trivial ::memcpy (&result, &hashVal, mBytes2Copy); DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wclass-memaccess\"") return result; } // NOTE - mkReturnType1_<string,XXX> () here uses enable_if and is_same, since C++ doesn't currently allow partial function template // specialization -- LGP 2020-10-02 template <typename OUT_RESULT, typename IN_RESULT> inline OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<not is_constructible_v<OUT_RESULT, IN_RESULT> and not(is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>) and (is_same_v<OUT_RESULT, string> or is_same_v<OUT_RESULT, Characters::String> or is_same_v<OUT_RESULT, Common::GUID>), short>* = nullptr) { return Format<OUT_RESULT> (hashVal); } } template <typename OUT_RESULT, typename IN_RESULT> constexpr OUT_RESULT ConvertResult (IN_RESULT inResult) { return Private_::mkReturnType_<OUT_RESULT> (inResult); } } #endif /*_Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_*/ <commit_msg>format<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ #define _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <type_traits> #include "../Format.h" namespace Stroika::Foundation::Cryptography::Digest { namespace Private_ { // Try to use simple constuction of result from argument if possible template <typename OUT_RESULT, typename IN_RESULT> constexpr OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<is_constructible_v<OUT_RESULT, IN_RESULT>, void>* = nullptr) { return OUT_RESULT (hashVal); // intentionally allow narrowing conversions (so () not {}) } // Else if both (IN AND OUT) values trivially copyable, use memcpy (and zero fill result as needed) template <typename OUT_RESULT, typename IN_RESULT> OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t< not is_constructible_v<OUT_RESULT, IN_RESULT> and (is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>), char>* = nullptr) { size_t mBytes2Copy = std::min (sizeof (OUT_RESULT), sizeof (IN_RESULT)); OUT_RESULT result{}; // zero initialize non-copied bits (@todo could just zero-fill end bits) DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wclass-memaccess\"") // memcpy only requires trivially_copyable, not is_trivial ::memcpy (&result, &hashVal, mBytes2Copy); DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wclass-memaccess\"") return result; } // NOTE - mkReturnType1_<string,XXX> () here uses enable_if and is_same, since C++ doesn't currently allow partial function template // specialization -- LGP 2020-10-02 template <typename OUT_RESULT, typename IN_RESULT> inline OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<not is_constructible_v<OUT_RESULT, IN_RESULT> and not(is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>) and (is_same_v<OUT_RESULT, string> or is_same_v<OUT_RESULT, Characters::String> or is_same_v<OUT_RESULT, Common::GUID>), short>* = nullptr) { return Format<OUT_RESULT> (hashVal); } } template <typename OUT_RESULT, typename IN_RESULT> constexpr OUT_RESULT ConvertResult (IN_RESULT inResult) { return Private_::mkReturnType_<OUT_RESULT> (inResult); } } #endif /*_Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_*/ <|endoftext|>
<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <configuration.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Integration.hpp> #include <Timer.hpp> #include <Stats.hpp> void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, cl::Buffer * input_d, const unsigned int input_size, cl::Buffer * output_d, const unsigned int output_size); int main(int argc, char * argv[]) { bool reInit = false; unsigned int padding = 0; unsigned int integration = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int vectorWidth = 0; AstroData::Observation observation; PulsarSearch::integrationSamplesDMsConf conf; cl::Event event; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); integration = args.getSwitchArgument< unsigned int >("-integration"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); vectorWidth = args.getSwitchArgument< unsigned int >("-vector"); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0f, 0.0f); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -integration ... -min_threads ... -max_threads ... -max_items ... -vector ... -samples ... -dms ... " << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Allocate host memory std::vector< dataType > input(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond(padding / sizeof(dataType))); std::vector< dataType > output(observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerSecond() / integration, padding / sizeof(dataType))); // Initialize OpenCL cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); // Allocate device memory cl::Buffer input_d; cl::Buffer output_d; try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), input_d, input.size(), output_d, output.size()); } catch ( cl::Error & err ) { std::cerr << err.what() << std::endl; return -1; } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrSamples integration samplesPerBlock samplesPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int samples = minThreads; samples <= maxThreads; samples++) { conf.setNrSamplesPerBlock(samples); if ( conf.getNrSamplesPerBlock() % vectorWidth != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { conf.setNrSamplesPerThread(samplesPerThread); if ( (observation.getNrSamplesPerSecond() % (integration * conf.getNrSamplesPerThread())) != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga((static_cast< uint64_t >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) + (static_cast< uint64_t >(observation.getNrDMs()) * (observation.getNrSamplesPerSecond() / integration))); isa::utils::Timer timer; cl::Kernel * kernel; std::string * code = PulsarSearch::getIntegrationSamplesDMsOpenCL< dataType >(conf, observation, dataName, integration, padding); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), input_d, input.size(), output_d, output.size()); } catch ( cl::Error & err ) { std::cerr << "Error in memory allocation: "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("integrationSamplesDMs" + isa::utils::toString(integration), *code, "-cl-mad-enable -Wall", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global((observation.getNrSamplesPerSecond() / integration) / conf.getNrSamplesPerThread(), observation.getNrDMs()); cl::NDRange local(conf.getNrSamplesPerBlock(), 1); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution ("; std::cerr << conf.print() << "): "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } reInit = true; break; } delete kernel; std::cout << observation.getNrDMs() << " " << observation.getNrSamplesPerSecond() << " " << integration << " "; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, cl::Buffer * input_d, const unsigned int input_size, cl::Buffer * output_d, const unsigned int output_size) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, input_size * sizeof(dataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, output_size * sizeof(dataType), 0, 0); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <commit_msg>Missing header.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <iomanip> #include <configuration.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Integration.hpp> #include <Timer.hpp> #include <Stats.hpp> void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, cl::Buffer * input_d, const unsigned int input_size, cl::Buffer * output_d, const unsigned int output_size); int main(int argc, char * argv[]) { bool reInit = false; unsigned int padding = 0; unsigned int integration = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int vectorWidth = 0; AstroData::Observation observation; PulsarSearch::integrationSamplesDMsConf conf; cl::Event event; try { isa::utils::ArgumentList args(argc, argv); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); integration = args.getSwitchArgument< unsigned int >("-integration"); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); vectorWidth = args.getSwitchArgument< unsigned int >("-vector"); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0f, 0.0f); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -integration ... -min_threads ... -max_threads ... -max_items ... -vector ... -samples ... -dms ... " << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Allocate host memory std::vector< dataType > input(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond(padding / sizeof(dataType))); std::vector< dataType > output(observation.getNrDMs() * isa::utils::pad(observation.getNrSamplesPerSecond() / integration, padding / sizeof(dataType))); // Initialize OpenCL cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); // Allocate device memory cl::Buffer input_d; cl::Buffer output_d; try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), input_d, input.size(), output_d, output.size()); } catch ( cl::Error & err ) { std::cerr << err.what() << std::endl; return -1; } std::cout << std::fixed << std::endl; std::cout << "# nrDMs nrSamples integration samplesPerBlock samplesPerThread GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int samples = minThreads; samples <= maxThreads; samples++) { conf.setNrSamplesPerBlock(samples); if ( conf.getNrSamplesPerBlock() % vectorWidth != 0 ) { continue; } for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) { conf.setNrSamplesPerThread(samplesPerThread); if ( (observation.getNrSamplesPerSecond() % (integration * conf.getNrSamplesPerThread())) != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()); double gbs = isa::utils::giga((static_cast< uint64_t >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) + (static_cast< uint64_t >(observation.getNrDMs()) * (observation.getNrSamplesPerSecond() / integration))); isa::utils::Timer timer; cl::Kernel * kernel; std::string * code = PulsarSearch::getIntegrationSamplesDMsOpenCL< dataType >(conf, observation, dataName, integration, padding); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), input_d, input.size(), output_d, output.size()); } catch ( cl::Error & err ) { std::cerr << "Error in memory allocation: "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("integrationSamplesDMs" + isa::utils::toString(integration), *code, "-cl-mad-enable -Wall", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global((observation.getNrSamplesPerSecond() / integration) / conf.getNrSamplesPerThread(), observation.getNrDMs()); cl::NDRange local(conf.getNrSamplesPerBlock(), 1); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event); event.wait(); timer.stop(); } } catch ( cl::Error & err ) { std::cerr << "OpenCL error kernel execution ("; std::cerr << conf.print() << "): "; std::cerr << isa::utils::toString(err.err()) << "." << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } reInit = true; break; } delete kernel; std::cout << observation.getNrDMs() << " " << observation.getNrSamplesPerSecond() << " " << integration << " "; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << gbs / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " "; std::cout << timer.getCoefficientOfVariation() << std::endl; } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, cl::Buffer * input_d, const unsigned int input_size, cl::Buffer * output_d, const unsigned int output_size) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, input_size * sizeof(dataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, output_size * sizeof(dataType), 0, 0); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <|endoftext|>