text
stringlengths
54
60.6k
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: configdlg.cpp // Purpose: Implementation of wxExtension config dialog class // Author: Anton van Wezenbeek // Copyright: (c) 2012 //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <functional> #include <algorithm> #include <wx/aui/auibook.h> #include <wx/bookctrl.h> #include <wx/choicebk.h> #include <wx/listbook.h> #include <wx/filepicker.h> #include <wx/persist/treebook.h> #include <wx/toolbook.h> #include <wx/extension/configdlg.h> #include <wx/extension/frame.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExConfigDialog, wxExDialog) EVT_BUTTON(wxID_APPLY, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_CANCEL, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_CLOSE, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_OK, wxExConfigDialog::OnCommand) EVT_UPDATE_UI(wxID_APPLY, wxExConfigDialog::OnUpdateUI) EVT_UPDATE_UI(wxID_OK, wxExConfigDialog::OnUpdateUI) END_EVENT_TABLE() // wxPropertySheetDialog has been tried as well, // then you always have a notebook, and apply button is not supported. wxExConfigDialog::wxExConfigDialog(wxWindow* parent, const std::vector<wxExConfigItem>& v, const wxString& title, int rows, int cols, long flags, wxWindowID id, int bookctrl_style, long style, const wxString& name) : wxExDialog( parent, title, flags, id, wxDefaultPosition, wxDefaultSize, style, name) , m_ForceCheckBoxChecked(false) , m_Page(wxEmptyString) , m_ConfigItems(v) { Layout(rows, cols, bookctrl_style); } std::vector< wxExConfigItem >::const_iterator wxExConfigDialog::FindConfigItem(int id) const { for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::const_iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { if (it->GetWindow()->GetId() == id) { return it; } } return m_ConfigItems.end(); } void wxExConfigDialog::Click(int id) const { wxExFrame* frame = wxDynamicCast(wxTheApp->GetTopWindow(), wxExFrame); if (frame != NULL) { frame->OnCommandConfigDialog(GetId(), id); } } void wxExConfigDialog::ForceCheckBoxChecked( const wxString& contains, const wxString& page) { m_ForceCheckBoxChecked = true; m_Contains = contains; m_Page = page; } void wxExConfigDialog::Layout(int rows, int cols, int bookctrl_style) { if (m_ConfigItems.empty()) { AddUserSizer(CreateTextSizer( _("No further info available")), wxSizerFlags().Center()); LayoutSizers(); return; } bool first_time = true; wxFlexGridSizer* sizer = NULL; wxFlexGridSizer* previous_item_sizer = NULL; int previous_item_type = -1; wxBookCtrlBase* bookctrl = NULL; if (!m_ConfigItems.begin()->GetPage().empty()) { switch (bookctrl_style) { case CONFIG_AUINOTEBOOK: bookctrl = new wxAuiNotebook(this); break; case CONFIG_CHOICEBOOK: bookctrl = new wxChoicebook(this, wxID_ANY); break; case CONFIG_LISTBOOK: bookctrl = new wxListbook(this, wxID_ANY); break; case CONFIG_NOTEBOOK: bookctrl = new wxNotebook(this, wxID_ANY); break; case CONFIG_TOOLBOOK: bookctrl = new wxToolbook(this, wxID_ANY); break; case CONFIG_TREEBOOK: bookctrl = new wxTreebook(this, wxID_ANY); break; default: wxFAIL; } } wxString previous_page = "XXXXXX"; for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { if (first_time || (it->GetPage() != previous_page && !it->GetPage().empty())) { first_time = false; if (bookctrl != NULL) { // Finish the current page. if (bookctrl->GetCurrentPage() != NULL) { bookctrl->GetCurrentPage()->SetSizerAndFit(sizer); } // And make a new one. bookctrl->AddPage( new wxWindow(bookctrl, wxID_ANY), it->GetPage(), true); // select } previous_page = it->GetPage(); const int use_cols = (it->GetColumns() != -1 ? it->GetColumns(): cols); sizer = (rows != 0 ? new wxFlexGridSizer(rows, use_cols, 0, 0): new wxFlexGridSizer(use_cols)); for (int i = 0; i < use_cols; i++) { sizer->AddGrowableCol(i); } } wxFlexGridSizer* use_item_sizer = (it->GetType() == previous_item_type ? previous_item_sizer: NULL); previous_item_sizer = it->Layout( (bookctrl != NULL ? bookctrl->GetCurrentPage(): this), sizer, GetButtonFlags() == wxCANCEL, use_item_sizer); previous_item_type = it->GetType(); if ( it->GetType() == CONFIG_BUTTON || it->GetType() == CONFIG_COMBOBOXDIR) { Bind( wxEVT_COMMAND_BUTTON_CLICKED, &wxExConfigDialog::OnCommand, this, it->GetWindow()->GetId()); } if ( sizer->GetRows() > 0 && !sizer->IsRowGrowable(sizer->GetRows() - 1)) { sizer->AddGrowableRow(sizer->GetRows() - 1); } } if (bookctrl != NULL) { bookctrl->GetCurrentPage()->SetSizerAndFit(sizer); bookctrl->SetName("book" + GetName()); if (!wxPersistenceManager::Get().RegisterAndRestore(bookctrl)) { // nothing was restored, so choose the default page ourselves bookctrl->SetSelection(0); } AddUserSizer(bookctrl); } else { AddUserSizer(sizer); } LayoutSizers(bookctrl == NULL); // add separator line if no bookctrl } void wxExConfigDialog::OnCommand(wxCommandEvent& command) { if (command.GetId() < wxID_LOWEST) { #ifdef wxExUSE_CPP0X auto it = FindConfigItem(command.GetId()); #else std::vector<wxExConfigItem>::const_iterator it = FindConfigItem(command.GetId()); #endif if (it != m_ConfigItems.end()) { if (it->GetType() == CONFIG_COMBOBOXDIR) { wxComboBox* browse = (wxComboBox*)it->GetWindow(); wxDirDialog dir_dlg( this, _(wxDirSelectorPromptStr), browse->GetValue(), wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dir_dlg.ShowModal() == wxID_OK) { browse->SetValue(dir_dlg.GetPath()); } } else if (it->GetType() == CONFIG_BUTTON) { Click(command.GetId()); } else { wxFAIL; } } } else if (command.GetId() == wxID_CANCEL) { Reload(); } else { for_each (m_ConfigItems.begin(), m_ConfigItems.end(), std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), true)); } if ( command.GetId() == wxID_APPLY || ((command.GetId() == wxID_OK || command.GetId() == wxID_CANCEL) && !IsModal())) { Click(command.GetId()); } command.Skip(); } void wxExConfigDialog::OnUpdateUI(wxUpdateUIEvent& event) { bool one_checkbox_checked = false; for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { switch (it->GetType()) { case CONFIG_CHECKBOX: if (m_ForceCheckBoxChecked) { wxCheckBox* cb = (wxCheckBox*)it->GetWindow(); if (it->GetLabel().Lower().Contains(m_Contains.Lower()) && cb->IsChecked() && it->GetPage() == m_Page) { one_checkbox_checked = true; } } break; case CONFIG_CHECKLISTBOX_NONAME: if (m_ForceCheckBoxChecked) { wxCheckListBox* clb = (wxCheckListBox*)it->GetWindow(); for ( size_t i = 0; i < clb->GetCount(); i++) { if (clb->GetString(i).Lower().Contains(m_Contains.Lower()) && clb->IsChecked(i) && it->GetPage() == m_Page) { one_checkbox_checked = true; } } } break; case CONFIG_COMBOBOX: case CONFIG_COMBOBOXDIR: { wxComboBox* cb = (wxComboBox*)it->GetWindow(); if (it->GetIsRequired()) { if (cb->GetValue().empty()) { event.Enable(false); return; } } } break; case CONFIG_INT: case CONFIG_STRING: { wxTextCtrl* tc = (wxTextCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (tc->GetValue().empty()) { event.Enable(false); return; } } } break; case CONFIG_DIRPICKERCTRL: { wxDirPickerCtrl* pc = (wxDirPickerCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (pc->GetPath().empty()) { event.Enable(false); return; } } } break; case CONFIG_FILEPICKERCTRL: { wxFilePickerCtrl* pc = (wxFilePickerCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (pc->GetPath().empty()) { event.Enable(false); return; } } } break; } } event.Enable(m_ForceCheckBoxChecked ? one_checkbox_checked: true); } void wxExConfigDialog::Reload() const { for_each (m_ConfigItems.begin(), m_ConfigItems.end(), std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), false)); } #endif // wxUSE_GUI <commit_msg>fixes for growable row<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: configdlg.cpp // Purpose: Implementation of wxExtension config dialog class // Author: Anton van Wezenbeek // Copyright: (c) 2012 //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <functional> #include <algorithm> #include <wx/aui/auibook.h> #include <wx/bookctrl.h> #include <wx/choicebk.h> #include <wx/listbook.h> #include <wx/filepicker.h> #include <wx/persist/treebook.h> #include <wx/toolbook.h> #include <wx/extension/configdlg.h> #include <wx/extension/frame.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExConfigDialog, wxExDialog) EVT_BUTTON(wxID_APPLY, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_CANCEL, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_CLOSE, wxExConfigDialog::OnCommand) EVT_BUTTON(wxID_OK, wxExConfigDialog::OnCommand) EVT_UPDATE_UI(wxID_APPLY, wxExConfigDialog::OnUpdateUI) EVT_UPDATE_UI(wxID_OK, wxExConfigDialog::OnUpdateUI) END_EVENT_TABLE() // wxPropertySheetDialog has been tried as well, // then you always have a notebook, and apply button is not supported. wxExConfigDialog::wxExConfigDialog(wxWindow* parent, const std::vector<wxExConfigItem>& v, const wxString& title, int rows, int cols, long flags, wxWindowID id, int bookctrl_style, long style, const wxString& name) : wxExDialog( parent, title, flags, id, wxDefaultPosition, wxDefaultSize, style, name) , m_ForceCheckBoxChecked(false) , m_Page(wxEmptyString) , m_ConfigItems(v) { Layout(rows, cols, bookctrl_style); } std::vector< wxExConfigItem >::const_iterator wxExConfigDialog::FindConfigItem(int id) const { for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::const_iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { if (it->GetWindow()->GetId() == id) { return it; } } return m_ConfigItems.end(); } void wxExConfigDialog::Click(int id) const { wxExFrame* frame = wxDynamicCast(wxTheApp->GetTopWindow(), wxExFrame); if (frame != NULL) { frame->OnCommandConfigDialog(GetId(), id); } } void wxExConfigDialog::ForceCheckBoxChecked( const wxString& contains, const wxString& page) { m_ForceCheckBoxChecked = true; m_Contains = contains; m_Page = page; } void wxExConfigDialog::Layout(int rows, int cols, int bookctrl_style) { if (m_ConfigItems.empty()) { AddUserSizer(CreateTextSizer( _("No further info available")), wxSizerFlags().Center()); LayoutSizers(); return; } bool first_time = true; wxFlexGridSizer* sizer = NULL; wxFlexGridSizer* previous_item_sizer = NULL; int previous_item_type = -1; wxBookCtrlBase* bookctrl = NULL; if (!m_ConfigItems.begin()->GetPage().empty()) { switch (bookctrl_style) { case CONFIG_AUINOTEBOOK: bookctrl = new wxAuiNotebook(this); break; case CONFIG_CHOICEBOOK: bookctrl = new wxChoicebook(this, wxID_ANY); break; case CONFIG_LISTBOOK: bookctrl = new wxListbook(this, wxID_ANY); break; case CONFIG_NOTEBOOK: bookctrl = new wxNotebook(this, wxID_ANY); break; case CONFIG_TOOLBOOK: bookctrl = new wxToolbook(this, wxID_ANY); break; case CONFIG_TREEBOOK: bookctrl = new wxTreebook(this, wxID_ANY); break; default: wxFAIL; } } wxString previous_page = "XXXXXX"; for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { if (first_time || (it->GetPage() != previous_page && !it->GetPage().empty())) { first_time = false; if (bookctrl != NULL) { // Finish the current page. if (bookctrl->GetCurrentPage() != NULL) { bookctrl->GetCurrentPage()->SetSizerAndFit(sizer); } // And make a new one. bookctrl->AddPage( new wxWindow(bookctrl, wxID_ANY), it->GetPage(), true); // select } previous_page = it->GetPage(); const int use_cols = (it->GetColumns() != -1 ? it->GetColumns(): cols); sizer = (rows != 0 ? new wxFlexGridSizer(rows, use_cols, 0, 0): new wxFlexGridSizer(use_cols)); for (int i = 0; i < use_cols; i++) { sizer->AddGrowableCol(i); } } wxFlexGridSizer* use_item_sizer = (it->GetType() == previous_item_type ? previous_item_sizer: NULL); previous_item_sizer = it->Layout( (bookctrl != NULL ? bookctrl->GetCurrentPage(): this), sizer, GetButtonFlags() == wxCANCEL, use_item_sizer); previous_item_type = it->GetType(); if ( it->GetType() == CONFIG_BUTTON || it->GetType() == CONFIG_COMBOBOXDIR) { Bind( wxEVT_COMMAND_BUTTON_CLICKED, &wxExConfigDialog::OnCommand, this, it->GetWindow()->GetId()); } std::vector<wxExConfigItem>::iterator next = it + 1; wxString next_page; if (next != m_ConfigItems.end()) { next_page = next->GetPage(); } else { next_page = "YYYYYY"; } if (sizer != NULL && it->GetPage() != next_page && sizer->GetEffectiveRowsCount() == 1 && !sizer->IsRowGrowable(sizer->GetEffectiveRowsCount() - 1)) { sizer->AddGrowableRow(sizer->GetEffectiveRowsCount() - 1); } } if (bookctrl != NULL) { bookctrl->GetCurrentPage()->SetSizerAndFit(sizer); bookctrl->SetName("book" + GetName()); if (!wxPersistenceManager::Get().RegisterAndRestore(bookctrl)) { // nothing was restored, so choose the default page ourselves bookctrl->SetSelection(0); } AddUserSizer(bookctrl); } else { AddUserSizer(sizer); } LayoutSizers(bookctrl == NULL); // add separator line if no bookctrl } void wxExConfigDialog::OnCommand(wxCommandEvent& command) { if (command.GetId() < wxID_LOWEST) { #ifdef wxExUSE_CPP0X auto it = FindConfigItem(command.GetId()); #else std::vector<wxExConfigItem>::const_iterator it = FindConfigItem(command.GetId()); #endif if (it != m_ConfigItems.end()) { if (it->GetType() == CONFIG_COMBOBOXDIR) { wxComboBox* browse = (wxComboBox*)it->GetWindow(); wxDirDialog dir_dlg( this, _(wxDirSelectorPromptStr), browse->GetValue(), wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dir_dlg.ShowModal() == wxID_OK) { browse->SetValue(dir_dlg.GetPath()); } } else if (it->GetType() == CONFIG_BUTTON) { Click(command.GetId()); } else { wxFAIL; } } } else if (command.GetId() == wxID_CANCEL) { Reload(); } else { for_each (m_ConfigItems.begin(), m_ConfigItems.end(), std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), true)); } if ( command.GetId() == wxID_APPLY || ((command.GetId() == wxID_OK || command.GetId() == wxID_CANCEL) && !IsModal())) { Click(command.GetId()); } command.Skip(); } void wxExConfigDialog::OnUpdateUI(wxUpdateUIEvent& event) { bool one_checkbox_checked = false; for ( #ifdef wxExUSE_CPP0X auto it = m_ConfigItems.begin(); #else std::vector<wxExConfigItem>::iterator it = m_ConfigItems.begin(); #endif it != m_ConfigItems.end(); ++it) { switch (it->GetType()) { case CONFIG_CHECKBOX: if (m_ForceCheckBoxChecked) { wxCheckBox* cb = (wxCheckBox*)it->GetWindow(); if (it->GetLabel().Lower().Contains(m_Contains.Lower()) && cb->IsChecked() && it->GetPage() == m_Page) { one_checkbox_checked = true; } } break; case CONFIG_CHECKLISTBOX_NONAME: if (m_ForceCheckBoxChecked) { wxCheckListBox* clb = (wxCheckListBox*)it->GetWindow(); for ( size_t i = 0; i < clb->GetCount(); i++) { if (clb->GetString(i).Lower().Contains(m_Contains.Lower()) && clb->IsChecked(i) && it->GetPage() == m_Page) { one_checkbox_checked = true; } } } break; case CONFIG_COMBOBOX: case CONFIG_COMBOBOXDIR: { wxComboBox* cb = (wxComboBox*)it->GetWindow(); if (it->GetIsRequired()) { if (cb->GetValue().empty()) { event.Enable(false); return; } } } break; case CONFIG_INT: case CONFIG_STRING: { wxTextCtrl* tc = (wxTextCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (tc->GetValue().empty()) { event.Enable(false); return; } } } break; case CONFIG_DIRPICKERCTRL: { wxDirPickerCtrl* pc = (wxDirPickerCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (pc->GetPath().empty()) { event.Enable(false); return; } } } break; case CONFIG_FILEPICKERCTRL: { wxFilePickerCtrl* pc = (wxFilePickerCtrl*)it->GetWindow(); if (it->GetIsRequired()) { if (pc->GetPath().empty()) { event.Enable(false); return; } } } break; } } event.Enable(m_ForceCheckBoxChecked ? one_checkbox_checked: true); } void wxExConfigDialog::Reload() const { for_each (m_ConfigItems.begin(), m_ConfigItems.end(), std::bind2nd(std::mem_fun_ref(&wxExConfigItem::ToConfig), false)); } #endif // wxUSE_GUI <|endoftext|>
<commit_before>/********************************************************************** * File: serialis.h (Formerly serialmac.h) * Description: Inline routines and macros for serialisation functions * Author: Phil Cheatle * Created: Tue Oct 08 08:33:12 BST 1991 * * (C) Copyright 1990, Hewlett-Packard Ltd. ** 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 "mfcpch.h" //precompiled headers #include "serialis.h" #include "scanutils.h" /* ************************************************************************** These are the only routines that write/read data to/from the serialisation. "serialise_bytes" and "de_serialise_bytes" are used to serialise NON class items. The "make_serialise" macro generates "serialise" and "de_serialise" member functions for the class name specified in the macro parameter. ************************************************************************** */ DLLSYM void *de_serialise_bytes(FILE *f, int size) { void *ptr; ptr = alloc_mem (size); /* printf( "De_serialising bytes\n" ); printf( " Addr: %d Size: %d\n", int(ptr), size ); */ if (fread (ptr, size, 1, f) != 1) READFAILED.error ("de_serialise_bytes", ABORT, NULL); return ptr; } DLLSYM void serialise_bytes(FILE *f, void *ptr, int size) { /* printf( "Serialising bytes\n" ); printf( " Addr: %d Size: %d\n", int(ptr), size ); */ if (fwrite (ptr, size, 1, f) != 1) WRITEFAILED.error ("serialise_bytes", ABORT, NULL); } DLLSYM void serialise_INT32(FILE *f, inT32 the_int) { if (fprintf (f, INT32FORMAT "\n", the_int) < 0) WRITEFAILED.error ("serialise_INT32", ABORT, NULL); } DLLSYM inT32 de_serialise_INT32(FILE *f) { inT32 the_int; if (fscanf (f, INT32FORMAT, &the_int) != 1) READFAILED.error ("de_serialise_INT32", ABORT, NULL); return the_int; } DLLSYM void serialise_FLOAT64(FILE *f, double the_float) { if (fprintf (f, "%g\n", the_float) < 0) WRITEFAILED.error ("serialise_FLOAT64", ABORT, NULL); } DLLSYM double de_serialise_FLOAT64(FILE *f) { double the_float; if (tess_fscanf (f, "%lg", &the_float) != 1) READFAILED.error ("de_serialise_FLOAT64", ABORT, NULL); return the_float; } // Byte swap an inT64 or uinT64. DLLSYM uinT64 reverse64(uinT64 num) { return ((uinT64)reverse32((uinT32)(num & 0xffffffff)) << 32) | reverse32((uinT32)((num >> 32) & 0xffffffff)); } /********************************************************************** * reverse32 * * Byte swap an inT32 or uinT32. **********************************************************************/ DLLSYM uinT32 reverse32( //switch endian uinT32 num //number to fix ) { return (reverse16 ((uinT16) (num & 0xffff)) << 16) | reverse16 ((uinT16) ((num >> 16) & 0xffff)); } /********************************************************************** * reverse16 * * Byte swap an inT16 or uinT16. **********************************************************************/ DLLSYM uinT16 reverse16( //switch endian uinT16 num //number to fix ) { return ((num & 0xff) << 8) | ((num >> 8) & 0xff); } <commit_msg>Zdenko caught one I missed<commit_after>/********************************************************************** * File: serialis.h (Formerly serialmac.h) * Description: Inline routines and macros for serialisation functions * Author: Phil Cheatle * Created: Tue Oct 08 08:33:12 BST 1991 * * (C) Copyright 1990, Hewlett-Packard Ltd. ** 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 "mfcpch.h" //precompiled headers #include "serialis.h" #include "scanutils.h" /* ************************************************************************** These are the only routines that write/read data to/from the serialisation. "serialise_bytes" and "de_serialise_bytes" are used to serialise NON class items. The "make_serialise" macro generates "serialise" and "de_serialise" member functions for the class name specified in the macro parameter. ************************************************************************** */ DLLSYM void *de_serialise_bytes(FILE *f, int size) { void *ptr; ptr = alloc_mem (size); /* printf( "De_serialising bytes\n" ); printf( " Addr: %d Size: %d\n", int(ptr), size ); */ if (fread (ptr, size, 1, f) != 1) READFAILED.error ("de_serialise_bytes", ABORT, NULL); return ptr; } DLLSYM void serialise_bytes(FILE *f, void *ptr, int size) { /* printf( "Serialising bytes\n" ); printf( " Addr: %d Size: %d\n", int(ptr), size ); */ if (fwrite (ptr, size, 1, f) != 1) WRITEFAILED.error ("serialise_bytes", ABORT, NULL); } DLLSYM void serialise_INT32(FILE *f, inT32 the_int) { if (fprintf (f, INT32FORMAT "\n", the_int) < 0) WRITEFAILED.error ("serialise_INT32", ABORT, NULL); } DLLSYM inT32 de_serialise_INT32(FILE *f) { inT32 the_int; if (fscanf (f, INT32FORMAT, &the_int) != 1) READFAILED.error ("de_serialise_INT32", ABORT, NULL); return the_int; } DLLSYM void serialise_FLOAT64(FILE *f, double the_float) { if (fprintf (f, "%g\n", the_float) < 0) WRITEFAILED.error ("serialise_FLOAT64", ABORT, NULL); } DLLSYM double de_serialise_FLOAT64(FILE *f) { double the_float; #ifndef _MSC_VER if (tess_fscanf (f, "%lg", &the_float) != 1) #else if (fscanf (f, "%lg", &the_float) != 1) #endif READFAILED.error ("de_serialise_FLOAT64", ABORT, NULL); return the_float; } // Byte swap an inT64 or uinT64. DLLSYM uinT64 reverse64(uinT64 num) { return ((uinT64)reverse32((uinT32)(num & 0xffffffff)) << 32) | reverse32((uinT32)((num >> 32) & 0xffffffff)); } /********************************************************************** * reverse32 * * Byte swap an inT32 or uinT32. **********************************************************************/ DLLSYM uinT32 reverse32( //switch endian uinT32 num //number to fix ) { return (reverse16 ((uinT16) (num & 0xffff)) << 16) | reverse16 ((uinT16) ((num >> 16) & 0xffff)); } /********************************************************************** * reverse16 * * Byte swap an inT16 or uinT16. **********************************************************************/ DLLSYM uinT16 reverse16( //switch endian uinT16 num //number to fix ) { return ((num & 0xff) << 8) | ((num >> 8) & 0xff); } <|endoftext|>
<commit_before>#include "gamelib/editor/editor/tools/BrushTool.hpp" #include "imgui.h" #include "imgui-SFML.h" #include "gamelib/utils/log.hpp" #include "gamelib/core/ecs/EntityFactory.hpp" #include "editor/components/BrushComponent.hpp" #include "gamelib/components/rendering/PolygonShape.hpp" #include "gamelib/editor/editor/tools/SelectTool.hpp" #include "gamelib/editor/editor/tools/ToolUtils.hpp" #include "gamelib/editor/editor/ui/resources.hpp" #include "gamelib/editor/editor/EditorShared.hpp" namespace gamelib { static const char* brushEntities[] = { "brush_polygon", "brush_line", }; static const char* brushNames[] = { "Polygon", "Line", }; BrushTool::BrushTool() : _showdraggers(true), _snappoint(true), _linewidth(32), _type(Polygon), _tex(nullptr) { } void BrushTool::onMousePressed() { auto selected = _getIfSame(); if (selected) { math::Point2f p; if (_snappoint) p = snap(*selected->getBrushPolygon(), EditorShared::getMouse()); else p = EditorShared::getMouseSnapped(); LOG_DEBUG("Creating Vertex at (", p.x, ", ", p.y, ")"); selected->add(p); } else { auto handle = createEntity(brushEntities[_type]); auto brush = getEntity(handle); selected = brush->findByType<BrushComponent>(); selected->setWidth(_linewidth); selected->getBrushShape()->texture = _tex; selected->getBrushShape()->setTexOffset(_offset); brush->getTransform().setPosition(EditorShared::getMouseSnapped()); EditorShared::getSelectTool().select(brush); onMousePressed(); } } void BrushTool::render(sf::RenderTarget& target) { math::Point2f mouse = EditorShared::getMouseSnapped(); auto selected = _getIfSame(); if (selected) { auto pol = selected->getBrushPolygon(); if (!ImGui::GetIO().WantCaptureMouse) { if (_snappoint) mouse = snap(*pol, EditorShared::getMouse()); if (_type == Polygon && pol->size() > 1) { drawLine(target, pol->get(-1), mouse); drawLine(target, pol->get(-2), mouse); } else if ((_type == Line || _type == Polygon) && pol->size() > 0) { drawLine(target, pol->get(-1), mouse); } } if (_showdraggers) drawDragBoxes(target, *pol); } if (_showdraggers && !ImGui::GetIO().WantCaptureMouse) drawDragBox(target, mouse); } void BrushTool::drawGui() { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); ImGui::Combo("Brush type", (int*)&_type, brushNames, NumBrushTypes); if (_type == Line) { ImGui::InputInt("Line width", &_linewidth, 1, 32); if (_linewidth != (int)_tex->getSize().y) { ImGui::SameLine(); if (ImGui::Button("Reset")) _linewidth = _tex->getSize().y; } } if (inputResource(&_tex) && _tex) _linewidth = _tex->getSize().y; ImGui::InputFloat2("Texture offset", &_offset[0], 2); ImGui::Checkbox("Snap to points", &_snappoint); ImGui::Checkbox("Show drag boxes", &_showdraggers); ImGui::PopItemWidth(); ImGui::Separator(); auto brush = _getIfSame(); if (brush && ImGui::Button("Apply")) { brush->setWidth(_linewidth); brush->getBrushShape()->texture = _tex; brush->getBrushShape()->setTexOffset(_offset); } } BrushComponent* BrushTool::_getIfSame() const { auto selected = getIfBrush(EditorShared::getSelectTool().getSelected()); bool linebrush = selected && selected->getEntity()->getName() == brushEntities[Line]; if (((_type == Line) ^ linebrush)) return nullptr; return selected; } } <commit_msg>Fix crash in BrushTool<commit_after>#include "gamelib/editor/editor/tools/BrushTool.hpp" #include "imgui.h" #include "imgui-SFML.h" #include "gamelib/utils/log.hpp" #include "gamelib/core/ecs/EntityFactory.hpp" #include "editor/components/BrushComponent.hpp" #include "gamelib/components/rendering/PolygonShape.hpp" #include "gamelib/editor/editor/tools/SelectTool.hpp" #include "gamelib/editor/editor/tools/ToolUtils.hpp" #include "gamelib/editor/editor/ui/resources.hpp" #include "gamelib/editor/editor/EditorShared.hpp" namespace gamelib { static const char* brushEntities[] = { "brush_polygon", "brush_line", }; static const char* brushNames[] = { "Polygon", "Line", }; BrushTool::BrushTool() : _showdraggers(true), _snappoint(true), _linewidth(32), _type(Polygon), _tex(nullptr) { } void BrushTool::onMousePressed() { auto selected = _getIfSame(); if (selected) { math::Point2f p; if (_snappoint) p = snap(*selected->getBrushPolygon(), EditorShared::getMouse()); else p = EditorShared::getMouseSnapped(); LOG_DEBUG("Creating Vertex at (", p.x, ", ", p.y, ")"); selected->add(p); } else { auto handle = createEntity(brushEntities[_type]); auto brush = getEntity(handle); selected = brush->findByType<BrushComponent>(); selected->setWidth(_linewidth); selected->getBrushShape()->texture = _tex; selected->getBrushShape()->setTexOffset(_offset); brush->getTransform().setPosition(EditorShared::getMouseSnapped()); EditorShared::getSelectTool().select(brush); onMousePressed(); } } void BrushTool::render(sf::RenderTarget& target) { math::Point2f mouse = EditorShared::getMouseSnapped(); auto selected = _getIfSame(); if (selected) { auto pol = selected->getBrushPolygon(); if (!ImGui::GetIO().WantCaptureMouse) { if (_snappoint) mouse = snap(*pol, EditorShared::getMouse()); if (_type == Polygon && pol->size() > 1) { drawLine(target, pol->get(-1), mouse); drawLine(target, pol->get(-2), mouse); } else if ((_type == Line || _type == Polygon) && pol->size() > 0) { drawLine(target, pol->get(-1), mouse); } } if (_showdraggers) drawDragBoxes(target, *pol); } if (_showdraggers && !ImGui::GetIO().WantCaptureMouse) drawDragBox(target, mouse); } void BrushTool::drawGui() { ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); ImGui::Combo("Brush type", (int*)&_type, brushNames, NumBrushTypes); if (_type == Line) { ImGui::InputInt("Line width", &_linewidth, 1, 32); if (_tex && _linewidth != (int)_tex->getSize().y) { ImGui::SameLine(); if (ImGui::Button("Reset")) _linewidth = _tex->getSize().y; } } if (inputResource(&_tex) && _tex) _linewidth = _tex->getSize().y; ImGui::InputFloat2("Texture offset", &_offset[0], 2); ImGui::Checkbox("Snap to points", &_snappoint); ImGui::Checkbox("Show drag boxes", &_showdraggers); ImGui::PopItemWidth(); ImGui::Separator(); auto brush = _getIfSame(); if (brush && ImGui::Button("Apply")) { brush->setWidth(_linewidth); brush->getBrushShape()->texture = _tex; brush->getBrushShape()->setTexOffset(_offset); } } BrushComponent* BrushTool::_getIfSame() const { auto selected = getIfBrush(EditorShared::getSelectTool().getSelected()); bool linebrush = selected && selected->getEntity()->getName() == brushEntities[Line]; if (((_type == Line) ^ linebrush)) return nullptr; return selected; } } <|endoftext|>
<commit_before>#include <shared_ptr.h> #include <move.h> #include "yatf/include/yatf.h" using namespace yacppl; TEST(shared_ptr, can_create_empty_pointer) { shared_ptr<int> ptr; REQUIRE(ptr.get() == nullptr); REQUIRE(ptr.get_ref_count() == 0); } TEST(shared_ptr, can_create_valid_pointer) { shared_ptr<int> ptr(new int(4)); REQUIRE_FALSE(ptr.get() == nullptr); } TEST(shared_ptr, can_be_derefereced) { shared_ptr<int> ptr(new int(4)); REQUIRE(*ptr == 4); } TEST(shared_ptr, can_be_assigned) { shared_ptr<int> ptr; ptr = make_shared<int>(5); REQUIRE(*ptr == 5); } TEST(shared_ptr, can_be_copied) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2; ptr2 = ptr1; REQUIRE(*ptr1 == 10); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get_ref_count() == 2); REQUIRE(ptr2.get_ref_count() == 2); REQUIRE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_moved) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2; ptr2 = move(ptr1); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get() == nullptr); REQUIRE(ptr1.get_ref_count() == 0); REQUIRE(ptr2.get_ref_count() == 1); REQUIRE_FALSE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_constructed_by_copy) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2(ptr1); REQUIRE(*ptr1 == 10); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get_ref_count() == 2); REQUIRE(ptr2.get_ref_count() == 2); REQUIRE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_constructed_by_moving) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2 = move(ptr1); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get() == nullptr); REQUIRE(ptr1.get_ref_count() == 0); REQUIRE(ptr2.get_ref_count() == 1); REQUIRE_FALSE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_casted_to_raw_pointer) { auto ptr = make_shared<int>(10); int *raw_ptr = ptr; REQUIRE(*ptr == 10); REQUIRE(*raw_ptr == 10); REQUIRE(ptr.get() == raw_ptr); } TEST(shared_ptr, can_have_its_value_modified) { auto ptr = make_shared(10); *ptr = 39; REQUIRE(*ptr == 39); REQUIRE(ptr.get_ref_count() == 1); } <commit_msg>Minor changes in shared_ptr changes<commit_after>#include <shared_ptr.h> #include <move.h> #include "yatf/include/yatf.h" using namespace yacppl; TEST(shared_ptr, can_create_empty_pointer) { shared_ptr<int> ptr; REQUIRE(ptr.get() == nullptr); REQUIRE(ptr.get_ref_count() == 0); } TEST(shared_ptr, can_create_valid_pointer) { shared_ptr<int> ptr(new int(4)); REQUIRE(ptr.get() != nullptr); } TEST(shared_ptr, can_be_derefereced) { shared_ptr<int> ptr(new int(4)); REQUIRE(*ptr == 4); } TEST(shared_ptr, can_be_assigned) { shared_ptr<int> ptr; ptr = make_shared<int>(5); REQUIRE(*ptr == 5); } TEST(shared_ptr, can_be_copied) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2; ptr2 = ptr1; REQUIRE(*ptr1 == 10); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get_ref_count() == 2); REQUIRE(ptr2.get_ref_count() == 2); REQUIRE(ptr1.get() == ptr2.get()); { shared_ptr<int> ptr3; ptr3 = ptr2; REQUIRE(*ptr1 == 10); REQUIRE(*ptr2 == 10); REQUIRE(*ptr3 == 10); REQUIRE(ptr1.get_ref_count() == 3); REQUIRE(ptr2.get_ref_count() == 3); REQUIRE(ptr2.get_ref_count() == 3); REQUIRE(ptr1.get() == ptr3.get()); } REQUIRE(ptr1.get_ref_count() == 2); REQUIRE(ptr2.get_ref_count() == 2); REQUIRE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_moved) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2; ptr2 = move(ptr1); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get() == nullptr); REQUIRE(ptr1.get_ref_count() == 0); REQUIRE(ptr2.get_ref_count() == 1); REQUIRE_FALSE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_constructed_by_copy) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2(ptr1); REQUIRE(*ptr1 == 10); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get_ref_count() == 2); REQUIRE(ptr2.get_ref_count() == 2); REQUIRE(ptr1.get() == ptr2.get()); } TEST(shared_ptr, can_be_constructed_by_moving) { auto ptr1 = make_shared<int>(10); shared_ptr<int> ptr2 = move(ptr1); REQUIRE(*ptr2 == 10); REQUIRE(ptr1.get() == nullptr); REQUIRE(ptr1.get_ref_count() == 0); REQUIRE(ptr2.get_ref_count() == 1); REQUIRE(ptr1.get() != ptr2.get()); } TEST(shared_ptr, can_be_casted_to_raw_pointer) { auto ptr = make_shared<int>(10); int *raw_ptr = ptr; REQUIRE(*ptr == 10); REQUIRE(*raw_ptr == 10); REQUIRE(ptr.get() == raw_ptr); } TEST(shared_ptr, can_have_its_value_modified) { auto ptr = make_shared(10); *ptr = 39; REQUIRE(*ptr == 39); REQUIRE(ptr.get_ref_count() == 1); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP #define MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #pragma GCC diagnostic pop namespace mapnik { namespace json { namespace grammar { namespace x3 = boost::spirit::x3; class unicode_string_tag; using unicode_string_grammar_type = x3::rule<unicode_string_tag, std::string>; BOOST_SPIRIT_DECLARE(unicode_string_grammar_type); } grammar::unicode_string_grammar_type const& unicode_string_grammar(); }} #endif // MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP <commit_msg>consistent syntax<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP #define MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #pragma GCC diagnostic pop namespace mapnik { namespace json { namespace grammar { namespace x3 = boost::spirit::x3; using unicode_string_grammar_type = x3::rule<class unicode_string_tag, std::string>; BOOST_SPIRIT_DECLARE(unicode_string_grammar_type); } grammar::unicode_string_grammar_type const& unicode_string_grammar(); }} #endif // MAPNIK_JSON_UNICODE_STRING_GRAMMAR_X3_HPP <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2017 * * * * 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 <ghoul/logging/logmanager.h> namespace openspace::properties { // The following macros can be used to quickly generate the necessary PropertyDelegate // specializations required by the TemplateProperty class. Use the // REGISTER_TEMPLATEPROPERTY_HEADER macro in the header file and the // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new specialization of // a TemplateProperty // CLASS_NAME = The string that the Property::className() should return as well as the // C++ class name for which a typedef will be created // TYPE = The template parameter T for which the TemplateProperty is specialized #define REGISTER_TEMPLATEPROPERTY_HEADER(CLASS_NAME, TYPE) \ using CLASS_NAME = TemplateProperty<TYPE>; \ \ template <> \ std::string PropertyDelegate<TemplateProperty<TYPE>>::className(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::defaultValue<TYPE>(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromLuaValue(lua_State* state, \ bool& success); \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toLuaValue(lua_State* state, \ TYPE value); \ \ template <> \ int PropertyDelegate<TemplateProperty<TYPE>>::typeLua(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromString(std::string value, \ bool& success); \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toString(std::string& outValue, \ TYPE inValue); // CLASS_NAME = The string that the Property::className() should return as well as the // C++ class name for which a typedef will be created // TYPE = The template parameter T for which the TemplateProperty is specialized // DEFAULT_VALUE = The value (as type T) which should be used as a default value // FROM_LUA_LAMBDA_EXPRESSION = A lambda expression receiving a lua_State* as the first // parameter, a bool& as the second parameter and returning // a value T. It is used by the fromLua method of // TemplateProperty. The lambda expression must extract the // stored value from the lua_State, return the value and // report success in the second argument // TO_LUA_LAMBDA_EXPRESSION = A lambda expression receiving a lua_State*, a value T and // returning a bool. The lambda expression must encode the // value T onto the lua_State stack and return the success // LUA_TYPE = The Lua type that will be produced/consumed by the previous // Lambda expressions #define REGISTER_TEMPLATEPROPERTY_SOURCE(CLASS_NAME, TYPE, DEFAULT_VALUE, \ FROM_LUA_LAMBDA_EXPRESSION, \ TO_LUA_LAMBDA_EXPRESSION, \ FROM_STRING_LAMBDA_EXPRESSION, \ TO_STRING_LAMBDA_EXPRESSION, LUA_TYPE) \ template <> \ std::string PropertyDelegate<TemplateProperty<TYPE>>::className() \ { \ return #CLASS_NAME; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::defaultValue<TYPE>() \ { \ return DEFAULT_VALUE; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromLuaValue<TYPE>(lua_State * state, \ bool& success) \ { \ return FROM_LUA_LAMBDA_EXPRESSION(state, success); \ } \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toLuaValue<TYPE>(lua_State * state, \ TYPE value) \ { \ return TO_LUA_LAMBDA_EXPRESSION(state, value); \ } \ \ template <> \ int PropertyDelegate<TemplateProperty<TYPE>>::typeLua() \ { \ return LUA_TYPE; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromString(std::string value, \ bool& success) \ { \ return FROM_STRING_LAMBDA_EXPRESSION(value, success); \ } \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toString(std::string& outValue, \ TYPE inValue) \ { \ return TO_STRING_LAMBDA_EXPRESSION(outValue, inValue); \ } \ // Delegating constructors are necessary; automatic template deduction cannot // deduce template argument for 'U' if 'default' methods are used as default values in // a single constructor template <typename T> TemplateProperty<T>::TemplateProperty(std::string identifier, std::string guiName, Property::Visibility visibility) : TemplateProperty<T>( std::move(identifier), std::move(guiName), PropertyDelegate<TemplateProperty<T>>::template defaultValue<T>(), visibility) { } template <typename T> TemplateProperty<T>::TemplateProperty(std::string identifier, std::string guiName, T value, Property::Visibility visibility) : Property(std::move(identifier), std::move(guiName), visibility) , _value(std::move(value)) {} template <typename T> std::string TemplateProperty<T>::className() const { return PropertyDelegate<TemplateProperty<T>>::className(); } //template <typename T> //std::string TemplateProperty<T>::description() { // return //} template <typename T> TemplateProperty<T>::operator T() { return _value; } template <typename T> TemplateProperty<T>::operator T() const { return _value; } template <typename T> TemplateProperty<T>& TemplateProperty<T>::operator=(T val) { setValue(val); return *this; } template <typename T> T openspace::properties::TemplateProperty<T>::value() const { return _value; } template <typename T> void openspace::properties::TemplateProperty<T>::setValue(T val) { const bool changed = (val != _value); if (changed) { _value = std::move(val); notifyListener(); } } template <typename T> std::ostream& operator<<(std::ostream& os, const TemplateProperty<T>& obj) { os << obj.value(); return os; } template <typename T> ghoul::any TemplateProperty<T>::get() const { return ghoul::any(_value); } template <typename T> void TemplateProperty<T>::set(ghoul::any value) { try { T v = ghoul::any_cast<T>(std::move(value)); if (v != _value) { _value = std::move(v); notifyListener(); } } catch (std::bad_any_cast&) { LERRORC("TemplateProperty", "Illegal cast from '" << value.type().name() << "' to '" << typeid(T).name() << "'"); } } template <typename T> const std::type_info& TemplateProperty<T>::type() const { return typeid(T); } template <typename T> bool TemplateProperty<T>::getLuaValue(lua_State* state) const { bool success = PropertyDelegate<TemplateProperty<T>>::template toLuaValue<T>( state, _value ); return success; } template <typename T> bool TemplateProperty<T>::setLuaValue(lua_State* state) { bool success = false; T thisValue = PropertyDelegate<TemplateProperty<T>>::template fromLuaValue<T>( state, success ); if (success) { set(ghoul::any(thisValue)); } return success; } template <typename T> int TemplateProperty<T>::typeLua() const { return PropertyDelegate<TemplateProperty<T>>::typeLua(); } template <typename T> bool TemplateProperty<T>::getStringValue(std::string& value) const { bool success = PropertyDelegate<TemplateProperty<T>>::template toString<T>( value, _value ); return success; } template <typename T> bool TemplateProperty<T>::setStringValue(std::string value) { bool success = false; T thisValue = PropertyDelegate<TemplateProperty<T>>::template fromString<T>( value, success ); if (success) { set(ghoul::any(thisValue)); } return success; } } // namespace openspace::properties <commit_msg>Convert std::bad_any_cast back to ghoul::bad_any_cast<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2017 * * * * 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 <ghoul/logging/logmanager.h> namespace openspace::properties { // The following macros can be used to quickly generate the necessary PropertyDelegate // specializations required by the TemplateProperty class. Use the // REGISTER_TEMPLATEPROPERTY_HEADER macro in the header file and the // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new specialization of // a TemplateProperty // CLASS_NAME = The string that the Property::className() should return as well as the // C++ class name for which a typedef will be created // TYPE = The template parameter T for which the TemplateProperty is specialized #define REGISTER_TEMPLATEPROPERTY_HEADER(CLASS_NAME, TYPE) \ using CLASS_NAME = TemplateProperty<TYPE>; \ \ template <> \ std::string PropertyDelegate<TemplateProperty<TYPE>>::className(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::defaultValue<TYPE>(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromLuaValue(lua_State* state, \ bool& success); \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toLuaValue(lua_State* state, \ TYPE value); \ \ template <> \ int PropertyDelegate<TemplateProperty<TYPE>>::typeLua(); \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromString(std::string value, \ bool& success); \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toString(std::string& outValue, \ TYPE inValue); // CLASS_NAME = The string that the Property::className() should return as well as the // C++ class name for which a typedef will be created // TYPE = The template parameter T for which the TemplateProperty is specialized // DEFAULT_VALUE = The value (as type T) which should be used as a default value // FROM_LUA_LAMBDA_EXPRESSION = A lambda expression receiving a lua_State* as the first // parameter, a bool& as the second parameter and returning // a value T. It is used by the fromLua method of // TemplateProperty. The lambda expression must extract the // stored value from the lua_State, return the value and // report success in the second argument // TO_LUA_LAMBDA_EXPRESSION = A lambda expression receiving a lua_State*, a value T and // returning a bool. The lambda expression must encode the // value T onto the lua_State stack and return the success // LUA_TYPE = The Lua type that will be produced/consumed by the previous // Lambda expressions #define REGISTER_TEMPLATEPROPERTY_SOURCE(CLASS_NAME, TYPE, DEFAULT_VALUE, \ FROM_LUA_LAMBDA_EXPRESSION, \ TO_LUA_LAMBDA_EXPRESSION, \ FROM_STRING_LAMBDA_EXPRESSION, \ TO_STRING_LAMBDA_EXPRESSION, LUA_TYPE) \ template <> \ std::string PropertyDelegate<TemplateProperty<TYPE>>::className() \ { \ return #CLASS_NAME; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::defaultValue<TYPE>() \ { \ return DEFAULT_VALUE; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromLuaValue<TYPE>(lua_State * state, \ bool& success) \ { \ return FROM_LUA_LAMBDA_EXPRESSION(state, success); \ } \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toLuaValue<TYPE>(lua_State * state, \ TYPE value) \ { \ return TO_LUA_LAMBDA_EXPRESSION(state, value); \ } \ \ template <> \ int PropertyDelegate<TemplateProperty<TYPE>>::typeLua() \ { \ return LUA_TYPE; \ } \ \ template <> \ template <> \ TYPE PropertyDelegate<TemplateProperty<TYPE>>::fromString(std::string value, \ bool& success) \ { \ return FROM_STRING_LAMBDA_EXPRESSION(value, success); \ } \ \ template <> \ template <> \ bool PropertyDelegate<TemplateProperty<TYPE>>::toString(std::string& outValue, \ TYPE inValue) \ { \ return TO_STRING_LAMBDA_EXPRESSION(outValue, inValue); \ } \ // Delegating constructors are necessary; automatic template deduction cannot // deduce template argument for 'U' if 'default' methods are used as default values in // a single constructor template <typename T> TemplateProperty<T>::TemplateProperty(std::string identifier, std::string guiName, Property::Visibility visibility) : TemplateProperty<T>( std::move(identifier), std::move(guiName), PropertyDelegate<TemplateProperty<T>>::template defaultValue<T>(), visibility) { } template <typename T> TemplateProperty<T>::TemplateProperty(std::string identifier, std::string guiName, T value, Property::Visibility visibility) : Property(std::move(identifier), std::move(guiName), visibility) , _value(std::move(value)) {} template <typename T> std::string TemplateProperty<T>::className() const { return PropertyDelegate<TemplateProperty<T>>::className(); } //template <typename T> //std::string TemplateProperty<T>::description() { // return //} template <typename T> TemplateProperty<T>::operator T() { return _value; } template <typename T> TemplateProperty<T>::operator T() const { return _value; } template <typename T> TemplateProperty<T>& TemplateProperty<T>::operator=(T val) { setValue(val); return *this; } template <typename T> T openspace::properties::TemplateProperty<T>::value() const { return _value; } template <typename T> void openspace::properties::TemplateProperty<T>::setValue(T val) { const bool changed = (val != _value); if (changed) { _value = std::move(val); notifyListener(); } } template <typename T> std::ostream& operator<<(std::ostream& os, const TemplateProperty<T>& obj) { os << obj.value(); return os; } template <typename T> ghoul::any TemplateProperty<T>::get() const { return ghoul::any(_value); } template <typename T> void TemplateProperty<T>::set(ghoul::any value) { try { T v = ghoul::any_cast<T>(std::move(value)); if (v != _value) { _value = std::move(v); notifyListener(); } } catch (ghoul::bad_any_cast&) { LERRORC("TemplateProperty", "Illegal cast from '" << value.type().name() << "' to '" << typeid(T).name() << "'"); } } template <typename T> const std::type_info& TemplateProperty<T>::type() const { return typeid(T); } template <typename T> bool TemplateProperty<T>::getLuaValue(lua_State* state) const { bool success = PropertyDelegate<TemplateProperty<T>>::template toLuaValue<T>( state, _value ); return success; } template <typename T> bool TemplateProperty<T>::setLuaValue(lua_State* state) { bool success = false; T thisValue = PropertyDelegate<TemplateProperty<T>>::template fromLuaValue<T>( state, success ); if (success) { set(ghoul::any(thisValue)); } return success; } template <typename T> int TemplateProperty<T>::typeLua() const { return PropertyDelegate<TemplateProperty<T>>::typeLua(); } template <typename T> bool TemplateProperty<T>::getStringValue(std::string& value) const { bool success = PropertyDelegate<TemplateProperty<T>>::template toString<T>( value, _value ); return success; } template <typename T> bool TemplateProperty<T>::setStringValue(std::string value) { bool success = false; T thisValue = PropertyDelegate<TemplateProperty<T>>::template fromString<T>( value, success ); if (success) { set(ghoul::any(thisValue)); } return success; } } // namespace openspace::properties <|endoftext|>
<commit_before>#include "inferer.h" #include <functional> #include <unordered_map> namespace { using namespace grml; struct LiteralInferer : boost::static_visitor<Type> { Type operator()(int) const { return BasicType::INT; } Type operator()(bool) const { return BasicType::BOOL; } Type operator()(double) const { return BasicType::REAL; } }; struct DeclarationInferer : boost::static_visitor<std::pair<Identifier, Type> > { const Environment& env; DeclarationInferer(const Environment& e) : env(e) {} std::pair<Identifier, Type> operator()(const VariableDeclaration& d) const; std::pair<Identifier, Type> operator()(const FunctionDeclaration& d) const; }; struct ExpressionInferer : boost::static_visitor<Type> { using ResultType = ExpressionInferer::result_type; const Environment& env; ExpressionInferer(const Environment& e) : env(e) {} Type operator()(const Literal& e) const { return { boost::apply_visitor(LiteralInferer(), e) }; } Type operator()(const Identifier& e) const { return { env.at(e) }; } Type operator()(const UnaryOperation& e) const { return infer(e.rhs, env); } Type operator()(const BinaryOperation& e) const { /* TODO: impl as f-call */ return infer(e.lhs, env); } Type operator()(const LetConstruct& e) const { auto scope = env; for (const auto& decl: e.declarations) { auto [ id, t ] = boost::apply_visitor(DeclarationInferer(scope), decl); scope.insert_or_assign(std::move(id), std::move(t)); } return infer(e.expression, std::move(scope)); } Type operator()(const IfConstruct& e) const { auto testSub = unify(infer(e.test, env), BasicType::BOOL); auto whenTrue = substitute(infer(e.whenTrue, env), testSub); auto whenFalse = substitute(infer(e.whenFalse, env), testSub); auto bodySub = unify(whenTrue, whenFalse); return substitute(whenTrue, bodySub); } Type operator()(const FunctionCall& e) const { TypeVariable result; FunctionType::Parameters params; for (const auto& arg: e.arguments) { auto p = infer(arg, env); params.push_back(p); } auto rhs = FunctionType(result, params); auto lhs = infer(e.name, env); auto substitution = unify(lhs, rhs); return substitute(boost::get<FunctionType>(lhs).result, substitution); } }; std::pair<Identifier, Type> DeclarationInferer::operator()(const VariableDeclaration& d) const { return std::make_pair(d.name, infer(d.expression, env)); } std::pair<Identifier, Type> DeclarationInferer::operator()(const FunctionDeclaration& d) const { auto scope = env; FunctionType::Parameters params; for (const auto& param: d.parameters) { params.push_back(TypeVariable()); scope.insert_or_assign(param, params.back()); } FunctionType self = FunctionType(TypeVariable(), std::move(params)); scope.insert_or_assign(d.name, self); auto result = infer(d.expression, std::move(scope)); return std::make_pair(d.name, FunctionType(std::move(result), std::move(self.parameters))); } } std::size_t grml::detail::IdHasher::operator()(const grml::Identifier& id) const { return std::hash<std::string>{}(id.name); } namespace grml { Type infer(const Expression& expr, const Environment& env) { return boost::apply_visitor(ExpressionInferer(env), expr); } } <commit_msg>Fix passing functions as parameters<commit_after>#include "inferer.h" #include <functional> #include <unordered_map> namespace { using namespace grml; struct LiteralInferer : boost::static_visitor<Type> { Type operator()(int) const { return BasicType::INT; } Type operator()(bool) const { return BasicType::BOOL; } Type operator()(double) const { return BasicType::REAL; } }; struct DeclarationInferer : boost::static_visitor<std::pair<Identifier, Type> > { const Environment& env; DeclarationInferer(const Environment& e) : env(e) {} std::pair<Identifier, Type> operator()(const VariableDeclaration& d) const; std::pair<Identifier, Type> operator()(const FunctionDeclaration& d) const; }; struct ExpressionInferer : boost::static_visitor<Type> { using ResultType = ExpressionInferer::result_type; const Environment& env; ExpressionInferer(const Environment& e) : env(e) {} Type operator()(const Literal& e) const { return { boost::apply_visitor(LiteralInferer(), e) }; } Type operator()(const Identifier& e) const { return { env.at(e) }; } Type operator()(const UnaryOperation& e) const { return infer(e.rhs, env); } Type operator()(const BinaryOperation& e) const { /* TODO: impl as f-call */ return infer(e.lhs, env); } Type operator()(const LetConstruct& e) const { auto scope = env; for (const auto& decl: e.declarations) { auto [ id, t ] = boost::apply_visitor(DeclarationInferer(scope), decl); scope.insert_or_assign(std::move(id), std::move(t)); } return infer(e.expression, std::move(scope)); } Type operator()(const IfConstruct& e) const { auto testSub = unify(infer(e.test, env), BasicType::BOOL); auto whenTrue = substitute(infer(e.whenTrue, env), testSub); auto whenFalse = substitute(infer(e.whenFalse, env), testSub); auto bodySub = unify(whenTrue, whenFalse); return substitute(whenTrue, bodySub); } Type operator()(const FunctionCall& e) const { FunctionType::Parameters params; for (const auto& arg: e.arguments) { auto p = infer(arg, env); params.push_back(p); } auto rhs = FunctionType(TypeVariable(), params); auto lhs = infer(e.name, env); auto substitution = unify(lhs, rhs); auto result = substitute(lhs, substitution); return boost::get<FunctionType>(result).result; } }; std::pair<Identifier, Type> DeclarationInferer::operator()(const VariableDeclaration& d) const { return std::make_pair(d.name, infer(d.expression, env)); } std::pair<Identifier, Type> DeclarationInferer::operator()(const FunctionDeclaration& d) const { auto scope = env; FunctionType::Parameters params; for (const auto& param: d.parameters) { params.push_back(TypeVariable()); scope.insert_or_assign(param, params.back()); } FunctionType self = FunctionType(TypeVariable(), std::move(params)); scope.insert_or_assign(d.name, self); auto result = infer(d.expression, std::move(scope)); return std::make_pair(d.name, FunctionType(std::move(result), std::move(self.parameters))); } } std::size_t grml::detail::IdHasher::operator()(const grml::Identifier& id) const { return std::hash<std::string>{}(id.name); } namespace grml { Type infer(const Expression& expr, const Environment& env) { return boost::apply_visitor(ExpressionInferer(env), expr); } } <|endoftext|>
<commit_before>// testConfig.cpp : Derived from testPattern.cpp. // #include "log4cpp/Portability.hh" #ifdef WIN32 #include <windows.h> #endif #ifdef LOG4CPP_HAVE_UNISTD_H #include <unistd.h> #endif #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/OstreamAppender.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" #include "log4cpp/PatternLayout.hh" #include "log4cpp/SimpleConfigurator.hh" double calcPi() { double denominator = 3.0; double retVal = 4.0; long i; for (i = 0; i < 50000000l; i++) { retVal = retVal - (4.0 / denominator); denominator += 2.0; retVal = retVal + (4.0 /denominator); denominator += 2.0; } return retVal; } int main(int argc, char* argv[]) { try { log4cpp::SimpleConfigurator::configure("log4cpp.init"); } catch(log4cpp::ConfigureFailure& f) { std::cout << "Configure Problem " << f.what() << std::endl; return -1; } log4cpp::Category& root = log4cpp::Category::getRoot(); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); calcPi(); sub2.error("sub2 error"); sub2.warn("sub2 warn"); root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); #ifdef WIN32 Sleep(3000); #else sleep(3); #endif sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.error("%s %s %d", "test", "vform", 123); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 << log4cpp::CategoryStream::ENDLINE << "..warn4"; log4cpp::Category::shutdown(); return 0; } <commit_msg>read $srcdir for location of log4cpp.init in order to fix distcheck target.<commit_after>// testConfig.cpp : Derived from testPattern.cpp. // #include "log4cpp/Portability.hh" #ifdef WIN32 #include <windows.h> #endif #ifdef LOG4CPP_HAVE_UNISTD_H #include <unistd.h> #endif #include <stdlib.h> #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/OstreamAppender.hh" #include "log4cpp/FileAppender.hh" #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" #include "log4cpp/PatternLayout.hh" #include "log4cpp/SimpleConfigurator.hh" double calcPi() { double denominator = 3.0; double retVal = 4.0; long i; for (i = 0; i < 50000000l; i++) { retVal = retVal - (4.0 / denominator); denominator += 2.0; retVal = retVal + (4.0 /denominator); denominator += 2.0; } return retVal; } int main(int argc, char* argv[]) { try { /* looking for the init file in $srcdir is a requirement of automake's distcheck target. */ char* srcdir = ::getenv("srcdir"); std::string initFileName((srcdir == NULL) ? "./log4cpp.init" : std::string(srcdir) + "/log4cpp.init"); log4cpp::SimpleConfigurator::configure(initFileName); } catch(log4cpp::ConfigureFailure& f) { std::cout << "Configure Problem " << f.what() << std::endl; return -1; } log4cpp::Category& root = log4cpp::Category::getRoot(); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); calcPi(); sub2.error("sub2 error"); sub2.warn("sub2 warn"); root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); #ifdef WIN32 Sleep(3000); #else sleep(3); #endif sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.error("%s %s %d", "test", "vform", 123); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 << log4cpp::CategoryStream::ENDLINE << "..warn4"; log4cpp::Category::shutdown(); return 0; } <|endoftext|>
<commit_before><commit_msg>Improvement in the speed of general memory access. The idea was taken from patch written by LightCone<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightTaskOrbit.cpp */ #include "FlightTaskOrbit.hpp" #include <mathlib/mathlib.h> using namespace matrix; FlightTaskOrbit::FlightTaskOrbit() { _sticks_data_required = false; } bool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command) { const float &r = command.param3; // commanded radius const float &v = command.param4; // commanded velocity if (setRadius(r) && setVelocity(v)) { return FlightTaskManual::applyCommandParameters(command); } return false; } bool FlightTaskOrbit::setRadius(const float r) { if (math::isInRange(r, radius_min, radius_max)) { // radius is more important than velocity for safety if (!checkAcceleration(r, _v, acceleration_max)) { _v = sqrtf(acceleration_max * r); } _r = r; return true; } return false; } bool FlightTaskOrbit::setVelocity(const float v) { if (fabs(v) < velocity_max && checkAcceleration(_r, v, acceleration_max)) { _v = v; return true; } return false; } bool FlightTaskOrbit::checkAcceleration(float r, float v, float a) { return v * v < a * r; } bool FlightTaskOrbit::activate() { bool ret = FlightTaskManual::activate(); _r = 1.f; _v = 0.5f; _z = _position(2); _center = Vector2f(_position.data()); _center(0) -= _r; // need a valid position and velocity ret = ret && PX4_ISFINITE(_position(0)) && PX4_ISFINITE(_position(1)) && PX4_ISFINITE(_position(2)) && PX4_ISFINITE(_velocity(0)) && PX4_ISFINITE(_velocity(1)) && PX4_ISFINITE(_velocity(2)); return ret; } bool FlightTaskOrbit::update() { // stick input adjusts parameters const float r = _r + _sticks_expo(0) * _deltatime; const float v = _v - _sticks_expo(1) * _deltatime; _z += _sticks_expo(2) * _deltatime; setRadius(r); setVelocity(v); _position_setpoint = Vector3f(NAN, NAN, _z); // xy velocity to go around in a circle Vector2f center_to_position = Vector2f(_position.data()) - _center; Vector2f velocity_xy = Vector2f(center_to_position(1), -center_to_position(0)); velocity_xy = velocity_xy.unit_or_zero(); velocity_xy *= _v; // xy velocity adjustment to stay on the radius distance velocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero(); _velocity_setpoint = Vector3f(velocity_xy(0), velocity_xy(1), 0.f); // make vehicle front always point towards the center _yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F; // yawspeed feed-forward because we know the necessary angular rate _yawspeed_setpoint = -_v / _r; return true; } <commit_msg>FlightTaskOrbit: speed up stick input to a fixed time frame<commit_after>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightTaskOrbit.cpp */ #include "FlightTaskOrbit.hpp" #include <mathlib/mathlib.h> using namespace matrix; FlightTaskOrbit::FlightTaskOrbit() { _sticks_data_required = false; } bool FlightTaskOrbit::applyCommandParameters(const vehicle_command_s &command) { const float &r = command.param3; // commanded radius const float &v = command.param4; // commanded velocity if (setRadius(r) && setVelocity(v)) { return FlightTaskManual::applyCommandParameters(command); } return false; } bool FlightTaskOrbit::setRadius(const float r) { if (math::isInRange(r, radius_min, radius_max)) { // radius is more important than velocity for safety if (!checkAcceleration(r, _v, acceleration_max)) { _v = sqrtf(acceleration_max * r); } _r = r; return true; } return false; } bool FlightTaskOrbit::setVelocity(const float v) { if (fabs(v) < velocity_max && checkAcceleration(_r, v, acceleration_max)) { _v = v; return true; } return false; } bool FlightTaskOrbit::checkAcceleration(float r, float v, float a) { return v * v < a * r; } bool FlightTaskOrbit::activate() { bool ret = FlightTaskManual::activate(); _r = 1.f; _v = 0.5f; _z = _position(2); _center = Vector2f(_position.data()); _center(0) -= _r; // need a valid position and velocity ret = ret && PX4_ISFINITE(_position(0)) && PX4_ISFINITE(_position(1)) && PX4_ISFINITE(_position(2)) && PX4_ISFINITE(_velocity(0)) && PX4_ISFINITE(_velocity(1)) && PX4_ISFINITE(_velocity(2)); return ret; } bool FlightTaskOrbit::update() { // stick input adjusts parameters within a fixed time frame const float r = _r + _sticks_expo(0) * _deltatime * (radius_max / 8.f); const float v = _v - _sticks_expo(1) * _deltatime * (velocity_max / 4.f); _z += _sticks_expo(2) * _deltatime; setRadius(r); setVelocity(v); _position_setpoint = Vector3f(NAN, NAN, _z); // xy velocity to go around in a circle Vector2f center_to_position = Vector2f(_position.data()) - _center; Vector2f velocity_xy = Vector2f(center_to_position(1), -center_to_position(0)); velocity_xy = velocity_xy.unit_or_zero(); velocity_xy *= _v; // xy velocity adjustment to stay on the radius distance velocity_xy += (_r - center_to_position.norm()) * center_to_position.unit_or_zero(); _velocity_setpoint = Vector3f(velocity_xy(0), velocity_xy(1), 0.f); // make vehicle front always point towards the center _yaw_setpoint = atan2f(center_to_position(1), center_to_position(0)) + M_PI_F; // yawspeed feed-forward because we know the necessary angular rate _yawspeed_setpoint = -_v / _r; return true; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com> // #include "PlaybackAnimatedUpdateItem.h" #include "GeoDataAnimatedUpdate.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "GeoDataTypes.h" #include <QString> namespace Marble { PlaybackAnimatedUpdateItem::PlaybackAnimatedUpdateItem( GeoDataAnimatedUpdate* animatedUpdate ) { m_animatedUpdate = animatedUpdate; m_rootDocument = rootDocument( m_animatedUpdate ); m_playing = false; } const GeoDataAnimatedUpdate* PlaybackAnimatedUpdateItem::animatedUpdate() const { return m_animatedUpdate; } double PlaybackAnimatedUpdateItem::duration() const { return m_animatedUpdate->duration(); } void PlaybackAnimatedUpdateItem::play() { if( m_playing ){ return; } m_playing = true; if ( !m_rootDocument || !m_animatedUpdate->update() ) { return; } // Apply updates of elements if ( m_animatedUpdate->update()->change() ) { QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList(); for( int i = 0; i < placemarkList.size(); i++ ){ GeoDataPlacemark* placemark = placemarkList.at( i ); QString targetId = placemark->targetId(); if( placemark->isBalloonVisible() ){ GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ){ emit balloonShown( static_cast<GeoDataPlacemark*>( feature ) ); } } else { emit balloonHidden(); } } } // Create new elements if( m_animatedUpdate->update()->create() ){ for( int index = 0; index < m_animatedUpdate->update()->create()->size(); ++index ) { GeoDataFeature* child = m_animatedUpdate->update()->create()->child( index ); if( child && ( child->nodeType() == GeoDataTypes::GeoDataDocumentType || child->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer *addContainer = static_cast<GeoDataContainer*>( child ); QString targetId = addContainer->targetId(); GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && ( feature->nodeType() == GeoDataTypes::GeoDataDocumentType || feature->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer* container = static_cast<GeoDataContainer*>( feature ); for( int i = 0; i < addContainer->size(); ++i ) { emit added( container, addContainer->child( i ), -1 ); if( addContainer->child( i )->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( addContainer->child( i ) ); if( placemark->isBalloonVisible() ) { emit balloonShown( placemark ); } } } } } } } // Delete elements if( m_animatedUpdate->update()->getDelete() ){ for( int index = 0; index < m_animatedUpdate->update()->getDelete()->size(); ++index ) { GeoDataFeature* child = m_animatedUpdate->update()->getDelete()->child( index ); QString targetId = child->targetId(); GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && canDelete( feature->nodeType() ) ) { m_deletedObjects.append( feature ); emit removed( feature ); if( feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( feature ); if( placemark->isBalloonVisible() ) { emit balloonHidden(); } } } } } } GeoDataFeature* PlaybackAnimatedUpdateItem::findFeature(GeoDataFeature* feature, const QString& id ) const { if ( feature && feature->id() == id ){ return feature; } GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( feature ); if ( container ){ QVector<GeoDataFeature*>::Iterator end = container->end(); QVector<GeoDataFeature*>::Iterator iter = container->begin(); for( ; iter != end; ++iter ){ GeoDataFeature *foundFeature = findFeature( *iter, id ); if ( foundFeature ){ return foundFeature; } } } return 0; } GeoDataDocument *PlaybackAnimatedUpdateItem::rootDocument( GeoDataObject* object ) const { if( !object || !object->parent() ){ GeoDataDocument* document = dynamic_cast<GeoDataDocument*>( object ); return document; } else { return rootDocument( object->parent() ); } return 0; } void PlaybackAnimatedUpdateItem::pause() { //do nothing } void PlaybackAnimatedUpdateItem::seek( double position ) { Q_UNUSED( position ); play(); } void PlaybackAnimatedUpdateItem::stop() { if( !m_playing ){ return; } m_playing = false; if ( m_animatedUpdate->update()->change() ) { QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList(); for( int i = 0; i < placemarkList.size(); i++ ){ GeoDataPlacemark* placemark = placemarkList.at( i ); QString targetId = placemark->targetId(); GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( placemark->isBalloonVisible() ){ if( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ){ emit balloonHidden(); } } else { emit balloonShown( static_cast<GeoDataPlacemark*>( feature ) ); } } } if( m_animatedUpdate->update()->create() ){ for( int index = 0; index < m_animatedUpdate->update()->create()->size(); ++index ) { GeoDataFeature* feature = m_animatedUpdate->update()->create()->child( index ); if( feature && ( feature->nodeType() == GeoDataTypes::GeoDataDocumentType || feature->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer* container = static_cast<GeoDataContainer*>( feature ); for( int i = 0; i < container->size(); ++i ) { emit removed( container->child( i ) ); if( container->child( i )->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( container->child( i ) ); if( placemark->isBalloonVisible() ) { emit balloonHidden(); } } } } } } foreach( GeoDataFeature* feature, m_deletedObjects ) { GeoDataFeature* target = findFeature( m_rootDocument, feature->targetId() ); if ( target ) { /** @todo Do we have to note the original row position and restore it? */ Q_ASSERT( dynamic_cast<GeoDataContainer*>( target ) ); emit added( static_cast<GeoDataContainer*>( target ), feature, -1 ); if( feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( feature ); if( placemark->isBalloonVisible() ) { emit balloonShown( placemark ); } } } // else the root document was modified in an unfortunate way and we cannot restore it at this point } m_deletedObjects.clear(); } bool PlaybackAnimatedUpdateItem::isApplied() const { return m_playing; } bool PlaybackAnimatedUpdateItem::canDelete(const char *nodeType) const { return nodeType == GeoDataTypes::GeoDataDocumentType || nodeType == GeoDataTypes::GeoDataFolderType || nodeType == GeoDataTypes::GeoDataGroundOverlayType || nodeType == GeoDataTypes::GeoDataPlacemarkType || nodeType == GeoDataTypes::GeoDataScreenOverlayType || nodeType == GeoDataTypes::GeoDataPhotoOverlayType; } } #include "PlaybackAnimatedUpdateItem.moc" <commit_msg>Do not allow to remove/update element with empty id in Tours.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2014 Sanjiban Bairagya <sanjiban22393@gmail.com> // #include "PlaybackAnimatedUpdateItem.h" #include "GeoDataAnimatedUpdate.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "GeoDataTypes.h" #include <QString> namespace Marble { PlaybackAnimatedUpdateItem::PlaybackAnimatedUpdateItem( GeoDataAnimatedUpdate* animatedUpdate ) { m_animatedUpdate = animatedUpdate; m_rootDocument = rootDocument( m_animatedUpdate ); m_playing = false; } const GeoDataAnimatedUpdate* PlaybackAnimatedUpdateItem::animatedUpdate() const { return m_animatedUpdate; } double PlaybackAnimatedUpdateItem::duration() const { return m_animatedUpdate->duration(); } void PlaybackAnimatedUpdateItem::play() { if( m_playing ){ return; } m_playing = true; if ( !m_rootDocument || !m_animatedUpdate->update() ) { return; } // Apply updates of elements if ( m_animatedUpdate->update()->change() ) { QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList(); for( int i = 0; i < placemarkList.size(); i++ ){ GeoDataPlacemark* placemark = placemarkList.at( i ); QString targetId = placemark->targetId(); if( targetId.isEmpty() ) { continue; } if( placemark->isBalloonVisible() ){ GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ){ emit balloonShown( static_cast<GeoDataPlacemark*>( feature ) ); } } else { emit balloonHidden(); } } } // Create new elements if( m_animatedUpdate->update()->create() ){ for( int index = 0; index < m_animatedUpdate->update()->create()->size(); ++index ) { GeoDataFeature* child = m_animatedUpdate->update()->create()->child( index ); if( child && ( child->nodeType() == GeoDataTypes::GeoDataDocumentType || child->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer *addContainer = static_cast<GeoDataContainer*>( child ); QString targetId = addContainer->targetId(); GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && ( feature->nodeType() == GeoDataTypes::GeoDataDocumentType || feature->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer* container = static_cast<GeoDataContainer*>( feature ); for( int i = 0; i < addContainer->size(); ++i ) { emit added( container, addContainer->child( i ), -1 ); if( addContainer->child( i )->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( addContainer->child( i ) ); if( placemark->isBalloonVisible() ) { emit balloonShown( placemark ); } } } } } } } // Delete elements if( m_animatedUpdate->update()->getDelete() ){ for( int index = 0; index < m_animatedUpdate->update()->getDelete()->size(); ++index ) { GeoDataFeature* child = m_animatedUpdate->update()->getDelete()->child( index ); QString targetId = child->targetId(); if( targetId.isEmpty() ) { continue; } GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( feature && canDelete( feature->nodeType() ) ) { m_deletedObjects.append( feature ); emit removed( feature ); if( feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( feature ); if( placemark->isBalloonVisible() ) { emit balloonHidden(); } } } } } } GeoDataFeature* PlaybackAnimatedUpdateItem::findFeature(GeoDataFeature* feature, const QString& id ) const { if ( feature && feature->id() == id ){ return feature; } GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( feature ); if ( container ){ QVector<GeoDataFeature*>::Iterator end = container->end(); QVector<GeoDataFeature*>::Iterator iter = container->begin(); for( ; iter != end; ++iter ){ GeoDataFeature *foundFeature = findFeature( *iter, id ); if ( foundFeature ){ return foundFeature; } } } return 0; } GeoDataDocument *PlaybackAnimatedUpdateItem::rootDocument( GeoDataObject* object ) const { if( !object || !object->parent() ){ GeoDataDocument* document = dynamic_cast<GeoDataDocument*>( object ); return document; } else { return rootDocument( object->parent() ); } return 0; } void PlaybackAnimatedUpdateItem::pause() { //do nothing } void PlaybackAnimatedUpdateItem::seek( double position ) { Q_UNUSED( position ); play(); } void PlaybackAnimatedUpdateItem::stop() { if( !m_playing ){ return; } m_playing = false; if ( m_animatedUpdate->update()->change() ) { QVector<GeoDataPlacemark*> placemarkList = m_animatedUpdate->update()->change()->placemarkList(); for( int i = 0; i < placemarkList.size(); i++ ){ GeoDataPlacemark* placemark = placemarkList.at( i ); QString targetId = placemark->targetId(); if( targetId.isEmpty() ) { continue; } GeoDataFeature* feature = findFeature( m_rootDocument, targetId ); if( placemark->isBalloonVisible() ){ if( feature && feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ){ emit balloonHidden(); } } else { emit balloonShown( static_cast<GeoDataPlacemark*>( feature ) ); } } } if( m_animatedUpdate->update()->create() ){ for( int index = 0; index < m_animatedUpdate->update()->create()->size(); ++index ) { GeoDataFeature* feature = m_animatedUpdate->update()->create()->child( index ); if( feature && ( feature->nodeType() == GeoDataTypes::GeoDataDocumentType || feature->nodeType() == GeoDataTypes::GeoDataFolderType ) ) { GeoDataContainer* container = static_cast<GeoDataContainer*>( feature ); for( int i = 0; i < container->size(); ++i ) { emit removed( container->child( i ) ); if( container->child( i )->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( container->child( i ) ); if( placemark->isBalloonVisible() ) { emit balloonHidden(); } } } } } } foreach( GeoDataFeature* feature, m_deletedObjects ) { if( feature->targetId().isEmpty() ) { continue; } GeoDataFeature* target = findFeature( m_rootDocument, feature->targetId() ); if ( target ) { /** @todo Do we have to note the original row position and restore it? */ Q_ASSERT( dynamic_cast<GeoDataContainer*>( target ) ); emit added( static_cast<GeoDataContainer*>( target ), feature, -1 ); if( feature->nodeType() == GeoDataTypes::GeoDataPlacemarkType ) { GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( feature ); if( placemark->isBalloonVisible() ) { emit balloonShown( placemark ); } } } // else the root document was modified in an unfortunate way and we cannot restore it at this point } m_deletedObjects.clear(); } bool PlaybackAnimatedUpdateItem::isApplied() const { return m_playing; } bool PlaybackAnimatedUpdateItem::canDelete(const char *nodeType) const { return nodeType == GeoDataTypes::GeoDataDocumentType || nodeType == GeoDataTypes::GeoDataFolderType || nodeType == GeoDataTypes::GeoDataGroundOverlayType || nodeType == GeoDataTypes::GeoDataPlacemarkType || nodeType == GeoDataTypes::GeoDataScreenOverlayType || nodeType == GeoDataTypes::GeoDataPhotoOverlayType; } } #include "PlaybackAnimatedUpdateItem.moc" <|endoftext|>
<commit_before>#include "des.h" #include "des_data.h" DES::DES(ui64 key) { keygen(key); } ui64 DES::encrypt(ui64 block) { return des(block, false); } ui64 DES::decrypt(ui64 block) { return des(block, true); } ui64 DES::encrypt(ui64 block, ui64 key) { DES des(key); return des.des(block, false); } ui64 DES::decrypt(ui64 block, ui64 key) { DES des(key); return des.des(block, true); } void DES::keygen(ui64 key) { // initial key schedule calculation ui64 permuted_choice_1 = 0; // 56 bits for (ui8 i = 0; i < 56; i++) { permuted_choice_1 <<= 1; permuted_choice_1 |= (key >> (64-PC1[i])) & LB64_MASK; } // 28 bits ui32 C = (ui32) ((permuted_choice_1 >> 28) & 0x000000000fffffff); ui32 D = (ui32) (permuted_choice_1 & 0x000000000fffffff); // Calculation of the 16 keys for (ui8 i = 0; i < 16; i++) { // key schedule, shifting Ci and Di for (ui8 j = 0; j < iteration_shift[i]; j++) { C = (0x0fffffff & (C << 1)) | (0x00000001 & (C >> 27)); D = (0x0fffffff & (D << 1)) | (0x00000001 & (D >> 27)); } ui64 permuted_choice_2 = (((ui64) C) << 28) | (ui64) D; sub_key[i] = 0; for (ui8 j = 0; j < 48; j++) { sub_key[i] <<= 1; sub_key[i] |= (permuted_choice_2 >> (56-PC2[j])) & LB64_MASK; } } } ui64 DES::des(ui64 block, bool mode) { block = ip(block); ui32 L = (ui32) (block >> 32) & L64_MASK; ui32 R = (ui32) (block & L64_MASK); for (ui8 i = 0; i < 16; i++) { ui32 F = mode ? f(R, sub_key[15-i]) : f(R, sub_key[i]); feistel(L, R, F); } block = (((ui64) R) << 32) | (ui64) L; return pi(block); } ui64 DES::ip(ui64 block) { // initial permutation ui64 result = 0; for (ui8 i = 0; i < 64; i++) { result <<= 1; result |= (block >> (64-IP[i])) & LB64_MASK; } return result; } ui64 DES::pi(ui64 block) { // inverse initial permutation ui64 result = 0; for (ui8 i = 0; i < 64; i++) { result <<= 1; result |= (block >> (64-PI[i])) & LB64_MASK; } return result; } void DES::feistel(ui32 &L, ui32 &R, ui32 F) { ui32 temp = R; R = L ^ F; L = temp; } ui32 DES::f(ui32 R, ui64 k) // f(R,k) function { ui64 s_input = 0; for (ui8 i = 0; i < 48; i++) { s_input <<= 1; s_input |= (ui64) ((R >> (32-E[i])) & LB32_MASK); } // XORing expanded Ri with Ki s_input = s_input ^ k; // S-Box Tables ui32 s_output = 0; for (ui8 i = 0; i < 8; i++) { char row = (char) ((s_input & (0x0000840000000000 >> 6*i)) >> (42-6*i)); row = (row >> 4) | (row & 0x01); char column = (char) ((s_input & (0x0000780000000000 >> 6*i)) >> (43-6*i)); s_output <<= 4; s_output |= (ui32) (S[i][16*row + column] & 0x0f); } ui32 f_result = 0; for (ui8 i = 0; i < 32; i++) { f_result <<= 1; f_result |= (s_output >> (32 - P[i])) & LB32_MASK; } return f_result; } <commit_msg>minor<commit_after>#include "des.h" #include "des_data.h" DES::DES(ui64 key) { keygen(key); } ui64 DES::encrypt(ui64 block) { return des(block, false); } ui64 DES::decrypt(ui64 block) { return des(block, true); } ui64 DES::encrypt(ui64 block, ui64 key) { DES des(key); return des.des(block, false); } ui64 DES::decrypt(ui64 block, ui64 key) { DES des(key); return des.des(block, true); } void DES::keygen(ui64 key) { // initial key schedule calculation ui64 permuted_choice_1 = 0; // 56 bits for (ui8 i = 0; i < 56; i++) { permuted_choice_1 <<= 1; permuted_choice_1 |= (key >> (64-PC1[i])) & LB64_MASK; } // 28 bits ui32 C = (ui32) ((permuted_choice_1 >> 28) & 0x000000000fffffff); ui32 D = (ui32) (permuted_choice_1 & 0x000000000fffffff); // Calculation of the 16 keys for (ui8 i = 0; i < 16; i++) { // key schedule, shifting Ci and Di for (ui8 j = 0; j < iteration_shift[i]; j++) { C = (0x0fffffff & (C << 1)) | (0x00000001 & (C >> 27)); D = (0x0fffffff & (D << 1)) | (0x00000001 & (D >> 27)); } ui64 permuted_choice_2 = (((ui64) C) << 28) | (ui64) D; sub_key[i] = 0; for (ui8 j = 0; j < 48; j++) { sub_key[i] <<= 1; sub_key[i] |= (permuted_choice_2 >> (56-PC2[j])) & LB64_MASK; } } } ui64 DES::des(ui64 block, bool mode) { block = ip(block); ui32 L = (ui32) (block >> 32) & L64_MASK; ui32 R = (ui32) (block & L64_MASK); for (ui8 i = 0; i < 16; i++) { ui32 F = mode ? f(R, sub_key[15-i]) : f(R, sub_key[i]); feistel(L, R, F); } block = (((ui64) R) << 32) | (ui64) L; return pi(block); } ui64 DES::ip(ui64 block) { // initial permutation ui64 result = 0; for (ui8 i = 0; i < 64; i++) { result <<= 1; result |= (block >> (64-IP[i])) & LB64_MASK; } return result; } ui64 DES::pi(ui64 block) { // inverse initial permutation ui64 result = 0; for (ui8 i = 0; i < 64; i++) { result <<= 1; result |= (block >> (64-PI[i])) & LB64_MASK; } return result; } void DES::feistel(ui32 &L, ui32 &R, ui32 F) { ui32 temp = R; R = L ^ F; L = temp; } ui32 DES::f(ui32 R, ui64 k) // f(R,k) function { ui64 s_input = 0; for (ui8 i = 0; i < 48; i++) { s_input <<= 1; s_input |= (ui64) ((R >> (32-E[i])) & LB32_MASK); } // XORing expanded Ri with Ki s_input = s_input ^ k; // S-Box Tables ui32 s_output = 0; for (ui8 i = 0; i < 8; i++) { char row = (char) ((s_input & (0x0000840000000000 >> 6*i)) >> (42-6*i)); row = (row >> 4) | (row & 0x01); char column = (char) ((s_input & (0x0000780000000000 >> 6*i)) >> (43-6*i)); s_output <<= 4; s_output |= (ui32) (S[i][16*row + column] & 0x0f); } ui32 f_result = 0; for (ui8 i = 0; i < 32; i++) { f_result <<= 1; f_result |= (s_output >> (32 - P[i])) & LB32_MASK; } return f_result; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkPath.h" #include "SkRandom.h" #define W 400 #define H 400 #define N 10 constexpr SkScalar SH = SkIntToScalar(H); static void rnd_quad(SkPath* p, SkPaint* paint, SkRandom& rand) { p->moveTo(rand.nextRangeScalar(0, W), rand.nextRangeScalar(0, H)); for (int x = 0; x < 2; ++x) { p->quadTo(rand.nextRangeScalar(W / 4, W), rand.nextRangeScalar(0, H), rand.nextRangeScalar(0, W), rand.nextRangeScalar(H / 4, H)); } paint->setColor(rand.nextU()); SkScalar width = rand.nextRangeScalar(1, 5); width *= width; paint->setStrokeWidth(width); paint->setAlpha(0xFF); } static void rnd_cubic(SkPath* p, SkPaint* paint, SkRandom& rand) { p->moveTo(rand.nextRangeScalar(0, W), rand.nextRangeScalar(0, H)); for (int x = 0; x < 2; ++x) { p->cubicTo(rand.nextRangeScalar(W / 4, W), rand.nextRangeScalar(0, H), rand.nextRangeScalar(0, W), rand.nextRangeScalar(H / 4, H), rand.nextRangeScalar(W / 4, W), rand.nextRangeScalar(H / 4, H)); } paint->setColor(rand.nextU()); SkScalar width = rand.nextRangeScalar(1, 5); width *= width; paint->setStrokeWidth(width); paint->setAlpha(0xFF); } class BeziersGM : public skiagm::GM { public: BeziersGM() {} protected: SkString onShortName() override { return SkString("beziers"); } SkISize onISize() override { return SkISize::Make(W, H*2); } void onDraw(SkCanvas* canvas) override { SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkIntToScalar(9)/2); paint.setAntiAlias(true); SkRandom rand; for (int i = 0; i < N; i++) { SkPath p; rnd_quad(&p, &paint, rand); canvas->drawPath(p, paint); } canvas->translate(0, SH); for (int i = 0; i < N; i++) { SkPath p; rnd_cubic(&p, &paint, rand); canvas->drawPath(p, paint); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new BeziersGM; ) <commit_msg>These calls to SkRandom are not sequenced.<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkPath.h" #include "SkRandom.h" #define W 400 #define H 400 #define N 10 constexpr SkScalar SH = SkIntToScalar(H); static void rnd_quad(SkPath* p, SkPaint* paint, SkRandom& rand) { p->moveTo(rand.nextRangeScalar(0, W), rand.nextRangeScalar(0, H)); for (int x = 0; x < 2; ++x) { auto a = rand.nextRangeScalar(W/4, W), b = rand.nextRangeScalar( 0, H), c = rand.nextRangeScalar( 0, W), d = rand.nextRangeScalar(H/4, H); p->quadTo(a,b,c,d); } paint->setColor(rand.nextU()); SkScalar width = rand.nextRangeScalar(1, 5); width *= width; paint->setStrokeWidth(width); paint->setAlpha(0xFF); } static void rnd_cubic(SkPath* p, SkPaint* paint, SkRandom& rand) { auto a = rand.nextRangeScalar(0,W), b = rand.nextRangeScalar(0,H); p->moveTo(a,b); for (int x = 0; x < 2; ++x) { auto c = rand.nextRangeScalar(W/4, W), d = rand.nextRangeScalar( 0, H), e = rand.nextRangeScalar( 0, W), f = rand.nextRangeScalar(H/4, H), g = rand.nextRangeScalar(W/4, W), h = rand.nextRangeScalar(H/4, H); p->cubicTo(c,d,e,f,g,h); } paint->setColor(rand.nextU()); SkScalar width = rand.nextRangeScalar(1, 5); width *= width; paint->setStrokeWidth(width); paint->setAlpha(0xFF); } class BeziersGM : public skiagm::GM { public: BeziersGM() {} protected: SkString onShortName() override { return SkString("beziers"); } SkISize onISize() override { return SkISize::Make(W, H*2); } void onDraw(SkCanvas* canvas) override { SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SkIntToScalar(9)/2); paint.setAntiAlias(true); SkRandom rand; for (int i = 0; i < N; i++) { SkPath p; rnd_quad(&p, &paint, rand); canvas->drawPath(p, paint); } canvas->translate(0, SH); for (int i = 0; i < N; i++) { SkPath p; rnd_cubic(&p, &paint, rand); canvas->drawPath(p, paint); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new BeziersGM; ) <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurDrawLooper.h" namespace skiagm { /////////////////////////////////////////////////////////////////////////////// static void setup(SkPaint* paint, SkColor c, SkScalar strokeWidth) { paint->setColor(c); if (strokeWidth < 0) { paint->setStyle(SkPaint::kFill_Style); } else { paint->setStyle(SkPaint::kStroke_Style); paint->setStrokeWidth(strokeWidth); } } class ShadowsGM : public GM { public: SkPath fCirclePath; SkRect fRect; ShadowsGM() { this->setBGColor(0xFFDDDDDD); fCirclePath.addCircle(SkIntToScalar(20), SkIntToScalar(20), SkIntToScalar(10) ); fRect.set(SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(30), SkIntToScalar(30)); } protected: virtual SkString onShortName() { return SkString("shadows"); } virtual SkISize onISize() { return make_isize(200, 80); } virtual void onDraw(SkCanvas* canvas) { SkBlurDrawLooper* shadowLoopers[5]; shadowLoopers[0] = new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5), SkIntToScalar(10), 0xFF0000FF, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL0(shadowLoopers[0]); shadowLoopers[1] = new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5), SkIntToScalar(10), 0xFF0000FF, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag ); SkAutoUnref aurL1(shadowLoopers[1]); shadowLoopers[2] = new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(5), SkIntToScalar(10), 0xFF000000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL2(shadowLoopers[2]); shadowLoopers[3] = new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(-5), SkIntToScalar(-10), 0x7FFF0000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL3(shadowLoopers[3]); shadowLoopers[4] = new SkBlurDrawLooper (SkIntToScalar(0), SkIntToScalar(5), SkIntToScalar(5), 0xFF000000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL4(shadowLoopers[4]); static const struct { SkColor fColor; SkScalar fStrokeWidth; } gRec[] = { { SK_ColorRED, -SK_Scalar1 }, { SK_ColorGREEN, SkIntToScalar(4) }, }; SkPaint paint; paint.setAntiAlias(true); for (size_t i = 0; i < SK_ARRAY_COUNT(shadowLoopers); ++i) { SkAutoCanvasRestore acr(canvas, true); paint.setLooper(shadowLoopers[i]); canvas->translate(SkIntToScalar(i*40), SkIntToScalar(0)); setup(&paint, gRec[0].fColor, gRec[0].fStrokeWidth); canvas->drawRect(fRect, paint); canvas->translate(SkIntToScalar(0), SkIntToScalar(40)); setup(&paint, gRec[1].fColor, gRec[1].fStrokeWidth); canvas->drawPath(fCirclePath, paint); } } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ShadowsGM; } static GMRegistry reg(MyFactory); } <commit_msg>Augment gm shadows test to cover hairline paths<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurDrawLooper.h" namespace skiagm { /////////////////////////////////////////////////////////////////////////////// static void setup(SkPaint* paint, SkColor c, SkScalar strokeWidth) { paint->setColor(c); if (strokeWidth < 0) { paint->setStyle(SkPaint::kFill_Style); } else { paint->setStyle(SkPaint::kStroke_Style); paint->setStrokeWidth(strokeWidth); } } class ShadowsGM : public GM { public: SkPath fCirclePath; SkRect fRect; ShadowsGM() { this->setBGColor(0xFFDDDDDD); fCirclePath.addCircle(SkIntToScalar(20), SkIntToScalar(20), SkIntToScalar(10) ); fRect.set(SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(30), SkIntToScalar(30)); } protected: virtual SkString onShortName() { return SkString("shadows"); } virtual SkISize onISize() { return make_isize(200, 120); } virtual void onDraw(SkCanvas* canvas) { SkBlurDrawLooper* shadowLoopers[5]; shadowLoopers[0] = new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5), SkIntToScalar(10), 0xFF0000FF, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL0(shadowLoopers[0]); shadowLoopers[1] = new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5), SkIntToScalar(10), 0xFF0000FF, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag ); SkAutoUnref aurL1(shadowLoopers[1]); shadowLoopers[2] = new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(5), SkIntToScalar(10), 0xFF000000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL2(shadowLoopers[2]); shadowLoopers[3] = new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(-5), SkIntToScalar(-10), 0x7FFF0000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL3(shadowLoopers[3]); shadowLoopers[4] = new SkBlurDrawLooper (SkIntToScalar(0), SkIntToScalar(5), SkIntToScalar(5), 0xFF000000, SkBlurDrawLooper::kIgnoreTransform_BlurFlag | SkBlurDrawLooper::kOverrideColor_BlurFlag | SkBlurDrawLooper::kHighQuality_BlurFlag ); SkAutoUnref aurL4(shadowLoopers[4]); static const struct { SkColor fColor; SkScalar fStrokeWidth; } gRec[] = { { SK_ColorRED, -SK_Scalar1 }, { SK_ColorGREEN, SkIntToScalar(4) }, { SK_ColorBLUE, SkIntToScalar(0)}, }; SkPaint paint; paint.setAntiAlias(true); for (size_t i = 0; i < SK_ARRAY_COUNT(shadowLoopers); ++i) { SkAutoCanvasRestore acr(canvas, true); paint.setLooper(shadowLoopers[i]); canvas->translate(SkIntToScalar(i*40), SkIntToScalar(0)); setup(&paint, gRec[0].fColor, gRec[0].fStrokeWidth); canvas->drawRect(fRect, paint); canvas->translate(SkIntToScalar(0), SkIntToScalar(40)); setup(&paint, gRec[1].fColor, gRec[1].fStrokeWidth); canvas->drawPath(fCirclePath, paint); canvas->translate(SkIntToScalar(0), SkIntToScalar(40)); setup(&paint, gRec[2].fColor, gRec[2].fStrokeWidth); canvas->drawPath(fCirclePath, paint); } } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new ShadowsGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "RequestHandlerDispatcher.h" #include "Optional.h" #include "RequestHandler.h" #include "PathPattern.h" namespace CoAP { template <typename C> auto firstMatch(C &container, const Path &path) { auto it = std::find_if(std::begin(container), std::end(container), [path](auto& e){ return e.first.match(path); }); return (it != std::end(container)) ? Optional<typename C::value_type::second_type>(it->second) : Optional<typename C::value_type::second_type>(); }; CoAP::RestResponse RequestHandlerDispatcher::GET(const Path& uri) { auto f = [uri](const auto& e){ return e.GET(uri); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::PUT(const Path& uri, const std::string& payload) { auto f = [uri, payload](const auto& e){ return e.PUT(uri, payload); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::POST(const Path& uri, const std::string& payload) { auto f = [uri, payload](const auto& e){ return e.POST(uri, payload); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::DELETE(const Path& uri) { auto f = [uri](const auto& e){ return e.DELETE(uri); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::OBSERVE(const Path &uri, std::weak_ptr<Observable<CoAP::RestResponse>> notifications) { auto f = [uri, notifications](const auto& e){ return e.OBSERVE(uri, notifications); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } bool RequestHandlerDispatcher::isGetDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isGetDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isPutDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isPutDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isPostDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isPostDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isDeleteDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isDeleteDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isObserveDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isObserveDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } RequestHandler& RequestHandlerDispatcher::onUri(std::string pathPattern) { requestHandlers_.emplace_back(PathPattern(pathPattern), RequestHandler(*this)); return requestHandlers_.back().second; } } // namespace CoAP <commit_msg>Added missing include algorithm to use std::find_if<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "RequestHandlerDispatcher.h" #include "Optional.h" #include "RequestHandler.h" #include "PathPattern.h" #include <algorithm> namespace CoAP { template <typename C> auto firstMatch(C &container, const Path &path) { auto it = std::find_if(std::begin(container), std::end(container), [path](auto& e){ return e.first.match(path); }); return (it != std::end(container)) ? Optional<typename C::value_type::second_type>(it->second) : Optional<typename C::value_type::second_type>(); }; CoAP::RestResponse RequestHandlerDispatcher::GET(const Path& uri) { auto f = [uri](const auto& e){ return e.GET(uri); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::PUT(const Path& uri, const std::string& payload) { auto f = [uri, payload](const auto& e){ return e.PUT(uri, payload); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::POST(const Path& uri, const std::string& payload) { auto f = [uri, payload](const auto& e){ return e.POST(uri, payload); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::DELETE(const Path& uri) { auto f = [uri](const auto& e){ return e.DELETE(uri); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } CoAP::RestResponse RequestHandlerDispatcher::OBSERVE(const Path &uri, std::weak_ptr<Observable<CoAP::RestResponse>> notifications) { auto f = [uri, notifications](const auto& e){ return e.OBSERVE(uri, notifications); }; return lift<RequestHandler, RestResponse>(firstMatch(requestHandlers_, uri), f) .valueOr(CoAP::RestResponse().withCode(CoAP::Code::NotFound)); } bool RequestHandlerDispatcher::isGetDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isGetDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isPutDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isPutDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isPostDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isPostDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isDeleteDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isDeleteDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } bool RequestHandlerDispatcher::isObserveDelayed(const Path& uri) { auto f = [](const auto& e){ return e.isObserveDelayed(); }; return lift<RequestHandler, bool>(firstMatch(requestHandlers_, uri), f) .valueOr(false); } RequestHandler& RequestHandlerDispatcher::onUri(std::string pathPattern) { requestHandlers_.emplace_back(PathPattern(pathPattern), RequestHandler(*this)); return requestHandlers_.back().second; } } // namespace CoAP <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "homography_reader_process.h" #include <vistk/utilities/homography.h> #include <vistk/utilities/path.h> #include <vistk/pipeline/config.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <boost/make_shared.hpp> #include <vnl/vnl_double_3x3.h> #include <fstream> #include <string> /** * \file homography_reader_process.cxx * * \brief Implementation of the homography reader process. */ namespace vistk { class homography_reader_process::priv { public: priv(path_t const& input_path); ~priv(); path_t const path; bool read_error; std::ifstream fin; static config::key_t const config_path; static port_t const port_output; }; config::key_t const homography_reader_process::priv::config_path = config::key_t("input"); process::port_t const homography_reader_process::priv::port_output = process::port_t("homography"); homography_reader_process ::homography_reader_process(config_t const& config) : process(config) { declare_configuration_key(priv::config_path, boost::make_shared<conf_info>( config::value_t(), config::description_t("The input file with homographies to read."))); port_flags_t required; required.insert(flag_required); declare_output_port(priv::port_output, boost::make_shared<port_info>( "transform", required, port_description_t("The homographies that are read in."))); } homography_reader_process ::~homography_reader_process() { } void homography_reader_process ::_init() { // Configure the process. { path_t const path = config_value<path_t>(priv::config_path); d.reset(new priv(path)); } path_t::string_type const path = d->path.native(); if (path.empty()) { config::value_t const file_path = config::value_t(path.begin(), path.end()); static std::string const reason = "The path given was empty"; throw invalid_configuration_value_exception(name(), priv::config_path, file_path, reason); } d->fin.open(path.c_str()); if (!d->fin.good()) { std::string const file_path(path.begin(), path.end()); std::string const reason = "Failed to open the path: " + file_path; throw invalid_configuration_exception(name(), reason); } process::_init(); } void homography_reader_process ::_step() { datum_t dat; bool complete = false; if (d->fin.eof()) { complete = true; } else if (!d->fin.good()) { static datum::error_t const err_string = datum::error_t("Error with input file stream."); dat = datum::error_datum(err_string); } else { typedef vnl_matrix_fixed<double, 3, 3> matrix_t; matrix_t read_mat; for (size_t i = 0; i < 9; ++i) { std::istream const& istr = d->fin >> read_mat(i / 3, i % 3); if (!istr) { d->read_error = true; break; } if (d->fin.eof()) { complete = true; } } homography_base::transform_t const mat(read_mat); dat = datum::new_datum(mat); } if (d->read_error) { static datum::error_t const err_string = datum::error_t("Error reading from the input file."); dat = datum::error_datum(err_string); } if (complete) { mark_process_as_complete(); dat = datum::complete_datum(); } push_datum_to_port(priv::port_output, dat); process::_step(); } homography_reader_process::priv ::priv(path_t const& input_path) : path(input_path) , read_error(false) { } homography_reader_process::priv ::~priv() { } } <commit_msg>The read_error variable can be local to _step<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "homography_reader_process.h" #include <vistk/utilities/homography.h> #include <vistk/utilities/path.h> #include <vistk/pipeline/config.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <boost/make_shared.hpp> #include <vnl/vnl_double_3x3.h> #include <fstream> #include <string> /** * \file homography_reader_process.cxx * * \brief Implementation of the homography reader process. */ namespace vistk { class homography_reader_process::priv { public: priv(path_t const& input_path); ~priv(); path_t const path; std::ifstream fin; static config::key_t const config_path; static port_t const port_output; }; config::key_t const homography_reader_process::priv::config_path = config::key_t("input"); process::port_t const homography_reader_process::priv::port_output = process::port_t("homography"); homography_reader_process ::homography_reader_process(config_t const& config) : process(config) { declare_configuration_key(priv::config_path, boost::make_shared<conf_info>( config::value_t(), config::description_t("The input file with homographies to read."))); port_flags_t required; required.insert(flag_required); declare_output_port(priv::port_output, boost::make_shared<port_info>( "transform", required, port_description_t("The homographies that are read in."))); } homography_reader_process ::~homography_reader_process() { } void homography_reader_process ::_init() { // Configure the process. { path_t const path = config_value<path_t>(priv::config_path); d.reset(new priv(path)); } path_t::string_type const path = d->path.native(); if (path.empty()) { config::value_t const file_path = config::value_t(path.begin(), path.end()); static std::string const reason = "The path given was empty"; throw invalid_configuration_value_exception(name(), priv::config_path, file_path, reason); } d->fin.open(path.c_str()); if (!d->fin.good()) { std::string const file_path(path.begin(), path.end()); std::string const reason = "Failed to open the path: " + file_path; throw invalid_configuration_exception(name(), reason); } process::_init(); } void homography_reader_process ::_step() { datum_t dat; bool read_error = false; bool complete = false; if (d->fin.eof()) { complete = true; } else if (!d->fin.good()) { static datum::error_t const err_string = datum::error_t("Error with input file stream."); dat = datum::error_datum(err_string); } else { typedef vnl_matrix_fixed<double, 3, 3> matrix_t; matrix_t read_mat; for (size_t i = 0; i < 9; ++i) { std::istream const& istr = d->fin >> read_mat(i / 3, i % 3); if (!istr) { read_error = true; break; } if (d->fin.eof()) { complete = true; } } homography_base::transform_t const mat(read_mat); dat = datum::new_datum(mat); } if (read_error) { static datum::error_t const err_string = datum::error_t("Error reading from the input file."); dat = datum::error_datum(err_string); } if (complete) { mark_process_as_complete(); dat = datum::complete_datum(); } push_datum_to_port(priv::port_output, dat); process::_step(); } homography_reader_process::priv ::priv(path_t const& input_path) : path(input_path) { } homography_reader_process::priv ::~priv() { } } <|endoftext|>
<commit_before>#include "UnitTest++/UnitTestPP.h" #include "RecordingReporter.h" #include "UnitTest++/ReportAssert.h" #include "UnitTest++/TestList.h" #include "UnitTest++/TimeHelpers.h" #include "UnitTest++/TimeConstraint.h" #include "UnitTest++/ReportAssertImpl.h" using namespace UnitTest; namespace { struct MockTest : public Test { MockTest(char const* testName, bool const success_, bool const assert_, int const count_ = 1) : Test(testName) , success(success_) , asserted(assert_) , count(count_) { } virtual void RunImpl() const { TestResults& testResults_ = *CurrentTest::Results(); for (int i=0; i < count; ++i) { if (asserted) { ReportAssert("desc", "file", 0); } else if (!success) { testResults_.OnTestFailure(m_details, "message"); } } } bool const success; bool const asserted; int const count; }; struct FixtureBase { FixtureBase() : runner(reporter) { } template <class Predicate> int RunTestsIf(TestList const& list, char const* suiteName, const Predicate& predicate, int maxTestTimeInMs) { TestResults* oldResults = CurrentTest::Results(); const TestDetails* oldDetails = CurrentTest::Details(); int result = runner.RunTestsIf(list, suiteName, predicate, maxTestTimeInMs); CurrentTest::Results() = oldResults; CurrentTest::Details() = oldDetails; return result; } TestRunner runner; RecordingReporter reporter; }; struct TestRunnerFixture : public FixtureBase { TestList list; }; TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly) { MockTest test("goodtest", true, false); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); } TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly) { MockTest test("goodtest", true, false); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testFinishedCount); CHECK_EQUAL("goodtest", reporter.lastFinishedTest); } class SlowTest : public Test { public: SlowTest() : Test("slow", "somesuite", "filename", 123) { } virtual void RunImpl() const { TimeHelpers::SleepMs(20); } }; TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK(reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= 0.050f); } TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun) { CHECK_EQUAL(0, RunTestsIf(list, NULL, True(), 0)); CHECK_EQUAL(0, reporter.testRunCount); CHECK_EQUAL(0, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest) { MockTest test1("test", false, false); list.Add(&test1); MockTest test2("test", true, false); list.Add(&test2); MockTest test3("test", false, false); list.Add(&test3); CHECK_EQUAL(2, RunTestsIf(list, NULL, True(), 0)); CHECK_EQUAL(2, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing) { MockTest test("test", true, true); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfTestCount) { MockTest test1("test", true, false); MockTest test2("test", true, false); MockTest test3("test", true, false); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(3, reporter.summaryTotalTestCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailedTests) { MockTest test1("test", false, false, 2); MockTest test2("test", true, false); MockTest test3("test", false, false, 3); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(2, reporter.summaryFailedTestCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailures) { MockTest test1("test", false, false, 2); MockTest test2("test", true, false); MockTest test3("test", false, false, 3); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(5, reporter.summaryFailureCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(0, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); CHECK_EQUAL(1, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); using namespace std; CHECK_EQUAL(test.m_details.testName, reporter.lastFailedTest); CHECK(strstr(test.m_details.filename, reporter.lastFailedFile)); CHECK_EQUAL(test.m_details.lineNumber, reporter.lastFailedLine); CHECK(strstr(reporter.lastFailedMessage, "Global time constraint failed")); CHECK(strstr(reporter.lastFailedMessage, "3ms")); } TEST_FIXTURE(TestRunnerFixture, SlowTestWithTimeExemptionPasses) { class SlowExemptedTest : public Test { public: SlowExemptedTest() : Test("slowexempted", "", 0) {} virtual void RunImpl() const { UNITTEST_TIME_CONSTRAINT_EXEMPT(); TimeHelpers::SleepMs(20); } }; SlowExemptedTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); CHECK_EQUAL(0, reporter.testFailedCount); } struct TestSuiteFixture : FixtureBase { TestSuiteFixture() : test1("TestInDefaultSuite") , test2("TestInOtherSuite", "OtherSuite") , test3("SecondTestInDefaultSuite") { list.Add(&test1); list.Add(&test2); } Test test1; Test test2; Test test3; TestList list; }; TEST_FIXTURE(TestSuiteFixture, TestRunnerRunsAllSuitesIfNullSuiteIsPassed) { RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(2, reporter.summaryTotalTestCount); } TEST_FIXTURE(TestSuiteFixture,TestRunnerRunsOnlySpecifiedSuite) { RunTestsIf(list, "OtherSuite", True(), 0); CHECK_EQUAL(1, reporter.summaryTotalTestCount); CHECK_EQUAL("TestInOtherSuite", reporter.lastFinishedTest); } struct RunTestIfNameIs { RunTestIfNameIs(char const* name_) : name(name_) { } bool operator()(const Test* const test) const { using namespace std; return (0 == strcmp(test->m_details.testName, name)); } char const* name; }; TEST(TestMockPredicateBehavesCorrectly) { RunTestIfNameIs predicate("pass"); Test pass("pass"); Test fail("fail"); CHECK(predicate(&pass)); CHECK(!predicate(&fail)); } TEST_FIXTURE(TestRunnerFixture, TestRunnerRunsTestsThatPassPredicate) { Test should_run("goodtest"); list.Add(&should_run); Test should_not_run("badtest"); list.Add(&should_not_run); RunTestsIf(list, NULL, RunTestIfNameIs("goodtest"), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); } TEST_FIXTURE(TestRunnerFixture, TestRunnerOnlyRunsTestsInSpecifiedSuiteAndThatPassPredicate) { Test runningTest1("goodtest", "suite"); Test skippedTest2("goodtest"); Test skippedTest3("badtest", "suite"); Test skippedTest4("badtest"); list.Add(&runningTest1); list.Add(&skippedTest2); list.Add(&skippedTest3); list.Add(&skippedTest4); RunTestsIf(list, "suite", RunTestIfNameIs("goodtest"), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); CHECK_EQUAL("suite", reporter.lastStartedSuite); } }<commit_msg>Reduce possible timing test failures<commit_after>#include "UnitTest++/UnitTestPP.h" #include "RecordingReporter.h" #include "UnitTest++/ReportAssert.h" #include "UnitTest++/TestList.h" #include "UnitTest++/TimeHelpers.h" #include "UnitTest++/TimeConstraint.h" #include "UnitTest++/ReportAssertImpl.h" using namespace UnitTest; namespace { struct MockTest : public Test { MockTest(char const* testName, bool const success_, bool const assert_, int const count_ = 1) : Test(testName) , success(success_) , asserted(assert_) , count(count_) { } virtual void RunImpl() const { TestResults& testResults_ = *CurrentTest::Results(); for (int i=0; i < count; ++i) { if (asserted) { ReportAssert("desc", "file", 0); } else if (!success) { testResults_.OnTestFailure(m_details, "message"); } } } bool const success; bool const asserted; int const count; }; struct FixtureBase { FixtureBase() : runner(reporter) { } template <class Predicate> int RunTestsIf(TestList const& list, char const* suiteName, const Predicate& predicate, int maxTestTimeInMs) { TestResults* oldResults = CurrentTest::Results(); const TestDetails* oldDetails = CurrentTest::Details(); int result = runner.RunTestsIf(list, suiteName, predicate, maxTestTimeInMs); CurrentTest::Results() = oldResults; CurrentTest::Details() = oldDetails; return result; } TestRunner runner; RecordingReporter reporter; }; struct TestRunnerFixture : public FixtureBase { TestList list; }; TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly) { MockTest test("goodtest", true, false); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); } TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly) { MockTest test("goodtest", true, false); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testFinishedCount); CHECK_EQUAL("goodtest", reporter.lastFinishedTest); } class SlowTest : public Test { public: SlowTest() : Test("slow", "somesuite", "filename", 123) { } virtual void RunImpl() const { TimeHelpers::SleepMs(20); } }; TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime) { SlowTest test; list.Add(&test); // Using UnitTest::Timer here is arguably a bit hokey and self-recursive, but // it should guarantee that the test time recorded is less than that plus the // overhead of RunTestsIf -- the only thing we can reliably assert without // reworking the test to not use sleeps at all Timer actual; actual.Start(); RunTestsIf(list, NULL, True(), 0); CHECK(reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= actual.GetTimeInMs()); } TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun) { CHECK_EQUAL(0, RunTestsIf(list, NULL, True(), 0)); CHECK_EQUAL(0, reporter.testRunCount); CHECK_EQUAL(0, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest) { MockTest test1("test", false, false); list.Add(&test1); MockTest test2("test", true, false); list.Add(&test2); MockTest test3("test", false, false); list.Add(&test3); CHECK_EQUAL(2, RunTestsIf(list, NULL, True(), 0)); CHECK_EQUAL(2, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing) { MockTest test("test", true, true); list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(1, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfTestCount) { MockTest test1("test", true, false); MockTest test2("test", true, false); MockTest test3("test", true, false); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(3, reporter.summaryTotalTestCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailedTests) { MockTest test1("test", false, false, 2); MockTest test2("test", true, false); MockTest test3("test", false, false, 3); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(2, reporter.summaryFailedTestCount); } TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailures) { MockTest test1("test", false, false, 2); MockTest test2("test", true, false); MockTest test3("test", false, false, 3); list.Add(&test1); list.Add(&test2); list.Add(&test3); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(5, reporter.summaryFailureCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(0, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); CHECK_EQUAL(1, reporter.testFailedCount); } TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation) { SlowTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); using namespace std; CHECK_EQUAL(test.m_details.testName, reporter.lastFailedTest); CHECK(strstr(test.m_details.filename, reporter.lastFailedFile)); CHECK_EQUAL(test.m_details.lineNumber, reporter.lastFailedLine); CHECK(strstr(reporter.lastFailedMessage, "Global time constraint failed")); CHECK(strstr(reporter.lastFailedMessage, "3ms")); } TEST_FIXTURE(TestRunnerFixture, SlowTestWithTimeExemptionPasses) { class SlowExemptedTest : public Test { public: SlowExemptedTest() : Test("slowexempted", "", 0) {} virtual void RunImpl() const { UNITTEST_TIME_CONSTRAINT_EXEMPT(); TimeHelpers::SleepMs(20); } }; SlowExemptedTest test; list.Add(&test); RunTestsIf(list, NULL, True(), 3); CHECK_EQUAL(0, reporter.testFailedCount); } struct TestSuiteFixture : FixtureBase { TestSuiteFixture() : test1("TestInDefaultSuite") , test2("TestInOtherSuite", "OtherSuite") , test3("SecondTestInDefaultSuite") { list.Add(&test1); list.Add(&test2); } Test test1; Test test2; Test test3; TestList list; }; TEST_FIXTURE(TestSuiteFixture, TestRunnerRunsAllSuitesIfNullSuiteIsPassed) { RunTestsIf(list, NULL, True(), 0); CHECK_EQUAL(2, reporter.summaryTotalTestCount); } TEST_FIXTURE(TestSuiteFixture,TestRunnerRunsOnlySpecifiedSuite) { RunTestsIf(list, "OtherSuite", True(), 0); CHECK_EQUAL(1, reporter.summaryTotalTestCount); CHECK_EQUAL("TestInOtherSuite", reporter.lastFinishedTest); } struct RunTestIfNameIs { RunTestIfNameIs(char const* name_) : name(name_) { } bool operator()(const Test* const test) const { using namespace std; return (0 == strcmp(test->m_details.testName, name)); } char const* name; }; TEST(TestMockPredicateBehavesCorrectly) { RunTestIfNameIs predicate("pass"); Test pass("pass"); Test fail("fail"); CHECK(predicate(&pass)); CHECK(!predicate(&fail)); } TEST_FIXTURE(TestRunnerFixture, TestRunnerRunsTestsThatPassPredicate) { Test should_run("goodtest"); list.Add(&should_run); Test should_not_run("badtest"); list.Add(&should_not_run); RunTestsIf(list, NULL, RunTestIfNameIs("goodtest"), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); } TEST_FIXTURE(TestRunnerFixture, TestRunnerOnlyRunsTestsInSpecifiedSuiteAndThatPassPredicate) { Test runningTest1("goodtest", "suite"); Test skippedTest2("goodtest"); Test skippedTest3("badtest", "suite"); Test skippedTest4("badtest"); list.Add(&runningTest1); list.Add(&skippedTest2); list.Add(&skippedTest3); list.Add(&skippedTest4); RunTestsIf(list, "suite", RunTestIfNameIs("goodtest"), 0); CHECK_EQUAL(1, reporter.testRunCount); CHECK_EQUAL("goodtest", reporter.lastStartedTest); CHECK_EQUAL("suite", reporter.lastStartedSuite); } }<|endoftext|>
<commit_before>/*********************************************************** * photuris_utilities.cpp * * For getting information from Photuris utility sensors. * * Author: Albert Gural * Email: ag@albertgural.com * Date: 2013/08/07 - 2013/09/04 **********************************************************/ #include "photuris_utitlities.h" #include <math.h> /*** Battery Utilities ***/ // Returns the current battery voltage in volts. // Fully charged: 4.2V // Nominal voltage: 3.3V - 3.7V // Fully discharged: 2.7V // Connected to charger: -1V float getBatteryVoltage() { cbi(DDRC, 3); // 238.14 = 1024 [Full ADC Range] * 10/43 [Resistor Divider] const float kVoltageConvert = REFERENCE_VOLTAGE / 238.14; float voltage = kVoltageConvert * (float)analogRead(A3); if(voltage < 1.0) voltage = -1.0; delay(1); sbi(DDRC, 3); return voltage; } // Returns the theoretical (modeled) voltage you would expect after using a // given fraction of the total charge of the battery. // @usage - Fraction of the battery's charge used [0..1]. float getVoltageFromUsage(float usage) { // This formula is based on the AW IMR discharge curve. float voltage = 4.2 - 0.32 * log(8 * usage + 1) - exp(30 * (usage - 1)); return voltage; } // Returns the percent charge of the battery [0..100] or -1 if charging. // Uses a Li-Ion IMR discharge curve to approximate energy percentage // (as opposed to just using the direct voltage level). int getBatteryPercent() { const float kPrecision = 0.005; float pLower = 0.0, pUpper = 1.0; float voltage = getBatteryVoltage(); if(voltage < 2.5) return -1; while(pUpper - pLower > kPrecision) { float pMiddle = (pLower + pUpper) / 2; // getVoltageFromUsage is monotonically decreasing so if it's too large, // we should use the upper range. if(getVoltageFromUsage(pMiddle) > voltage) { pLower = pMiddle; } else { pUpper = pMiddle; } } return (int)(pLower * 100); } // Returns true if currently charging and false otherwise. // This can also be used to determine whether the device is connected to USB. bool isCharging() { return getBatteryVoltage() < 0; } /*** Temperature Utilities ***/ // Returns the current temperature in *C. // Very high: 50*C // High: 45*C float getTemperature() { return 0; } <commit_msg>Implemented temperature sensing. Adding system check function.<commit_after>/*********************************************************** * photuris_utilities.cpp * * For getting information from Photuris utility sensors. * * Author: Albert Gural * Email: ag@albertgural.com * Date: 2013/08/07 - 2013/09/04 **********************************************************/ #include "photuris_utitlities.h" #include <math.h> /*** Battery Utilities ***/ // Returns the current battery voltage in volts. // Fully charged: 4.2V // Nominal voltage: 3.3V - 3.7V // Fully discharged: 2.7V // Connected to charger: -1V float getBatteryVoltage() { cbi(DDRC, 3); // 238.14 = 1024 [Full ADC Range] * 10/43 [Resistor Divider] const float kVoltageConvert = REFERENCE_VOLTAGE / 238.14; float voltage = kVoltageConvert * (float)analogRead(A3); if(voltage < 1.0) voltage = -1.0; delay(1); sbi(DDRC, 3); return voltage; } // Returns the theoretical (modeled) voltage you would expect after using a // given fraction of the total charge of the battery. // @usage - Fraction of the battery's charge used [0..1]. float getVoltageFromUsage(float usage) { // This formula is based on the AW IMR discharge curve. float voltage = 4.2 - 0.32 * log(8 * usage + 1) - exp(30 * (usage - 1)); return voltage; } // Returns the percent charge of the battery [0..100] or -1 if charging. // Uses a Li-Ion IMR discharge curve to approximate energy percentage // (as opposed to just using the direct voltage level). int getBatteryPercent() { const float kPrecision = 0.005; float pLower = 0.0, pUpper = 1.0; float voltage = getBatteryVoltage(); if(voltage < 2.5) return -1; while(pUpper - pLower > kPrecision) { float pMiddle = (pLower + pUpper) / 2; // getVoltageFromUsage is monotonically decreasing so if it's too large, // we should use the upper range. if(getVoltageFromUsage(pMiddle) > voltage) { pLower = pMiddle; } else { pUpper = pMiddle; } } return (int)(pLower * 100); } // Returns true if currently charging and false otherwise. // This can also be used to determine whether the device is connected to USB. bool isCharging() { return getBatteryVoltage() < 0; } /*** Temperature Utilities ***/ // Returns the raw ADC output for a temperature sample. int chipTempRaw(void) { ADCSRA |= _BV(ADSC); while((ADCSRA & _BV(ADSC))); return (ADCL | (ADCH << 8)); } // Returns the current temperature in *C. // Very high: 50*C // High: 45*C float getTemperature() { int kTempSamples = 100; float avg; ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3); delay(10); chipTempRaw(); for(int i = 1; i < kTempSamples; i++) { avg += chipTempRaw(); } avg /= kTempSamples; // Interestingly, the value of average is very close to the actual // temperature in kelvin. Too bad it's not exact. avg = 1.01 * avg - 272; return avg; } /*** System Utilities ***/ // Checks the voltage and temperature to see if everything's ok. // The return value gives the current status: // Quaternary output AB where A gives battery status and B gives temperature. // For A: // * 0: Battery OK! // * 1: Plugged in / no battery // * 2: Battery low // * 3: Battery critically low // For B: // * 0: Temperature OK! // * 1: Temperature high // * 2: Temperature critically high // * 3: Temperature critically low int systemCheck() { // TODO return 0; } <|endoftext|>
<commit_before> #include <ros/ros.h> #include <gtest/gtest.h> #include <control_toolbox/pid.h> #include <boost/math/special_functions/fpclassify.hpp> using namespace control_toolbox; TEST(ParameterTest, zeroITermBadIBoundsTest) { RecordProperty("description","This test checks robustness against divide-by-zero errors when given integral term bounds which do not include 0.0."); Pid pid(1.0, 0.0, 0.0, -1.0, 0.0); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); } TEST(ParameterTest, integrationWindupTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is non-zero."); Pid pid(0.0, 1.0, 0.0, 1.0, -1.0); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(1.0, cmd); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(1.0, cmd); } TEST(ParameterTest, integrationWindupZeroGainTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is zero. If the integral error is allowed to wind up while it is disabled, it can cause sudden jumps to the minimum or maximum bound in control command when re-enabled."); double i_gain = 0.0; double i_min = -1.0; double i_max = 1.0; Pid pid(0.0, i_gain, 0.0, i_max, i_min); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Added test for getting/settings gains, copying/assigning pid class<commit_after> #include <ros/ros.h> #include <gtest/gtest.h> #include <control_toolbox/pid.h> #include <boost/math/special_functions/fpclassify.hpp> using namespace control_toolbox; TEST(ParameterTest, zeroITermBadIBoundsTest) { RecordProperty("description","This test checks robustness against divide-by-zero errors when given integral term bounds which do not include 0.0."); Pid pid(1.0, 0.0, 0.0, -1.0, 0.0); double cmd = 0.0; double pe,ie,de; cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); } TEST(ParameterTest, integrationWindupTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is non-zero."); Pid pid(0.0, 1.0, 0.0, 1.0, -1.0); double cmd = 0.0; double pe,ie,de; cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(-1.0, cmd); cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(-1.0, cmd); } TEST(ParameterTest, integrationWindupZeroGainTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is zero. If the integral error is allowed to wind up while it is disabled, it can cause sudden jumps to the minimum or maximum bound in control command when re-enabled."); double i_gain = 0.0; double i_min = -1.0; double i_max = 1.0; Pid pid(0.0, i_gain, 0.0, i_max, i_min); double cmd = 0.0; double pe,ie,de; cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); cmd = pid.computeCommand(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); } TEST(ParameterTest, gainSettingCopyPIDTest) { RecordProperty("description","This test succeeds if a PID object has its gain set at different points in time then the values are get-ed and still remain the same, as well as when PID is copied."); // Test values double p_gain = rand() % 100; double i_gain = rand() % 100; double d_gain = rand() % 100; double i_max = rand() % 100; double i_min = -1 * rand() % 100; // Initialize the default way Pid pid1(p_gain, i_gain, d_gain, i_max, i_min); // Test return values ------------------------------------------------- double p_gain_return, i_gain_return, d_gain_return, i_max_return, i_min_return; pid1.getGains(p_gain_return, i_gain_return, d_gain_return, i_max_return, i_min_return); EXPECT_EQ(p_gain, p_gain_return); EXPECT_EQ(i_gain, i_gain_return); EXPECT_EQ(d_gain, d_gain_return); EXPECT_EQ(i_max, i_max_return); EXPECT_EQ(i_min, i_min_return); // Test return values using struct ------------------------------------------------- // New values p_gain = rand() % 100; i_gain = rand() % 100; d_gain = rand() % 100; i_max = rand() % 100; i_min = -1 * rand() % 100; pid1.setGains(p_gain, i_gain, d_gain, i_max, i_min); Pid::Gains g1 = pid1.getGains(); EXPECT_EQ(p_gain, g1.p_gain_); EXPECT_EQ(i_gain, g1.i_gain_); EXPECT_EQ(d_gain, g1.d_gain_); EXPECT_EQ(i_max, g1.i_max_); EXPECT_EQ(i_min, g1.i_min_); // Test return values using struct - const version ------------------------------------------------- // New values p_gain = rand() % 100; i_gain = rand() % 100; d_gain = rand() % 100; i_max = rand() % 100; i_min = -1 * rand() % 100; pid1.setGains(p_gain, i_gain, d_gain, i_max, i_min); Pid::Gains g2 = pid1.getGainsConst(); EXPECT_EQ(p_gain, g2.p_gain_); EXPECT_EQ(i_gain, g2.i_gain_); EXPECT_EQ(d_gain, g2.d_gain_); EXPECT_EQ(i_max, g2.i_max_); EXPECT_EQ(i_min, g2.i_min_); // \todo test initParam() ------------------------------------------------- // \todo test bool init(const ros::NodeHandle &n); ----------------------------------- // Send update command to populate errors ------------------------------------------------- pid1.setCurrentCmd(10); pid1.computeCommand(20, ros::Duration(1.0)); // Test copy constructor ------------------------------------------------- Pid pid2(pid1); pid2.getGains(p_gain_return, i_gain_return, d_gain_return, i_max_return, i_min_return); EXPECT_EQ(p_gain, p_gain_return); EXPECT_EQ(i_gain, i_gain_return); EXPECT_EQ(d_gain, d_gain_return); EXPECT_EQ(i_max, i_max_return); EXPECT_EQ(i_min, i_min_return); // Test that errors are zero double pe, ie, de; pid2.getCurrentPIDErrors(&pe, &ie, &de); EXPECT_EQ(0.0, pe); EXPECT_EQ(0.0, ie); EXPECT_EQ(0.0, de); // Test assignment constructor ------------------------------------------------- Pid pid3; pid3 = pid1; pid3.getGains(p_gain_return, i_gain_return, d_gain_return, i_max_return, i_min_return); EXPECT_EQ(p_gain, p_gain_return); EXPECT_EQ(i_gain, i_gain_return); EXPECT_EQ(d_gain, d_gain_return); EXPECT_EQ(i_max, i_max_return); EXPECT_EQ(i_min, i_min_return); // Test that errors are zero double pe2, ie2, de2; pid3.getCurrentPIDErrors(&pe2, &ie2, &de2); EXPECT_EQ(0.0, pe2); EXPECT_EQ(0.0, ie2); EXPECT_EQ(0.0, de2); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|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. #ifndef MFEM_PBILINEARFORM #define MFEM_PBILINEARFORM #include "../config/config.hpp" #ifdef MFEM_USE_MPI #include <mpi.h> #include "pfespace.hpp" #include "pgridfunc.hpp" #include "bilinearform.hpp" namespace mfem { /// Class for parallel bilinear form class ParBilinearForm : public BilinearForm { protected: ParFiniteElementSpace *pfes; mutable ParGridFunction X, Y; // used in TrueAddMult OperatorHandle p_mat, p_mat_e; bool keep_nbr_block; // Allocate mat - called when (mat == NULL && fbfi.Size() > 0) void pAllocMat(); void AssembleSharedFaces(int skip_zeros = 1); public: ParBilinearForm(ParFiniteElementSpace *pf) : BilinearForm(pf), pfes(pf), p_mat(Operator::Hypre_ParCSR), p_mat_e(Operator::Hypre_ParCSR) { keep_nbr_block = false; } ParBilinearForm(ParFiniteElementSpace *pf, ParBilinearForm *bf) : BilinearForm(pf, bf), pfes(pf), p_mat(Operator::Hypre_ParCSR), p_mat_e(Operator::Hypre_ParCSR) { keep_nbr_block = false; } /** When set to true and the ParBilinearForm has interior face integrators, the local SparseMatrix will include the rows (in addition to the columns) corresponding to face-neighbor dofs. The default behavior is to disregard those rows. Must be called before the first Assemble call. */ void KeepNbrBlock(bool knb = true) { keep_nbr_block = knb; } /// Set the operator type id for the parallel matrix/operator. /** If using static condensation or hybridization, call this method *after* enabling it. */ void SetOperatorType(Operator::Type tid) { p_mat.SetType(tid); p_mat_e.SetType(tid); if (hybridization) { hybridization->SetOperatorType(tid); } if (static_cond) { static_cond->SetOperatorType(tid); } } /// Assemble the local matrix void Assemble(int skip_zeros = 1); /// Returns the matrix assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssemble() { return ParallelAssemble(mat); } /// Returns the eliminated matrix assembled on the true dofs, i.e. P^t A_e P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssembleElim() { return ParallelAssemble(mat_e); } /// Return the matrix @a m assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssemble(SparseMatrix *m); /** @brief Returns the matrix assembled on the true dofs, i.e. @a A = P^t A_local P, in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A) { ParallelAssemble(A, mat); } /** Returns the eliminated matrix assembled on the true dofs, i.e. @a A_elim = P^t A_elim_local P in the format (type id) specified by @a A. */ void ParallelAssembleElim(OperatorHandle &A_elim) { ParallelAssemble(A_elim, mat_e); } /** Returns the matrix @a A_local assembled on the true dofs, i.e. @a A = P^t A_local P in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A, SparseMatrix *A_local); /// Eliminate essential boundary DOFs from a parallel assembled system. /** The array @a bdr_attr_is_ess marks boundary attributes that constitute the essential part of the boundary. */ void ParallelEliminateEssentialBC(const Array<int> &bdr_attr_is_ess, HypreParMatrix &A, const HypreParVector &X, HypreParVector &B) const; /// Eliminate essential boundary DOFs from a parallel assembled matrix @a A. /** The array @a bdr_attr_is_ess marks boundary attributes that constitute the essential part of the boundary. The eliminated part is stored in a matrix A_elim such that A_original = A_new + A_elim. Returns a pointer to the newly allocated matrix A_elim which should be deleted by the caller. The matrices @a A and A_elim can be used to eliminate boundary conditions in multiple right-hand sides, by calling the function EliminateBC() (from hypre.hpp). */ HypreParMatrix *ParallelEliminateEssentialBC(const Array<int> &bdr_attr_is_ess, HypreParMatrix &A) const; /// Eliminate essential true DOFs from a parallel assembled matrix @a A. /** Given a list of essential true dofs and the parallel assembled matrix @a A, eliminate the true dofs from the matrix, storing the eliminated part in a matrix A_elim such that A_original = A_new + A_elim. Returns a pointer to the newly allocated matrix A_elim which should be deleted by the caller. The matrices @a A and A_elim can be used to eliminate boundary conditions in multiple right-hand sides, by calling the function EliminateBC() (from hypre.hpp). */ HypreParMatrix *ParallelEliminateTDofs(const Array<int> &tdofs_list, HypreParMatrix &A) const { return A.EliminateRowsCols(tdofs_list); } /** @brief Compute @a y += @a a (P^t A P) @a x, where @a x and @a y are vectors on the true dofs. */ void TrueAddMult(const Vector &x, Vector &y, const double a = 1.0) const; /// Return the parallel FE space associated with the ParBilinearForm. ParFiniteElementSpace *ParFESpace() const { return pfes; } /// Return the parallel trace FE space associated with static condensation. ParFiniteElementSpace *SCParFESpace() const { return static_cond ? static_cond->GetParTraceFESpace() : NULL; } /// Get the parallel finite element space prolongation matrix virtual const Operator *GetProlongation() const { return pfes->GetProlongationMatrix(); } /// Get the parallel finite element space restriction matrix virtual const Operator *GetRestriction() const { return pfes->GetRestrictionMatrix(); } /** Form the linear system A X = B, corresponding to the current bilinear form and b(.), by applying any necessary transformations such as: eliminating boundary conditions; applying conforming constraints for non-conforming AMR; parallel assembly; static condensation; hybridization. The ParGridFunction-size vector x must contain the essential b.c. The ParBilinearForm and the ParLinearForm-size vector b must be assembled. The vector X is initialized with a suitable initial guess: when using hybridization, the vector X is set to zero; otherwise, the essential entries of X are set to the corresponding b.c. and all other entries are set to zero (copy_interior == 0) or copied from x (copy_interior != 0). This method can be called multiple times (with the same ess_tdof_list array) to initialize different right-hand sides and boundary condition values. After solving the linear system, the finite element solution x can be recovered by calling RecoverFEMSolution (with the same vectors X, b, and x). */ void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OperatorHandle &A, Vector &X, Vector &B, int copy_interior = 0); /** Version of the method FormLinearSystem() where the system matrix is returned in the variable @a A, of type OpType, holding a *reference* to the system matrix (created with the method OpType::MakeRef()). The reference will be invalidated when SetOperatorType(), Update(), or the destructor is called. */ template <typename OpType> void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OpType &A, Vector &X, Vector &B, int copy_interior = 0) { OperatorHandle Ah; FormLinearSystem(ess_tdof_list, x, b, Ah, X, B, copy_interior); OpType *A_ptr = Ah.Is<OpType>(); MFEM_VERIFY(A_ptr, "invalid OpType used"); A.MakeRef(*A_ptr); } /// Form the linear system matrix @a A, see FormLinearSystem() for details. void FormSystemMatrix(const Array<int> &ess_tdof_list, OperatorHandle &A); /** Version of the method FormSystemMatrix() where the system matrix is returned in the variable @a A, of type OpType, holding a *reference* to the system matrix (created with the method OpType::MakeRef()). The reference will be invalidated when SetOperatorType(), Update(), or the destructor is called. */ template <typename OpType> void FormSystemMatrix(const Array<int> &ess_tdof_list, OpType &A) { OperatorHandle Ah; FormSystemMatrix(ess_tdof_list, Ah); OpType *A_ptr = Ah.Is<OpType>(); MFEM_VERIFY(A_ptr, "invalid OpType used"); A.MakeRef(*A_ptr); } /** Call this method after solving a linear system constructed using the FormLinearSystem method to recover the solution as a ParGridFunction-size vector in x. Use the same arguments as in the FormLinearSystem call. */ virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x); virtual void Update(FiniteElementSpace *nfes = NULL); virtual ~ParBilinearForm() { } }; /// Class for parallel bilinear form using different test and trial FE spaces. class ParMixedBilinearForm : public MixedBilinearForm { protected: ParFiniteElementSpace *trial_pfes; ParFiniteElementSpace *test_pfes; mutable ParGridFunction X, Y; // used in TrueAddMult public: ParMixedBilinearForm(ParFiniteElementSpace *trial_fes, ParFiniteElementSpace *test_fes) : MixedBilinearForm(trial_fes, test_fes) { trial_pfes = trial_fes; test_pfes = test_fes; } /// Returns the matrix assembled on the true dofs, i.e. P_test^t A P_trial. HypreParMatrix *ParallelAssemble(); /** @brief Returns the matrix assembled on the true dofs, i.e. @a A = P_test^t A_local P_trial, in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A); /// Compute y += a (P^t A P) x, where x and y are vectors on the true dofs void TrueAddMult(const Vector &x, Vector &y, const double a = 1.0) const; virtual ~ParMixedBilinearForm() { } }; // Class for parallel sesquilinear form class ParSesquilinearForm { protected: ParBilinearForm *pblfr_; ParBilinearForm *pblfi_; public: ParSesquilinearForm(ParFiniteElementSpace *pf); /// Adds new Domain Integrator. void AddDomainIntegrator(BilinearFormIntegrator *bfi_real, BilinearFormIntegrator *bfi_imag); /// Adds new Boundary Integrator. void AddBoundaryIntegrator(BilinearFormIntegrator *bfi_real, BilinearFormIntegrator *bfi_imag); /// Assemble the local matrix void Assemble(int skip_zeros = 1); /// Finalizes the matrix initialization. void Finalize(int skip_zeros = 1); /// Returns the matrix assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ ComplexOperator *ParallelAssemble(const ComplexOperator::Convention & conv = ComplexOperator::BLOCK_ANTISYMMETRIC); /// Return the parallel FE space associated with the ParBilinearForm. ParFiniteElementSpace *ParFESpace() const { return pblfr_->ParFESpace(); } void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OperatorHandle &A, Vector &X, Vector &B, int copy_interior = 0); /** Call this method after solving a linear system constructed using the FormLinearSystem method to recover the solution as a ParGridFunction-size vector in x. Use the same arguments as in the FormLinearSystem call. */ virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x); virtual void Update(FiniteElementSpace *nfes = NULL); virtual ~ParSesquilinearForm(); }; /** The parallel matrix representation a linear operator between parallel finite element spaces */ class ParDiscreteLinearOperator : public DiscreteLinearOperator { protected: ParFiniteElementSpace *domain_fes; ParFiniteElementSpace *range_fes; public: ParDiscreteLinearOperator(ParFiniteElementSpace *dfes, ParFiniteElementSpace *rfes) : DiscreteLinearOperator(dfes, rfes) { domain_fes=dfes; range_fes=rfes; } /// Returns the matrix "assembled" on the true dofs HypreParMatrix *ParallelAssemble() const; /** Extract the parallel blocks corresponding to the vector dimensions of the domain and range parallel finite element spaces */ void GetParBlocks(Array2D<HypreParMatrix *> &blocks) const; virtual ~ParDiscreteLinearOperator() { } }; } #endif // MFEM_USE_MPI #endif <commit_msg>Changing name of enumeration value<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. #ifndef MFEM_PBILINEARFORM #define MFEM_PBILINEARFORM #include "../config/config.hpp" #ifdef MFEM_USE_MPI #include <mpi.h> #include "pfespace.hpp" #include "pgridfunc.hpp" #include "bilinearform.hpp" namespace mfem { /// Class for parallel bilinear form class ParBilinearForm : public BilinearForm { protected: ParFiniteElementSpace *pfes; mutable ParGridFunction X, Y; // used in TrueAddMult OperatorHandle p_mat, p_mat_e; bool keep_nbr_block; // Allocate mat - called when (mat == NULL && fbfi.Size() > 0) void pAllocMat(); void AssembleSharedFaces(int skip_zeros = 1); public: ParBilinearForm(ParFiniteElementSpace *pf) : BilinearForm(pf), pfes(pf), p_mat(Operator::Hypre_ParCSR), p_mat_e(Operator::Hypre_ParCSR) { keep_nbr_block = false; } ParBilinearForm(ParFiniteElementSpace *pf, ParBilinearForm *bf) : BilinearForm(pf, bf), pfes(pf), p_mat(Operator::Hypre_ParCSR), p_mat_e(Operator::Hypre_ParCSR) { keep_nbr_block = false; } /** When set to true and the ParBilinearForm has interior face integrators, the local SparseMatrix will include the rows (in addition to the columns) corresponding to face-neighbor dofs. The default behavior is to disregard those rows. Must be called before the first Assemble call. */ void KeepNbrBlock(bool knb = true) { keep_nbr_block = knb; } /// Set the operator type id for the parallel matrix/operator. /** If using static condensation or hybridization, call this method *after* enabling it. */ void SetOperatorType(Operator::Type tid) { p_mat.SetType(tid); p_mat_e.SetType(tid); if (hybridization) { hybridization->SetOperatorType(tid); } if (static_cond) { static_cond->SetOperatorType(tid); } } /// Assemble the local matrix void Assemble(int skip_zeros = 1); /// Returns the matrix assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssemble() { return ParallelAssemble(mat); } /// Returns the eliminated matrix assembled on the true dofs, i.e. P^t A_e P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssembleElim() { return ParallelAssemble(mat_e); } /// Return the matrix @a m assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ HypreParMatrix *ParallelAssemble(SparseMatrix *m); /** @brief Returns the matrix assembled on the true dofs, i.e. @a A = P^t A_local P, in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A) { ParallelAssemble(A, mat); } /** Returns the eliminated matrix assembled on the true dofs, i.e. @a A_elim = P^t A_elim_local P in the format (type id) specified by @a A. */ void ParallelAssembleElim(OperatorHandle &A_elim) { ParallelAssemble(A_elim, mat_e); } /** Returns the matrix @a A_local assembled on the true dofs, i.e. @a A = P^t A_local P in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A, SparseMatrix *A_local); /// Eliminate essential boundary DOFs from a parallel assembled system. /** The array @a bdr_attr_is_ess marks boundary attributes that constitute the essential part of the boundary. */ void ParallelEliminateEssentialBC(const Array<int> &bdr_attr_is_ess, HypreParMatrix &A, const HypreParVector &X, HypreParVector &B) const; /// Eliminate essential boundary DOFs from a parallel assembled matrix @a A. /** The array @a bdr_attr_is_ess marks boundary attributes that constitute the essential part of the boundary. The eliminated part is stored in a matrix A_elim such that A_original = A_new + A_elim. Returns a pointer to the newly allocated matrix A_elim which should be deleted by the caller. The matrices @a A and A_elim can be used to eliminate boundary conditions in multiple right-hand sides, by calling the function EliminateBC() (from hypre.hpp). */ HypreParMatrix *ParallelEliminateEssentialBC(const Array<int> &bdr_attr_is_ess, HypreParMatrix &A) const; /// Eliminate essential true DOFs from a parallel assembled matrix @a A. /** Given a list of essential true dofs and the parallel assembled matrix @a A, eliminate the true dofs from the matrix, storing the eliminated part in a matrix A_elim such that A_original = A_new + A_elim. Returns a pointer to the newly allocated matrix A_elim which should be deleted by the caller. The matrices @a A and A_elim can be used to eliminate boundary conditions in multiple right-hand sides, by calling the function EliminateBC() (from hypre.hpp). */ HypreParMatrix *ParallelEliminateTDofs(const Array<int> &tdofs_list, HypreParMatrix &A) const { return A.EliminateRowsCols(tdofs_list); } /** @brief Compute @a y += @a a (P^t A P) @a x, where @a x and @a y are vectors on the true dofs. */ void TrueAddMult(const Vector &x, Vector &y, const double a = 1.0) const; /// Return the parallel FE space associated with the ParBilinearForm. ParFiniteElementSpace *ParFESpace() const { return pfes; } /// Return the parallel trace FE space associated with static condensation. ParFiniteElementSpace *SCParFESpace() const { return static_cond ? static_cond->GetParTraceFESpace() : NULL; } /// Get the parallel finite element space prolongation matrix virtual const Operator *GetProlongation() const { return pfes->GetProlongationMatrix(); } /// Get the parallel finite element space restriction matrix virtual const Operator *GetRestriction() const { return pfes->GetRestrictionMatrix(); } /** Form the linear system A X = B, corresponding to the current bilinear form and b(.), by applying any necessary transformations such as: eliminating boundary conditions; applying conforming constraints for non-conforming AMR; parallel assembly; static condensation; hybridization. The ParGridFunction-size vector x must contain the essential b.c. The ParBilinearForm and the ParLinearForm-size vector b must be assembled. The vector X is initialized with a suitable initial guess: when using hybridization, the vector X is set to zero; otherwise, the essential entries of X are set to the corresponding b.c. and all other entries are set to zero (copy_interior == 0) or copied from x (copy_interior != 0). This method can be called multiple times (with the same ess_tdof_list array) to initialize different right-hand sides and boundary condition values. After solving the linear system, the finite element solution x can be recovered by calling RecoverFEMSolution (with the same vectors X, b, and x). */ void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OperatorHandle &A, Vector &X, Vector &B, int copy_interior = 0); /** Version of the method FormLinearSystem() where the system matrix is returned in the variable @a A, of type OpType, holding a *reference* to the system matrix (created with the method OpType::MakeRef()). The reference will be invalidated when SetOperatorType(), Update(), or the destructor is called. */ template <typename OpType> void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OpType &A, Vector &X, Vector &B, int copy_interior = 0) { OperatorHandle Ah; FormLinearSystem(ess_tdof_list, x, b, Ah, X, B, copy_interior); OpType *A_ptr = Ah.Is<OpType>(); MFEM_VERIFY(A_ptr, "invalid OpType used"); A.MakeRef(*A_ptr); } /// Form the linear system matrix @a A, see FormLinearSystem() for details. void FormSystemMatrix(const Array<int> &ess_tdof_list, OperatorHandle &A); /** Version of the method FormSystemMatrix() where the system matrix is returned in the variable @a A, of type OpType, holding a *reference* to the system matrix (created with the method OpType::MakeRef()). The reference will be invalidated when SetOperatorType(), Update(), or the destructor is called. */ template <typename OpType> void FormSystemMatrix(const Array<int> &ess_tdof_list, OpType &A) { OperatorHandle Ah; FormSystemMatrix(ess_tdof_list, Ah); OpType *A_ptr = Ah.Is<OpType>(); MFEM_VERIFY(A_ptr, "invalid OpType used"); A.MakeRef(*A_ptr); } /** Call this method after solving a linear system constructed using the FormLinearSystem method to recover the solution as a ParGridFunction-size vector in x. Use the same arguments as in the FormLinearSystem call. */ virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x); virtual void Update(FiniteElementSpace *nfes = NULL); virtual ~ParBilinearForm() { } }; /// Class for parallel bilinear form using different test and trial FE spaces. class ParMixedBilinearForm : public MixedBilinearForm { protected: ParFiniteElementSpace *trial_pfes; ParFiniteElementSpace *test_pfes; mutable ParGridFunction X, Y; // used in TrueAddMult public: ParMixedBilinearForm(ParFiniteElementSpace *trial_fes, ParFiniteElementSpace *test_fes) : MixedBilinearForm(trial_fes, test_fes) { trial_pfes = trial_fes; test_pfes = test_fes; } /// Returns the matrix assembled on the true dofs, i.e. P_test^t A P_trial. HypreParMatrix *ParallelAssemble(); /** @brief Returns the matrix assembled on the true dofs, i.e. @a A = P_test^t A_local P_trial, in the format (type id) specified by @a A. */ void ParallelAssemble(OperatorHandle &A); /// Compute y += a (P^t A P) x, where x and y are vectors on the true dofs void TrueAddMult(const Vector &x, Vector &y, const double a = 1.0) const; virtual ~ParMixedBilinearForm() { } }; // Class for parallel sesquilinear form class ParSesquilinearForm { protected: ParBilinearForm *pblfr_; ParBilinearForm *pblfi_; public: ParSesquilinearForm(ParFiniteElementSpace *pf); /// Adds new Domain Integrator. void AddDomainIntegrator(BilinearFormIntegrator *bfi_real, BilinearFormIntegrator *bfi_imag); /// Adds new Boundary Integrator. void AddBoundaryIntegrator(BilinearFormIntegrator *bfi_real, BilinearFormIntegrator *bfi_imag); /// Assemble the local matrix void Assemble(int skip_zeros = 1); /// Finalizes the matrix initialization. void Finalize(int skip_zeros = 1); /// Returns the matrix assembled on the true dofs, i.e. P^t A P. /** The returned matrix has to be deleted by the caller. */ ComplexOperator *ParallelAssemble(const ComplexOperator::Convention & conv = ComplexOperator::HERMITIAN); /// Return the parallel FE space associated with the ParBilinearForm. ParFiniteElementSpace *ParFESpace() const { return pblfr_->ParFESpace(); } void FormLinearSystem(const Array<int> &ess_tdof_list, Vector &x, Vector &b, OperatorHandle &A, Vector &X, Vector &B, int copy_interior = 0); /** Call this method after solving a linear system constructed using the FormLinearSystem method to recover the solution as a ParGridFunction-size vector in x. Use the same arguments as in the FormLinearSystem call. */ virtual void RecoverFEMSolution(const Vector &X, const Vector &b, Vector &x); virtual void Update(FiniteElementSpace *nfes = NULL); virtual ~ParSesquilinearForm(); }; /** The parallel matrix representation a linear operator between parallel finite element spaces */ class ParDiscreteLinearOperator : public DiscreteLinearOperator { protected: ParFiniteElementSpace *domain_fes; ParFiniteElementSpace *range_fes; public: ParDiscreteLinearOperator(ParFiniteElementSpace *dfes, ParFiniteElementSpace *rfes) : DiscreteLinearOperator(dfes, rfes) { domain_fes=dfes; range_fes=rfes; } /// Returns the matrix "assembled" on the true dofs HypreParMatrix *ParallelAssemble() const; /** Extract the parallel blocks corresponding to the vector dimensions of the domain and range parallel finite element spaces */ void GetParBlocks(Array2D<HypreParMatrix *> &blocks) const; virtual ~ParDiscreteLinearOperator() { } }; } #endif // MFEM_USE_MPI #endif <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testCMCGait10dof18musc.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2014 Stanford University and the 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 #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/AnalysisSet.h> #include <OpenSim/Tools/CMCTool.h> #include <OpenSim/Tools/ForwardTool.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; void testGait10dof18musc(); int main() { SimTK::Array_<std::string> failures; try { testGait10dof18musc(); } catch (const std::exception& e) { cout << e.what() << endl; failures.push_back("testGait10dof18musc"); } // redo with the Millard2012EquilibriumMuscle Object::renameType("Thelen2003Muscle", "Millard2012EquilibriumMuscle"); try { testGait10dof18musc(); } catch (const std::exception& e) { cout << e.what() <<endl; failures.push_back("testGait10dof18musc_Millard"); } if (!failures.empty()) { cout << "Done, with failure(s): " << failures << endl; return 1; } cout << "Done" << endl; return 0; } void testGait10dof18musc() { cout<<"\n******************************************************************" << endl; cout << "* testGait10dof18musc *" << endl; cout << "******************************************************************\n" << endl; CMCTool cmc("gait10dof18musc_Setup_CMC.xml"); const string& muscleType = cmc.getModel().getMuscles()[0].getConcreteClassName(); if (cmc.run()) OPENSIM_THROW(Exception, "testGait10dof18musc " + muscleType + " failed to complete."); Storage results("gait10dof18musc_ResultsCMC/walk_subject_states.sto"); Storage temp("gait10dof18musc_std_walk_subject_states.sto"); Storage *standard = new Storage(); cmc.getModel().formStateStorage(temp, *standard); int nstates = standard->getColumnLabels().size() - 1; // angles and speeds within .6 degrees .6 degs/s; activations within 1% Array<double> rms_tols(0.01, nstates); CHECK_STORAGE_AGAINST_STANDARD(results, *standard, rms_tols, __FILE__, __LINE__, "testGait10dof18musc failed"); cout << "\ntestGait10dof18musc "+muscleType+" passed\n" << endl; } <commit_msg>Throw only if CMC does NOT complete.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testCMCGait10dof18musc.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2014 Stanford University and the 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 #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/AnalysisSet.h> #include <OpenSim/Tools/CMCTool.h> #include <OpenSim/Tools/ForwardTool.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; void testGait10dof18musc(); int main() { SimTK::Array_<std::string> failures; try { testGait10dof18musc(); } catch (const std::exception& e) { cout << e.what() << endl; failures.push_back("testGait10dof18musc"); } // redo with the Millard2012EquilibriumMuscle Object::renameType("Thelen2003Muscle", "Millard2012EquilibriumMuscle"); try { testGait10dof18musc(); } catch (const std::exception& e) { cout << e.what() <<endl; failures.push_back("testGait10dof18musc_Millard"); } if (!failures.empty()) { cout << "Done, with failure(s): " << failures << endl; return 1; } cout << "Done" << endl; return 0; } void testGait10dof18musc() { cout<<"\n******************************************************************" << endl; cout << "* testGait10dof18musc *" << endl; cout << "******************************************************************\n" << endl; CMCTool cmc("gait10dof18musc_Setup_CMC.xml"); const string& muscleType = cmc.getModel().getMuscles()[0].getConcreteClassName(); if (!cmc.run()) OPENSIM_THROW(Exception, "testGait10dof18musc " + muscleType + " failed to complete."); Storage results("gait10dof18musc_ResultsCMC/walk_subject_states.sto"); Storage temp("gait10dof18musc_std_walk_subject_states.sto"); Storage *standard = new Storage(); cmc.getModel().formStateStorage(temp, *standard); int nstates = standard->getColumnLabels().size() - 1; // angles and speeds within .6 degrees .6 degs/s; activations within 1% Array<double> rms_tols(0.01, nstates); CHECK_STORAGE_AGAINST_STANDARD(results, *standard, rms_tols, __FILE__, __LINE__, "testGait10dof18musc failed"); cout << "\ntestGait10dof18musc "+muscleType+" passed\n" << endl; } <|endoftext|>
<commit_before>//===-- BuildSystem.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "llbuild/BuildSystem/BuildSystem.h" #include "llbuild/BuildSystem/BuildFile.h" #include <memory> using namespace llbuild; using namespace llbuild::buildsystem; BuildSystemDelegate::~BuildSystemDelegate() {} #pragma mark - BuildSystem implementation namespace { class BuildSystemImpl; class BuildSystemFileDelegate : public BuildFileDelegate { BuildSystemImpl& system; public: BuildSystemFileDelegate(BuildSystemImpl& system) : BuildFileDelegate(), system(system) {} BuildSystemDelegate& getSystemDelegate(); /// @name Delegate Implementation /// @{ virtual void error(const std::string& filename, const std::string& message) override; virtual bool configureClient(const std::string& name, uint32_t version, const property_list_type& properties) override; virtual std::unique_ptr<Tool> lookupTool(const std::string& name) override; virtual void loadedTarget(const std::string& name, const Target& target) override; virtual void loadedTask(const std::string& name, const Task& target) override; virtual std::unique_ptr<Node> lookupNode(const std::string& name, bool isImplicit=false) override; /// @} }; class BuildSystemImpl { BuildSystem& buildSystem; /// The delegate the BuildSystem was configured with. BuildSystemDelegate& delegate; /// The name of the main input file. std::string mainFilename; public: BuildSystemImpl(class BuildSystem& buildSystem, BuildSystemDelegate& delegate, const std::string& mainFilename) : buildSystem(buildSystem), delegate(delegate), mainFilename(mainFilename) {} BuildSystem& getBuildSystem() { return buildSystem; } BuildSystemDelegate& getDelegate() { return delegate; } const std::string& getMainFilename() { return mainFilename; } /// @name Actions /// @{ bool build(const std::string& target) { // Load the build file. // // FIXME: Eventually, we may want to support something fancier where we load // the build file in the background so we can immediately start building // things as they show up. BuildSystemFileDelegate fileDelegate(*this); BuildFile buildFile(mainFilename, fileDelegate); buildFile.load(); return false; } /// @} }; #pragma mark - BuildNode implementation // FIXME: Figure out how this is going to be organized. class BuildNode : public Node { public: using Node::Node; virtual bool configureAttribute(const std::string& name, const std::string& value) override { // We don't support any custom attributes. return false; } }; #pragma mark - ShellTool implementation class ShellTask : public Task { BuildSystemImpl& system; std::vector<Node*> inputs; std::vector<Node*> outputs; std::string args; public: ShellTask(BuildSystemImpl& system, const std::string& name) : Task(name), system(system) {} virtual void configureInputs(const std::vector<Node*>& value) override { inputs = value; } virtual void configureOutputs(const std::vector<Node*>& value) override { outputs = value; } virtual bool configureAttribute(const std::string& name, const std::string& value) override { if (name == "args") { args = value; } else { system.getDelegate().error( system.getMainFilename(), "unexpected attribute: '" + name + "'"); return false; } return true; } }; class ShellTool : public Tool { BuildSystemImpl& system; public: ShellTool(BuildSystemImpl& system, const std::string& name) : Tool(name), system(system) {} virtual bool configureAttribute(const std::string& name, const std::string& value) override { system.getDelegate().error( system.getMainFilename(), "unexpected attribute: '" + name + "'"); // No supported attributes. return false; } virtual std::unique_ptr<Task> createTask(const std::string& name) override { return std::make_unique<ShellTask>(system, name); } }; #pragma mark - BuildSystemFileDelegate BuildSystemDelegate& BuildSystemFileDelegate::getSystemDelegate() { return system.getDelegate(); } void BuildSystemFileDelegate::error(const std::string& filename, const std::string& message) { // Delegate to the system delegate. getSystemDelegate().error(filename, message); } bool BuildSystemFileDelegate::configureClient(const std::string& name, uint32_t version, const property_list_type& properties) { // The client must match the configured name of the build system. if (name != getSystemDelegate().getName()) return false; // FIXME: Give the client an opportunity to respond to the schema version and // configuration the properties. return true; } std::unique_ptr<Tool> BuildSystemFileDelegate::lookupTool(const std::string& name) { // First, give the client an opportunity to create the tool. auto tool = getSystemDelegate().lookupTool(name); if (tool) return std::move(tool); // Otherwise, look for one of the builtin tool definitions. if (name == "shell") { return std::make_unique<ShellTool>(system, name); } return nullptr; } void BuildSystemFileDelegate::loadedTarget(const std::string& name, const Target& target) { } void BuildSystemFileDelegate::loadedTask(const std::string& name, const Task& target) { } std::unique_ptr<Node> BuildSystemFileDelegate::lookupNode(const std::string& name, bool isImplicit) { return std::make_unique<BuildNode>(name); } } #pragma mark - BuildSystem BuildSystem::BuildSystem(BuildSystemDelegate& delegate, const std::string& mainFilename) : impl(new BuildSystemImpl(*this, delegate, mainFilename)) { } BuildSystem::~BuildSystem() { delete static_cast<BuildSystemImpl*>(impl); } BuildSystemDelegate& BuildSystem::getDelegate() { return static_cast<BuildSystemImpl*>(impl)->getDelegate(); } bool BuildSystem::build(const std::string& name) { return static_cast<BuildSystemImpl*>(impl)->build(name); } <commit_msg>[buildsystem] Sketch integration between BuildSystem and lower level engine.<commit_after>//===-- BuildSystem.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "llbuild/BuildSystem/BuildSystem.h" #include "llvm/ADT/StringRef.h" #include "llbuild/Core/BuildEngine.h" #include "llbuild/BuildSystem/BuildFile.h" #include <memory> using namespace llbuild; using namespace llbuild::buildsystem; BuildSystemDelegate::~BuildSystemDelegate() {} #pragma mark - BuildSystem implementation namespace { class BuildSystemImpl; class BuildSystemFileDelegate : public BuildFileDelegate { BuildSystemImpl& system; public: BuildSystemFileDelegate(BuildSystemImpl& system) : BuildFileDelegate(), system(system) {} BuildSystemDelegate& getSystemDelegate(); /// @name Delegate Implementation /// @{ virtual void error(const std::string& filename, const std::string& message) override; virtual bool configureClient(const std::string& name, uint32_t version, const property_list_type& properties) override; virtual std::unique_ptr<Tool> lookupTool(const std::string& name) override; virtual void loadedTarget(const std::string& name, const Target& target) override; virtual void loadedTask(const std::string& name, const Task& target) override; virtual std::unique_ptr<Node> lookupNode(const std::string& name, bool isImplicit=false) override; /// @} }; class BuildSystemImpl { BuildSystem& buildSystem; /// The delegate the BuildSystem was configured with. BuildSystemDelegate& delegate; /// The name of the main input file. std::string mainFilename; public: BuildSystemImpl(class BuildSystem& buildSystem, BuildSystemDelegate& delegate, const std::string& mainFilename) : buildSystem(buildSystem), delegate(delegate), mainFilename(mainFilename) {} BuildSystem& getBuildSystem() { return buildSystem; } BuildSystemDelegate& getDelegate() { return delegate; } const std::string& getMainFilename() { return mainFilename; } /// @name Actions /// @{ bool build(const std::string& target); /// @} }; #pragma mark - BuildSystem engine integration /// The system key defines the helpers for translating to and from the key space /// used by the BuildSystem when using the core BuildEngine. struct SystemKey { enum class Kind { /// A key used to identify a named target. Target, /// An invalid key kind. Unknown, }; /// The actual key data. core::KeyType key; private: SystemKey(const core::KeyType& key) : key(key) {} SystemKey(char kindCode, llvm::StringRef str) { key.reserve(str.size() + 1); key.push_back(kindCode); key.append(str.begin(), str.end()); } public: // Support copy and move. SystemKey(SystemKey&& rhs) : key(rhs.key) { } void operator=(const SystemKey& rhs) { if (this != &rhs) key = rhs.key; } SystemKey& operator=(SystemKey&& rhs) { if (this != &rhs) key = rhs.key; return *this; } // Allow implicit conversion to the contained key. operator const core::KeyType& () const { return getKeyData(); } /// @name Construction Functions /// @{ static SystemKey fromKeyData(const core::KeyType& key) { auto result = SystemKey(key); assert(result.getKind() != Kind::Unknown && "invalid key"); return result; } static SystemKey makeTarget(llvm::StringRef name) { return SystemKey('T', name); } /// @} /// @name Accessors /// @{ const core::KeyType& getKeyData() const { return key; } Kind getKind() const { switch (key[0]) { case 'T': return Kind::Target; default: return Kind::Unknown; } } bool isTarget() const { return getKind() == Kind::Target; } llvm::StringRef getTargetName() const { return llvm::StringRef(key.data()+1, key.size()-1); } /// @} }; class ToolBasedCoreTask : public core::Task { virtual void start(core::BuildEngine&) override { } virtual void providePriorValue(core::BuildEngine&, const core::ValueType& value) override { } virtual void provideValue(core::BuildEngine&, uintptr_t inputID, const core::ValueType& value) override { } virtual void inputsAvailable(core::BuildEngine& engine) override { // Complete the task immediately. engine.taskIsComplete(this, core::ValueType()); } }; class BuildSystemEngineDelegate : public core::BuildEngineDelegate { BuildSystemImpl& system; public: BuildSystemEngineDelegate(BuildSystemImpl& system) : system(system) {} virtual core::Rule lookupRule(const core::KeyType& keyData) override { // Decode the key. auto key = SystemKey::fromKeyData(keyData); switch (key.getKind()) { default: assert(0 && "invalid key"); abort(); case SystemKey::Kind::Target: { // FIXME: Return an appropriate rule. return core::Rule{ key, /*Action=*/ [&](core::BuildEngine& engine) -> core::Task* { return engine.registerTask(new ToolBasedCoreTask()); } }; } } } virtual void cycleDetected(const std::vector<core::Rule*>& items) override { system.getDelegate().error(system.getMainFilename(), "cycle detected while building"); } }; bool BuildSystemImpl::build(const std::string& target) { // Load the build file. // // FIXME: Eventually, we may want to support something fancier where we load // the build file in the background so we can immediately start building // things as they show up. BuildSystemFileDelegate fileDelegate(*this); BuildFile buildFile(mainFilename, fileDelegate); buildFile.load(); // Create the engine to use for building. BuildSystemEngineDelegate engineDelegate(*this); core::BuildEngine engine(engineDelegate); // Build the target. engine.build(SystemKey::makeTarget(target)); return false; } #pragma mark - BuildNode implementation // FIXME: Figure out how this is going to be organized. class BuildNode : public Node { public: using Node::Node; virtual bool configureAttribute(const std::string& name, const std::string& value) override { // We don't support any custom attributes. return false; } }; #pragma mark - ShellTool implementation class ShellTask : public Task { BuildSystemImpl& system; std::vector<Node*> inputs; std::vector<Node*> outputs; std::string args; public: ShellTask(BuildSystemImpl& system, const std::string& name) : Task(name), system(system) {} virtual void configureInputs(const std::vector<Node*>& value) override { inputs = value; } virtual void configureOutputs(const std::vector<Node*>& value) override { outputs = value; } virtual bool configureAttribute(const std::string& name, const std::string& value) override { if (name == "args") { args = value; } else { system.getDelegate().error( system.getMainFilename(), "unexpected attribute: '" + name + "'"); return false; } return true; } }; class ShellTool : public Tool { BuildSystemImpl& system; public: ShellTool(BuildSystemImpl& system, const std::string& name) : Tool(name), system(system) {} virtual bool configureAttribute(const std::string& name, const std::string& value) override { system.getDelegate().error( system.getMainFilename(), "unexpected attribute: '" + name + "'"); // No supported attributes. return false; } virtual std::unique_ptr<Task> createTask(const std::string& name) override { return std::make_unique<ShellTask>(system, name); } }; #pragma mark - BuildSystemFileDelegate BuildSystemDelegate& BuildSystemFileDelegate::getSystemDelegate() { return system.getDelegate(); } void BuildSystemFileDelegate::error(const std::string& filename, const std::string& message) { // Delegate to the system delegate. getSystemDelegate().error(filename, message); } bool BuildSystemFileDelegate::configureClient(const std::string& name, uint32_t version, const property_list_type& properties) { // The client must match the configured name of the build system. if (name != getSystemDelegate().getName()) return false; // FIXME: Give the client an opportunity to respond to the schema version and // configuration the properties. return true; } std::unique_ptr<Tool> BuildSystemFileDelegate::lookupTool(const std::string& name) { // First, give the client an opportunity to create the tool. auto tool = getSystemDelegate().lookupTool(name); if (tool) return std::move(tool); // Otherwise, look for one of the builtin tool definitions. if (name == "shell") { return std::make_unique<ShellTool>(system, name); } return nullptr; } void BuildSystemFileDelegate::loadedTarget(const std::string& name, const Target& target) { } void BuildSystemFileDelegate::loadedTask(const std::string& name, const Task& target) { } std::unique_ptr<Node> BuildSystemFileDelegate::lookupNode(const std::string& name, bool isImplicit) { return std::make_unique<BuildNode>(name); } } #pragma mark - BuildSystem BuildSystem::BuildSystem(BuildSystemDelegate& delegate, const std::string& mainFilename) : impl(new BuildSystemImpl(*this, delegate, mainFilename)) { } BuildSystem::~BuildSystem() { delete static_cast<BuildSystemImpl*>(impl); } BuildSystemDelegate& BuildSystem::getDelegate() { return static_cast<BuildSystemImpl*>(impl)->getDelegate(); } bool BuildSystem::build(const std::string& name) { return static_cast<BuildSystemImpl*>(impl)->build(name); } <|endoftext|>
<commit_before>//===-- MachineCodeForMethod.cpp -------------------------------------------=// // // Purpose: // Collect native machine code information for a function. // This allows target-specific information about the generated code // to be stored with each function. //===---------------------------------------------------------------------===// #include "llvm/CodeGen/MachineCodeForMethod.h" #include "llvm/CodeGen/MachineInstr.h" // For debug output #include "llvm/Target/TargetMachine.h" #include "llvm/Target/MachineFrameInfo.h" #include "llvm/Target/MachineCacheInfo.h" #include "llvm/Function.h" #include "llvm/BasicBlock.h" #include "llvm/iOther.h" #include <limits.h> #include <iostream> const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits<int>::max(); static AnnotationID MCFM_AID( AnnotationManager::getID("CodeGen::MachineCodeForFunction")); // The next two methods are used to construct and to retrieve // the MachineCodeForFunction object for the given function. // construct() -- Allocates and initializes for a given function and target // get() -- Returns a handle to the object. // This should not be called before "construct()" // for a given Function. // MachineCodeForMethod& MachineCodeForMethod::construct(const Function *M, const TargetMachine &Tar) { assert(M->getAnnotation(MCFM_AID) == 0 && "Object already exists for this function!"); MachineCodeForMethod* mcInfo = new MachineCodeForMethod(M, Tar); M->addAnnotation(mcInfo); return *mcInfo; } void MachineCodeForMethod::destruct(const Function *M) { bool Deleted = M->deleteAnnotation(MCFM_AID); assert(Deleted && "Machine code did not exist for function!"); } MachineCodeForMethod& MachineCodeForMethod::get(const Function *F) { MachineCodeForMethod *mc = (MachineCodeForMethod*)F->getAnnotation(MCFM_AID); assert(mc && "Call construct() method first to allocate the object"); return *mc; } static unsigned ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F, unsigned &maxOptionalNumArgs) { const MachineFrameInfo& frameInfo = target.getFrameInfo(); unsigned maxSize = 0; for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const CallInst *callInst = dyn_cast<CallInst>(&*I)) { unsigned numOperands = callInst->getNumOperands() - 1; int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs(); if (numExtra <= 0) continue; unsigned int sizeForThisCall; if (frameInfo.argsOnStackHaveFixedSize()) { int argSize = frameInfo.getSizeOfEachArgOnStack(); sizeForThisCall = numExtra * (unsigned) argSize; } else { assert(0 && "UNTESTED CODE: Size per stack argument is not " "fixed on this architecture: use actual arg sizes to " "compute MaxOptionalArgsSize"); sizeForThisCall = 0; for (unsigned i = 0; i < numOperands; ++i) sizeForThisCall += target.findOptimalStorageSize(callInst-> getOperand(i)->getType()); } if (maxSize < sizeForThisCall) maxSize = sizeForThisCall; if ((int)maxOptionalNumArgs < numExtra) maxOptionalNumArgs = (unsigned) numExtra; } return maxSize; } // Align data larger than one L1 cache line on L1 cache line boundaries. // Align all smaller data on the next higher 2^x boundary (4, 8, ...). // // THIS FUNCTION HAS BEEN COPIED FROM EMITASSEMBLY.CPP AND // SHOULD BE USED DIRECTLY THERE // inline unsigned int SizeToAlignment(unsigned int size, const TargetMachine& target) { unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); if (size > (unsigned) cacheLineSize / 2) return cacheLineSize; else for (unsigned sz=1; /*no condition*/; sz *= 2) if (sz >= size) return sz; } /*ctor*/ MachineCodeForMethod::MachineCodeForMethod(const Function *F, const TargetMachine& target) : Annotation(MCFM_AID), method(F), staticStackSize(0), automaticVarsSize(0), regSpillsSize(0), maxOptionalArgsSize(0), maxOptionalNumArgs(0), currentTmpValuesSize(0), maxTmpValuesSize(0), compiledAsLeaf(false), spillsAreaFrozen(false), automaticVarsAreaFrozen(false) { maxOptionalArgsSize = ComputeMaxOptionalArgsSize(target, method, maxOptionalNumArgs); staticStackSize = maxOptionalArgsSize + target.getFrameInfo().getMinStackFrameSize(); } int MachineCodeForMethod::computeOffsetforLocalVar(const TargetMachine& target, const Value* val, unsigned int& getPaddedSize, unsigned int sizeToUse = 0) { bool growUp; int firstOffset =target.getFrameInfo().getFirstAutomaticVarOffset(*this, growUp); unsigned char align; if (sizeToUse == 0) { sizeToUse = target.findOptimalStorageSize(val->getType()); // align = target.DataLayout.getTypeAlignment(val->getType()); } align = SizeToAlignment(sizeToUse, target); int offset = getAutomaticVarsSize(); if (! growUp) offset += sizeToUse; if (unsigned int mod = offset % align) { offset += align - mod; getPaddedSize = sizeToUse + align - mod; } else getPaddedSize = sizeToUse; offset = growUp? firstOffset + offset : firstOffset - offset; return offset; } int MachineCodeForMethod::allocateLocalVar(const TargetMachine& target, const Value* val, unsigned int sizeToUse = 0) { assert(! automaticVarsAreaFrozen && "Size of auto vars area has been used to compute an offset so " "no more automatic vars should be allocated!"); // Check if we've allocated a stack slot for this value already // int offset = getOffset(val); if (offset == INVALID_FRAME_OFFSET) { unsigned int getPaddedSize; offset = this->computeOffsetforLocalVar(target, val, getPaddedSize, sizeToUse); offsets[val] = offset; incrementAutomaticVarsSize(getPaddedSize); } return offset; } int MachineCodeForMethod::allocateSpilledValue(const TargetMachine& target, const Type* type) { assert(! spillsAreaFrozen && "Size of reg spills area has been used to compute an offset so " "no more register spill slots should be allocated!"); unsigned int size = target.findOptimalStorageSize(type); unsigned char align = target.DataLayout.getTypeAlignment(type); bool growUp; int firstOffset = target.getFrameInfo().getRegSpillAreaOffset(*this, growUp); int offset = getRegSpillsSize(); if (! growUp) offset += size; if (unsigned int mod = offset % align) { offset += align - mod; size += align - mod; } offset = growUp? firstOffset + offset : firstOffset - offset; incrementRegSpillsSize(size); return offset; } int MachineCodeForMethod::pushTempValue(const TargetMachine& target, unsigned int size) { // Compute a power-of-2 alignment according to the possible sizes, // but not greater than the alignment of the largest type we support // (currently a double word -- see class TargetData). unsigned char align = 1; for (; align < size && align < target.DataLayout.getDoubleAlignment(); align = 2*align) ; bool growUp; int firstTmpOffset = target.getFrameInfo().getTmpAreaOffset(*this, growUp); int offset = currentTmpValuesSize; if (! growUp) offset += size; if (unsigned int mod = offset % align) { offset += align - mod; size += align - mod; } offset = growUp ? firstTmpOffset + offset : firstTmpOffset - offset; incrementTmpAreaSize(size); return offset; } void MachineCodeForMethod::popAllTempValues(const TargetMachine& target) { resetTmpAreaSize(); } int MachineCodeForMethod::getOffset(const Value* val) const { std::hash_map<const Value*, int>::const_iterator pair = offsets.find(val); return (pair == offsets.end())? INVALID_FRAME_OFFSET : pair->second; } void MachineCodeForMethod::dump() const { std::cerr << "\n" << method->getReturnType() << " \"" << method->getName() << "\"\n"; for (Function::const_iterator BB = method->begin(); BB != method->end(); ++BB) { std::cerr << "\n" << BB->getName() << " (" << *BB << ")" << ":\n"; MachineCodeForBasicBlock& mvec = BB->getMachineInstrVec(); for (unsigned i=0; i < mvec.size(); i++) std::cerr << "\t" << *mvec[i]; } std::cerr << "\nEnd function \"" << method->getName() << "\"\n\n"; } <commit_msg>Fix printing of BB in dump.<commit_after>//===-- MachineCodeForMethod.cpp -------------------------------------------=// // // Purpose: // Collect native machine code information for a function. // This allows target-specific information about the generated code // to be stored with each function. //===---------------------------------------------------------------------===// #include "llvm/CodeGen/MachineCodeForMethod.h" #include "llvm/CodeGen/MachineInstr.h" // For debug output #include "llvm/CodeGen/MachineCodeForBasicBlock.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/MachineFrameInfo.h" #include "llvm/Target/MachineCacheInfo.h" #include "llvm/Function.h" #include "llvm/BasicBlock.h" #include "llvm/iOther.h" #include <limits.h> #include <iostream> const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits<int>::max(); static AnnotationID MCFM_AID( AnnotationManager::getID("CodeGen::MachineCodeForFunction")); // The next two methods are used to construct and to retrieve // the MachineCodeForFunction object for the given function. // construct() -- Allocates and initializes for a given function and target // get() -- Returns a handle to the object. // This should not be called before "construct()" // for a given Function. // MachineCodeForMethod& MachineCodeForMethod::construct(const Function *M, const TargetMachine &Tar) { assert(M->getAnnotation(MCFM_AID) == 0 && "Object already exists for this function!"); MachineCodeForMethod* mcInfo = new MachineCodeForMethod(M, Tar); M->addAnnotation(mcInfo); return *mcInfo; } void MachineCodeForMethod::destruct(const Function *M) { bool Deleted = M->deleteAnnotation(MCFM_AID); assert(Deleted && "Machine code did not exist for function!"); } MachineCodeForMethod& MachineCodeForMethod::get(const Function *F) { MachineCodeForMethod *mc = (MachineCodeForMethod*)F->getAnnotation(MCFM_AID); assert(mc && "Call construct() method first to allocate the object"); return *mc; } static unsigned ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F, unsigned &maxOptionalNumArgs) { const MachineFrameInfo& frameInfo = target.getFrameInfo(); unsigned maxSize = 0; for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) if (const CallInst *callInst = dyn_cast<CallInst>(&*I)) { unsigned numOperands = callInst->getNumOperands() - 1; int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs(); if (numExtra <= 0) continue; unsigned int sizeForThisCall; if (frameInfo.argsOnStackHaveFixedSize()) { int argSize = frameInfo.getSizeOfEachArgOnStack(); sizeForThisCall = numExtra * (unsigned) argSize; } else { assert(0 && "UNTESTED CODE: Size per stack argument is not " "fixed on this architecture: use actual arg sizes to " "compute MaxOptionalArgsSize"); sizeForThisCall = 0; for (unsigned i = 0; i < numOperands; ++i) sizeForThisCall += target.findOptimalStorageSize(callInst-> getOperand(i)->getType()); } if (maxSize < sizeForThisCall) maxSize = sizeForThisCall; if ((int)maxOptionalNumArgs < numExtra) maxOptionalNumArgs = (unsigned) numExtra; } return maxSize; } // Align data larger than one L1 cache line on L1 cache line boundaries. // Align all smaller data on the next higher 2^x boundary (4, 8, ...). // // THIS FUNCTION HAS BEEN COPIED FROM EMITASSEMBLY.CPP AND // SHOULD BE USED DIRECTLY THERE // inline unsigned int SizeToAlignment(unsigned int size, const TargetMachine& target) { unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); if (size > (unsigned) cacheLineSize / 2) return cacheLineSize; else for (unsigned sz=1; /*no condition*/; sz *= 2) if (sz >= size) return sz; } /*ctor*/ MachineCodeForMethod::MachineCodeForMethod(const Function *F, const TargetMachine& target) : Annotation(MCFM_AID), method(F), staticStackSize(0), automaticVarsSize(0), regSpillsSize(0), maxOptionalArgsSize(0), maxOptionalNumArgs(0), currentTmpValuesSize(0), maxTmpValuesSize(0), compiledAsLeaf(false), spillsAreaFrozen(false), automaticVarsAreaFrozen(false) { maxOptionalArgsSize = ComputeMaxOptionalArgsSize(target, method, maxOptionalNumArgs); staticStackSize = maxOptionalArgsSize + target.getFrameInfo().getMinStackFrameSize(); } int MachineCodeForMethod::computeOffsetforLocalVar(const TargetMachine& target, const Value* val, unsigned int& getPaddedSize, unsigned int sizeToUse = 0) { bool growUp; int firstOffset =target.getFrameInfo().getFirstAutomaticVarOffset(*this, growUp); unsigned char align; if (sizeToUse == 0) { sizeToUse = target.findOptimalStorageSize(val->getType()); // align = target.DataLayout.getTypeAlignment(val->getType()); } align = SizeToAlignment(sizeToUse, target); int offset = getAutomaticVarsSize(); if (! growUp) offset += sizeToUse; if (unsigned int mod = offset % align) { offset += align - mod; getPaddedSize = sizeToUse + align - mod; } else getPaddedSize = sizeToUse; offset = growUp? firstOffset + offset : firstOffset - offset; return offset; } int MachineCodeForMethod::allocateLocalVar(const TargetMachine& target, const Value* val, unsigned int sizeToUse = 0) { assert(! automaticVarsAreaFrozen && "Size of auto vars area has been used to compute an offset so " "no more automatic vars should be allocated!"); // Check if we've allocated a stack slot for this value already // int offset = getOffset(val); if (offset == INVALID_FRAME_OFFSET) { unsigned int getPaddedSize; offset = this->computeOffsetforLocalVar(target, val, getPaddedSize, sizeToUse); offsets[val] = offset; incrementAutomaticVarsSize(getPaddedSize); } return offset; } int MachineCodeForMethod::allocateSpilledValue(const TargetMachine& target, const Type* type) { assert(! spillsAreaFrozen && "Size of reg spills area has been used to compute an offset so " "no more register spill slots should be allocated!"); unsigned int size = target.findOptimalStorageSize(type); unsigned char align = target.DataLayout.getTypeAlignment(type); bool growUp; int firstOffset = target.getFrameInfo().getRegSpillAreaOffset(*this, growUp); int offset = getRegSpillsSize(); if (! growUp) offset += size; if (unsigned int mod = offset % align) { offset += align - mod; size += align - mod; } offset = growUp? firstOffset + offset : firstOffset - offset; incrementRegSpillsSize(size); return offset; } int MachineCodeForMethod::pushTempValue(const TargetMachine& target, unsigned int size) { // Compute a power-of-2 alignment according to the possible sizes, // but not greater than the alignment of the largest type we support // (currently a double word -- see class TargetData). unsigned char align = 1; for (; align < size && align < target.DataLayout.getDoubleAlignment(); align = 2*align) ; bool growUp; int firstTmpOffset = target.getFrameInfo().getTmpAreaOffset(*this, growUp); int offset = currentTmpValuesSize; if (! growUp) offset += size; if (unsigned int mod = offset % align) { offset += align - mod; size += align - mod; } offset = growUp ? firstTmpOffset + offset : firstTmpOffset - offset; incrementTmpAreaSize(size); return offset; } void MachineCodeForMethod::popAllTempValues(const TargetMachine& target) { resetTmpAreaSize(); } int MachineCodeForMethod::getOffset(const Value* val) const { std::hash_map<const Value*, int>::const_iterator pair = offsets.find(val); return (pair == offsets.end())? INVALID_FRAME_OFFSET : pair->second; } void MachineCodeForMethod::dump() const { std::cerr << "\n" << method->getReturnType() << " \"" << method->getName() << "\"\n"; for (Function::const_iterator BB = method->begin(); BB != method->end(); ++BB) { std::cerr << "\n" << BB->getName() << " (" << (const void*) BB << ")" << ":\n"; MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(BB); for (unsigned i=0; i < mvec.size(); i++) std::cerr << "\t" << *mvec[i]; } std::cerr << "\nEnd function \"" << method->getName() << "\"\n\n"; } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <iostream> #include <iomanip> #include "instruction_procedures.h" #include "decoder.h" #include "memory.h" #include "global_registers.h" #include "register_procedures.h" using namespace std; void Format(AddressingMode addressingMode) { switch (addressingMode) { case Immediate: cout << "#$" << setw(2) << setfill('0') << uppercase << hex; break; case ZeroPage: case ZeroPageX: case ZeroPageY: case Relative: cout << "$" << setw(2) << setfill('0') << uppercase << hex; break; case Absolute: case AbsoluteX: case AbsoluteY: cout << "$" << setw(4) << setfill('0') << uppercase << hex; break; case ZeroPageIndirectX: case ZeroPageIndirectY: cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex; break; } //Anything else does not need special formatting } void PrintOperands(AddressingMode addressingMode, uint8_t operands[]) { Format(addressingMode); uint16_t operand; switch (addressingMode) { case Immediate: cout << (int)operands[0]; break; case ZeroPage: cout << (int)operands[0]; break; case ZeroPageX: cout << (int)operands[0] << ",X"; break; case ZeroPageY: cout << (int)operands[0] << ",Y"; case Relative: cout << (int)operands[0]; break; case Absolute: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand; break; case AbsoluteX: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",X"; break; case AbsoluteY: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",Y"; break; case ZeroPageIndirectX: cout << (int)operands[0] << ",X)"; break; case ZeroPageIndirectY: cout << (int)operands[0] << "),Y"; break; } cout << endl; } uint16_t _8_to_16(uint8_t high, uint8_t low) { return (uint16_t)high << 8 | low; } uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Absolute: return _8_to_16(operands[1], operands[0]); case ZeroPage: return operands[0]; case Relative: return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0]; case AbsoluteX: return reg::X + (int16_t)_8_to_16(operands[1], operands[0]); case AbsoluteY: return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]); case ZeroPageX: return (uint16_t)((reg::X + operands[0]) % 0xFF); case ZeroPageY: return (uint16_t)((reg::Y + operands[0]) % 0xFF); case ZeroPageIndirectX: return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]); case ZeroPageIndirectY: return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]); default: return 0; } } // Should not be used with addressing modes Accumulator and Implied. uint8_t& _fetch_operand(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Immediate: return operands[0]; default: return mem[_calculate_address(addressingMode, operands)]; } } void ProcADC(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); if (!GetFlagD()) { bool bit7 = (reg::Accumulator & (1 << 7)) != 0; uint8_t oldAcc = reg::Accumulator; if (reg::Accumulator + operand > 255) SetFlagC(true); else SetFlagC(false); reg::Accumulator += operand; SetFlagN((reg::Accumulator & (1 << 7)) != 0); // Put bit 7 in S flag SetFlagZ(!reg::Accumulator); //TODO: Implement overflow flag setting } } void ProcAND(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Accumulator & operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcASL(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = (addressingMode == Accumulator) ? reg::Accumulator : _fetch_operand(addressingMode, operands); SetFlagC((operand & (1 << 7)) != 0); SetFlagN((operand & (1 << 6)) != 0); operand <<= 1; SetFlagZ(operand == 0); } void ProcBCC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCC "; PrintOperands(addressingMode, operands); } void ProcBCS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCS "; PrintOperands(addressingMode, operands); } void ProcBEQ(AddressingMode addressingMode, uint8_t operands[]) { cout << "BEQ "; PrintOperands(addressingMode, operands); } void ProcBIT(AddressingMode addressingMode, uint8_t operands[]) { cout << "BIT "; PrintOperands(addressingMode, operands); } void ProcBMI(AddressingMode addressingMode, uint8_t operands[]) { cout << "BMI "; PrintOperands(addressingMode, operands); } void ProcBNE(AddressingMode addressingMode, uint8_t operands[]) { cout << "BNE "; PrintOperands(addressingMode, operands); } void ProcBPL(AddressingMode addressingMode, uint8_t operands[]) { cout << "BPL "; PrintOperands(addressingMode, operands); } void ProcBRK(AddressingMode addressingMode, uint8_t operands[]) { cout << "BRK "; PrintOperands(addressingMode, operands); } void ProcBVC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVC "; PrintOperands(addressingMode, operands); } void ProcBVS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVS "; PrintOperands(addressingMode, operands); } void ProcCLC(AddressingMode addressingMode, uint8_t operands[]) { SetFlagC(false); } void ProcCLD(AddressingMode addressingMode, uint8_t operands[]) { SetFlagD(false); } void ProcCLI(AddressingMode addressingMode, uint8_t operands[]) { SetFlagI(false); } void ProcCLV(AddressingMode addressingMode, uint8_t operands[]) { SetFlagV(false); } void ProcCMP(AddressingMode addressingMode, uint8_t operands[]) { uint8_t &operand = _fetch_operand(addressingMode, operands); SetFlagZ(operand == reg::Accumulator); SetFlagN(reg::Accumulator < operand); SetFlagC(reg::Accumulator >= operand); } void ProcCPX(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPX "; PrintOperands(addressingMode, operands); } void ProcCPY(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPY "; PrintOperands(addressingMode, operands); } void ProcDEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEC "; PrintOperands(addressingMode, operands); } void ProcDEX(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEX "; PrintOperands(addressingMode, operands); } void ProcDEY(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEY "; PrintOperands(addressingMode, operands); } void ProcEOR(AddressingMode addressingMode, uint8_t operands[]) { cout << "EOR "; PrintOperands(addressingMode, operands); } void ProcINC(AddressingMode addressingMode, uint8_t operands[]) { cout << "INC "; PrintOperands(addressingMode, operands); } void ProcINX(AddressingMode addressingMode, uint8_t operands[]) { cout << "INX "; PrintOperands(addressingMode, operands); } void ProcINY(AddressingMode addressingMode, uint8_t operands[]) { cout << "INY "; PrintOperands(addressingMode, operands); } void ProcJMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "JMP "; PrintOperands(addressingMode, operands); } void ProcJSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "JSR "; PrintOperands(addressingMode, operands); } void ProcLDA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcLDX(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::X = operand; SetFlagZ(reg::X == 0); SetFlagN((reg::X & (1 << 7)) != 0); } void ProcLDY(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Y= operand; SetFlagN((reg::Y & (1 << 7)) != 0); SetFlagZ(reg::Y == 0); } void ProcLSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "LSR "; PrintOperands(addressingMode, operands); } void ProcNOP(AddressingMode addressingMode, uint8_t operands[]) { } void ProcORA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Accumulator | operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcPHA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHA "; PrintOperands(addressingMode, operands); } void ProcPHP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHP "; PrintOperands(addressingMode, operands); } void ProcPLA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLA "; PrintOperands(addressingMode, operands); } void ProcPLP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLP "; PrintOperands(addressingMode, operands); } void ProcROL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROL "; PrintOperands(addressingMode, operands); } void ProcROR(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROR "; PrintOperands(addressingMode, operands); } void ProcRTI(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTI "; PrintOperands(addressingMode, operands); } void ProcRTS(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTS "; PrintOperands(addressingMode, operands); } void ProcSBC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SBC "; PrintOperands(addressingMode, operands); } void ProcSEC(AddressingMode addressingMode, uint8_t operands[]) { SetFlagC(true); } void ProcSED(AddressingMode addressingMode, uint8_t operands[]) { SetFlagD(true); } void ProcSEI(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEI "; PrintOperands(addressingMode, operands); } void ProcSTA(AddressingMode addressingMode, uint8_t operands[]) { cout << "STA "; PrintOperands(addressingMode, operands); } void ProcSTX(AddressingMode addressingMode, uint8_t operands[]) { cout << "STX "; PrintOperands(addressingMode, operands); } void ProcSTY(AddressingMode addressingMode, uint8_t operands[]) { cout << "STY "; PrintOperands(addressingMode, operands); } void ProcTAX(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::X = reg::Accumulator & operand; SetFlagZ(reg::X == 0); SetFlagN((reg::X & (1 << 7)) != 0); } void ProcTAY(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Y = reg::Accumulator & operand; SetFlagZ(reg::Y == 0); SetFlagN((reg::Y & (1 << 7)) != 0); } void ProcTSX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TSX "; PrintOperands(addressingMode, operands); } void ProcTXA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::X & operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcTXS(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXS "; PrintOperands(addressingMode, operands); } void ProcTYA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Y & operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } <commit_msg>fix TAY, TYA, TAX, TXA<commit_after>#pragma once #include <cstdint> #include <iostream> #include <iomanip> #include "instruction_procedures.h" #include "decoder.h" #include "memory.h" #include "global_registers.h" #include "register_procedures.h" using namespace std; void Format(AddressingMode addressingMode) { switch (addressingMode) { case Immediate: cout << "#$" << setw(2) << setfill('0') << uppercase << hex; break; case ZeroPage: case ZeroPageX: case ZeroPageY: case Relative: cout << "$" << setw(2) << setfill('0') << uppercase << hex; break; case Absolute: case AbsoluteX: case AbsoluteY: cout << "$" << setw(4) << setfill('0') << uppercase << hex; break; case ZeroPageIndirectX: case ZeroPageIndirectY: cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex; break; } //Anything else does not need special formatting } void PrintOperands(AddressingMode addressingMode, uint8_t operands[]) { Format(addressingMode); uint16_t operand; switch (addressingMode) { case Immediate: cout << (int)operands[0]; break; case ZeroPage: cout << (int)operands[0]; break; case ZeroPageX: cout << (int)operands[0] << ",X"; break; case ZeroPageY: cout << (int)operands[0] << ",Y"; case Relative: cout << (int)operands[0]; break; case Absolute: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand; break; case AbsoluteX: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",X"; break; case AbsoluteY: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",Y"; break; case ZeroPageIndirectX: cout << (int)operands[0] << ",X)"; break; case ZeroPageIndirectY: cout << (int)operands[0] << "),Y"; break; } cout << endl; } uint16_t _8_to_16(uint8_t high, uint8_t low) { return (uint16_t)high << 8 | low; } uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Absolute: return _8_to_16(operands[1], operands[0]); case ZeroPage: return operands[0]; case Relative: return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0]; case AbsoluteX: return reg::X + (int16_t)_8_to_16(operands[1], operands[0]); case AbsoluteY: return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]); case ZeroPageX: return (uint16_t)((reg::X + operands[0]) % 0xFF); case ZeroPageY: return (uint16_t)((reg::Y + operands[0]) % 0xFF); case ZeroPageIndirectX: return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]); case ZeroPageIndirectY: return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]); default: return 0; } } // Should not be used with addressing modes Accumulator and Implied. uint8_t& _fetch_operand(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Immediate: return operands[0]; default: return mem[_calculate_address(addressingMode, operands)]; } } void ProcADC(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); if (!GetFlagD()) { bool bit7 = (reg::Accumulator & (1 << 7)) != 0; uint8_t oldAcc = reg::Accumulator; if (reg::Accumulator + operand > 255) SetFlagC(true); else SetFlagC(false); reg::Accumulator += operand; SetFlagN((reg::Accumulator & (1 << 7)) != 0); // Put bit 7 in S flag SetFlagZ(!reg::Accumulator); //TODO: Implement overflow flag setting } } void ProcAND(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Accumulator & operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcASL(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = (addressingMode == Accumulator) ? reg::Accumulator : _fetch_operand(addressingMode, operands); SetFlagC((operand & (1 << 7)) != 0); SetFlagN((operand & (1 << 6)) != 0); operand <<= 1; SetFlagZ(operand == 0); } void ProcBCC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCC "; PrintOperands(addressingMode, operands); } void ProcBCS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCS "; PrintOperands(addressingMode, operands); } void ProcBEQ(AddressingMode addressingMode, uint8_t operands[]) { cout << "BEQ "; PrintOperands(addressingMode, operands); } void ProcBIT(AddressingMode addressingMode, uint8_t operands[]) { cout << "BIT "; PrintOperands(addressingMode, operands); } void ProcBMI(AddressingMode addressingMode, uint8_t operands[]) { cout << "BMI "; PrintOperands(addressingMode, operands); } void ProcBNE(AddressingMode addressingMode, uint8_t operands[]) { cout << "BNE "; PrintOperands(addressingMode, operands); } void ProcBPL(AddressingMode addressingMode, uint8_t operands[]) { cout << "BPL "; PrintOperands(addressingMode, operands); } void ProcBRK(AddressingMode addressingMode, uint8_t operands[]) { cout << "BRK "; PrintOperands(addressingMode, operands); } void ProcBVC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVC "; PrintOperands(addressingMode, operands); } void ProcBVS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVS "; PrintOperands(addressingMode, operands); } void ProcCLC(AddressingMode addressingMode, uint8_t operands[]) { SetFlagC(false); } void ProcCLD(AddressingMode addressingMode, uint8_t operands[]) { SetFlagD(false); } void ProcCLI(AddressingMode addressingMode, uint8_t operands[]) { SetFlagI(false); } void ProcCLV(AddressingMode addressingMode, uint8_t operands[]) { SetFlagV(false); } void ProcCMP(AddressingMode addressingMode, uint8_t operands[]) { uint8_t &operand = _fetch_operand(addressingMode, operands); SetFlagZ(operand == reg::Accumulator); SetFlagN(reg::Accumulator < operand); SetFlagC(reg::Accumulator >= operand); } void ProcCPX(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPX "; PrintOperands(addressingMode, operands); } void ProcCPY(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPY "; PrintOperands(addressingMode, operands); } void ProcDEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEC "; PrintOperands(addressingMode, operands); } void ProcDEX(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEX "; PrintOperands(addressingMode, operands); } void ProcDEY(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEY "; PrintOperands(addressingMode, operands); } void ProcEOR(AddressingMode addressingMode, uint8_t operands[]) { cout << "EOR "; PrintOperands(addressingMode, operands); } void ProcINC(AddressingMode addressingMode, uint8_t operands[]) { cout << "INC "; PrintOperands(addressingMode, operands); } void ProcINX(AddressingMode addressingMode, uint8_t operands[]) { cout << "INX "; PrintOperands(addressingMode, operands); } void ProcINY(AddressingMode addressingMode, uint8_t operands[]) { cout << "INY "; PrintOperands(addressingMode, operands); } void ProcJMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "JMP "; PrintOperands(addressingMode, operands); } void ProcJSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "JSR "; PrintOperands(addressingMode, operands); } void ProcLDA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcLDX(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::X = operand; SetFlagZ(reg::X == 0); SetFlagN((reg::X & (1 << 7)) != 0); } void ProcLDY(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Y= operand; SetFlagN((reg::Y & (1 << 7)) != 0); SetFlagZ(reg::Y == 0); } void ProcLSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "LSR "; PrintOperands(addressingMode, operands); } void ProcNOP(AddressingMode addressingMode, uint8_t operands[]) { } void ProcORA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Accumulator | operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcPHA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHA "; PrintOperands(addressingMode, operands); } void ProcPHP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHP "; PrintOperands(addressingMode, operands); } void ProcPLA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLA "; PrintOperands(addressingMode, operands); } void ProcPLP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLP "; PrintOperands(addressingMode, operands); } void ProcROL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROL "; PrintOperands(addressingMode, operands); } void ProcROR(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROR "; PrintOperands(addressingMode, operands); } void ProcRTI(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTI "; PrintOperands(addressingMode, operands); } void ProcRTS(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTS "; PrintOperands(addressingMode, operands); } void ProcSBC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SBC "; PrintOperands(addressingMode, operands); } void ProcSEC(AddressingMode addressingMode, uint8_t operands[]) { SetFlagC(true); } void ProcSED(AddressingMode addressingMode, uint8_t operands[]) { SetFlagD(true); } void ProcSEI(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEI "; PrintOperands(addressingMode, operands); } void ProcSTA(AddressingMode addressingMode, uint8_t operands[]) { cout << "STA "; PrintOperands(addressingMode, operands); } void ProcSTX(AddressingMode addressingMode, uint8_t operands[]) { cout << "STX "; PrintOperands(addressingMode, operands); } void ProcSTY(AddressingMode addressingMode, uint8_t operands[]) { cout << "STY "; PrintOperands(addressingMode, operands); } void ProcTAX(AddressingMode addressingMode, uint8_t operands[]) { reg::X = reg::Accumulator; SetFlagZ(reg::X == 0); SetFlagN((reg::X & (1 << 7)) != 0); } void ProcTAY(AddressingMode addressingMode, uint8_t operands[]) { reg::Y = reg::Accumulator; SetFlagZ(reg::Y == 0); SetFlagN((reg::Y & (1 << 7)) != 0); } void ProcTSX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TSX "; PrintOperands(addressingMode, operands); } void ProcTXA(AddressingMode addressingMode, uint8_t operands[]) { reg::Accumulator = reg::X; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } void ProcTXS(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXS "; PrintOperands(addressingMode, operands); } void ProcTYA(AddressingMode addressingMode, uint8_t operands[]) { uint8_t& operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Y & operand; SetFlagZ(reg::Accumulator == 0); SetFlagN((reg::Accumulator & (1 << 7)) != 0); } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <iostream> #include <iomanip> #include "instruction_procedures.h" #include "decoder.h" #include "memory.h" #include "global_registers.h" #include "register_procedures.h" using namespace std; void Format(AddressingMode addressingMode) { switch (addressingMode) { case Immediate: cout << "#$" << setw(2) << setfill('0') << uppercase << hex; break; case ZeroPage: case ZeroPageX: case ZeroPageY: case Relative: cout << "$" << setw(2) << setfill('0') << uppercase << hex; break; case Absolute: case AbsoluteX: case AbsoluteY: cout << "$" << setw(4) << setfill('0') << uppercase << hex; break; case ZeroPageIndirectX: case ZeroPageIndirectY: cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex; break; } //Anything else does not need special formatting } void PrintOperands(AddressingMode addressingMode, uint8_t operands[]) { Format(addressingMode); uint16_t operand; switch (addressingMode) { case Immediate: cout << (int)operands[0]; break; case ZeroPage: cout << (int)operands[0]; break; case ZeroPageX: cout << (int)operands[0] << ",X"; break; case ZeroPageY: cout << (int)operands[0] << ",Y"; case Relative: cout << (int)operands[0]; break; case Absolute: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand; break; case AbsoluteX: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",X"; break; case AbsoluteY: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",Y"; break; case ZeroPageIndirectX: cout << (int)operands[0] << ",X)"; break; case ZeroPageIndirectY: cout << (int)operands[0] << "),Y"; break; } cout << endl; } uint16_t _8_to_16(uint8_t high, uint8_t low) { return (uint16_t)high << 8 | low; } uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Absolute: return _8_to_16(operands[1], operands[0]); case ZeroPage: return operands[0]; case Relative: return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0]; case AbsoluteX: return reg::X + (int16_t)_8_to_16(operands[1], operands[0]); case AbsoluteY: return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]); case ZeroPageX: return (uint16_t)((reg::X + operands[0]) % 0xFF); case ZeroPageY: return (uint16_t)((reg::Y + operands[0]) % 0xFF); case ZeroPageIndirectX: return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]); case ZeroPageIndirectY: return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]); } } // Should not be used with addressing modes Accumulator and Implied. uint8_t _fetch_operand(AddressingMode addressingMode, uint8_t operands[]) { uint8_t operand; switch (addressingMode) { case Immediate: return operands[0]; default: return mem[_calculate_address(addressingMode, operands)]; } } void ProcADC(AddressingMode addressingMode, uint8_t operands[]) { uint8_t operand = _fetch_operand(addressingMode, operands); if (!GetFlagD()) { bool bit7 = reg::Accumulator & (1 << 7); uint8_t oldAcc = reg::Accumulator; if (reg::Accumulator + operand > 255) SetFlagC(true); else SetFlagC(false); reg::Accumulator += operand; SetFlagS(reg::Accumulator & (1 << 7)); // Put bit 7 in S flag SetFlagZ(!reg::Accumulator); //TODO: Implement overflow flag setting } } void ProcAND(AddressingMode addressingMode, uint8_t operands[]) { cout << "AND "; PrintOperands(addressingMode, operands); } void ProcASL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ASL "; PrintOperands(addressingMode, operands); } void ProcBCC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCC "; PrintOperands(addressingMode, operands); } void ProcBCS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCS "; PrintOperands(addressingMode, operands); } void ProcBEQ(AddressingMode addressingMode, uint8_t operands[]) { cout << "BEQ "; PrintOperands(addressingMode, operands); } void ProcBIT(AddressingMode addressingMode, uint8_t operands[]) { cout << "BIT "; PrintOperands(addressingMode, operands); } void ProcBMI(AddressingMode addressingMode, uint8_t operands[]) { cout << "BMI "; PrintOperands(addressingMode, operands); } void ProcBNE(AddressingMode addressingMode, uint8_t operands[]) { cout << "BNE "; PrintOperands(addressingMode, operands); } void ProcBPL(AddressingMode addressingMode, uint8_t operands[]) { cout << "BPL "; PrintOperands(addressingMode, operands); } void ProcBRK(AddressingMode addressingMode, uint8_t operands[]) { cout << "BRK "; PrintOperands(addressingMode, operands); } void ProcBVC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVC "; PrintOperands(addressingMode, operands); } void ProcBVS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVS "; PrintOperands(addressingMode, operands); } void ProcCLC(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLC "; PrintOperands(addressingMode, operands); } void ProcCLD(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLD "; PrintOperands(addressingMode, operands); } void ProcCLI(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLI "; PrintOperands(addressingMode, operands); } void ProcCLV(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLV "; PrintOperands(addressingMode, operands); } void ProcCMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "CMP "; PrintOperands(addressingMode, operands); } void ProcCPX(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPX "; PrintOperands(addressingMode, operands); } void ProcCPY(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPY "; PrintOperands(addressingMode, operands); } void ProcDEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEC "; PrintOperands(addressingMode, operands); } void ProcDEX(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEX "; PrintOperands(addressingMode, operands); } void ProcDEY(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEY "; PrintOperands(addressingMode, operands); } void ProcEOR(AddressingMode addressingMode, uint8_t operands[]) { cout << "EOR "; PrintOperands(addressingMode, operands); } void ProcINC(AddressingMode addressingMode, uint8_t operands[]) { cout << "INC "; PrintOperands(addressingMode, operands); } void ProcINX(AddressingMode addressingMode, uint8_t operands[]) { cout << "INX "; PrintOperands(addressingMode, operands); } void ProcINY(AddressingMode addressingMode, uint8_t operands[]) { cout << "INY "; PrintOperands(addressingMode, operands); } void ProcJMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "JMP "; PrintOperands(addressingMode, operands); } void ProcJSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "JSR "; PrintOperands(addressingMode, operands); } void ProcLDA(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDA "; PrintOperands(addressingMode, operands); } void ProcLDX(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDX "; PrintOperands(addressingMode, operands); } void ProcLDY(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDY "; PrintOperands(addressingMode, operands); } void ProcLSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "LSR "; PrintOperands(addressingMode, operands); } void ProcNOP(AddressingMode addressingMode, uint8_t operands[]) { cout << "NOP "; PrintOperands(addressingMode, operands); } void ProcORA(AddressingMode addressingMode, uint8_t operands[]) { cout << "ORA "; PrintOperands(addressingMode, operands); } void ProcPHA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHA "; PrintOperands(addressingMode, operands); } void ProcPHP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHP "; PrintOperands(addressingMode, operands); } void ProcPLA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLA "; PrintOperands(addressingMode, operands); } void ProcPLP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLP "; PrintOperands(addressingMode, operands); } void ProcROL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROL "; PrintOperands(addressingMode, operands); } void ProcROR(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROR "; PrintOperands(addressingMode, operands); } void ProcRTI(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTI "; PrintOperands(addressingMode, operands); } void ProcRTS(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTS "; PrintOperands(addressingMode, operands); } void ProcSBC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SBC "; PrintOperands(addressingMode, operands); } void ProcSEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEC "; PrintOperands(addressingMode, operands); } void ProcSED(AddressingMode addressingMode, uint8_t operands[]) { cout << "SED "; PrintOperands(addressingMode, operands); } void ProcSEI(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEI "; PrintOperands(addressingMode, operands); } void ProcSTA(AddressingMode addressingMode, uint8_t operands[]) { cout << "STA "; PrintOperands(addressingMode, operands); } void ProcSTX(AddressingMode addressingMode, uint8_t operands[]) { cout << "STX "; PrintOperands(addressingMode, operands); } void ProcSTY(AddressingMode addressingMode, uint8_t operands[]) { cout << "STY "; PrintOperands(addressingMode, operands); } void ProcTAX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TAX "; PrintOperands(addressingMode, operands); } void ProcTAY(AddressingMode addressingMode, uint8_t operands[]) { cout << "TAY "; PrintOperands(addressingMode, operands); } void ProcTSX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TSX "; PrintOperands(addressingMode, operands); } void ProcTXA(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXA "; PrintOperands(addressingMode, operands); } void ProcTXS(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXS "; PrintOperands(addressingMode, operands); } void ProcTYA(AddressingMode addressingMode, uint8_t operands[]) { cout << "TYA "; PrintOperands(addressingMode, operands); } <commit_msg>implement AND<commit_after>#pragma once #include <cstdint> #include <iostream> #include <iomanip> #include "instruction_procedures.h" #include "decoder.h" #include "memory.h" #include "global_registers.h" #include "register_procedures.h" using namespace std; void Format(AddressingMode addressingMode) { switch (addressingMode) { case Immediate: cout << "#$" << setw(2) << setfill('0') << uppercase << hex; break; case ZeroPage: case ZeroPageX: case ZeroPageY: case Relative: cout << "$" << setw(2) << setfill('0') << uppercase << hex; break; case Absolute: case AbsoluteX: case AbsoluteY: cout << "$" << setw(4) << setfill('0') << uppercase << hex; break; case ZeroPageIndirectX: case ZeroPageIndirectY: cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex; break; } //Anything else does not need special formatting } void PrintOperands(AddressingMode addressingMode, uint8_t operands[]) { Format(addressingMode); uint16_t operand; switch (addressingMode) { case Immediate: cout << (int)operands[0]; break; case ZeroPage: cout << (int)operands[0]; break; case ZeroPageX: cout << (int)operands[0] << ",X"; break; case ZeroPageY: cout << (int)operands[0] << ",Y"; case Relative: cout << (int)operands[0]; break; case Absolute: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand; break; case AbsoluteX: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",X"; break; case AbsoluteY: operand = (uint16_t)operands[1] << 8 | operands[0]; cout << operand << ",Y"; break; case ZeroPageIndirectX: cout << (int)operands[0] << ",X)"; break; case ZeroPageIndirectY: cout << (int)operands[0] << "),Y"; break; } cout << endl; } uint16_t _8_to_16(uint8_t high, uint8_t low) { return (uint16_t)high << 8 | low; } uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[]) { switch (addressingMode) { case Absolute: return _8_to_16(operands[1], operands[0]); case ZeroPage: return operands[0]; case Relative: return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0]; case AbsoluteX: return reg::X + (int16_t)_8_to_16(operands[1], operands[0]); case AbsoluteY: return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]); case ZeroPageX: return (uint16_t)((reg::X + operands[0]) % 0xFF); case ZeroPageY: return (uint16_t)((reg::Y + operands[0]) % 0xFF); case ZeroPageIndirectX: return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]); case ZeroPageIndirectY: return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]); } } // Should not be used with addressing modes Accumulator and Implied. uint8_t _fetch_operand(AddressingMode addressingMode, uint8_t operands[]) { uint8_t operand; switch (addressingMode) { case Immediate: return operands[0]; default: return mem[_calculate_address(addressingMode, operands)]; } } void ProcADC(AddressingMode addressingMode, uint8_t operands[]) { uint8_t operand = _fetch_operand(addressingMode, operands); if (!GetFlagD()) { bool bit7 = reg::Accumulator & (1 << 7); uint8_t oldAcc = reg::Accumulator; if (reg::Accumulator + operand > 255) SetFlagC(true); else SetFlagC(false); reg::Accumulator += operand; SetFlagS(reg::Accumulator & (1 << 7)); // Put bit 7 in S flag SetFlagZ(!reg::Accumulator); //TODO: Implement overflow flag setting } } void ProcAND(AddressingMode addressingMode, uint8_t operands[]) { uint8_t operand = _fetch_operand(addressingMode, operands); reg::Accumulator = reg::Accumulator & operand; SetFlagZ(reg::Accumulator); SetFlagS(reg::Accumulator & (1 << 7)); } void ProcASL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ASL "; PrintOperands(addressingMode, operands); } void ProcBCC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCC "; PrintOperands(addressingMode, operands); } void ProcBCS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BCS "; PrintOperands(addressingMode, operands); } void ProcBEQ(AddressingMode addressingMode, uint8_t operands[]) { cout << "BEQ "; PrintOperands(addressingMode, operands); } void ProcBIT(AddressingMode addressingMode, uint8_t operands[]) { cout << "BIT "; PrintOperands(addressingMode, operands); } void ProcBMI(AddressingMode addressingMode, uint8_t operands[]) { cout << "BMI "; PrintOperands(addressingMode, operands); } void ProcBNE(AddressingMode addressingMode, uint8_t operands[]) { cout << "BNE "; PrintOperands(addressingMode, operands); } void ProcBPL(AddressingMode addressingMode, uint8_t operands[]) { cout << "BPL "; PrintOperands(addressingMode, operands); } void ProcBRK(AddressingMode addressingMode, uint8_t operands[]) { cout << "BRK "; PrintOperands(addressingMode, operands); } void ProcBVC(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVC "; PrintOperands(addressingMode, operands); } void ProcBVS(AddressingMode addressingMode, uint8_t operands[]) { cout << "BVS "; PrintOperands(addressingMode, operands); } void ProcCLC(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLC "; PrintOperands(addressingMode, operands); } void ProcCLD(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLD "; PrintOperands(addressingMode, operands); } void ProcCLI(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLI "; PrintOperands(addressingMode, operands); } void ProcCLV(AddressingMode addressingMode, uint8_t operands[]) { cout << "CLV "; PrintOperands(addressingMode, operands); } void ProcCMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "CMP "; PrintOperands(addressingMode, operands); } void ProcCPX(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPX "; PrintOperands(addressingMode, operands); } void ProcCPY(AddressingMode addressingMode, uint8_t operands[]) { cout << "CPY "; PrintOperands(addressingMode, operands); } void ProcDEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEC "; PrintOperands(addressingMode, operands); } void ProcDEX(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEX "; PrintOperands(addressingMode, operands); } void ProcDEY(AddressingMode addressingMode, uint8_t operands[]) { cout << "DEY "; PrintOperands(addressingMode, operands); } void ProcEOR(AddressingMode addressingMode, uint8_t operands[]) { cout << "EOR "; PrintOperands(addressingMode, operands); } void ProcINC(AddressingMode addressingMode, uint8_t operands[]) { cout << "INC "; PrintOperands(addressingMode, operands); } void ProcINX(AddressingMode addressingMode, uint8_t operands[]) { cout << "INX "; PrintOperands(addressingMode, operands); } void ProcINY(AddressingMode addressingMode, uint8_t operands[]) { cout << "INY "; PrintOperands(addressingMode, operands); } void ProcJMP(AddressingMode addressingMode, uint8_t operands[]) { cout << "JMP "; PrintOperands(addressingMode, operands); } void ProcJSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "JSR "; PrintOperands(addressingMode, operands); } void ProcLDA(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDA "; PrintOperands(addressingMode, operands); } void ProcLDX(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDX "; PrintOperands(addressingMode, operands); } void ProcLDY(AddressingMode addressingMode, uint8_t operands[]) { cout << "LDY "; PrintOperands(addressingMode, operands); } void ProcLSR(AddressingMode addressingMode, uint8_t operands[]) { cout << "LSR "; PrintOperands(addressingMode, operands); } void ProcNOP(AddressingMode addressingMode, uint8_t operands[]) { cout << "NOP "; PrintOperands(addressingMode, operands); } void ProcORA(AddressingMode addressingMode, uint8_t operands[]) { cout << "ORA "; PrintOperands(addressingMode, operands); } void ProcPHA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHA "; PrintOperands(addressingMode, operands); } void ProcPHP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PHP "; PrintOperands(addressingMode, operands); } void ProcPLA(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLA "; PrintOperands(addressingMode, operands); } void ProcPLP(AddressingMode addressingMode, uint8_t operands[]) { cout << "PLP "; PrintOperands(addressingMode, operands); } void ProcROL(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROL "; PrintOperands(addressingMode, operands); } void ProcROR(AddressingMode addressingMode, uint8_t operands[]) { cout << "ROR "; PrintOperands(addressingMode, operands); } void ProcRTI(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTI "; PrintOperands(addressingMode, operands); } void ProcRTS(AddressingMode addressingMode, uint8_t operands[]) { cout << "RTS "; PrintOperands(addressingMode, operands); } void ProcSBC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SBC "; PrintOperands(addressingMode, operands); } void ProcSEC(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEC "; PrintOperands(addressingMode, operands); } void ProcSED(AddressingMode addressingMode, uint8_t operands[]) { cout << "SED "; PrintOperands(addressingMode, operands); } void ProcSEI(AddressingMode addressingMode, uint8_t operands[]) { cout << "SEI "; PrintOperands(addressingMode, operands); } void ProcSTA(AddressingMode addressingMode, uint8_t operands[]) { cout << "STA "; PrintOperands(addressingMode, operands); } void ProcSTX(AddressingMode addressingMode, uint8_t operands[]) { cout << "STX "; PrintOperands(addressingMode, operands); } void ProcSTY(AddressingMode addressingMode, uint8_t operands[]) { cout << "STY "; PrintOperands(addressingMode, operands); } void ProcTAX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TAX "; PrintOperands(addressingMode, operands); } void ProcTAY(AddressingMode addressingMode, uint8_t operands[]) { cout << "TAY "; PrintOperands(addressingMode, operands); } void ProcTSX(AddressingMode addressingMode, uint8_t operands[]) { cout << "TSX "; PrintOperands(addressingMode, operands); } void ProcTXA(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXA "; PrintOperands(addressingMode, operands); } void ProcTXS(AddressingMode addressingMode, uint8_t operands[]) { cout << "TXS "; PrintOperands(addressingMode, operands); } void ProcTYA(AddressingMode addressingMode, uint8_t operands[]) { cout << "TYA "; PrintOperands(addressingMode, operands); } <|endoftext|>
<commit_before>int DEBUG=1; TCPClient client; long SerialSpeed[] = {600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200}; void ipArrayFromString(byte ipArray[], String ipString) { int dot1 = ipString.indexOf('.'); ipArray[0] = ipString.substring(0, dot1).toInt(); int dot2 = ipString.indexOf('.', dot1 + 1); ipArray[1] = ipString.substring(dot1 + 1, dot2).toInt(); dot1 = ipString.indexOf('.', dot2 + 1); ipArray[2] = ipString.substring(dot2 + 1, dot1).toInt(); ipArray[3] = ipString.substring(dot1 + 1).toInt(); } int connectToMyServer(String params) { //parse data int colonIndex = params.indexOf(":"); String ip = params.substring(0, colonIndex); String port = params.substring(colonIndex+1, params.length()); if(DEBUG) Serial.println("Attempting to connect to server: "+ip+":"+port); byte serverAddress[4]; ipArrayFromString(serverAddress, ip); int serverPort = port.toInt(); if (client.connect(serverAddress, serverPort)) { if (DEBUG) Serial.println("Connected to server: "+ip+":"+port); return 1; // successfully connected } else { if(DEBUG) Serial.println("Unable to connect to server: "+ip+":"+port); return -1; // failed to connect } } void setup() { Spark.function("connect", connectToMyServer); if(DEBUG) Serial.begin(115200); } void loop() { if (client.connected()) { if (client.available()) { // parse and execute commands int action = client.read(); if(DEBUG) Serial.println("Action received: "+('0'+action)); char charVal; int pin, mode, val, type, speed, address, stop; switch (action) { case 0x00: // pinMode pin = client.read(); mode = client.read(); //mode is modeled after Standard Firmata if (mode == 0x00) { pinMode(pin, INPUT); } else if (mode == 0x02) { pinMode(pin, INPUT_PULLUP); } else if (mode == 0x03) { pinMode(pin, INPUT_PULLDOWN); } else if (mode == 0x01) { pinMode(pin, OUTPUT); } break; case 0x01: // digitalWrite pin = client.read(); val = client.read(); digitalWrite(pin, val); break; case 0x02: // analogWrite pin = client.read(); val = client.read(); analogWrite(pin, val); break; case 0x03: // digitalRead pin = client.read(); val = digitalRead(pin); client.write(0x03); client.write(pin); client.write(val); break; case 0x04: // analogRead pin = client.read(); val = analogRead(pin); client.write(0x04); client.write(pin); client.write(val); break; // Serial API case 0x10: // serial.begin type = client.read(); speed = client.read(); if (type == 0) { Serial.begin(SerialSpeed[speed]); } else { Serial1.begin(SerialSpeed[speed]); } break; case 0x12: // serial.end type = client.read(); if (type == 0) { Serial.end(); } else { Serial1.end(); } break; case 0x13: // serial.peek type = client.read(); if (type == 0) { val = Serial.peek(); } else { val = Serial1.peek(); } client.write(0x07); client.write(type); client.write(val); break; case 0x14: // serial.available() type = client.read(); if (type == 0) { val = Serial.available(); } else { val = Serial1.available(); } client.write(0x07); client.write(type); client.write(val); break; case 0x15: // serial.write type = client.read(); len = client.read(); while (i = 0; i < len; i++) { if (type ==0) { Serial.write(client.read()); } else { Serial1.write(client.read()); } } break; case 0x16: // serial.read type = client.read(); if (type == 0) { val = Serial.read(); } else { val = Serial1.read(); } client.write(0x16); client.write(type); client.write(val); break; case 0x17: // serial.flush type = client.read(); if (type == 0) { Serial.flush(); } else { Serial1.flush(); } break; // SPI API case 0x20: // SPI.begin SPI.begin(); break; case 0x21: // SPI.end SPI.end(); break; case 0x22: // SPI.setBitOrder type = client.read(); SPI.setBitOrder((type ? MSBFIRST : LSBFIRST)); break; case 0x22: // SPI.setClockDivider val = client.read(); if (val == 0) { SPI.setClockDivider(SPI_CLOCK_DIV2); } else if (val == 1) { SPI.setClockDivider(SPI_CLOCK_DIV4); } else if (val == 2) { SPI.setClockDivider(SPI_CLOCK_DIV8); } else if (val == 3) { SPI.setClockDivider(SPI_CLOCK_DIV16); } else if (val == 4) { SPI.setClockDivider(SPI_CLOCK_DIV32); } else if (val == 5) { SPI.setClockDivider(SPI_CLOCK_DIV64); } else if (val == 6) { SPI.setClockDivider(SPI_CLOCK_DIV128); } else if (val == 7) { SPI.setClockDivider(SPI_CLOCK_DIV256); } break; case 0x23: // SPI.setDataMode val = client.read(); if (val == 0) { SPI.setDataMode(SPI_MODE0); } else if (val == 1) { SPI.setDataMode(SPI_MODE1); } else if (val == 2) { SPI.setDataMode(SPI_MODE2); } else if (val == 3) { SPI.setDataMode(SPI_MODE3); } break; case 0x24: // SPI.transfer val = client.read(); val = SPI.transfer(val); client.write(0x24); client.write(val); break; // Wire API case 0x30: // Wire.begin address = client.read(); if (address == 0) { Wire.begin(); } else { Wire.begin(address); } break; case 0x31: // Wire.requestFrom address = client.read(); int quantity = client.read(); stop = client.read(); Wire.requestFrom(address, quantity, stop); break; case 0x32: // Wire.beginTransmission address = client.read(); Wire.beginTransmission(address); break; case 0x33: // Wire.endTransmission stop = client.read(); val = Wire.endTransmission(stop); client.write(0x33); client.write(val); break; case 0x34: // Wire.write len = client.read(); char wireData[len]; for (i = 0; i< len; i++) { wireData[i] = client.read(); } val = Wire.write(data, len); client.write(0x34); client.write(val); break; case 0x35: // Wire.available val = Wire.available(); client.write(0x35); client.write(val); break; case 0x36: // Wire.read val = Wire.read(); client.write(0x36); client.write(val); break; default: // noop break; } } } }<commit_msg>Update to allow always send.<commit_after>int DEBUG=1; TCPClient client; bool reading[20]; long SerialSpeed[] = {600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200}; void ipArrayFromString(byte ipArray[], String ipString) { int dot1 = ipString.indexOf('.'); ipArray[0] = ipString.substring(0, dot1).toInt(); int dot2 = ipString.indexOf('.', dot1 + 1); ipArray[1] = ipString.substring(dot1 + 1, dot2).toInt(); dot1 = ipString.indexOf('.', dot2 + 1); ipArray[2] = ipString.substring(dot2 + 1, dot1).toInt(); ipArray[3] = ipString.substring(dot1 + 1).toInt(); } int connectToMyServer(String params) { //parse data int colonIndex = params.indexOf(":"); String ip = params.substring(0, colonIndex); String port = params.substring(colonIndex+1, params.length()); if(DEBUG) Serial.println("Attempting to connect to server: "+ip+":"+port); byte serverAddress[4]; ipArrayFromString(serverAddress, ip); int serverPort = port.toInt(); if (client.connect(serverAddress, serverPort)) { if (DEBUG) Serial.println("Connected to server: "+ip+":"+port); return 1; // successfully connected } else { if(DEBUG) Serial.println("Unable to connect to server: "+ip+":"+port); return -1; // failed to connect } } void setup() { Spark.function("connect", connectToMyServer); if(DEBUG) Serial.begin(115200); } void report() { int action = 0x03; for (int i = 0; i < 20; i++) { if (reading[i]) { if (i < 10 && (reading[i] & 1)) { // Digital pins are 0-9 and can only do digital read client.write(0x03); client.write(i); client.write(digitalRead(i)); } else { if (reading[i] & 1) { client.write(0x03); client.write(i); client.write(digitalRead(i)); } else if (reading[i] & 2) { client.write(0x04); client.write(i); client.write(analogRead(i)); } } } } } void loop() { report(); if (client.connected()) { if (client.available()) { // parse and execute commands int action = client.read(); if(DEBUG) Serial.println("Action received: "+('0'+action)); char charVal; int pin, mode, val, type, speed, address, stop; switch (action) { case 0x00: // pinMode pin = client.read(); mode = client.read(); //mode is modeled after Standard Firmata if (mode == 0x00) { pinMode(pin, INPUT); } else if (mode == 0x02) { pinMode(pin, INPUT_PULLUP); } else if (mode == 0x03) { pinMode(pin, INPUT_PULLDOWN); } else if (mode == 0x01) { pinMode(pin, OUTPUT); } break; case 0x01: // digitalWrite pin = client.read(); val = client.read(); digitalWrite(pin, val); break; case 0x02: // analogWrite pin = client.read(); val = client.read(); analogWrite(pin, val); break; case 0x03: // digitalRead pin = client.read(); val = digitalRead(pin); client.write(0x03); client.write(pin); client.write(val); break; case 0x04: // analogRead pin = client.read(); val = analogRead(pin); client.write(0x04); client.write(pin); client.write(val); break; case 0x05: // set always send bit pin = client.read(); val = client.read(); reading[pin] = val; break; // Serial API case 0x10: // serial.begin type = client.read(); speed = client.read(); if (type == 0) { Serial.begin(SerialSpeed[speed]); } else { Serial1.begin(SerialSpeed[speed]); } break; case 0x12: // serial.end type = client.read(); if (type == 0) { Serial.end(); } else { Serial1.end(); } break; case 0x13: // serial.peek type = client.read(); if (type == 0) { val = Serial.peek(); } else { val = Serial1.peek(); } client.write(0x07); client.write(type); client.write(val); break; case 0x14: // serial.available() type = client.read(); if (type == 0) { val = Serial.available(); } else { val = Serial1.available(); } client.write(0x07); client.write(type); client.write(val); break; case 0x15: // serial.write type = client.read(); len = client.read(); while (i = 0; i < len; i++) { if (type ==0) { Serial.write(client.read()); } else { Serial1.write(client.read()); } } break; case 0x16: // serial.read type = client.read(); if (type == 0) { val = Serial.read(); } else { val = Serial1.read(); } client.write(0x16); client.write(type); client.write(val); break; case 0x17: // serial.flush type = client.read(); if (type == 0) { Serial.flush(); } else { Serial1.flush(); } break; // SPI API case 0x20: // SPI.begin SPI.begin(); break; case 0x21: // SPI.end SPI.end(); break; case 0x22: // SPI.setBitOrder type = client.read(); SPI.setBitOrder((type ? MSBFIRST : LSBFIRST)); break; case 0x22: // SPI.setClockDivider val = client.read(); if (val == 0) { SPI.setClockDivider(SPI_CLOCK_DIV2); } else if (val == 1) { SPI.setClockDivider(SPI_CLOCK_DIV4); } else if (val == 2) { SPI.setClockDivider(SPI_CLOCK_DIV8); } else if (val == 3) { SPI.setClockDivider(SPI_CLOCK_DIV16); } else if (val == 4) { SPI.setClockDivider(SPI_CLOCK_DIV32); } else if (val == 5) { SPI.setClockDivider(SPI_CLOCK_DIV64); } else if (val == 6) { SPI.setClockDivider(SPI_CLOCK_DIV128); } else if (val == 7) { SPI.setClockDivider(SPI_CLOCK_DIV256); } break; case 0x23: // SPI.setDataMode val = client.read(); if (val == 0) { SPI.setDataMode(SPI_MODE0); } else if (val == 1) { SPI.setDataMode(SPI_MODE1); } else if (val == 2) { SPI.setDataMode(SPI_MODE2); } else if (val == 3) { SPI.setDataMode(SPI_MODE3); } break; case 0x24: // SPI.transfer val = client.read(); val = SPI.transfer(val); client.write(0x24); client.write(val); break; // Wire API case 0x30: // Wire.begin address = client.read(); if (address == 0) { Wire.begin(); } else { Wire.begin(address); } break; case 0x31: // Wire.requestFrom address = client.read(); int quantity = client.read(); stop = client.read(); Wire.requestFrom(address, quantity, stop); break; case 0x32: // Wire.beginTransmission address = client.read(); Wire.beginTransmission(address); break; case 0x33: // Wire.endTransmission stop = client.read(); val = Wire.endTransmission(stop); client.write(0x33); client.write(val); break; case 0x34: // Wire.write len = client.read(); char wireData[len]; for (i = 0; i< len; i++) { wireData[i] = client.read(); } val = Wire.write(data, len); client.write(0x34); client.write(val); break; case 0x35: // Wire.available val = Wire.available(); client.write(0x35); client.write(val); break; case 0x36: // Wire.read val = Wire.read(); client.write(0x36); client.write(val); break; default: // noop break; } } } }<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2013 PX4 Development Team. All rights reserved. * Author: Pavel Kirienko <pavel.kirienko@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 <ch.h> #include <hal.h> #include <cassert> #include <cerrno> #include <cmath> #include <cstdint> #include <unistd.h> #include <board/board.hpp> #include <board/led.hpp> #include <console.hpp> #include <pwm_input.hpp> #include <temperature_sensor.hpp> #include <motor/motor.h> #include <uavcan_node/uavcan_node.hpp> namespace { static constexpr unsigned WATCHDOG_TIMEOUT = 10000; board::LEDOverlay led_ctl; os::watchdog::Timer init() { auto wdt = board::init(WATCHDOG_TIMEOUT); led_ctl.set(board::LEDColor::PALE_WHITE); // Temperature sensor int res = temperature_sensor::init(); if (res < 0) { os::lowsyslog("Failed to init temperature sensor\n"); board::die(res); } // Motor control (must be initialized earlier than communicaton interfaces) res = motor_init(); if (res < 0) { board::die(res); } // PWM input pwm_input_init(); // UAVCAN node res = uavcan_node::init(); if (res < 0) { board::die(res); } // Self test res = motor_test_hardware(); if (res != 0) { board::die(res); } if (motor_test_motor()) { os::lowsyslog("Motor is not connected or damaged\n"); } // Initializing console after delay to ensure that CLI is flushed usleep(300000); console_init(); return wdt; } void do_startup_beep() { motor_beep(1000, 100); ::usleep(200 * 1000); motor_beep(1000, 100); } } namespace os { void applicationHaltHook() { motor_emergency(); board::led_emergency_override(board::LEDColor::RED); } } int main() { auto wdt = init(); chThdSetPriority(LOWPRIO); do_startup_beep(); motor_confirm_initialization(); uavcan_node::set_node_status_ok(); /* * Here we run some high-level self diagnostics, indicating the system health via UAVCAN and LED. * TODO: Refactor. * TODO: Report status flags via vendor-specific status field. */ auto config_modifications = os::config::getModificationCounter(); while (!os::isRebootRequested()) { wdt.reset(); if (motor_is_blocked() || !temperature_sensor::is_ok()) { led_ctl.set(board::LEDColor::YELLOW); uavcan_node::set_node_status_critical(); } else { led_ctl.set(board::LEDColor::DARK_GREEN); uavcan_node::set_node_status_ok(); } const auto new_config_modifications = os::config::getModificationCounter(); if ((new_config_modifications != config_modifications) && motor_is_idle()) { config_modifications = new_config_modifications; os::lowsyslog("Saving configuration... "); const int res = ::configSave(); // TODO use C++ API os::lowsyslog("Done [%d]\n", res); } ::usleep(10 * 1000); } ::usleep(100 * 1000); motor_stop(); board::reboot(); return 0; } #define MATCH_GCC_VERSION(major, minor) \ ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor))) #if !MATCH_GCC_VERSION(4, 9) # error "This compiler is not supported" #endif <commit_msg>Delayed config saving<commit_after>/**************************************************************************** * * Copyright (C) 2013 PX4 Development Team. All rights reserved. * Author: Pavel Kirienko <pavel.kirienko@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 <ch.h> #include <hal.h> #include <cassert> #include <cerrno> #include <cmath> #include <cstdint> #include <unistd.h> #include <board/board.hpp> #include <board/led.hpp> #include <console.hpp> #include <pwm_input.hpp> #include <temperature_sensor.hpp> #include <motor/motor.h> #include <uavcan_node/uavcan_node.hpp> namespace { static constexpr unsigned WATCHDOG_TIMEOUT = 10000; board::LEDOverlay led_ctl; os::watchdog::Timer init() { auto wdt = board::init(WATCHDOG_TIMEOUT); led_ctl.set(board::LEDColor::PALE_WHITE); // Temperature sensor int res = temperature_sensor::init(); if (res < 0) { os::lowsyslog("Failed to init temperature sensor\n"); board::die(res); } // Motor control (must be initialized earlier than communicaton interfaces) res = motor_init(); if (res < 0) { board::die(res); } // PWM input pwm_input_init(); // UAVCAN node res = uavcan_node::init(); if (res < 0) { board::die(res); } // Self test res = motor_test_hardware(); if (res != 0) { board::die(res); } if (motor_test_motor()) { os::lowsyslog("Motor is not connected or damaged\n"); } // Initializing console after delay to ensure that CLI is flushed usleep(300000); console_init(); return wdt; } void do_startup_beep() { motor_beep(1000, 100); ::usleep(200 * 1000); motor_beep(1000, 100); } /** * Managing configuration parameters in the background from the main thread. * This code was borrowed from PX4ESC. */ class BackgroundConfigManager { static constexpr float SaveDelay = 1.0F; static constexpr float SaveDelayAfterError = 10.0F; os::Logger logger { "BackgroundConfigManager" }; unsigned modification_counter_ = os::config::getModificationCounter(); ::systime_t last_modification_ts_ = chVTGetSystemTimeX(); bool pending_save_ = false; bool last_save_failed_ = false; float getTimeSinceModification() const { return float(ST2MS(chVTTimeElapsedSinceX(last_modification_ts_))) / 1e3F; } public: void poll() { const auto new_mod_cnt = os::config::getModificationCounter(); if (new_mod_cnt != modification_counter_) { modification_counter_ = new_mod_cnt; last_modification_ts_ = chVTGetSystemTimeX(); pending_save_ = true; } if (pending_save_) { if (getTimeSinceModification() > (last_save_failed_ ? SaveDelayAfterError : SaveDelay)) { os::TemporaryPriorityChanger priority_changer(HIGHPRIO); if (motor_is_idle()) { logger.println("Saving [modcnt=%u]", modification_counter_); const int res = os::config::save(); if (res >= 0) { pending_save_ = false; last_save_failed_ = false; } else { last_save_failed_ = true; logger.println("SAVE ERROR %d '%s'", res, std::strerror(std::abs(res))); } } } } } }; } namespace os { void applicationHaltHook() { motor_emergency(); board::led_emergency_override(board::LEDColor::RED); } } int main() { auto wdt = init(); chThdSetPriority(LOWPRIO); do_startup_beep(); motor_confirm_initialization(); uavcan_node::set_node_status_ok(); /* * Here we run some high-level self diagnostics, indicating the system health via UAVCAN and LED. * TODO: Refactor. * TODO: Report status flags via vendor-specific status field. */ BackgroundConfigManager bg_config_manager; while (!os::isRebootRequested()) { wdt.reset(); if (motor_is_blocked() || !temperature_sensor::is_ok()) { led_ctl.set(board::LEDColor::YELLOW); uavcan_node::set_node_status_critical(); } else { led_ctl.set(board::LEDColor::DARK_GREEN); uavcan_node::set_node_status_ok(); } bg_config_manager.poll(); ::usleep(10 * 1000); } ::usleep(100 * 1000); motor_stop(); board::reboot(); return 0; } #define MATCH_GCC_VERSION(major, minor) \ ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor))) #if !MATCH_GCC_VERSION(4, 9) # error "This compiler is not supported" #endif <|endoftext|>
<commit_before>#include <pxp-agent/external_module.hpp> #define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.external_module" #include <leatherman/logging/logging.hpp> #include <leatherman/execution/execution.hpp> #include <leatherman/file_util/file.hpp> #include <horsewhisperer/horsewhisperer.h> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <atomic> #include <memory> // shared_ptr // TODO(ale): disable assert() once we're confident with the code... // To disable assert() // #define NDEBUG #include <cassert> namespace PXPAgent { static const std::string METADATA_SCHEMA_NAME { "external_module_metadata" }; static const std::string ACTION_SCHEMA_NAME { "action_metadata" }; static const std::string METADATA_CONFIGURATION_ENTRY { "configuration" }; static const std::string METADATA_ACTIONS_ENTRY { "actions" }; static const int EXTERNAL_MODULE_FILE_ERROR_EC { 5 }; namespace fs = boost::filesystem; namespace HW = HorseWhisperer; namespace lth_exec = leatherman::execution; namespace lth_file = leatherman::file_util; // // Free functions // // Provides the module metadata validator PCPClient::Validator getMetadataValidator() { // Metadata schema PCPClient::Schema metadata_schema { METADATA_SCHEMA_NAME, PCPClient::ContentType::Json }; using T_C = PCPClient::TypeConstraint; metadata_schema.addConstraint("description", T_C::String, true); metadata_schema.addConstraint(METADATA_CONFIGURATION_ENTRY, T_C::Object, false); metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, T_C::Array, true); // 'actions' is an array of actions; define the action sub_schema PCPClient::Schema action_schema { ACTION_SCHEMA_NAME, PCPClient::ContentType::Json }; action_schema.addConstraint("description", T_C::String, false); action_schema.addConstraint("name", T_C::String, true); action_schema.addConstraint("input", T_C::Object, true); action_schema.addConstraint("results", T_C::Object, true); metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, action_schema, false); PCPClient::Validator validator {}; validator.registerSchema(metadata_schema); return validator; } // // Public interface // ExternalModule::ExternalModule(const std::string& path, const lth_jc::JsonContainer& config) : path_ { path }, config_ { config } { fs::path module_path { path }; module_name = module_path.stem().string(); auto metadata = getMetadata(); try { if (metadata.includes(METADATA_CONFIGURATION_ENTRY)) { registerConfiguration( metadata.get<lth_jc::JsonContainer>(METADATA_CONFIGURATION_ENTRY)); } else { LOG_DEBUG("Found no configuration schema for module '%1%'", module_name); } registerActions(metadata); } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata of module %1%: %2%", module_name, e.what()); std::string err { "invalid metadata of module " + module_name }; throw Module::LoadingError { err }; } } ExternalModule::ExternalModule(const std::string& path) : path_ { path }, config_ { "{}" } { fs::path module_path { path }; module_name = module_path.stem().string(); auto metadata = getMetadata(); try { registerActions(metadata); } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata of module %1%: %2%", module_name, e.what()); std::string err { "invalid metadata of module " + module_name }; throw Module::LoadingError { err }; } } void ExternalModule::validateConfiguration() { if (config_validator_.includesSchema(module_name)) { config_validator_.validate(config_, module_name); } else { LOG_DEBUG("The '%1%' configuration will not be validated; no JSON " "schema is available", module_name); } } // // Static functions // void ExternalModule::readNonBlockingOutcome(const ActionRequest& request, const std::string& out_file, const std::string& err_file, std::string& out_txt, std::string& err_txt) { if (fs::exists(err_file)) { if (!lth_file::read(err_file, err_txt)) { LOG_ERROR("Failed to read error file '%1%' of '%2% %3%'; will " "continue processing the output", err_file, request.module(), request.action()); } else { LOG_TRACE("Successfully read error file '%1%'", err_file); } } if (!fs::exists(out_file)) { LOG_DEBUG("Output file '%1%' of '%2% %3%' does not exist", out_file, request.module(), request.action()); } else if (!lth_file::read(out_file, out_txt)) { LOG_ERROR("Failed to read output file '%1%' of '%2% %3%'", out_file, request.module(), request.action()); throw Module::ProcessingError { "failed to read" }; } else if (out_txt.empty()) { LOG_TRACE("Output file '%1%' of '%2% %3%' is empty", out_file, request.module(), request.action()); } else { LOG_TRACE("Successfully read output file '%1%'", out_file); } } // // Private interface // // Metadata validator (static member) const PCPClient::Validator ExternalModule::metadata_validator_ { getMetadataValidator() }; // Retrieve and validate the module metadata const lth_jc::JsonContainer ExternalModule::getMetadata() { auto exec = #ifdef _WIN32 lth_exec::execute("cmd.exe", { "/c", path_, "metadata" }, #else lth_exec::execute(path_, { "metadata" }, #endif 0, {lth_exec::execution_options::merge_environment}); if (!exec.error.empty()) { LOG_ERROR("Failed to load the external module metadata from %1%: %2%", path_, exec.error); throw Module::LoadingError { "failed to load external module metadata" }; } lth_jc::JsonContainer metadata { exec.output }; try { metadata_validator_.validate(metadata, METADATA_SCHEMA_NAME); LOG_DEBUG("External module %1%: metadata validation OK", module_name); } catch (PCPClient::validation_error& e) { throw Module::LoadingError { std::string { "metadata validation failure: " } + e.what() }; } return metadata; } void ExternalModule::registerConfiguration(const lth_jc::JsonContainer& config_metadata) { try { PCPClient::Schema configuration_schema { module_name, config_metadata }; LOG_DEBUG("Registering module config schema for '%1%'", module_name); config_validator_.registerSchema(configuration_schema); } catch (PCPClient::schema_error& e) { LOG_ERROR("Failed to parse the configuration schema of module '%1%': %2%", module_name, e.what()); std::string err { "invalid configuration schema of module " + module_name }; throw Module::LoadingError { err }; } } void ExternalModule::registerActions(const lth_jc::JsonContainer& metadata) { for (auto& action : metadata.get<std::vector<lth_jc::JsonContainer>>( METADATA_ACTIONS_ENTRY)) { registerAction(action); } } // Register the specified action after ensuring that the input and // output schemas are valid JSON (i.e. we can instantiate Schema). void ExternalModule::registerAction(const lth_jc::JsonContainer& action) { // NOTE(ale): name, input, and output are required action entries auto action_name = action.get<std::string>("name"); LOG_DEBUG("Validating action '%1% %2%'", module_name, action_name); try { auto input_schema_json = action.get<lth_jc::JsonContainer>("input"); PCPClient::Schema input_schema { action_name, input_schema_json }; auto results_schema_json = action.get<lth_jc::JsonContainer>("results"); PCPClient::Schema results_schema { action_name, results_schema_json }; // Metadata schemas are valid JSON; store metadata LOG_DEBUG("Action '%1% %2%' has been validated", module_name, action_name); actions.push_back(action_name); input_validator_.registerSchema(input_schema); results_validator_.registerSchema(results_schema); } catch (PCPClient::schema_error& e) { LOG_ERROR("Failed to parse metadata schemas of action '%1% %2%': %3%", module_name, action_name, e.what()); std::string err { "invalid schemas of '" + module_name + " " + action_name + "'" }; throw Module::LoadingError { err }; } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata schemas of action '%1% %2%': %3%", module_name, action_name, e.what()); std::string err { "invalid metadata of '" + module_name + " " + action_name + "'" }; throw Module::LoadingError { err }; } } std::string ExternalModule::getActionArguments(const ActionRequest& request) { lth_jc::JsonContainer action_args {}; action_args.set<lth_jc::JsonContainer>("input", request.params()); if (!config_.empty()) action_args.set<lth_jc::JsonContainer>("configuration", config_); if (request.type() == RequestType::NonBlocking) { fs::path r_d_p { request.resultsDir() }; lth_jc::JsonContainer output_files {}; output_files.set<std::string>("stdout", (r_d_p / "stdout").string()); output_files.set<std::string>("stderr", (r_d_p / "stderr").string()); output_files.set<std::string>("exitcode", (r_d_p / "exitcode").string()); action_args.set<lth_jc::JsonContainer>("output_files", output_files); } return action_args.toString(); } ActionOutcome ExternalModule::processRequestOutcome(const ActionRequest& request, int exit_code, std::string& out_txt, std::string& err_txt) { auto action_name = request.action(); if (out_txt.empty()) { LOG_DEBUG("'%1% %2%' produced no output", module_name, action_name); } else { LOG_DEBUG("'%1% %2%' output: %3%", module_name, action_name, out_txt); } if (exit_code != EXIT_SUCCESS) { if (!err_txt.empty()) { LOG_ERROR("'%1% %2%' failure, returned %3%; error: %4%", module_name, action_name, exit_code, err_txt); } else { LOG_ERROR("'%1% %2%' failure, returned %3%", module_name, action_name, exit_code); } } else if (!err_txt.empty()) { LOG_WARNING("'%1% %2%' error: %3%", module_name, action_name, err_txt); } try { // Ensure output format is valid JSON by instantiating JsonContainer // NB: JsonContainer's ctor does not accept empty strings lth_jc::JsonContainer results { (out_txt.empty() ? "null" : out_txt) }; return ActionOutcome { exit_code, err_txt, out_txt, results }; } catch (lth_jc::data_parse_error& e) { LOG_ERROR("'%1% %2%' output is not valid JSON: %3%", module_name, action_name, e.what()); std::string err_msg { "'" + module_name + " " + action_name + "' " "returned invalid JSON" }; if (!err_txt.empty()) { err_msg += " - stderr: " + err_txt; } throw Module::ProcessingError { err_msg }; } } ActionOutcome ExternalModule::callBlockingAction(const ActionRequest& request) { auto action_name = request.action(); auto action_args = getActionArguments(request); LOG_INFO("Executing '%1% %2%' (blocking request), transaction id %3%", module_name, action_name, request.transactionId()); LOG_TRACE("Blocking request %1% input: %2%", request.transactionId(), action_args); auto exec = lth_exec::execute( #ifdef _WIN32 "cmd.exe", { "/c", path_, action_name }, #else path_, { action_name }, #endif action_args, // args std::map<std::string, std::string>(), // environment 0, // timeout { lth_exec::execution_options::merge_environment }); // options return processRequestOutcome(request, exec.exit_code, exec.output, exec.error); } ActionOutcome ExternalModule::callNonBlockingAction(const ActionRequest& request) { auto action_name = request.action(); auto input_txt = getActionArguments(request); fs::path results_dir_path { request.resultsDir() }; auto out_file = (results_dir_path / "stdout").string(); auto err_file = (results_dir_path / "stderr").string(); LOG_INFO("Starting '%1% %2%' non-blocking task (stdout and stderr will " "be stored in %3%), transaction id %4%", module_name, action_name, request.resultsDir(), request.transactionId()); LOG_TRACE("Non-blocking request %1% input: %2%", request.transactionId(), input_txt); auto exec = lth_exec::execute( #ifdef _WIN32 "cmd.exe", { "/c", path_, action_name }, #else path_, { action_name }, #endif input_txt, // input std::map<std::string, std::string>(), // environment [results_dir_path](size_t pid) { auto pid_file = (results_dir_path / "pid").string(); lth_file::atomic_write_to_file(std::to_string(pid) + "\n", pid_file); }, // pid callback 0, // timeout { lth_exec::execution_options::merge_environment }); // options if (exec.exit_code == EXTERNAL_MODULE_FILE_ERROR_EC) { LOG_DEBUG("The '%1% %2%' non-blocking task %3% failed to write its " "output on file%4%%5%", module_name, action_name, request.transactionId(), (exec.output.empty() ? "" : std::string("; output: ") + exec.output), (exec.output.empty() ? "" : std::string("; error: ") + exec.error)); throw Module::ProcessingError { "failed to write output to files" }; } // Stdout / stderr output is on file; read it std::string out_txt; std::string err_txt; readNonBlockingOutcome(request, out_file, err_file, out_txt, err_txt); return processRequestOutcome(request, exec.exit_code, out_txt, err_txt); } ActionOutcome ExternalModule::callAction(const ActionRequest& request) { if (request.type() == RequestType::Blocking) { return callBlockingAction(request); } else { // Guranteed by Configuration assert(!request.resultsDir().empty()); return callNonBlockingAction(request); } } } // namespace PXPAgent <commit_msg>(maint) Deal with meatadata parsing as done for validation<commit_after>#include <pxp-agent/external_module.hpp> #define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.external_module" #include <leatherman/logging/logging.hpp> #include <leatherman/execution/execution.hpp> #include <leatherman/file_util/file.hpp> #include <horsewhisperer/horsewhisperer.h> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <atomic> #include <memory> // shared_ptr // TODO(ale): disable assert() once we're confident with the code... // To disable assert() // #define NDEBUG #include <cassert> namespace PXPAgent { static const std::string METADATA_SCHEMA_NAME { "external_module_metadata" }; static const std::string ACTION_SCHEMA_NAME { "action_metadata" }; static const std::string METADATA_CONFIGURATION_ENTRY { "configuration" }; static const std::string METADATA_ACTIONS_ENTRY { "actions" }; static const int EXTERNAL_MODULE_FILE_ERROR_EC { 5 }; namespace fs = boost::filesystem; namespace HW = HorseWhisperer; namespace lth_exec = leatherman::execution; namespace lth_file = leatherman::file_util; // // Free functions // // Provides the module metadata validator PCPClient::Validator getMetadataValidator() { // Metadata schema PCPClient::Schema metadata_schema { METADATA_SCHEMA_NAME, PCPClient::ContentType::Json }; using T_C = PCPClient::TypeConstraint; metadata_schema.addConstraint("description", T_C::String, true); metadata_schema.addConstraint(METADATA_CONFIGURATION_ENTRY, T_C::Object, false); metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, T_C::Array, true); // 'actions' is an array of actions; define the action sub_schema PCPClient::Schema action_schema { ACTION_SCHEMA_NAME, PCPClient::ContentType::Json }; action_schema.addConstraint("description", T_C::String, false); action_schema.addConstraint("name", T_C::String, true); action_schema.addConstraint("input", T_C::Object, true); action_schema.addConstraint("results", T_C::Object, true); metadata_schema.addConstraint(METADATA_ACTIONS_ENTRY, action_schema, false); PCPClient::Validator validator {}; validator.registerSchema(metadata_schema); return validator; } // // Public interface // ExternalModule::ExternalModule(const std::string& path, const lth_jc::JsonContainer& config) : path_ { path }, config_ { config } { fs::path module_path { path }; module_name = module_path.stem().string(); auto metadata = getMetadata(); try { if (metadata.includes(METADATA_CONFIGURATION_ENTRY)) { registerConfiguration( metadata.get<lth_jc::JsonContainer>(METADATA_CONFIGURATION_ENTRY)); } else { LOG_DEBUG("Found no configuration schema for module '%1%'", module_name); } registerActions(metadata); } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata of module %1%: %2%", module_name, e.what()); std::string err { "invalid metadata of module " + module_name }; throw Module::LoadingError { err }; } } ExternalModule::ExternalModule(const std::string& path) : path_ { path }, config_ { "{}" } { fs::path module_path { path }; module_name = module_path.stem().string(); auto metadata = getMetadata(); try { registerActions(metadata); } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata of module %1%: %2%", module_name, e.what()); std::string err { "invalid metadata of module " + module_name }; throw Module::LoadingError { err }; } } void ExternalModule::validateConfiguration() { if (config_validator_.includesSchema(module_name)) { config_validator_.validate(config_, module_name); } else { LOG_DEBUG("The '%1%' configuration will not be validated; no JSON " "schema is available", module_name); } } // // Static functions // void ExternalModule::readNonBlockingOutcome(const ActionRequest& request, const std::string& out_file, const std::string& err_file, std::string& out_txt, std::string& err_txt) { if (fs::exists(err_file)) { if (!lth_file::read(err_file, err_txt)) { LOG_ERROR("Failed to read error file '%1%' of '%2% %3%'; will " "continue processing the output", err_file, request.module(), request.action()); } else { LOG_TRACE("Successfully read error file '%1%'", err_file); } } if (!fs::exists(out_file)) { LOG_DEBUG("Output file '%1%' of '%2% %3%' does not exist", out_file, request.module(), request.action()); } else if (!lth_file::read(out_file, out_txt)) { LOG_ERROR("Failed to read output file '%1%' of '%2% %3%'", out_file, request.module(), request.action()); throw Module::ProcessingError { "failed to read" }; } else if (out_txt.empty()) { LOG_TRACE("Output file '%1%' of '%2% %3%' is empty", out_file, request.module(), request.action()); } else { LOG_TRACE("Successfully read output file '%1%'", out_file); } } // // Private interface // // Metadata validator (static member) const PCPClient::Validator ExternalModule::metadata_validator_ { getMetadataValidator() }; // Retrieve and validate the module metadata const lth_jc::JsonContainer ExternalModule::getMetadata() { auto exec = #ifdef _WIN32 lth_exec::execute("cmd.exe", { "/c", path_, "metadata" }, #else lth_exec::execute(path_, { "metadata" }, #endif 0, {lth_exec::execution_options::merge_environment}); if (!exec.error.empty()) { LOG_ERROR("Failed to load the external module metadata from %1%: %2%", path_, exec.error); throw Module::LoadingError { "failed to load external module metadata" }; } lth_jc::JsonContainer metadata; try { metadata = lth_jc::JsonContainer { exec.output }; LOG_DEBUG("External module %1%: metadata is valid JSON", module_name); } catch (PCPClient::validation_error& e) { throw Module::LoadingError { std::string { "metadata is not in a valid " "JSON format: " } + e.what() }; } try { metadata_validator_.validate(metadata, METADATA_SCHEMA_NAME); LOG_DEBUG("External module %1%: metadata validation OK", module_name); } catch (PCPClient::validation_error& e) { throw Module::LoadingError { std::string { "metadata validation failure: " } + e.what() }; } return metadata; } void ExternalModule::registerConfiguration(const lth_jc::JsonContainer& config_metadata) { try { PCPClient::Schema configuration_schema { module_name, config_metadata }; LOG_DEBUG("Registering module config schema for '%1%'", module_name); config_validator_.registerSchema(configuration_schema); } catch (PCPClient::schema_error& e) { LOG_ERROR("Failed to parse the configuration schema of module '%1%': %2%", module_name, e.what()); std::string err { "invalid configuration schema of module " + module_name }; throw Module::LoadingError { err }; } } void ExternalModule::registerActions(const lth_jc::JsonContainer& metadata) { for (auto& action : metadata.get<std::vector<lth_jc::JsonContainer>>( METADATA_ACTIONS_ENTRY)) { registerAction(action); } } // Register the specified action after ensuring that the input and // output schemas are valid JSON (i.e. we can instantiate Schema). void ExternalModule::registerAction(const lth_jc::JsonContainer& action) { // NOTE(ale): name, input, and output are required action entries auto action_name = action.get<std::string>("name"); LOG_DEBUG("Validating action '%1% %2%'", module_name, action_name); try { auto input_schema_json = action.get<lth_jc::JsonContainer>("input"); PCPClient::Schema input_schema { action_name, input_schema_json }; auto results_schema_json = action.get<lth_jc::JsonContainer>("results"); PCPClient::Schema results_schema { action_name, results_schema_json }; // Metadata schemas are valid JSON; store metadata LOG_DEBUG("Action '%1% %2%' has been validated", module_name, action_name); actions.push_back(action_name); input_validator_.registerSchema(input_schema); results_validator_.registerSchema(results_schema); } catch (PCPClient::schema_error& e) { LOG_ERROR("Failed to parse metadata schemas of action '%1% %2%': %3%", module_name, action_name, e.what()); std::string err { "invalid schemas of '" + module_name + " " + action_name + "'" }; throw Module::LoadingError { err }; } catch (lth_jc::data_error& e) { LOG_ERROR("Failed to retrieve metadata schemas of action '%1% %2%': %3%", module_name, action_name, e.what()); std::string err { "invalid metadata of '" + module_name + " " + action_name + "'" }; throw Module::LoadingError { err }; } } std::string ExternalModule::getActionArguments(const ActionRequest& request) { lth_jc::JsonContainer action_args {}; action_args.set<lth_jc::JsonContainer>("input", request.params()); if (!config_.empty()) action_args.set<lth_jc::JsonContainer>("configuration", config_); if (request.type() == RequestType::NonBlocking) { fs::path r_d_p { request.resultsDir() }; lth_jc::JsonContainer output_files {}; output_files.set<std::string>("stdout", (r_d_p / "stdout").string()); output_files.set<std::string>("stderr", (r_d_p / "stderr").string()); output_files.set<std::string>("exitcode", (r_d_p / "exitcode").string()); action_args.set<lth_jc::JsonContainer>("output_files", output_files); } return action_args.toString(); } ActionOutcome ExternalModule::processRequestOutcome(const ActionRequest& request, int exit_code, std::string& out_txt, std::string& err_txt) { auto action_name = request.action(); if (out_txt.empty()) { LOG_DEBUG("'%1% %2%' produced no output", module_name, action_name); } else { LOG_DEBUG("'%1% %2%' output: %3%", module_name, action_name, out_txt); } if (exit_code != EXIT_SUCCESS) { if (!err_txt.empty()) { LOG_ERROR("'%1% %2%' failure, returned %3%; error: %4%", module_name, action_name, exit_code, err_txt); } else { LOG_ERROR("'%1% %2%' failure, returned %3%", module_name, action_name, exit_code); } } else if (!err_txt.empty()) { LOG_WARNING("'%1% %2%' error: %3%", module_name, action_name, err_txt); } try { // Ensure output format is valid JSON by instantiating JsonContainer // NB: JsonContainer's ctor does not accept empty strings lth_jc::JsonContainer results { (out_txt.empty() ? "null" : out_txt) }; return ActionOutcome { exit_code, err_txt, out_txt, results }; } catch (lth_jc::data_parse_error& e) { LOG_ERROR("'%1% %2%' output is not valid JSON: %3%", module_name, action_name, e.what()); std::string err_msg { "'" + module_name + " " + action_name + "' " "returned invalid JSON" }; if (!err_txt.empty()) { err_msg += " - stderr: " + err_txt; } throw Module::ProcessingError { err_msg }; } } ActionOutcome ExternalModule::callBlockingAction(const ActionRequest& request) { auto action_name = request.action(); auto action_args = getActionArguments(request); LOG_INFO("Executing '%1% %2%' (blocking request), transaction id %3%", module_name, action_name, request.transactionId()); LOG_TRACE("Blocking request %1% input: %2%", request.transactionId(), action_args); auto exec = lth_exec::execute( #ifdef _WIN32 "cmd.exe", { "/c", path_, action_name }, #else path_, { action_name }, #endif action_args, // args std::map<std::string, std::string>(), // environment 0, // timeout { lth_exec::execution_options::merge_environment }); // options return processRequestOutcome(request, exec.exit_code, exec.output, exec.error); } ActionOutcome ExternalModule::callNonBlockingAction(const ActionRequest& request) { auto action_name = request.action(); auto input_txt = getActionArguments(request); fs::path results_dir_path { request.resultsDir() }; auto out_file = (results_dir_path / "stdout").string(); auto err_file = (results_dir_path / "stderr").string(); LOG_INFO("Starting '%1% %2%' non-blocking task (stdout and stderr will " "be stored in %3%), transaction id %4%", module_name, action_name, request.resultsDir(), request.transactionId()); LOG_TRACE("Non-blocking request %1% input: %2%", request.transactionId(), input_txt); auto exec = lth_exec::execute( #ifdef _WIN32 "cmd.exe", { "/c", path_, action_name }, #else path_, { action_name }, #endif input_txt, // input std::map<std::string, std::string>(), // environment [results_dir_path](size_t pid) { auto pid_file = (results_dir_path / "pid").string(); lth_file::atomic_write_to_file(std::to_string(pid) + "\n", pid_file); }, // pid callback 0, // timeout { lth_exec::execution_options::merge_environment }); // options if (exec.exit_code == EXTERNAL_MODULE_FILE_ERROR_EC) { LOG_DEBUG("The '%1% %2%' non-blocking task %3% failed to write its " "output on file%4%%5%", module_name, action_name, request.transactionId(), (exec.output.empty() ? "" : std::string("; output: ") + exec.output), (exec.output.empty() ? "" : std::string("; error: ") + exec.error)); throw Module::ProcessingError { "failed to write output to files" }; } // Stdout / stderr output is on file; read it std::string out_txt; std::string err_txt; readNonBlockingOutcome(request, out_file, err_file, out_txt, err_txt); return processRequestOutcome(request, exec.exit_code, out_txt, err_txt); } ActionOutcome ExternalModule::callAction(const ActionRequest& request) { if (request.type() == RequestType::Blocking) { return callBlockingAction(request); } else { // Guranteed by Configuration assert(!request.resultsDir().empty()); return callNonBlockingAction(request); } } } // namespace PXPAgent <|endoftext|>
<commit_before>#ifndef ITER_DROPWHILE_H_ #define ITER_DROPWHILE_H_ #include <iterbase.hpp> #include <utility> #include <iterator> #include <initializer_list> namespace iter { template <typename FilterFunc, typename Container> class DropWhile; template <typename FilterFunc, typename Container> DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container&&); template <typename FilterFunc, typename T> DropWhile<FilterFunc, std::initializer_list<T>> dropwhile( FilterFunc, std::initializer_list<T>); template <typename FilterFunc, typename Container> class DropWhile { private: Container container; FilterFunc filter_func; friend DropWhile dropwhile<FilterFunc, Container>( FilterFunc, Container&&); template <typename FF, typename T> friend DropWhile<FF, std::initializer_list<T>> dropwhile( FF, std::initializer_list<T>); DropWhile(FilterFunc filter_func, Container&& container) : container(std::forward<Container>(container)), filter_func(filter_func) { } public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; DerefHolder<iterator_deref<Container>> item; FilterFunc *filter_func; void inc_sub_iter() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { this->item.reset(*this->sub_iter); } } // skip all values for which the predicate is true void skip_passes() { while (this->sub_iter != this->sub_end && (*this->filter_func)(this->item.get())) { this->inc_sub_iter(); } } public: Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end, FilterFunc& filter_func) : sub_iter{std::move(iter)}, sub_end{std::move(end)}, filter_func(&filter_func) { if (this->sub_iter != this->sub_end) { this->item.reset(*this->sub_iter); } this->skip_passes(); } iterator_deref<Container> operator*() { return this->item.pull(); } Iterator& operator++() { this->inc_sub_iter(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->filter_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->filter_func}; } }; template <typename FilterFunc, typename Container> DropWhile<FilterFunc, Container> dropwhile( FilterFunc filter_func, Container&& container) { return {filter_func, std::forward<Container>(container)}; } template <typename FilterFunc, typename T> DropWhile<FilterFunc, std::initializer_list<T>> dropwhile( FilterFunc filter_func, std::initializer_list<T> il) { return {filter_func, std::move(il)}; } } #endif <commit_msg>replaces <> with "" for include of iterbase<commit_after>#ifndef ITER_DROPWHILE_H_ #define ITER_DROPWHILE_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { template <typename FilterFunc, typename Container> class DropWhile; template <typename FilterFunc, typename Container> DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container&&); template <typename FilterFunc, typename T> DropWhile<FilterFunc, std::initializer_list<T>> dropwhile( FilterFunc, std::initializer_list<T>); template <typename FilterFunc, typename Container> class DropWhile { private: Container container; FilterFunc filter_func; friend DropWhile dropwhile<FilterFunc, Container>( FilterFunc, Container&&); template <typename FF, typename T> friend DropWhile<FF, std::initializer_list<T>> dropwhile( FF, std::initializer_list<T>); DropWhile(FilterFunc filter_func, Container&& container) : container(std::forward<Container>(container)), filter_func(filter_func) { } public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; DerefHolder<iterator_deref<Container>> item; FilterFunc *filter_func; void inc_sub_iter() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { this->item.reset(*this->sub_iter); } } // skip all values for which the predicate is true void skip_passes() { while (this->sub_iter != this->sub_end && (*this->filter_func)(this->item.get())) { this->inc_sub_iter(); } } public: Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end, FilterFunc& filter_func) : sub_iter{std::move(iter)}, sub_end{std::move(end)}, filter_func(&filter_func) { if (this->sub_iter != this->sub_end) { this->item.reset(*this->sub_iter); } this->skip_passes(); } iterator_deref<Container> operator*() { return this->item.pull(); } Iterator& operator++() { this->inc_sub_iter(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->filter_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->filter_func}; } }; template <typename FilterFunc, typename Container> DropWhile<FilterFunc, Container> dropwhile( FilterFunc filter_func, Container&& container) { return {filter_func, std::forward<Container>(container)}; } template <typename FilterFunc, typename T> DropWhile<FilterFunc, std::initializer_list<T>> dropwhile( FilterFunc filter_func, std::initializer_list<T> il) { return {filter_func, std::move(il)}; } } #endif <|endoftext|>
<commit_before>#include "bbmh.h" #include "hll.h" using namespace sketch; using namespace common; using namespace mh; #ifndef SIMPLE_HASH #define SIMPLE_HASH 1 #endif int main() { static_assert(sizeof(schism::Schismatic<int32_t>) == sizeof(schism::Schismatic<uint32_t>), "wrong size!"); { BBitMinHasher<uint64_t> b1(10, 4), b2(10, 4); b1.addh(1); b1.addh(4); b1.addh(137); b2.addh(1); b2.addh(4); b2.addh(17); auto f1 = b1.cfinalize(), f2 = b2.cfinalize(); std::fprintf(stderr, "f1 popcount: %" PRIu64 "\n", f1.popcnt()); std::fprintf(stderr, "f2 popcount: %" PRIu64 "\n", f2.popcnt()); b1.show(); b2.show(); auto b3 = b1 + b2; b3.show(); auto f3 = b3.finalize(); std::fprintf(stderr, "f3 popcount: %" PRIu64 "\n", f3.popcnt()); auto neqb12 = f1.equal_bblocks(f2); std::fprintf(stderr, "eqb: %zu. With itself: %zu\n", size_t(neqb12), size_t(f1.equal_bblocks(f1))); } for(size_t i = 7; i <= 14; i += 2) { for(const auto b: {7u, 13u, 14u, 17u, 9u}) { std::fprintf(stderr, "b: %u. i: %zu\n", b, i); SuperMinHash<policy::SizePow2Policy> smhp2(1 << i); SuperMinHash<policy::SizeDivPolicy> smhdp(1 << i); SuperMinHash<policy::SizePow2Policy> smhp21(1 << i); SuperMinHash<policy::SizeDivPolicy> smhdp1(1 << i); hll::hll_t h1(i), h2(i); uint64_t seed = h1.hash(h1.hash(i) ^ h1.hash(b)); #if SIMPLE_HASH using HasherType = hash::WangHash; #else using HasherType = hash::MultiplyAddXoRotNVec<33>; #endif BBitMinHasher<uint64_t, HasherType> b1(i, b, 1, seed), b2(i, b, 1, seed), b3(i, b, 1, seed); size_t dbval = 1.5 * (size_t(1) << i); DivBBitMinHasher<uint64_t> db1(dbval, b), db2(dbval, b), db3(dbval, b); //DivBBitMinHasher<uint64_t> fb(i, b); CountingBBitMinHasher<uint64_t, uint32_t> cb1(i, b), cb2(i, b), cb3(i, b); DefaultRNGType gen(137 + (i * b)); size_t shared = 0, b1c = 0, b2c = 0; constexpr size_t niter = 5000000; for(size_t i = niter; --i;) { #if SIMPLE_HASH auto v = i; #else auto v = gen(); #endif switch(v & 0x3uL) { case 0: case 1: h1.addh(v); h2.addh(v); b2.addh(v); b1.addh(v); ++shared; b3.addh(v); db1.addh(v); db2.addh(v); smhp2.addh(v); smhp21.addh(v); smhdp.addh(v); smhdp1.addh(v); /*fb.addh(v);*/ break; case 2: h1.addh(v); b1.addh(v); ++b1c; b3.addh(v); cb3.addh(v); db1.addh(v); smhp2.addh(v); smhdp.addh(v); break; case 3: h2.addh(v); b2.addh(v); ++b2c; cb1.addh(v); db2.addh(v); smhdp1.addh(v); smhp21.addh(v); break; } //if(i % 250000 == 0) std::fprintf(stderr, "%zu iterations left\n", size_t(i)); } b1.densify(); b2.densify(); auto f1 = b1.finalize(), f2 = b2.finalize(), f3 = b3.finalize(); auto est = (b1 + b2).cardinality_estimate(); assert((b1 + b2).cardinality_estimate() == b1.union_size(b2)); assert(i <= 9 || std::abs(est - niter < niter * 5 / 100.) || !std::fprintf(stderr, "est: %lf\n", est)); //b1 += b2; auto f12 = b1.finalize(); auto fdb1 = db1.finalize(); auto fdb2 = db2.finalize(); auto smh1 = smhp2.finalize(16), smh2 = smhp21.finalize(16); auto smhd1 = smhdp.finalize(16), smhd2 = smhdp1.finalize(16); assert(smh1.jaccard_index(smh1) == 1.); std::fprintf(stderr, "estimate: %f\n", smh1.jaccard_index(smh2)); assert(std::abs(smh1.jaccard_index(smh2) - .5) < 0.05); std::fprintf(stderr, "with ss=%zu, smh1 and itself: %lf. 2 and 2/1 jaccard? %lf/%lf\n", size_t(1) << i, double(smh1.jaccard_index(smh1)), double(smh2.jaccard_index(smh1)), smh1.jaccard_index(smh2)); std::fprintf(stderr, "smh1 card %lf, smh2 %lf\n", smh1.est_cardinality_, smh2.est_cardinality_); std::fprintf(stderr, "with ss=%zu, smhd1 and itself: %lf. 2 and 2/1 jaccard? %lf/%lf\n", size_t(1) << i, double(smhd1.jaccard_index(smhd1)), double(smhd2.jaccard_index(smhd1)), smhd1.jaccard_index(smhd2)); std::fprintf(stderr, "Expected Cardinality [shared:%zu/b1:%zu/b2:%zu]\n", shared, b1c, b2c); std::fprintf(stderr, "h1 est %lf, h2 est: %lf\n", h1.report(), h2.report()); std::fprintf(stderr, "Estimate Harmonicard [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(HARMONIC_MEAN), b2.cardinality_estimate(HARMONIC_MEAN)); std::fprintf(stderr, "Estimate div Harmonicard [b1:%lf/b2:%lf]\n", db1.cardinality_estimate(HARMONIC_MEAN), db2.cardinality_estimate(HARMONIC_MEAN)); std::fprintf(stderr, "Estimate HLL [b1:%lf/b2:%lf/b3:%lf]\n", b1.cardinality_estimate(HLL_METHOD), b2.cardinality_estimate(HLL_METHOD), b3.cardinality_estimate(HLL_METHOD)); std::fprintf(stderr, "Estimate arithmetic mean [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(ARITHMETIC_MEAN), b2.cardinality_estimate(ARITHMETIC_MEAN)); std::fprintf(stderr, "Estimate (median) b1:%lf/b2:%lf]\n", b1.cardinality_estimate(MEDIAN), b2.cardinality_estimate(MEDIAN)); std::fprintf(stderr, "Estimate geometic mean [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(GEOMETRIC_MEAN), b2.cardinality_estimate(GEOMETRIC_MEAN)); std::fprintf(stderr, "JI for f3 and f2: %lf\n", f1.jaccard_index(f2)); std::fprintf(stderr, "JI for fdb1 and fdb2: %lf, where nmin = %zu and b = %d\n", fdb2.jaccard_index(fdb1), i, b); //std::fprintf(stderr, "equal blocks: %zu\n", size_t(f2.equal_bblocks(f3))); std::fprintf(stderr, "f1, f2, and f3 cardinalities: %lf, %lf, %lf\n", f1.est_cardinality_, f2.est_cardinality_, f3.est_cardinality_); auto fcb1 = cb1.finalize(), fcb2 = cb3.finalize(); //auto cb13res = fcb1.histogram_sums(fcb2); //assert(sizeof(cb13res) == sizeof(uint64_t) * 4); //std::fprintf(stderr, "cb13res %lf, %lf\n", cb13res.weighted_jaccard_index(), cb13res.jaccard_index()); cb1.finalize().write("ZOMG.cb"); decltype(cb1.finalize()) cbr("ZOMG.cb"); assert(cbr == cb1.finalize()); //cbr.histogram_sums(cb2.finalize()).print(); auto whl = b1.make_whll(); auto phl = b1.make_packed16hll(); std::fprintf(stderr, "p16 card: %lf\n", phl.cardinality_estimate()); std::fprintf(stderr, "whl card: %lf/%zu vs expected %lf/%lf/%lf\n", whl.cardinality_estimate(), whl.core_.size(), f1.est_cardinality_, h1.report(), whl.union_size(whl)); } } if(std::system("rm ZOMG.cb")) throw std::runtime_error("Failed to delete ZOMG.cb"); } <commit_msg>cleanup in bbmhtest<commit_after>#include "bbmh.h" #include "hll.h" using namespace sketch; using namespace common; using namespace mh; #ifndef SIMPLE_HASH #define SIMPLE_HASH 1 #endif template<typename T> struct scope_executor { T x_; scope_executor(T &&x): x_(std::move(x)) {} scope_executor(const T &x): x_(x) {} ~scope_executor() {x_();} }; int main() { static_assert(sizeof(schism::Schismatic<int32_t>) == sizeof(schism::Schismatic<uint32_t>), "wrong size!"); { BBitMinHasher<uint64_t> b1(10, 4), b2(10, 4); b1.addh(1); b1.addh(4); b1.addh(137); b2.addh(1); b2.addh(4); b2.addh(17); auto f1 = b1.cfinalize(), f2 = b2.cfinalize(); std::fprintf(stderr, "f1 popcount: %" PRIu64 "\n", f1.popcnt()); std::fprintf(stderr, "f2 popcount: %" PRIu64 "\n", f2.popcnt()); b1.show(); b2.show(); auto b3 = b1 + b2; b3.show(); auto f3 = b3.finalize(); std::fprintf(stderr, "f3 popcount: %" PRIu64 "\n", f3.popcnt()); auto neqb12 = f1.equal_bblocks(f2); std::fprintf(stderr, "eqb: %zu. With itself: %zu\n", size_t(neqb12), size_t(f1.equal_bblocks(f1))); } for(size_t i = 7; i <= 14; i += 2) { for(const auto b: {7u, 13u, 14u, 17u, 9u}) { std::fprintf(stderr, "b: %u. i: %zu\n", b, i); SuperMinHash<policy::SizePow2Policy> smhp2(1 << i); SuperMinHash<policy::SizeDivPolicy> smhdp(1 << i); SuperMinHash<policy::SizePow2Policy> smhp21(1 << i); SuperMinHash<policy::SizeDivPolicy> smhdp1(1 << i); hll::hll_t h1(i), h2(i); uint64_t seed = h1.hash(h1.hash(i) ^ h1.hash(b)); #if SIMPLE_HASH using HasherType = hash::WangHash; #else using HasherType = hash::MultiplyAddXoRotNVec<33>; #endif BBitMinHasher<uint64_t, HasherType> b1(i, b, 1, seed), b2(i, b, 1, seed), b3(i, b, 1, seed); size_t dbval = 1.5 * (size_t(1) << i); DivBBitMinHasher<uint64_t> db1(dbval, b), db2(dbval, b), db3(dbval, b); //DivBBitMinHasher<uint64_t> fb(i, b); CountingBBitMinHasher<uint64_t, uint32_t> cb1(i, b), cb2(i, b), cb3(i, b); DefaultRNGType gen(137 + (i * b)); size_t shared = 0, b1c = 0, b2c = 0; constexpr size_t niter = 5000000; for(size_t i = niter; --i;) { #if SIMPLE_HASH auto v = i; #else auto v = gen(); #endif switch(v & 0x3uL) { case 0: case 1: h1.addh(v); h2.addh(v); b2.addh(v); b1.addh(v); ++shared; b3.addh(v); db1.addh(v); db2.addh(v); smhp2.addh(v); smhp21.addh(v); smhdp.addh(v); smhdp1.addh(v); /*fb.addh(v);*/ break; case 2: h1.addh(v); b1.addh(v); ++b1c; b3.addh(v); cb3.addh(v); db1.addh(v); smhp2.addh(v); smhdp.addh(v); break; case 3: h2.addh(v); b2.addh(v); ++b2c; cb1.addh(v); db2.addh(v); smhdp1.addh(v); smhp21.addh(v); break; } //if(i % 250000 == 0) std::fprintf(stderr, "%zu iterations left\n", size_t(i)); } b1.densify(); b2.densify(); auto f1 = b1.finalize(), f2 = b2.finalize(), f3 = b3.finalize(); auto est = (b1 + b2).cardinality_estimate(); assert((b1 + b2).cardinality_estimate() == b1.union_size(b2)); assert(i <= 9 || std::abs(est - niter < niter * 5 / 100.) || !std::fprintf(stderr, "est: %lf\n", est)); //b1 += b2; auto f12 = b1.finalize(); auto fdb1 = db1.finalize(); auto fdb2 = db2.finalize(); auto smh1 = smhp2.finalize(16), smh2 = smhp21.finalize(16); auto smhd1 = smhdp.finalize(16), smhd2 = smhdp1.finalize(16); assert(smh1.jaccard_index(smh1) == 1.); std::fprintf(stderr, "estimate: %f\n", smh1.jaccard_index(smh2)); assert(std::abs(smh1.jaccard_index(smh2) - .5) < 0.05); std::fprintf(stderr, "with ss=%zu, smh1 and itself: %lf. 2 and 2/1 jaccard? %lf/%lf\n", size_t(1) << i, double(smh1.jaccard_index(smh1)), double(smh2.jaccard_index(smh1)), smh1.jaccard_index(smh2)); std::fprintf(stderr, "smh1 card %lf, smh2 %lf\n", smh1.est_cardinality_, smh2.est_cardinality_); std::fprintf(stderr, "with ss=%zu, smhd1 and itself: %lf. 2 and 2/1 jaccard? %lf/%lf\n", size_t(1) << i, double(smhd1.jaccard_index(smhd1)), double(smhd2.jaccard_index(smhd1)), smhd1.jaccard_index(smhd2)); std::fprintf(stderr, "Expected Cardinality [shared:%zu/b1:%zu/b2:%zu]\n", shared, b1c, b2c); std::fprintf(stderr, "h1 est %lf, h2 est: %lf\n", h1.report(), h2.report()); std::fprintf(stderr, "Estimate Harmonicard [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(HARMONIC_MEAN), b2.cardinality_estimate(HARMONIC_MEAN)); std::fprintf(stderr, "Estimate div Harmonicard [b1:%lf/b2:%lf]\n", db1.cardinality_estimate(HARMONIC_MEAN), db2.cardinality_estimate(HARMONIC_MEAN)); std::fprintf(stderr, "Estimate HLL [b1:%lf/b2:%lf/b3:%lf]\n", b1.cardinality_estimate(HLL_METHOD), b2.cardinality_estimate(HLL_METHOD), b3.cardinality_estimate(HLL_METHOD)); std::fprintf(stderr, "Estimate arithmetic mean [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(ARITHMETIC_MEAN), b2.cardinality_estimate(ARITHMETIC_MEAN)); std::fprintf(stderr, "Estimate (median) b1:%lf/b2:%lf]\n", b1.cardinality_estimate(MEDIAN), b2.cardinality_estimate(MEDIAN)); std::fprintf(stderr, "Estimate geometic mean [b1:%lf/b2:%lf]\n", b1.cardinality_estimate(GEOMETRIC_MEAN), b2.cardinality_estimate(GEOMETRIC_MEAN)); std::fprintf(stderr, "JI for f3 and f2: %lf\n", f1.jaccard_index(f2)); std::fprintf(stderr, "JI for fdb1 and fdb2: %lf, where nmin = %zu and b = %d\n", fdb2.jaccard_index(fdb1), i, b); //std::fprintf(stderr, "equal blocks: %zu\n", size_t(f2.equal_bblocks(f3))); std::fprintf(stderr, "f1, f2, and f3 cardinalities: %lf, %lf, %lf\n", f1.est_cardinality_, f2.est_cardinality_, f3.est_cardinality_); auto fcb1 = cb1.finalize(), fcb2 = cb3.finalize(); //auto cb13res = fcb1.histogram_sums(fcb2); //assert(sizeof(cb13res) == sizeof(uint64_t) * 4); //std::fprintf(stderr, "cb13res %lf, %lf\n", cb13res.weighted_jaccard_index(), cb13res.jaccard_index()); cb1.finalize().write("ZOMG.cb"); decltype(cb1.finalize()) cbr("ZOMG.cb"); auto deleter = []() {if(std::system("rm ZOMG.cb")) throw std::runtime_error("Failed to delete ZOMG.cb");}; scope_executor<decltype(deleter)> se(deleter); assert(cbr == cb1.finalize()); //cbr.histogram_sums(cb2.finalize()).print(); auto whl = b1.make_whll(); auto phl = b1.make_packed16hll(); std::fprintf(stderr, "p16 card: %lf\n", phl.cardinality_estimate()); std::fprintf(stderr, "whl card: %lf/%zu vs expected %lf/%lf/%lf\n", whl.cardinality_estimate(), whl.core_.size(), f1.est_cardinality_, h1.report(), whl.union_size(whl)); } } } <|endoftext|>
<commit_before><commit_msg>Not freeing the cached request data when we get OnHttpEquiv(done==TRUE) and the browser is tagged for CF navigation. I found that if I load a CF page, then go to the address bar and press enter, we will actually get both OnHttpEquiv(done==false) and then followed by OnHttpEquiv(done==TRUE) even though we kicked off a new navigation in between. When this happened we would clear the cache in OnHttpEquiv(done==true) and subsequently we'd have to go to the network to fetch the content once CF is instantiated.<commit_after><|endoftext|>
<commit_before>//===- IdentifierResolver.cpp - Lexical Scope Name lookup -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierResolver class, which is used for lexical // scoped lookup, based on identifier. // //===----------------------------------------------------------------------===// #include "IdentifierResolver.h" #include "clang/Basic/IdentifierTable.h" #include "clang/AST/Decl.h" #include <list> #include <vector> using namespace clang; namespace { class IdDeclInfo; /// Identifier's FETokenInfo contains a Decl pointer if lower bit == 0. static inline bool isDeclPtr(void *Ptr) { return (reinterpret_cast<uintptr_t>(Ptr) & 0x1) == 0; } /// Identifier's FETokenInfo contains a IdDeclInfo pointer if lower bit == 1. static inline IdDeclInfo *toIdDeclInfo(void *Ptr) { return reinterpret_cast<IdDeclInfo*>( reinterpret_cast<uintptr_t>(Ptr) & ~0x1 ); } /// IdDeclInfo - Keeps track of information about decls associated to a /// particular identifier. IdDeclInfos are lazily constructed and assigned /// to an identifier the first time a decl with that identifier is shadowed /// in some scope. class IdDeclInfo { typedef llvm::SmallVector<NamedDecl *, 2> ShadowedTy; ShadowedTy ShadowedDecls; public: typedef ShadowedTy::iterator ShadowedIter; inline ShadowedIter shadowed_begin() { return ShadowedDecls.begin(); } inline ShadowedIter shadowed_end() { return ShadowedDecls.end(); } /// Add a decl in the scope chain. void PushShadowed(NamedDecl *D) { assert(D && "Decl null"); ShadowedDecls.push_back(D); } /// Add the decl at the top of scope chain. void PushGlobalShadowed(NamedDecl *D) { assert(D && "Decl null"); ShadowedDecls.insert(ShadowedDecls.begin(), D); } /// RemoveShadowed - Remove the decl from the scope chain. /// The decl must already be part of the decl chain. void RemoveShadowed(NamedDecl *D); }; } // end anonymous namespace /// IdDeclInfoMap - Associates IdDeclInfos with Identifiers. /// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each /// individual IdDeclInfo to heap. class IdentifierResolver::IdDeclInfoMap { static const unsigned int VECTOR_SIZE = 512; // Holds vectors of IdDeclInfos that serve as 'pools'. // New vectors are added when the current one is full. std::list< std::vector<IdDeclInfo> > IDIVecs; unsigned int CurIndex; public: IdDeclInfoMap() : CurIndex(VECTOR_SIZE) {} /// Returns the IdDeclInfo associated to the IdentifierInfo. /// It creates a new IdDeclInfo if one was not created before for this id. IdDeclInfo &operator[](IdentifierInfo *II); }; IdentifierResolver::IdentifierResolver() : IdDeclInfos(*new IdDeclInfoMap) {} IdentifierResolver::~IdentifierResolver() { delete &IdDeclInfos; } /// AddDecl - Link the decl to its shadowed decl chain. void IdentifierResolver::AddDecl(NamedDecl *D, Scope *S) { assert(D && S && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) { II->setFETokenInfo(D); return; } IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { II->setFETokenInfo(NULL); IDI = &IdDeclInfos[II]; IDI->PushShadowed(static_cast<NamedDecl*>(Ptr)); } else IDI = toIdDeclInfo(Ptr); IDI->PushShadowed(D); } /// AddGlobalDecl - Link the decl at the top of the shadowed decl chain. void IdentifierResolver::AddGlobalDecl(NamedDecl *D) { assert(D && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) { II->setFETokenInfo(D); return; } IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { II->setFETokenInfo(NULL); IDI = &IdDeclInfos[II]; IDI->PushShadowed(static_cast<NamedDecl*>(Ptr)); } else IDI = toIdDeclInfo(Ptr); IDI->PushGlobalShadowed(D); } /// RemoveDecl - Unlink the decl from its shadowed decl chain. /// The decl must already be part of the decl chain. void IdentifierResolver::RemoveDecl(NamedDecl *D) { assert(D && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); assert(Ptr && "Didn't find this decl on its identifier's chain!"); if (isDeclPtr(Ptr)) { assert(D == Ptr && "Didn't find this decl on its identifier's chain!"); II->setFETokenInfo(NULL); return; } return toIdDeclInfo(Ptr)->RemoveShadowed(D); } /// Lookup - Find the non-shadowed decl that belongs to a particular /// Decl::IdentifierNamespace. NamedDecl *IdentifierResolver::Lookup(const IdentifierInfo *II, unsigned NSI) { assert(II && "null param passed"); Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI; void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) return NULL; if (isDeclPtr(Ptr)) { NamedDecl *D = static_cast<NamedDecl*>(Ptr); return (D->getIdentifierNamespace() == NS) ? D : NULL; } IdDeclInfo *IDI = toIdDeclInfo(Ptr); // ShadowedDecls are ordered from most shadowed to less shadowed. // So we do a reverse iteration from end to begin. for (IdDeclInfo::ShadowedIter SI = IDI->shadowed_end(); SI != IDI->shadowed_begin(); --SI) { NamedDecl *D = *(SI-1); if (D->getIdentifierNamespace() == NS) return D; } // we didn't find the decl. return NULL; } /// RemoveShadowed - Remove the decl from the scope chain. /// The decl must already be part of the decl chain. void IdDeclInfo::RemoveShadowed(NamedDecl *D) { assert(D && "null decl passed"); assert(ShadowedDecls.size() > 0 && "Didn't find this decl on its identifier's chain!"); // common case if (D == ShadowedDecls.back()) { ShadowedDecls.pop_back(); return; } for (ShadowedIter SI = ShadowedDecls.end()-1; SI != ShadowedDecls.begin(); --SI) { if (*(SI-1) == D) { ShadowedDecls.erase(SI-1); return; } } assert(false && "Didn't find this decl on its identifier's chain!"); } /// Returns the IdDeclInfo associated to the IdentifierInfo. /// It creates a new IdDeclInfo if one was not created before for this id. IdDeclInfo &IdentifierResolver::IdDeclInfoMap::operator[](IdentifierInfo *II) { assert (II && "null IdentifierInfo passed"); void *Ptr = II->getFETokenInfo<void>(); if (Ptr) { assert(!isDeclPtr(Ptr) && "didn't clear decl for FEToken"); return *toIdDeclInfo(Ptr); } if (CurIndex == VECTOR_SIZE) { // Add a IdDeclInfo vector 'pool' IDIVecs.resize(IDIVecs.size() + 1); // Fill the vector IDIVecs.back().resize(VECTOR_SIZE); CurIndex = 0; } IdDeclInfo *IDI = &IDIVecs.back()[CurIndex]; II->setFETokenInfo(reinterpret_cast<void*>( reinterpret_cast<uintptr_t>(IDI) | 0x1) ); ++CurIndex; return *IDI; } <commit_msg>Use std::list's push_back instead of resize to add an element.<commit_after>//===- IdentifierResolver.cpp - Lexical Scope Name lookup -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierResolver class, which is used for lexical // scoped lookup, based on identifier. // //===----------------------------------------------------------------------===// #include "IdentifierResolver.h" #include "clang/Basic/IdentifierTable.h" #include "clang/AST/Decl.h" #include <list> #include <vector> using namespace clang; namespace { class IdDeclInfo; /// Identifier's FETokenInfo contains a Decl pointer if lower bit == 0. static inline bool isDeclPtr(void *Ptr) { return (reinterpret_cast<uintptr_t>(Ptr) & 0x1) == 0; } /// Identifier's FETokenInfo contains a IdDeclInfo pointer if lower bit == 1. static inline IdDeclInfo *toIdDeclInfo(void *Ptr) { return reinterpret_cast<IdDeclInfo*>( reinterpret_cast<uintptr_t>(Ptr) & ~0x1 ); } /// IdDeclInfo - Keeps track of information about decls associated to a /// particular identifier. IdDeclInfos are lazily constructed and assigned /// to an identifier the first time a decl with that identifier is shadowed /// in some scope. class IdDeclInfo { typedef llvm::SmallVector<NamedDecl *, 2> ShadowedTy; ShadowedTy ShadowedDecls; public: typedef ShadowedTy::iterator ShadowedIter; inline ShadowedIter shadowed_begin() { return ShadowedDecls.begin(); } inline ShadowedIter shadowed_end() { return ShadowedDecls.end(); } /// Add a decl in the scope chain. void PushShadowed(NamedDecl *D) { assert(D && "Decl null"); ShadowedDecls.push_back(D); } /// Add the decl at the top of scope chain. void PushGlobalShadowed(NamedDecl *D) { assert(D && "Decl null"); ShadowedDecls.insert(ShadowedDecls.begin(), D); } /// RemoveShadowed - Remove the decl from the scope chain. /// The decl must already be part of the decl chain. void RemoveShadowed(NamedDecl *D); }; } // end anonymous namespace /// IdDeclInfoMap - Associates IdDeclInfos with Identifiers. /// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each /// individual IdDeclInfo to heap. class IdentifierResolver::IdDeclInfoMap { static const unsigned int VECTOR_SIZE = 512; // Holds vectors of IdDeclInfos that serve as 'pools'. // New vectors are added when the current one is full. std::list< std::vector<IdDeclInfo> > IDIVecs; unsigned int CurIndex; public: IdDeclInfoMap() : CurIndex(VECTOR_SIZE) {} /// Returns the IdDeclInfo associated to the IdentifierInfo. /// It creates a new IdDeclInfo if one was not created before for this id. IdDeclInfo &operator[](IdentifierInfo *II); }; IdentifierResolver::IdentifierResolver() : IdDeclInfos(*new IdDeclInfoMap) {} IdentifierResolver::~IdentifierResolver() { delete &IdDeclInfos; } /// AddDecl - Link the decl to its shadowed decl chain. void IdentifierResolver::AddDecl(NamedDecl *D, Scope *S) { assert(D && S && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) { II->setFETokenInfo(D); return; } IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { II->setFETokenInfo(NULL); IDI = &IdDeclInfos[II]; IDI->PushShadowed(static_cast<NamedDecl*>(Ptr)); } else IDI = toIdDeclInfo(Ptr); IDI->PushShadowed(D); } /// AddGlobalDecl - Link the decl at the top of the shadowed decl chain. void IdentifierResolver::AddGlobalDecl(NamedDecl *D) { assert(D && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) { II->setFETokenInfo(D); return; } IdDeclInfo *IDI; if (isDeclPtr(Ptr)) { II->setFETokenInfo(NULL); IDI = &IdDeclInfos[II]; IDI->PushShadowed(static_cast<NamedDecl*>(Ptr)); } else IDI = toIdDeclInfo(Ptr); IDI->PushGlobalShadowed(D); } /// RemoveDecl - Unlink the decl from its shadowed decl chain. /// The decl must already be part of the decl chain. void IdentifierResolver::RemoveDecl(NamedDecl *D) { assert(D && "null param passed"); IdentifierInfo *II = D->getIdentifier(); void *Ptr = II->getFETokenInfo<void>(); assert(Ptr && "Didn't find this decl on its identifier's chain!"); if (isDeclPtr(Ptr)) { assert(D == Ptr && "Didn't find this decl on its identifier's chain!"); II->setFETokenInfo(NULL); return; } return toIdDeclInfo(Ptr)->RemoveShadowed(D); } /// Lookup - Find the non-shadowed decl that belongs to a particular /// Decl::IdentifierNamespace. NamedDecl *IdentifierResolver::Lookup(const IdentifierInfo *II, unsigned NSI) { assert(II && "null param passed"); Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI; void *Ptr = II->getFETokenInfo<void>(); if (!Ptr) return NULL; if (isDeclPtr(Ptr)) { NamedDecl *D = static_cast<NamedDecl*>(Ptr); return (D->getIdentifierNamespace() == NS) ? D : NULL; } IdDeclInfo *IDI = toIdDeclInfo(Ptr); // ShadowedDecls are ordered from most shadowed to less shadowed. // So we do a reverse iteration from end to begin. for (IdDeclInfo::ShadowedIter SI = IDI->shadowed_end(); SI != IDI->shadowed_begin(); --SI) { NamedDecl *D = *(SI-1); if (D->getIdentifierNamespace() == NS) return D; } // we didn't find the decl. return NULL; } /// RemoveShadowed - Remove the decl from the scope chain. /// The decl must already be part of the decl chain. void IdDeclInfo::RemoveShadowed(NamedDecl *D) { assert(D && "null decl passed"); assert(!ShadowedDecls.empty() && "Didn't find this decl on its identifier's chain!"); // common case if (D == ShadowedDecls.back()) { ShadowedDecls.pop_back(); return; } for (ShadowedIter SI = ShadowedDecls.end()-1; SI != ShadowedDecls.begin(); --SI) { if (*(SI-1) == D) { ShadowedDecls.erase(SI-1); return; } } assert(false && "Didn't find this decl on its identifier's chain!"); } /// Returns the IdDeclInfo associated to the IdentifierInfo. /// It creates a new IdDeclInfo if one was not created before for this id. IdDeclInfo &IdentifierResolver::IdDeclInfoMap::operator[](IdentifierInfo *II) { assert (II && "null IdentifierInfo passed"); void *Ptr = II->getFETokenInfo<void>(); if (Ptr) { assert(!isDeclPtr(Ptr) && "didn't clear decl for FEToken"); return *toIdDeclInfo(Ptr); } if (CurIndex == VECTOR_SIZE) { // Add a IdDeclInfo vector 'pool' IDIVecs.push_back(std::vector<IdDeclInfo>()); // Fill the vector IDIVecs.back().resize(VECTOR_SIZE); CurIndex = 0; } IdDeclInfo *IDI = &IDIVecs.back()[CurIndex]; II->setFETokenInfo(reinterpret_cast<void*>( reinterpret_cast<uintptr_t>(IDI) | 0x1) ); ++CurIndex; return *IDI; } <|endoftext|>
<commit_before>/* Copyright (c) 2016-2019, The C++ IPFS client library developers 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 <ipfs/client.h> #include <ipfs/test/utils.h> #include <iostream> #include <sstream> #include <stdexcept> int main(int, char**) { try { ipfs::Client client("localhost", 5001); /** [ipfs::Client::FilesGet] */ std::stringstream contents; client.FilesGet( "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme", &contents); std::cout << "Retrieved contents: " << contents.str().substr(0, 8) << "..." << std::endl; /* An example output: Retrieved contents: Hello an... */ /** [ipfs::Client::FilesGet] */ ipfs::test::check_if_string_contains("client.FilesGet()", contents.str(), "Hello and Welcome to IPFS!"); /** [ipfs::Client::FilesAdd] */ ipfs::Json add_result; client.FilesAdd( {{"foo.txt", ipfs::http::FileUpload::Type::kFileContents, "abcd"}, {"bar.txt", ipfs::http::FileUpload::Type::kFileName, "../compile_commands.json"}}, &add_result); std::cout << "FilesAdd() result:" << std::endl << add_result.dump(2) << std::endl; /* An example output: [ { "path": "foo.txt", "hash": "QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", "size": 4 } { "path": "bar.txt", "hash": "QmVjQsMgtRsRKpNM8amTCDRuUPriY8tGswsTpo137jPWwL", "size": 1176 }, ] */ /** [ipfs::Client::FilesAdd] */ /** [ipfs::Client::FilesLs] */ ipfs::Json ls_result; client.FilesLs("/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", &ls_result); std::cout << "FilesLs() result:" << std::endl << ls_result.dump(2) << std::endl; /* An example output: { "Arguments": { "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG" }, "Objects": { "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG": { "Hash": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "Links": [ { "Hash": "QmZTR5bcpQD7cFgTorqxZDYaew1Wqgfbd2ud9QqGPAkK2V", "Name": "about", "Size": 1677, "Type": "File" }, ... { "Hash": "QmdncfsVm2h5Kqq9hPmU7oAVX2zTSVP3L869tgTbPYnsha", "Name": "quick-start", "Size": 1717, "Type": "File" }, ... ], "Size": 0, "Type": "Directory" } } } */ /** [ipfs::Client::FilesLs] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <commit_msg>Store code coverage to 100%<commit_after>/* Copyright (c) 2016-2020, The C++ IPFS client library developers 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 <ipfs/client.h> #include <ipfs/test/utils.h> #include <iostream> #include <sstream> #include <stdexcept> int main(int, char**) { try { // Try Files API tests with time-out setting of 20 seconds ipfs::Client client("localhost", 5001, "20s"); /** [ipfs::Client::FilesGet] */ std::stringstream contents; client.FilesGet( "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme", &contents); std::cout << "Retrieved contents: " << contents.str().substr(0, 8) << "..." << std::endl; /* An example output: Retrieved contents: Hello an... */ /** [ipfs::Client::FilesGet] */ ipfs::test::check_if_string_contains("client.FilesGet()", contents.str(), "Hello and Welcome to IPFS!"); /** [ipfs::Client::FilesAdd] */ ipfs::Json add_result; client.FilesAdd( {{"foo.txt", ipfs::http::FileUpload::Type::kFileContents, "abcd"}, {"bar.txt", ipfs::http::FileUpload::Type::kFileName, "../compile_commands.json"}}, &add_result); std::cout << "FilesAdd() result:" << std::endl << add_result.dump(2) << std::endl; /* An example output: [ { "path": "foo.txt", "hash": "QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", "size": 4 } { "path": "bar.txt", "hash": "QmVjQsMgtRsRKpNM8amTCDRuUPriY8tGswsTpo137jPWwL", "size": 1176 }, ] */ /** [ipfs::Client::FilesAdd] */ /** [ipfs::Client::FilesLs] */ ipfs::Json ls_result; client.FilesLs("/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", &ls_result); std::cout << "FilesLs() result:" << std::endl << ls_result.dump(2) << std::endl; /* An example output: { "Arguments": { "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG" }, "Objects": { "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG": { "Hash": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG", "Links": [ { "Hash": "QmZTR5bcpQD7cFgTorqxZDYaew1Wqgfbd2ud9QqGPAkK2V", "Name": "about", "Size": 1677, "Type": "File" }, ... { "Hash": "QmdncfsVm2h5Kqq9hPmU7oAVX2zTSVP3L869tgTbPYnsha", "Name": "quick-start", "Size": 1717, "Type": "File" }, ... ], "Size": 0, "Type": "Directory" } } } */ /** [ipfs::Client::FilesLs] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "rencontre.h" #include "match.h" #include "equipe.h" #include "utils.h" //----------------------------------------------------------------- Constructeur Rencontre::Rencontre(Club* home, Club* away, std::string date) : _match(CreerMatch(home,away)), _dateDeRencontre(To_Date(date)) {} //----------------------------------------------------------------- Destructeur Rencontre::~Rencontre() { delete _match; } //----------------------------------------------------------------- Constructeur de recopie Rencontre::Rencontre(const Rencontre& other) : _match(other._match), _dateDeRencontre(other._dateDeRencontre) {} //----------------------------------------------------------------- Operateur d'affectation Rencontre& Rencontre::operator=(Rencontre&& other) { _match=other._match; _dateDeRencontre=other._dateDeRencontre; return *this; } //----------------------------------------------------------------- getMatchAndGame void Rencontre::getMatchAndGame(){ std::cout << _dateDeRencontre.To_String() << "/ " << _match->getCouleurClub(_match->getLocaux()) << " vs. " << _match->getCouleurClub(_match->getVisiteurs()) << std::endl; } //----------------------------------------------------------------- methods for Add Match /* Ajout des matchs Entre des Équipes */ Match* Rencontre::CreerMatch(Club* home, Club* away) { Equipe* locaux = new Equipe(home, 18, 2, home->getEffectif()[0]); Equipe* visiteurs = new Equipe(away, 18, 2, away->getEffectif()[0]); Match* newMatch = new Match(locaux, visiteurs); return newMatch; } //----------------------------------------------------------------- methods for affichage /*double Rencontre::resultatAUneDateDonne(std::string date){ if (To_Date(date) == _dateDeRencontre)){ _match->getResultat(); } }*/ <commit_msg>Ajout du dossier<commit_after>#include "rencontre.h" #include "match.h" #include "equipe.h" #include "utils.h" //----------------------------------------------------------------- Constructeur Rencontre::Rencontre(Club* home, Club* away, std::string date) : _match(CreerMatch(home,away)), _dateDeRencontre(To_Date(date)) {} //----------------------------------------------------------------- Destructeur Rencontre::~Rencontre() { delete _match; } //----------------------------------------------------------------- Constructeur de recopie Rencontre::Rencontre(const Rencontre& other) : _match(other._match), _dateDeRencontre(other._dateDeRencontre) {} //----------------------------------------------------------------- Operateur d'affectation Rencontre& Rencontre::operator=(Rencontre&& other) { _match=other._match; _dateDeRencontre=other._dateDeRencontre; return *this; } //----------------------------------------------------------------- getMatchAndGame void Rencontre::getMatchAndGame(){ std::cout << _dateDeRencontre.To_String() << "/ " << _match->getCouleurClub(_match->getLocaux()) << " vs. " << _match->getCouleurClub(_match->getVisiteurs()) << std::endl; } //----------------------------------------------------------------- methods for Add Match /* Ajout des matchs Entre des Équipes */ Match* Rencontre::CreerMatch(Club* home, Club* away) { Equipe* locaux = new Equipe(home, 18, 2, home->getEffectif()[0]); Equipe* visiteurs = new Equipe(away, 18, 2, away->getEffectif()[0]); Match* newMatch = new Match(locaux, visiteurs); return newMatch; } //----------------------------------------------------------------- methods for affichage /*double Rencontre::resultatAUneDateDonne(std::string date){ if (To_Date(date) == _dateDeRencontre)){ _match->getResultat(); } }*/ <|endoftext|>
<commit_before>/* Copyright (c) 2014 Argent77 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 "version.h" int vers_major = 0; int vers_minor = 5; int vers_patch = 1; char vers_suffix[] = ""; char prog_name[] = "tileconv"; char author[] = "Argent77"; <commit_msg>Version 0.6<commit_after>/* Copyright (c) 2014 Argent77 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 "version.h" int vers_major = 0; int vers_minor = 6; int vers_patch = 0; char vers_suffix[] = ""; char prog_name[] = "tileconv"; char author[] = "Argent77"; <|endoftext|>
<commit_before>#include <cli/CommandLine.h> #include <stdio.h> #include <readline/readline.h> #include <readline/history.h> extern "C" char *xmalloc (size_t size); namespace cli { namespace { char * dupstr (const char * s) { char *r = xmalloc (strlen (s) + 1); strcpy (r, s); return r; } } CommandLine::CommandLine() { rl_readline_name = "AFT"; rl_attempted_completion_function = &CommandLine::CompletionCallback; } CommandLine & CommandLine::Get() { static CommandLine cmd; return cmd; } char * CommandLine::CompletionGenerator(const char *text, int state) { return state == 0? dupstr("dummy"): NULL; } char ** CommandLine::CompletionCallback(const char *text, int start, int end) { if (start == 0) return rl_completion_matches(text, &CompletionGenerator); else return NULL; } bool CommandLine::ReadLine(const std::string &prompt, std::string &input) { char *line = readline(prompt.c_str()); if (!line) return false; input.assign(line); return true; } } <commit_msg>removed xmalloc ref<commit_after>#include <cli/CommandLine.h> #include <stdio.h> #include <readline/readline.h> #include <readline/history.h> namespace cli { namespace { char * dupstr (const char * s) { char *r = strdup(s); if (!r) std::terminate(); return r; } } CommandLine::CommandLine() { rl_readline_name = "AFT"; rl_attempted_completion_function = &CommandLine::CompletionCallback; } CommandLine & CommandLine::Get() { static CommandLine cmd; return cmd; } char * CommandLine::CompletionGenerator(const char *text, int state) { return state == 0? dupstr("dummy"): NULL; } char ** CommandLine::CompletionCallback(const char *text, int start, int end) { if (start == 0) return rl_completion_matches(text, &CompletionGenerator); else return NULL; } bool CommandLine::ReadLine(const std::string &prompt, std::string &input) { char *line = readline(prompt.c_str()); if (!line) return false; input.assign(line); return true; } } <|endoftext|>
<commit_before>#include "ruby.h" #include "grammar.hpp" #include "symbols.hpp" #ifdef __cplusplus extern "C" { #endif VALUE melbourne_string_to_ast(VALUE self, VALUE source, VALUE name, VALUE line) { bstring b_str = blk2bstr(RSTRING_PTR(source), RSTRING_LEN(source)); VALUE result = melbourne::string_to_ast(self, RSTRING_PTR(name), b_str, FIX2INT(line)); bdestroy(b_str); return result; } VALUE melbourne_file_to_ast(VALUE self, VALUE fname, VALUE start) { FILE *file = fopen(RSTRING_PTR(fname), "r"); if(file) { VALUE result = melbourne::file_to_ast(self, RSTRING_PTR(fname), file, FIX2INT(start)); fclose(file); return result; } else { rb_raise(rb_eLoadError, "no such file to load -- %s", RSTRING_PTR(fname)); } } void Init_melbourne(void) { VALUE rb_cMelbourne; melbourne::init_symbols(); #ifndef RUBINIUS VALUE rb_mRubinius = rb_const_get(rb_cObject, rb_intern("Rubinius")); #endif rb_cMelbourne = rb_define_class_under(rb_mRubinius, "Melbourne", rb_cObject); rb_define_method(rb_cMelbourne, "string_to_ast", RUBY_METHOD_FUNC(melbourne_string_to_ast), 3); rb_define_method(rb_cMelbourne, "file_to_ast", RUBY_METHOD_FUNC(melbourne_file_to_ast), 2); } #ifdef __cplusplus } /* extern "C" { */ #endif <commit_msg>Make sure the arguments are Strings. @bugfix<commit_after>#include "ruby.h" #include "grammar.hpp" #include "symbols.hpp" #ifdef __cplusplus extern "C" { #endif VALUE melbourne_string_to_ast(VALUE self, VALUE source, VALUE name, VALUE line) { StringValue(source); StringValue(name); bstring b_str = blk2bstr(RSTRING_PTR(source), RSTRING_LEN(source)); VALUE result = melbourne::string_to_ast(self, RSTRING_PTR(name), b_str, FIX2INT(line)); bdestroy(b_str); return result; } VALUE melbourne_file_to_ast(VALUE self, VALUE fname, VALUE start) { StringValue(fname); FILE *file = fopen(RSTRING_PTR(fname), "r"); if(file) { VALUE result = melbourne::file_to_ast(self, RSTRING_PTR(fname), file, FIX2INT(start)); fclose(file); return result; } else { rb_raise(rb_eLoadError, "no such file to load -- %s", RSTRING_PTR(fname)); } } void Init_melbourne(void) { VALUE rb_cMelbourne; melbourne::init_symbols(); #ifndef RUBINIUS VALUE rb_mRubinius = rb_const_get(rb_cObject, rb_intern("Rubinius")); #endif rb_cMelbourne = rb_define_class_under(rb_mRubinius, "Melbourne", rb_cObject); rb_define_method(rb_cMelbourne, "string_to_ast", RUBY_METHOD_FUNC(melbourne_string_to_ast), 3); rb_define_method(rb_cMelbourne, "file_to_ast", RUBY_METHOD_FUNC(melbourne_file_to_ast), 2); } #ifdef __cplusplus } /* extern "C" { */ #endif <|endoftext|>
<commit_before>#pragma once #include <tudocomp/Algorithm.hpp> #include <tudocomp/util/Hash.hpp> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> namespace tdc { namespace lz78 { template< typename HashRoller = ZBackupRollingHash, typename HashProber = LinearProber, typename HashManager = SizeManagerPrime, typename HashFunction = NoopHasher > class RollingTrie : public Algorithm, public LZ78Trie<factorid_t> { typedef typename HashRoller::key_type key_type; HashRoller m_roller; HashMap<key_type, factorid_t, undef_id, HashFunction, std::equal_to<key_type>, HashProber, HashManager> m_table; key_type hash_node(uliteral_t c) { m_roller += c; return m_roller(); } public: inline static Meta meta() { Meta m("lz78trie", "rolling", "Rolling Hash Trie"); m.option("hash_roller").templated<HashRoller, ZBackupRollingHash>("hash_roller"); m.option("hash_prober").templated<HashProber, LinearProber>("hash_prober"); m.option("hash_manager").templated<HashManager, SizeManagerPrime>("hash_manager"); m.option("load_factor").dynamic(30); m.option("hash_function").templated<HashFunction, NoopHasher>("hash_function"); return m; } RollingTrie(Env&& env, const size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) , m_roller(this->env().env_for_option("hash_roller")) , m_table(this->env(), n, remaining_characters) { m_table.max_load_factor(this->env().option("load_factor").as_integer()/100.0f ); if(reserve > 0) { m_table.reserve(reserve); } } IF_STATS( MoveGuard m_guard; inline ~RollingTrie() { if (m_guard) { m_table.collect_stats(env()); } } ) RollingTrie(RollingTrie&& other) = default; RollingTrie& operator=(RollingTrie&& other) = default; node_t add_rootnode(uliteral_t c) override { m_table.insert(std::make_pair<key_type,factorid_t>(hash_node(c), size())); m_roller.clear(); return size() - 1; } node_t get_rootnode(uliteral_t c) override { hash_node(c); return c; } void clear() override { // m_table.clear(); } node_t find_or_insert(const node_t&, uliteral_t c) override { const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary auto ret = m_table.insert(std::make_pair(hash_node(c), newleaf_id)); if(ret.second) { m_roller.clear(); return undef_id; // added a new node } return ret.first.value(); } factorid_t size() const override { return m_table.entries(); } }; }} //ns <commit_msg>adjust RollingTrie to non-virtual<commit_after>#pragma once #include <tudocomp/Algorithm.hpp> #include <tudocomp/util/Hash.hpp> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> namespace tdc { namespace lz78 { template< typename HashRoller = ZBackupRollingHash, typename HashProber = LinearProber, typename HashManager = SizeManagerPrime, typename HashFunction = NoopHasher > class RollingTrie : public Algorithm, public LZ78Trie<factorid_t> { typedef typename HashRoller::key_type key_type; HashRoller m_roller; HashMap<key_type, factorid_t, undef_id, HashFunction, std::equal_to<key_type>, HashProber, HashManager> m_table; key_type hash_node(uliteral_t c) { m_roller += c; return m_roller(); } public: inline static Meta meta() { Meta m("lz78trie", "rolling", "Rolling Hash Trie"); m.option("hash_roller").templated<HashRoller, ZBackupRollingHash>("hash_roller"); m.option("hash_prober").templated<HashProber, LinearProber>("hash_prober"); m.option("hash_manager").templated<HashManager, SizeManagerPrime>("hash_manager"); m.option("load_factor").dynamic(30); m.option("hash_function").templated<HashFunction, NoopHasher>("hash_function"); return m; } inline RollingTrie(Env&& env, const size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) , m_roller(this->env().env_for_option("hash_roller")) , m_table(this->env(), n, remaining_characters) { m_table.max_load_factor(this->env().option("load_factor").as_integer()/100.0f ); if(reserve > 0) { m_table.reserve(reserve); } } IF_STATS( MoveGuard m_guard; inline ~RollingTrie() { if (m_guard) { m_table.collect_stats(env()); } } ) RollingTrie(RollingTrie&& other) = default; RollingTrie& operator=(RollingTrie&& other) = default; inline node_t add_rootnode(uliteral_t c) { m_table.insert(std::make_pair<key_type,factorid_t>(hash_node(c), size())); m_roller.clear(); return size() - 1; } inline node_t get_rootnode(uliteral_t c) { hash_node(c); return c; } inline void clear() { // m_table.clear(); } inline node_t find_or_insert(const node_t&, uliteral_t c) { const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary auto ret = m_table.insert(std::make_pair(hash_node(c), newleaf_id)); if(ret.second) { m_roller.clear(); return undef_id; // added a new node } return ret.first.value(); } inline factorid_t size() const { return m_table.entries(); } }; }} //ns <|endoftext|>
<commit_before>#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> #include <QtCore/QSocketNotifier> #include <QtCore/QTimer> #include <QtCore/QThread> #include <QtCore/QWaitCondition> #include "virtualserialdevice.h" namespace SymbianUtils { class VirtualSerialDevicePrivate { public: int portHandle; QSocketNotifier* readNotifier; QSocketNotifier* writeUnblockedNotifier; }; void VirtualSerialDevice::platInit() { d = new VirtualSerialDevicePrivate; d->portHandle = -1; d->readNotifier = NULL; d->writeUnblockedNotifier = NULL; connect(this, SIGNAL(AsyncCall_emitBytesWrittenIfNeeded(qint64)), this, SIGNAL(bytesWritten(qint64)), Qt::QueuedConnection); } bool VirtualSerialDevice::open(OpenMode mode) { if (isOpen()) return true; d->portHandle = ::open(portName.toAscii().constData(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (d->portHandle == -1) { setErrorString(QString("Posix error %1 opening %2").arg(errno).arg(portName)); return false; } struct termios termInfo; if (tcgetattr(d->portHandle, &termInfo) < 0) { setErrorString(QString::fromLatin1("Unable to retrieve terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno)))); close(); return false; } cfmakeraw(&termInfo); // Turn off terminal echo as not get messages back, among other things termInfo.c_cflag |= CREAD|CLOCAL; termInfo.c_cc[VTIME] = 0; termInfo.c_lflag &= (~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); termInfo.c_iflag &= (~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY|IXON|IXOFF)); termInfo.c_oflag &= (~OPOST); termInfo.c_cc[VMIN] = 0; termInfo.c_cc[VINTR] = _POSIX_VDISABLE; termInfo.c_cc[VQUIT] = _POSIX_VDISABLE; termInfo.c_cc[VSTART] = _POSIX_VDISABLE; termInfo.c_cc[VSTOP] = _POSIX_VDISABLE; termInfo.c_cc[VSUSP] = _POSIX_VDISABLE; if (tcsetattr(d->portHandle, TCSAFLUSH, &termInfo) < 0) { setErrorString(QString::fromLatin1("Unable to apply terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno)))); close(); return false; } d->readNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Read); connect(d->readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead())); d->writeUnblockedNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Write); d->writeUnblockedNotifier->setEnabled(false); connect(d->writeUnblockedNotifier, SIGNAL(activated(int)), this, SLOT(writeHasUnblocked(int))); bool ok = QIODevice::open(mode | QIODevice::Unbuffered); if (!ok) close(); return ok; } void VirtualSerialDevice::platClose() { delete d->readNotifier; d->readNotifier = NULL; delete d->writeUnblockedNotifier; d->writeUnblockedNotifier = NULL; ::close(d->portHandle); d->portHandle = -1; } VirtualSerialDevice::~VirtualSerialDevice() { close(); delete d; } qint64 VirtualSerialDevice::bytesAvailable() const { QMutexLocker locker(&lock); if (!isOpen()) return 0; int avail = 0; if (ioctl(d->portHandle, FIONREAD, &avail) == -1) { return 0; } return (qint64)avail + QIODevice::bytesAvailable(); } qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize) { QMutexLocker locker(&lock); int result = ::read(d->portHandle, data, maxSize); if (result == -1 && errno == EAGAIN) result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors return result; } qint64 VirtualSerialDevice::writeData(const char *data, qint64 maxSize) { QMutexLocker locker(&lock); qint64 bytesWritten; bool needToWait = tryFlushPendingBuffers(locker, EmitBytesWrittenAsync); if (!needToWait) { needToWait = tryWrite(data, maxSize, bytesWritten); if (needToWait && bytesWritten > 0) { // Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing data += bytesWritten; maxSize -= bytesWritten; } } if (needToWait) { pendingWrites.append(QByteArray(data, maxSize)); d->writeUnblockedNotifier->setEnabled(true); // Now wait for the writeUnblocked signal or for a call to waitForBytesWritten return bytesWritten + maxSize; } else { //emitBytesWrittenIfNeeded(locker, bytesWritten); // Can't emit bytesWritten directly from writeData - means clients end up recursing emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten); return bytesWritten; } } /* Returns true if EAGAIN encountered. * if error occurred (other than EAGAIN) returns -1 in bytesWritten * lock must be held. Doesn't emit signals or set notifiers. */ bool VirtualSerialDevice::tryWrite(const char *data, qint64 maxSize, qint64& bytesWritten) { // Must be locked bytesWritten = 0; while (maxSize > 0) { int result = ::write(d->portHandle, data, maxSize); if (result == -1) { if (errno == EAGAIN) return true; // Need to wait setErrorString(QString("Posix error %1 from write to %2").arg(errno).arg(portName)); bytesWritten = -1; return false; } else { if (result == 0) qWarning("Zero bytes written to port!"); bytesWritten += result; maxSize -= result; data += result; } } return false; // If we reach here we've successfully written all the data without blocking } /* Returns true if EAGAIN encountered. Emits (or queues) bytesWritten for any buffers written. * If stopAfterWritingOneBuffer is true, return immediately if a single buffer is written, rather than * attempting to drain the whole queue. * Doesn't modify notifier. */ bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags) { while (pendingWrites.count() > 0) { // Try writing everything we've got, until we hit EAGAIN const QByteArray& data = pendingWrites[0]; qint64 bytesWritten; bool needToWait = tryWrite(data.constData(), data.size(), bytesWritten); if (needToWait) { if (bytesWritten > 0) { // We wrote some of the data, update the pending queue QByteArray remainder = data.mid(bytesWritten); pendingWrites.removeFirst(); pendingWrites.insert(0, remainder); } return needToWait; } else { pendingWrites.removeFirst(); if (flags & EmitBytesWrittenAsync) { emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten); } else { emitBytesWrittenIfNeeded(locker, bytesWritten); } if (flags & StopAfterWritingOneBuffer) return false; // Otherwise go round loop again } } return false; // no EAGAIN encountered } void VirtualSerialDevice::writeHasUnblocked(int fileHandle) { Q_ASSERT(fileHandle == d->portHandle); (void)fileHandle; // Compiler shutter-upper d->writeUnblockedNotifier->setEnabled(false); QMutexLocker locker(&lock); bool needToWait = tryFlushPendingBuffers(locker); if (needToWait) d->writeUnblockedNotifier->setEnabled(true); } // Copy of qt_safe_select from /qt/src/corelib/kernel/qeventdispatcher_unix.cpp // But without the timeout correction int safe_select(int nfds, fd_set *fdread, fd_set *fdwrite, fd_set *fdexcept, const struct timeval *orig_timeout) { if (!orig_timeout) { // no timeout -> block forever register int ret; do { ret = select(nfds, fdread, fdwrite, fdexcept, 0); } while (ret == -1 && errno == EINTR); return ret; } timeval timeout = *orig_timeout; int ret; forever { ret = ::select(nfds, fdread, fdwrite, fdexcept, &timeout); if (ret != -1 || errno != EINTR) return ret; } } bool VirtualSerialDevice::waitForBytesWritten(int msecs) { QMutexLocker locker(&lock); if (pendingWrites.count() == 0) return false; if (QThread::currentThread() != thread()) { // Wait for signal from main thread unsigned long timeout = msecs; if (msecs == -1) timeout = ULONG_MAX; if (waiterForBytesWritten == NULL) waiterForBytesWritten = new QWaitCondition; return waiterForBytesWritten->wait(&lock, timeout); } d->writeUnblockedNotifier->setEnabled(false); forever { fd_set writeSet; FD_ZERO(&writeSet); FD_SET(d->portHandle, &writeSet); struct timeval timeout; if (msecs != -1) { timeout.tv_sec = msecs / 1000; timeout.tv_usec = (msecs % 1000) * 1000; } int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout); if (ret == 0) { // Timeout return false; } else if (ret < 0) { setErrorString(QString("Posix error %1 returned from select in waitForBytesWritten").arg(errno)); return false; } else { bool needToWait = tryFlushPendingBuffers(locker, StopAfterWritingOneBuffer); if (needToWait) { // go round the select again } else { return true; } } } } void VirtualSerialDevice::flush() { while (waitForBytesWritten(-1)) { /* loop */ } tcflush(d->portHandle, TCIOFLUSH); } bool VirtualSerialDevice::waitForReadyRead(int msecs) { return QIODevice::waitForReadyRead(msecs); //TODO } } // namespace SymbianUtils <commit_msg>Add missing #include for unistd.h<commit_after>#include <stdio.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> #include <unistd.h> #include <QtCore/QSocketNotifier> #include <QtCore/QTimer> #include <QtCore/QThread> #include <QtCore/QWaitCondition> #include "virtualserialdevice.h" namespace SymbianUtils { class VirtualSerialDevicePrivate { public: int portHandle; QSocketNotifier* readNotifier; QSocketNotifier* writeUnblockedNotifier; }; void VirtualSerialDevice::platInit() { d = new VirtualSerialDevicePrivate; d->portHandle = -1; d->readNotifier = NULL; d->writeUnblockedNotifier = NULL; connect(this, SIGNAL(AsyncCall_emitBytesWrittenIfNeeded(qint64)), this, SIGNAL(bytesWritten(qint64)), Qt::QueuedConnection); } bool VirtualSerialDevice::open(OpenMode mode) { if (isOpen()) return true; d->portHandle = ::open(portName.toAscii().constData(), O_RDWR | O_NONBLOCK | O_NOCTTY); if (d->portHandle == -1) { setErrorString(QString("Posix error %1 opening %2").arg(errno).arg(portName)); return false; } struct termios termInfo; if (tcgetattr(d->portHandle, &termInfo) < 0) { setErrorString(QString::fromLatin1("Unable to retrieve terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno)))); close(); return false; } cfmakeraw(&termInfo); // Turn off terminal echo as not get messages back, among other things termInfo.c_cflag |= CREAD|CLOCAL; termInfo.c_cc[VTIME] = 0; termInfo.c_lflag &= (~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG)); termInfo.c_iflag &= (~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY|IXON|IXOFF)); termInfo.c_oflag &= (~OPOST); termInfo.c_cc[VMIN] = 0; termInfo.c_cc[VINTR] = _POSIX_VDISABLE; termInfo.c_cc[VQUIT] = _POSIX_VDISABLE; termInfo.c_cc[VSTART] = _POSIX_VDISABLE; termInfo.c_cc[VSTOP] = _POSIX_VDISABLE; termInfo.c_cc[VSUSP] = _POSIX_VDISABLE; if (tcsetattr(d->portHandle, TCSAFLUSH, &termInfo) < 0) { setErrorString(QString::fromLatin1("Unable to apply terminal settings: %1 %2").arg(errno).arg(QString::fromAscii(strerror(errno)))); close(); return false; } d->readNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Read); connect(d->readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead())); d->writeUnblockedNotifier = new QSocketNotifier(d->portHandle, QSocketNotifier::Write); d->writeUnblockedNotifier->setEnabled(false); connect(d->writeUnblockedNotifier, SIGNAL(activated(int)), this, SLOT(writeHasUnblocked(int))); bool ok = QIODevice::open(mode | QIODevice::Unbuffered); if (!ok) close(); return ok; } void VirtualSerialDevice::platClose() { delete d->readNotifier; d->readNotifier = NULL; delete d->writeUnblockedNotifier; d->writeUnblockedNotifier = NULL; ::close(d->portHandle); d->portHandle = -1; } VirtualSerialDevice::~VirtualSerialDevice() { close(); delete d; } qint64 VirtualSerialDevice::bytesAvailable() const { QMutexLocker locker(&lock); if (!isOpen()) return 0; int avail = 0; if (ioctl(d->portHandle, FIONREAD, &avail) == -1) { return 0; } return (qint64)avail + QIODevice::bytesAvailable(); } qint64 VirtualSerialDevice::readData(char *data, qint64 maxSize) { QMutexLocker locker(&lock); int result = ::read(d->portHandle, data, maxSize); if (result == -1 && errno == EAGAIN) result = 0; // To Qt, 0 here means nothing ready right now, and -1 is reserved for permanent errors return result; } qint64 VirtualSerialDevice::writeData(const char *data, qint64 maxSize) { QMutexLocker locker(&lock); qint64 bytesWritten; bool needToWait = tryFlushPendingBuffers(locker, EmitBytesWrittenAsync); if (!needToWait) { needToWait = tryWrite(data, maxSize, bytesWritten); if (needToWait && bytesWritten > 0) { // Wrote some of the buffer, adjust pointers to point to the remainder that needs queueing data += bytesWritten; maxSize -= bytesWritten; } } if (needToWait) { pendingWrites.append(QByteArray(data, maxSize)); d->writeUnblockedNotifier->setEnabled(true); // Now wait for the writeUnblocked signal or for a call to waitForBytesWritten return bytesWritten + maxSize; } else { //emitBytesWrittenIfNeeded(locker, bytesWritten); // Can't emit bytesWritten directly from writeData - means clients end up recursing emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten); return bytesWritten; } } /* Returns true if EAGAIN encountered. * if error occurred (other than EAGAIN) returns -1 in bytesWritten * lock must be held. Doesn't emit signals or set notifiers. */ bool VirtualSerialDevice::tryWrite(const char *data, qint64 maxSize, qint64& bytesWritten) { // Must be locked bytesWritten = 0; while (maxSize > 0) { int result = ::write(d->portHandle, data, maxSize); if (result == -1) { if (errno == EAGAIN) return true; // Need to wait setErrorString(QString("Posix error %1 from write to %2").arg(errno).arg(portName)); bytesWritten = -1; return false; } else { if (result == 0) qWarning("Zero bytes written to port!"); bytesWritten += result; maxSize -= result; data += result; } } return false; // If we reach here we've successfully written all the data without blocking } /* Returns true if EAGAIN encountered. Emits (or queues) bytesWritten for any buffers written. * If stopAfterWritingOneBuffer is true, return immediately if a single buffer is written, rather than * attempting to drain the whole queue. * Doesn't modify notifier. */ bool VirtualSerialDevice::tryFlushPendingBuffers(QMutexLocker& locker, FlushPendingOptions flags) { while (pendingWrites.count() > 0) { // Try writing everything we've got, until we hit EAGAIN const QByteArray& data = pendingWrites[0]; qint64 bytesWritten; bool needToWait = tryWrite(data.constData(), data.size(), bytesWritten); if (needToWait) { if (bytesWritten > 0) { // We wrote some of the data, update the pending queue QByteArray remainder = data.mid(bytesWritten); pendingWrites.removeFirst(); pendingWrites.insert(0, remainder); } return needToWait; } else { pendingWrites.removeFirst(); if (flags & EmitBytesWrittenAsync) { emit AsyncCall_emitBytesWrittenIfNeeded(bytesWritten); } else { emitBytesWrittenIfNeeded(locker, bytesWritten); } if (flags & StopAfterWritingOneBuffer) return false; // Otherwise go round loop again } } return false; // no EAGAIN encountered } void VirtualSerialDevice::writeHasUnblocked(int fileHandle) { Q_ASSERT(fileHandle == d->portHandle); (void)fileHandle; // Compiler shutter-upper d->writeUnblockedNotifier->setEnabled(false); QMutexLocker locker(&lock); bool needToWait = tryFlushPendingBuffers(locker); if (needToWait) d->writeUnblockedNotifier->setEnabled(true); } // Copy of qt_safe_select from /qt/src/corelib/kernel/qeventdispatcher_unix.cpp // But without the timeout correction int safe_select(int nfds, fd_set *fdread, fd_set *fdwrite, fd_set *fdexcept, const struct timeval *orig_timeout) { if (!orig_timeout) { // no timeout -> block forever register int ret; do { ret = select(nfds, fdread, fdwrite, fdexcept, 0); } while (ret == -1 && errno == EINTR); return ret; } timeval timeout = *orig_timeout; int ret; forever { ret = ::select(nfds, fdread, fdwrite, fdexcept, &timeout); if (ret != -1 || errno != EINTR) return ret; } } bool VirtualSerialDevice::waitForBytesWritten(int msecs) { QMutexLocker locker(&lock); if (pendingWrites.count() == 0) return false; if (QThread::currentThread() != thread()) { // Wait for signal from main thread unsigned long timeout = msecs; if (msecs == -1) timeout = ULONG_MAX; if (waiterForBytesWritten == NULL) waiterForBytesWritten = new QWaitCondition; return waiterForBytesWritten->wait(&lock, timeout); } d->writeUnblockedNotifier->setEnabled(false); forever { fd_set writeSet; FD_ZERO(&writeSet); FD_SET(d->portHandle, &writeSet); struct timeval timeout; if (msecs != -1) { timeout.tv_sec = msecs / 1000; timeout.tv_usec = (msecs % 1000) * 1000; } int ret = safe_select(d->portHandle+1, NULL, &writeSet, NULL, msecs == -1 ? NULL : &timeout); if (ret == 0) { // Timeout return false; } else if (ret < 0) { setErrorString(QString("Posix error %1 returned from select in waitForBytesWritten").arg(errno)); return false; } else { bool needToWait = tryFlushPendingBuffers(locker, StopAfterWritingOneBuffer); if (needToWait) { // go round the select again } else { return true; } } } } void VirtualSerialDevice::flush() { while (waitForBytesWritten(-1)) { /* loop */ } tcflush(d->portHandle, TCIOFLUSH); } bool VirtualSerialDevice::waitForReadyRead(int msecs) { return QIODevice::waitForReadyRead(msecs); //TODO } } // namespace SymbianUtils <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #include <functional> #include <unordered_map> #include <boost/functional/hash.hpp> #include <boost/graph/adjacency_matrix.hpp> #include "debug.hpp" #include "range.hpp" namespace detail { boost::adjacency_matrix<boost::undirectedS> typedef graph; } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; boost::hash_combine(seed, v.first); boost::hash_combine(seed, v.second); return seed; } }; } template <class Graph> class leaf_info { public: leaf_info(Graph const & T_) : T(T_) { update(); } bool is_path() const { return L.size() == 2; } std::vector<unsigned> const & leaves() const { return L; } unsigned branching(unsigned l) const { return B.at(l); } unsigned parent(unsigned x, unsigned l) const { return P.at(uintpair(l, x)); } unsigned branching_neighbor(unsigned l, unsigned x) const { return BN.at(uintpair(l, x)); } bool on_branch(unsigned l, unsigned x) const { return BN.count(uintpair(l, x)) == 0; } void update() { L.clear(); B.clear(); P.clear(); BN.clear(); for(auto v : range(vertices(T))) if(degree(v, T) == 1) { L.push_back(v); traverse(v, T); } } void traverse(unsigned l, Graph const & T) { traverse(l, l, l, T); } void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) { do { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; } while(degree(b, T) == 2); if(degree(b, T) > 2) { B[l] = b; for(auto v : range(adjacent_vertices(b, T))) if(v != a) traverse(l, v, b, v, T); } } void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) { P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; while(degree(b, T) == 2) { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; } if(degree(b, T) > 2) { for(auto v : range(adjacent_vertices(b, T))) if(v != a) traverse(l, blx, b, v, T); } } std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) { auto it = adjacent_vertices(b, T).first; return std::make_pair(b, a == *it ? *(++it) : *it); } private: Graph const& T; std::vector<unsigned> L; std::pair<unsigned, unsigned> typedef uintpair; std::unordered_map<unsigned, unsigned> B; std::unordered_map<uintpair, unsigned> P, BN; }; class prieto { public: template<class Graph, class Tree> int operator()(Graph& G, Tree& T) { //detail::graph M(num_vertices(G)); //detail::copy_edges(G, M); leaf_info<Tree> info(T); int i = -1; do { ++i; //show("tree" + std::to_string(i++) + ".dot", M, T); } while(!info.is_path() && rule2(G, T, info)); return i; } }; template <class Graph, class Tree, class LeafInfo> bool rule1(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { auto x = l1; auto y = *adjacent_vertices(l1, T).first; while(y != l2) { x = y; y = info.parent(y, l2); if(degree(x, T) > 2 && degree(y, T) > 2) { add_edge(l1, l2, T); remove_edge(x, y, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule2(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { add_edge(l1, l2, T); auto b = info.branching(l1); remove_edge(b, info.parent(b, l1), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule3(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor) { auto xl = info.parent(x, l); if(degree(xl, T) > 2) { add_edge(l, x, T); remove_edge(x, xl, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule4(Graph& G, Tree& T, LeafInfo& info) { int n = num_vertices(G); std::vector<std::vector<std::pair<int,int>>> extra(n); for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor) { auto xl = info.parent(x, l); if(degree(xl, T) == 2) extra[xl].emplace_back(l, x); } } for(int l2 : info.leaves()) for(int xl = 0; xl < n; ++xl) if(!extra[xl].empty() && edge(l2, xl, G).second) { int l, x; if(extra[xl].size() == 1 && extra[xl].begin()->first == l2) continue; std::tie(l, x) = extra[xl].begin()->first == l2 ? *(extra[xl].begin()+1) : *extra[xl].begin(); add_edge(l, x, T); remove_edge(x, xl, T); info.update(); add_edge(l2, xl, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule5(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor && !info.on_branch(l, x)) { auto bl = info.branching(l); auto blx = info.branching_neighbor(l, x); if(degree(blx, T) > 2) { add_edge(l, x, T); remove_edge(bl, blx, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule6(Graph& G, Tree& T, LeafInfo& info) { int n = num_vertices(G); std::vector<std::vector<std::pair<int,int>>> extra(n); for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor && !info.on_branch(l, x)) { auto blx = info.branching_neighbor(l, x); if(degree(blx, T) == 2) { extra[blx].emplace_back(l, x); } } } for(int l2 : info.leaves()) for(int blx = 0; blx < n; ++blx) if(!extra[blx].empty() && edge(l2, blx, G).second) { int l, x; if(extra[blx].size() == 1 && extra[blx].begin()->first == l2) continue; std::tie(l, x) = extra[blx].begin()->first == l2 ? *(extra[blx].begin()+1) : *extra[blx].begin(); add_edge(l, x, T); remove_edge(info.branching(l), blx, T); info.update(); add_edge(l2, blx, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } return false; } class lost_light { public: template <class Graph, class Tree> int operator() (Graph& G, Tree& T) { leaf_info<Tree> info(T); std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule; std::vector<rule> rules { rule2<Graph,Tree,leaf_info<Tree>>, rule3<Graph,Tree,leaf_info<Tree>>, rule4<Graph,Tree,leaf_info<Tree>>, rule5<Graph,Tree,leaf_info<Tree>>, rule6<Graph,Tree,leaf_info<Tree>>, }; int i = 0; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { ++i; applied = true; break; } } } return i; } }; class lost { public: template <class Graph, class Tree> int operator() (Graph& G, Tree& T) { leaf_info<Tree> info(T); std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule; std::vector<rule> rules { rule1<Graph,Tree,leaf_info<Tree>>, rule2<Graph,Tree,leaf_info<Tree>>, rule3<Graph,Tree,leaf_info<Tree>>, rule4<Graph,Tree,leaf_info<Tree>>, rule5<Graph,Tree,leaf_info<Tree>>, rule6<Graph,Tree,leaf_info<Tree>>, }; int i = 0; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { ++i; applied = true; break; } } } return i; } }; <commit_msg>rule 7<commit_after>// (C) 2014 Arek Olek #include <functional> #include <unordered_map> #include <boost/functional/hash.hpp> #include <boost/graph/adjacency_matrix.hpp> #include "debug.hpp" #include "range.hpp" namespace detail { boost::adjacency_matrix<boost::undirectedS> typedef graph; } namespace std { template<typename S, typename T> struct hash<pair<S, T>> { inline size_t operator()(const pair<S, T> & v) const { size_t seed = 0; boost::hash_combine(seed, v.first); boost::hash_combine(seed, v.second); return seed; } }; } template <class Graph> class leaf_info { public: leaf_info(Graph const & T_) : T(T_) { update(); } bool is_path() const { return L.size() == 2; } std::vector<unsigned> const & leaves() const { return L; } unsigned branching(unsigned l) const { return B.at(l); } unsigned parent(unsigned x, unsigned l) const { return P.at(uintpair(l, x)); } unsigned branching_neighbor(unsigned l, unsigned x) const { return BN.at(uintpair(l, x)); } bool on_branch(unsigned l, unsigned x) const { return BN.count(uintpair(l, x)) == 0; } bool is_short(unsigned l) { return parent(branching(l), l) == l; } void update() { L.clear(); B.clear(); P.clear(); BN.clear(); for(auto v : range(vertices(T))) if(degree(v, T) == 1) { L.push_back(v); traverse(v, T); } } void traverse(unsigned l, Graph const & T) { traverse(l, l, l, T); } void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) { do { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; } while(degree(b, T) == 2); if(degree(b, T) > 2) { B[l] = b; for(auto v : range(adjacent_vertices(b, T))) if(v != a) traverse(l, v, b, v, T); } } void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) { P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; while(degree(b, T) == 2) { std::tie(a, b) = next(a, b, T); P[uintpair(l, b)] = a; BN[uintpair(l, b)] = blx; } if(degree(b, T) > 2) { for(auto v : range(adjacent_vertices(b, T))) if(v != a) traverse(l, blx, b, v, T); } } std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) { auto it = adjacent_vertices(b, T).first; return std::make_pair(b, a == *it ? *(++it) : *it); } private: Graph const& T; std::vector<unsigned> L; std::pair<unsigned, unsigned> typedef uintpair; std::unordered_map<unsigned, unsigned> B; std::unordered_map<uintpair, unsigned> P, BN; }; class prieto { public: template<class Graph, class Tree> int operator()(Graph& G, Tree& T) { //detail::graph M(num_vertices(G)); //detail::copy_edges(G, M); leaf_info<Tree> info(T); int i = -1; do { ++i; //show("tree" + std::to_string(i++) + ".dot", M, T); } while(!info.is_path() && rule2(G, T, info)); return i; } }; template <class Graph, class Tree, class LeafInfo> bool rule1(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { auto x = l1; auto y = *adjacent_vertices(l1, T).first; while(y != l2) { x = y; y = info.parent(y, l2); if(degree(x, T) > 2 && degree(y, T) > 2) { add_edge(l1, l2, T); remove_edge(x, y, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule2(Graph& G, Tree& T, LeafInfo& info) { for(auto l1 : info.leaves()) for(auto l2 : info.leaves()) if(edge(l1, l2, G).second) { add_edge(l1, l2, T); auto b = info.branching(l1); remove_edge(b, info.parent(b, l1), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule3(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor) { auto xl = info.parent(x, l); if(degree(xl, T) > 2) { add_edge(l, x, T); remove_edge(x, xl, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule4(Graph& G, Tree& T, LeafInfo& info) { int n = num_vertices(G); std::vector<std::vector<std::pair<int,int>>> extra(n); for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor) { auto xl = info.parent(x, l); if(degree(xl, T) == 2) extra[xl].emplace_back(l, x); } } for(int l2 : info.leaves()) for(int xl = 0; xl < n; ++xl) if(!extra[xl].empty() && edge(l2, xl, G).second) { int l, x; if(extra[xl].size() == 1 && extra[xl].begin()->first == l2) continue; std::tie(l, x) = extra[xl].begin()->first == l2 ? *(extra[xl].begin()+1) : *extra[xl].begin(); add_edge(l, x, T); remove_edge(x, xl, T); info.update(); add_edge(l2, xl, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule5(Graph& G, Tree& T, LeafInfo& info) { for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor && !info.on_branch(l, x)) { auto bl = info.branching(l); auto blx = info.branching_neighbor(l, x); if(degree(blx, T) > 2) { add_edge(l, x, T); remove_edge(bl, blx, T); info.update(); return true; } } } return false; } template <class Graph, class Tree, class LeafInfo> bool rule6(Graph& G, Tree& T, LeafInfo& info) { int n = num_vertices(G); std::vector<std::vector<std::pair<int,int>>> extra(n); for(auto l : info.leaves()) { auto treeNeighbor = *adjacent_vertices(l, T).first; for(auto x : range(adjacent_vertices(l, G))) if(x != treeNeighbor && !info.on_branch(l, x)) { auto blx = info.branching_neighbor(l, x); if(degree(blx, T) == 2) { extra[blx].emplace_back(l, x); } } } for(int l2 : info.leaves()) for(int blx = 0; blx < n; ++blx) if(!extra[blx].empty() && edge(l2, blx, G).second) { int l, x; if(extra[blx].size() == 1 && extra[blx].begin()->first == l2) continue; std::tie(l, x) = extra[blx].begin()->first == l2 ? *(extra[blx].begin()+1) : *extra[blx].begin(); add_edge(l, x, T); remove_edge(info.branching(l), blx, T); info.update(); add_edge(l2, blx, T); auto b = info.branching(l2); remove_edge(b, info.parent(b, l2), T); info.update(); return true; } return false; } template <class Graph, class Tree, class LeafInfo> bool rule7(Graph& G, Tree& T, LeafInfo& info) { for(auto e : range(edges(T))) { auto x = source(e, T); auto y = target(e, T); for(auto l : info.leaves()) { if(info.is_short(l) && !edge(l, x, T).second && !edge(l, y, T).second && edge(l, x, G).second && edge(l, y, G).second) { add_edge(l, x, T); add_edge(l, y, T); remove_edge(x, y, T); remove_edge(l, info.branching(l), T); info.update(); return true; } } } return false; } class lost_light { public: template <class Graph, class Tree> int operator() (Graph& G, Tree& T) { leaf_info<Tree> info(T); std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule; std::vector<rule> rules { rule2<Graph,Tree,leaf_info<Tree>>, rule3<Graph,Tree,leaf_info<Tree>>, rule4<Graph,Tree,leaf_info<Tree>>, rule5<Graph,Tree,leaf_info<Tree>>, rule6<Graph,Tree,leaf_info<Tree>>, }; int i = 0; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { ++i; applied = true; break; } } } return i; } }; class lost { public: template <class Graph, class Tree> int operator() (Graph& G, Tree& T) { leaf_info<Tree> info(T); std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule; std::vector<rule> rules { rule1<Graph,Tree,leaf_info<Tree>>, rule2<Graph,Tree,leaf_info<Tree>>, rule3<Graph,Tree,leaf_info<Tree>>, rule4<Graph,Tree,leaf_info<Tree>>, rule5<Graph,Tree,leaf_info<Tree>>, rule6<Graph,Tree,leaf_info<Tree>>, rule7<Graph,Tree,leaf_info<Tree>>, }; int i = 0; bool applied = true; while(applied && !info.is_path()) { applied = false; for(auto rule : rules) { if(rule(G, T, info)) { ++i; applied = true; break; } } } return i; } }; <|endoftext|>
<commit_before>#include "utilities.hpp" #include <stdio.h> #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif using namespace cv; void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions) { if(searchFrame.x <= 0) searchFrame.x = 0; if(searchFrame.x >= videoDimensions.width-searchFrame.width) searchFrame.x = videoDimensions.width-searchFrame.width; if(searchFrame.y <= 0) searchFrame.y = 0; if(searchFrame.y >= videoDimensions.height-searchFrame.height) searchFrame.y = videoDimensions.height-searchFrame.height; } Rect createOuterFrameFromInnerFrame(const Rect &regionOfInterest,const Size &videoDimensions, int factor ) { Rect searchFrame( regionOfInterest.x-((factor*regionOfInterest.width)/2-regionOfInterest.width/2), regionOfInterest.y-((factor*regionOfInterest.height)/2-regionOfInterest.height/2), factor*regionOfInterest.width, factor*regionOfInterest.height); clampRectangleToVideoDemensions(searchFrame, videoDimensions); return searchFrame; } void DrawPoint( Mat &img,const Point &center,const Scalar &Color) { int thickness = -1; int lineType = 1; double radius = 0.5; circle( img, center, radius, Color, thickness, lineType ); } void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color) { line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y), color, 0,1); } void createNewInnerFrameFromMatchLocation(const Point &matchLoc,Rect &regionOfInterest,const Size &videoDimensions) { regionOfInterest = Rect( matchLoc.x-regionOfInterest.width/2, matchLoc.y-regionOfInterest.height/2, regionOfInterest.width, regionOfInterest.height); clampRectangleToVideoDemensions(regionOfInterest,videoDimensions); } void mouseCallBack(int event, int x, int y, int flags, void* userdata) { if ( event == EVENT_LBUTTONDOWN ) { Rect* innerFrame = (Rect*)userdata; innerFrame->x = x - innerFrame->width / 2; innerFrame->y = y - innerFrame->height / 2; } else if( event == EVENT_LBUTTONUP) { } } VideoCapture webcam(const int cameraIndex) { printf ("Successfully opened Camera with Index: %d\n",cameraIndex); return VideoCapture(cameraIndex); } VideoCapture videoFile(const std::string &videoFileName) { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { exit(-1); } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ VideoCapture videoHandle = VideoCapture(videoFileName); // open the default camera if(!videoHandle.isOpened()) // check if we succeeded { printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str()); exit(-1); }else{ printf ("Successfully loaded File: %s/%s\n", cCurrentPath,videoFileName.c_str()); } return videoHandle; } <commit_msg>searchframe can be chosen interactively<commit_after>#include "utilities.hpp" #include <stdio.h> #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif using namespace cv; void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions) { if(searchFrame.x <= 0) searchFrame.x = 0; if(searchFrame.x >= videoDimensions.width-searchFrame.width) searchFrame.x = videoDimensions.width-searchFrame.width; if(searchFrame.y <= 0) searchFrame.y = 0; if(searchFrame.y >= videoDimensions.height-searchFrame.height) searchFrame.y = videoDimensions.height-searchFrame.height; } Rect createOuterFrameFromInnerFrame(const Rect &regionOfInterest,const Size &videoDimensions, int factor ) { Rect searchFrame( regionOfInterest.x-((factor*regionOfInterest.width)/2-regionOfInterest.width/2), regionOfInterest.y-((factor*regionOfInterest.height)/2-regionOfInterest.height/2), factor*regionOfInterest.width, factor*regionOfInterest.height); clampRectangleToVideoDemensions(searchFrame, videoDimensions); return searchFrame; } void DrawPoint( Mat &img,const Point &center,const Scalar &Color) { int thickness = -1; int lineType = 1; double radius = 0.5; circle( img, center, radius, Color, thickness, lineType ); } void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color) { line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y), Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), color, 0,1); line(matrixToDrawTheRectangleIn, Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height), Point(rectangleToDraw.x,rectangleToDraw.y), color, 0,1); } void createNewInnerFrameFromMatchLocation(const Point &matchLoc,Rect &regionOfInterest,const Size &videoDimensions) { regionOfInterest = Rect( matchLoc.x-regionOfInterest.width/2, matchLoc.y-regionOfInterest.height/2, regionOfInterest.width, regionOfInterest.height); clampRectangleToVideoDemensions(regionOfInterest,videoDimensions); } Point buttonDownPosition(-1,-1); Point p1, p2; void mouseCallBack(int event, int x, int y, int flags, void* userdata) { // change size of innerFrame if ( event == EVENT_LBUTTONDOWN ) { buttonDownPosition.x = x; buttonDownPosition.y = y; p1 = Point(x,y); } if(buttonDownPosition.x != -1 && buttonDownPosition.y != -1) { Rect* innerFrame = (Rect*)userdata; if(x >= buttonDownPosition.x) { innerFrame->x = buttonDownPosition.x; innerFrame->width = std::max(1, x - buttonDownPosition.x); } else //(x < buttonDownPosition.x) { innerFrame->x = x; innerFrame->width = buttonDownPosition.x - x; } if(y >= buttonDownPosition.y) { innerFrame->y = buttonDownPosition.y; innerFrame->height = std::max(1, y - buttonDownPosition.y); } else //(y < buttonDownPosition.y) { innerFrame->y = y; innerFrame->height = buttonDownPosition.y - y; } } if( event == EVENT_LBUTTONUP) { Rect* innerFrame = (Rect*)userdata; p2 = Point(x,y); buttonDownPosition.x = -1; buttonDownPosition.y = -1; } } VideoCapture webcam(const int cameraIndex) { printf ("Successfully opened Camera with Index: %d\n",cameraIndex); return VideoCapture(cameraIndex); } VideoCapture videoFile(const std::string &videoFileName) { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { exit(-1); } cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */ VideoCapture videoHandle = VideoCapture(videoFileName); // open the default camera if(!videoHandle.isOpened()) // check if we succeeded { printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str()); exit(-1); }else{ printf ("Successfully loaded File: %s/%s\n", cCurrentPath,videoFileName.c_str()); } return videoHandle; } <|endoftext|>
<commit_before>#include <stan/mcmc/mcmc_output.hpp> #include <gtest/gtest.h> #include <cstdlib> #include <cstdio> #include <cmath> #include <boost/math/distributions/students_t.hpp> #include <stdio.h> class Models_BasicDistributions_Binormal : public ::testing::Test { protected: virtual void SetUp() { FILE *in; if(!(in = popen("make path_separator --no-print-directory", "r"))) throw std::runtime_error("\"make path_separator\" has failed."); path_separator += fgetc(in); pclose(in); model.append("models").append(path_separator); model.append("basic_distributions").append(path_separator); model.append("binormal"); output1 = model + "1.csv"; output2 = model + "2.csv"; factory.addFile(output1); factory.addFile(output2); expected_y1 = 0.0; expected_y2 = 0.0; } std::string path_separator; std::string model; std::string output1; std::string output2; stan::mcmc::mcmc_output_factory factory; double expected_y1; double expected_y2; }; TEST_F(Models_BasicDistributions_Binormal,RunModel) { std::string command; command = model; command += " --samples="; command += output1; EXPECT_EQ(0, system(command.c_str())) << "Can not execute command: " << command << std::endl; command = model; command += " --samples="; command += output2; EXPECT_EQ(0, system(command.c_str())) << "Can not execute command: " << command << std::endl; } /* TEST_F(Models_BasicDistributions_Binormal, y1) { stan::mcmc::mcmc_output y1 = factory.create("y.1"); double neff = y1.effectiveSize(); boost::math::students_t t(neff-1.0); double T = boost::math::quantile(t, 0.975); EXPECT_NEAR(expected_y1, y1.mean(), T*sqrt(y1.variance()/neff)); } TEST_F(Models_BasicDistributions_Binormal, y2) { stan::mcmc::mcmc_output y2 = factory.create("y.2"); double neff = y2.effectiveSize(); boost::math::students_t t(neff-1.0); double T = boost::math::quantile(t, 0.975); EXPECT_NEAR(expected_y2, y2.mean(), T*sqrt(y2.variance()/neff)); } */ <commit_msg>chains: removed reference to mcmc_output<commit_after>#include <gtest/gtest.h> #include <cstdlib> #include <cstdio> #include <cmath> #include <boost/math/distributions/students_t.hpp> #include <stdio.h> class Models_BasicDistributions_Binormal : public ::testing::Test { protected: virtual void SetUp() { FILE *in; if(!(in = popen("make path_separator --no-print-directory", "r"))) throw std::runtime_error("\"make path_separator\" has failed."); path_separator += fgetc(in); pclose(in); model.append("models").append(path_separator); model.append("basic_distributions").append(path_separator); model.append("binormal"); output1 = model + "1.csv"; output2 = model + "2.csv"; factory.addFile(output1); factory.addFile(output2); expected_y1 = 0.0; expected_y2 = 0.0; } std::string path_separator; std::string model; std::string output1; std::string output2; stan::mcmc::mcmc_output_factory factory; double expected_y1; double expected_y2; }; TEST_F(Models_BasicDistributions_Binormal,RunModel) { std::string command; command = model; command += " --samples="; command += output1; EXPECT_EQ(0, system(command.c_str())) << "Can not execute command: " << command << std::endl; command = model; command += " --samples="; command += output2; EXPECT_EQ(0, system(command.c_str())) << "Can not execute command: " << command << std::endl; } /* TEST_F(Models_BasicDistributions_Binormal, y1) { stan::mcmc::mcmc_output y1 = factory.create("y.1"); double neff = y1.effectiveSize(); boost::math::students_t t(neff-1.0); double T = boost::math::quantile(t, 0.975); EXPECT_NEAR(expected_y1, y1.mean(), T*sqrt(y1.variance()/neff)); } TEST_F(Models_BasicDistributions_Binormal, y2) { stan::mcmc::mcmc_output y2 = factory.create("y.2"); double neff = y2.effectiveSize(); boost::math::students_t t(neff-1.0); double T = boost::math::quantile(t, 0.975); EXPECT_NEAR(expected_y2, y2.mean(), T*sqrt(y2.variance()/neff)); } */ <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2015 Niek J. Bouman // // 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. // #ifndef REALEXPRCONV_HPP #define REALEXPRCONV_HPP // Niek J. Bouman (EPFL, 2015) // // Convenience function for (type-safe) definition of a RealExpr'ession // in a Commelec Advertisement // #include <string> #include <capnp/message.h> #include "schema.capnp.h" #include "polynomial-convenience.hpp" // some macros for repetitive stuff #define BINOP(name) struct name { \ void setOp(msg::BinaryOperation::Builder binOp) const { \ binOp.initOperation().set ## name(); \ } \ }; #define UNOP(name) struct name { \ void setOp(msg::UnaryOperation::Builder unaryOp) const { \ unaryOp.initOperation().set ## name(); \ } \ }; #define UNOPFUN(name,type) template<typename TypeA> \ Expr<UnaryOp<Expr<TypeA>,type>> name(Expr<TypeA> a) \ { \ return Expr<UnaryOp<Expr<TypeA>,type>>(a); \ } #define BINOPFUN(name,type) template<typename TypeA, typename TypeB> \ Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,type>> name(Expr<TypeA> a, Expr<TypeB> b) \ { \ return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,type>>(a,b); \ } namespace cv { // instantiate classes for unary operations UNOP(Negate) UNOP(Exp) UNOP(Sin) UNOP(Cos) UNOP(Square) UNOP(Sqrt) UNOP(Log10) UNOP(Ln) UNOP(Round) UNOP(Floor) UNOP(Ceil) UNOP(MultInv) UNOP(Abs) UNOP(Sign) // instantiate classes for binary operations BINOP(Sum) BINOP(Prod) BINOP(Pow) BINOP(Min) BINOP(Max) BINOP(LessEqThan) BINOP(GreaterThan) // define +,-,*,/ operators that bind only to RealExprBase expressions template <typename T> class Expr {}; class _Ref {}; template <> class Expr<_Ref> { // Used to refer to named RealExpr- or SetExpr-essions, for example Ref a("a") const std::string &_refname; public: Expr(const std::string &ref) : _refname(ref) {} const std::string &getName() const { return _refname; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setReference(_refname); } }; using Ref = Expr<_Ref>; class _Var {}; template <> class Expr<_Var> { // Symbolic variable, for example Var X("X") const std::string &_varname; public: Expr(const std::string &var) : _varname(var) {} const std::string &getName() const { return _varname; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setVariable(_varname); } }; using Var = Expr<_Var>; template <typename T> class _Name {}; template <typename T> class Expr<_Name<Expr<T>>> { // can be used to name a (sub-) expression const Expr<T> &_expr; const std::string &_name; public: Expr(const Ref &ref, Expr<T> ex) : _name(ref.getName()), _expr(ex) {} void build(msg::RealExpr::Builder realExpr) const { realExpr.setName(_name); _expr.build(realExpr); } }; template <typename T> Expr<_Name<Expr<T>>> name(const Ref &ref, const Expr<T> &ex) { return Expr<_Name<Expr<T>>>(ref, ex); } class _Real {}; template <> class Expr<_Real> { double _value = 0.0; public: Expr(double val) : _value(val) {} void setValue(double val) { _value = val; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setReal(_value); } }; using Real = Expr<_Real>; class _Polynomial {}; template <> class Expr<_Polynomial> { const MonomialSum& _expr; public: Expr(const MonomialSum& m) : _expr(m) {} void build(msg::RealExpr::Builder realExpr) const { buildPolynomial(realExpr.getPolynomial(), _expr); } }; using Polynomial = Expr<_Polynomial>; template <typename TypeA, typename Operation> class UnaryOp {}; template <typename T, typename Operation> class Expr<UnaryOp<Expr<T>, Operation>> : public Operation { const Expr<T> &arg; public: Expr(const Expr<T> &a) : arg(a) {} void build(msg::RealExpr::Builder realExpr) const { auto unaryop = realExpr.initUnaryOperation(); Operation::setOp(unaryop); arg.build(unaryop.initArg()); } }; // template specialization template <typename TypeA, typename TypeB, typename Operation> class BinaryOp {}; template <typename T1, typename T2, typename Operation> class Expr<BinaryOp<Expr<T1>, Expr<T2>, Operation>> : public Operation { const Expr<T1> &argA; const Expr<T2> &argB; public: Expr(const Expr<T1> &a, const Expr<T2> &b) : argA(a), argB(b) {} void build(msg::RealExpr::Builder realExpr) const { auto binop = realExpr.initBinaryOperation(); Operation::setOp(binop); argA.build(binop.initArgA()); argB.build(binop.initArgB()); } }; // instantiate convenience functions for using the unary operation classes UNOPFUN(exp,Exp) UNOPFUN(sin,Sin) UNOPFUN(cos,Sin) UNOPFUN(sqrt,Sqrt) UNOPFUN(square,Square) UNOPFUN(log10,Log10) UNOPFUN(ln,Ln) UNOPFUN(round,Round) UNOPFUN(floor,Floor) UNOPFUN(ceil,Ceil) UNOPFUN(abs,Abs) UNOPFUN(sign,Sign) // instantiate convenience functions for using the binary operation classes BINOPFUN(max,Max) BINOPFUN(min,Min) BINOPFUN(pow,Pow) // binary operators template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Sum>> operator+(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Sum>>(a,b); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,Negate>>,Sum>> operator-(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,Negate>>,Sum>>(a,Expr<UnaryOp<Expr<TypeB>,Negate>>(b)); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Prod>> operator*(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Prod>>(a,b); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,MultInv>>,Prod>> operator/(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,MultInv>>,Prod>>(a,Expr<UnaryOp<Expr<TypeB>,MultInv>>(b)); } // toplevel build function template<typename T> void buildRealExpr(msg::RealExpr::Builder realExpr,Expr<T> e) { e.build(realExpr); } } // namespace cv #endif <commit_msg>Moved from using const refs to copies in expression templates<commit_after>// The MIT License (MIT) // // Copyright (c) 2015 Niek J. Bouman // // 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. // #ifndef REALEXPRCONV_HPP #define REALEXPRCONV_HPP // Niek J. Bouman (EPFL, 2015) // // Convenience function for (type-safe) definition of a RealExpr'ession // in a Commelec Advertisement // #include <string> #include <capnp/message.h> #include "schema.capnp.h" #include "polynomial-convenience.hpp" // some macros for repetitive stuff #define BINOP(name) struct name { \ void setOp(msg::BinaryOperation::Builder binOp) const { \ binOp.initOperation().set ## name(); \ } \ }; #define UNOP(name) struct name { \ void setOp(msg::UnaryOperation::Builder unaryOp) const { \ unaryOp.initOperation().set ## name(); \ } \ }; #define UNOPFUN(name,type) template<typename TypeA> \ Expr<UnaryOp<Expr<TypeA>,type>> name(Expr<TypeA> a) \ { \ return Expr<UnaryOp<Expr<TypeA>,type>>(a); \ } #define BINOPFUN(name,type) template<typename TypeA, typename TypeB> \ Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,type>> name(Expr<TypeA> a, Expr<TypeB> b) \ { \ return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,type>>(a,b); \ } namespace cv { // instantiate classes for unary operations UNOP(Negate) UNOP(Exp) UNOP(Sin) UNOP(Cos) UNOP(Square) UNOP(Sqrt) UNOP(Log10) UNOP(Ln) UNOP(Round) UNOP(Floor) UNOP(Ceil) UNOP(MultInv) UNOP(Abs) UNOP(Sign) // instantiate classes for binary operations BINOP(Sum) BINOP(Prod) BINOP(Pow) BINOP(Min) BINOP(Max) BINOP(LessEqThan) BINOP(GreaterThan) // define +,-,*,/ operators that bind only to RealExprBase expressions template <typename T> class Expr {}; class _Ref {}; template <> class Expr<_Ref> { // Used to refer to named RealExpr- or SetExpr-essions, for example Ref a("a") const std::string _refname; public: Expr(const std::string &ref) : _refname(ref) {} const std::string &getName() const { return _refname; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setReference(_refname); } }; using Ref = Expr<_Ref>; class _Var {}; template <> class Expr<_Var> { // Symbolic variable, for example Var X("X") const std::string _varname; public: Expr(const std::string &var) : _varname(var) {} const std::string &getName() const { return _varname; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setVariable(_varname); } }; using Var = Expr<_Var>; template <typename T> class _Name {}; template <typename T> class Expr<_Name<Expr<T>>> { // can be used to name a (sub-) expression Expr<T> _expr; const std::string _name; public: Expr(const Ref &ref, const Expr<T>& ex) : _name(ref.getName()), _expr(ex) {} void build(msg::RealExpr::Builder realExpr) const { realExpr.setName(_name); _expr.build(realExpr); } }; template <typename T> Expr<_Name<Expr<T>>> name(const Ref &ref, const Expr<T> &ex) { return Expr<_Name<Expr<T>>>(ref, ex); } class _Real {}; template <> class Expr<_Real> { double _value = 0.0; public: Expr(double val) : _value(val) {} void setValue(double val) { _value = val; } void build(msg::RealExpr::Builder realExpr) const { realExpr.setReal(_value); } }; using Real = Expr<_Real>; class _Polynomial {}; template <> class Expr<_Polynomial> { MonomialSum _expr; public: Expr(const MonomialSum& m) : _expr(m) {} void build(msg::RealExpr::Builder realExpr) const { buildPolynomial(realExpr.getPolynomial(), _expr); } }; using Polynomial = Expr<_Polynomial>; template <typename TypeA, typename Operation> class UnaryOp {}; template <typename T, typename Operation> class Expr<UnaryOp<Expr<T>, Operation>> : public Operation { Expr<T> arg; public: Expr(const Expr<T> &a) : arg(a) {} void build(msg::RealExpr::Builder realExpr) const { auto unaryop = realExpr.initUnaryOperation(); Operation::setOp(unaryop); arg.build(unaryop.initArg()); } }; // template specialization template <typename TypeA, typename TypeB, typename Operation> class BinaryOp {}; template <typename T1, typename T2, typename Operation> class Expr<BinaryOp<Expr<T1>, Expr<T2>, Operation>> : public Operation { Expr<T1> argA; Expr<T2> argB; public: Expr(const Expr<T1> &a, const Expr<T2> &b) : argA(a), argB(b) {} void build(msg::RealExpr::Builder realExpr) const { auto binop = realExpr.initBinaryOperation(); Operation::setOp(binop); argA.build(binop.initArgA()); argB.build(binop.initArgB()); } }; // instantiate convenience functions for using the unary operation classes UNOPFUN(exp,Exp) UNOPFUN(sin,Sin) UNOPFUN(cos,Sin) UNOPFUN(sqrt,Sqrt) UNOPFUN(square,Square) UNOPFUN(log10,Log10) UNOPFUN(ln,Ln) UNOPFUN(round,Round) UNOPFUN(floor,Floor) UNOPFUN(ceil,Ceil) UNOPFUN(abs,Abs) UNOPFUN(sign,Sign) // instantiate convenience functions for using the binary operation classes BINOPFUN(max,Max) BINOPFUN(min,Min) BINOPFUN(pow,Pow) // binary operators template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Sum>> operator+(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Sum>>(a,b); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,Negate>>,Sum>> operator-(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,Negate>>,Sum>>(a,Expr<UnaryOp<Expr<TypeB>,Negate>>(b)); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Prod>> operator*(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<TypeB>,Prod>>(a,b); } template<typename TypeA,typename TypeB> Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,MultInv>>,Prod>> operator/(Expr<TypeA> a, Expr<TypeB> b) { return Expr<BinaryOp<Expr<TypeA>,Expr<UnaryOp<Expr<TypeB>,MultInv>>,Prod>>(a,Expr<UnaryOp<Expr<TypeB>,MultInv>>(b)); } // toplevel build function template<typename T> void buildRealExpr(msg::RealExpr::Builder realExpr,Expr<T> e) { e.build(realExpr); } } // namespace cv #endif <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> char buf[1024]; char tmp[256]; void sendWindow(int fd, unsigned baseSeqNo, const char *data, unsigned dataLen); void finalize(int fd); int main(int argc, char **argv) { if (argc != 4) fprintf(stderr, "usage: %s [receiver address] [receiver port] [input file]\n", argv[0]); int fd; if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) perror("socket() error"); struct sockaddr_in sa; bzero(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons((uint16_t) strtoul(argv[2], NULL, 10)); if (inet_pton(AF_INET, argv[1], &sa.sin_addr) <= 0) perror("inet_pton() error"); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 500000; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) perror("setsockopt() error"); if (connect(fd, (const struct sockaddr *) &sa, sizeof(sa)) < 0) perror("connect() error"); std::ifstream fs(argv[3], std::ios::in | std::ios::binary); if (!fs.is_open()) fprintf(stderr, "cannot read %s\n", argv[3]); unsigned no = 0; char data[129024]; while (fs.good()) { fs.read(data, 129024); sendWindow(fd, no, data, (unsigned) fs.gcount()); no += 128; } fs.close(); finalize(fd); return 0; } void sendWindow(int fd, unsigned baseSeqNo, const char *data, unsigned dataLen) { std::vector<unsigned> remainingPackets(128); for (unsigned i = 0; i < 128; ++i) remainingPackets[i] = i; while (true) { for (auto i = remainingPackets.begin(); i != remainingPackets.end(); ++i) { // SEQ_NO // sequence number, in text, 8 bytes sprintf(buf, "%08d", baseSeqNo + *i); // LEN // length of data, in text, 8 bytes int slen = dataLen - *i * 1008; slen = slen < 0 ? 0 : slen > 1008 ? 1008 : slen; unsigned len = (unsigned) slen; sprintf(tmp, "%08d", len); strcat(buf, tmp); // DATA // data, in binary, LEN bytes memcpy(buf + 16, data + *i * 1008, len); // send the packet, maximum 1024 bytes if (send(fd, buf, len + 16, 0) < 0) perror("send() error"); } bool done = false; while (true) { if (remainingPackets.empty()) { done = true; break; } // receive the packet, always 8 bytes if (recv(fd, buf, 8, 0) < 0) { if (errno == EWOULDBLOCK) break; else perror("recv() error"); } // ACK_NO // acknowledgement number, in text, 8 bytes buf[8] = 0; unsigned no = (unsigned) strtoul(buf, NULL, 10); if (no < baseSeqNo) continue; auto it = std::find(remainingPackets.begin(), remainingPackets.end(), no - baseSeqNo); if (it != remainingPackets.end()) remainingPackets.erase(it); } if (done) break; } } void finalize(int fd) { int count = 0; while (count < 64) { count++; // FIN // tell receiver to close, in text, 8 bytes strcpy(buf, "FFFFFFFF"); if (send(fd, buf, 8, 0) < 0) perror("send() error"); if (recv(fd, buf, 8, 0) < 0) { if (errno != EWOULDBLOCK) perror("recv() error"); continue; } // FIN_ACK // receiver got it, in text, 8 bytes strcpy(tmp, "EEEEEEEE"); if (!memcmp(buf, tmp, 8)) break; } } <commit_msg>Optimize performance.<commit_after>#include <algorithm> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> char buf[1024]; char tmp[256]; void sendWindow(int fd, unsigned baseSeqNo, const char *data, unsigned dataLen); void finalize(int fd); int main(int argc, char **argv) { if (argc != 4) fprintf(stderr, "usage: %s [receiver address] [receiver port] [input file]\n", argv[0]); int fd; if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) perror("socket() error"); struct sockaddr_in sa; bzero(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons((uint16_t) strtoul(argv[2], NULL, 10)); if (inet_pton(AF_INET, argv[1], &sa.sin_addr) <= 0) perror("inet_pton() error"); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 75000; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) perror("setsockopt() error"); if (connect(fd, (const struct sockaddr *) &sa, sizeof(sa)) < 0) perror("connect() error"); std::ifstream fs(argv[3], std::ios::in | std::ios::binary); if (!fs.is_open()) fprintf(stderr, "cannot read %s\n", argv[3]); unsigned no = 0; char data[129024]; while (fs.good()) { fs.read(data, 129024); sendWindow(fd, no, data, (unsigned) fs.gcount()); no += 128; } fs.close(); finalize(fd); return 0; } void sendWindow(int fd, unsigned baseSeqNo, const char *data, unsigned dataLen) { std::vector<unsigned> remainingPackets(128); for (unsigned i = 0; i < 128; ++i) remainingPackets[i] = i; while (true) { for (auto i = remainingPackets.begin(); i != remainingPackets.end(); ++i) { // SEQ_NO // sequence number, in text, 8 bytes sprintf(buf, "%08d", baseSeqNo + *i); // LEN // length of data, in text, 8 bytes int slen = dataLen - *i * 1008; slen = slen < 0 ? 0 : slen > 1008 ? 1008 : slen; unsigned len = (unsigned) slen; sprintf(tmp, "%08d", len); strcat(buf, tmp); // DATA // data, in binary, LEN bytes memcpy(buf + 16, data + *i * 1008, len); // send the packet, maximum 1024 bytes if (send(fd, buf, len + 16, 0) < 0) perror("send() error"); } bool done = false; while (true) { if (remainingPackets.empty()) { done = true; break; } // receive the packet, always 8 bytes if (recv(fd, buf, 8, 0) < 0) { if (errno == EWOULDBLOCK) break; else perror("recv() error"); } // ACK_NO // acknowledgement number, in text, 8 bytes buf[8] = 0; unsigned no = (unsigned) strtoul(buf, NULL, 10); if (no < baseSeqNo) continue; auto it = std::find(remainingPackets.begin(), remainingPackets.end(), no - baseSeqNo); if (it != remainingPackets.end()) remainingPackets.erase(it); } if (done) break; } } void finalize(int fd) { int count = 0; while (count < 64) { count++; // FIN // tell receiver to close, in text, 8 bytes strcpy(buf, "FFFFFFFF"); if (send(fd, buf, 8, 0) < 0) perror("send() error"); if (recv(fd, buf, 8, 0) < 0) { if (errno != EWOULDBLOCK) perror("recv() error"); continue; } // FIN_ACK // receiver got it, in text, 8 bytes strcpy(tmp, "EEEEEEEE"); if (!memcmp(buf, tmp, 8)) break; } } <|endoftext|>
<commit_before><commit_msg>Delete Mmseg.hpp<commit_after><|endoftext|>
<commit_before>#include "Model.h" #include <algorithm> #include "View.h" #include "Structure_factory.h" #include "Agent_factory.h" #include "Geometry.h" #include "Structure.h" #include "Agent.h" #include "Group.h" #include "Utility.h" #include <functional> using std::map; using std::bind; using std::pair; using std::string; using std::shared_ptr; using namespace std::placeholders; using std::for_each; Model& Model::get_instance() { static Model m; return m; } Model::Model() { time = 0; // Create the default initial structures shared_ptr<Structure> structure_R = create_structure("Rivendale", "Farm", Point(10., 10.)); shared_ptr<Structure> structure_S = create_structure("Sunnybrook", "Farm", Point(0., 30.)); shared_ptr<Structure> structure_Sh = create_structure("Shire", "Town_Hall", Point(20., 20.)); shared_ptr<Structure> structure_P = create_structure("Paduca", "Town_Hall", Point(30., 30.)); // Create the default initial agents shared_ptr<Agent> agent_P = create_agent("Pippin", "Peasant", Point(5., 10.)); shared_ptr<Agent> agent_M = create_agent("Merry", "Peasant", Point(0., 25.)); shared_ptr<Agent> agent_Z = create_agent("Zug", "Soldier", Point(20., 30.)); shared_ptr<Agent> agent_B = create_agent("Bug", "Soldier", Point(15., 20.)); shared_ptr<Agent> agent_I = create_agent("Iriel", "Archer", Point(20.,38.)); sim_object_pool = { {structure_R->get_name(), structure_R}, {structure_S->get_name(), structure_S}, {structure_Sh->get_name(), structure_Sh}, {structure_P->get_name(), structure_P}, {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; agent_pool = { {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; structure_pool = { {structure_R->get_name(), structure_R}, {structure_S->get_name(), structure_S}, {structure_Sh->get_name(), structure_Sh}, {structure_P->get_name(), structure_P} }; unit_pool = { {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; } Model::~Model() {} // is name already in use for either agent or structure? // return true if the name matches the name of an existing agent or structure bool Model::is_name_in_use(const string& name) const { return sim_object_pool.find(name) != sim_object_pool.end() || group_pool.find(name) != group_pool.end(); } // is there a structure with this name? bool Model::is_structure_present(const string& name) const { return structure_pool.find(name) != structure_pool.end(); } // add a new structure; assumes none with the same name void Model::add_structure(shared_ptr<Structure> structure_ptr) { sim_object_pool.emplace(structure_ptr->get_name(), structure_ptr); structure_pool.emplace(structure_ptr->get_name(), structure_ptr); structure_ptr->broadcast_current_state(); } // will throw Error("Structure not found!") if no structure of that name shared_ptr<Structure> Model::get_structure_ptr(const string& name) const { auto structure_iter = structure_pool.find(name); if (structure_iter == structure_pool.end()) throw Error("Structure not found!"); else return structure_iter->second; } shared_ptr<Structure> Model::get_nearest_structure_ptr(const string& name) const { shared_ptr<Structure> min_distance_structure = nullptr; shared_ptr<Agent> cur_agent = get_agent_ptr(name); for (auto& content : structure_pool) { if (!min_distance_structure) min_distance_structure = content.second; else if ( cartesian_distance(content.second->get_location(), cur_agent->get_location()) < cartesian_distance(min_distance_structure->get_location(), cur_agent->get_location()) ) { min_distance_structure = content.second; } } return min_distance_structure; } // is there an agent with this name? bool Model::is_agent_present(const string& name) const { return agent_pool.find(name) != agent_pool.end(); } // add a new agent; assumes none with the same name void Model::add_agent(shared_ptr<Agent> agent_ptr) { // update three pool together sim_object_pool.emplace(agent_ptr->get_name(), agent_ptr); agent_pool.emplace(agent_ptr->get_name(), agent_ptr); unit_pool.emplace(agent_ptr->get_name(), agent_ptr); // tell the view about the information agent_ptr->broadcast_current_state(); } // will throw Error("Agent not found!") if no agent of that name shared_ptr<Agent> Model::get_agent_ptr(const string& name) const { auto agent_iter = agent_pool.find(name); if (agent_iter == agent_pool.end()) throw Error("Agent not found!"); else return agent_iter->second; } void Model::remove_agent(const string& name) { shared_ptr<Agent> agent_ptr = get_agent_ptr(name); // error is checked sim_object_pool.erase(name); unit_pool.erase(name); agent_pool.erase(name); // remove the existence from group agent_ptr->set_parent(nullptr); } // Using a range for looks better then min_element with struct shared_ptr<Agent> Model::get_nearest_agent_ptr(const string& name) const { shared_ptr<Agent> min_distance_agent = nullptr; shared_ptr<Agent> cur_agent = get_agent_ptr(name); for (auto& content : agent_pool) { // ignore the same name if (content.first == name) continue; if (!min_distance_agent) min_distance_agent = content.second; else if ( cartesian_distance(content.second->get_location(), cur_agent->get_location()) < cartesian_distance(min_distance_agent->get_location(), cur_agent->get_location()) ) { min_distance_agent = content.second; } } return min_distance_agent; } bool Model::is_group_present(const string& name) const { return group_pool.find(name) != group_pool.end(); } void Model::add_group(shared_ptr<Group> group_ptr) { string name = group_ptr->get_name(); group_pool[name] = group_ptr; unit_pool[name] = group_ptr; } void Model::remove_group(const string& name) { shared_ptr<Group> group_ptr = get_group_ptr(name); // error is checked group_ptr->set_parent(shared_ptr<Unit>()); group_pool.erase(name); unit_pool.erase(name); } shared_ptr<Group> Model::get_group_ptr(const string& name) const { auto group_iter = group_pool.find(name); if (group_iter == group_pool.end()) throw Error("Group not found!"); return group_iter->second; } bool Model::is_unit_present(const string& name) const { return unit_pool.find(name) != unit_pool.end(); } shared_ptr<Unit> Model::get_unit_ptr(const string& name) const { auto unit_iter = unit_pool.find(name); if (unit_iter != unit_pool.end()) return unit_iter->second; else throw Error("No unit with that name!"); } // tell all objects to describe themselves to the console void Model::describe() const { for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::describe, bind(&map<string, shared_ptr<Sim_object>>::value_type::second, _1))); for_each(group_pool.begin(), group_pool.end(), bind(&Group::describe, bind(&map<string, shared_ptr<Group>>::value_type::second, _1))); } // increment the time, and tell all objects to update themselves void Model::update() { ++time; for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::update, bind(&sim_object_pool_t::value_type::second, _1))); } /* View services */ // Attaching a View adds it to the container and causes it to be updated // with all current objects'location (or other state information. void Model::attach(shared_ptr<View> view_in) { views.insert(view_in); for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::broadcast_current_state, bind(&sim_object_pool_t::value_type::second, _1))); } // Detach the View by discarding the supplied pointer from the container of Views // - no updates sent to it thereafter. void Model::detach(shared_ptr<View> view_in) { views.erase(view_in); } // notify the views about an object's location void Model::notify_location(const string& name, Point location) { for_each(views.begin(), views.end(), bind(&View::update_location, _1, name, location)); } // notify the view about an object's health change void Model::notify_health(const string& name, double health) { for_each(views.begin(), views.end(), bind(&View::update_health, _1, name, health)); } // notify the view about an object's food carry change void Model::notify_food_carry(const string& name, double food_carry) { for_each(views.begin(), views.end(), bind(&View::update_food_carry, _1, name, food_carry)); } // notify the views that an object is now gone void Model::notify_gone(const string& name) { for_each(views.begin(), views.end(), bind(&View::update_remove, _1, name)); } <commit_msg>Model refactor<commit_after>#include "Model.h" #include <algorithm> #include "View.h" #include "Structure_factory.h" #include "Agent_factory.h" #include "Geometry.h" #include "Structure.h" #include "Agent.h" #include "Group.h" #include "Utility.h" #include <functional> using std::map; using std::bind; using std::pair; using std::string; using std::shared_ptr; using namespace std::placeholders; using std::for_each; Model& Model::get_instance() { static Model m; return m; } Model::Model() { time = 0; // Create the default initial structures shared_ptr<Structure> structure_R = create_structure("Rivendale", "Farm", Point(10., 10.)); shared_ptr<Structure> structure_S = create_structure("Sunnybrook", "Farm", Point(0., 30.)); shared_ptr<Structure> structure_Sh = create_structure("Shire", "Town_Hall", Point(20., 20.)); shared_ptr<Structure> structure_P = create_structure("Paduca", "Town_Hall", Point(30., 30.)); // Create the default initial agents shared_ptr<Agent> agent_P = create_agent("Pippin", "Peasant", Point(5., 10.)); shared_ptr<Agent> agent_M = create_agent("Merry", "Peasant", Point(0., 25.)); shared_ptr<Agent> agent_Z = create_agent("Zug", "Soldier", Point(20., 30.)); shared_ptr<Agent> agent_B = create_agent("Bug", "Soldier", Point(15., 20.)); shared_ptr<Agent> agent_I = create_agent("Iriel", "Archer", Point(20.,38.)); sim_object_pool = { {structure_R->get_name(), structure_R}, {structure_S->get_name(), structure_S}, {structure_Sh->get_name(), structure_Sh}, {structure_P->get_name(), structure_P}, {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; agent_pool = { {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; structure_pool = { {structure_R->get_name(), structure_R}, {structure_S->get_name(), structure_S}, {structure_Sh->get_name(), structure_Sh}, {structure_P->get_name(), structure_P} }; unit_pool = { {agent_P->get_name(), agent_P}, {agent_M->get_name(), agent_M}, {agent_Z->get_name(), agent_Z}, {agent_B->get_name(), agent_B}, {agent_I->get_name(), agent_I} }; } Model::~Model() {} // is name already in use for either agent or structure? // return true if the name matches the name of an existing agent or structure bool Model::is_name_in_use(const string& name) const { return sim_object_pool.find(name) != sim_object_pool.end() || group_pool.find(name) != group_pool.end(); } // is there a structure with this name? bool Model::is_structure_present(const string& name) const { return structure_pool.find(name) != structure_pool.end(); } // add a new structure; assumes none with the same name void Model::add_structure(shared_ptr<Structure> structure_ptr) { sim_object_pool.emplace(structure_ptr->get_name(), structure_ptr); structure_pool.emplace(structure_ptr->get_name(), structure_ptr); structure_ptr->broadcast_current_state(); } // will throw Error("Structure not found!") if no structure of that name shared_ptr<Structure> Model::get_structure_ptr(const string& name) const { auto structure_iter = structure_pool.find(name); if (structure_iter == structure_pool.end()) throw Error("Structure not found!"); else return structure_iter->second; } shared_ptr<Structure> Model::get_nearest_structure_ptr(const string& name) const { shared_ptr<Structure> min_distance_structure = nullptr; shared_ptr<Agent> cur_agent = get_agent_ptr(name); for (auto& content : structure_pool) { if (!min_distance_structure) min_distance_structure = content.second; else if ( cartesian_distance(content.second->get_location(), cur_agent->get_location()) < cartesian_distance(min_distance_structure->get_location(), cur_agent->get_location()) ) { min_distance_structure = content.second; } } return min_distance_structure; } // is there an agent with this name? bool Model::is_agent_present(const string& name) const { return agent_pool.find(name) != agent_pool.end(); } // add a new agent; assumes none with the same name void Model::add_agent(shared_ptr<Agent> agent_ptr) { // update three pool together sim_object_pool.emplace(agent_ptr->get_name(), agent_ptr); agent_pool.emplace(agent_ptr->get_name(), agent_ptr); unit_pool.emplace(agent_ptr->get_name(), agent_ptr); // tell the view about the information agent_ptr->broadcast_current_state(); } // will throw Error("Agent not found!") if no agent of that name shared_ptr<Agent> Model::get_agent_ptr(const string& name) const { auto agent_iter = agent_pool.find(name); if (agent_iter == agent_pool.end()) throw Error("Agent not found!"); else return agent_iter->second; } void Model::remove_agent(const string& name) { shared_ptr<Agent> agent_ptr = get_agent_ptr(name); // error is checked sim_object_pool.erase(name); unit_pool.erase(name); agent_pool.erase(name); // remove the existence from group agent_ptr->set_parent(nullptr); } // Using a range for looks better then min_element with struct shared_ptr<Agent> Model::get_nearest_agent_ptr(const string& name) const { shared_ptr<Agent> min_distance_agent = nullptr; shared_ptr<Agent> cur_agent = get_agent_ptr(name); for (auto& content : agent_pool) { // ignore the same name if (content.first == name) continue; if (!min_distance_agent) min_distance_agent = content.second; else if ( cartesian_distance(content.second->get_location(), cur_agent->get_location()) < cartesian_distance(min_distance_agent->get_location(), cur_agent->get_location()) ) { min_distance_agent = content.second; } } return min_distance_agent; } bool Model::is_group_present(const string& name) const { return group_pool.find(name) != group_pool.end(); } void Model::add_group(shared_ptr<Group> group_ptr) { string name = group_ptr->get_name(); group_pool[name] = group_ptr; unit_pool[name] = group_ptr; } void Model::remove_group(const string& name) { shared_ptr<Group> group_ptr = get_group_ptr(name); // error is checked group_ptr->set_parent(nullptr); group_pool.erase(name); unit_pool.erase(name); } shared_ptr<Group> Model::get_group_ptr(const string& name) const { auto group_iter = group_pool.find(name); if (group_iter == group_pool.end()) throw Error("Group not found!"); return group_iter->second; } bool Model::is_unit_present(const string& name) const { return unit_pool.find(name) != unit_pool.end(); } shared_ptr<Unit> Model::get_unit_ptr(const string& name) const { auto unit_iter = unit_pool.find(name); if (unit_iter != unit_pool.end()) return unit_iter->second; else throw Error("No unit with that name!"); } // tell all objects to describe themselves to the console void Model::describe() const { for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::describe, bind(&map<string, shared_ptr<Sim_object>>::value_type::second, _1))); for_each(group_pool.begin(), group_pool.end(), bind(&Group::describe, bind(&map<string, shared_ptr<Group>>::value_type::second, _1))); } // increment the time, and tell all objects to update themselves void Model::update() { ++time; for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::update, bind(&sim_object_pool_t::value_type::second, _1))); } /* View services */ // Attaching a View adds it to the container and causes it to be updated // with all current objects'location (or other state information. void Model::attach(shared_ptr<View> view_in) { views.insert(view_in); for_each(sim_object_pool.begin(), sim_object_pool.end(), bind(&Sim_object::broadcast_current_state, bind(&sim_object_pool_t::value_type::second, _1))); } // Detach the View by discarding the supplied pointer from the container of Views // - no updates sent to it thereafter. void Model::detach(shared_ptr<View> view_in) { views.erase(view_in); } // notify the views about an object's location void Model::notify_location(const string& name, Point location) { for_each(views.begin(), views.end(), bind(&View::update_location, _1, name, location)); } // notify the view about an object's health change void Model::notify_health(const string& name, double health) { for_each(views.begin(), views.end(), bind(&View::update_health, _1, name, health)); } // notify the view about an object's food carry change void Model::notify_food_carry(const string& name, double food_carry) { for_each(views.begin(), views.end(), bind(&View::update_food_carry, _1, name, food_carry)); } // notify the views that an object is now gone void Model::notify_gone(const string& name) { for_each(views.begin(), views.end(), bind(&View::update_remove, _1, name)); } <|endoftext|>
<commit_before>// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <stdio.h> #include <sstream> #include <string> #include <OpenColorIO/OpenColorIO.h> #include "GPUUnitTest.h" #include "GPUHelpers.h" namespace OCIO = OCIO_NAMESPACE; // TODO: Add ctf file unit tests when the CLF reader is in. namespace CDL_Data_1 { const double slope[3] = { 1.35, 1.10, 0.71 }; const double offset[3] = { 0.05, -0.23, 0.11 }; const double power[3] = { 0.93, 0.81, 1.27 }; }; // Use the legacy shader description with the CDL from OCIO v1 implementation OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1_legacy_shader) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateLegacyShaderDesc(32); test.setContext(cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); // TODO: Would like to be able to remove the setTestNaN(false) // from all of these tests. test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v1 implementation OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); test.setContext(cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op (with the fwd clamp style) and a forward direction) OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-5f); } // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op (with the fwd clamp style) and an inverse direction) OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-4f); } namespace CDL_Data_2 { const double slope[3] = { 1.15, 1.10, 0.90 }; const double offset[3] = { 0.05, 0.02, 0.07 }; const double power[3] = { 1.20, 0.95, 1.13 }; }; // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op (with the fwd clamp style) and a forward direction) OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(2e-5f); } namespace CDL_Data_3 { const double slope[3] = { 3.405, 1.0, 1.0 }; const double offset[3] = { -0.178, -0.178, -0.178 }; const double power[3] = { 1.095, 1.095, 1.095 }; }; // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op (with the fwd clamp style) and a forward direction) OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2_Data_3) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_3::slope); cdl->setOffset(CDL_Data_3::offset); cdl->setPower(CDL_Data_3::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-5f); } <commit_msg>Adjust CDL GPU tests for default transform style change (#969)<commit_after>// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include <stdio.h> #include <sstream> #include <string> #include <OpenColorIO/OpenColorIO.h> #include "GPUUnitTest.h" #include "GPUHelpers.h" namespace OCIO = OCIO_NAMESPACE; // TODO: Add ctf file unit tests when the CLF reader is in. namespace CDL_Data_1 { constexpr double slope[3] = { 1.35, 1.10, 0.71 }; constexpr double offset[3] = { 0.05, -0.23, 0.11 }; constexpr double power[3] = { 0.93, 0.81, 1.27 }; }; // Use the legacy shader description with the CDL from OCIO v1 implementation. OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1_legacy_shader) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateLegacyShaderDesc(32); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(1); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); // TODO: Would like to be able to remove the setTestNaN(false) // from all of these tests. test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v1 implementation. OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(1); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op with the ASC/clamping style and a forward direction). OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_ASC); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-5f); } OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_no_clamp_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); test.setTestNaN(false); test.setTestInfinity(false); } // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op with the ASC/clamping style and a inverse direction). OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_ASC); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-4f); } OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_no_clamp_v2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_1::slope); cdl->setOffset(CDL_Data_1::offset); cdl->setPower(CDL_Data_1::power); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-4f); } namespace CDL_Data_2 { constexpr double slope[3] = { 1.15, 1.10, 0.90 }; constexpr double offset[3] = { 0.05, -0.02, 0.07 }; constexpr double power[3] = { 1.20, 0.95, 1.13 }; constexpr double saturation = 0.9; }; // Use the legacy shader description with the CDL from OCIO v1 implementation. OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1_legacy_shader_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateLegacyShaderDesc(32); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(1); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v1 implementation. OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v1_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(1); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(1e-6f); test.setTestNaN(false); } // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op with the ASC/clamping style and a forward direction). OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_ASC); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(2e-5f); } OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_v2_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_ASC); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(2e-5f); } OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_no_clamp_v2_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); test.setTestNaN(false); test.setTestInfinity(false); } OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_no_clamp_v2_Data_2) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_2::slope); cdl->setOffset(CDL_Data_2::offset); cdl->setPower(CDL_Data_2::power); cdl->setSat(CDL_Data_2::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); test.setTestNaN(false); test.setTestInfinity(false); } namespace CDL_Data_3 { constexpr double slope[3] = { 3.405, 1.0, 1.0 }; constexpr double offset[3] = { -0.178, -0.178, -0.178 }; constexpr double power[3] = { 1.095, 1.095, 1.0 }; constexpr double saturation = 1.2; }; // Use the generic shader description with the CDL from OCIO v2 implementation // (i.e. use the CDL Op with the ASC/clamping style and a forward direction). OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_v2_Data_3) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_ASC); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_3::slope); cdl->setOffset(CDL_Data_3::offset); cdl->setPower(CDL_Data_3::power); cdl->setSat(CDL_Data_3::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(true); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); } OCIO_ADD_GPU_TEST(CDLOp, clamp_fwd_no_clamp_v2_Data_3) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_FORWARD); cdl->setSlope(CDL_Data_3::slope); cdl->setOffset(CDL_Data_3::offset); cdl->setPower(CDL_Data_3::power); cdl->setSat(CDL_Data_3::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(false); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); test.setTestNaN(false); test.setTestInfinity(false); } OCIO_ADD_GPU_TEST(CDLOp, clamp_inv_no_clamp_v2_Data_3) { OCIO::CDLTransformRcPtr cdl = OCIO::CDLTransform::Create(); cdl->setStyle(OCIO::CDL_NO_CLAMP); cdl->setDirection(OCIO::TRANSFORM_DIR_INVERSE); cdl->setSlope(CDL_Data_3::slope); cdl->setOffset(CDL_Data_3::offset); cdl->setPower(CDL_Data_3::power); cdl->setSat(CDL_Data_3::saturation); OCIO::GpuShaderDescRcPtr shaderDesc = OCIO::GpuShaderDesc::CreateShaderDesc(); OCIO::ConfigRcPtr config = OCIO_NAMESPACE::Config::Create(); config->setMajorVersion(2); test.setContext(config, cdl, shaderDesc); test.setTestWideRange(false); test.setRelativeComparison(false); test.setErrorThreshold(5e-5f); test.setTestNaN(false); test.setTestInfinity(false); } <|endoftext|>
<commit_before>#include "hext/ResultTree.h" #include "hext/Rule.h" namespace hext { ResultTree::ResultTree(const Rule * rule) : children_(), values_(), matching_rule_(rule) { } ResultTree::ResultTree(const Rule * rule, std::vector<NameValuePair> values) : children_(), values_(values), matching_rule_(rule) { } ResultTree * ResultTree::create_branch( const Rule * rule, std::vector<NameValuePair> values ) { this->children_.push_back(MakeUnique<ResultTree>(rule, values)); return this->children_.back().get(); } bool ResultTree::filter() { // depth first for(auto& c : this->children_) if( c->filter() ) c.reset(nullptr); // erase all empty unique_ptr this->children_.erase( std::remove(this->children_.begin(), this->children_.end(), nullptr), this->children_.end() ); // Check if all rules are present in this ResultTree. if( this->matching_rule_ ) { //TODO / BUG: This code implies that rules on the same level also have to // append a ResultTree on the same level - which is simply not true! // auto c_begin = this->children_.begin(); auto c_end = this->children_.end(); for(const auto& rl : this->matching_rule_->children()) { // If there are no more result branches, all rules that follow must // be optional. if( c_begin == c_end ) { if( !rl.optional() ) return true; } // result branches and rule children have the same order. // Check if child has this rule. else if( *c_begin && (*c_begin)->matching_rule_ == &rl ) { c_begin++; } // Optional rules can be omitted else if( !rl.optional() ) { return true; } } } // keep return false; } Result ResultTree::to_result() const { typedef std::vector<std::unique_ptr<ResultTree>>::size_type c_size_type; Result results(this->children_.size()); for(c_size_type i = 0; i < this->children_.size(); ++i) this->children_[i]->save(results[i]); return results; } void ResultTree::save(std::multimap<std::string, std::string>& map) const { for(const auto& p : this->values_) map.insert(p); for(const auto& c : this->children_) c->save(map); } } // namespace hext <commit_msg>fix bug that caused ResultTrees with duplicates to be filtered out erroneously<commit_after>#include "hext/ResultTree.h" #include "hext/Rule.h" namespace hext { ResultTree::ResultTree(const Rule * rule) : children_(), values_(), matching_rule_(rule) { } ResultTree::ResultTree(const Rule * rule, std::vector<NameValuePair> values) : children_(), values_(values), matching_rule_(rule) { } ResultTree * ResultTree::create_branch( const Rule * rule, std::vector<NameValuePair> values ) { this->children_.push_back(MakeUnique<ResultTree>(rule, values)); return this->children_.back().get(); } bool ResultTree::filter() { // depth first for(auto& c : this->children_) if( c->filter() ) c.reset(nullptr); // erase all empty unique_ptr this->children_.erase( std::remove(this->children_.begin(), this->children_.end(), nullptr), this->children_.end() ); // Check if all rules are present in this ResultTree. if( this->matching_rule_ ) { auto c_begin = this->children_.begin(); auto c_end = this->children_.end(); const auto& rule_children = this->matching_rule_->children(); auto r_begin = rule_children.begin(); auto r_end = rule_children.end(); // All rule-children of the matching rule must be contained in this RuleTree // branch's children. Duplicates are safe to ignore. // We can take advantage of the fact that ResultTrees are appended in the // same order as Rule-children are stored. while( r_begin != r_end ) { if( c_begin != c_end && (*c_begin)->matching_rule_ == &(*r_begin) ) { while( c_begin != c_end && (*c_begin)->matching_rule_ == &(*r_begin) ) c_begin++; } else if( !r_begin->optional() ) { // remove return true; } r_begin++; } } // keep return false; } Result ResultTree::to_result() const { typedef std::vector<std::unique_ptr<ResultTree>>::size_type c_size_type; Result results(this->children_.size()); for(c_size_type i = 0; i < this->children_.size(); ++i) this->children_[i]->save(results[i]); return results; } void ResultTree::save(std::multimap<std::string, std::string>& map) const { for(const auto& p : this->values_) map.insert(p); for(const auto& c : this->children_) c->save(map); } } // namespace hext <|endoftext|>
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API 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 Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "lz4_wrapper.h" #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> namespace { template < typename T > std::string to_string(T t) { std::ostringstream out; out<<std::setprecision(14)<<t; return out.str(); } } LZ4_Deflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Deflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Deflate::LZ4_Deflate() { } LZ4_Deflate::~LZ4_Deflate() { } int LZ4_Deflate::compress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret = LZ4_compress_limitedOutput((const char*) in, (char *) out + 4, in_size, out_buffer_size - 4); if (ret == 0) { // compression failed if (in_size > out_buffer_size - 4) throw std::runtime_error("LZ4: output buffer too small during compression"); *(int*)out = in_size * -1; std::memcpy ((char *) out + 4, (const char*)in, in_size); ret = in_size; } else *(int*)out = ret; return ret + 4; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } LZ4_Inflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Inflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Inflate::LZ4_Inflate() { } LZ4_Inflate::~LZ4_Inflate() { } int LZ4_Inflate::decompress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret; int in_buffer_size = *(int*)in; if (in_buffer_size > 0) { ret = LZ4_decompress_safe((const char*) in + 4, (char*) out, in_buffer_size, out_buffer_size); if (ret < 0) throw std::runtime_error("LZ4_decompress_safe failed"); } else { in_buffer_size *= -1; if (in_buffer_size > out_buffer_size) throw std::runtime_error ("LZ4: output buffer too small during decompression"); std::memcpy ((char*) out, (const char*) in + 4, in_buffer_size); ret = in_buffer_size; } return ret; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } <commit_msg>lz4: fallback to uncompressed input if result size increases during compression<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API 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 Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "lz4_wrapper.h" #include <cstring> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> namespace { template < typename T > std::string to_string(T t) { std::ostringstream out; out<<std::setprecision(14)<<t; return out.str(); } } LZ4_Deflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Deflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Deflate::LZ4_Deflate() { } LZ4_Deflate::~LZ4_Deflate() { } int LZ4_Deflate::compress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret = LZ4_compress_limitedOutput((const char*) in, (char *) out + 4, in_size, out_buffer_size - 4); if (ret == 0 || ret > in_size) { // compression failed, or result size increased during compression if (in_size > out_buffer_size - 4) throw std::runtime_error("LZ4: output buffer too small during compression"); *(int*)out = in_size * -1; std::memcpy ((char *) out + 4, (const char*)in, in_size); ret = in_size; } else *(int*)out = ret; return ret + 4; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } LZ4_Inflate::Error::Error(int error_code_) : std::runtime_error("LZ4_Inflate: " + to_string(error_code_)), error_code(error_code_) {} LZ4_Inflate::LZ4_Inflate() { } LZ4_Inflate::~LZ4_Inflate() { } int LZ4_Inflate::decompress(const void* in, int in_size, void* out, int out_buffer_size) { #ifdef HAVE_LZ4 int ret; int in_buffer_size = *(int*)in; if (in_buffer_size > 0) { ret = LZ4_decompress_safe((const char*) in + 4, (char*) out, in_buffer_size, out_buffer_size); if (ret < 0) throw std::runtime_error("LZ4_decompress_safe failed"); } else { in_buffer_size *= -1; if (in_buffer_size > out_buffer_size) throw std::runtime_error ("LZ4: output buffer too small during decompression"); std::memcpy ((char*) out, (const char*) in + 4, in_buffer_size); ret = in_buffer_size; } return ret; #else throw std::runtime_error("Overpass API was compiled without lz4 compression library support"); #endif } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QEthereum.cpp * @authors: * Gav Wood <i@gavwood.com> * Marek Kotewicz <marek@ethdev.com> * @date 2014 */ #include <QtCore/QtCore> #include "QEthereum.h" using namespace std; QWebThree::QWebThree(QObject* _p): QObject(_p) { moveToThread(_p->thread()); } QWebThree::~QWebThree() { } void QWebThree::poll() { if (m_watches.size() == 0) return; QJsonArray batch; for (int w: m_watches) { QJsonObject res; res["jsonrpc"] = "2.0"; res["method"] = "changed"; QJsonArray params; params.append(w); res["params"] = params; res["id"] = w; batch.append(res); } emit processData(QString::fromUtf8(QJsonDocument(batch).toJson()), "changed"); } void QWebThree::clearWatches() { if (m_watches.size() == 0) return; QJsonArray batch; for (int w: m_watches) { QJsonObject res; res["jsonrpc"] = "2.0"; res["method"] = "uninstallFilter"; QJsonArray params; params.append(w); res["params"] = params; res["id"] = w; batch.append(params); } m_watches.clear(); emit processData(QString::fromUtf8(QJsonDocument(batch).toJson()), "internal"); } void QWebThree::clientDieing() { this->disconnect(); clearWatches(); } static QString formatInput(QJsonObject const& _object) { QJsonObject res; res["jsonrpc"] = "2.0"; res["method"] = _object["call"]; res["params"] = _object["args"]; res["id"] = _object["_id"]; return QString::fromUtf8(QJsonDocument(res).toJson()); } void QWebThree::postData(QString _json) { QJsonObject f = QJsonDocument::fromJson(_json.toUtf8()).object(); QString method = f["call"].toString(); if (!method.compare("uninstallFilter")) { int idToRemove = -1; if (f["args"].isArray()) if (f["args"].toArray().size()) idToRemove = f["args"].toArray()[0].toInt();; m_watches.erase(std::remove(m_watches.begin(), m_watches.end(), idToRemove), m_watches.end()); } emit processData(formatInput(f), method); } static QString formatOutput(QJsonObject const& _object) { QJsonObject res; res["_id"] = _object["id"]; res["data"] = _object["result"]; return QString::fromUtf8(QJsonDocument(res).toJson()); } void QWebThree::onDataProcessed(QString _json, QString _addInfo) { if (!_addInfo.compare("internal")) return; if (!_addInfo.compare("changed")) { QJsonArray resultsArray = QJsonDocument::fromJson(_json.toUtf8()).array(); for (int i = 0; i < resultsArray.size(); i++) { QJsonObject elem = resultsArray[i].toObject(); if (elem.contains("result") && elem["result"].toBool() == true) { QJsonObject res; res["_event"] = "messages"; res["data"] = (int)m_watches[i]; // we can do that couse poll is synchronous response(QString::fromUtf8(QJsonDocument(res).toJson())); } } return; } QJsonObject f = QJsonDocument::fromJson(_json.toUtf8()).object(); if (!_addInfo.compare("newFilter") || !_addInfo.compare("newFilterString")) if (f.contains("result")) m_watches.push_back(f["result"].toInt()); response(formatOutput(f)); } QWebThreeConnector::QWebThreeConnector(QWebThree* _q): m_qweb(_q) { } QWebThreeConnector::~QWebThreeConnector() { StopListening(); } bool QWebThreeConnector::StartListening() { connect(m_qweb, SIGNAL(processData(QString, QString)), this, SLOT(onProcessData(QString, QString))); connect(this, SIGNAL(dataProcessed(QString, QString)), m_qweb, SLOT(onDataProcessed(QString, QString))); return true; } bool QWebThreeConnector::StopListening() { this->disconnect(); return true; } bool QWebThreeConnector::SendResponse(std::string const& _response, void* _addInfo) { emit dataProcessed(QString::fromStdString(_response), *(QString*)_addInfo); return true; } void QWebThreeConnector::onProcessData(QString const& _json, QString const& _addInfo) { OnRequest(_json.toStdString(), (void*)&_addInfo); } // extra bits needed to link on VS #ifdef _MSC_VER // include moc file, ofuscated to hide from automoc #include\ "moc_QEthereum.cpp" #endif <commit_msg>explicitly inserting Qstring cause of compiler errors<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QEthereum.cpp * @authors: * Gav Wood <i@gavwood.com> * Marek Kotewicz <marek@ethdev.com> * @date 2014 */ #include <QtCore/QtCore> #include "QEthereum.h" using namespace std; QWebThree::QWebThree(QObject* _p): QObject(_p) { moveToThread(_p->thread()); } QWebThree::~QWebThree() { } void QWebThree::poll() { if (m_watches.size() == 0) return; QJsonArray batch; for (int w: m_watches) { QJsonObject res; res["jsonrpc"] = QString::fromStdString("2.0"); res["method"] = QString::fromStdString("changed"); QJsonArray params; params.append(w); res["params"] = params; res["id"] = w; batch.append(res); } emit processData(QString::fromUtf8(QJsonDocument(batch).toJson()), "changed"); } void QWebThree::clearWatches() { if (m_watches.size() == 0) return; QJsonArray batch; for (int w: m_watches) { QJsonObject res; res["jsonrpc"] = QString::fromStdString("2.0"); res["method"] = QString::fromStdString("uninstallFilter"); QJsonArray params; params.append(w); res["params"] = params; res["id"] = w; batch.append(params); } m_watches.clear(); emit processData(QString::fromUtf8(QJsonDocument(batch).toJson()), "internal"); } void QWebThree::clientDieing() { this->disconnect(); clearWatches(); } static QString formatInput(QJsonObject const& _object) { QJsonObject res; res["jsonrpc"] = QString::fromStdString("2.0"); res["method"] = _object["call"]; res["params"] = _object["args"]; res["id"] = _object["_id"]; return QString::fromUtf8(QJsonDocument(res).toJson()); } void QWebThree::postData(QString _json) { QJsonObject f = QJsonDocument::fromJson(_json.toUtf8()).object(); QString method = f["call"].toString(); if (!method.compare("uninstallFilter")) { int idToRemove = -1; if (f["args"].isArray()) if (f["args"].toArray().size()) idToRemove = f["args"].toArray()[0].toInt();; m_watches.erase(std::remove(m_watches.begin(), m_watches.end(), idToRemove), m_watches.end()); } emit processData(formatInput(f), method); } static QString formatOutput(QJsonObject const& _object) { QJsonObject res; res["_id"] = _object["id"]; res["data"] = _object["result"]; return QString::fromUtf8(QJsonDocument(res).toJson()); } void QWebThree::onDataProcessed(QString _json, QString _addInfo) { if (!_addInfo.compare("internal")) return; if (!_addInfo.compare("changed")) { QJsonArray resultsArray = QJsonDocument::fromJson(_json.toUtf8()).array(); for (int i = 0; i < resultsArray.size(); i++) { QJsonObject elem = resultsArray[i].toObject(); if (elem.contains("result") && elem["result"].toBool() == true) { QJsonObject res; res["_event"] = QString::fromStdString("messages"); res["data"] = (int)m_watches[i]; // we can do that couse poll is synchronous response(QString::fromUtf8(QJsonDocument(res).toJson())); } } return; } QJsonObject f = QJsonDocument::fromJson(_json.toUtf8()).object(); if (!_addInfo.compare("newFilter") || !_addInfo.compare("newFilterString")) if (f.contains("result")) m_watches.push_back(f["result"].toInt()); response(formatOutput(f)); } QWebThreeConnector::QWebThreeConnector(QWebThree* _q): m_qweb(_q) { } QWebThreeConnector::~QWebThreeConnector() { StopListening(); } bool QWebThreeConnector::StartListening() { connect(m_qweb, SIGNAL(processData(QString, QString)), this, SLOT(onProcessData(QString, QString))); connect(this, SIGNAL(dataProcessed(QString, QString)), m_qweb, SLOT(onDataProcessed(QString, QString))); return true; } bool QWebThreeConnector::StopListening() { this->disconnect(); return true; } bool QWebThreeConnector::SendResponse(std::string const& _response, void* _addInfo) { emit dataProcessed(QString::fromStdString(_response), *(QString*)_addInfo); return true; } void QWebThreeConnector::onProcessData(QString const& _json, QString const& _addInfo) { OnRequest(_json.toStdString(), (void*)&_addInfo); } // extra bits needed to link on VS #ifdef _MSC_VER // include moc file, ofuscated to hide from automoc #include\ "moc_QEthereum.cpp" #endif <|endoftext|>
<commit_before>#include <CGAL/Cartesian.h> #include <iostream> #ifndef CGAL_USE_GEOMVIEW int main() { std::cout << "Geomview doesn't work on Windows, so..." << std::endl; return 0; } #else #include <fstream> #include <unistd.h> // for sleep() #include <CGAL/Projection_traits_xy_3.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Delaunay_triangulation_3.h> #include <CGAL/IO/Geomview_stream.h> #include <CGAL/IO/Triangulation_geomview_ostream_2.h> #include <CGAL/IO/Triangulation_geomview_ostream_3.h> #include <CGAL/intersections.h> typedef CGAL::Cartesian<double> K; typedef K::Point_2 Point2; typedef CGAL::Projection_traits_xy_3<K> Gt3; typedef Gt3::Point Point3; typedef CGAL::Delaunay_triangulation_2<K> Delaunay; typedef CGAL::Delaunay_triangulation_2<Gt3> Terrain; typedef CGAL::Delaunay_triangulation_3<K> Delaunay3d; int main() { CGAL::Geomview_stream gv(CGAL::Bbox_3(-100, -100, -100, 600, 600, 600)); gv.set_line_width(4); // gv.set_trace(true); gv.set_bg_color(CGAL::Color(0, 200, 200)); // gv.clear(); Delaunay D; Delaunay3d D3d; Terrain T; std::ifstream iFile("data/points3", std::ios::in); Point3 p; while ( iFile >> p ) { D.insert( Point2(p.x(), p.y()) ); D3d.insert( p ); T.insert( p ); } // use different colors, and put a few sleeps/clear. gv << CGAL::BLUE; std::cout << "Drawing 2D Delaunay triangulation in wired mode.\n"; gv.set_wired(true); gv << D; #if 1 // It's too slow ! Needs to use OFF for that. gv << CGAL::RED; std::cout << "Drawing its Voronoi diagram.\n"; gv.set_wired(true); D.draw_dual(gv); #endif sleep(5); gv.clear(); std::cout << "Drawing 2D Delaunay triangulation in non-wired mode.\n"; gv.set_wired(false); gv << D; sleep(5); gv.clear(); std::cout << "Drawing 3D Delaunay triangulation in wired mode.\n"; gv.set_wired(true); gv << D3d; sleep(5); gv.clear(); std::cout << "Drawing 3D Delaunay triangulation in non-wired mode.\n"; gv.set_wired(false); gv << D3d; sleep(5); gv.clear(); std::cout << "Drawing Terrain in wired mode.\n"; gv.set_wired(true); gv << T; sleep(5); gv.clear(); std::cout << "Drawing Terrain in non-wired mode.\n"; gv.set_wired(false); gv << T; std::cout << "Enter a key to finish" << std::endl; char ch; std::cin >> ch; return 0; } #endif<commit_msg>Exact formatting from example<commit_after>/// From http://doc.cgal.org/latest/Geomview/Geomview_2gv_terrain_8cpp-example.html #include <CGAL/Cartesian.h> #include <iostream> #ifndef CGAL_USE_GEOMVIEW int main() { std::cout << "Geomview doesn't work on Windows, so..." << std::endl; return 0; } #else #include <fstream> #include <unistd.h> // for sleep() #include <CGAL/Projection_traits_xy_3.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Delaunay_triangulation_3.h> #include <CGAL/IO/Geomview_stream.h> #include <CGAL/IO/Triangulation_geomview_ostream_2.h> #include <CGAL/IO/Triangulation_geomview_ostream_3.h> #include <CGAL/intersections.h> typedef CGAL::Cartesian<double> K; typedef K::Point_2 Point2; typedef CGAL::Projection_traits_xy_3<K> Gt3; typedef Gt3::Point Point3; typedef CGAL::Delaunay_triangulation_2<K> Delaunay; typedef CGAL::Delaunay_triangulation_2<Gt3> Terrain; typedef CGAL::Delaunay_triangulation_3<K> Delaunay3d; int main() { CGAL::Geomview_stream gv(CGAL::Bbox_3(-100, -100, -100, 600, 600, 600)); gv.set_line_width(4); // gv.set_trace(true); gv.set_bg_color(CGAL::Color(0, 200, 200)); // gv.clear(); Delaunay D; Delaunay3d D3d; Terrain T; std::ifstream iFile("data/points3", std::ios::in); Point3 p; while ( iFile >> p ) { D.insert( Point2(p.x(), p.y()) ); D3d.insert( p ); T.insert( p ); } // use different colors, and put a few sleeps/clear. gv << CGAL::BLUE; std::cout << "Drawing 2D Delaunay triangulation in wired mode.\n"; gv.set_wired(true); gv << D; #if 1 // It's too slow ! Needs to use OFF for that. gv << CGAL::RED; std::cout << "Drawing its Voronoi diagram.\n"; gv.set_wired(true); D.draw_dual(gv); #endif sleep(5); gv.clear(); std::cout << "Drawing 2D Delaunay triangulation in non-wired mode.\n"; gv.set_wired(false); gv << D; sleep(5); gv.clear(); std::cout << "Drawing 3D Delaunay triangulation in wired mode.\n"; gv.set_wired(true); gv << D3d; sleep(5); gv.clear(); std::cout << "Drawing 3D Delaunay triangulation in non-wired mode.\n"; gv.set_wired(false); gv << D3d; sleep(5); gv.clear(); std::cout << "Drawing Terrain in wired mode.\n"; gv.set_wired(true); gv << T; sleep(5); gv.clear(); std::cout << "Drawing Terrain in non-wired mode.\n"; gv.set_wired(false); gv << T; std::cout << "Enter a key to finish" << std::endl; char ch; std::cin >> ch; return 0; } #endif<|endoftext|>
<commit_before>// This file is part of Parsito <http://github.com/ufal/parsito/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <ctime> #include <iomanip> #include <iostream> #include <memory> #include <vector> #include "parsito.h" using namespace ufal::parsito; using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " model_file" << endl; return 1; } unique_ptr<tree_input_format> input_format(tree_input_format::new_conllu_input_format()); unique_ptr<tree_output_format> output_format(tree_output_format::new_conllu_output_format()); cerr << "Loading parser: "; unique_ptr<parser> p(parser::load(argv[1])); if (!p) { cerr << "Cannot load parser from file '" << argv[1] << "'!" << endl; return 1; } cerr << "done" << endl; clock_t now = clock(); tree t; string input, output; while (input_format->read_block(cin, input)) { // Process all trees in the block input_format->set_text(input); while (input_format->next_tree(t)) { // Parse the tree p->parse(t); // Output the parsed tree output_format->write_tree(t, output, input_format.get()); cout << output << flush; } if (!input_format->last_error().empty()) { cerr << "Cannot load input: " << input_format->last_error() << endl; return 1; } } cerr << "Parsing done, in " << fixed << setprecision(3) << (clock() - now) / double(CLOCKS_PER_SEC) << " seconds." << endl; return 0; } <commit_msg>Add missing include.<commit_after>// This file is part of Parsito <http://github.com/ufal/parsito/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <ctime> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <vector> #include "parsito.h" using namespace ufal::parsito; using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cerr << "Usage: " << argv[0] << " model_file" << endl; return 1; } unique_ptr<tree_input_format> input_format(tree_input_format::new_conllu_input_format()); unique_ptr<tree_output_format> output_format(tree_output_format::new_conllu_output_format()); cerr << "Loading parser: "; unique_ptr<parser> p(parser::load(argv[1])); if (!p) { cerr << "Cannot load parser from file '" << argv[1] << "'!" << endl; return 1; } cerr << "done" << endl; clock_t now = clock(); tree t; string input, output; while (input_format->read_block(cin, input)) { // Process all trees in the block input_format->set_text(input); while (input_format->next_tree(t)) { // Parse the tree p->parse(t); // Output the parsed tree output_format->write_tree(t, output, input_format.get()); cout << output << flush; } if (!input_format->last_error().empty()) { cerr << "Cannot load input: " << input_format->last_error() << endl; return 1; } } cerr << "Parsing done, in " << fixed << setprecision(3) << (clock() - now) / double(CLOCKS_PER_SEC) << " seconds." << endl; return 0; } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <math/statistic.h> #include <storage/memstorage.h> class Moc_I1:public dariadb::statistic::BaseMethod { public: Moc_I1(){ _a=_b=dariadb::Meas::empty(); } void calc(const dariadb::Meas&a,const dariadb::Meas&b)override{ _a=a; _b=b; } dariadb::Value result()const { return dariadb::Value(); } dariadb::Meas _a; dariadb::Meas _b; }; BOOST_AUTO_TEST_CASE(CallCalc) { std::unique_ptr<Moc_I1> p{new Moc_I1}; auto m=dariadb::Meas::empty(); m.id=1; p->call(m); BOOST_CHECK_EQUAL(p->_a.id,dariadb::Id(0)); m.id=2; p->call(m); BOOST_CHECK_EQUAL(p->_a.id,dariadb::Id(1)); BOOST_CHECK_EQUAL(p->_b.id,dariadb::Id(2)); m.id=3; p->call(m); BOOST_CHECK_EQUAL(p->_a.id,dariadb::Id(2)); BOOST_CHECK_EQUAL(p->_b.id,dariadb::Id(3)); { using dariadb::statistic::average::Average; auto ms = new dariadb::storage::MemoryStorage{ 500 }; m = dariadb::Meas::empty(); const size_t total_count = 100; const dariadb::Time time_step = 1; for (size_t i = 0; i < total_count; i += time_step) { m.id = 1; m.flag = dariadb::Flag(i); m.time = i; m.value = 5; ms->append(m); } std::unique_ptr<Average> p_average{ new Average() }; auto rdr = ms->readInterval(0, total_count); p_average->fromReader(rdr, 0, total_count, 1); BOOST_CHECK_CLOSE(p_average->result(), dariadb::Value(5), 0.1); } } BOOST_AUTO_TEST_CASE(RectangleMethod) { {//left using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::LEFT) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(0)); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(1)); } {//right using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::RIGHT) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(1)); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(3)); } {//midle using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::MIDLE) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(0.5),0.01); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(2), 0.01); } } BOOST_AUTO_TEST_CASE(Average) { {//midle using dariadb::statistic::average::Average; std::unique_ptr<Average> p{ new Average() }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(1), 0.01); } } <commit_msg>statistic_test.<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <math/statistic.h> #include <storage/memstorage.h> class Moc_I1:public dariadb::statistic::BaseMethod { public: Moc_I1(){ _a=_b=dariadb::Meas::empty(); } void calc(const dariadb::Meas&a,const dariadb::Meas&b)override{ _a=a; _b=b; } dariadb::Value result()const { return dariadb::Value(); } dariadb::Meas _a; dariadb::Meas _b; }; BOOST_AUTO_TEST_CASE(CallCalc) { std::unique_ptr<Moc_I1> p{new Moc_I1}; auto m=dariadb::Meas::empty(); m.time=1; p->call(m); BOOST_CHECK_EQUAL(p->_a.time,dariadb::Time(0)); m.time =2; p->call(m); BOOST_CHECK_EQUAL(p->_a.time,dariadb::Time(1)); BOOST_CHECK_EQUAL(p->_b.time,dariadb::Time(2)); m.time =3; p->call(m); BOOST_CHECK_EQUAL(p->_a.time,dariadb::Time(2)); BOOST_CHECK_EQUAL(p->_b.time,dariadb::Time(3)); { using dariadb::statistic::average::Average; auto ms = new dariadb::storage::MemoryStorage{ 500 }; m = dariadb::Meas::empty(); const size_t total_count = 100; const dariadb::Time time_step = 1; for (size_t i = 0; i < total_count; i += time_step) { m.id = 1; m.flag = dariadb::Flag(i); m.time = i; m.value = 5; ms->append(m); } std::unique_ptr<Average> p_average{ new Average() }; auto rdr = ms->readInterval(0, total_count); p_average->fromReader(rdr, 0, total_count, 1); BOOST_CHECK_CLOSE(p_average->result(), dariadb::Value(5), 0.1); } } BOOST_AUTO_TEST_CASE(RectangleMethod) { {//left using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::LEFT) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(0)); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(1)); } {//right using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::RIGHT) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(1)); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_EQUAL(p->result(), dariadb::Value(3)); } {//midle using dariadb::statistic::integral::RectangleMethod; std::unique_ptr<RectangleMethod> p{ new RectangleMethod(RectangleMethod::Kind::MIDLE) }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(0.5),0.01); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(2), 0.01); } } BOOST_AUTO_TEST_CASE(Average) { {//midle using dariadb::statistic::average::Average; std::unique_ptr<Average> p{ new Average() }; auto m = dariadb::Meas::empty(); m.id = 1; m.time = 0; m.value = 0; p->call(m); m.time = 1; m.value = 1; p->call(m); m.time = 2; m.value = 2; p->call(m); BOOST_CHECK_CLOSE(p->result(), dariadb::Value(1), 0.01); } } <|endoftext|>
<commit_before>// // Created by Ivan Shynkarenka on 01.09.2016. // #include "catch.hpp" #include "math/math.h" using namespace CppCommon; TEST_CASE("Math", "[CppCommon][Math]") { REQUIRE(Math::MulDiv64(4984198405165151231, 6132198419878046132, 9156498145135109843) == 3337967539561099935); REQUIRE(Math::MulDiv64(11540173641653250113, 10150593219136339683, 13592284235543989460) == 8618095846487663363); REQUIRE(Math::MulDiv64(449033535071450778, 3155170653582908051, 4945421831474875872) == 286482625873293138); REQUIRE(Math::MulDiv64(303601908757, 829267376026, 659820219978) == 381569328444); REQUIRE(Math::MulDiv64(449033535071450778, 829267376026, 659820219978) == 564348969767547451); REQUIRE(Math::MulDiv64(1234568, 829267376026, 1) == 1023786965885666768); REQUIRE(Math::MulDiv64(6991754535226557229, 7798003721120799096, 4923601287520449332) == 11073546515850664288); REQUIRE(Math::MulDiv64(9223372036854775808, 2147483648, 18446744073709551615) == 1073741824); REQUIRE(Math::MulDiv64(9223372032559808512, 9223372036854775807, 9223372036854775807) == 9223372032559808512); REQUIRE(Math::MulDiv64(9223372032559808512, 9223372036854775807, 12) == 18446744073709551615); REQUIRE(Math::MulDiv64(18446744073709551615, 18446744073709551615, 9223372036854775808) == 18446744073709551615); } <commit_msg>Bugfixing<commit_after>// // Created by Ivan Shynkarenka on 01.09.2016. // #include "catch.hpp" #include "math/math.h" using namespace CppCommon; bool Compare(uint64_t a, uint64_t b) { return a == b; } TEST_CASE("Math", "[CppCommon][Math]") { REQUIRE(Compare(Math::MulDiv64(4984198405165151231, 6132198419878046132, 9156498145135109843), 3337967539561099935)); REQUIRE(Compare(Math::MulDiv64(11540173641653250113, 10150593219136339683, 13592284235543989460), 8618095846487663363)); REQUIRE(Compare(Math::MulDiv64(449033535071450778, 3155170653582908051, 4945421831474875872), 286482625873293138)); REQUIRE(Compare(Math::MulDiv64(303601908757, 829267376026, 659820219978), 381569328444)); REQUIRE(Compare(Math::MulDiv64(449033535071450778, 829267376026, 659820219978), 564348969767547451)); REQUIRE(Compare(Math::MulDiv64(1234568, 829267376026, 1), 1023786965885666768)); REQUIRE(Compare(Math::MulDiv64(6991754535226557229, 7798003721120799096, 4923601287520449332), 11073546515850664288)); REQUIRE(Compare(Math::MulDiv64(9223372036854775808, 2147483648, 18446744073709551615), 1073741824)); REQUIRE(Compare(Math::MulDiv64(9223372032559808512, 9223372036854775807, 9223372036854775807), 9223372032559808512)); REQUIRE(Compare(Math::MulDiv64(9223372032559808512, 9223372036854775807, 12), 18446744073709551615)); REQUIRE(Compare(Math::MulDiv64(18446744073709551615, 18446744073709551615, 9223372036854775808), 18446744073709551615)); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <cmath> #include <assert.h> #include <atomic> #include <algorithm> #include <gtest/gtest.h> #include "../algorithm.h" #include "../parallel.h" #include "../sequence.h" #include "../async.h" #include "../task.h" class Parallel2Test : testing::Test { }; TEST(Parallel2Test, Test1) { std::future<int> f1 = asyncply::_async([](int data){return data;}, 10); ASSERT_EQ(f1.get(), 10); } TEST(Parallel2Test, Test2) { auto f1 = asyncply::async([](){return 15;}); auto f2 = f1->then([](int data) { std::cout << "post, received: " << data << std::endl; return data + 6; }); ASSERT_EQ(f2->get(), 15 + 6); } TEST(Parallel2Test, Test3) { std::vector<int> a; for(int i=0; i<100; ++i) { a.push_back(1); a.push_back(4); a.push_back(12); a.push_back(-3); a.push_back(22); } std::atomic<int> total; total = 0; asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) { total += i; }); ASSERT_EQ(total, 3600); } TEST(Parallel2Test, Test3_async) { std::vector<int> a; for(int i=0; i<100; ++i) { a.push_back(1); a.push_back(4); a.push_back(12); a.push_back(-3); a.push_back(22); } std::atomic<int> total; total = 0; asyncply::for_each(a.begin(), a.end(), [&total](int i) { total += i; }); ASSERT_EQ(total, 3600); } TEST(Parallel2Test, Test4) { auto total_ps = asyncply::parallel_sync( []() { return asyncply::sequence(1.0, [](double data) { return data + 1.0; }, [](double data) { return data + 1.0; }); }, []() { return asyncply::sequence(1.0, [](double data) { return data + 1.0; }, [](double data) { return data + 1.0; }); } ); ASSERT_EQ(total_ps, 6); } TEST(Parallel2Test, Test5) { std::atomic<int> total; total = 0; auto process = asyncply::parallel( [&total]() { std::cout << "hi" << std::endl; total += 1; }, [&total]() { std::cout << "bye" << std::endl; total += 1; } ); auto process2 = process->then([&total]() { std::cout << "no accum" << std::endl; total += 1; }); process2->get(); ASSERT_EQ(total, 3); } TEST(Parallel2Test, Test6) { std::atomic<int> total; total = 0; { auto process2 = asyncply::parallel( [&total]() { std::cout << "hi" << std::endl; total += 1; }, [&total]() { std::cout << "bye" << std::endl; total += 1; } ); process2->then([&total]() { std::cout << "no accum" << std::endl; total += 1; }); } ASSERT_EQ(total, 3); } <commit_msg>Update test_parallel2.cpp<commit_after>#include <iostream> #include <vector> #include <cmath> #include <assert.h> #include <atomic> #include <algorithm> #include <gtest/gtest.h> #include "../algorithm.h" #include "../parallel.h" #include "../sequence.h" #include "../async.h" #include "../task.h" class Parallel2Test : testing::Test { }; TEST(Parallel2Test, Test1) { std::future<int> f1 = asyncply::_async([](int data){return data;}, 10); ASSERT_EQ(f1.get(), 10); } TEST(Parallel2Test, Test2) { auto f1 = asyncply::async([](){return 15;}); auto f2 = f1->then([](int data) { std::cout << "post, received: " << data << std::endl; return data + 6; }); ASSERT_EQ(f2->get(), 15 + 6); } TEST(Parallel2Test, Test3) { std::vector<int> a; for(int i=0; i<100; ++i) { a.push_back(1); a.push_back(4); a.push_back(12); a.push_back(-3); a.push_back(22); } std::atomic<int> total; total = 0; asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) { total += i; }); ASSERT_EQ(total, 3600); } TEST(Parallel2Test, Test3_async) { std::vector<int> a; for(int i=0; i<100; ++i) { a.push_back(1); a.push_back(4); a.push_back(12); a.push_back(-3); a.push_back(22); } std::atomic<int> total; total = 0; asyncply::for_each(a.begin(), a.end(), [&total](int i) { total += i; }); ASSERT_EQ(total, 3600); } TEST(Parallel2Test, Test4) { auto total_ps = asyncply::parallel_sync( []() { return asyncply::sequence(1.0, [](double data) { return data + 1.0; }, [](double data) { return data + 1.0; }); }, []() { return asyncply::sequence(1.0, [](double data) { return data + 1.0; }, [](double data) { return data + 1.0; }); } ); ASSERT_EQ(total_ps, 6); } TEST(Parallel2Test, Test5) { std::atomic<int> total; total = 0; auto process = asyncply::parallel( [&total]() { std::cout << "hi" << std::endl; total += 1; }, [&total]() { std::cout << "bye" << std::endl; total += 1; } ); auto process2 = process->then([&total]() { std::cout << "no accum" << std::endl; total += 1; }); process2->get(); ASSERT_EQ(total, 3); } TEST(Parallel2Test, DISABLED_Test6) { std::atomic<int> total; total = 0; { auto process2 = asyncply::parallel( [&total]() { std::cout << "hi" << std::endl; total += 1; }, [&total]() { std::cout << "bye" << std::endl; total += 1; } ); process2->then([&total]() { std::cout << "no accum" << std::endl; total += 1; }); } ASSERT_EQ(total, 3); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <ten/json.hh> #include <array> #include "ten/logging.hh" #include "ten/jsonstream.hh" #include <map> using namespace std; using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; TEST(Json, Path1) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1{o.path("/store/book/author")}; EXPECT_EQ(json::load(a1), r1); json r2{o.path("//author")}; EXPECT_EQ(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3{o.path("/store/*")}; json t3{json::load(a3)}; EXPECT_EQ(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4{o.path("/store//price")}; EXPECT_EQ(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5{o.path("//book[3]")}; EXPECT_EQ(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6{o.path("/store/book[3]/author")}; EXPECT_EQ(json::load(a6), r6); EXPECT_TRUE(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7{o.path("/store/book[category=\"fiction\"]")}; EXPECT_EQ(json::load(a7), r7); } TEST(Json, Path2) { json o{json::load("[{\"type\": 0}, {\"type\": 1}]")}; EXPECT_EQ(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } TEST(Json, FilterKeyExists) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r{o.path("//book[isbn]")}; EXPECT_EQ(json::load(a), r); json r1{o.path("//book[doesnotexist]")}; ASSERT_TRUE(r1.is_array()); EXPECT_EQ(0u, r1.asize()); } TEST(Json, Truth) { json o{{}}; // empty init list EXPECT_TRUE(o.get("nothing").is_true() == false); EXPECT_TRUE(o.get("nothing").is_false() == false); EXPECT_TRUE(o.get("nothing").is_null() == false); EXPECT_TRUE(!o.get("nothing")); } TEST(Json, Path3) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); EXPECT_EQ(o, o.path("/")); EXPECT_EQ("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; EXPECT_EQ(json(1), json::load(text).path("/[type=\"b\"]/value")); } TEST(Json, InitList) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; ASSERT_TRUE((bool)meta); ASSERT_TRUE(meta.is_object()); EXPECT_EQ(meta.osize(), 5u); EXPECT_EQ(meta["foo"].integer(), 17); EXPECT_EQ(meta["corge"][0].integer(), 1); EXPECT_EQ(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); EXPECT_EQ((json_type)j2.type(), t); EXPECT_EQ(j, j2); T val2 = json_cast<T>(j2); EXPECT_EQ(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } TEST(Json, Conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); EXPECT_EQ(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } TEST(Json, Create) { json obj1{{}}; EXPECT_TRUE((bool)obj1); obj1.set("test", "set"); EXPECT_TRUE((bool)obj1.get("test")); json root{ {"obj1", obj1} }; EXPECT_EQ(root.get("obj1"), obj1); obj1.set("this", "that"); EXPECT_EQ(root.get("obj1").get("this").str(), "that"); json obj2{ {"answer", 42} }; obj1.set("obj2", obj2); EXPECT_EQ(root.get("obj1").get("obj2"), obj2); } TEST(Json, Stream) { // TODO: improve these tests or don't. this is a hack anyway using namespace jsonstream_manip; std::stringstream ss; jsonstream s(ss); int8_t c = 'C'; // printable float fval = -1.28; double dval = -1.28; s << jsobject << "key1" << 1234 << "key2" << "value" << "list" << jsarray << "1" << 2.0f << 3.14e-20 << 4 << 5 << jsend << "list2" << jsarray << jsobject << jsend << jsend << "max_dbl" << std::numeric_limits<double>::max() << "inf" << std::numeric_limits<float>::infinity() << "nan" << (1.0 / 0.0) << "vec" << std::vector<int>({0, 1, 2, 3}) << "char" << c << "bool" << false << jsescape << "escape" << "\n\t\"" << "noescape" << "blahblah" << "raw" << jsraw << "[]" << jsnoraw << "lahalha" << 666 << "fval" << fval << "dval" << dval //<< "map" << std::map<const char *, int>({{"key", 1}}) << jsend; VLOG(1) << ss.str(); auto js = json::load(ss.str()); EXPECT_TRUE((bool)js); EXPECT_EQ(js.get("fval"), js.get("dval")); } <commit_msg>test variadic json accessors<commit_after>#include "gtest/gtest.h" #include <ten/json.hh> #include <array> #include "ten/logging.hh" #include "ten/jsonstream.hh" #include <map> using namespace std; using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; TEST(Json, Path1) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1{o.path("/store/book/author")}; EXPECT_EQ(json::load(a1), r1); json r2{o.path("//author")}; EXPECT_EQ(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3{o.path("/store/*")}; json t3{json::load(a3)}; EXPECT_EQ(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4{o.path("/store//price")}; EXPECT_EQ(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5{o.path("//book[3]")}; EXPECT_EQ(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6{o.path("/store/book[3]/author")}; EXPECT_EQ(json::load(a6), r6); EXPECT_TRUE(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7{o.path("/store/book[category=\"fiction\"]")}; EXPECT_EQ(json::load(a7), r7); } TEST(Json, Path2) { json o{json::load("[{\"type\": 0}, {\"type\": 1}]")}; EXPECT_EQ(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } TEST(Json, FilterKeyExists) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r{o.path("//book[isbn]")}; EXPECT_EQ(json::load(a), r); json r1{o.path("//book[doesnotexist]")}; ASSERT_TRUE(r1.is_array()); EXPECT_EQ(0u, r1.asize()); } TEST(Json, Truth) { json o{{}}; // empty init list EXPECT_TRUE(o.get("nothing").is_true() == false); EXPECT_TRUE(o.get("nothing").is_false() == false); EXPECT_TRUE(o.get("nothing").is_null() == false); EXPECT_TRUE(!o.get("nothing")); } TEST(Json, Path3) { json o{json::load(json_text)}; ASSERT_TRUE(o.get()); EXPECT_EQ(o, o.path("/")); EXPECT_EQ("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; EXPECT_EQ(json(1), json::load(text).path("/[type=\"b\"]/value")); } TEST(Json, VariadicPath) { json arr = json::array({ 42 }); EXPECT_FALSE(arr.set(0, "foo", 17)); // arr[0] is not an object EXPECT_TRUE(arr.set(1, "foo", 0, "bar")); EXPECT_TRUE(arr.set(2, "bar", "grault")); EXPECT_FALSE(arr.set(1, 1, 1)); // arr[1] is not an array VLOG(1) << "VariadicPath #1: " << arr.dump(JSON_SORT_KEYS | JSON_INDENT(4)); EXPECT_EQ(arr[1]["foo"][0], json{"bar"}); EXPECT_EQ(arr[2]["bar"], json{"grault"}); EXPECT_EQ(arr.get(1, "foo", 0), json{"bar"}); EXPECT_EQ(arr.get(2, "bar"), json{"grault"}); EXPECT_EQ(3u, arr.asize()); EXPECT_EQ(1u, arr[1].osize()); EXPECT_EQ(1u, arr[1]["foo"].asize()); EXPECT_EQ(1u, arr[2].osize()); json obj{ { "foo", json::array({ 17, 42 }) }, }; EXPECT_TRUE(obj.set("foo", 1, "corge")); EXPECT_TRUE(obj.set("bar", "baz", "grault")); EXPECT_FALSE(obj.set("foo", "bar", 1)); // wrong type at second level VLOG(1) << "VariadicPath #2: " << obj.dump(JSON_SORT_KEYS | JSON_INDENT(4)); EXPECT_EQ(obj["foo"][1], json{"corge"}); EXPECT_EQ(obj["bar"]["baz"], json{"grault"}); EXPECT_EQ(obj.get("foo", 1), json{"corge"}); EXPECT_EQ(obj.get("bar", "baz"), json{"grault"}); EXPECT_EQ(obj.osize(), 2u); EXPECT_EQ(obj["foo"].asize(), 2u); } TEST(Json, InitList) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; ASSERT_TRUE((bool)meta); ASSERT_TRUE(meta.is_object()); EXPECT_EQ(meta.osize(), 5u); EXPECT_EQ(meta["foo"].integer(), 17); EXPECT_EQ(meta["corge"][0].integer(), 1); EXPECT_EQ(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); EXPECT_EQ((json_type)j2.type(), t); EXPECT_EQ(j, j2); T val2 = json_cast<T>(j2); EXPECT_EQ(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } TEST(Json, Conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); EXPECT_EQ(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } TEST(Json, Create) { json obj1{{}}; EXPECT_TRUE((bool)obj1); obj1.set("test", "set"); EXPECT_TRUE((bool)obj1.get("test")); json root{ {"obj1", obj1} }; EXPECT_EQ(root.get("obj1"), obj1); obj1.set("this", "that"); EXPECT_EQ(root.get("obj1").get("this").str(), "that"); json obj2{ {"answer", 42} }; obj1.set("obj2", obj2); EXPECT_EQ(root.get("obj1").get("obj2"), obj2); } TEST(Json, Stream) { // TODO: improve these tests or don't. this is a hack anyway using namespace jsonstream_manip; std::stringstream ss; jsonstream s(ss); int8_t c = 'C'; // printable float fval = -1.28; double dval = -1.28; s << jsobject << "key1" << 1234 << "key2" << "value" << "list" << jsarray << "1" << 2.0f << 3.14e-20 << 4 << 5 << jsend << "list2" << jsarray << jsobject << jsend << jsend << "max_dbl" << std::numeric_limits<double>::max() << "inf" << std::numeric_limits<float>::infinity() << "nan" << (1.0 / 0.0) << "vec" << std::vector<int>({0, 1, 2, 3}) << "char" << c << "bool" << false << jsescape << "escape" << "\n\t\"" << "noescape" << "blahblah" << "raw" << jsraw << "[]" << jsnoraw << "lahalha" << 666 << "fval" << fval << "dval" << dval //<< "map" << std::map<const char *, int>({{"key", 1}}) << jsend; VLOG(1) << ss.str(); auto js = json::load(ss.str()); EXPECT_TRUE((bool)js); EXPECT_EQ(js.get("fval"), js.get("dval")); } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE json test #include <boost/test/unit_test.hpp> #include "ten/json.hh" #include "ten/jserial.hh" using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; BOOST_AUTO_TEST_CASE(json_test_path1) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1(o.path("/store/book/author")); BOOST_CHECK_EQUAL(json::load(a1), r1); json r2(o.path("//author")); BOOST_CHECK_EQUAL(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3(o.path("/store/*")); json t3(json::load(a3)); BOOST_CHECK_EQUAL(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4(o.path("/store//price")); BOOST_CHECK_EQUAL(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5(o.path("//book[3]")); BOOST_CHECK_EQUAL(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6(o.path("/store/book[3]/author")); BOOST_CHECK_EQUAL(json::load(a6), r6); BOOST_CHECK(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7(o.path("/store/book[category=\"fiction\"]")); BOOST_CHECK_EQUAL(json::load(a7), r7); } BOOST_AUTO_TEST_CASE(json_test_path2) { json o(json::load("[{\"type\": 0}, {\"type\": 1}]")); BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r(o.path("//book[isbn]")); BOOST_CHECK_EQUAL(json::load(a), r); json r1(o.path("//book[doesnotexist]")); BOOST_REQUIRE(r1.is_array()); BOOST_CHECK_EQUAL(0, r1.asize()); } BOOST_AUTO_TEST_CASE(json_test_truth) { json o(json::object()); BOOST_CHECK(o.get("nothing").is_true() == false); BOOST_CHECK(o.get("nothing").is_false() == false); BOOST_CHECK(o.get("nothing").is_null() == false); BOOST_CHECK(!o.get("nothing")); } BOOST_AUTO_TEST_CASE(json_test_path3) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); BOOST_CHECK_EQUAL(o, o.path("/")); BOOST_CHECK_EQUAL("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value")); } BOOST_AUTO_TEST_CASE(json_init_list) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; BOOST_REQUIRE(meta); BOOST_REQUIRE(meta.is_object()); BOOST_CHECK_EQUAL(meta.osize(), 5); BOOST_CHECK_EQUAL(meta["foo"].integer(), 17); BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1); BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); BOOST_CHECK_EQUAL(j2.type(), t); BOOST_CHECK_EQUAL(j, j2); T val2 = json_cast<T>(j2); BOOST_CHECK_EQUAL(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } BOOST_AUTO_TEST_CASE(json_conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); BOOST_CHECK_EQUAL(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } struct corge { int foo; string bar; corge() : foo(), bar() {} corge(int foo_, string bar_) : foo(foo_), bar(bar_) {} }; template <class AR> inline AR & operator & (AR &ar, corge &c) { return ar & kv("foo", c.foo) & kv("bar", c.bar); } inline bool operator == (const corge &a, const corge &b) { return a.foo == b.foo && a.bar == b.bar; } BOOST_AUTO_TEST_CASE(json_serial) { corge c1(42, "grault"); auto j = jsave_all(c1); cout << "json: " << j.dump() << endl; corge c2; JLoad(j) >> c2; BOOST_CHECK(c1 == c2); #if 0 map<string, int> m; JLoad(j) >> m; cout << "map:"; for (auto v : m) cout << " " << v.first << ":" << v.second; cout << endl; BOOST_CHECK_EQUAL(m.size(), 5); BOOST_CHECK(m.find("bucks") != m.end()); BOOST_CHECK_EQUAL(m["bucks"], 1); #endif } <commit_msg>remove debugging line<commit_after>#define BOOST_TEST_MODULE json test #include <boost/test/unit_test.hpp> #include "ten/json.hh" #include "ten/jserial.hh" using namespace ten; const char json_text[] = "{ \"store\": {" " \"book\": [" " { \"category\": \"reference\"," " \"author\": \"Nigel Rees\"," " \"title\": \"Sayings of the Century\"," " \"price\": 8.95" " }," " { \"category\": \"fiction\"," " \"author\": \"Evelyn Waugh\"," " \"title\": \"Sword of Honour\"," " \"price\": 12.99" " }," " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }" " ]," " \"bicycle\": {" " \"color\": \"red\"," " \"price\": 19.95" " }" " }" "}"; BOOST_AUTO_TEST_CASE(json_test_path1) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]"; json r1(o.path("/store/book/author")); BOOST_CHECK_EQUAL(json::load(a1), r1); json r2(o.path("//author")); BOOST_CHECK_EQUAL(json::load(a1), r2); // jansson hashtable uses size_t for hash // we think this is causing the buckets to change on 32bit vs. 64bit #if (__SIZEOF_SIZE_T__ == 4) static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; #endif json r3(o.path("/store/*")); json t3(json::load(a3)); BOOST_CHECK_EQUAL(t3, r3); #if (__SIZEOF_SIZE_T__ == 4) static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]"; #elif (__SIZEOF_SIZE_T__ == 8) static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]"; #endif json r4(o.path("/store//price")); BOOST_CHECK_EQUAL(json::load(a4), r4); static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}"; json r5(o.path("//book[3]")); BOOST_CHECK_EQUAL(json::load(a5), r5); static const char a6[] = "\"J. R. R. Tolkien\""; json r6(o.path("/store/book[3]/author")); BOOST_CHECK_EQUAL(json::load(a6), r6); BOOST_CHECK(json::load(a6) == r6); static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]"; json r7(o.path("/store/book[category=\"fiction\"]")); BOOST_CHECK_EQUAL(json::load(a7), r7); } BOOST_AUTO_TEST_CASE(json_test_path2) { json o(json::load("[{\"type\": 0}, {\"type\": 1}]")); BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]")); } BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); static const char a[] = "[" " { \"category\": \"fiction\"," " \"author\": \"Herman Melville\"," " \"title\": \"Moby Dick\"," " \"isbn\": \"0-553-21311-3\"," " \"price\": 8.99" " }," " { \"category\": \"fiction\"," " \"author\": \"J. R. R. Tolkien\"," " \"title\": \"The Lord of the Rings\"," " \"isbn\": \"0-395-19395-8\"," " \"price\": 22.99" " }]"; json r(o.path("//book[isbn]")); BOOST_CHECK_EQUAL(json::load(a), r); json r1(o.path("//book[doesnotexist]")); BOOST_REQUIRE(r1.is_array()); BOOST_CHECK_EQUAL(0, r1.asize()); } BOOST_AUTO_TEST_CASE(json_test_truth) { json o(json::object()); BOOST_CHECK(o.get("nothing").is_true() == false); BOOST_CHECK(o.get("nothing").is_false() == false); BOOST_CHECK(o.get("nothing").is_null() == false); BOOST_CHECK(!o.get("nothing")); } BOOST_AUTO_TEST_CASE(json_test_path3) { json o(json::load(json_text)); BOOST_REQUIRE(o.get()); BOOST_CHECK_EQUAL(o, o.path("/")); BOOST_CHECK_EQUAL("Sayings of the Century", o.path("/store/book[category=\"reference\"]/title")); static const char text[] = "[" "{\"type\":\"a\", \"value\":0}," "{\"type\":\"b\", \"value\":1}," "{\"type\":\"c\", \"value\":2}," "{\"type\":\"c\", \"value\":3}" "]"; BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value")); } BOOST_AUTO_TEST_CASE(json_init_list) { json meta{ { "foo", 17 }, { "bar", 23 }, { "baz", true }, { "corge", json::array({ 1, 3.14159 }) }, { "grault", json::array({ "hello", string("world") }) }, }; BOOST_REQUIRE(meta); BOOST_REQUIRE(meta.is_object()); BOOST_CHECK_EQUAL(meta.osize(), 5); BOOST_CHECK_EQUAL(meta["foo"].integer(), 17); BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1); BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world"); } template <class T> inline void test_conv(T val, json j, json_type t) { json j2 = to_json(val); BOOST_CHECK_EQUAL(j2.type(), t); BOOST_CHECK_EQUAL(j, j2); T val2 = json_cast<T>(j2); BOOST_CHECK_EQUAL(val, val2); } template <class T, json_type TYPE = JSON_INTEGER> inline void test_conv_num() { typedef numeric_limits<T> lim; T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() }; for (unsigned i = 0; i < 5; ++i) test_conv<T>(range[i], json(range[i]), TYPE); } BOOST_AUTO_TEST_CASE(json_conversions) { test_conv<string>(string("hello"), json::str("hello"), JSON_STRING); BOOST_CHECK_EQUAL(to_json("world"), json::str("world")); test_conv_num<short>(); test_conv_num<int>(); test_conv_num<long>(); test_conv_num<long long>(); test_conv_num<unsigned short>(); test_conv_num<unsigned>(); #if ULONG_MAX < LLONG_MAX test_conv_num<unsigned long>(); #endif test_conv_num<double, JSON_REAL>(); test_conv_num<float, JSON_REAL>(); test_conv<bool>(true, json::jtrue(), JSON_TRUE); test_conv<bool>(false, json::jfalse(), JSON_FALSE); } struct corge { int foo; string bar; corge() : foo(), bar() {} corge(int foo_, string bar_) : foo(foo_), bar(bar_) {} }; template <class AR> inline AR & operator & (AR &ar, corge &c) { return ar & kv("foo", c.foo) & kv("bar", c.bar); } inline bool operator == (const corge &a, const corge &b) { return a.foo == b.foo && a.bar == b.bar; } BOOST_AUTO_TEST_CASE(json_serial) { corge c1(42, "grault"); auto j = jsave_all(c1); corge c2; JLoad(j) >> c2; BOOST_CHECK(c1 == c2); #if 0 map<string, int> m; JLoad(j) >> m; cout << "map:"; for (auto v : m) cout << " " << v.first << ":" << v.second; cout << endl; BOOST_CHECK_EQUAL(m.size(), 5); BOOST_CHECK(m.find("bucks") != m.end()); BOOST_CHECK_EQUAL(m["bucks"], 1); #endif } <|endoftext|>
<commit_before>#include "Rainback.hpp" #include <lua-cxx/LuaEnvironment.hpp> #include <lua-cxx/LuaValue.hpp> #include <QFile> int main(int argc, char* argv[]) { Lua lua; rainback::Rainback rainback(lua); std::string srcdir(getenv("srcdir")); QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua"); return (bool)lua(testRunner) ? 0 : 1; } <commit_msg>Create a QCoreApplication when testing Lua<commit_after>#include "Rainback.hpp" #include <lua-cxx/LuaEnvironment.hpp> #include <lua-cxx/LuaValue.hpp> #include <QFile> #include <QCoreApplication> int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); Lua lua; rainback::Rainback rainback(lua); std::string srcdir(getenv("srcdir")); QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua"); return (bool)lua(testRunner) ? 0 : 1; } <|endoftext|>
<commit_before>#ifndef TRACE_HPP #define TRACE_HPP #define DO_TRACE #if defined(DO_TRACE) // essential macros #define TRACE_OPEN(filename) trace_open(filename) #define TRACE_FINISH() trace_finish() #define TRACE_PROP(name, value) trace_prop((name), (value)) #include <iostream> #include <fstream> static std::ofstream trace_out; static inline void trace_open(const char* filename) { trace_out.open(filename, std::ofstream::out); } static inline void trace_finish() { trace_out.close(); } template<typename T> static inline void trace_prop(const char* name, const T& value) { trace_out << name << "=" << value << std::endl; } enum class DataType : uint8_t { Edge, Vertex, Property, Weight, Aux }; static inline const char* to_string(DataType tt) { switch (tt) { case DataType::Edge: return "E"; case DataType::Vertex: return "V"; case DataType::Property: return "P"; case DataType::Weight: return "W"; case DataType::Aux: return "A"; default: return "?"; } } enum class AccessType : uint8_t { Read, ReadWrite, Write }; static inline const char* to_string(AccessType tt) { switch (tt) { case AccessType::Read: return "r"; case AccessType::ReadWrite: return "rw"; case AccessType::Write: return "w"; default: return "?"; } } typedef uint64_t IdType; template<typename T> static inline void TRACE_VERTEX_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_READ(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_VERTEX_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_WRITE(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_VERTEX_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_RW(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::ReadWrite, (id), start_addr); } template<typename T> static inline void TRACE_PROP_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_READ(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_PROP_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_WRITE(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_PROP_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_RW(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::ReadWrite, (id), start_addr); } template<typename T> static inline void TRACE_EDGE_READ(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::Read, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_READ(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::Read, id1, id2, start_addr); } template<typename T> static inline void TRACE_EDGE_WRITE(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::Write, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_WRITE(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::Write, id1, id2, start_addr); } template<typename T> static inline void TRACE_EDGE_RW(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::ReadWrite, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_RW(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::ReadWrite, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_READ(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::Read, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_READ(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::Read, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_WRITE(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::Write, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_WRITE(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::Write, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_RW(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::ReadWrite, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_RW(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::ReadWrite, id1, id2, start_addr); } template<typename T> static inline void TRACE_AUX_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_READ(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_AUX_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_WRITE(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_AUX_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_RW(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::ReadWrite, (id), start_addr); } // TODO: trace address range template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id, T* start_addr, long unsigned int size) { trace_out << to_string(data) << "," << id << "," << start_addr << "," << size << std::endl; } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id, T* start_addr) { trace_out << to_string(data) << "," << id << "," << start_addr << "," << sizeof(T) << std::endl; } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_out << to_string(data) << ",<" << id1 << " " << id2 << ">," << start_addr << "," << size << std::endl; } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id1, IdType id2, T* start_addr) { trace_out << to_string(data) << ",<" << id1 << " " << id2 << ">," << start_addr << "," << sizeof(T) << std::endl; } #else #define TRACE_OPEN(filename) #define TRACE_FINISH() #define TRACE_PROP(name, value) #define TRACE_VERTEX_READ(id) #define TRACE_VERTEX_WRITE(id) #define TRACE_EDGE_READ(id) #define TRACE_EDGE_WRITE(id) #endif // short hands / constants #define TRACE_LOAD_GRAPH_VERTEX_COUNT(n) TRACE_PROP("vertex_count", n) #define TRACE_LOAD_GRAPH_EDGE_COUNT(m) TRACE_PROP("edge_count", m) #endif // TRACE_HPP <commit_msg>[trace] only 3 core functions to define format<commit_after>#ifndef TRACE_HPP #define TRACE_HPP #define DO_TRACE #if defined(DO_TRACE) // essential macros #define TRACE_OPEN(filename) trace_open(filename) #define TRACE_FINISH() trace_finish() #define TRACE_PROP(name, value) trace_prop((name), (value)) #include <iostream> #include <fstream> static std::ofstream trace_out; static inline void trace_open(const char* filename) { trace_out.open(filename, std::ofstream::out); } static inline void trace_finish() { trace_out.close(); } typedef uint64_t IdType; enum class DataType : uint8_t { Edge, Vertex, Property, Weight, Aux }; static inline const char* to_string(DataType tt) { switch (tt) { case DataType::Edge: return "E"; case DataType::Vertex: return "V"; case DataType::Property: return "P"; case DataType::Weight: return "W"; case DataType::Aux: return "A"; default: return "?"; } } enum class AccessType : uint8_t { Read, ReadWrite, Write }; static inline const char* to_string(AccessType tt) { switch (tt) { case AccessType::Read: return "r"; case AccessType::ReadWrite: return "rw"; case AccessType::Write: return "w"; default: return "?"; } } template<typename T> static inline void TRACE_VERTEX_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_READ(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_VERTEX_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_WRITE(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_VERTEX_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Vertex, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_VERTEX_RW(IdType id, T* start_addr) { trace_access(DataType::Vertex, AccessType::ReadWrite, (id), start_addr); } template<typename T> static inline void TRACE_PROP_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_READ(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_PROP_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_WRITE(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_PROP_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Property, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_PROP_RW(IdType id, T* start_addr) { trace_access(DataType::Property, AccessType::ReadWrite, (id), start_addr); } template<typename T> static inline void TRACE_EDGE_READ(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::Read, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_READ(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::Read, id1, id2, start_addr); } template<typename T> static inline void TRACE_EDGE_WRITE(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::Write, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_WRITE(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::Write, id1, id2, start_addr); } template<typename T> static inline void TRACE_EDGE_RW(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Edge, AccessType::ReadWrite, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_EDGE_RW(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Edge, AccessType::ReadWrite, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_READ(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::Read, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_READ(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::Read, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_WRITE(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::Write, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_WRITE(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::Write, id1, id2, start_addr); } template<typename T> static inline void TRACE_WEIGHT_RW(IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_access(DataType::Weight, AccessType::ReadWrite, id1, id2, start_addr, size); } template<typename T> static inline void TRACE_WEIGHT_RW(IdType id1, IdType id2, T* start_addr) { trace_access(DataType::Weight, AccessType::ReadWrite, id1, id2, start_addr); } template<typename T> static inline void TRACE_AUX_READ(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::Read, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_READ(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::Read, (id), start_addr); } template<typename T> static inline void TRACE_AUX_WRITE(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::Write, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_WRITE(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::Write, (id), start_addr); } template<typename T> static inline void TRACE_AUX_RW(IdType id, T* start_addr, long unsigned int size) { trace_access(DataType::Aux, AccessType::ReadWrite, (id), start_addr, size); } template<typename T> static inline void TRACE_AUX_RW(IdType id, T* start_addr) { trace_access(DataType::Aux, AccessType::ReadWrite, (id), start_addr); } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id, T* start_addr) { trace_access(data, access, id, start_addr, sizeof(T)); } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id1, IdType id2, T* start_addr) { trace_access(data, access, id1, id2, start_addr, sizeof(T)); } //////////////////////////////////////////////////////////////////////////////// // trace format definition //////////////////////////////////////////////////////////////////////////////// template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id, T* start_addr, long unsigned int size) { trace_out << to_string(data) << "," << id << "," << start_addr << "," << size << std::endl; } template<typename T> static inline void trace_access(DataType data, AccessType access, IdType id1, IdType id2, T* start_addr, long unsigned int size) { trace_out << to_string(data) << ",<" << id1 << " " << id2 << ">," << start_addr << "," << size << std::endl; } template<typename T> static inline void trace_prop(const char* name, const T& value) { trace_out << name << "=" << value << std::endl; } #else #define TRACE_OPEN(filename) #define TRACE_FINISH() #define TRACE_PROP(name, value) #define TRACE_VERTEX_READ(id) #define TRACE_VERTEX_WRITE(id) #define TRACE_EDGE_READ(id) #define TRACE_EDGE_WRITE(id) #endif // short hands / constants #define TRACE_LOAD_GRAPH_VERTEX_COUNT(n) TRACE_PROP("vertex_count", n) #define TRACE_LOAD_GRAPH_EDGE_COUNT(m) TRACE_PROP("edge_count", m) #endif // TRACE_HPP <|endoftext|>
<commit_before>/* * Camera.cpp * Prueba Opengl iPad * * Created by Agustin Trujillo Pino on 24/01/11. * Copyright 2011 Universidad de Las Palmas. All rights reserved. * */ #include "Camera.hpp" #include <string> #include "Sphere.hpp" #include "Sector.hpp" void Camera::initialize(const G3MContext* context) { _planet = context->getPlanet(); if (_planet->isFlat()) { setCartesianPosition( MutableVector3D(0, 0, _planet->getRadii()._y * 5) ); setUp(MutableVector3D(0, 1, 0)); } else { setCartesianPosition( MutableVector3D(_planet->getRadii().maxAxis() * 5, 0, 0) ); setUp(MutableVector3D(0, 0, 1)); } _dirtyFlags.setAll(true); } void Camera::copyFrom(const Camera &that) { //TODO: IMPROVE PERFORMANCE _width = that._width; _height = that._height; _planet = that._planet; _position = MutableVector3D(that._position); _center = MutableVector3D(that._center); _up = MutableVector3D(that._up); _normalizedPosition = MutableVector3D(that._normalizedPosition); _dirtyFlags.copyFrom(that._dirtyFlags); _frustumData = FrustumData(that._frustumData); _projectionMatrix.copyValue(that._projectionMatrix); _modelMatrix.copyValue(that._modelMatrix); _modelViewMatrix.copyValue(that._modelViewMatrix); _cartesianCenterOfView = MutableVector3D(that._cartesianCenterOfView); delete _geodeticCenterOfView; _geodeticCenterOfView = (that._geodeticCenterOfView == NULL) ? NULL : new Geodetic3D(*that._geodeticCenterOfView); delete _frustum; _frustum = (that._frustum == NULL) ? NULL : new Frustum(*that._frustum); delete _frustumInModelCoordinates; _frustumInModelCoordinates = (that._frustumInModelCoordinates == NULL) ? NULL : new Frustum(*that._frustumInModelCoordinates); delete _geodeticPosition; _geodeticPosition = ((that._geodeticPosition == NULL) ? NULL : new Geodetic3D(*that._geodeticPosition)); _angle2Horizon = that._angle2Horizon; _tanHalfVerticalFieldOfView = that._tanHalfVerticalFieldOfView; _tanHalfHorizontalFieldOfView = that._tanHalfHorizontalFieldOfView; } Camera::Camera() : _planet(NULL), _position(0, 0, 0), _center(0, 0, 0), _up(0, 0, 1), _dirtyFlags(), _frustumData(), _projectionMatrix(), _modelMatrix(), _modelViewMatrix(), _cartesianCenterOfView(0,0,0), _geodeticCenterOfView(NULL), _frustum(NULL), _frustumInModelCoordinates(NULL), _camEffectTarget(new CameraEffectTarget()), _geodeticPosition(NULL), _angle2Horizon(-99), _normalizedPosition(0, 0, 0), _tanHalfVerticalFieldOfView(NAND), _tanHalfHorizontalFieldOfView(NAND), _rollInRadians(0) { resizeViewport(0, 0); _dirtyFlags.setAll(true); } void Camera::resizeViewport(int width, int height) { _width = width; _height = height; _dirtyFlags.setAll(true); } void Camera::print() { getModelMatrix().print("Model Matrix", ILogger::instance()); getProjectionMatrix().print("Projection Matrix", ILogger::instance()); getModelViewMatrix().print("ModelView Matrix", ILogger::instance()); ILogger::instance()->logInfo("Width: %d, Height %d\n", _width, _height); } const Angle Camera::getHeading() const{ return getHeadingPitchRoll()._heading; } void Camera::setHeading(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA HEADING: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angle, angles._pitch, angles._roll); setCameraCoordinateSystem(cameraRS); } const Angle Camera::getPitch() const { return getHeadingPitchRoll()._pitch; } void Camera::setPitch(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA PITCH: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angles._heading, angle, angles._roll); setCameraCoordinateSystem(cameraRS); } void Camera::setGeodeticPosition(const Geodetic3D& g3d) { const Angle heading = getHeading(); const Angle pitch = getPitch(); setPitch(Angle::fromDegrees(-90)); MutableMatrix44D dragMatrix = _planet->drag(getGeodeticPosition(), g3d); if (dragMatrix.isValid()) applyTransform(dragMatrix); setHeading(heading); setPitch(pitch); } const Vector3D Camera::pixel2Ray(const Vector2I& pixel) const { const int px = pixel._x; const int py = _height - pixel._y; const Vector3D pixel3D(px, py, 0); const Vector3D obj = getModelViewMatrix().unproject(pixel3D, 0, 0, _width, _height); if (obj.isNan()) { return obj; } return obj.sub(_position.asVector3D()); } const Vector3D Camera::pixel2PlanetPoint(const Vector2I& pixel) const { return _planet->closestIntersection(_position.asVector3D(), pixel2Ray(pixel)); } const Vector2F Camera::point2Pixel(const Vector3D& point) const { const Vector2D p = getModelViewMatrix().project(point, 0, 0, _width, _height); return Vector2F((float) p._x, (float) (_height - p._y) ); } const Vector2F Camera::point2Pixel(const Vector3F& point) const { const Vector2F p = getModelViewMatrix().project(point, 0, 0, _width, _height); return Vector2F(p._x, (_height - p._y) ); } void Camera::applyTransform(const MutableMatrix44D& M) { setCartesianPosition( _position.transformedBy(M, 1.0) ); setCenter( _center.transformedBy(M, 1.0) ); setUp( _up.transformedBy(M, 0.0) ); //_dirtyFlags.setAll(true); } void Camera::dragCamera(const Vector3D& p0, const Vector3D& p1) { // compute the rotation axe const Vector3D rotationAxis = p0.cross(p1); // compute the angle //const Angle rotationDelta = Angle::fromRadians( - acos(p0.normalized().dot(p1.normalized())) ); const Angle rotationDelta = Angle::fromRadians(-IMathUtils::instance()->asin(rotationAxis.length()/p0.length()/p1.length())); if (rotationDelta.isNan()) { return; } rotateWithAxis(rotationAxis, rotationDelta); } void Camera::translateCamera(const Vector3D &desp) { applyTransform(MutableMatrix44D::createTranslationMatrix(desp)); } void Camera::rotateWithAxis(const Vector3D& axis, const Angle& delta) { applyTransform(MutableMatrix44D::createRotationMatrix(delta, axis)); } void Camera::moveForward(double d) { const Vector3D view = getViewDirection().normalized(); applyTransform(MutableMatrix44D::createTranslationMatrix(view.times(d))); } void Camera::pivotOnCenter(const Angle& a) { const Vector3D rotationAxis = _position.sub(_center).asVector3D(); rotateWithAxis(rotationAxis, a); } void Camera::rotateWithAxisAndPoint(const Vector3D& axis, const Vector3D& point, const Angle& delta) { const MutableMatrix44D m = MutableMatrix44D::createGeneralRotationMatrix(delta, axis, point); applyTransform(m); } Vector3D Camera::centerOfViewOnPlanet() const { return _planet->closestIntersection(_position.asVector3D(), getViewDirection()); } Vector3D Camera::getHorizontalVector() { //int todo_remove_get_in_matrix; const MutableMatrix44D M = getModelMatrix(); return Vector3D(M.get0(), M.get4(), M.get8()); } Angle Camera::compute3DAngularDistance(const Vector2I& pixel0, const Vector2I& pixel1) { const Vector3D point0 = pixel2PlanetPoint(pixel0); if (point0.isNan()) { return Angle::nan(); } const Vector3D point1 = pixel2PlanetPoint(pixel1); if (point1.isNan()) { return Angle::nan(); } return point0.angleBetween(point1); } void Camera::setPointOfView(const Geodetic3D& center, double distance, const Angle& azimuth, const Angle& altitude) { // TODO_deal_with_cases_when_center_in_poles const Vector3D cartesianCenter = _planet->toCartesian(center); const Vector3D normal = _planet->geodeticSurfaceNormal(center); const Vector3D north2D = _planet->getNorth().projectionInPlane(normal); const Vector3D orientedVector = north2D.rotateAroundAxis(normal, azimuth.times(-1)); const Vector3D axis = orientedVector.cross(normal); const Vector3D finalVector = orientedVector.rotateAroundAxis(axis, altitude); const Vector3D position = cartesianCenter.add(finalVector.normalized().times(distance)); const Vector3D finalUp = finalVector.rotateAroundAxis(axis, Angle::fromDegrees(90.0f)); setCartesianPosition(position.asMutableVector3D()); setCenter(cartesianCenter.asMutableVector3D()); setUp(finalUp.asMutableVector3D()); // _dirtyFlags.setAll(true); } FrustumData Camera::calculateFrustumData() const { const double height = getGeodeticPosition()._height; double zNear = height * 0.1; double zFar = _planet->distanceToHorizon(_position.asVector3D()); const double goalRatio = 1000; const double ratio = zFar / zNear; if (ratio < goalRatio) { zNear = zFar / goalRatio; } // int __TODO_remove_debug_code; // printf(">>> height=%f zNear=%f zFar=%f ratio=%f\n", // height, // zNear, // zFar, // ratio); // compute rest of frustum numbers double tanHalfHFOV = _tanHalfHorizontalFieldOfView; double tanHalfVFOV = _tanHalfVerticalFieldOfView; if (ISNAN(tanHalfHFOV) || ISNAN(tanHalfVFOV)) { const double ratioScreen = (double) _height / _width; if (ISNAN(tanHalfHFOV) && ISNAN(tanHalfVFOV)) { tanHalfVFOV = 0.3; //Default behaviour _tanHalfFieldOfView = 0.3 => aprox tan(34 degrees / 2) tanHalfHFOV = tanHalfVFOV / ratioScreen; } else { if (ISNAN(tanHalfHFOV)) { tanHalfHFOV = tanHalfVFOV / ratioScreen; } else { if ISNAN(tanHalfVFOV) { tanHalfVFOV = tanHalfHFOV * ratioScreen; } } } } const double right = tanHalfHFOV * zNear; const double left = -right; const double top = tanHalfVFOV * zNear; const double bottom = -top; return FrustumData(left, right, bottom, top, zNear, zFar); } double Camera::getProjectedSphereArea(const Sphere& sphere) const { // this implementation is not right exact, but it's faster. const double z = sphere._center.distanceTo(getCartesianPosition()); const double rWorld = sphere._radius * _frustumData._znear / z; const double rScreen = rWorld * _height / (_frustumData._top - _frustumData._bottom); return PI * rScreen * rScreen; } bool Camera::isPositionWithin(const Sector& sector, double height) const{ const Geodetic3D position = getGeodeticPosition(); return sector.contains(position._latitude, position._longitude) && height >= position._height; } bool Camera::isCenterOfViewWithin(const Sector& sector, double height) const{ const Geodetic3D position = getGeodeticCenterOfView(); return sector.contains(position._latitude, position._longitude) && height >= position._height; } void Camera::setFOV(const Angle& vertical, const Angle& horizontal) { const Angle halfHFOV = horizontal.div(2.0); const Angle halfVFOV = vertical.div(2.0); const double newH = halfHFOV.tangent(); const double newV = halfVFOV.tangent(); if ((newH != _tanHalfHorizontalFieldOfView) || (newV != _tanHalfVerticalFieldOfView)) { _tanHalfHorizontalFieldOfView = newH; _tanHalfVerticalFieldOfView = newV; _dirtyFlags._frustumDataDirty = true; _dirtyFlags._projectionMatrixDirty = true; _dirtyFlags._modelViewMatrixDirty = true; _dirtyFlags._frustumDirty = true; _dirtyFlags._frustumMCDirty = true; } } void Camera::setRoll(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA ROLL: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angles._heading, angles._pitch, angle); setCameraCoordinateSystem(cameraRS); } Angle Camera::getRoll() const { return getHeadingPitchRoll()._roll; } CoordinateSystem Camera::getLocalCoordinateSystem() const{ return _planet->getCoordinateSystemAt(getGeodeticPosition()); } CoordinateSystem Camera::getCameraCoordinateSystem() const{ return CoordinateSystem(getViewDirection(), getUp(), getCartesianPosition()); } void Camera::setCameraCoordinateSystem(const CoordinateSystem& rs) { _center = _position.add(rs._y.asMutableVector3D()); _up = rs._z.asMutableVector3D(); _dirtyFlags.setAll(true); //Recalculate Everything } TaitBryanAngles Camera::getHeadingPitchRoll() const{ const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = getCameraCoordinateSystem(); return cameraRS.getTaitBryanAngles(localRS); } void Camera::setHeadingPitchRoll(const Angle& heading, const Angle& pitch, const Angle& roll) { const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem newCameraRS = localRS.applyTaitBryanAngles(heading, pitch, roll); setCameraCoordinateSystem(newCameraRS); } double Camera::getEstimatedPixelDistance(const Vector3D& point0, const Vector3D& point1) const { //const Vector3D cameraPosition = getCartesianPosition(); const Vector3D ray0 = _position.sub(point0); const Vector3D ray1 = _position.sub(point1); const double angleInRadians = ray1.angleInRadiansBetween(ray0); const FrustumData frustumData = getFrustumData(); const double X = frustumData._znear * IMathUtils::instance()->atan(angleInRadians/2); return X * _height / frustumData._top; } <commit_msg>added Camera::setGeodeticPositionStablePitch()<commit_after>/* * Camera.cpp * Prueba Opengl iPad * * Created by Agustin Trujillo Pino on 24/01/11. * Copyright 2011 Universidad de Las Palmas. All rights reserved. * */ #include "Camera.hpp" #include <string> #include "Sphere.hpp" #include "Sector.hpp" void Camera::initialize(const G3MContext* context) { _planet = context->getPlanet(); if (_planet->isFlat()) { setCartesianPosition( MutableVector3D(0, 0, _planet->getRadii()._y * 5) ); setUp(MutableVector3D(0, 1, 0)); } else { setCartesianPosition( MutableVector3D(_planet->getRadii().maxAxis() * 5, 0, 0) ); setUp(MutableVector3D(0, 0, 1)); } _dirtyFlags.setAll(true); } void Camera::copyFrom(const Camera &that) { //TODO: IMPROVE PERFORMANCE _width = that._width; _height = that._height; _planet = that._planet; _position = MutableVector3D(that._position); _center = MutableVector3D(that._center); _up = MutableVector3D(that._up); _normalizedPosition = MutableVector3D(that._normalizedPosition); _dirtyFlags.copyFrom(that._dirtyFlags); _frustumData = FrustumData(that._frustumData); _projectionMatrix.copyValue(that._projectionMatrix); _modelMatrix.copyValue(that._modelMatrix); _modelViewMatrix.copyValue(that._modelViewMatrix); _cartesianCenterOfView = MutableVector3D(that._cartesianCenterOfView); delete _geodeticCenterOfView; _geodeticCenterOfView = (that._geodeticCenterOfView == NULL) ? NULL : new Geodetic3D(*that._geodeticCenterOfView); delete _frustum; _frustum = (that._frustum == NULL) ? NULL : new Frustum(*that._frustum); delete _frustumInModelCoordinates; _frustumInModelCoordinates = (that._frustumInModelCoordinates == NULL) ? NULL : new Frustum(*that._frustumInModelCoordinates); delete _geodeticPosition; _geodeticPosition = ((that._geodeticPosition == NULL) ? NULL : new Geodetic3D(*that._geodeticPosition)); _angle2Horizon = that._angle2Horizon; _tanHalfVerticalFieldOfView = that._tanHalfVerticalFieldOfView; _tanHalfHorizontalFieldOfView = that._tanHalfHorizontalFieldOfView; } Camera::Camera() : _planet(NULL), _position(0, 0, 0), _center(0, 0, 0), _up(0, 0, 1), _dirtyFlags(), _frustumData(), _projectionMatrix(), _modelMatrix(), _modelViewMatrix(), _cartesianCenterOfView(0,0,0), _geodeticCenterOfView(NULL), _frustum(NULL), _frustumInModelCoordinates(NULL), _camEffectTarget(new CameraEffectTarget()), _geodeticPosition(NULL), _angle2Horizon(-99), _normalizedPosition(0, 0, 0), _tanHalfVerticalFieldOfView(NAND), _tanHalfHorizontalFieldOfView(NAND), _rollInRadians(0) { resizeViewport(0, 0); _dirtyFlags.setAll(true); } void Camera::resizeViewport(int width, int height) { _width = width; _height = height; _dirtyFlags.setAll(true); } void Camera::print() { getModelMatrix().print("Model Matrix", ILogger::instance()); getProjectionMatrix().print("Projection Matrix", ILogger::instance()); getModelViewMatrix().print("ModelView Matrix", ILogger::instance()); ILogger::instance()->logInfo("Width: %d, Height %d\n", _width, _height); } const Angle Camera::getHeading() const{ return getHeadingPitchRoll()._heading; } void Camera::setHeading(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA HEADING: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angle, angles._pitch, angles._roll); setCameraCoordinateSystem(cameraRS); } const Angle Camera::getPitch() const { return getHeadingPitchRoll()._pitch; } void Camera::setPitch(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA PITCH: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angles._heading, angle, angles._roll); setCameraCoordinateSystem(cameraRS); } void Camera::setGeodeticPosition(const Geodetic3D& g3d) { const Angle heading = getHeading(); const Angle pitch = getPitch(); setPitch(Angle::fromDegrees(-90)); MutableMatrix44D dragMatrix = _planet->drag(getGeodeticPosition(), g3d); if (dragMatrix.isValid()) applyTransform(dragMatrix); setHeading(heading); setPitch(pitch); } void Camera::setGeodeticPositionStablePitch(const Geodetic3D& g3d) { MutableMatrix44D dragMatrix = _planet->drag(getGeodeticPosition(), g3d); if (dragMatrix.isValid()) applyTransform(dragMatrix); } const Vector3D Camera::pixel2Ray(const Vector2I& pixel) const { const int px = pixel._x; const int py = _height - pixel._y; const Vector3D pixel3D(px, py, 0); const Vector3D obj = getModelViewMatrix().unproject(pixel3D, 0, 0, _width, _height); if (obj.isNan()) { return obj; } return obj.sub(_position.asVector3D()); } const Vector3D Camera::pixel2PlanetPoint(const Vector2I& pixel) const { return _planet->closestIntersection(_position.asVector3D(), pixel2Ray(pixel)); } const Vector2F Camera::point2Pixel(const Vector3D& point) const { const Vector2D p = getModelViewMatrix().project(point, 0, 0, _width, _height); return Vector2F((float) p._x, (float) (_height - p._y) ); } const Vector2F Camera::point2Pixel(const Vector3F& point) const { const Vector2F p = getModelViewMatrix().project(point, 0, 0, _width, _height); return Vector2F(p._x, (_height - p._y) ); } void Camera::applyTransform(const MutableMatrix44D& M) { setCartesianPosition( _position.transformedBy(M, 1.0) ); setCenter( _center.transformedBy(M, 1.0) ); setUp( _up.transformedBy(M, 0.0) ); //_dirtyFlags.setAll(true); } void Camera::dragCamera(const Vector3D& p0, const Vector3D& p1) { // compute the rotation axe const Vector3D rotationAxis = p0.cross(p1); // compute the angle //const Angle rotationDelta = Angle::fromRadians( - acos(p0.normalized().dot(p1.normalized())) ); const Angle rotationDelta = Angle::fromRadians(-IMathUtils::instance()->asin(rotationAxis.length()/p0.length()/p1.length())); if (rotationDelta.isNan()) { return; } rotateWithAxis(rotationAxis, rotationDelta); } void Camera::translateCamera(const Vector3D &desp) { applyTransform(MutableMatrix44D::createTranslationMatrix(desp)); } void Camera::rotateWithAxis(const Vector3D& axis, const Angle& delta) { applyTransform(MutableMatrix44D::createRotationMatrix(delta, axis)); } void Camera::moveForward(double d) { const Vector3D view = getViewDirection().normalized(); applyTransform(MutableMatrix44D::createTranslationMatrix(view.times(d))); } void Camera::pivotOnCenter(const Angle& a) { const Vector3D rotationAxis = _position.sub(_center).asVector3D(); rotateWithAxis(rotationAxis, a); } void Camera::rotateWithAxisAndPoint(const Vector3D& axis, const Vector3D& point, const Angle& delta) { const MutableMatrix44D m = MutableMatrix44D::createGeneralRotationMatrix(delta, axis, point); applyTransform(m); } Vector3D Camera::centerOfViewOnPlanet() const { return _planet->closestIntersection(_position.asVector3D(), getViewDirection()); } Vector3D Camera::getHorizontalVector() { //int todo_remove_get_in_matrix; const MutableMatrix44D M = getModelMatrix(); return Vector3D(M.get0(), M.get4(), M.get8()); } Angle Camera::compute3DAngularDistance(const Vector2I& pixel0, const Vector2I& pixel1) { const Vector3D point0 = pixel2PlanetPoint(pixel0); if (point0.isNan()) { return Angle::nan(); } const Vector3D point1 = pixel2PlanetPoint(pixel1); if (point1.isNan()) { return Angle::nan(); } return point0.angleBetween(point1); } void Camera::setPointOfView(const Geodetic3D& center, double distance, const Angle& azimuth, const Angle& altitude) { // TODO_deal_with_cases_when_center_in_poles const Vector3D cartesianCenter = _planet->toCartesian(center); const Vector3D normal = _planet->geodeticSurfaceNormal(center); const Vector3D north2D = _planet->getNorth().projectionInPlane(normal); const Vector3D orientedVector = north2D.rotateAroundAxis(normal, azimuth.times(-1)); const Vector3D axis = orientedVector.cross(normal); const Vector3D finalVector = orientedVector.rotateAroundAxis(axis, altitude); const Vector3D position = cartesianCenter.add(finalVector.normalized().times(distance)); const Vector3D finalUp = finalVector.rotateAroundAxis(axis, Angle::fromDegrees(90.0f)); setCartesianPosition(position.asMutableVector3D()); setCenter(cartesianCenter.asMutableVector3D()); setUp(finalUp.asMutableVector3D()); // _dirtyFlags.setAll(true); } FrustumData Camera::calculateFrustumData() const { const double height = getGeodeticPosition()._height; double zNear = height * 0.1; double zFar = _planet->distanceToHorizon(_position.asVector3D()); const double goalRatio = 1000; const double ratio = zFar / zNear; if (ratio < goalRatio) { zNear = zFar / goalRatio; } // int __TODO_remove_debug_code; // printf(">>> height=%f zNear=%f zFar=%f ratio=%f\n", // height, // zNear, // zFar, // ratio); // compute rest of frustum numbers double tanHalfHFOV = _tanHalfHorizontalFieldOfView; double tanHalfVFOV = _tanHalfVerticalFieldOfView; if (ISNAN(tanHalfHFOV) || ISNAN(tanHalfVFOV)) { const double ratioScreen = (double) _height / _width; if (ISNAN(tanHalfHFOV) && ISNAN(tanHalfVFOV)) { tanHalfVFOV = 0.3; //Default behaviour _tanHalfFieldOfView = 0.3 => aprox tan(34 degrees / 2) tanHalfHFOV = tanHalfVFOV / ratioScreen; } else { if (ISNAN(tanHalfHFOV)) { tanHalfHFOV = tanHalfVFOV / ratioScreen; } else { if ISNAN(tanHalfVFOV) { tanHalfVFOV = tanHalfHFOV * ratioScreen; } } } } const double right = tanHalfHFOV * zNear; const double left = -right; const double top = tanHalfVFOV * zNear; const double bottom = -top; return FrustumData(left, right, bottom, top, zNear, zFar); } double Camera::getProjectedSphereArea(const Sphere& sphere) const { // this implementation is not right exact, but it's faster. const double z = sphere._center.distanceTo(getCartesianPosition()); const double rWorld = sphere._radius * _frustumData._znear / z; const double rScreen = rWorld * _height / (_frustumData._top - _frustumData._bottom); return PI * rScreen * rScreen; } bool Camera::isPositionWithin(const Sector& sector, double height) const{ const Geodetic3D position = getGeodeticPosition(); return sector.contains(position._latitude, position._longitude) && height >= position._height; } bool Camera::isCenterOfViewWithin(const Sector& sector, double height) const{ const Geodetic3D position = getGeodeticCenterOfView(); return sector.contains(position._latitude, position._longitude) && height >= position._height; } void Camera::setFOV(const Angle& vertical, const Angle& horizontal) { const Angle halfHFOV = horizontal.div(2.0); const Angle halfVFOV = vertical.div(2.0); const double newH = halfHFOV.tangent(); const double newV = halfVFOV.tangent(); if ((newH != _tanHalfHorizontalFieldOfView) || (newV != _tanHalfVerticalFieldOfView)) { _tanHalfHorizontalFieldOfView = newH; _tanHalfVerticalFieldOfView = newV; _dirtyFlags._frustumDataDirty = true; _dirtyFlags._projectionMatrixDirty = true; _dirtyFlags._modelViewMatrixDirty = true; _dirtyFlags._frustumDirty = true; _dirtyFlags._frustumMCDirty = true; } } void Camera::setRoll(const Angle& angle) { //ILogger::instance()->logInfo("SET CAMERA ROLL: %f", angle._degrees); const TaitBryanAngles angles = getHeadingPitchRoll(); const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = localRS.applyTaitBryanAngles(angles._heading, angles._pitch, angle); setCameraCoordinateSystem(cameraRS); } Angle Camera::getRoll() const { return getHeadingPitchRoll()._roll; } CoordinateSystem Camera::getLocalCoordinateSystem() const{ return _planet->getCoordinateSystemAt(getGeodeticPosition()); } CoordinateSystem Camera::getCameraCoordinateSystem() const{ return CoordinateSystem(getViewDirection(), getUp(), getCartesianPosition()); } void Camera::setCameraCoordinateSystem(const CoordinateSystem& rs) { _center = _position.add(rs._y.asMutableVector3D()); _up = rs._z.asMutableVector3D(); _dirtyFlags.setAll(true); //Recalculate Everything } TaitBryanAngles Camera::getHeadingPitchRoll() const{ const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem cameraRS = getCameraCoordinateSystem(); return cameraRS.getTaitBryanAngles(localRS); } void Camera::setHeadingPitchRoll(const Angle& heading, const Angle& pitch, const Angle& roll) { const CoordinateSystem localRS = getLocalCoordinateSystem(); const CoordinateSystem newCameraRS = localRS.applyTaitBryanAngles(heading, pitch, roll); setCameraCoordinateSystem(newCameraRS); } double Camera::getEstimatedPixelDistance(const Vector3D& point0, const Vector3D& point1) const { //const Vector3D cameraPosition = getCartesianPosition(); const Vector3D ray0 = _position.sub(point0); const Vector3D ray1 = _position.sub(point1); const double angleInRadians = ray1.angleInRadiansBetween(ray0); const FrustumData frustumData = getFrustumData(); const double X = frustumData._znear * IMathUtils::instance()->atan(angleInRadians/2); return X * _height / frustumData._top; } <|endoftext|>
<commit_before>/*** For more information please refer to files in the COPYRIGHT directory ***/ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <time.h> #include <assert.h> #include "irodsFs.hpp" #include "iFuseLib.hpp" #include "iFuseOper.hpp" #include "hashtable.hpp" #include "list.hpp" #include "iFuseLib.Lock.hpp" #undef USE_BOOST /* * An ifuseconn->inuseLock is locked when before it goes from free to inuse and during the whole time it is in use, it is only unlocked when it is unused. */ concurrentList_t *ConnectedConn; concurrentList_t *FreeConn; concurrentList_t *ConnReqWaitQue; static int ConnManagerStarted = 0; void initConn() { ConnectedConn = newConcurrentList(); FreeConn = newConcurrentList(); ConnReqWaitQue = newConcurrentList(); } /* getIFuseConnByPath - try to use the same conn as opened desc of the * same path */ iFuseConn_t *getAndUseConnByPath( char *localPath, int *status ) { iFuseConn_t *iFuseConn; /* make sure iFuseConn is not released after getAndLockIFuseDescByPath finishes */ pathCache_t *tmpPathCache; matchAndLockPathCache( localPath, &tmpPathCache ); if ( tmpPathCache != NULL ) { *status = _getAndUseConnForPathCache( &iFuseConn, tmpPathCache ); UNLOCK_STRUCT( *tmpPathCache ); } else { /* no match. just assign one */ *status = getAndUseIFuseConn( &iFuseConn ); } return iFuseConn; } /* precond: lock paca */ int _getAndUseConnForPathCache( iFuseConn_t **iFuseConn, pathCache_t *paca ) { int status; /* if connection already closed by connection manager, get new ifuseconn */ if ( paca->iFuseConn != NULL ) { LOCK_STRUCT( *( paca->iFuseConn ) ); if ( paca->iFuseConn->conn != NULL ) { if ( paca->iFuseConn->inuseCnt == 0 ) { _useIFuseConn( paca->iFuseConn ); UNLOCK_STRUCT( *( paca->iFuseConn ) ); /* ifuseReconnect(paca->iFuseConn); */ *iFuseConn = paca->iFuseConn; return 0; } else { UNLOCK_STRUCT( *( paca->iFuseConn ) ); } } else { UNLOCK_STRUCT( *( paca->iFuseConn ) ); /* disconnect by not freed yet */ UNREF( paca->iFuseConn, IFuseConn ); } } iFuseConn_t *tmpIFuseConn; UNLOCK_STRUCT( *paca ); status = getAndUseIFuseConn( &tmpIFuseConn ); LOCK_STRUCT( *paca ); if ( status < 0 ) { rodsLog( LOG_ERROR, "ifuseClose: cannot get ifuse connection for %s error, status = %d", paca->localPath, status ); return status; } if ( paca->iFuseConn != NULL ) { /* has been changed by other threads, or current paca->ifuseconn inuse, * return new ifuseconn without setting paca->ifuseconn */ *iFuseConn = tmpIFuseConn; } else { /* conn in use, cannot be deleted by conn manager * therefore, it is safe to do the following without locking conn */ REF( paca->iFuseConn, tmpIFuseConn ); *iFuseConn = paca->iFuseConn; } return 0; } int getAndUseIFuseConn( iFuseConn_t **iFuseConn ) { int ret = _getAndUseIFuseConn( iFuseConn ); return ret; } void _waitForConn() { connReqWait_t myConnReqWait; bzero( &myConnReqWait, sizeof( myConnReqWait ) ); initConnReqWaitMutex( &myConnReqWait ); addToConcurrentList( ConnReqWaitQue, &myConnReqWait ); while ( myConnReqWait.state == 0 ) { timeoutWait( &myConnReqWait.mutex, &myConnReqWait.cond, CONN_REQ_SLEEP_TIME ); } deleteConnReqWaitMutex( &myConnReqWait ); } int _getAndUseIFuseConn( iFuseConn_t **iFuseConn ) { int status; iFuseConn_t *tmpIFuseConn; *iFuseConn = NULL; while ( *iFuseConn == NULL ) { /* get a free IFuseConn */ if ( listSize( ConnectedConn ) >= MAX_NUM_CONN && listSize( FreeConn ) == 0 ) { /* have to wait */ _waitForConn(); /* start from begining */ continue; } else { tmpIFuseConn = ( iFuseConn_t * ) removeFirstElementOfConcurrentList( FreeConn ); if ( tmpIFuseConn == NULL ) { if ( listSize( ConnectedConn ) < MAX_NUM_CONN ) { /* may cause num of conn > max num of conn */ /* get here when nothing free. make one */ tmpIFuseConn = newIFuseConn( &status ); if ( status < 0 ) { _freeIFuseConn( tmpIFuseConn ); return status; } _useFreeIFuseConn( tmpIFuseConn ); addToConcurrentList( ConnectedConn, tmpIFuseConn ); *iFuseConn = tmpIFuseConn; break; } _waitForConn(); continue; } else { useIFuseConn( tmpIFuseConn ); *iFuseConn = tmpIFuseConn; break; } } } /* while *iFuseConn */ if ( ++ConnManagerStarted == HIGH_NUM_CONN ) { /* don't do it the first time */ #ifdef USE_BOOST ConnManagerThr = new boost::thread( connManager ); #else status = pthread_create( &ConnManagerThr, pthread_attr_default, ( void * ( * )( void * ) ) connManager, ( void * ) NULL ); #endif if ( status < 0 ) { ConnManagerStarted--; rodsLog( LOG_ERROR, "pthread_create failure, status = %d", status ); } } return 0; } int useIFuseConn( iFuseConn_t *iFuseConn ) { int status; if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } LOCK_STRUCT( *iFuseConn ); status = _useIFuseConn( iFuseConn ); UNLOCK_STRUCT( *iFuseConn ); return status; } int _useIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } iFuseConn->actTime = time( NULL ); iFuseConn->pendingCnt++; UNLOCK_STRUCT( *iFuseConn ); /* wait for iFuseConn to be unlocked */ LOCK( iFuseConn->inuseLock ); LOCK_STRUCT( *iFuseConn ); iFuseConn->inuseCnt++; iFuseConn->pendingCnt--; /* move unlock to caller site */ /* UNLOCK (ConnLock); */ return 0; } int _useFreeIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL ) { return USER__NULL_INPUT_ERR; } iFuseConn->actTime = time( NULL ); iFuseConn->inuseCnt++; LOCK( iFuseConn->inuseLock ); return 0; } int unuseIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } LOCK_STRUCT( *iFuseConn ); iFuseConn->actTime = time( NULL ); iFuseConn->inuseCnt--; if ( iFuseConn->pendingCnt == 0 ) { addToConcurrentList( FreeConn, iFuseConn ); } UNLOCK_STRUCT( *iFuseConn ); UNLOCK( iFuseConn->inuseLock ); signalConnManager(); return 0; } int ifuseConnect( iFuseConn_t *iFuseConn, rodsEnv *myRodsEnv ) { int status = 0; LOCK_STRUCT( *iFuseConn ); if ( iFuseConn->conn == NULL ) { rErrMsg_t errMsg; iFuseConn->conn = rcConnect( myRodsEnv->rodsHost, myRodsEnv->rodsPort, myRodsEnv->rodsUserName, myRodsEnv->rodsZone, NO_RECONN, &errMsg ); if ( iFuseConn->conn == NULL ) { /* try one more */ iFuseConn->conn = rcConnect( myRodsEnv->rodsHost, myRodsEnv->rodsPort, myRodsEnv->rodsUserName, myRodsEnv->rodsZone, NO_RECONN, &errMsg ); if ( iFuseConn->conn == NULL ) { rodsLogError( LOG_ERROR, errMsg.status, "ifuseConnect: rcConnect failure %s", errMsg.msg ); if ( errMsg.status < 0 ) { return errMsg.status; } else { return -1; } } } status = clientLogin( iFuseConn->conn ); if ( status != 0 ) { rcDisconnect( iFuseConn->conn ); iFuseConn->conn = NULL; } } UNLOCK_STRUCT( *iFuseConn ); return status; } void _ifuseDisconnect( iFuseConn_t *tmpIFuseConn ) { if ( tmpIFuseConn->conn != NULL ) { rcDisconnect( tmpIFuseConn->conn ); tmpIFuseConn->conn = NULL; } } void ifuseDisconnect( iFuseConn_t *tmpIFuseConn ) { LOCK_STRUCT( *tmpIFuseConn ); _ifuseDisconnect( tmpIFuseConn ); UNLOCK_STRUCT( *tmpIFuseConn ); } int signalConnManager() { if ( listSize( ConnectedConn ) > HIGH_NUM_CONN ) { notifyTimeoutWait( &ConnManagerLock, &ConnManagerCond ); } return 0; } int disconnectAll() { iFuseConn_t *tmpIFuseConn; while ( ( tmpIFuseConn = ( iFuseConn_t * ) removeFirstElementOfConcurrentList( ConnectedConn ) ) != NULL ) { ifuseDisconnect( tmpIFuseConn ); } return 0; } /* have to do this after getIFuseConn - lock */ int ifuseReconnect( iFuseConn_t *iFuseConn ) { int status = 0; if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } rodsLog( LOG_DEBUG, "ifuseReconnect: reconnecting" ); ifuseDisconnect( iFuseConn ); status = ifuseConnect( iFuseConn, &MyRodsEnv ); return status; } void connManager() { time_t curTime; iFuseConn_t *tmpIFuseConn; ListNode *node; List *TimeOutList = newListNoRegion(); while ( 1 ) { curTime = time( NULL ); /* exceed high water mark for number of connection ? */ if ( listSize( ConnectedConn ) > HIGH_NUM_CONN ) { LOCK_STRUCT( *ConnectedConn ); int disconnTarget = _listSize( ConnectedConn ) - HIGH_NUM_CONN; node = ConnectedConn->list->head; while ( node != NULL ) { tmpIFuseConn = ( iFuseConn_t * ) node->value; if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) { listAppendNoRegion( TimeOutList, tmpIFuseConn ); node = node->next; } } UNLOCK_STRUCT( *ConnectedConn ); node = TimeOutList->head; int disconned = 0; while ( node != NULL && disconned < disconnTarget ) { tmpIFuseConn = ( iFuseConn_t * ) node->value; LOCK_STRUCT( *tmpIFuseConn ); if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) { removeFromConcurrentList2( FreeConn, tmpIFuseConn ); removeFromConcurrentList2( ConnectedConn, tmpIFuseConn ); if ( tmpIFuseConn->status == 0 ) { /* no struct is referring to it, we can unlock it and free it */ UNLOCK_STRUCT( *tmpIFuseConn ); /* rodsLog(LOG_ERROR, "[FREE IFUSE CONN] %s:%d %p", __FILE__, __LINE__, tmpIFuseConn); */ _freeIFuseConn( tmpIFuseConn ); } else { /* set to timed out */ _ifuseDisconnect( tmpIFuseConn ); UNLOCK_STRUCT( *tmpIFuseConn ); } disconned ++; } else { UNLOCK_STRUCT( *tmpIFuseConn ); } node = node->next; } clearListNoRegion( TimeOutList ); } while ( listSize( ConnectedConn ) <= MAX_NUM_CONN || listSize( FreeConn ) != 0 ) { /* signal one in the wait queue */ connReqWait_t *myConnReqWait = ( connReqWait_t * ) removeFirstElementOfConcurrentList( ConnReqWaitQue ); /* if there is no conn req left, exit loop */ if ( myConnReqWait == NULL ) { break; } myConnReqWait->state = 1; notifyTimeoutWait( &myConnReqWait->mutex, &myConnReqWait->cond ); } #if 0 rodsSleep( CONN_MANAGER_SLEEP_TIME, 0 ); #else timeoutWait( &ConnManagerLock, &ConnManagerCond, CONN_MANAGER_SLEEP_TIME ); #endif } deleteListNoRegion( TimeOutList ); } <commit_msg>[#2212] CID49417:<commit_after>/*** For more information please refer to files in the COPYRIGHT directory ***/ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <time.h> #include <assert.h> #include "irodsFs.hpp" #include "iFuseLib.hpp" #include "iFuseOper.hpp" #include "hashtable.hpp" #include "list.hpp" #include "iFuseLib.Lock.hpp" #undef USE_BOOST /* * An ifuseconn->inuseLock is locked when before it goes from free to inuse and during the whole time it is in use, it is only unlocked when it is unused. */ concurrentList_t *ConnectedConn; concurrentList_t *FreeConn; concurrentList_t *ConnReqWaitQue; static int ConnManagerStarted = 0; void initConn() { ConnectedConn = newConcurrentList(); FreeConn = newConcurrentList(); ConnReqWaitQue = newConcurrentList(); } /* getIFuseConnByPath - try to use the same conn as opened desc of the * same path */ iFuseConn_t *getAndUseConnByPath( char *localPath, int *status ) { iFuseConn_t *iFuseConn; /* make sure iFuseConn is not released after getAndLockIFuseDescByPath finishes */ pathCache_t *tmpPathCache; matchAndLockPathCache( localPath, &tmpPathCache ); if ( tmpPathCache != NULL ) { *status = _getAndUseConnForPathCache( &iFuseConn, tmpPathCache ); UNLOCK_STRUCT( *tmpPathCache ); } else { /* no match. just assign one */ *status = getAndUseIFuseConn( &iFuseConn ); } return iFuseConn; } /* precond: lock paca */ int _getAndUseConnForPathCache( iFuseConn_t **iFuseConn, pathCache_t *paca ) { int status; /* if connection already closed by connection manager, get new ifuseconn */ if ( paca->iFuseConn != NULL ) { LOCK_STRUCT( *( paca->iFuseConn ) ); if ( paca->iFuseConn->conn != NULL ) { if ( paca->iFuseConn->inuseCnt == 0 ) { _useIFuseConn( paca->iFuseConn ); UNLOCK_STRUCT( *( paca->iFuseConn ) ); /* ifuseReconnect(paca->iFuseConn); */ *iFuseConn = paca->iFuseConn; return 0; } else { UNLOCK_STRUCT( *( paca->iFuseConn ) ); } } else { UNLOCK_STRUCT( *( paca->iFuseConn ) ); /* disconnect by not freed yet */ UNREF( paca->iFuseConn, IFuseConn ); } } iFuseConn_t *tmpIFuseConn; UNLOCK_STRUCT( *paca ); status = getAndUseIFuseConn( &tmpIFuseConn ); LOCK_STRUCT( *paca ); if ( status < 0 ) { rodsLog( LOG_ERROR, "ifuseClose: cannot get ifuse connection for %s error, status = %d", paca->localPath, status ); return status; } if ( paca->iFuseConn != NULL ) { /* has been changed by other threads, or current paca->ifuseconn inuse, * return new ifuseconn without setting paca->ifuseconn */ *iFuseConn = tmpIFuseConn; } else { /* conn in use, cannot be deleted by conn manager * therefore, it is safe to do the following without locking conn */ REF( paca->iFuseConn, tmpIFuseConn ); *iFuseConn = paca->iFuseConn; } return 0; } int getAndUseIFuseConn( iFuseConn_t **iFuseConn ) { int ret = _getAndUseIFuseConn( iFuseConn ); return ret; } void _waitForConn() { connReqWait_t myConnReqWait; bzero( &myConnReqWait, sizeof( myConnReqWait ) ); initConnReqWaitMutex( &myConnReqWait ); addToConcurrentList( ConnReqWaitQue, &myConnReqWait ); while ( myConnReqWait.state == 0 ) { timeoutWait( &myConnReqWait.mutex, &myConnReqWait.cond, CONN_REQ_SLEEP_TIME ); } deleteConnReqWaitMutex( &myConnReqWait ); } int _getAndUseIFuseConn( iFuseConn_t **iFuseConn ) { int status; iFuseConn_t *tmpIFuseConn; *iFuseConn = NULL; while ( *iFuseConn == NULL ) { /* get a free IFuseConn */ if ( listSize( ConnectedConn ) >= MAX_NUM_CONN && listSize( FreeConn ) == 0 ) { /* have to wait */ _waitForConn(); /* start from begining */ continue; } else { tmpIFuseConn = ( iFuseConn_t * ) removeFirstElementOfConcurrentList( FreeConn ); if ( tmpIFuseConn == NULL ) { if ( listSize( ConnectedConn ) < MAX_NUM_CONN ) { /* may cause num of conn > max num of conn */ /* get here when nothing free. make one */ tmpIFuseConn = newIFuseConn( &status ); if ( status < 0 ) { _freeIFuseConn( tmpIFuseConn ); return status; } _useFreeIFuseConn( tmpIFuseConn ); addToConcurrentList( ConnectedConn, tmpIFuseConn ); *iFuseConn = tmpIFuseConn; break; } _waitForConn(); continue; } else { useIFuseConn( tmpIFuseConn ); *iFuseConn = tmpIFuseConn; break; } } } /* while *iFuseConn */ if ( ++ConnManagerStarted == HIGH_NUM_CONN ) { /* don't do it the first time */ #ifdef USE_BOOST ConnManagerThr = new boost::thread( connManager ); #else status = pthread_create( &ConnManagerThr, pthread_attr_default, ( void * ( * )( void * ) ) connManager, ( void * ) NULL ); #endif if ( status < 0 ) { ConnManagerStarted--; rodsLog( LOG_ERROR, "pthread_create failure, status = %d", status ); } } return 0; } int useIFuseConn( iFuseConn_t *iFuseConn ) { int status; if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } LOCK_STRUCT( *iFuseConn ); status = _useIFuseConn( iFuseConn ); UNLOCK_STRUCT( *iFuseConn ); return status; } int _useIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } iFuseConn->actTime = time( NULL ); iFuseConn->pendingCnt++; UNLOCK_STRUCT( *iFuseConn ); /* wait for iFuseConn to be unlocked */ LOCK( iFuseConn->inuseLock ); LOCK_STRUCT( *iFuseConn ); iFuseConn->inuseCnt++; iFuseConn->pendingCnt--; /* move unlock to caller site */ /* UNLOCK (ConnLock); */ return 0; } int _useFreeIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL ) { return USER__NULL_INPUT_ERR; } iFuseConn->actTime = time( NULL ); iFuseConn->inuseCnt++; LOCK( iFuseConn->inuseLock ); return 0; } int unuseIFuseConn( iFuseConn_t *iFuseConn ) { if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } LOCK_STRUCT( *iFuseConn ); iFuseConn->actTime = time( NULL ); iFuseConn->inuseCnt--; if ( iFuseConn->pendingCnt == 0 ) { addToConcurrentList( FreeConn, iFuseConn ); } UNLOCK_STRUCT( *iFuseConn ); UNLOCK( iFuseConn->inuseLock ); signalConnManager(); return 0; } int ifuseConnect( iFuseConn_t *iFuseConn, rodsEnv *myRodsEnv ) { int status = 0; LOCK_STRUCT( *iFuseConn ); if ( iFuseConn->conn == NULL ) { rErrMsg_t errMsg; iFuseConn->conn = rcConnect( myRodsEnv->rodsHost, myRodsEnv->rodsPort, myRodsEnv->rodsUserName, myRodsEnv->rodsZone, NO_RECONN, &errMsg ); if ( iFuseConn->conn == NULL ) { /* try one more */ iFuseConn->conn = rcConnect( myRodsEnv->rodsHost, myRodsEnv->rodsPort, myRodsEnv->rodsUserName, myRodsEnv->rodsZone, NO_RECONN, &errMsg ); if ( iFuseConn->conn == NULL ) { rodsLogError( LOG_ERROR, errMsg.status, "ifuseConnect: rcConnect failure %s", errMsg.msg ); UNLOCK_STRUCT( *iFuseConn ); if ( errMsg.status < 0 ) { return errMsg.status; } else { return -1; } } } status = clientLogin( iFuseConn->conn ); if ( status != 0 ) { rcDisconnect( iFuseConn->conn ); iFuseConn->conn = NULL; } } UNLOCK_STRUCT( *iFuseConn ); return status; } void _ifuseDisconnect( iFuseConn_t *tmpIFuseConn ) { if ( tmpIFuseConn->conn != NULL ) { rcDisconnect( tmpIFuseConn->conn ); tmpIFuseConn->conn = NULL; } } void ifuseDisconnect( iFuseConn_t *tmpIFuseConn ) { LOCK_STRUCT( *tmpIFuseConn ); _ifuseDisconnect( tmpIFuseConn ); UNLOCK_STRUCT( *tmpIFuseConn ); } int signalConnManager() { if ( listSize( ConnectedConn ) > HIGH_NUM_CONN ) { notifyTimeoutWait( &ConnManagerLock, &ConnManagerCond ); } return 0; } int disconnectAll() { iFuseConn_t *tmpIFuseConn; while ( ( tmpIFuseConn = ( iFuseConn_t * ) removeFirstElementOfConcurrentList( ConnectedConn ) ) != NULL ) { ifuseDisconnect( tmpIFuseConn ); } return 0; } /* have to do this after getIFuseConn - lock */ int ifuseReconnect( iFuseConn_t *iFuseConn ) { int status = 0; if ( iFuseConn == NULL || iFuseConn->conn == NULL ) { return USER__NULL_INPUT_ERR; } rodsLog( LOG_DEBUG, "ifuseReconnect: reconnecting" ); ifuseDisconnect( iFuseConn ); status = ifuseConnect( iFuseConn, &MyRodsEnv ); return status; } void connManager() { time_t curTime; iFuseConn_t *tmpIFuseConn; ListNode *node; List *TimeOutList = newListNoRegion(); while ( 1 ) { curTime = time( NULL ); /* exceed high water mark for number of connection ? */ if ( listSize( ConnectedConn ) > HIGH_NUM_CONN ) { LOCK_STRUCT( *ConnectedConn ); int disconnTarget = _listSize( ConnectedConn ) - HIGH_NUM_CONN; node = ConnectedConn->list->head; while ( node != NULL ) { tmpIFuseConn = ( iFuseConn_t * ) node->value; if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) { listAppendNoRegion( TimeOutList, tmpIFuseConn ); node = node->next; } } UNLOCK_STRUCT( *ConnectedConn ); node = TimeOutList->head; int disconned = 0; while ( node != NULL && disconned < disconnTarget ) { tmpIFuseConn = ( iFuseConn_t * ) node->value; LOCK_STRUCT( *tmpIFuseConn ); if ( tmpIFuseConn->inuseCnt == 0 && tmpIFuseConn->pendingCnt == 0 && curTime - tmpIFuseConn->actTime > IFUSE_CONN_TIMEOUT ) { removeFromConcurrentList2( FreeConn, tmpIFuseConn ); removeFromConcurrentList2( ConnectedConn, tmpIFuseConn ); if ( tmpIFuseConn->status == 0 ) { /* no struct is referring to it, we can unlock it and free it */ UNLOCK_STRUCT( *tmpIFuseConn ); /* rodsLog(LOG_ERROR, "[FREE IFUSE CONN] %s:%d %p", __FILE__, __LINE__, tmpIFuseConn); */ _freeIFuseConn( tmpIFuseConn ); } else { /* set to timed out */ _ifuseDisconnect( tmpIFuseConn ); UNLOCK_STRUCT( *tmpIFuseConn ); } disconned ++; } else { UNLOCK_STRUCT( *tmpIFuseConn ); } node = node->next; } clearListNoRegion( TimeOutList ); } while ( listSize( ConnectedConn ) <= MAX_NUM_CONN || listSize( FreeConn ) != 0 ) { /* signal one in the wait queue */ connReqWait_t *myConnReqWait = ( connReqWait_t * ) removeFirstElementOfConcurrentList( ConnReqWaitQue ); /* if there is no conn req left, exit loop */ if ( myConnReqWait == NULL ) { break; } myConnReqWait->state = 1; notifyTimeoutWait( &myConnReqWait->mutex, &myConnReqWait->cond ); } #if 0 rodsSleep( CONN_MANAGER_SLEEP_TIME, 0 ); #else timeoutWait( &ConnManagerLock, &ConnManagerCond, CONN_MANAGER_SLEEP_TIME ); #endif } deleteListNoRegion( TimeOutList ); } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Color.hpp> # include <Siv3D/ColorF.hpp> # include <Siv3D/FormatInt.hpp> namespace s3d { namespace detail { [[nodiscard]] inline double RemoveSRGBCurve(double x) { return ((x < 0.04045) ? (x / 12.92) : std::pow((x + 0.055) / 1.055, 2.4)); } [[nodiscard]] inline double ApplySRGBCurve(double x) { return ((x < 0.0031308) ? (12.92 * x) : (1.055 * std::pow(x, (1.0 / 2.4)) - 0.055)); } } void Color::_Formatter(FormatData& formatData, const Color& value) { const size_t bufferSize = (detail::Uint32Width * 4) + 8 + 1; char32 buf[bufferSize]; char32* p = buf; *(p++) = U'('; detail::AppendInt32(&p, value.r); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.g); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.b); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.a); *(p++) = U')'; formatData.string.append(buf, p - buf); } ColorF ColorF::removeSRGBCurve() const noexcept { return{ detail::RemoveSRGBCurve(r), detail::RemoveSRGBCurve(g), detail::RemoveSRGBCurve(b), a }; } ColorF ColorF::applySRGBCurve() const noexcept { return{ detail::ApplySRGBCurve(r), detail::ApplySRGBCurve(g), detail::ApplySRGBCurve(b), a }; } } <commit_msg>[共通] fix<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/ColorHSV.hpp> # include <Siv3D/FormatInt.hpp> namespace s3d { namespace detail { [[nodiscard]] inline double RemoveSRGBCurve(double x) { return ((x < 0.04045) ? (x / 12.92) : std::pow((x + 0.055) / 1.055, 2.4)); } [[nodiscard]] inline double ApplySRGBCurve(double x) { return ((x < 0.0031308) ? (12.92 * x) : (1.055 * std::pow(x, (1.0 / 2.4)) - 0.055)); } } void Color::_Formatter(FormatData& formatData, const Color& value) { const size_t bufferSize = (detail::Uint32Width * 4) + 8 + 1; char32 buf[bufferSize]; char32* p = buf; *(p++) = U'('; detail::AppendInt32(&p, value.r); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.g); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.b); *(p++) = U','; *(p++) = U' '; detail::AppendInt32(&p, value.a); *(p++) = U')'; formatData.string.append(buf, p - buf); } ColorF ColorF::removeSRGBCurve() const noexcept { return{ detail::RemoveSRGBCurve(r), detail::RemoveSRGBCurve(g), detail::RemoveSRGBCurve(b), a }; } ColorF ColorF::applySRGBCurve() const noexcept { return{ detail::ApplySRGBCurve(r), detail::ApplySRGBCurve(g), detail::ApplySRGBCurve(b), a }; } } <|endoftext|>
<commit_before>#ifndef GP_NODE_BASIC_OPERATION_NODE #define GP_NODE_BASIC_OPERATION_NODE #include "node_base.hpp" #include <gp/utility/left_hand_value.hpp> namespace gp::node { template <typename T> class SubstitutionNode: public NodeBase<T(utility::LeftHandValue<T>, T)> { using ThisType = SubstitutionNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto lvalue = std::get<0>(this->children)->evaluate(evaluationContext); if(!lvalue) { evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidLeftHandValue); return utility::getDefaultValue<T>(); } lvalue.getRef() = std::get<1>(this->children)->evaluate(evaluationContext); return lvalue.getRef(); } public: std::string getNodeName()const override { return std::string("Substitute[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() + std::declval<T>())> > > class AddNode: public NodeBase<T(T, T)> { using ThisType = AddNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 + a2; } public: std::string getNodeName()const override { return std::string("Add[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() - std::declval<T>())> > > class SubtractNode: public NodeBase<T(T, T)> { using ThisType = SubtractNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 - a2; } public: std::string getNodeName()const override { return std::string("Sub[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() * std::declval<T>())> > > class MultiplyNode: public NodeBase<T(T, T)> { using ThisType = MultiplyNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 * a2; } public: std::string getNodeName()const override { return std::string("Mult[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> class DivisionNode: public NodeBase<T(T, T)> { using ThisType = DivisionNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [c1, c2] = evaluateChildren(this->children, evaluationContext); if(c2 == 0){ evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidValue); return utility::getDefaultValue<T>(); } return c1 / c2; } public: std::string getNodeName()const override { return std::string("Div[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class AndNode: public NodeBase<bool(bool, bool)> { using ThisType = AndNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [b1, b2] = evaluateChildren(this->children, evaluationContext); return b1 && b2; } public: std::string getNodeName()const override {return std::string("AND");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class OrNode: public NodeBase<bool(bool, bool)> { using ThisType = OrNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [b1, b2] = evaluateChildren(this->children, evaluationContext); return b1 || b2; } public: std::string getNodeName()const override {return std::string("OR");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class NotNode: public NodeBase<bool(bool)> { using ThisType = NotNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { return !std::get<0>(this->children)->evaluate(evaluationContext); } public: std::string getNodeName()const override {return std::string("NOT");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T> class IfNode: public NodeBase<T(bool, T, T)> { using ThisType = IfNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto cond = std::get<0>(this->children)->evaluate(evaluationContext); if(cond) { return std::get<1>(this->children)->evaluate(evaluationContext); } else { return std::get<2>(this->children)->evaluate(evaluationContext); } } public: std::string getNodeName()const override { return std::string("If[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() > std::declval<T>())> > > class GreaterNode: public NodeBase<bool(T, T)> { using ThisType = GreaterNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 > a2; } public: std::string getNodeName()const override { return std::string("Greater[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() >= std::declval<T>())> > > class GreaterEqNode: public NodeBase<bool(T, T)> { using ThisType = GreaterEqNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 >= a2; } public: std::string getNodeName()const override { return std::string("GreaterEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() < std::declval<T>())> > > class LessThanNode: public NodeBase<bool(T, T)> { using ThisType = LessThanNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 < a2; } public: std::string getNodeName()const override { return std::string("Less[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() <= std::declval<T>())> > > class LessThanEqNode: public NodeBase<bool(T, T)> { using ThisType = LessThanEqNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 <= a2; } public: std::string getNodeName()const override { return std::string("LessEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() == std::declval<T>())> > > class EqualNode: public NodeBase<bool(T, T)> { using ThisType = EqualNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 == a2; } public: std::string getNodeName()const override { return std::string("Eq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() != std::declval<T>())> > > class NotEqualNode: public NodeBase<bool(T, T)> { using ThisType = NotEqualNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 != a2; } public: std::string getNodeName()const override { return std::string("NotEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T> class NopNode: public NodeBase<T(void)> { using ThisType = NopNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { return utility::getDefaultValue<T>(); } public: std::string getNodeName()const override { return std::string("Nop[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; //0th child: number of repeat, 1st child: evaluated repeatedly template <typename T1, typename T2, typename = std::enable_if_t<std::is_integral_v<T2>>> class RepeatNode: public NodeBase<T1(T2, T1)> { using ThisType = RepeatNode; using node_instance_type = NodeInterface::node_instance_type; private: T1 evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto num = std::get<0>(this->children)->evaluate(evaluationContext); if(num < 0) { evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidValue); return utility::getDefaultValue<T1>(); } auto ans = utility::getDefaultValue<T1>(); for(T2 i = 0; i < num - 1; ++i) { auto ans = std::get<1>(this->children)->evaluate(evaluationContext); if(evaluationContext.getEvaluationStatus() == utility::EvaluationStatus::BreakCalled) { evaluationContext.clearEvaluationStatus(); break; } else if (evaluationContext.getEvaluationStatus() == utility::EvaluationStatus::ContinueCalled) { evaluationContext.clearEvaluationStatus(); continue; } else if (evaluationContext.getEvaluationStatus() != utility::EvaluationStatus::Evaluating) { return utility::getDefaultValue<T1>(); } } return ans; } public: std::string getNodeName()const override { return std::string("Repeat[") + utility::typeInfo<T1>().name() + "," + utility::typeInfo<T2>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; } #endif <commit_msg>fix bug in RepeatNode<commit_after>#ifndef GP_NODE_BASIC_OPERATION_NODE #define GP_NODE_BASIC_OPERATION_NODE #include "node_base.hpp" #include <gp/utility/left_hand_value.hpp> namespace gp::node { template <typename T> class SubstitutionNode: public NodeBase<T(utility::LeftHandValue<T>, T)> { using ThisType = SubstitutionNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto lvalue = std::get<0>(this->children)->evaluate(evaluationContext); if(!lvalue) { evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidLeftHandValue); return utility::getDefaultValue<T>(); } lvalue.getRef() = std::get<1>(this->children)->evaluate(evaluationContext); return lvalue.getRef(); } public: std::string getNodeName()const override { return std::string("Substitute[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() + std::declval<T>())> > > class AddNode: public NodeBase<T(T, T)> { using ThisType = AddNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 + a2; } public: std::string getNodeName()const override { return std::string("Add[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() - std::declval<T>())> > > class SubtractNode: public NodeBase<T(T, T)> { using ThisType = SubtractNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 - a2; } public: std::string getNodeName()const override { return std::string("Sub[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<T, decltype(std::declval<T>() * std::declval<T>())> > > class MultiplyNode: public NodeBase<T(T, T)> { using ThisType = MultiplyNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 * a2; } public: std::string getNodeName()const override { return std::string("Mult[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> class DivisionNode: public NodeBase<T(T, T)> { using ThisType = DivisionNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [c1, c2] = evaluateChildren(this->children, evaluationContext); if(c2 == 0){ evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidValue); return utility::getDefaultValue<T>(); } return c1 / c2; } public: std::string getNodeName()const override { return std::string("Div[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class AndNode: public NodeBase<bool(bool, bool)> { using ThisType = AndNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [b1, b2] = evaluateChildren(this->children, evaluationContext); return b1 && b2; } public: std::string getNodeName()const override {return std::string("AND");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class OrNode: public NodeBase<bool(bool, bool)> { using ThisType = OrNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [b1, b2] = evaluateChildren(this->children, evaluationContext); return b1 || b2; } public: std::string getNodeName()const override {return std::string("OR");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; class NotNode: public NodeBase<bool(bool)> { using ThisType = NotNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { return !std::get<0>(this->children)->evaluate(evaluationContext); } public: std::string getNodeName()const override {return std::string("NOT");} node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T> class IfNode: public NodeBase<T(bool, T, T)> { using ThisType = IfNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto cond = std::get<0>(this->children)->evaluate(evaluationContext); if(cond) { return std::get<1>(this->children)->evaluate(evaluationContext); } else { return std::get<2>(this->children)->evaluate(evaluationContext); } } public: std::string getNodeName()const override { return std::string("If[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() > std::declval<T>())> > > class GreaterNode: public NodeBase<bool(T, T)> { using ThisType = GreaterNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 > a2; } public: std::string getNodeName()const override { return std::string("Greater[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() >= std::declval<T>())> > > class GreaterEqNode: public NodeBase<bool(T, T)> { using ThisType = GreaterEqNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 >= a2; } public: std::string getNodeName()const override { return std::string("GreaterEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() < std::declval<T>())> > > class LessThanNode: public NodeBase<bool(T, T)> { using ThisType = LessThanNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 < a2; } public: std::string getNodeName()const override { return std::string("Less[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() <= std::declval<T>())> > > class LessThanEqNode: public NodeBase<bool(T, T)> { using ThisType = LessThanEqNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 <= a2; } public: std::string getNodeName()const override { return std::string("LessEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() == std::declval<T>())> > > class EqualNode: public NodeBase<bool(T, T)> { using ThisType = EqualNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 == a2; } public: std::string getNodeName()const override { return std::string("Eq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T, typename = std::enable_if_t< std::is_convertible_v<bool, decltype(std::declval<T>() != std::declval<T>())> > > class NotEqualNode: public NodeBase<bool(T, T)> { using ThisType = NotEqualNode; using node_instance_type = NodeInterface::node_instance_type; private: bool evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto [a1, a2] = evaluateChildren(this->children, evaluationContext); return a1 != a2; } public: std::string getNodeName()const override { return std::string("NotEq[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; template <typename T> class NopNode: public NodeBase<T(void)> { using ThisType = NopNode; using node_instance_type = NodeInterface::node_instance_type; private: T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { return utility::getDefaultValue<T>(); } public: std::string getNodeName()const override { return std::string("Nop[") + utility::typeInfo<T>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; //0th child: number of repeat, 1st child: evaluated repeatedly template <typename T1, typename T2, typename = std::enable_if_t<std::is_integral_v<T2>>> class RepeatNode: public NodeBase<T1(T2, T1)> { using ThisType = RepeatNode; using node_instance_type = NodeInterface::node_instance_type; private: T1 evaluationDefinition(utility::EvaluationContext& evaluationContext)const override { auto num = std::get<0>(this->children)->evaluate(evaluationContext); if(num < 0) { evaluationContext.setEvaluationStatusWithoutUpdate(utility::EvaluationStatus::InvalidValue); return utility::getDefaultValue<T1>(); } auto ans = utility::getDefaultValue<T1>(); for(T2 i = 0; i < num; ++i) { auto ans = std::get<1>(this->children)->evaluate(evaluationContext); if(evaluationContext.getEvaluationStatus() == utility::EvaluationStatus::BreakCalled) { evaluationContext.clearEvaluationStatus(); break; } else if (evaluationContext.getEvaluationStatus() == utility::EvaluationStatus::ContinueCalled) { evaluationContext.clearEvaluationStatus(); continue; } else if (evaluationContext.getEvaluationStatus() != utility::EvaluationStatus::Evaluating) { return utility::getDefaultValue<T1>(); } } return ans; } public: std::string getNodeName()const override { return std::string("Repeat[") + utility::typeInfo<T1>().name() + "," + utility::typeInfo<T2>().name() + std::string("]"); } node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>();} }; } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __IGN_TRANSPORT_REQHANDLER_HH_INCLUDED__ #define __IGN_TRANSPORT_REQHANDLER_HH_INCLUDED__ #include <google/protobuf/message.h> #include <uuid/uuid.h> #include <condition_variable> #include <functional> #include <iostream> #include <memory> #include <string> #include "ignition/transport/Packet.hh" #include "ignition/transport/TransportTypes.hh" namespace ignition { namespace transport { /// \class IReqHandler ReqHandler.hh /// \brief Interface class used to manage a request handler. class IReqHandler { /// \brief Constructor. /// \param[in] _uuid UUID of the node registering the request handler. public: IReqHandler(const std::string &_nUuid) : nUuidStr(_nUuid), requested(false), repAvailable(false), result(false) { uuid_t uuid; uuid_generate(uuid); this->hUuid = GetGuidStr(uuid); } /// \brief Destructor. public: virtual ~IReqHandler() { } /// \brief Executes the local callback registered for this handler. /// \param[in] _topic Topic to be passed to the callback. /// \param[in] _msg Protobuf message received. /// \return 0 when success. /* public: virtual int RunLocalCallback(const std::string &_topic, const transport::ProtoMsg &_msg) = 0; */ /// \brief Executes the callback registered for this handler. /// \param[in] _topic Topic to be passed to the callback. /// \param[in] _data Serialized data received. The data will be used /// to compose a specific protobuf message and will be passed to the /// callback function. /// \return 0 when success. public: virtual void NotifyResult(const std::string &_topic, const std::string &_rep, const bool _result) = 0; /// \brief Get the node UUID. /// \return The string representation of the node UUID. public: std::string GetNodeUuid() { return this->nUuidStr; } /// \brief public: bool Requested() const { return this->requested; } /// \brief public: void SetRequested(bool _value) { this->requested = _value; } /// \brief public: virtual std::string Serialize() = 0; /// \brief public: std::string GetHandlerUuid() const { return this->hUuid; } /// \brief Unique handler's UUID. protected: std::string hUuid; /// \brief Node UUID (string). private: std::string nUuidStr; /// \brief When true, the REQ was already sent and the REP should be on /// its way. Used to not resend the same REQ more than one time. private: bool requested; /// \brief public: bool repAvailable; /// \brief public: std::condition_variable_any condition; /// \brief public: std::string rep; /// \brief public: bool result; }; /// \class ReqHandler ReqHandler.hh /// \brief It creates service reply handlers for each specific protobuf /// message used. template <typename T1, typename T2> class ReqHandler : public IReqHandler { // Documentation inherited. public: ReqHandler(const std::string &_nUuid) : IReqHandler(_nUuid) { } /// \brief Create a specific protobuf message given its serialized data. /// \param[in] _data The serialized data. /// \return Pointer to the specific protobuf message. public: std::shared_ptr<T2> CreateMsg(const char *_data) { // Instantiate a specific protobuf message std::shared_ptr<T2> msgPtr(new T2()); // Create the message using some serialized data msgPtr->ParseFromString(_data); return msgPtr; } /// \brief Set the callback for this handler. /// \param[in] _cb The callback. public: void SetCallback( const std::function<void(const std::string &, const T2 &, bool)> &_cb) { this->cb = _cb; } public: void SetMessage(const T1 &_reqMsg) { this->reqMsg = _reqMsg; } public: std::string Serialize() { std::string buffer; this->reqMsg.SerializeToString(&buffer); return buffer; } // Documentation inherited. /*public: int RunLocalCallback(const std::string &_topic, const transport::ProtoMsg &_msg) { // Execute the callback (if existing) if (this->cb) { auto msgPtr = google::protobuf::down_cast<const T*>(&_msg); this->cb(_topic, *msgPtr); return 0; } else { std::cerr << "ReqHandler::RunLocalCallback() error: " << "Callback is NULL" << std::endl; return -1; } }*/ // Documentation inherited. public: void NotifyResult(const std::string &_topic, const std::string &_rep, const bool _result) { // Execute the callback (if existing). if (this->cb) { // Instantiate the specific protobuf message associated to this topic. auto msg = this->CreateMsg(_rep.c_str()); this->cb(_topic, *msg, _result); } else { this->rep = _rep; this->result = _result; } this->repAvailable = true; this->condition.notify_one(); } // Protobuf message containing the request's parameters. private: T1 reqMsg; /// \brief Callback to the function registered for this handler. private: std::function<void(const std::string &, const T2 &, bool)> cb; }; } } #endif <commit_msg>Cleaning ReqHandler class.<commit_after>/* * Copyright (C) 2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __IGN_TRANSPORT_REQHANDLER_HH_INCLUDED__ #define __IGN_TRANSPORT_REQHANDLER_HH_INCLUDED__ #include <google/protobuf/message.h> #include <uuid/uuid.h> #include <condition_variable> #include <functional> #include <iostream> #include <memory> #include <string> #include "ignition/transport/Packet.hh" #include "ignition/transport/TransportTypes.hh" namespace ignition { namespace transport { /// \class IReqHandler ReqHandler.hh /// \brief Interface class used to manage a request handler. class IReqHandler { /// \brief Constructor. /// \param[in] _uuid UUID of the node registering the request handler. public: IReqHandler(const std::string &_nUuid) : result(false), nUuidStr(_nUuid), requested(false), repAvailable(false) { uuid_t uuid; uuid_generate(uuid); this->hUuid = GetGuidStr(uuid); } /// \brief Destructor. public: virtual ~IReqHandler() = default; /// \brief Executes the callback registered for this handler and notify /// a potential requester waiting on a blocking call. /// \param[in] _topic Topic to be passed to the callback. /// \param[in] _rep Serialized data containing the response coming from /// the service call responser. /// \param[in] _result Contains the result of the service call coming from /// the service call responser. public: virtual void NotifyResult(const std::string &_topic, const std::string &_rep, const bool _result) = 0; /// \brief Get the node UUID. /// \return The string representation of the node UUID. public: std::string GetNodeUuid() { return this->nUuidStr; } /// \brief Returns if this service call request has already been requested /// \return True when the service call has been requested. public: bool Requested() const { return this->requested; } /// \brief Mark the service call as requested (or not). /// \param[in] _value true when you want to flag this REQ as requested. public: void SetRequested(bool _value) { this->requested = _value; } /// \brief Serialize the Req protobuf message stored. /// \return The serialized data. public: virtual std::string Serialize() = 0; /// \brief Returns the unique handler UUID. public: std::string GetHandlerUuid() const { return this->hUuid; } /// \brief Condition variable used to wait until a service call REP is /// available. public: std::condition_variable_any condition; /// \brief Stores the service call response as raw bytes. public: std::string rep; /// \brief Stores the result of the service call. public: bool result; /// \brief Unique handler's UUID. protected: std::string hUuid; /// \brief Node UUID (string). private: std::string nUuidStr; /// \brief When true, the REQ was already sent and the REP should be on /// its way. Used to not resend the same REQ more than one time. private: bool requested; /// \brief When there is a blocking service call request, the call can /// be unlocked when a service call REP is available. This variable /// captures if we have found a node that can satisty our request. public: bool repAvailable; }; /// \class ReqHandler ReqHandler.hh /// \brief It creates a reply handler for the specific protobuf /// messages used. template <typename T1, typename T2> class ReqHandler : public IReqHandler { // Documentation inherited. public: ReqHandler(const std::string &_nUuid) : IReqHandler(_nUuid) { } /// \brief Create a specific protobuf message given its serialized data. /// \param[in] _data The serialized data. /// \return Pointer to the specific protobuf message. public: std::shared_ptr<T2> CreateMsg(const char *_data) { // Instantiate a specific protobuf message std::shared_ptr<T2> msgPtr(new T2()); // Create the message using some serialized data msgPtr->ParseFromString(_data); return msgPtr; } /// \brief Set the callback for this handler. /// \param[in] _cb The callback. public: void SetCallback( const std::function<void(const std::string &, const T2 &, bool)> &_cb) { this->cb = _cb; } /// \brief Set the REQ protobuf message for this handler. /// \param[in] _reqMsg Input parameter of the service call (protobuf). public: void SetMessage(const T1 &_reqMsg) { this->reqMsg = _reqMsg; } // Documentation inherited public: std::string Serialize() { std::string buffer; this->reqMsg.SerializeToString(&buffer); return buffer; } // Documentation inherited. public: void NotifyResult(const std::string &_topic, const std::string &_rep, const bool _result) { // Execute the callback (if existing). if (this->cb) { // Instantiate the specific protobuf message associated to this topic. auto msg = this->CreateMsg(_rep.c_str()); this->cb(_topic, *msg, _result); } else { this->rep = _rep; this->result = _result; } this->repAvailable = true; this->condition.notify_one(); } // Protobuf message containing the request's parameters. private: T1 reqMsg; /// \brief Callback to the function registered for this handler. private: std::function<void(const std::string &, const T2 &, bool)> cb; }; } } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/invariant_check.hpp" #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/integer_traits.hpp> #include <boost/thread/mutex.hpp> #include <deque> using boost::weak_ptr; using boost::shared_ptr; using boost::intrusive_ptr; using boost::bind; namespace libtorrent { // the maximum block of bandwidth quota to // hand out is 33kB. The block size may // be smaller on lower limits enum { max_bandwidth_block_size = 33000, min_bandwidth_block_size = 400 }; const time_duration bw_window_size = seconds(1); template<class PeerConnection, class Torrent> struct history_entry { history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t , int a, ptime exp) : expires_at(exp), amount(a), peer(p), tor(t) {} ptime expires_at; int amount; intrusive_ptr<PeerConnection> peer; weak_ptr<Torrent> tor; }; template<class PeerConnection> struct bw_queue_entry { bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe , int blk, bool no_prio) : peer(pe), max_block_size(blk), non_prioritized(no_prio) {} boost::intrusive_ptr<PeerConnection> peer; int max_block_size; bool non_prioritized; }; // member of peer_connection struct bandwidth_limit { static const int inf = boost::integer_traits<int>::const_max; bandwidth_limit() : m_quota_left(0) , m_local_limit(inf) , m_current_rate(0) {} void throttle(int limit) { m_local_limit = limit; } int throttle() const { return m_local_limit; } void assign(int amount) { assert(amount > 0); m_current_rate += amount; m_quota_left += amount; } void use_quota(int amount) { assert(amount <= m_quota_left); m_quota_left -= amount; } int quota_left() const { return (std::max)(m_quota_left, 0); } void expire(int amount) { assert(amount >= 0); m_current_rate -= amount; } int max_assignable() const { if (m_local_limit == inf) return inf; if (m_local_limit <= m_current_rate) return 0; return m_local_limit - m_current_rate; } private: // this is the amount of bandwidth we have // been assigned without using yet. i.e. // the bandwidth that we use up every time // we receive or send a message. Once this // hits zero, we need to request more // bandwidth from the torrent which // in turn will request bandwidth from // the bandwidth manager int m_quota_left; // the local limit is the number of bytes // per window size we are allowed to use. int m_local_limit; // the current rate is the number of // bytes we have been assigned within // the window size. int m_current_rate; }; template<class T> T clamp(T val, T ceiling, T floor) { assert(ceiling >= floor); if (val >= ceiling) return ceiling; else if (val <= floor) return floor; return val; } template<class PeerConnection, class Torrent> struct bandwidth_manager { bandwidth_manager(io_service& ios, int channel) : m_ios(ios) , m_history_timer(m_ios) , m_limit(bandwidth_limit::inf) , m_current_quota(0) , m_channel(channel) {} void throttle(int limit) { mutex_t::scoped_lock l(m_mutex); assert(limit >= 0); m_limit = limit; } int throttle() const { mutex_t::scoped_lock l(m_mutex); return m_limit; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds void request_bandwidth(intrusive_ptr<PeerConnection> peer , int blk , bool non_prioritized) { INVARIANT_CHECK; assert(blk > 0); assert(!peer->ignore_bandwidth_limits()); // make sure this peer isn't already in line // waiting for bandwidth #ifndef NDEBUG for (typename queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { assert(i->peer < peer || peer < i->peer); } #endif assert(peer->max_assignable_bandwidth(m_channel) > 0); boost::shared_ptr<Torrent> t = peer->associated_torrent().lock(); m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized)); if (!non_prioritized) { typename queue_t::reverse_iterator i = m_queue.rbegin(); typename queue_t::reverse_iterator j(i); for (++j; j != m_queue.rend(); ++j) { // if the peer's torrent is not the same one // continue looking for a peer from the same torrent if (j->peer->associated_torrent().lock() != t) continue; // if we found a peer from the same torrent that // is prioritized, there is no point looking // any further. if (!j->non_prioritized) break; using std::swap; swap(*i, *j); i = j; } } if (m_queue.size() == 1) hand_out_bandwidth(); } #ifndef NDEBUG void check_invariant() const { int current_quota = 0; for (typename history_t::const_iterator i = m_history.begin(), end(m_history.end()); i != end; ++i) { current_quota += i->amount; } assert(current_quota == m_current_quota); } #endif private: void add_history_entry(history_entry<PeerConnection, Torrent> const& e) try { INVARIANT_CHECK; m_history.push_front(e); m_current_quota += e.amount; // in case the size > 1 there is already a timer // active that will be invoked, no need to set one up if (m_history.size() > 1) return; m_history_timer.expires_at(e.expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } catch (std::exception&) { assert(false); } void on_history_expire(asio::error_code const& e) try { INVARIANT_CHECK; if (e) return; assert(!m_history.empty()); ptime now(time_now()); while (!m_history.empty() && m_history.back().expires_at <= now) { history_entry<PeerConnection, Torrent> e = m_history.back(); m_history.pop_back(); m_current_quota -= e.amount; assert(m_current_quota >= 0); intrusive_ptr<PeerConnection> c = e.peer; shared_ptr<Torrent> t = e.tor.lock(); if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount); if (t) t->expire_bandwidth(m_channel, e.amount); } // now, wait for the next chunk to expire if (!m_history.empty()) { m_history_timer.expires_at(m_history.back().expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } // since some bandwidth just expired, it // means we can hand out more (in case there // are still consumers in line) if (!m_queue.empty()) hand_out_bandwidth(); } catch (std::exception&) { assert(false); }; void hand_out_bandwidth() try { INVARIANT_CHECK; ptime now(time_now()); mutex_t::scoped_lock l(m_mutex); int limit = m_limit; l.unlock(); // available bandwidth to hand out int amount = limit - m_current_quota; while (!m_queue.empty() && amount > 0) { assert(amount == limit - m_current_quota); bw_queue_entry<PeerConnection> qe = m_queue.front(); m_queue.pop_front(); shared_ptr<Torrent> t = qe.peer->associated_torrent().lock(); if (!t) continue; if (qe.peer->is_disconnecting()) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // at this point, max_assignable may actually be zero. Since // the bandwidth quota is subtracted once the data has been // sent. If the peer was added to the queue while the data was // still being sent, max_assignable may have been > 0 at that time. int max_assignable = (std::min)( qe.peer->max_assignable_bandwidth(m_channel) , t->max_assignable_bandwidth(m_channel)); if (max_assignable == 0) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // this is the limit of the block size. It depends on the throttle // so that it can be closer to optimal. Larger block sizes will give lower // granularity to the rate but will be more efficient. At high rates // the block sizes are bigger and at low rates, the granularity // is more important and block sizes are smaller // the minimum rate that can be given is the block size, so, the // block size must be smaller for lower rates. This is because // the history window is one second, and the block will be forgotten // after one second. int block_size = (std::min)(qe.max_block_size , (std::min)(qe.peer->bandwidth_throttle(m_channel) , m_limit / 10)); if (block_size < min_bandwidth_block_size) { block_size = min_bandwidth_block_size; } else if (block_size > max_bandwidth_block_size) { if (m_limit == bandwidth_limit::inf) { block_size = max_bandwidth_block_size; } else { // try to make the block_size a divisor of // m_limit to make the distributions as fair // as possible // TODO: move this calculcation to where the limit // is changed block_size = m_limit / (m_limit / max_bandwidth_block_size); } } if (amount < block_size / 2) { m_queue.push_front(qe); break; } // so, hand out max_assignable, but no more than // the available bandwidth (amount) and no more // than the max_bandwidth_block_size int hand_out_amount = (std::min)((std::min)(block_size, max_assignable) , amount); assert(hand_out_amount > 0); amount -= hand_out_amount; t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size); qe.peer->assign_bandwidth(m_channel, hand_out_amount); add_history_entry(history_entry<PeerConnection, Torrent>( qe.peer, t, hand_out_amount, now + bw_window_size)); } } catch (std::exception& e) { assert(false); }; typedef boost::mutex mutex_t; mutable mutex_t m_mutex; // the io_service used for the timer io_service& m_ios; // the timer that is waiting for the entries // in the history queue to expire (slide out // of the history window) deadline_timer m_history_timer; // the rate limit (bytes per second) int m_limit; // the sum of all recently handed out bandwidth blocks int m_current_quota; // these are the consumers that want bandwidth typedef std::deque<bw_queue_entry<PeerConnection> > queue_t; queue_t m_queue; // these are the consumers that have received bandwidth // that will expire typedef std::deque<history_entry<PeerConnection, Torrent> > history_t; history_t m_history; // this is the channel within the consumers // that bandwidth is assigned to (upload or download) int m_channel; }; } #endif <commit_msg>added an assert to bandwidth limiter<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/invariant_check.hpp" #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/integer_traits.hpp> #include <boost/thread/mutex.hpp> #include <deque> using boost::weak_ptr; using boost::shared_ptr; using boost::intrusive_ptr; using boost::bind; namespace libtorrent { // the maximum block of bandwidth quota to // hand out is 33kB. The block size may // be smaller on lower limits enum { max_bandwidth_block_size = 33000, min_bandwidth_block_size = 400 }; const time_duration bw_window_size = seconds(1); template<class PeerConnection, class Torrent> struct history_entry { history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t , int a, ptime exp) : expires_at(exp), amount(a), peer(p), tor(t) {} ptime expires_at; int amount; intrusive_ptr<PeerConnection> peer; weak_ptr<Torrent> tor; }; template<class PeerConnection> struct bw_queue_entry { bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe , int blk, bool no_prio) : peer(pe), max_block_size(blk), non_prioritized(no_prio) {} boost::intrusive_ptr<PeerConnection> peer; int max_block_size; bool non_prioritized; }; // member of peer_connection struct bandwidth_limit { static const int inf = boost::integer_traits<int>::const_max; bandwidth_limit() : m_quota_left(0) , m_local_limit(inf) , m_current_rate(0) {} void throttle(int limit) { m_local_limit = limit; } int throttle() const { return m_local_limit; } void assign(int amount) { assert(amount > 0); m_current_rate += amount; m_quota_left += amount; } void use_quota(int amount) { assert(amount <= m_quota_left); m_quota_left -= amount; } int quota_left() const { return (std::max)(m_quota_left, 0); } void expire(int amount) { assert(amount >= 0); m_current_rate -= amount; } int max_assignable() const { if (m_local_limit == inf) return inf; if (m_local_limit <= m_current_rate) return 0; return m_local_limit - m_current_rate; } private: // this is the amount of bandwidth we have // been assigned without using yet. i.e. // the bandwidth that we use up every time // we receive or send a message. Once this // hits zero, we need to request more // bandwidth from the torrent which // in turn will request bandwidth from // the bandwidth manager int m_quota_left; // the local limit is the number of bytes // per window size we are allowed to use. int m_local_limit; // the current rate is the number of // bytes we have been assigned within // the window size. int m_current_rate; }; template<class T> T clamp(T val, T ceiling, T floor) { assert(ceiling >= floor); if (val >= ceiling) return ceiling; else if (val <= floor) return floor; return val; } template<class PeerConnection, class Torrent> struct bandwidth_manager { bandwidth_manager(io_service& ios, int channel) : m_ios(ios) , m_history_timer(m_ios) , m_limit(bandwidth_limit::inf) , m_current_quota(0) , m_channel(channel) {} void throttle(int limit) { mutex_t::scoped_lock l(m_mutex); assert(limit >= 0); m_limit = limit; } int throttle() const { mutex_t::scoped_lock l(m_mutex); return m_limit; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds void request_bandwidth(intrusive_ptr<PeerConnection> peer , int blk , bool non_prioritized) { INVARIANT_CHECK; assert(blk > 0); assert(!peer->ignore_bandwidth_limits()); // make sure this peer isn't already in line // waiting for bandwidth #ifndef NDEBUG for (typename queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { assert(i->peer < peer || peer < i->peer); } #endif assert(peer->max_assignable_bandwidth(m_channel) > 0); boost::shared_ptr<Torrent> t = peer->associated_torrent().lock(); m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized)); if (!non_prioritized) { typename queue_t::reverse_iterator i = m_queue.rbegin(); typename queue_t::reverse_iterator j(i); for (++j; j != m_queue.rend(); ++j) { // if the peer's torrent is not the same one // continue looking for a peer from the same torrent if (j->peer->associated_torrent().lock() != t) continue; // if we found a peer from the same torrent that // is prioritized, there is no point looking // any further. if (!j->non_prioritized) break; using std::swap; swap(*i, *j); i = j; } } if (m_queue.size() == 1) hand_out_bandwidth(); } #ifndef NDEBUG void check_invariant() const { int current_quota = 0; for (typename history_t::const_iterator i = m_history.begin(), end(m_history.end()); i != end; ++i) { current_quota += i->amount; } assert(current_quota == m_current_quota); } #endif private: void add_history_entry(history_entry<PeerConnection, Torrent> const& e) try { INVARIANT_CHECK; m_history.push_front(e); m_current_quota += e.amount; // in case the size > 1 there is already a timer // active that will be invoked, no need to set one up if (m_history.size() > 1) return; m_history_timer.expires_at(e.expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } catch (std::exception&) { assert(false); } void on_history_expire(asio::error_code const& e) try { INVARIANT_CHECK; if (e) return; assert(!m_history.empty()); ptime now(time_now()); while (!m_history.empty() && m_history.back().expires_at <= now) { history_entry<PeerConnection, Torrent> e = m_history.back(); m_history.pop_back(); m_current_quota -= e.amount; assert(m_current_quota >= 0); intrusive_ptr<PeerConnection> c = e.peer; shared_ptr<Torrent> t = e.tor.lock(); if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount); if (t) t->expire_bandwidth(m_channel, e.amount); } // now, wait for the next chunk to expire if (!m_history.empty()) { m_history_timer.expires_at(m_history.back().expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } // since some bandwidth just expired, it // means we can hand out more (in case there // are still consumers in line) if (!m_queue.empty()) hand_out_bandwidth(); } catch (std::exception&) { assert(false); }; void hand_out_bandwidth() try { INVARIANT_CHECK; ptime now(time_now()); mutex_t::scoped_lock l(m_mutex); int limit = m_limit; l.unlock(); // available bandwidth to hand out int amount = limit - m_current_quota; while (!m_queue.empty() && amount > 0) { assert(amount == limit - m_current_quota); bw_queue_entry<PeerConnection> qe = m_queue.front(); m_queue.pop_front(); shared_ptr<Torrent> t = qe.peer->associated_torrent().lock(); if (!t) continue; if (qe.peer->is_disconnecting()) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // at this point, max_assignable may actually be zero. Since // the bandwidth quota is subtracted once the data has been // sent. If the peer was added to the queue while the data was // still being sent, max_assignable may have been > 0 at that time. int max_assignable = (std::min)( qe.peer->max_assignable_bandwidth(m_channel) , t->max_assignable_bandwidth(m_channel)); if (max_assignable == 0) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // this is the limit of the block size. It depends on the throttle // so that it can be closer to optimal. Larger block sizes will give lower // granularity to the rate but will be more efficient. At high rates // the block sizes are bigger and at low rates, the granularity // is more important and block sizes are smaller // the minimum rate that can be given is the block size, so, the // block size must be smaller for lower rates. This is because // the history window is one second, and the block will be forgotten // after one second. int block_size = (std::min)(qe.max_block_size , (std::min)(qe.peer->bandwidth_throttle(m_channel) , m_limit / 10)); if (block_size < min_bandwidth_block_size) { block_size = min_bandwidth_block_size; } else if (block_size > max_bandwidth_block_size) { if (m_limit == bandwidth_limit::inf) { block_size = max_bandwidth_block_size; } else { // try to make the block_size a divisor of // m_limit to make the distributions as fair // as possible // TODO: move this calculcation to where the limit // is changed block_size = m_limit / (m_limit / max_bandwidth_block_size); } } if (amount < block_size / 2) { m_queue.push_front(qe); break; } // so, hand out max_assignable, but no more than // the available bandwidth (amount) and no more // than the max_bandwidth_block_size int hand_out_amount = (std::min)((std::min)(block_size, max_assignable) , amount); assert(hand_out_amount > 0); amount -= hand_out_amount; assert(hand_out_amount <= qe.max_block_size); t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size); qe.peer->assign_bandwidth(m_channel, hand_out_amount); add_history_entry(history_entry<PeerConnection, Torrent>( qe.peer, t, hand_out_amount, now + bw_window_size)); } } catch (std::exception& e) { assert(false); }; typedef boost::mutex mutex_t; mutable mutex_t m_mutex; // the io_service used for the timer io_service& m_ios; // the timer that is waiting for the entries // in the history queue to expire (slide out // of the history window) deadline_timer m_history_timer; // the rate limit (bytes per second) int m_limit; // the sum of all recently handed out bandwidth blocks int m_current_quota; // these are the consumers that want bandwidth typedef std::deque<bw_queue_entry<PeerConnection> > queue_t; queue_t m_queue; // these are the consumers that have received bandwidth // that will expire typedef std::deque<history_entry<PeerConnection, Torrent> > history_t; history_t m_history; // this is the channel within the consumers // that bandwidth is assigned to (upload or download) int m_channel; }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/invariant_check.hpp" #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/integer_traits.hpp> #include <boost/thread/mutex.hpp> #include <deque> using boost::weak_ptr; using boost::shared_ptr; using boost::intrusive_ptr; using boost::bind; namespace libtorrent { // the maximum block of bandwidth quota to // hand out is 33kB. The block size may // be smaller on lower limits enum { max_bandwidth_block_size = 33000, min_bandwidth_block_size = 400 }; const time_duration bw_window_size = seconds(1); template<class PeerConnection, class Torrent> struct history_entry { history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t , int a, ptime exp) : expires_at(exp), amount(a), peer(p), tor(t) {} ptime expires_at; int amount; intrusive_ptr<PeerConnection> peer; weak_ptr<Torrent> tor; }; template<class PeerConnection> struct bw_queue_entry { bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe , int blk, bool no_prio) : peer(pe), max_block_size(blk), non_prioritized(no_prio) {} boost::intrusive_ptr<PeerConnection> peer; int max_block_size; bool non_prioritized; }; // member of peer_connection struct bandwidth_limit { static const int inf = boost::integer_traits<int>::const_max; bandwidth_limit() throw() : m_quota_left(0) , m_local_limit(inf) , m_current_rate(0) {} void throttle(int limit) throw() { m_local_limit = limit; } int throttle() const throw() { return m_local_limit; } void assign(int amount) throw() { assert(amount > 0); m_current_rate += amount; m_quota_left += amount; } void use_quota(int amount) throw() { assert(amount <= m_quota_left); m_quota_left -= amount; } int quota_left() const throw() { return (std::max)(m_quota_left, 0); } void expire(int amount) throw() { assert(amount >= 0); m_current_rate -= amount; } int max_assignable() const throw() { if (m_local_limit == inf) return inf; if (m_local_limit <= m_current_rate) return 0; return m_local_limit - m_current_rate; } private: // this is the amount of bandwidth we have // been assigned without using yet. i.e. // the bandwidth that we use up every time // we receive or send a message. Once this // hits zero, we need to request more // bandwidth from the torrent which // in turn will request bandwidth from // the bandwidth manager int m_quota_left; // the local limit is the number of bytes // per window size we are allowed to use. int m_local_limit; // the current rate is the number of // bytes we have been assigned within // the window size. int m_current_rate; }; template<class T> T clamp(T val, T ceiling, T floor) throw() { assert(ceiling >= floor); if (val >= ceiling) return ceiling; else if (val <= floor) return floor; return val; } template<class PeerConnection, class Torrent> struct bandwidth_manager { bandwidth_manager(io_service& ios, int channel) throw() : m_ios(ios) , m_history_timer(m_ios) , m_limit(bandwidth_limit::inf) , m_current_quota(0) , m_channel(channel) {} void throttle(int limit) throw() { mutex_t::scoped_lock l(m_mutex); assert(limit >= 0); m_limit = limit; } int throttle() const throw() { mutex_t::scoped_lock l(m_mutex); return m_limit; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds void request_bandwidth(intrusive_ptr<PeerConnection> peer , int blk , bool non_prioritized) throw() { INVARIANT_CHECK; assert(blk > 0); assert(!peer->ignore_bandwidth_limits()); // make sure this peer isn't already in line // waiting for bandwidth #ifndef NDEBUG for (typename queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { assert(i->peer < peer || peer < i->peer); } #endif assert(peer->max_assignable_bandwidth(m_channel) > 0); boost::shared_ptr<Torrent> t = peer->associated_torrent().lock(); m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized)); if (!non_prioritized) { typename queue_t::reverse_iterator i = m_queue.rbegin(); typename queue_t::reverse_iterator j(i); for (++j; j != m_queue.rend(); ++j) { // if the peer's torrent is not the same one // continue looking for a peer from the same torrent if (j->peer->associated_torrent().lock() != t) continue; // if we found a peer from the same torrent that // is prioritized, there is no point looking // any further. if (!j->non_prioritized) break; using std::swap; swap(*i, *j); i = j; } } if (m_queue.size() == 1) hand_out_bandwidth(); } #ifndef NDEBUG void check_invariant() const { int current_quota = 0; for (typename history_t::const_iterator i = m_history.begin(), end(m_history.end()); i != end; ++i) { current_quota += i->amount; } assert(current_quota == m_current_quota); } #endif private: void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; m_history.push_front(e); m_current_quota += e.amount; // in case the size > 1 there is already a timer // active that will be invoked, no need to set one up if (m_history.size() > 1) return; m_history_timer.expires_at(e.expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); #ifndef NDEBUG } catch (std::exception&) { assert(false); } #endif } void on_history_expire(asio::error_code const& e) throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; if (e) return; assert(!m_history.empty()); ptime now(time_now()); while (!m_history.empty() && m_history.back().expires_at <= now) { history_entry<PeerConnection, Torrent> e = m_history.back(); m_history.pop_back(); m_current_quota -= e.amount; assert(m_current_quota >= 0); intrusive_ptr<PeerConnection> c = e.peer; shared_ptr<Torrent> t = e.tor.lock(); if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount); if (t) t->expire_bandwidth(m_channel, e.amount); } // now, wait for the next chunk to expire if (!m_history.empty()) { m_history_timer.expires_at(m_history.back().expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } // since some bandwidth just expired, it // means we can hand out more (in case there // are still consumers in line) if (!m_queue.empty()) hand_out_bandwidth(); #ifndef NDEBUG } catch (std::exception&) { assert(false); } #endif } void hand_out_bandwidth() throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; ptime now(time_now()); mutex_t::scoped_lock l(m_mutex); int limit = m_limit; l.unlock(); // available bandwidth to hand out int amount = limit - m_current_quota; while (!m_queue.empty() && amount > 0) { assert(amount == limit - m_current_quota); bw_queue_entry<PeerConnection> qe = m_queue.front(); m_queue.pop_front(); shared_ptr<Torrent> t = qe.peer->associated_torrent().lock(); if (!t) continue; if (qe.peer->is_disconnecting()) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // at this point, max_assignable may actually be zero. Since // the bandwidth quota is subtracted once the data has been // sent. If the peer was added to the queue while the data was // still being sent, max_assignable may have been > 0 at that time. int max_assignable = (std::min)( qe.peer->max_assignable_bandwidth(m_channel) , t->max_assignable_bandwidth(m_channel)); if (max_assignable == 0) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // this is the limit of the block size. It depends on the throttle // so that it can be closer to optimal. Larger block sizes will give lower // granularity to the rate but will be more efficient. At high rates // the block sizes are bigger and at low rates, the granularity // is more important and block sizes are smaller // the minimum rate that can be given is the block size, so, the // block size must be smaller for lower rates. This is because // the history window is one second, and the block will be forgotten // after one second. int block_size = (std::min)(qe.max_block_size , (std::min)(qe.peer->bandwidth_throttle(m_channel) , m_limit / 10)); if (block_size < min_bandwidth_block_size) { block_size = min_bandwidth_block_size; } else if (block_size > max_bandwidth_block_size) { if (m_limit == bandwidth_limit::inf) { block_size = max_bandwidth_block_size; } else { // try to make the block_size a divisor of // m_limit to make the distributions as fair // as possible // TODO: move this calculcation to where the limit // is changed block_size = m_limit / (m_limit / max_bandwidth_block_size); } } if (amount < block_size / 2) { m_queue.push_front(qe); break; } // so, hand out max_assignable, but no more than // the available bandwidth (amount) and no more // than the max_bandwidth_block_size int hand_out_amount = (std::min)((std::min)(block_size, max_assignable) , amount); assert(hand_out_amount > 0); amount -= hand_out_amount; assert(hand_out_amount <= qe.max_block_size); t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size); qe.peer->assign_bandwidth(m_channel, hand_out_amount); add_history_entry(history_entry<PeerConnection, Torrent>( qe.peer, t, hand_out_amount, now + bw_window_size)); } #ifndef NDEBUG } catch (std::exception& e) { assert(false); }; #endif } typedef boost::mutex mutex_t; mutable mutex_t m_mutex; // the io_service used for the timer io_service& m_ios; // the timer that is waiting for the entries // in the history queue to expire (slide out // of the history window) deadline_timer m_history_timer; // the rate limit (bytes per second) int m_limit; // the sum of all recently handed out bandwidth blocks int m_current_quota; // these are the consumers that want bandwidth typedef std::deque<bw_queue_entry<PeerConnection> > queue_t; queue_t m_queue; // these are the consumers that have received bandwidth // that will expire typedef std::deque<history_entry<PeerConnection, Torrent> > history_t; history_t m_history; // this is the channel within the consumers // that bandwidth is assigned to (upload or download) int m_channel; }; } #endif <commit_msg>bandwidth limiter fix<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/invariant_check.hpp" #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/integer_traits.hpp> #include <boost/thread/mutex.hpp> #include <deque> using boost::weak_ptr; using boost::shared_ptr; using boost::intrusive_ptr; using boost::bind; namespace libtorrent { // the maximum block of bandwidth quota to // hand out is 33kB. The block size may // be smaller on lower limits enum { max_bandwidth_block_size = 33000, min_bandwidth_block_size = 400 }; const time_duration bw_window_size = seconds(1); template<class PeerConnection, class Torrent> struct history_entry { history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t , int a, ptime exp) : expires_at(exp), amount(a), peer(p), tor(t) {} ptime expires_at; int amount; intrusive_ptr<PeerConnection> peer; weak_ptr<Torrent> tor; }; template<class PeerConnection> struct bw_queue_entry { bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe , int blk, bool no_prio) : peer(pe), max_block_size(blk), non_prioritized(no_prio) {} boost::intrusive_ptr<PeerConnection> peer; int max_block_size; bool non_prioritized; }; // member of peer_connection struct bandwidth_limit { static const int inf = boost::integer_traits<int>::const_max; bandwidth_limit() throw() : m_quota_left(0) , m_local_limit(inf) , m_current_rate(0) {} void throttle(int limit) throw() { m_local_limit = limit; } int throttle() const throw() { return m_local_limit; } void assign(int amount) throw() { assert(amount > 0); m_current_rate += amount; m_quota_left += amount; } void use_quota(int amount) throw() { assert(amount <= m_quota_left); m_quota_left -= amount; } int quota_left() const throw() { return (std::max)(m_quota_left, 0); } void expire(int amount) throw() { assert(amount >= 0); m_current_rate -= amount; } int max_assignable() const throw() { if (m_local_limit == inf) return inf; if (m_local_limit <= m_current_rate) return 0; return m_local_limit - m_current_rate; } private: // this is the amount of bandwidth we have // been assigned without using yet. i.e. // the bandwidth that we use up every time // we receive or send a message. Once this // hits zero, we need to request more // bandwidth from the torrent which // in turn will request bandwidth from // the bandwidth manager int m_quota_left; // the local limit is the number of bytes // per window size we are allowed to use. int m_local_limit; // the current rate is the number of // bytes we have been assigned within // the window size. int m_current_rate; }; template<class T> T clamp(T val, T ceiling, T floor) throw() { assert(ceiling >= floor); if (val >= ceiling) return ceiling; else if (val <= floor) return floor; return val; } template<class PeerConnection, class Torrent> struct bandwidth_manager { bandwidth_manager(io_service& ios, int channel) throw() : m_ios(ios) , m_history_timer(m_ios) , m_limit(bandwidth_limit::inf) , m_current_quota(0) , m_channel(channel) {} void throttle(int limit) throw() { mutex_t::scoped_lock l(m_mutex); assert(limit >= 0); m_limit = limit; } int throttle() const throw() { mutex_t::scoped_lock l(m_mutex); return m_limit; } // non prioritized means that, if there's a line for bandwidth, // others will cut in front of the non-prioritized peers. // this is used by web seeds void request_bandwidth(intrusive_ptr<PeerConnection> peer , int blk , bool non_prioritized) throw() { INVARIANT_CHECK; assert(blk > 0); assert(!peer->ignore_bandwidth_limits()); // make sure this peer isn't already in line // waiting for bandwidth #ifndef NDEBUG for (typename queue_t::iterator i = m_queue.begin() , end(m_queue.end()); i != end; ++i) { assert(i->peer < peer || peer < i->peer); } #endif assert(peer->max_assignable_bandwidth(m_channel) > 0); boost::shared_ptr<Torrent> t = peer->associated_torrent().lock(); m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized)); if (!non_prioritized) { typename queue_t::reverse_iterator i = m_queue.rbegin(); typename queue_t::reverse_iterator j(i); for (++j; j != m_queue.rend(); ++j) { // if the peer's torrent is not the same one // continue looking for a peer from the same torrent if (j->peer->associated_torrent().lock() != t) continue; // if we found a peer from the same torrent that // is prioritized, there is no point looking // any further. if (!j->non_prioritized) break; using std::swap; swap(*i, *j); i = j; } } if (m_queue.size() == 1) hand_out_bandwidth(); } #ifndef NDEBUG void check_invariant() const { int current_quota = 0; for (typename history_t::const_iterator i = m_history.begin(), end(m_history.end()); i != end; ++i) { current_quota += i->amount; } assert(current_quota == m_current_quota); } #endif private: void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; m_history.push_front(e); m_current_quota += e.amount; // in case the size > 1 there is already a timer // active that will be invoked, no need to set one up if (m_history.size() > 1) return; m_history_timer.expires_at(e.expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); #ifndef NDEBUG } catch (std::exception&) { assert(false); } #endif } void on_history_expire(asio::error_code const& e) throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; if (e) return; assert(!m_history.empty()); ptime now(time_now()); while (!m_history.empty() && m_history.back().expires_at <= now) { history_entry<PeerConnection, Torrent> e = m_history.back(); m_history.pop_back(); m_current_quota -= e.amount; assert(m_current_quota >= 0); intrusive_ptr<PeerConnection> c = e.peer; shared_ptr<Torrent> t = e.tor.lock(); if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount); if (t) t->expire_bandwidth(m_channel, e.amount); } // now, wait for the next chunk to expire if (!m_history.empty()) { m_history_timer.expires_at(m_history.back().expires_at); m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1)); } // since some bandwidth just expired, it // means we can hand out more (in case there // are still consumers in line) if (!m_queue.empty()) hand_out_bandwidth(); #ifndef NDEBUG } catch (std::exception&) { assert(false); } #endif } void hand_out_bandwidth() throw() { #ifndef NDEBUG try { #endif INVARIANT_CHECK; ptime now(time_now()); mutex_t::scoped_lock l(m_mutex); int limit = m_limit; l.unlock(); // available bandwidth to hand out int amount = limit - m_current_quota; while (!m_queue.empty() && amount > 0) { assert(amount == limit - m_current_quota); bw_queue_entry<PeerConnection> qe = m_queue.front(); m_queue.pop_front(); shared_ptr<Torrent> t = qe.peer->associated_torrent().lock(); if (!t) continue; if (qe.peer->is_disconnecting()) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // at this point, max_assignable may actually be zero. Since // the bandwidth quota is subtracted once the data has been // sent. If the peer was added to the queue while the data was // still being sent, max_assignable may have been > 0 at that time. int max_assignable = (std::min)( qe.peer->max_assignable_bandwidth(m_channel) , t->max_assignable_bandwidth(m_channel)); if (max_assignable == 0) { t->expire_bandwidth(m_channel, qe.max_block_size); continue; } // this is the limit of the block size. It depends on the throttle // so that it can be closer to optimal. Larger block sizes will give lower // granularity to the rate but will be more efficient. At high rates // the block sizes are bigger and at low rates, the granularity // is more important and block sizes are smaller // the minimum rate that can be given is the block size, so, the // block size must be smaller for lower rates. This is because // the history window is one second, and the block will be forgotten // after one second. int block_size = (std::min)(qe.max_block_size , (std::min)(qe.peer->bandwidth_throttle(m_channel) , m_limit / 10)); if (block_size < min_bandwidth_block_size) { block_size = min_bandwidth_block_size; } else if (block_size > max_bandwidth_block_size) { if (m_limit == bandwidth_limit::inf) { block_size = max_bandwidth_block_size; } else { // try to make the block_size a divisor of // m_limit to make the distributions as fair // as possible // TODO: move this calculcation to where the limit // is changed block_size = m_limit / (m_limit / max_bandwidth_block_size); } if (block_size > qe.max_block_size) block_size = qe.max_block_size; } if (amount < block_size / 2) { m_queue.push_front(qe); break; } // so, hand out max_assignable, but no more than // the available bandwidth (amount) and no more // than the max_bandwidth_block_size int hand_out_amount = (std::min)((std::min)(block_size, max_assignable) , amount); assert(hand_out_amount > 0); amount -= hand_out_amount; assert(hand_out_amount <= qe.max_block_size); t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size); qe.peer->assign_bandwidth(m_channel, hand_out_amount); add_history_entry(history_entry<PeerConnection, Torrent>( qe.peer, t, hand_out_amount, now + bw_window_size)); } #ifndef NDEBUG } catch (std::exception& e) { assert(false); }; #endif } typedef boost::mutex mutex_t; mutable mutex_t m_mutex; // the io_service used for the timer io_service& m_ios; // the timer that is waiting for the entries // in the history queue to expire (slide out // of the history window) deadline_timer m_history_timer; // the rate limit (bytes per second) int m_limit; // the sum of all recently handed out bandwidth blocks int m_current_quota; // these are the consumers that want bandwidth typedef std::deque<bw_queue_entry<PeerConnection> > queue_t; queue_t m_queue; // these are the consumers that have received bandwidth // that will expire typedef std::deque<history_entry<PeerConnection, Torrent> > history_t; history_t m_history; // this is the channel within the consumers // that bandwidth is assigned to (upload or download) int m_channel; }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include "../Precompiled.h" #include "../Core/Context.h" #include "../Graphics/DebugRenderer.h" #include "../Resource/ResourceCache.h" #include "../Scene/Node.h" #include "../Scene/Scene.h" #include "../Urho2D/TileMap2D.h" #include "../Urho2D/TileMapLayer2D.h" #include "../Urho2D/TmxFile2D.h" #include "../DebugNew.h" namespace Urho3D { extern const char* URHO2D_CATEGORY; TileMap2D::TileMap2D(Context* context) : Component(context) { } TileMap2D::~TileMap2D() = default; void TileMap2D::RegisterObject(Context* context) { context->RegisterFactory<TileMap2D>(URHO2D_CATEGORY); URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Tmx File", GetTmxFileAttr, SetTmxFileAttr, ResourceRef, ResourceRef(TmxFile2D::GetTypeStatic()), AM_DEFAULT); } // Transform vector from node-local space to global space static Vector2 TransformNode2D(const Matrix3x4& transform, Vector2 local) { Vector3 transformed = transform * Vector4(local.x_, local.y_, 0.f, 1.f); return Vector2(transformed.x_, transformed.y_); } void TileMap2D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { const Color& color = Color::RED; float mapW = info_.GetMapWidth(); float mapH = info_.GetMapHeight(); const Matrix3x4 transform = GetNode()->GetTransform(); switch (info_.orientation_) { case O_ORTHOGONAL: case O_STAGGERED: case O_HEXAGONAL: debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, 0.0f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, 0.0f))), color); break; case O_ISOMETRIC: debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, mapH * 0.5f))), Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, 0.0f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, mapH * 0.5f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, mapH * 0.5f))), Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, mapH * 0.5f))), color); break; } for (unsigned i = 0; i < layers_.Size(); ++i) layers_[i]->DrawDebugGeometry(debug, depthTest); } void TileMap2D::DrawDebugGeometry() { Scene* scene = GetScene(); if (!scene) return; auto* debug = scene->GetComponent<DebugRenderer>(); if (!debug) return; DrawDebugGeometry(debug, false); } void TileMap2D::SetTmxFile(TmxFile2D* tmxFile) { if (tmxFile == tmxFile_) return; if (rootNode_) rootNode_->RemoveAllChildren(); layers_.Clear(); tmxFile_ = tmxFile; if (!tmxFile_) return; info_ = tmxFile_->GetInfo(); if (!rootNode_) { rootNode_ = GetNode()->CreateTemporaryChild("_root_", LOCAL); } unsigned numLayers = tmxFile_->GetNumLayers(); layers_.Resize(numLayers); for (unsigned i = 0; i < numLayers; ++i) { const TmxLayer2D* tmxLayer = tmxFile_->GetLayer(i); Node* layerNode(rootNode_->CreateTemporaryChild(tmxLayer->GetName(), LOCAL)); auto* layer = layerNode->CreateComponent<TileMapLayer2D>(); layer->Initialize(this, tmxLayer); layer->SetDrawOrder(i * 10); layers_[i] = layer; } } TmxFile2D* TileMap2D::GetTmxFile() const { return tmxFile_; } TileMapLayer2D* TileMap2D::GetLayer(unsigned index) const { if (index >= layers_.Size()) return nullptr; return layers_[index]; } Vector2 TileMap2D::TileIndexToPosition(int x, int y) const { return info_.TileIndexToPosition(x, y); } bool TileMap2D::PositionToTileIndex(int& x, int& y, const Vector2& position) const { return info_.PositionToTileIndex(x, y, position); } void TileMap2D::SetTmxFileAttr(const ResourceRef& value) { auto* cache = GetSubsystem<ResourceCache>(); SetTmxFile(cache->GetResource<TmxFile2D>(value.name_)); } ResourceRef TileMap2D::GetTmxFileAttr() const { return GetResourceRef(tmxFile_, TmxFile2D::GetTypeStatic()); } Vector<SharedPtr<TileMapObject2D>> TileMap2D::GetTileCollisionShapes(unsigned gid) const { Vector<SharedPtr<TileMapObject2D>> shapes; return tmxFile_ ? tmxFile_->GetTileCollisionShapes(gid) : shapes; } } <commit_msg>TileMap2D.cpp: fix warning<commit_after>// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include "../Precompiled.h" #include "../Core/Context.h" #include "../Graphics/DebugRenderer.h" #include "../Resource/ResourceCache.h" #include "../Scene/Node.h" #include "../Scene/Scene.h" #include "../Urho2D/TileMap2D.h" #include "../Urho2D/TileMapLayer2D.h" #include "../Urho2D/TmxFile2D.h" #include "../DebugNew.h" namespace Urho3D { extern const char* URHO2D_CATEGORY; TileMap2D::TileMap2D(Context* context) : Component(context) { } TileMap2D::~TileMap2D() = default; void TileMap2D::RegisterObject(Context* context) { context->RegisterFactory<TileMap2D>(URHO2D_CATEGORY); URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Tmx File", GetTmxFileAttr, SetTmxFileAttr, ResourceRef, ResourceRef(TmxFile2D::GetTypeStatic()), AM_DEFAULT); } // Transform vector from node-local space to global space static Vector2 TransformNode2D(const Matrix3x4& transform, Vector2 local) { Vector3 transformed = transform * Vector4(local.x_, local.y_, 0.f, 1.f); return Vector2(transformed.x_, transformed.y_); } void TileMap2D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { const Color& color = Color::RED; float mapW = info_.GetMapWidth(); float mapH = info_.GetMapHeight(); const Matrix3x4 transform = GetNode()->GetTransform(); switch (info_.orientation_) { case O_ORTHOGONAL: case O_STAGGERED: case O_HEXAGONAL: debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, 0.0f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, 0.0f))), color); break; case O_ISOMETRIC: debug->AddLine(Vector3(TransformNode2D(transform, Vector2(0.0f, mapH * 0.5f))), Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, 0.0f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, 0.0f))), Vector3(TransformNode2D(transform, Vector2(mapW, mapH * 0.5f))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW, mapH * 0.5f))), Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, mapH))), color); debug->AddLine(Vector3(TransformNode2D(transform, Vector2(mapW * 0.5f, mapH))), Vector3(TransformNode2D(transform, Vector2(0.0f, mapH * 0.5f))), color); break; } for (const WeakPtr<TileMapLayer2D>& layer : layers_) layer->DrawDebugGeometry(debug, depthTest); } void TileMap2D::DrawDebugGeometry() { Scene* scene = GetScene(); if (!scene) return; auto* debug = scene->GetComponent<DebugRenderer>(); if (!debug) return; DrawDebugGeometry(debug, false); } void TileMap2D::SetTmxFile(TmxFile2D* tmxFile) { if (tmxFile == tmxFile_) return; if (rootNode_) rootNode_->RemoveAllChildren(); layers_.Clear(); tmxFile_ = tmxFile; if (!tmxFile_) return; info_ = tmxFile_->GetInfo(); if (!rootNode_) { rootNode_ = GetNode()->CreateTemporaryChild("_root_", LOCAL); } unsigned numLayers = tmxFile_->GetNumLayers(); layers_.Resize(numLayers); for (unsigned i = 0; i < numLayers; ++i) { const TmxLayer2D* tmxLayer = tmxFile_->GetLayer(i); Node* layerNode(rootNode_->CreateTemporaryChild(tmxLayer->GetName(), LOCAL)); auto* layer = layerNode->CreateComponent<TileMapLayer2D>(); layer->Initialize(this, tmxLayer); layer->SetDrawOrder(i * 10); layers_[i] = layer; } } TmxFile2D* TileMap2D::GetTmxFile() const { return tmxFile_; } TileMapLayer2D* TileMap2D::GetLayer(unsigned index) const { if (index >= layers_.Size()) return nullptr; return layers_[index]; } Vector2 TileMap2D::TileIndexToPosition(int x, int y) const { return info_.TileIndexToPosition(x, y); } bool TileMap2D::PositionToTileIndex(int& x, int& y, const Vector2& position) const { return info_.PositionToTileIndex(x, y, position); } void TileMap2D::SetTmxFileAttr(const ResourceRef& value) { auto* cache = GetSubsystem<ResourceCache>(); SetTmxFile(cache->GetResource<TmxFile2D>(value.name_)); } ResourceRef TileMap2D::GetTmxFileAttr() const { return GetResourceRef(tmxFile_, TmxFile2D::GetTypeStatic()); } Vector<SharedPtr<TileMapObject2D>> TileMap2D::GetTileCollisionShapes(unsigned gid) const { Vector<SharedPtr<TileMapObject2D>> shapes; return tmxFile_ ? tmxFile_->GetTileCollisionShapes(gid) : shapes; } } <|endoftext|>
<commit_before>#include "ocu.h" #include <cuda.h> #include <nvrtc.h> #ifdef __USE_CUDA__ ocu_args_d_t& getOcu(void) { static bool bInit = false; static ocu_args_d_t ocu; if (bInit == true) return ocu; bInit = true; CUresult err = cuInit(0); LOG_CU_RESULT(err); CUdevice dev = 0; CUcontext ctxt; CUstream stream; err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev); LOG_CU_RESULT(err); char name[1024]; int proc_count = 0; int thread_count = 0; int cap_major = 0, cap_minor = 0; cuDeviceGetName(name, sizeof(name), dev); cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev); cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev); cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev); cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev); LogError("CUDA Adapter:%s Ver%d.%d MP %d MaxThread Per MP %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count); /* char* source = nullptr; size_t src_size = 0; ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size); nvrtcProgram prog; const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" }; nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL); nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts); if (NVRTC_SUCCESS != compile_result) { // Obtain compilation log from the program. size_t logSize = 0; nvrtcGetProgramLogSize(prog, &logSize); char *log = new char[logSize]; nvrtcGetProgramLog(prog, log); LogError("BuildInfo:\r\n%s\r\n", log); delete[] log; } delete[] source; // Obtain PTX from the program. size_t ptxSize = 0; nvrtcGetPTXSize(prog, &ptxSize); char *ptx = new char[ptxSize]; nvrtcGetPTX(prog, ptx); */ char* ptx = nullptr; size_t src_size = 0; #ifdef _WIN64 ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size); #else ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size); #endif CUmodule mod; CUjit_option jit_options[2]; void *jit_optvals[2]; jit_options[0] = CU_JIT_CACHE_MODE; jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA; err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals); LOG_CU_RESULT(err); delete[] ptx; cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex"); cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx"); cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED); cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE); cuStreamCreate(&stream, 0); ocu.dev = dev; ocu.commandQueue = stream; ocu.mod = mod; ocu.ctxt = ctxt; return ocu; } ocu_args_d_t::ocu_args_d_t() : dev(0) , commandQueue(NULL) , mod(NULL) , ctxt(NULL) { } ocu_args_d_t::~ocu_args_d_t() { cuModuleUnload(mod); cuCtxDestroy(ctxt); // cuStreamDestroy(commandQueue); } cu_mem ocu_args_d_t::allocMem(size_t s, const void *init) { cu_mem mem; cuMemAlloc(&mem, s); if (init) { cuMemcpyHtoDAsync(mem, init, s, commandQueue); } else { cuMemsetD8Async(mem, 0, s, commandQueue); } return mem; } ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2) { const void *c[3] = { c0, c1, c2 }; ocu_channels img; for (int i = 0; i < 3; i++) { img.ch[i] = allocMem(s, c[i]); } return img; } void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb) { for (int i = 0; i < 3; i++) { cuMemFree(rgb.ch[i]); rgb.ch[i] = NULL; } } const char* TranslateCUDAError(CUresult errorCode) { switch (errorCode) { case CUDA_SUCCESS: return "CUDA_SUCCESS"; case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE"; case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY"; case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED"; case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED"; case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED"; case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED"; case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED"; case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED"; case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE"; case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE"; case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE"; case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT"; case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT"; case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED"; case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED"; case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED"; case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED"; case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU"; case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED"; case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED"; case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY"; case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER"; case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE"; case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT"; case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE"; case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED"; case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX"; case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT"; case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE"; case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE"; case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND"; case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND"; case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED"; case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM"; case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE"; case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND"; case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY"; case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS"; case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES"; case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT"; case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING"; case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED"; case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED"; case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE"; case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED"; case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT"; case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS"; case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED"; case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED"; case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR"; case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION"; case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS"; case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE"; case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC"; case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED"; case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED"; case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED"; case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN"; default: return "CUDA_ERROR_UNKNOWN"; } } #endif<commit_msg>修正64、32位判断的宏<commit_after>#include "ocu.h" #include <cuda.h> #include <nvrtc.h> #ifdef __USE_CUDA__ ocu_args_d_t& getOcu(void) { static bool bInit = false; static ocu_args_d_t ocu; if (bInit == true) return ocu; bInit = true; CUresult err = cuInit(0); LOG_CU_RESULT(err); CUdevice dev = 0; CUcontext ctxt; CUstream stream; err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev); LOG_CU_RESULT(err); char name[1024]; int proc_count = 0; int thread_count = 0; int cap_major = 0, cap_minor = 0; cuDeviceGetName(name, sizeof(name), dev); cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev); cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev); cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev); cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev); LogError("CUDA Adapter:%s Ver%d.%d MP %d MaxThread Per MP %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count); /* char* source = nullptr; size_t src_size = 0; ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size); nvrtcProgram prog; const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" }; nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL); nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts); if (NVRTC_SUCCESS != compile_result) { // Obtain compilation log from the program. size_t logSize = 0; nvrtcGetProgramLogSize(prog, &logSize); char *log = new char[logSize]; nvrtcGetProgramLog(prog, log); LogError("BuildInfo:\r\n%s\r\n", log); delete[] log; } delete[] source; // Obtain PTX from the program. size_t ptxSize = 0; nvrtcGetPTXSize(prog, &ptxSize); char *ptx = new char[ptxSize]; nvrtcGetPTX(prog, ptx); */ char* ptx = nullptr; size_t src_size = 0; if (sizeof(void*) == 8) ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size); else ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size); CUmodule mod; CUjit_option jit_options[2]; void *jit_optvals[2]; jit_options[0] = CU_JIT_CACHE_MODE; jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA; err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals); LOG_CU_RESULT(err); delete[] ptx; cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex"); cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx"); cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx"); cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED); cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE); cuStreamCreate(&stream, 0); ocu.dev = dev; ocu.commandQueue = stream; ocu.mod = mod; ocu.ctxt = ctxt; return ocu; } ocu_args_d_t::ocu_args_d_t() : dev(0) , commandQueue(NULL) , mod(NULL) , ctxt(NULL) { } ocu_args_d_t::~ocu_args_d_t() { cuModuleUnload(mod); cuCtxDestroy(ctxt); // cuStreamDestroy(commandQueue); } cu_mem ocu_args_d_t::allocMem(size_t s, const void *init) { cu_mem mem; cuMemAlloc(&mem, s); if (init) { cuMemcpyHtoDAsync(mem, init, s, commandQueue); } else { cuMemsetD8Async(mem, 0, s, commandQueue); } return mem; } ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2) { const void *c[3] = { c0, c1, c2 }; ocu_channels img; for (int i = 0; i < 3; i++) { img.ch[i] = allocMem(s, c[i]); } return img; } void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb) { for (int i = 0; i < 3; i++) { cuMemFree(rgb.ch[i]); rgb.ch[i] = NULL; } } const char* TranslateCUDAError(CUresult errorCode) { switch (errorCode) { case CUDA_SUCCESS: return "CUDA_SUCCESS"; case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE"; case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY"; case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED"; case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED"; case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED"; case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED"; case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED"; case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED"; case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE"; case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE"; case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE"; case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT"; case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT"; case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED"; case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED"; case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED"; case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED"; case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU"; case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED"; case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED"; case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY"; case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER"; case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE"; case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT"; case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE"; case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED"; case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX"; case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT"; case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE"; case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE"; case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND"; case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND"; case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED"; case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM"; case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE"; case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND"; case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY"; case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS"; case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES"; case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT"; case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING"; case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED"; case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED"; case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE"; case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED"; case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT"; case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS"; case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED"; case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED"; case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR"; case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION"; case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS"; case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE"; case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC"; case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED"; case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED"; case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED"; case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN"; default: return "CUDA_ERROR_UNKNOWN"; } } #endif<|endoftext|>
<commit_before>/* * Copyright (C) 2010 Google 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 "core/fileapi/FileReader.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/CrossThreadTask.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/events/ProgressEvent.h" #include "core/fileapi/File.h" #include "core/frame/LocalFrame.h" #include "core/workers/WorkerClients.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/Logging.h" #include "platform/Supplementable.h" #include "wtf/ArrayBuffer.h" #include "wtf/CurrentTime.h" #include "wtf/Deque.h" #include "wtf/HashSet.h" #include "wtf/ThreadSpecific.h" #include "wtf/Threading.h" #include "wtf/text/CString.h" namespace blink { namespace { #if !LOG_DISABLED const CString utf8BlobUUID(Blob* blob) { return blob->uuid().utf8(); } const CString utf8FilePath(Blob* blob) { return blob->hasBackingFile() ? toFile(blob)->path().utf8() : ""; } #endif } // namespace // Embedders like chromium limit the number of simultaneous requests to avoid // excessive IPC congestion. We limit this to 100 per thread to throttle the // requests (the value is arbitrarily chosen). static const size_t kMaxOutstandingRequestsPerThread = 100; static const double progressNotificationIntervalMS = 50; // FIXME: Oilpan: if ExecutionContext is moved to the heap, consider // making this object an ExecutionContext supplement (only.) class FileReader::ThrottlingController FINAL : public NoBaseWillBeGarbageCollectedFinalized<FileReader::ThrottlingController>, public WillBeHeapSupplement<LocalFrame>, public WillBeHeapSupplement<WorkerClients> { WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(FileReader::ThrottlingController); public: static ThrottlingController* from(ExecutionContext* context) { if (!context) return 0; if (context->isDocument()) { Document* document = toDocument(context); if (!document->frame()) return 0; ThrottlingController* controller = static_cast<ThrottlingController*>(WillBeHeapSupplement<LocalFrame>::from(document->frame(), supplementName())); if (controller) return controller; controller = new ThrottlingController(); WillBeHeapSupplement<LocalFrame>::provideTo(*document->frame(), supplementName(), adoptPtrWillBeNoop(controller)); return controller; } ASSERT(!isMainThread()); ASSERT(context->isWorkerGlobalScope()); WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context); ThrottlingController* controller = static_cast<ThrottlingController*>(WillBeHeapSupplement<WorkerClients>::from(workerGlobalScope->clients(), supplementName())); if (controller) return controller; controller = new ThrottlingController(); WillBeHeapSupplement<WorkerClients>::provideTo(*workerGlobalScope->clients(), supplementName(), adoptPtrWillBeNoop(controller)); return controller; } ~ThrottlingController() { } enum FinishReaderType { DoNotRunPendingReaders, RunPendingReaders }; static void pushReader(ExecutionContext* context, FileReader* reader) { ThrottlingController* controller = from(context); if (!controller) return; controller->pushReader(reader); } static FinishReaderType removeReader(ExecutionContext* context, FileReader* reader) { ThrottlingController* controller = from(context); if (!controller) return DoNotRunPendingReaders; return controller->removeReader(reader); } static void finishReader(ExecutionContext* context, FileReader* reader, FinishReaderType nextStep) { ThrottlingController* controller = from(context); if (!controller) return; controller->finishReader(reader, nextStep); } void trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_pendingReaders); visitor->trace(m_runningReaders); #endif WillBeHeapSupplement<LocalFrame>::trace(visitor); WillBeHeapSupplement<WorkerClients>::trace(visitor); } private: ThrottlingController() : m_maxRunningReaders(kMaxOutstandingRequestsPerThread) { } void pushReader(FileReader* reader) { if (m_pendingReaders.isEmpty() && m_runningReaders.size() < m_maxRunningReaders) { reader->executePendingRead(); ASSERT(!m_runningReaders.contains(reader)); m_runningReaders.add(reader); return; } m_pendingReaders.append(reader); executeReaders(); } FinishReaderType removeReader(FileReader* reader) { WillBeHeapHashSet<RawPtrWillBeMember<FileReader> >::const_iterator hashIter = m_runningReaders.find(reader); if (hashIter != m_runningReaders.end()) { m_runningReaders.remove(hashIter); return RunPendingReaders; } WillBeHeapDeque<RawPtrWillBeMember<FileReader> >::const_iterator dequeEnd = m_pendingReaders.end(); for (WillBeHeapDeque<RawPtrWillBeMember<FileReader> >::const_iterator it = m_pendingReaders.begin(); it != dequeEnd; ++it) { if (*it == reader) { m_pendingReaders.remove(it); break; } } return DoNotRunPendingReaders; } void finishReader(FileReader* reader, FinishReaderType nextStep) { if (nextStep == RunPendingReaders) executeReaders(); } void executeReaders() { while (m_runningReaders.size() < m_maxRunningReaders) { if (m_pendingReaders.isEmpty()) return; FileReader* reader = m_pendingReaders.takeFirst(); reader->executePendingRead(); m_runningReaders.add(reader); } } static const char* supplementName() { return "FileReaderThrottlingController"; } const size_t m_maxRunningReaders; WillBeHeapDeque<RawPtrWillBeMember<FileReader> > m_pendingReaders; WillBeHeapHashSet<RawPtrWillBeMember<FileReader> > m_runningReaders; }; PassRefPtrWillBeRawPtr<FileReader> FileReader::create(ExecutionContext* context) { RefPtrWillBeRawPtr<FileReader> fileReader(adoptRefWillBeNoop(new FileReader(context))); fileReader->suspendIfNeeded(); return fileReader.release(); } FileReader::FileReader(ExecutionContext* context) : ActiveDOMObject(context) , m_state(EMPTY) , m_loadingState(LoadingStateNone) , m_readType(FileReaderLoader::ReadAsBinaryString) , m_lastProgressNotificationTimeMS(0) { ScriptWrappable::init(this); } FileReader::~FileReader() { terminate(); } const AtomicString& FileReader::interfaceName() const { return EventTargetNames::FileReader; } void FileReader::stop() { if (hasPendingActivity()) ThrottlingController::finishReader(executionContext(), this, ThrottlingController::removeReader(executionContext(), this)); terminate(); } bool FileReader::hasPendingActivity() const { return m_state == LOADING; } void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, exceptionState); } void FileReader::readAsBinaryString(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsBinaryString, exceptionState); } void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); m_encoding = encoding; readInternal(blob, FileReaderLoader::ReadAsText, exceptionState); } void FileReader::readAsText(Blob* blob, ExceptionState& exceptionState) { readAsText(blob, String(), exceptionState); } void FileReader::readAsDataURL(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsDataURL, exceptionState); } void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& exceptionState) { // If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING. if (m_state == LOADING) { exceptionState.throwDOMException(InvalidStateError, "The object is already busy reading Blobs."); return; } if (blob->hasBeenClosed()) { exceptionState.throwDOMException(InvalidStateError, String(blob->isFile() ? "File" : "Blob") + " has been closed."); return; } if (!ThrottlingController::from(executionContext())) { exceptionState.throwDOMException(AbortError, "Reading from a Document-detached FileReader is not supported."); return; } // "Snapshot" the Blob data rather than the Blob itself as ongoing // read operations should not be affected if close() is called on // the Blob being read. m_blobDataHandle = blob->blobDataHandle(); m_blobType = blob->type(); m_readType = type; m_state = LOADING; m_loadingState = LoadingStatePending; m_error = nullptr; ThrottlingController::pushReader(executionContext(), this); } void FileReader::executePendingRead() { ASSERT(m_loadingState == LoadingStatePending); m_loadingState = LoadingStateLoading; m_loader = adoptPtr(new FileReaderLoader(m_readType, this)); m_loader->setEncoding(m_encoding); m_loader->setDataType(m_blobType); m_loader->start(executionContext(), m_blobDataHandle); m_blobDataHandle = nullptr; } static void delayedAbort(ExecutionContext*, FileReader* reader) { reader->doAbort(); } void FileReader::abort() { WTF_LOG(FileAPI, "FileReader: aborting\n"); if (m_loadingState != LoadingStateLoading && m_loadingState != LoadingStatePending) { return; } m_loadingState = LoadingStateAborted; // Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack. executionContext()->postTask( createCrossThreadTask(&delayedAbort, AllowAccessLater(this))); } void FileReader::doAbort() { ASSERT(m_state != DONE); terminate(); m_error = FileError::create(FileError::ABORT_ERR); // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::error); fireEvent(EventTypeNames::abort); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::terminate() { if (m_loader) { m_loader->cancel(); m_loader = nullptr; } m_state = DONE; m_loadingState = LoadingStateNone; } void FileReader::didStartLoading() { fireEvent(EventTypeNames::loadstart); } void FileReader::didReceiveData() { // Fire the progress event at least every 50ms. double now = currentTimeMS(); if (!m_lastProgressNotificationTimeMS) m_lastProgressNotificationTimeMS = now; else if (now - m_lastProgressNotificationTimeMS > progressNotificationIntervalMS) { fireEvent(EventTypeNames::progress); m_lastProgressNotificationTimeMS = now; } } void FileReader::didFinishLoading() { if (m_loadingState == LoadingStateAborted) return; ASSERT(m_loadingState == LoadingStateLoading); // It's important that we change m_loadingState before firing any events // since any of the events could call abort(), which internally checks // if we're still loading (therefore we need abort process) or not. m_loadingState = LoadingStateNone; fireEvent(EventTypeNames::progress); ASSERT(m_state != DONE); m_state = DONE; // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::load); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::didFail(FileError::ErrorCode errorCode) { if (m_loadingState == LoadingStateAborted) return; ASSERT(m_loadingState == LoadingStateLoading); m_loadingState = LoadingStateNone; ASSERT(m_state != DONE); m_state = DONE; m_error = FileError::create(static_cast<FileError::ErrorCode>(errorCode)); // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::error); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::fireEvent(const AtomicString& type) { if (!m_loader) { dispatchEvent(ProgressEvent::create(type, false, 0, 0)); return; } if (m_loader->totalBytes() >= 0) dispatchEvent(ProgressEvent::create(type, true, m_loader->bytesLoaded(), m_loader->totalBytes())); else dispatchEvent(ProgressEvent::create(type, false, m_loader->bytesLoaded(), 0)); } PassRefPtr<ArrayBuffer> FileReader::arrayBufferResult() const { if (!m_loader || m_error) return nullptr; return m_loader->arrayBufferResult(); } String FileReader::stringResult() { if (!m_loader || m_error) return String(); return m_loader->stringResult(); } void FileReader::trace(Visitor* visitor) { visitor->trace(m_error); EventTargetWithInlineData::trace(visitor); } } // namespace blink <commit_msg>Remove unused threading includes from FileReader.<commit_after>/* * Copyright (C) 2010 Google 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 "core/fileapi/FileReader.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/CrossThreadTask.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/events/ProgressEvent.h" #include "core/fileapi/File.h" #include "core/frame/LocalFrame.h" #include "core/workers/WorkerClients.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/Logging.h" #include "platform/Supplementable.h" #include "wtf/ArrayBuffer.h" #include "wtf/CurrentTime.h" #include "wtf/Deque.h" #include "wtf/HashSet.h" #include "wtf/text/CString.h" namespace blink { namespace { #if !LOG_DISABLED const CString utf8BlobUUID(Blob* blob) { return blob->uuid().utf8(); } const CString utf8FilePath(Blob* blob) { return blob->hasBackingFile() ? toFile(blob)->path().utf8() : ""; } #endif } // namespace // Embedders like chromium limit the number of simultaneous requests to avoid // excessive IPC congestion. We limit this to 100 per thread to throttle the // requests (the value is arbitrarily chosen). static const size_t kMaxOutstandingRequestsPerThread = 100; static const double progressNotificationIntervalMS = 50; // FIXME: Oilpan: if ExecutionContext is moved to the heap, consider // making this object an ExecutionContext supplement (only.) class FileReader::ThrottlingController FINAL : public NoBaseWillBeGarbageCollectedFinalized<FileReader::ThrottlingController>, public WillBeHeapSupplement<LocalFrame>, public WillBeHeapSupplement<WorkerClients> { WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(FileReader::ThrottlingController); public: static ThrottlingController* from(ExecutionContext* context) { if (!context) return 0; if (context->isDocument()) { Document* document = toDocument(context); if (!document->frame()) return 0; ThrottlingController* controller = static_cast<ThrottlingController*>(WillBeHeapSupplement<LocalFrame>::from(document->frame(), supplementName())); if (controller) return controller; controller = new ThrottlingController(); WillBeHeapSupplement<LocalFrame>::provideTo(*document->frame(), supplementName(), adoptPtrWillBeNoop(controller)); return controller; } ASSERT(!isMainThread()); ASSERT(context->isWorkerGlobalScope()); WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context); ThrottlingController* controller = static_cast<ThrottlingController*>(WillBeHeapSupplement<WorkerClients>::from(workerGlobalScope->clients(), supplementName())); if (controller) return controller; controller = new ThrottlingController(); WillBeHeapSupplement<WorkerClients>::provideTo(*workerGlobalScope->clients(), supplementName(), adoptPtrWillBeNoop(controller)); return controller; } ~ThrottlingController() { } enum FinishReaderType { DoNotRunPendingReaders, RunPendingReaders }; static void pushReader(ExecutionContext* context, FileReader* reader) { ThrottlingController* controller = from(context); if (!controller) return; controller->pushReader(reader); } static FinishReaderType removeReader(ExecutionContext* context, FileReader* reader) { ThrottlingController* controller = from(context); if (!controller) return DoNotRunPendingReaders; return controller->removeReader(reader); } static void finishReader(ExecutionContext* context, FileReader* reader, FinishReaderType nextStep) { ThrottlingController* controller = from(context); if (!controller) return; controller->finishReader(reader, nextStep); } void trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_pendingReaders); visitor->trace(m_runningReaders); #endif WillBeHeapSupplement<LocalFrame>::trace(visitor); WillBeHeapSupplement<WorkerClients>::trace(visitor); } private: ThrottlingController() : m_maxRunningReaders(kMaxOutstandingRequestsPerThread) { } void pushReader(FileReader* reader) { if (m_pendingReaders.isEmpty() && m_runningReaders.size() < m_maxRunningReaders) { reader->executePendingRead(); ASSERT(!m_runningReaders.contains(reader)); m_runningReaders.add(reader); return; } m_pendingReaders.append(reader); executeReaders(); } FinishReaderType removeReader(FileReader* reader) { WillBeHeapHashSet<RawPtrWillBeMember<FileReader> >::const_iterator hashIter = m_runningReaders.find(reader); if (hashIter != m_runningReaders.end()) { m_runningReaders.remove(hashIter); return RunPendingReaders; } WillBeHeapDeque<RawPtrWillBeMember<FileReader> >::const_iterator dequeEnd = m_pendingReaders.end(); for (WillBeHeapDeque<RawPtrWillBeMember<FileReader> >::const_iterator it = m_pendingReaders.begin(); it != dequeEnd; ++it) { if (*it == reader) { m_pendingReaders.remove(it); break; } } return DoNotRunPendingReaders; } void finishReader(FileReader* reader, FinishReaderType nextStep) { if (nextStep == RunPendingReaders) executeReaders(); } void executeReaders() { while (m_runningReaders.size() < m_maxRunningReaders) { if (m_pendingReaders.isEmpty()) return; FileReader* reader = m_pendingReaders.takeFirst(); reader->executePendingRead(); m_runningReaders.add(reader); } } static const char* supplementName() { return "FileReaderThrottlingController"; } const size_t m_maxRunningReaders; WillBeHeapDeque<RawPtrWillBeMember<FileReader> > m_pendingReaders; WillBeHeapHashSet<RawPtrWillBeMember<FileReader> > m_runningReaders; }; PassRefPtrWillBeRawPtr<FileReader> FileReader::create(ExecutionContext* context) { RefPtrWillBeRawPtr<FileReader> fileReader(adoptRefWillBeNoop(new FileReader(context))); fileReader->suspendIfNeeded(); return fileReader.release(); } FileReader::FileReader(ExecutionContext* context) : ActiveDOMObject(context) , m_state(EMPTY) , m_loadingState(LoadingStateNone) , m_readType(FileReaderLoader::ReadAsBinaryString) , m_lastProgressNotificationTimeMS(0) { ScriptWrappable::init(this); } FileReader::~FileReader() { terminate(); } const AtomicString& FileReader::interfaceName() const { return EventTargetNames::FileReader; } void FileReader::stop() { if (hasPendingActivity()) ThrottlingController::finishReader(executionContext(), this, ThrottlingController::removeReader(executionContext(), this)); terminate(); } bool FileReader::hasPendingActivity() const { return m_state == LOADING; } void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, exceptionState); } void FileReader::readAsBinaryString(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsBinaryString, exceptionState); } void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); m_encoding = encoding; readInternal(blob, FileReaderLoader::ReadAsText, exceptionState); } void FileReader::readAsText(Blob* blob, ExceptionState& exceptionState) { readAsText(blob, String(), exceptionState); } void FileReader::readAsDataURL(Blob* blob, ExceptionState& exceptionState) { if (!blob) { exceptionState.throwTypeError("The argument is not a Blob."); return; } WTF_LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data()); readInternal(blob, FileReaderLoader::ReadAsDataURL, exceptionState); } void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& exceptionState) { // If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING. if (m_state == LOADING) { exceptionState.throwDOMException(InvalidStateError, "The object is already busy reading Blobs."); return; } if (blob->hasBeenClosed()) { exceptionState.throwDOMException(InvalidStateError, String(blob->isFile() ? "File" : "Blob") + " has been closed."); return; } if (!ThrottlingController::from(executionContext())) { exceptionState.throwDOMException(AbortError, "Reading from a Document-detached FileReader is not supported."); return; } // "Snapshot" the Blob data rather than the Blob itself as ongoing // read operations should not be affected if close() is called on // the Blob being read. m_blobDataHandle = blob->blobDataHandle(); m_blobType = blob->type(); m_readType = type; m_state = LOADING; m_loadingState = LoadingStatePending; m_error = nullptr; ThrottlingController::pushReader(executionContext(), this); } void FileReader::executePendingRead() { ASSERT(m_loadingState == LoadingStatePending); m_loadingState = LoadingStateLoading; m_loader = adoptPtr(new FileReaderLoader(m_readType, this)); m_loader->setEncoding(m_encoding); m_loader->setDataType(m_blobType); m_loader->start(executionContext(), m_blobDataHandle); m_blobDataHandle = nullptr; } static void delayedAbort(ExecutionContext*, FileReader* reader) { reader->doAbort(); } void FileReader::abort() { WTF_LOG(FileAPI, "FileReader: aborting\n"); if (m_loadingState != LoadingStateLoading && m_loadingState != LoadingStatePending) { return; } m_loadingState = LoadingStateAborted; // Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack. executionContext()->postTask( createCrossThreadTask(&delayedAbort, AllowAccessLater(this))); } void FileReader::doAbort() { ASSERT(m_state != DONE); terminate(); m_error = FileError::create(FileError::ABORT_ERR); // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::error); fireEvent(EventTypeNames::abort); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::terminate() { if (m_loader) { m_loader->cancel(); m_loader = nullptr; } m_state = DONE; m_loadingState = LoadingStateNone; } void FileReader::didStartLoading() { fireEvent(EventTypeNames::loadstart); } void FileReader::didReceiveData() { // Fire the progress event at least every 50ms. double now = currentTimeMS(); if (!m_lastProgressNotificationTimeMS) m_lastProgressNotificationTimeMS = now; else if (now - m_lastProgressNotificationTimeMS > progressNotificationIntervalMS) { fireEvent(EventTypeNames::progress); m_lastProgressNotificationTimeMS = now; } } void FileReader::didFinishLoading() { if (m_loadingState == LoadingStateAborted) return; ASSERT(m_loadingState == LoadingStateLoading); // It's important that we change m_loadingState before firing any events // since any of the events could call abort(), which internally checks // if we're still loading (therefore we need abort process) or not. m_loadingState = LoadingStateNone; fireEvent(EventTypeNames::progress); ASSERT(m_state != DONE); m_state = DONE; // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::load); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::didFail(FileError::ErrorCode errorCode) { if (m_loadingState == LoadingStateAborted) return; ASSERT(m_loadingState == LoadingStateLoading); m_loadingState = LoadingStateNone; ASSERT(m_state != DONE); m_state = DONE; m_error = FileError::create(static_cast<FileError::ErrorCode>(errorCode)); // Unregister the reader. ThrottlingController::FinishReaderType finalStep = ThrottlingController::removeReader(executionContext(), this); fireEvent(EventTypeNames::error); fireEvent(EventTypeNames::loadend); // All possible events have fired and we're done, no more pending activity. ThrottlingController::finishReader(executionContext(), this, finalStep); } void FileReader::fireEvent(const AtomicString& type) { if (!m_loader) { dispatchEvent(ProgressEvent::create(type, false, 0, 0)); return; } if (m_loader->totalBytes() >= 0) dispatchEvent(ProgressEvent::create(type, true, m_loader->bytesLoaded(), m_loader->totalBytes())); else dispatchEvent(ProgressEvent::create(type, false, m_loader->bytesLoaded(), 0)); } PassRefPtr<ArrayBuffer> FileReader::arrayBufferResult() const { if (!m_loader || m_error) return nullptr; return m_loader->arrayBufferResult(); } String FileReader::stringResult() { if (!m_loader || m_error) return String(); return m_loader->stringResult(); } void FileReader::trace(Visitor* visitor) { visitor->trace(m_error); EventTargetWithInlineData::trace(visitor); } } // namespace blink <|endoftext|>
<commit_before>#pragma once #include "../message/MessageLoop.h" #include <thread> namespace hurricane { namespace base { template<typename TaskType> class Executor { public: enum class Status { Stopping, Running, }; Executor() : m_status(Status::Stopping) {} virtual ~Executor() {} /// @param name 任务名 /// @param task 用户传递的任务 void StartTask(std::string const& name, TaskType* task) { m_taskName = name; m_task = std::shared_ptr<TaskType>(task); m_thread = std::thread(std::bind(&Executor::StartThread, this)); } virtual void StopTask() { m_messageLoop.stop(); } Status status()const { return m_status; } std::string const& GetTaskName()const { return m_taskName; } protected: virtual void OnCreate() = 0; virtual void OnStop() = 0; std::shared_ptr<TaskType> m_task; message::MessageLoop m_messageLoop; private: void StartThread() { m_status = Status::Running; OnCreate(); m_messageLoop.run(); OnStop(); } Status m_status; std::string m_taskName; }; } } <commit_msg>thread<commit_after>#pragma once #include "../message/MessageLoop.h" #include <thread> namespace hurricane { namespace base { template<typename TaskType> class Executor { public: enum class Status { Stopping, Running, }; Executor() : m_status(Status::Stopping) {} virtual ~Executor() {} /// @param name 任务名 /// @param task 用户传递的任务 void StartTask(std::string const& name, TaskType* task) { m_taskName = name; m_task = std::shared_ptr<TaskType>(task); m_thread = std::thread(std::bind(&Executor::StartThread, this)); } virtual void StopTask() { m_messageLoop.stop(); } Status status()const { return m_status; } std::string const& GetTaskName()const { return m_taskName; } protected: virtual void OnCreate() = 0; virtual void OnStop() = 0; std::shared_ptr<TaskType> m_task; message::MessageLoop m_messageLoop; private: void StartThread() { m_status = Status::Running; OnCreate(); m_messageLoop.run(); OnStop(); } std::thread m_thread; Status m_status; std::string m_taskName; }; } } <|endoftext|>
<commit_before>// ============================================================================ // SeqAn - The Library for Sequence Analysis // ============================================================================ // // Copyright (c) 2006-2017, Knut Reinert & Freie Universitaet Berlin // Copyright (c) 2016-2017, Knut Reinert & MPI Molekulare Genetik // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ============================================================================ /*!\file core/concept/iterator.hpp * \brief Adaptions of Iterator concepts from the Ranges TS. * \ingroup core * \author Rene Rahn <rene.rahn AT fu-berlin.de> */ #pragma once #include <range/v3/range_concepts.hpp> #include <range/v3/utility/iterator.hpp> #include <seqan3/core/concepts/core.hpp> namespace seqan3 { //!\name Iterator Concepts //!\{ /*!\brief Resolves to `ranges::Readable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Readable */ template <typename t> concept bool readable_concept = static_cast<bool>(ranges::Readable<t>()); /*!\brief Resolves to `ranges::Writable<out_type, type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Writable */ template <typename out, typename t> concept bool writable_concept = static_cast<bool>(ranges::Writable<out, t>()); /*!\brief Resolves to `ranges::WeaklyIncrementable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/WeaklyIncrementable */ template<typename i> concept bool weakly_incrementable_concept = semi_regular_concept<i> && static_cast<bool>(ranges::WeaklyIncrementable<i>()); /*!\brief Resolves to `ranges::Incrementable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Incrementable */ template<typename i> concept bool incrementable_concept = regular_concept<i> && weakly_incrementable_concept<i> && static_cast<bool>(ranges::Incrementable<i>()); /*!\brief Resolves to `ranges::Iterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/Iterator */ template<typename i> concept bool iterator_concept = weakly_incrementable_concept<i> && copyable_concept<i> && static_cast<bool>(ranges::Iterator<i>()); /*!\brief Resolves to `ranges::Sentinel<sentinel_type, iterator_type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Sentinel */ template<typename s, typename i> concept bool sentinel_concept = semi_regular_concept<s> && iterator_concept<i> && static_cast<bool>(ranges::Sentinel<s, i>()); /*!\brief Resolves to `ranges::SizedSentinel<sentinel_type, iterator_type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/SizedSentinel */ template<typename s, typename i> concept bool sized_sentinel_concept = sentinel_concept<s, i> && static_cast<bool>(ranges::SizedSentinel<s, i>()); /*!\brief Resolves to `ranges::OutputIterator<iterator_type, type>()` * \sa http://en.cppreference.com/w/cpp/concept/OutputIterator */ template<typename out, typename t> concept bool output_iterator_concept = iterator_concept<out> && writable_concept<out, t> && static_cast<bool>(ranges::OutputIterator<out, t>()); /*!\brief Resolves to `ranges::InputIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/InputIterator */ template<typename i> concept bool input_iterator_concept = iterator_concept<i> && readable_concept<i> && static_cast<bool>(ranges::InputIterator<i>()); /*!\brief Resolves to `ranges::ForwardIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/ForwardIterator */ template<typename i> concept bool forward_iterator_concept = input_iterator_concept<i> && incrementable_concept<i> && sentinel_concept<i, i> && static_cast<bool>(ranges::ForwardIterator<i>()); /*!\brief Resolves to `ranges::BidirectionalIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/BidirectionalIterator */ template<typename i> concept bool bidirectional_iterator_concept = forward_iterator_concept<i> && static_cast<bool>(ranges::BidirectionalIterator<i>()); /*!\brief Resolves to `ranges::RandomAccessIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/RandomAccessIterator */ template<typename i> concept bool random_access_iterator_concept = bidirectional_iterator_concept<i> && totally_ordered_concept<i> && sized_sentinel_concept<i, i> && static_cast<bool>(ranges::RandomAccessIterator<i>()); //!\} // Iterator Concepts. } // namespace seqan3 #ifndef NDEBUG /* Check the iterator concepts */ #include <seqan3/core/concepts/iterator_detail.hpp> #endif // NDEBUG <commit_msg>Correct included header path (‘/concept/’ instead of ‘/concepts/’).<commit_after>// ============================================================================ // SeqAn - The Library for Sequence Analysis // ============================================================================ // // Copyright (c) 2006-2017, Knut Reinert & Freie Universitaet Berlin // Copyright (c) 2016-2017, Knut Reinert & MPI Molekulare Genetik // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ============================================================================ /*!\file core/concept/iterator.hpp * \brief Adaptions of Iterator concepts from the Ranges TS. * \ingroup core * \author Rene Rahn <rene.rahn AT fu-berlin.de> */ #pragma once #include <range/v3/range_concepts.hpp> #include <range/v3/utility/iterator.hpp> #include <seqan3/core/concept/core.hpp> namespace seqan3 { //!\name Iterator Concepts //!\{ /*!\brief Resolves to `ranges::Readable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Readable */ template <typename t> concept bool readable_concept = static_cast<bool>(ranges::Readable<t>()); /*!\brief Resolves to `ranges::Writable<out_type, type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Writable */ template <typename out, typename t> concept bool writable_concept = static_cast<bool>(ranges::Writable<out, t>()); /*!\brief Resolves to `ranges::WeaklyIncrementable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/WeaklyIncrementable */ template<typename i> concept bool weakly_incrementable_concept = semi_regular_concept<i> && static_cast<bool>(ranges::WeaklyIncrementable<i>()); /*!\brief Resolves to `ranges::Incrementable<type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Incrementable */ template<typename i> concept bool incrementable_concept = regular_concept<i> && weakly_incrementable_concept<i> && static_cast<bool>(ranges::Incrementable<i>()); /*!\brief Resolves to `ranges::Iterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/Iterator */ template<typename i> concept bool iterator_concept = weakly_incrementable_concept<i> && copyable_concept<i> && static_cast<bool>(ranges::Iterator<i>()); /*!\brief Resolves to `ranges::Sentinel<sentinel_type, iterator_type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/Sentinel */ template<typename s, typename i> concept bool sentinel_concept = semi_regular_concept<s> && iterator_concept<i> && static_cast<bool>(ranges::Sentinel<s, i>()); /*!\brief Resolves to `ranges::SizedSentinel<sentinel_type, iterator_type>()` * \sa http://en.cppreference.com/w/cpp/experimental/ranges/iterator/SizedSentinel */ template<typename s, typename i> concept bool sized_sentinel_concept = sentinel_concept<s, i> && static_cast<bool>(ranges::SizedSentinel<s, i>()); /*!\brief Resolves to `ranges::OutputIterator<iterator_type, type>()` * \sa http://en.cppreference.com/w/cpp/concept/OutputIterator */ template<typename out, typename t> concept bool output_iterator_concept = iterator_concept<out> && writable_concept<out, t> && static_cast<bool>(ranges::OutputIterator<out, t>()); /*!\brief Resolves to `ranges::InputIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/InputIterator */ template<typename i> concept bool input_iterator_concept = iterator_concept<i> && readable_concept<i> && static_cast<bool>(ranges::InputIterator<i>()); /*!\brief Resolves to `ranges::ForwardIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/ForwardIterator */ template<typename i> concept bool forward_iterator_concept = input_iterator_concept<i> && incrementable_concept<i> && sentinel_concept<i, i> && static_cast<bool>(ranges::ForwardIterator<i>()); /*!\brief Resolves to `ranges::BidirectionalIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/BidirectionalIterator */ template<typename i> concept bool bidirectional_iterator_concept = forward_iterator_concept<i> && static_cast<bool>(ranges::BidirectionalIterator<i>()); /*!\brief Resolves to `ranges::RandomAccessIterator<iterator_type>()` * \sa http://en.cppreference.com/w/cpp/concept/RandomAccessIterator */ template<typename i> concept bool random_access_iterator_concept = bidirectional_iterator_concept<i> && totally_ordered_concept<i> && sized_sentinel_concept<i, i> && static_cast<bool>(ranges::RandomAccessIterator<i>()); //!\} // Iterator Concepts. } // namespace seqan3 #ifndef NDEBUG /* Check the iterator concepts */ #include <seqan3/core/concepts/iterator_detail.hpp> #endif // NDEBUG <|endoftext|>
<commit_before>#ifndef SYSCALL_PROCESS_H_ #define SYSCALL_PROCESS_H_ #include <factory.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <linux/sched.h> #include <linux/limits.h> #include <sys/ptrace.h> #include <asm/ptrace.h> #include <sys/prctl.h> #include <sys/time.h> /* * System calls defined in this file. */ namespace Syscall { SYSTEM_CALL pid_t getpid(void); SYSTEM_CALL pid_t getppid(void); SYSTEM_CALL pid_t gettid(void); SYSTEM_CALL pid_t fork(void); NO_RETURN SYSTEM_CALL int execve(const char *, char *const[], char *const[]); #if SYSCALL_EXISTS(execveat) NO_RETURN SYSTEM_CALL int execveat(int, const char *, char *const[], char *const[], int); #endif SYSTEM_CALL_INLINE long clone(unsigned long, void *, void *, void *, void *); SYSTEM_CALL int prctl(int, unsigned long, unsigned long, unsigned long, unsigned long); #if SYSCALL_EXISTS(setitimer) SYSTEM_CALL int setitimer(int, const struct itimerval *, struct itimerval *); #endif SYSTEM_CALL long ptrace(enum __ptrace_request, pid_t, void *, void *); SYSTEM_CALL pid_t wait4(pid_t, int *, int, struct rusage *); SYSTEM_CALL int tkill(pid_t, int); SYSTEM_CALL int kill(pid_t, int); NO_RETURN SYSTEM_CALL void exit(int); NO_RETURN SYSTEM_CALL void exit_group(int); SYSTEM_CALL pid_t getpid(void) { return DO_SYSCALL(getpid); } SYSTEM_CALL pid_t getppid(void) { return DO_SYSCALL(getppid); } SYSTEM_CALL pid_t gettid(void) { return DO_SYSCALL(gettid); } SYSTEM_CALL pid_t fork(void) { return DO_SYSCALL(fork); } NO_RETURN SYSTEM_CALL int execve(const char *filename, char *const argv[], char *const envp[]) { DO_SYSCALL(execve, filename, argv, envp); __builtin_unreachable(); } #if SYSCALL_EXISTS(execveat) NO_RETURN SYSTEM_CALL int execveat(int dirfd, const char *pathname, char *const argv[], char *const envp[], int flags) { DO_SYSCALL(execveat, dirfd, pathname, argv, envp, flags); __builtin_unreachable(); } #endif // // clone has the ability to change the child stack. // It must be always be inlined since it cannot return from another stack. // SYSTEM_CALL_INLINE long clone(unsigned long flags, void *child_stack, void *ptid, void *tls, void *ctid) { return DO_SYSCALL(clone, flags, child_stack, ptid, tls, ctid); } SYSTEM_CALL int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5) { return DO_SYSCALL(prctl, option, arg2, arg3, arg4, arg5); } #if SYSCALL_EXISTS(setitimer) SYSTEM_CALL int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue) { return DO_SYSCALL(setitimer, which, value, ovalue); } #endif SYSTEM_CALL unsigned int alarm(unsigned int seconds) { #if SYSCALL_EXISTS(alarm) return DO_SYSCALL(alarm, seconds); #else struct itimerval itv = { {0,0}, {0,0} }; itv.it_value.tv_sec = seconds; return Syscall::setitimer(ITIMER_REAL, &itv, &itv); #endif } SYSTEM_CALL int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { return DO_SYSCALL(rt_sigaction, signum, act, oldact, 8); } SYSTEM_CALL long ptrace(enum __ptrace_request request, pid_t pid, void *addr, void *data) { return DO_SYSCALL(ptrace, request, pid, addr, data); } SYSTEM_CALL pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage) { return DO_SYSCALL(wait4, pid, status, options, rusage); } SYSTEM_CALL int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options) { return DO_SYSCALL(waitid, idtype, id, infop, options); } SYSTEM_CALL int tkill(pid_t tid, int sig) { return DO_SYSCALL(tkill, tid, sig); } SYSTEM_CALL int kill(pid_t pid, int sig) { return DO_SYSCALL(kill, pid, sig); } NO_RETURN SYSTEM_CALL void exit(int status) { DO_SYSCALL(exit, status); __builtin_unreachable(); } NO_RETURN SYSTEM_CALL void exit_group(int status) { DO_SYSCALL(exit_group, status); __builtin_unreachable(); } } #endif <commit_msg>target/linux: fix fifth argument in waitid<commit_after>#ifndef SYSCALL_PROCESS_H_ #define SYSCALL_PROCESS_H_ #include <factory.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <linux/sched.h> #include <linux/limits.h> #include <sys/ptrace.h> #include <asm/ptrace.h> #include <sys/prctl.h> #include <sys/time.h> /* * System calls defined in this file. */ namespace Syscall { SYSTEM_CALL pid_t getpid(void); SYSTEM_CALL pid_t getppid(void); SYSTEM_CALL pid_t gettid(void); SYSTEM_CALL pid_t fork(void); NO_RETURN SYSTEM_CALL int execve(const char *, char *const[], char *const[]); #if SYSCALL_EXISTS(execveat) NO_RETURN SYSTEM_CALL int execveat(int, const char *, char *const[], char *const[], int); #endif SYSTEM_CALL_INLINE long clone(unsigned long, void *, void *, void *, void *); SYSTEM_CALL int prctl(int, unsigned long, unsigned long, unsigned long, unsigned long); #if SYSCALL_EXISTS(setitimer) SYSTEM_CALL int setitimer(int, const struct itimerval *, struct itimerval *); #endif SYSTEM_CALL long ptrace(enum __ptrace_request, pid_t, void *, void *); SYSTEM_CALL pid_t wait4(pid_t, int *, int, struct rusage *); SYSTEM_CALL int waitid(idtype_t, id_t, siginfo_t *, int, struct rusage *); SYSTEM_CALL int tkill(pid_t, int); SYSTEM_CALL int kill(pid_t, int); NO_RETURN SYSTEM_CALL void exit(int); NO_RETURN SYSTEM_CALL void exit_group(int); SYSTEM_CALL pid_t getpid(void) { return DO_SYSCALL(getpid); } SYSTEM_CALL pid_t getppid(void) { return DO_SYSCALL(getppid); } SYSTEM_CALL pid_t gettid(void) { return DO_SYSCALL(gettid); } SYSTEM_CALL pid_t fork(void) { return DO_SYSCALL(fork); } NO_RETURN SYSTEM_CALL int execve(const char *filename, char *const argv[], char *const envp[]) { DO_SYSCALL(execve, filename, argv, envp); __builtin_unreachable(); } #if SYSCALL_EXISTS(execveat) NO_RETURN SYSTEM_CALL int execveat(int dirfd, const char *pathname, char *const argv[], char *const envp[], int flags) { DO_SYSCALL(execveat, dirfd, pathname, argv, envp, flags); __builtin_unreachable(); } #endif // // clone has the ability to change the child stack. // It must be always be inlined since it cannot return from another stack. // SYSTEM_CALL_INLINE long clone(unsigned long flags, void *child_stack, void *ptid, void *tls, void *ctid) { return DO_SYSCALL(clone, flags, child_stack, ptid, tls, ctid); } SYSTEM_CALL int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5) { return DO_SYSCALL(prctl, option, arg2, arg3, arg4, arg5); } #if SYSCALL_EXISTS(setitimer) SYSTEM_CALL int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue) { return DO_SYSCALL(setitimer, which, value, ovalue); } #endif SYSTEM_CALL unsigned int alarm(unsigned int seconds) { #if SYSCALL_EXISTS(alarm) return DO_SYSCALL(alarm, seconds); #else struct itimerval itv = { {0,0}, {0,0} }; itv.it_value.tv_sec = seconds; return Syscall::setitimer(ITIMER_REAL, &itv, &itv); #endif } SYSTEM_CALL int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { return DO_SYSCALL(rt_sigaction, signum, act, oldact, 8); } SYSTEM_CALL long ptrace(enum __ptrace_request request, pid_t pid, void *addr, void *data) { return DO_SYSCALL(ptrace, request, pid, addr, data); } SYSTEM_CALL pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage) { return DO_SYSCALL(wait4, pid, status, options, rusage); } SYSTEM_CALL int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options, struct rusage *rusage) { return DO_SYSCALL(waitid, idtype, id, infop, options, rusage); } SYSTEM_CALL int tkill(pid_t tid, int sig) { return DO_SYSCALL(tkill, tid, sig); } SYSTEM_CALL int kill(pid_t pid, int sig) { return DO_SYSCALL(kill, pid, sig); } NO_RETURN SYSTEM_CALL void exit(int status) { DO_SYSCALL(exit, status); __builtin_unreachable(); } NO_RETURN SYSTEM_CALL void exit_group(int status) { DO_SYSCALL(exit_group, status); __builtin_unreachable(); } } #endif <|endoftext|>
<commit_before>// See http://www.zaphoyd.com/websocketpp/manual/reference/cpp11-support // for prepocessor directives and choosing between boost and cpp11 // C++11 STL tokens #define _WEBSOCKETPP_CPP11_FUNCTIONAL_ #define _WEBSOCKETPP_CPP11_MEMORY_ #define _WEBSOCKETPP_CPP11_RANDOM_DEVICE_ #define _WEBSOCKETPP_CPP11_SYSTEM_ERROR_ #define _WEBSOCKETPP_NO_CPP11_THREAD_ #include <cpp-pcp-client/connector/connection.hpp> #include <cpp-pcp-client/connector/errors.hpp> #include <cpp-pcp-client/protocol/message.hpp> #include <cpp-pcp-client/util/thread.hpp> #include <cpp-pcp-client/util/chrono.hpp> #include <websocketpp/common/connection_hdl.hpp> #include <websocketpp/client.hpp> #include <websocketpp/config/asio_client.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CPP_PCP_CLIENT_LOGGING_PREFIX".connection" #include <leatherman/logging/logging.hpp> #include <cstdio> #include <iostream> #include <random> // TODO(ale): disable assert() once we're confident with the code... // To disable assert() // #define NDEBUG #include <cassert> namespace PCPClient { // // Constants // static const uint32_t CONNECTION_MIN_INTERVAL { 200 }; // [ms] static const uint32_t CONNECTION_BACKOFF_LIMIT { 33000 }; // [ms] static const uint32_t CONNECTION_BACKOFF_MULTIPLIER { 2 }; // // Connection // Connection::Connection(const std::string& broker_ws_uri, const ClientMetadata& client_metadata) : broker_ws_uri_ { broker_ws_uri }, client_metadata_ { client_metadata }, connection_state_ { ConnectionStateValues::initialized }, consecutive_pong_timeouts_ { 0 }, endpoint_ { new WS_Client_Type() }{ // Turn off websocketpp logging to avoid runtime errors (see CTH-69) endpoint_->clear_access_channels(websocketpp::log::alevel::all); endpoint_->clear_error_channels(websocketpp::log::elevel::all); // Initialize the transport system. Note that in perpetual mode, // the event loop does not terminate when there are no connections endpoint_->init_asio(); endpoint_->start_perpetual(); try { endpoint_->set_tls_init_handler( std::bind(&Connection::onTlsInit, this, std::placeholders::_1)); endpoint_->set_open_handler( std::bind(&Connection::onOpen, this, std::placeholders::_1)); endpoint_->set_close_handler( std::bind(&Connection::onClose, this, std::placeholders::_1)); endpoint_->set_fail_handler( std::bind(&Connection::onFail, this, std::placeholders::_1)); endpoint_->set_message_handler( std::bind(&Connection::onMessage, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_ping_handler( std::bind(&Connection::onPing, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_pong_handler( std::bind(&Connection::onPong, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_pong_timeout_handler( std::bind(&Connection::onPongTimeout, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_tcp_pre_init_handler( std::bind(&Connection::onPreTCPInit, this, std::placeholders::_1)); endpoint_->set_tcp_post_init_handler( std::bind(&Connection::onPostTCPInit, this, std::placeholders::_1)); // Start the event loop thread endpoint_thread_.reset(new Util::thread(&WS_Client_Type::run, endpoint_.get())); } catch (...) { LOG_DEBUG("Failed to configure the WebSocket endpoint; about to stop " "the event loop"); cleanUp(); throw connection_config_error { "failed to initialize" }; } } Connection::~Connection() { cleanUp(); } ConnectionState Connection::getConnectionState() { return connection_state_.load(); } // // Callback modifiers // void Connection::setOnOpenCallback(std::function<void()> c_b) { onOpen_callback = c_b; } void Connection::setOnMessageCallback(std::function<void(std::string msg)> c_b) { onMessage_callback_ = c_b; } void Connection::resetCallbacks() { onOpen_callback = [](){}; // NOLINT [false positive readability/braces] onMessage_callback_ = [](std::string message){}; // NOLINT [false positive readability/braces] } // // Synchronous calls // void Connection::connect(int max_connect_attempts) { // FSM // - states are ConnectionStateValues: // * initialized - connecting - open - closing - closed // - for the transitions, we assume that the connection_state_: // * can be set to 'initialized' only by the Connection constructor; // * is set to 'connecting' by connect_(); // * after a connect_() call, it will become, eventually, open or // closed. ConnectionState previous_c_s = connection_state_.load(); ConnectionState current_c_s; int idx { 0 }; bool try_again { true }; bool got_max_backoff { false }; std::random_device rd; std::default_random_engine engine(rd()); std::uniform_int_distribution<int> dist(-250, 250); do { current_c_s = connection_state_.load(); idx++; if (max_connect_attempts) { try_again = (idx < max_connect_attempts); } got_max_backoff |= (connection_backoff_ms_ * CONNECTION_BACKOFF_MULTIPLIER >= CONNECTION_BACKOFF_LIMIT); switch (current_c_s) { case(ConnectionStateValues::initialized): assert(previous_c_s == ConnectionStateValues::initialized); connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); break; case(ConnectionStateValues::connecting): previous_c_s = ConnectionStateValues::connecting; Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); continue; case(ConnectionStateValues::open): if (previous_c_s != ConnectionStateValues::open) { connection_backoff_ms_ = CONNECTION_BACKOFF_MS; } return; case(ConnectionStateValues::closing): previous_c_s = ConnectionStateValues::closing; Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); continue; case(ConnectionStateValues::closed): if (previous_c_s == ConnectionStateValues::closed) { connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); previous_c_s = ConnectionStateValues::connecting; } else { LOG_WARNING("Failed to establish a WebSocket connection; " "retrying in %1% seconds", static_cast<int>(connection_backoff_ms_ / 1000)); // Randomly adjust the interval slightly to help calm a // thundering herd Util::this_thread::sleep_for( Util::chrono::milliseconds(connection_backoff_ms_ + dist(engine))); connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); if (try_again && !got_max_backoff) { connection_backoff_ms_ *= CONNECTION_BACKOFF_MULTIPLIER; } } break; } } while (try_again); connection_backoff_ms_ = CONNECTION_BACKOFF_MS; throw connection_fatal_error { "failed to establish a WebSocket connection " "after " + std::to_string(idx) + " attempt" + (idx > 1 ? "s" : "") }; } void Connection::send(const std::string& msg) { websocketpp::lib::error_code ec; endpoint_->send(connection_handle_, msg, websocketpp::frame::opcode::binary, ec); if (ec) { throw connection_processing_error { "failed to send message: " + ec.message() }; } } void Connection::send(void* const serialized_msg_ptr, size_t msg_len) { websocketpp::lib::error_code ec; endpoint_->send(connection_handle_, serialized_msg_ptr, msg_len, websocketpp::frame::opcode::binary, ec); if (ec) { throw connection_processing_error { "failed to send message: " + ec.message() }; } } void Connection::ping(const std::string& binary_payload) { websocketpp::lib::error_code ec; endpoint_->ping(connection_handle_, binary_payload, ec); if (ec) { throw connection_processing_error { "failed to send WebSocket ping: " + ec.message() }; } } void Connection::close(CloseCode code, const std::string& reason) { LOG_DEBUG("About to close connection"); websocketpp::lib::error_code ec; endpoint_->close(connection_handle_, code, reason, ec); if (ec) { throw connection_processing_error { "failed to close WebSocket " "connection: " + ec.message() }; } } // // Private interface // void Connection::cleanUp() { endpoint_->stop_perpetual(); if (connection_state_ == ConnectionStateValues::open) { try { close(); } catch (connection_processing_error& e) { LOG_ERROR("Failed to close the WebSocket connection: %1%", e.what()); } } if (endpoint_thread_ != nullptr && endpoint_thread_->joinable()) { endpoint_thread_->join(); } } void Connection::connect_() { connection_state_ = ConnectionStateValues::connecting; connection_timings_ = ConnectionTimings(); websocketpp::lib::error_code ec; WS_Client_Type::connection_ptr connection_ptr { endpoint_->get_connection(broker_ws_uri_, ec) }; if (ec) { throw connection_processing_error { "failed to establish the WebSocket " "connection with " + broker_ws_uri_ + ": " + ec.message() }; } connection_handle_ = connection_ptr->get_handle(); endpoint_->connect(connection_ptr); } // // Event handlers (private) // WS_Context_Ptr Connection::onTlsInit(WS_Connection_Handle hdl) { LOG_INFO("WebSocket TLS initialization event; about to validate the certificate"); // NB: for TLS certificates, refer to: // www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/ssl__context.html WS_Context_Ptr ctx { new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1) }; try { ctx->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); ctx->use_certificate_file(client_metadata_.crt, boost::asio::ssl::context::file_format::pem); ctx->use_private_key_file(client_metadata_.key, boost::asio::ssl::context::file_format::pem); ctx->load_verify_file(client_metadata_.ca); } catch (std::exception& e) { LOG_ERROR("Failed to configure TLS: %1%", e.what()); } return ctx; } void Connection::onClose(WS_Connection_Handle hdl) { connection_timings_.close = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket connection closed"); connection_state_ = ConnectionStateValues::closed; } void Connection::onFail(WS_Connection_Handle hdl) { connection_timings_.close = Util::chrono::high_resolution_clock::now(); connection_timings_.connection_failed = true; LOG_DEBUG("WebSocket on fail event - %1%", connection_timings_.toString()); connection_state_ = ConnectionStateValues::closed; } bool Connection::onPing(WS_Connection_Handle hdl, std::string binary_payload) { LOG_TRACE("WebSocket onPing event - payload: %1%", binary_payload); // Returning true so the transport layer will send back a pong return true; } void Connection::onPong(WS_Connection_Handle hdl, std::string binary_payload) { LOG_DEBUG("WebSocket onPong event"); if (consecutive_pong_timeouts_) { consecutive_pong_timeouts_ = 0; } } void Connection::onPongTimeout(WS_Connection_Handle hdl, std::string binary_payload) { LOG_WARNING("WebSocket onPongTimeout event (%1% consecutive)", consecutive_pong_timeouts_++); } void Connection::onPreTCPInit(WS_Connection_Handle hdl) { connection_timings_.tcp_pre_init = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket pre-TCP initialization event"); } void Connection::onPostTCPInit(WS_Connection_Handle hdl) { connection_timings_.tcp_post_init = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket post-TCP initialization event"); } void Connection::onOpen(WS_Connection_Handle hdl) { connection_timings_.open = Util::chrono::high_resolution_clock::now(); connection_timings_.connection_started = true; LOG_DEBUG("WebSocket on open event - %1%", connection_timings_.toString()); LOG_INFO("WebSocket connection established"); connection_state_ = ConnectionStateValues::open; if (onOpen_callback) { try { onOpen_callback(); return; } catch (std::exception& e) { LOG_ERROR("onOpen callback failure: %1%; closing the " "WebSocket connection", e.what()); } catch (...) { LOG_ERROR("onOpen callback failure; closing the WebSocket " "connection"); } close(CloseCodeValues::normal, "onOpen callback failure"); } } void Connection::onMessage(WS_Connection_Handle hdl, WS_Client_Type::message_ptr msg) { if (onMessage_callback_) { try { // NB: on_message_callback_ should not raise; in case of // failure; it must be able to notify back the error... onMessage_callback_(msg->get_payload()); } catch (std::exception& e) { LOG_ERROR("onMessage WebSocket callback failure: %1%", e.what()); } catch (...) { LOG_ERROR("onMessage WebSocket callback failure: unexpected error"); } } } } // namespace PCPClient <commit_msg>(PCP-5) Improve OPEN event log message<commit_after>// See http://www.zaphoyd.com/websocketpp/manual/reference/cpp11-support // for prepocessor directives and choosing between boost and cpp11 // C++11 STL tokens #define _WEBSOCKETPP_CPP11_FUNCTIONAL_ #define _WEBSOCKETPP_CPP11_MEMORY_ #define _WEBSOCKETPP_CPP11_RANDOM_DEVICE_ #define _WEBSOCKETPP_CPP11_SYSTEM_ERROR_ #define _WEBSOCKETPP_NO_CPP11_THREAD_ #include <cpp-pcp-client/connector/connection.hpp> #include <cpp-pcp-client/connector/errors.hpp> #include <cpp-pcp-client/protocol/message.hpp> #include <cpp-pcp-client/util/thread.hpp> #include <cpp-pcp-client/util/chrono.hpp> #include <websocketpp/common/connection_hdl.hpp> #include <websocketpp/client.hpp> #include <websocketpp/config/asio_client.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CPP_PCP_CLIENT_LOGGING_PREFIX".connection" #include <leatherman/logging/logging.hpp> #include <cstdio> #include <iostream> #include <random> // TODO(ale): disable assert() once we're confident with the code... // To disable assert() // #define NDEBUG #include <cassert> namespace PCPClient { // // Constants // static const uint32_t CONNECTION_MIN_INTERVAL { 200 }; // [ms] static const uint32_t CONNECTION_BACKOFF_LIMIT { 33000 }; // [ms] static const uint32_t CONNECTION_BACKOFF_MULTIPLIER { 2 }; // // Connection // Connection::Connection(const std::string& broker_ws_uri, const ClientMetadata& client_metadata) : broker_ws_uri_ { broker_ws_uri }, client_metadata_ { client_metadata }, connection_state_ { ConnectionStateValues::initialized }, consecutive_pong_timeouts_ { 0 }, endpoint_ { new WS_Client_Type() }{ // Turn off websocketpp logging to avoid runtime errors (see CTH-69) endpoint_->clear_access_channels(websocketpp::log::alevel::all); endpoint_->clear_error_channels(websocketpp::log::elevel::all); // Initialize the transport system. Note that in perpetual mode, // the event loop does not terminate when there are no connections endpoint_->init_asio(); endpoint_->start_perpetual(); try { endpoint_->set_tls_init_handler( std::bind(&Connection::onTlsInit, this, std::placeholders::_1)); endpoint_->set_open_handler( std::bind(&Connection::onOpen, this, std::placeholders::_1)); endpoint_->set_close_handler( std::bind(&Connection::onClose, this, std::placeholders::_1)); endpoint_->set_fail_handler( std::bind(&Connection::onFail, this, std::placeholders::_1)); endpoint_->set_message_handler( std::bind(&Connection::onMessage, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_ping_handler( std::bind(&Connection::onPing, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_pong_handler( std::bind(&Connection::onPong, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_pong_timeout_handler( std::bind(&Connection::onPongTimeout, this, std::placeholders::_1, std::placeholders::_2)); endpoint_->set_tcp_pre_init_handler( std::bind(&Connection::onPreTCPInit, this, std::placeholders::_1)); endpoint_->set_tcp_post_init_handler( std::bind(&Connection::onPostTCPInit, this, std::placeholders::_1)); // Start the event loop thread endpoint_thread_.reset(new Util::thread(&WS_Client_Type::run, endpoint_.get())); } catch (...) { LOG_DEBUG("Failed to configure the WebSocket endpoint; about to stop " "the event loop"); cleanUp(); throw connection_config_error { "failed to initialize" }; } } Connection::~Connection() { cleanUp(); } ConnectionState Connection::getConnectionState() { return connection_state_.load(); } // // Callback modifiers // void Connection::setOnOpenCallback(std::function<void()> c_b) { onOpen_callback = c_b; } void Connection::setOnMessageCallback(std::function<void(std::string msg)> c_b) { onMessage_callback_ = c_b; } void Connection::resetCallbacks() { onOpen_callback = [](){}; // NOLINT [false positive readability/braces] onMessage_callback_ = [](std::string message){}; // NOLINT [false positive readability/braces] } // // Synchronous calls // void Connection::connect(int max_connect_attempts) { // FSM // - states are ConnectionStateValues: // * initialized - connecting - open - closing - closed // - for the transitions, we assume that the connection_state_: // * can be set to 'initialized' only by the Connection constructor; // * is set to 'connecting' by connect_(); // * after a connect_() call, it will become, eventually, open or // closed. ConnectionState previous_c_s = connection_state_.load(); ConnectionState current_c_s; int idx { 0 }; bool try_again { true }; bool got_max_backoff { false }; std::random_device rd; std::default_random_engine engine(rd()); std::uniform_int_distribution<int> dist(-250, 250); do { current_c_s = connection_state_.load(); idx++; if (max_connect_attempts) { try_again = (idx < max_connect_attempts); } got_max_backoff |= (connection_backoff_ms_ * CONNECTION_BACKOFF_MULTIPLIER >= CONNECTION_BACKOFF_LIMIT); switch (current_c_s) { case(ConnectionStateValues::initialized): assert(previous_c_s == ConnectionStateValues::initialized); connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); break; case(ConnectionStateValues::connecting): previous_c_s = ConnectionStateValues::connecting; Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); continue; case(ConnectionStateValues::open): if (previous_c_s != ConnectionStateValues::open) { connection_backoff_ms_ = CONNECTION_BACKOFF_MS; } return; case(ConnectionStateValues::closing): previous_c_s = ConnectionStateValues::closing; Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); continue; case(ConnectionStateValues::closed): if (previous_c_s == ConnectionStateValues::closed) { connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); previous_c_s = ConnectionStateValues::connecting; } else { LOG_WARNING("Failed to establish a WebSocket connection; " "retrying in %1% seconds", static_cast<int>(connection_backoff_ms_ / 1000)); // Randomly adjust the interval slightly to help calm a // thundering herd Util::this_thread::sleep_for( Util::chrono::milliseconds(connection_backoff_ms_ + dist(engine))); connect_(); Util::this_thread::sleep_for( Util::chrono::milliseconds(CONNECTION_MIN_INTERVAL)); if (try_again && !got_max_backoff) { connection_backoff_ms_ *= CONNECTION_BACKOFF_MULTIPLIER; } } break; } } while (try_again); connection_backoff_ms_ = CONNECTION_BACKOFF_MS; throw connection_fatal_error { "failed to establish a WebSocket connection " "after " + std::to_string(idx) + " attempt" + (idx > 1 ? "s" : "") }; } void Connection::send(const std::string& msg) { websocketpp::lib::error_code ec; endpoint_->send(connection_handle_, msg, websocketpp::frame::opcode::binary, ec); if (ec) { throw connection_processing_error { "failed to send message: " + ec.message() }; } } void Connection::send(void* const serialized_msg_ptr, size_t msg_len) { websocketpp::lib::error_code ec; endpoint_->send(connection_handle_, serialized_msg_ptr, msg_len, websocketpp::frame::opcode::binary, ec); if (ec) { throw connection_processing_error { "failed to send message: " + ec.message() }; } } void Connection::ping(const std::string& binary_payload) { websocketpp::lib::error_code ec; endpoint_->ping(connection_handle_, binary_payload, ec); if (ec) { throw connection_processing_error { "failed to send WebSocket ping: " + ec.message() }; } } void Connection::close(CloseCode code, const std::string& reason) { LOG_DEBUG("About to close connection"); websocketpp::lib::error_code ec; endpoint_->close(connection_handle_, code, reason, ec); if (ec) { throw connection_processing_error { "failed to close WebSocket " "connection: " + ec.message() }; } } // // Private interface // void Connection::cleanUp() { endpoint_->stop_perpetual(); if (connection_state_ == ConnectionStateValues::open) { try { close(); } catch (connection_processing_error& e) { LOG_ERROR("Failed to close the WebSocket connection: %1%", e.what()); } } if (endpoint_thread_ != nullptr && endpoint_thread_->joinable()) { endpoint_thread_->join(); } } void Connection::connect_() { connection_state_ = ConnectionStateValues::connecting; connection_timings_ = ConnectionTimings(); websocketpp::lib::error_code ec; WS_Client_Type::connection_ptr connection_ptr { endpoint_->get_connection(broker_ws_uri_, ec) }; if (ec) { throw connection_processing_error { "failed to establish the WebSocket " "connection with " + broker_ws_uri_ + ": " + ec.message() }; } connection_handle_ = connection_ptr->get_handle(); endpoint_->connect(connection_ptr); } // // Event handlers (private) // WS_Context_Ptr Connection::onTlsInit(WS_Connection_Handle hdl) { LOG_INFO("WebSocket TLS initialization event; about to validate the certificate"); // NB: for TLS certificates, refer to: // www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/ssl__context.html WS_Context_Ptr ctx { new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1) }; try { ctx->set_options(boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); ctx->use_certificate_file(client_metadata_.crt, boost::asio::ssl::context::file_format::pem); ctx->use_private_key_file(client_metadata_.key, boost::asio::ssl::context::file_format::pem); ctx->load_verify_file(client_metadata_.ca); } catch (std::exception& e) { LOG_ERROR("Failed to configure TLS: %1%", e.what()); } return ctx; } void Connection::onClose(WS_Connection_Handle hdl) { connection_timings_.close = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket connection closed"); connection_state_ = ConnectionStateValues::closed; } void Connection::onFail(WS_Connection_Handle hdl) { connection_timings_.close = Util::chrono::high_resolution_clock::now(); connection_timings_.connection_failed = true; LOG_DEBUG("WebSocket on fail event - %1%", connection_timings_.toString()); connection_state_ = ConnectionStateValues::closed; } bool Connection::onPing(WS_Connection_Handle hdl, std::string binary_payload) { LOG_TRACE("WebSocket onPing event - payload: %1%", binary_payload); // Returning true so the transport layer will send back a pong return true; } void Connection::onPong(WS_Connection_Handle hdl, std::string binary_payload) { LOG_DEBUG("WebSocket onPong event"); if (consecutive_pong_timeouts_) { consecutive_pong_timeouts_ = 0; } } void Connection::onPongTimeout(WS_Connection_Handle hdl, std::string binary_payload) { LOG_WARNING("WebSocket onPongTimeout event (%1% consecutive)", consecutive_pong_timeouts_++); } void Connection::onPreTCPInit(WS_Connection_Handle hdl) { connection_timings_.tcp_pre_init = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket pre-TCP initialization event"); } void Connection::onPostTCPInit(WS_Connection_Handle hdl) { connection_timings_.tcp_post_init = Util::chrono::high_resolution_clock::now(); LOG_TRACE("WebSocket post-TCP initialization event"); } void Connection::onOpen(WS_Connection_Handle hdl) { connection_timings_.open = Util::chrono::high_resolution_clock::now(); connection_timings_.connection_started = true; LOG_DEBUG("WebSocket on open event - %1%", connection_timings_.toString()); LOG_INFO("Successfully established a WebSocket connection with the PCP broker"); connection_state_ = ConnectionStateValues::open; if (onOpen_callback) { try { onOpen_callback(); return; } catch (std::exception& e) { LOG_ERROR("onOpen callback failure: %1%; closing the " "WebSocket connection", e.what()); } catch (...) { LOG_ERROR("onOpen callback failure; closing the WebSocket " "connection"); } close(CloseCodeValues::normal, "onOpen callback failure"); } } void Connection::onMessage(WS_Connection_Handle hdl, WS_Client_Type::message_ptr msg) { if (onMessage_callback_) { try { // NB: on_message_callback_ should not raise; in case of // failure; it must be able to notify back the error... onMessage_callback_(msg->get_payload()); } catch (std::exception& e) { LOG_ERROR("onMessage WebSocket callback failure: %1%", e.what()); } catch (...) { LOG_ERROR("onMessage WebSocket callback failure: unexpected error"); } } } } // namespace PCPClient <|endoftext|>
<commit_before> #include "bhget.h" #include <iostream> #include <list> #include <sstream> #include <utility> #include "buildconf.hpp" namespace asio = boost::asio; namespace po = boost::program_options; using namespace std; using namespace bithorde; const static size_t BLOCK_SIZE = (64*1024); const static size_t PARALLELL_BLOCKS = (4); struct OutQueue { typedef pair<uint64_t, string> Chunk; uint64_t position; list<Chunk> _stored; OutQueue() : position(0) {} void send(uint64_t offset, const string& data) { if (offset <= position) { BOOST_ASSERT(offset == position); _flush(data); _dequeue(); } else { _queue(offset, data); } } private: void _queue(uint64_t offset, const string& data) { list<Chunk>::iterator pos = _stored.begin(); while ((pos != _stored.end()) && (pos->first < offset)) pos++; _stored.insert(pos, Chunk(offset, data)); } void _dequeue() { while (_stored.size()) { Chunk& first = _stored.front(); if (first.first > position) { break; } else { BOOST_ASSERT(first.first == position); _flush(first.second); _stored.pop_front(); } } } void _flush(const string& data) { ssize_t datasize = data.size(); if (write(1, data.data(), datasize) == datasize) position += datasize; else (cerr << "ERROR: failed to write block" << endl).flush(); } }; BHGet::BHGet(po::variables_map& args) : optMyName(args["name"].as<string>()), optQuiet(args.count("quiet")), optConnectUrl(args["url"].as<string>()), _res(0), optDebug(false) {} int BHGet::main(const std::vector<std::string>& args) { _res = 0; std::vector<std::string>::const_iterator iter; for (iter = args.begin(); iter != args.end(); iter++) { if (!queueAsset(*iter)) return 1; } _client = Client::create(_ioSvc, optMyName); _client->authenticated.connect(boost::bind(&BHGet::onAuthenticated, this, _1, _2)); _client->connect(optConnectUrl); _ioSvc.run(); return _res; } bool resolvePath(MagnetURI& uri, const std::string &path_) { char pathbuf[PATH_MAX]; auto path__ = realpath(path_.c_str(), pathbuf); if (!path__) { return false; } else { boost::filesystem::path p(path__); return uri.parse(p.filename().string()); } } bool BHGet::queueAsset(const std::string& _uri) { MagnetURI uri; if (!uri.parse(_uri) && !resolvePath(uri, _uri)) { cerr << "ERROR: Only magnet-links and symlinks to magnet-links supported, not '" << _uri << "'" << endl; return false; } if (uri.xtIds.size()) { _assets.push_back(uri); return true; } else { cerr << "ERROR: No hash-Identifiers in '" << _uri << "'" << endl; return false; } } void BHGet::nextAsset() { if (_asset) { _asset->close(); _asset.reset(); } BitHordeIds ids; while ((!ids.size()) && (!_assets.empty())) { MagnetURI nextUri = _assets.front(); _assets.pop_front(); ids = nextUri.toIdList(); } if (!ids.size()) { _ioSvc.stop(); return; } _asset.reset(new ReadAsset(_client, ids)); _asset->statusUpdate.connect(boost::bind(&BHGet::onStatusUpdate, this, _1)); _asset->dataArrived.connect(boost::bind(&BHGet::onDataChunk, this, _1, _2, _3)); _client->bind(*_asset); _outQueue = new OutQueue(); _currentOffset = 0; } void BHGet::onStatusUpdate(const bithorde::AssetStatus& status) { switch (status.status()) { case bithorde::SUCCESS: if (status.size() > 0) { if (status.handle()) { if (optDebug) cerr << "DEBUG: Downloading ..." << endl; requestMore(); } else { cerr << "WARNING: Broken response" << endl; nextAsset(); } } else { cerr << "DEBUG: Zero-sized asset, skipping ..." << endl; nextAsset(); } break; default: cerr << "ERROR: Failed (" << bithorde::Status_Name(status.status()) << ") ..." << endl; _res += 1; nextAsset(); break; } } void BHGet::requestMore() { while (_currentOffset < (_outQueue->position + (BLOCK_SIZE*PARALLELL_BLOCKS)) && _currentOffset < _asset->size()) { _asset->aSyncRead(_currentOffset, BLOCK_SIZE); _currentOffset += BLOCK_SIZE; } } void BHGet::onDataChunk(uint64_t offset, const string& data, int tag) { if ((data.size() < BLOCK_SIZE) && ((offset+data.size()) < _asset->size())) { cerr << "ERROR: got unexpectedly small data-block " << data.size() << " vs. " << BLOCK_SIZE << endl; } _outQueue->send(offset, data); if (_outQueue->position < _asset->size()) { requestMore(); } else { nextAsset(); } } void BHGet::onAuthenticated(Client& c, const string& peerName) { if (peerName.empty()) { cerr << "Failed authentication" << endl; _ioSvc.stop(); } if (optDebug) cerr << "DEBUG: Connected to " << peerName << endl; cerr.flush(); nextAsset(); } int main(int argc, char *argv[]) { po::options_description desc("Supported options"); desc.add_options() ("help,h", "Show help") ("debug,d", "Activate debug-logging") ("version,v", "Show version") ("name,n", po::value< string >()->default_value("bhget"), "Bithorde-name of this client") ("quiet,q", "Don't show progressbar") ("url,u", po::value< string >()->default_value("/tmp/bithorde"), "Where to connect to bithorde. Either host:port, or /path/socket") ("magnet-url", po::value< vector<string> >(), "magnet url(s) to fetch") ; po::positional_options_description p; p.add("magnet-url", -1); po::command_line_parser parser(argc, argv); parser.options(desc).positional(p); po::variables_map vm; po::store(parser.run(), vm); po::notify(vm); if (vm.count("version")) return bithorde::exit_version(); if (vm.count("help") || !vm.count("magnet-url")) { cerr << desc << endl; return 1; } int res = -1; try { BHGet app(vm); app.optDebug = vm.count("debug"); res = app.main(vm["magnet-url"].as< vector<string> >()); } catch (std::string err) { cerr << err << endl; } cerr.flush(); return res; } <commit_msg>[clients/bhget]Unbind previous asset when fetching next.<commit_after> #include "bhget.h" #include <iostream> #include <list> #include <sstream> #include <utility> #include "buildconf.hpp" namespace asio = boost::asio; namespace po = boost::program_options; using namespace std; using namespace bithorde; const static size_t BLOCK_SIZE = (64*1024); const static size_t PARALLELL_BLOCKS = (4); struct OutQueue { typedef pair<uint64_t, string> Chunk; uint64_t position; list<Chunk> _stored; OutQueue() : position(0) {} void send(uint64_t offset, const string& data) { if (offset <= position) { BOOST_ASSERT(offset == position); _flush(data); _dequeue(); } else { _queue(offset, data); } } private: void _queue(uint64_t offset, const string& data) { list<Chunk>::iterator pos = _stored.begin(); while ((pos != _stored.end()) && (pos->first < offset)) pos++; _stored.insert(pos, Chunk(offset, data)); } void _dequeue() { while (_stored.size()) { Chunk& first = _stored.front(); if (first.first > position) { break; } else { BOOST_ASSERT(first.first == position); _flush(first.second); _stored.pop_front(); } } } void _flush(const string& data) { ssize_t datasize = data.size(); if (write(1, data.data(), datasize) == datasize) position += datasize; else (cerr << "ERROR: failed to write block" << endl).flush(); } }; BHGet::BHGet(po::variables_map& args) : optMyName(args["name"].as<string>()), optQuiet(args.count("quiet")), optConnectUrl(args["url"].as<string>()), _res(0), optDebug(false) {} int BHGet::main(const std::vector<std::string>& args) { _res = 0; std::vector<std::string>::const_iterator iter; for (iter = args.begin(); iter != args.end(); iter++) { if (!queueAsset(*iter)) return 1; } _client = Client::create(_ioSvc, optMyName); _client->authenticated.connect(boost::bind(&BHGet::onAuthenticated, this, _1, _2)); _client->connect(optConnectUrl); _ioSvc.run(); return _res; } bool resolvePath(MagnetURI& uri, const std::string &path_) { char pathbuf[PATH_MAX]; auto path__ = realpath(path_.c_str(), pathbuf); if (!path__) { return false; } else { boost::filesystem::path p(path__); return uri.parse(p.filename().string()); } } bool BHGet::queueAsset(const std::string& _uri) { MagnetURI uri; if (!uri.parse(_uri) && !resolvePath(uri, _uri)) { cerr << "ERROR: Only magnet-links and symlinks to magnet-links supported, not '" << _uri << "'" << endl; return false; } if (uri.xtIds.size()) { _assets.push_back(uri); return true; } else { cerr << "ERROR: No hash-Identifiers in '" << _uri << "'" << endl; return false; } } void BHGet::nextAsset() { if (_asset) { _asset->statusUpdate.disconnect(boost::bind(&BHGet::onStatusUpdate, this, _1)); _asset->dataArrived.disconnect(boost::bind(&BHGet::onDataChunk, this, _1, _2, _3)); _asset->close(); _asset.reset(); } BitHordeIds ids; while ((!ids.size()) && (!_assets.empty())) { MagnetURI nextUri = _assets.front(); _assets.pop_front(); ids = nextUri.toIdList(); } if (!ids.size()) { _ioSvc.stop(); return; } _asset.reset(new ReadAsset(_client, ids)); _asset->statusUpdate.connect(boost::bind(&BHGet::onStatusUpdate, this, _1)); _asset->dataArrived.connect(boost::bind(&BHGet::onDataChunk, this, _1, _2, _3)); _client->bind(*_asset); _outQueue = new OutQueue(); _currentOffset = 0; } void BHGet::onStatusUpdate(const bithorde::AssetStatus& status) { switch (status.status()) { case bithorde::SUCCESS: if (status.size() > 0) { if (status.handle()) { if (optDebug) cerr << "DEBUG: Downloading ..." << endl; requestMore(); } else { cerr << "WARNING: Broken response" << endl; nextAsset(); } } else { cerr << "DEBUG: Zero-sized asset, skipping ..." << endl; nextAsset(); } break; default: cerr << "ERROR: Failed (" << bithorde::Status_Name(status.status()) << ") ..." << endl; _res += 1; nextAsset(); break; } } void BHGet::requestMore() { while (_currentOffset < (_outQueue->position + (BLOCK_SIZE*PARALLELL_BLOCKS)) && _currentOffset < _asset->size()) { _asset->aSyncRead(_currentOffset, BLOCK_SIZE); _currentOffset += BLOCK_SIZE; } } void BHGet::onDataChunk(uint64_t offset, const string& data, int tag) { if ((data.size() < BLOCK_SIZE) && ((offset+data.size()) < _asset->size())) { cerr << "ERROR: got unexpectedly small data-block " << data.size() << " vs. " << BLOCK_SIZE << endl; } _outQueue->send(offset, data); if (_outQueue->position < _asset->size()) { requestMore(); } else { nextAsset(); } } void BHGet::onAuthenticated(Client& c, const string& peerName) { if (peerName.empty()) { cerr << "Failed authentication" << endl; _ioSvc.stop(); } if (optDebug) cerr << "DEBUG: Connected to " << peerName << endl; cerr.flush(); nextAsset(); } int main(int argc, char *argv[]) { po::options_description desc("Supported options"); desc.add_options() ("help,h", "Show help") ("debug,d", "Activate debug-logging") ("version,v", "Show version") ("name,n", po::value< string >()->default_value("bhget"), "Bithorde-name of this client") ("quiet,q", "Don't show progressbar") ("url,u", po::value< string >()->default_value("/tmp/bithorde"), "Where to connect to bithorde. Either host:port, or /path/socket") ("magnet-url", po::value< vector<string> >(), "magnet url(s) to fetch") ; po::positional_options_description p; p.add("magnet-url", -1); po::command_line_parser parser(argc, argv); parser.options(desc).positional(p); po::variables_map vm; po::store(parser.run(), vm); po::notify(vm); if (vm.count("version")) return bithorde::exit_version(); if (vm.count("help") || !vm.count("magnet-url")) { cerr << desc << endl; return 1; } int res = -1; try { BHGet app(vm); app.optDebug = vm.count("debug"); res = app.main(vm["magnet-url"].as< vector<string> >()); } catch (std::string err) { cerr << err << endl; } cerr.flush(); return res; } <|endoftext|>
<commit_before>#include "ScreamRx.h" #include "ScreamTx.h" #include <string.h> #include <climits> #include <algorithm> #include <iostream> using namespace std; ScreamRx::Stream::Stream(uint32_t ssrc_) { ssrc = ssrc_; ackVector = 0; receiveTimestamp = 0x0; highestSeqNr = 0x0; lastFeedbackT_us = 0; nRtpSinceLastRtcp = 0; firstReceived = false; } bool ScreamRx::Stream::checkIfFlushAck(int seqNr) { return (seqNr - highestSeqNr > kAckVectorBits/2) && nRtpSinceLastRtcp >= 1; } void ScreamRx::Stream::receive(uint64_t time_us, void* rtpPacket, int size, uint16_t seqNr) { nRtpSinceLastRtcp++; /* * Make things wrap-around safe */ if (firstReceived == false) { highestSeqNr = seqNr; highestSeqNr--; firstReceived = true; } uint32_t seqNrExt = seqNr; uint32_t highestSeqNrExt = highestSeqNr; if (seqNr < highestSeqNr) { if (highestSeqNr - seqNr > 1000) seqNrExt += 65536; } if (highestSeqNr < seqNr) { if (seqNr - highestSeqNr > 1000) highestSeqNrExt += 65536; } /* * Update the ACK vector that indicates receiption '=1' of RTP packets prior to * the highest received sequence number. * The next highest SN is indicated by the least significant bit, * this means that for the first received RTP, the ACK vector is * 0x0, for the second received RTP, the ACK vector it is 0x1, for the third 0x3 and so * on, provided that no packets are lost. * A 64 bit ACK vector means that it theory it is possible to send one feedback every * 64 RTP packets, while this can possibly work at low bitrates, it is less likely to work * at high bitrates because the ACK clocking in SCReAM is disturbed then. */ if (seqNrExt >= highestSeqNrExt) { /* * Normal in-order reception */ uint16_t diff = seqNrExt - highestSeqNrExt; if (diff != 0) { if (diff >= kAckVectorBits) { ackVector = 0x0000; } else { // Fill with potential zeros ackVector = ackVector << diff; // Add previous highest seq nr to ack vector ackVector |= (INT64_C(1) << (diff - 1)); } } highestSeqNr = seqNr; } else { /* * Out-of-order reception */ uint16_t diff = highestSeqNrExt - seqNrExt; if (diff < kAckVectorBits) { ackVector = ackVector | (INT64_C(1) << (diff - 1)); } } receiveTimestamp = (uint32_t)(time_us / (int(1000000 / kTimestampRate))); } ScreamRx::ScreamRx() { lastFeedbackT_us = 0; bytesReceived = 0; lastRateComputeT_us = 0; averageReceivedRate = 1e5; } bool ScreamRx::checkIfFlushAck( uint32_t ssrc, uint16_t seqNr) { if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->isMatch(ssrc)) { /* * Packets for this SSRC received earlier * stream is thus already in list */ return (*it)->checkIfFlushAck(seqNr); } } } return false; } void ScreamRx::receive(uint64_t time_us, void* rtpPacket, uint32_t ssrc, int size, uint16_t seqNr) { bytesReceived += size; if (lastRateComputeT_us == 0) lastRateComputeT_us = time_us; if (time_us - lastRateComputeT_us > 200000) { /* * Media rate computation (for all medias) is done at least every 200ms * This is used for RTCP feedback rate calculation */ float delta = (time_us - lastRateComputeT_us) / 1e6f; lastRateComputeT_us = time_us; averageReceivedRate = std::max(0.95f*averageReceivedRate, bytesReceived * 8 / delta); bytesReceived = 0; } if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->isMatch(ssrc)) { /* * Packets for this SSRC received earlier * stream is thus already in list */ (*it)->receive(time_us, rtpPacket, size, seqNr); return; } } } /* * New {SSRC,PT} */ Stream *stream = new Stream(ssrc); stream->receive(time_us, rtpPacket, size, seqNr); streams.push_back(stream); } uint64_t ScreamRx::getRtcpFbInterval() { /* * The RTCP feedback rate depends on the received media date * at very low bitrates (<50kbps) an RTCP feedback interval of ~200ms is sufficient * while higher rates (>2Mbps) a feedback interval of ~20ms is sufficient */ float res = 1000000 / std::min(100.0f, std::max(10.0f, averageReceivedRate / 10000.0f)); return uint64_t(res); } bool ScreamRx::isFeedback(uint64_t time_us) { if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { Stream *stream = (*it); if (stream->nRtpSinceLastRtcp >= 1) { return true; } } } return false; } bool ScreamRx::getFeedback(uint64_t time_us, uint32_t &ssrc, uint32_t &receiveTimestamp, uint16_t &highestSeqNr, uint64_t &ackVector) { Stream *stream = NULL; uint64_t minT_us = ULONG_MAX; for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->nRtpSinceLastRtcp > 0 && (*it)->lastFeedbackT_us < minT_us) { stream = *it; minT_us = (*it)->lastFeedbackT_us; } } if (stream == NULL) return false; receiveTimestamp = stream->receiveTimestamp; highestSeqNr = stream->highestSeqNr; ssrc = stream->ssrc; ackVector = stream->ackVector; stream->lastFeedbackT_us = time_us; stream->nRtpSinceLastRtcp = 0; lastFeedbackT_us = time_us; return true; } <commit_msg>FIX use ULLONG_MAX for uint64_t<commit_after>#include "ScreamRx.h" #include "ScreamTx.h" #include <string.h> #include <climits> #include <algorithm> #include <iostream> using namespace std; ScreamRx::Stream::Stream(uint32_t ssrc_) { ssrc = ssrc_; ackVector = 0; receiveTimestamp = 0x0; highestSeqNr = 0x0; lastFeedbackT_us = 0; nRtpSinceLastRtcp = 0; firstReceived = false; } bool ScreamRx::Stream::checkIfFlushAck(int seqNr) { return (seqNr - highestSeqNr > kAckVectorBits/2) && nRtpSinceLastRtcp >= 1; } void ScreamRx::Stream::receive(uint64_t time_us, void* rtpPacket, int size, uint16_t seqNr) { nRtpSinceLastRtcp++; /* * Make things wrap-around safe */ if (firstReceived == false) { highestSeqNr = seqNr; highestSeqNr--; firstReceived = true; } uint32_t seqNrExt = seqNr; uint32_t highestSeqNrExt = highestSeqNr; if (seqNr < highestSeqNr) { if (highestSeqNr - seqNr > 1000) seqNrExt += 65536; } if (highestSeqNr < seqNr) { if (seqNr - highestSeqNr > 1000) highestSeqNrExt += 65536; } /* * Update the ACK vector that indicates receiption '=1' of RTP packets prior to * the highest received sequence number. * The next highest SN is indicated by the least significant bit, * this means that for the first received RTP, the ACK vector is * 0x0, for the second received RTP, the ACK vector it is 0x1, for the third 0x3 and so * on, provided that no packets are lost. * A 64 bit ACK vector means that it theory it is possible to send one feedback every * 64 RTP packets, while this can possibly work at low bitrates, it is less likely to work * at high bitrates because the ACK clocking in SCReAM is disturbed then. */ if (seqNrExt >= highestSeqNrExt) { /* * Normal in-order reception */ uint16_t diff = seqNrExt - highestSeqNrExt; if (diff != 0) { if (diff >= kAckVectorBits) { ackVector = 0x0000; } else { // Fill with potential zeros ackVector = ackVector << diff; // Add previous highest seq nr to ack vector ackVector |= (INT64_C(1) << (diff - 1)); } } highestSeqNr = seqNr; } else { /* * Out-of-order reception */ uint16_t diff = highestSeqNrExt - seqNrExt; if (diff < kAckVectorBits) { ackVector = ackVector | (INT64_C(1) << (diff - 1)); } } receiveTimestamp = (uint32_t)(time_us / (int(1000000 / kTimestampRate))); } ScreamRx::ScreamRx() { lastFeedbackT_us = 0; bytesReceived = 0; lastRateComputeT_us = 0; averageReceivedRate = 1e5; } bool ScreamRx::checkIfFlushAck( uint32_t ssrc, uint16_t seqNr) { if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->isMatch(ssrc)) { /* * Packets for this SSRC received earlier * stream is thus already in list */ return (*it)->checkIfFlushAck(seqNr); } } } return false; } void ScreamRx::receive(uint64_t time_us, void* rtpPacket, uint32_t ssrc, int size, uint16_t seqNr) { bytesReceived += size; if (lastRateComputeT_us == 0) lastRateComputeT_us = time_us; if (time_us - lastRateComputeT_us > 200000) { /* * Media rate computation (for all medias) is done at least every 200ms * This is used for RTCP feedback rate calculation */ float delta = (time_us - lastRateComputeT_us) / 1e6f; lastRateComputeT_us = time_us; averageReceivedRate = std::max(0.95f*averageReceivedRate, bytesReceived * 8 / delta); bytesReceived = 0; } if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->isMatch(ssrc)) { /* * Packets for this SSRC received earlier * stream is thus already in list */ (*it)->receive(time_us, rtpPacket, size, seqNr); return; } } } /* * New {SSRC,PT} */ Stream *stream = new Stream(ssrc); stream->receive(time_us, rtpPacket, size, seqNr); streams.push_back(stream); } uint64_t ScreamRx::getRtcpFbInterval() { /* * The RTCP feedback rate depends on the received media date * at very low bitrates (<50kbps) an RTCP feedback interval of ~200ms is sufficient * while higher rates (>2Mbps) a feedback interval of ~20ms is sufficient */ float res = 1000000 / std::min(100.0f, std::max(10.0f, averageReceivedRate / 10000.0f)); return uint64_t(res); } bool ScreamRx::isFeedback(uint64_t time_us) { if (!streams.empty()) { for (auto it = streams.begin(); it != streams.end(); ++it) { Stream *stream = (*it); if (stream->nRtpSinceLastRtcp >= 1) { return true; } } } return false; } bool ScreamRx::getFeedback(uint64_t time_us, uint32_t &ssrc, uint32_t &receiveTimestamp, uint16_t &highestSeqNr, uint64_t &ackVector) { Stream *stream = NULL; uint64_t minT_us = ULLONG_MAX; for (auto it = streams.begin(); it != streams.end(); ++it) { if ((*it)->nRtpSinceLastRtcp > 0 && (*it)->lastFeedbackT_us < minT_us) { stream = *it; minT_us = (*it)->lastFeedbackT_us; } } if (stream == NULL) return false; receiveTimestamp = stream->receiveTimestamp; highestSeqNr = stream->highestSeqNr; ssrc = stream->ssrc; ackVector = stream->ackVector; stream->lastFeedbackT_us = time_us; stream->nRtpSinceLastRtcp = 0; lastFeedbackT_us = time_us; return true; } <|endoftext|>
<commit_before>/** * \file dcs/testbed/traits.hpp * * \brief Type traits class. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * 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. */ #ifndef DCS_TESTBED_TRAITS_HPP #define DCS_TESTBED_TRAITS_HPP namespace dcs { namespace testbed { template <typename RealT, typename UIntT> struct traits { typedef RealT real_type; typedef UIntT uint_type; }; // traits }} // Namespace dcs::testbed #endif // DCS_TESTBED_TRAITS_HPP <commit_msg>(change) Added random number generator type to the type traits<commit_after>/** * \file dcs/testbed/traits.hpp * * \brief Type traits class. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * 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. */ #ifndef DCS_TESTBED_TRAITS_HPP #define DCS_TESTBED_TRAITS_HPP #include <boost/random/mersenne_twister.hpp> namespace dcs { namespace testbed { template <typename RealT=double, typename UIntT=unsigned long, typename RNGT=boost::random::mt19937> struct traits { typedef RealT real_type; typedef UIntT uint_type; typedef RNGT rng_type; }; // traits }} // Namespace dcs::testbed #endif // DCS_TESTBED_TRAITS_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "etl/etl.hpp" namespace dll { /*! * \brief Prepare a ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * * \return The all-ready output */ template<typename Layer, typename Input, cpp_enable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_one_ready_output(Layer& layer, const Input& input){ auto out = layer.template prepare_one_output<Input>(); // At this point, the dimensions are not ready, so inherit out.inherit_if_null(input); return out; } /*! * \brief Prepare a ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * * \return The all-ready output */ template<typename Layer, typename Input, cpp_disable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_one_ready_output(Layer& layer, const Input& input){ cpp_unused(input); return layer.template prepare_one_output<Input>(); } /*! * \brief Prepare a collection of ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * \param n The number of samples to prepare * * \return The collection of all-ready output */ template<typename Layer, typename Input, cpp_enable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_many_ready_output(Layer& layer, const Input& input, size_t n){ auto out = layer.template prepare_output<Input>(n); // At this point, the dimensions are not ready, so inherit for (auto& x : out) { x.inherit_if_null(input); } return out; } /*! * \brief Prepare a collection of ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * \param n The number of samples to prepare * * \return The collection of all-ready output */ template<typename Layer, typename Input, cpp_disable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_many_ready_output(Layer& layer, const Input& input, size_t n){ cpp_unused(input); return layer.template prepare_output<Input>(n); } } //end of dll namespace <commit_msg>Add missing include<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "etl/etl.hpp" #include "dll/layer_traits.hpp" namespace dll { /*! * \brief Prepare a ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * * \return The all-ready output */ template<typename Layer, typename Input, cpp_enable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_one_ready_output(Layer& layer, const Input& input){ auto out = layer.template prepare_one_output<Input>(); // At this point, the dimensions are not ready, so inherit out.inherit_if_null(input); return out; } /*! * \brief Prepare a ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * * \return The all-ready output */ template<typename Layer, typename Input, cpp_disable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_one_ready_output(Layer& layer, const Input& input){ cpp_unused(input); return layer.template prepare_one_output<Input>(); } /*! * \brief Prepare a collection of ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * \param n The number of samples to prepare * * \return The collection of all-ready output */ template<typename Layer, typename Input, cpp_enable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_many_ready_output(Layer& layer, const Input& input, size_t n){ auto out = layer.template prepare_output<Input>(n); // At this point, the dimensions are not ready, so inherit for (auto& x : out) { x.inherit_if_null(input); } return out; } /*! * \brief Prepare a collection of ready output for the given layer from the given input. * * A ready output as all its dimensions set correctly. * * \param layer The layer to use to generate the output * \param input The input to the layer * \param n The number of samples to prepare * * \return The collection of all-ready output */ template<typename Layer, typename Input, cpp_disable_if(decay_layer_traits<Layer>::is_transform_layer())> auto prepare_many_ready_output(Layer& layer, const Input& input, size_t n){ cpp_unused(input); return layer.template prepare_output<Input>(n); } } //end of dll namespace <|endoftext|>
<commit_before>/* * Copyright (C) 2016 Nagisa Sekiguchi * * 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. */ #ifndef AQUARIUS_CXX_INTERNAL_STATE_HPP #define AQUARIUS_CXX_INTERNAL_STATE_HPP namespace aquarius { template <typename RandomAccessIterator> class ParserState { private: RandomAccessIterator begin_; RandomAccessIterator end_; /** * indicating current input position. */ RandomAccessIterator cursor_; /** * indicating parser result (success or failure). */ bool result_; public: ParserState(RandomAccessIterator begin, RandomAccessIterator end) : begin_(begin), end_(end), cursor_(begin), result_(true) { } const RandomAccessIterator begin() const { return this->begin_; } const RandomAccessIterator end() const { return this->end_; } RandomAccessIterator &cursor() { return this->cursor_; } size_t consumedSize() const { return std::distance(this->begin_, this->cursor_); } size_t remainedSize() const { return std::distance(this->cursor_, this->end_); } void reportFailure() { this->result_ = false; } void setResult(bool set) { this->result_ = set; } bool result() const { return this->result_; } }; template <typename RandomAccessIterator> inline ParserState<RandomAccessIterator> createState(RandomAccessIterator begin, RandomAccessIterator end) { return ParserState<RandomAccessIterator>(begin, end); } } // namespace aquarius #endif //AQUARIUS_CXX_INTERNAL_STATE_HPP <commit_msg>record longest matched faulure position<commit_after>/* * Copyright (C) 2016 Nagisa Sekiguchi * * 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. */ #ifndef AQUARIUS_CXX_INTERNAL_STATE_HPP #define AQUARIUS_CXX_INTERNAL_STATE_HPP namespace aquarius { template <typename RandomAccessIterator> class ParserState { private: RandomAccessIterator begin_; RandomAccessIterator end_; /** * indicating current input position. */ RandomAccessIterator cursor_; /** * indicating parser result (success or failure). */ bool result_; /** * indicate longest matched failure */ RandomAccessIterator failure_; public: ParserState(RandomAccessIterator begin, RandomAccessIterator end) : begin_(begin), end_(end), cursor_(begin), result_(true), failure_(begin) { } const RandomAccessIterator begin() const { return this->begin_; } const RandomAccessIterator end() const { return this->end_; } RandomAccessIterator &cursor() { return this->cursor_; } size_t consumedSize() const { return std::distance(this->begin_, this->cursor_); } size_t remainedSize() const { return std::distance(this->cursor_, this->end_); } void reportFailure() { this->result_ = false; if(this->cursor_ > this->failure_) { this->failure_ = this->cursor_; } } size_t failurePos() const { return std::distance(this->cursor_, this->failure_); } void setResult(bool set) { this->result_ = set; } bool result() const { return this->result_; } }; template <typename RandomAccessIterator> inline ParserState<RandomAccessIterator> createState(RandomAccessIterator begin, RandomAccessIterator end) { return ParserState<RandomAccessIterator>(begin, end); } } // namespace aquarius #endif //AQUARIUS_CXX_INTERNAL_STATE_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_HPP #define MAPNIK_FEATURE_HPP // mapnik #include <mapnik/value.hpp> #include <mapnik/geometry.hpp> #include <mapnik/raster.hpp> // boost #include <boost/version.hpp> #if BOOST_VERSION >= 104000 #include <boost/property_map/property_map.hpp> #else #include <boost/property_map.hpp> #endif #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> // stl #include <map> namespace mapnik { typedef boost::shared_ptr<raster> raster_ptr; typedef std::map<std::string,int> map_type; typedef boost::associative_property_map<map_type> base_type; class feature_impl; class context : private boost::noncopyable, public base_type { friend class feature_impl; public: context() : base_type(mapping_) {} void push(std::string const& name) { mapping_.insert(std::make_pair(name,mapping_.size())); } private: map_type mapping_; }; typedef boost::shared_ptr<context> context_ptr; class feature_impl : private boost::noncopyable { public: typedef mapnik::value value_type; typedef std::vector<value_type> cont_type; feature_impl(context_ptr const& ctx, int id) : id_(id), ctx_(ctx), data_(ctx_->mapping_.size()) {} inline int id() const { return id_;} void set_id(int id) { id_ = id;} template <typename T> void set(std::string const& key, T const& val) { map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end()) { data_[itr->second] = value(val); } } value_type const& get(std::string const& key) const { map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end()) { return data_[itr->second]; } static const value_type default_value; return default_value; } boost::ptr_vector<geometry_type> & paths() { return geom_cont_; } void add_geometry(geometry_type * geom) { geom_cont_.push_back(geom); } unsigned num_geometries() const { return geom_cont_.size(); } geometry_type const& get_geometry(unsigned index) const { return geom_cont_[index]; } geometry_type& get_geometry(unsigned index) { return geom_cont_[index]; } const raster_ptr& get_raster() const { return raster_; } void set_raster(raster_ptr const& raster) { raster_ = raster; } std::string to_string() const { std::stringstream ss; ss << "Feature (" << std::endl; map_type::const_iterator itr = ctx_->mapping_.begin(); map_type::const_iterator end = ctx_->mapping_.end(); for ( ;itr!=end; ++itr) { ss << " " << itr->first << ":" << data_[itr->second] << std::endl; } ss << ")" << std::endl; return ss.str(); } private: context_ptr ctx_; int id_; boost::ptr_vector<geometry_type> geom_cont_; raster_ptr raster_; cont_type data_; }; inline std::ostream& operator<< (std::ostream & out,feature_impl const& f) { out << f.to_string(); return out; } typedef feature_impl Feature; } #endif // MAPNIK_FEATURE_HPP <commit_msg>keep old names<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_HPP #define MAPNIK_FEATURE_HPP // mapnik #include <mapnik/value.hpp> #include <mapnik/geometry.hpp> #include <mapnik/raster.hpp> // boost #include <boost/version.hpp> #if BOOST_VERSION >= 104000 #include <boost/property_map/property_map.hpp> #else #include <boost/property_map.hpp> #endif #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> // stl #include <map> namespace mapnik { typedef boost::shared_ptr<raster> raster_ptr; typedef std::map<std::string,int> map_type; typedef boost::associative_property_map<map_type> base_type; class feature_impl; class context : private boost::noncopyable, public base_type { friend class feature_impl; public: context() : base_type(mapping_) {} void push(std::string const& name) { mapping_.insert(std::make_pair(name,mapping_.size())); } private: map_type mapping_; }; typedef boost::shared_ptr<context> context_ptr; class feature_impl : private boost::noncopyable { public: typedef mapnik::value value_type; typedef std::vector<value_type> cont_type; feature_impl(context_ptr const& ctx, int id) : id_(id), ctx_(ctx), data_(ctx_->mapping_.size()) {} inline int id() const { return id_;} inline void set_id(int id) { id_ = id;} template <typename T> void put(std::string const& key, T const& val) { map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end()) { data_[itr->second] = value(val); } } value_type const& get(std::string const& key) const { map_type::const_iterator itr = ctx_->mapping_.find(key); if (itr != ctx_->mapping_.end()) { return data_[itr->second]; } static const value_type default_value; return default_value; } boost::ptr_vector<geometry_type> & paths() { return geom_cont_; } void add_geometry(geometry_type * geom) { geom_cont_.push_back(geom); } unsigned num_geometries() const { return geom_cont_.size(); } geometry_type const& get_geometry(unsigned index) const { return geom_cont_[index]; } geometry_type& get_geometry(unsigned index) { return geom_cont_[index]; } const raster_ptr& get_raster() const { return raster_; } void set_raster(raster_ptr const& raster) { raster_ = raster; } std::string to_string() const { std::stringstream ss; ss << "Feature (" << std::endl; map_type::const_iterator itr = ctx_->mapping_.begin(); map_type::const_iterator end = ctx_->mapping_.end(); for ( ;itr!=end; ++itr) { ss << " " << itr->first << ":" << data_[itr->second] << std::endl; } ss << ")" << std::endl; return ss.str(); } private: context_ptr ctx_; int id_; boost::ptr_vector<geometry_type> geom_cont_; raster_ptr raster_; cont_type data_; }; inline std::ostream& operator<< (std::ostream & out,feature_impl const& f) { out << f.to_string(); return out; } typedef feature_impl Feature; } #endif // MAPNIK_FEATURE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/extensions/browser/xwalk_extension_process_host.h" #include <string> #include "base/command_line.h" #include "base/logging.h" #include "base/files/file_path.h" #include "content/public/browser/browser_child_process_host.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/child_process_host.h" #include "content/public/common/process_type.h" #include "content/public/common/content_switches.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" #include "ipc/ipc_message.h" #include "ipc/ipc_switches.h" #include "xwalk/extensions/common/xwalk_extension_messages.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/runtime/common/xwalk_switches.h" using content::BrowserThread; namespace xwalk { namespace extensions { // This filter is used by ExtensionProcessHost to intercept when Render Process // ask for the Extension Channel handle (that is created by extension process). class XWalkExtensionProcessHost::RenderProcessMessageFilter : public IPC::ChannelProxy::MessageFilter { public: explicit RenderProcessMessageFilter(XWalkExtensionProcessHost* eph) : eph_(eph) {} // This exists to fulfill the requirement for delayed reply handling, since it // needs to send a message back if the parameters couldn't be correctly read // from the original message received. See DispatchDealyReplyWithSendParams(). bool Send(IPC::Message* message) { if (eph_) return eph_->render_process_host_->Send(message); delete message; return false; } void Invalidate() { eph_ = NULL; } private: // IPC::ChannelProxy::MessageFilter implementation. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderProcessMessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY( XWalkExtensionProcessHostMsg_GetExtensionProcessChannel, OnGetExtensionProcessChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void OnGetExtensionProcessChannel(IPC::Message* reply) { scoped_ptr<IPC::Message> scoped_reply(reply); if (eph_) eph_->OnGetExtensionProcessChannel(scoped_reply.Pass()); } virtual ~RenderProcessMessageFilter() {} XWalkExtensionProcessHost* eph_; }; class ExtensionSandboxedProcessLauncherDelegate : public content::SandboxedProcessLauncherDelegate { public: explicit ExtensionSandboxedProcessLauncherDelegate( content::ChildProcessHost* host) #if defined(OS_POSIX) : ipc_fd_(host->TakeClientFileDescriptor()) {} #endif virtual ~ExtensionSandboxedProcessLauncherDelegate() {} #if defined(OS_WIN) virtual void ShouldSandbox(bool* in_sandbox) OVERRIDE { *in_sandbox = false; } #elif defined(OS_POSIX) virtual int GetIpcFd() OVERRIDE { return ipc_fd_; } #endif private: #if defined(OS_POSIX) int ipc_fd_; #endif DISALLOW_COPY_AND_ASSIGN(ExtensionSandboxedProcessLauncherDelegate); }; bool XWalkExtensionProcessHost::Delegate::OnRegisterPermissions( int render_process_id, const std::string& extension_name, const std::string& perm_table) { return false; } XWalkExtensionProcessHost::XWalkExtensionProcessHost( content::RenderProcessHost* render_process_host, const base::FilePath& external_extensions_path, XWalkExtensionProcessHost::Delegate* delegate, const base::ValueMap& runtime_variables) : ep_rp_channel_handle_(""), render_process_host_(render_process_host), render_process_message_filter_(new RenderProcessMessageFilter(this)), external_extensions_path_(external_extensions_path), is_extension_process_channel_ready_(false), delegate_(delegate), runtime_variables_(runtime_variables) { render_process_host_->GetChannel()->AddFilter(render_process_message_filter_); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&XWalkExtensionProcessHost::StartProcess, base::Unretained(this))); } XWalkExtensionProcessHost::~XWalkExtensionProcessHost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); render_process_message_filter_->Invalidate(); StopProcess(); } namespace { void ToListValue(base::ValueMap* vm, base::ListValue* lv) { lv->Clear(); for (base::ValueMap::iterator it = vm->begin(); it != vm->end(); it++) { base::DictionaryValue* dv = new base::DictionaryValue(); dv->Set(it->first, it->second); lv->Append(dv); } } } // namespace void XWalkExtensionProcessHost::StartProcess() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); CHECK(!process_ || !channel_); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kXWalkRunAsService)) { #if defined(OS_LINUX) std::string channel_id = IPC::Channel::GenerateVerifiedChannelID(std::string()); channel_.reset(new IPC::Channel( channel_id, IPC::Channel::MODE_SERVER, this)); if (!channel_->Connect()) NOTREACHED(); IPC::ChannelHandle channel_handle(channel_id, base::FileDescriptor(channel_->TakeClientFileDescriptor(), true)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &XWalkExtensionProcessHost::Delegate::OnExtensionProcessCreated, base::Unretained(delegate_), render_process_host_->GetID(), channel_handle)); #else NOTIMPLEMENTED(); #endif } else { process_.reset(content::BrowserChildProcessHost::Create( content::PROCESS_TYPE_CONTENT_END, this)); std::string channel_id = process_->GetHost()->CreateChannel(); CHECK(!channel_id.empty()); CommandLine::StringType extension_cmd_prefix; #if defined(OS_POSIX) const CommandLine &browser_command_line = *CommandLine::ForCurrentProcess(); extension_cmd_prefix = browser_command_line.GetSwitchValueNative( switches::kXWalkExtensionCmdPrefix); #endif #if defined(OS_LINUX) int flags = extension_cmd_prefix.empty() ? content::ChildProcessHost::CHILD_ALLOW_SELF : content::ChildProcessHost::CHILD_NORMAL; #else int flags = content::ChildProcessHost::CHILD_NORMAL; #endif base::FilePath exe_path = content::ChildProcessHost::GetChildPath(flags); if (exe_path.empty()) return; scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path)); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kXWalkExtensionProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); if (!extension_cmd_prefix.empty()) cmd_line->PrependWrapper(extension_cmd_prefix); process_->Launch( new ExtensionSandboxedProcessLauncherDelegate(process_->GetHost()), cmd_line.release()); } base::ListValue runtime_variables_lv; ToListValue(&const_cast<base::ValueMap&>(runtime_variables_), &runtime_variables_lv); Send(new XWalkExtensionProcessMsg_RegisterExtensions( external_extensions_path_, runtime_variables_lv)); } void XWalkExtensionProcessHost::StopProcess() { if (process_); process_.reset(); if (channel_) channel_.reset(); } void XWalkExtensionProcessHost::OnGetExtensionProcessChannel( scoped_ptr<IPC::Message> reply) { pending_reply_for_render_process_ = reply.Pass(); ReplyChannelHandleToRenderProcess(); } bool XWalkExtensionProcessHost::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(XWalkExtensionProcessHost, message) IPC_MESSAGE_HANDLER( XWalkExtensionProcessHostMsg_RenderProcessChannelCreated, OnRenderChannelCreated) IPC_MESSAGE_HANDLER_DELAY_REPLY( XWalkExtensionProcessHostMsg_CheckAPIAccessControl, OnCheckAPIAccessControl) IPC_MESSAGE_HANDLER( XWalkExtensionProcessHostMsg_RegisterPermissions, OnRegisterPermissions) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void XWalkExtensionProcessHost::OnChannelError() { // This function is called just before // BrowserChildProcessHostImpl::OnChildDisconnected gets called. Please refer // to ChildProcessHostImpl::OnChannelError() from child_process_host_impl.cc. // This means that content::BrowserChildProcessHost (process_, in our case) // is about to delete its delegate, which is us! // We should alert our XWalkExtensionProcessHost::Delegate, since it will // most likely have a pointer to us that needs to be invalidated. VLOG(1) << "\n\nExtensionProcess crashed"; if (delegate_) delegate_->OnExtensionProcessDied(this, render_process_host_->GetID()); } void XWalkExtensionProcessHost::OnProcessLaunched() { VLOG(1) << "\n\nExtensionProcess was started!"; } void XWalkExtensionProcessHost::OnRenderChannelCreated( const IPC::ChannelHandle& handle) { is_extension_process_channel_ready_ = true; ep_rp_channel_handle_ = handle; ReplyChannelHandleToRenderProcess(); } void XWalkExtensionProcessHost::ReplyChannelHandleToRenderProcess() { // Replying the channel handle to RP depends on two events: // - EP already notified EPH that new channel was created (for RP<->EP). // - RP already asked for the channel handle. // // The order for this events is not determined, so we call this function from // both, and the second execution will send the reply. if (!is_extension_process_channel_ready_ || !pending_reply_for_render_process_) return; XWalkExtensionProcessHostMsg_GetExtensionProcessChannel::WriteReplyParams( pending_reply_for_render_process_.get(), ep_rp_channel_handle_); render_process_host_->Send(pending_reply_for_render_process_.release()); } void XWalkExtensionProcessHost::ReplyAccessControlToExtension( IPC::Message* reply_msg, RuntimePermission perm) { XWalkExtensionProcessHostMsg_CheckAPIAccessControl ::WriteReplyParams(reply_msg, perm); Send(reply_msg); } void XWalkExtensionProcessHost::OnCheckAPIAccessControl( const std::string& extension_name, const std::string& api_name, IPC::Message* reply_msg) { CHECK(delegate_); delegate_->OnCheckAPIAccessControl(render_process_host_->GetID(), extension_name, api_name, base::Bind(&XWalkExtensionProcessHost::ReplyAccessControlToExtension, base::Unretained(this), reply_msg)); } void XWalkExtensionProcessHost::OnRegisterPermissions( const std::string& extension_name, const std::string& perm_table, bool* result) { CHECK(delegate_); *result = delegate_->OnRegisterPermissions( render_process_host_->GetID(), extension_name, perm_table); } bool XWalkExtensionProcessHost::Send(IPC::Message* msg) { if (process_) return process_->GetHost()->Send(msg); if (channel_) return channel_->Send(msg); return false; } } // namespace extensions } // namespace xwalk <commit_msg>[Extension] Fix ";" typo after if-clause<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/extensions/browser/xwalk_extension_process_host.h" #include <string> #include "base/command_line.h" #include "base/logging.h" #include "base/files/file_path.h" #include "content/public/browser/browser_child_process_host.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/child_process_host.h" #include "content/public/common/process_type.h" #include "content/public/common/content_switches.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" #include "ipc/ipc_message.h" #include "ipc/ipc_switches.h" #include "xwalk/extensions/common/xwalk_extension_messages.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/runtime/common/xwalk_switches.h" using content::BrowserThread; namespace xwalk { namespace extensions { // This filter is used by ExtensionProcessHost to intercept when Render Process // ask for the Extension Channel handle (that is created by extension process). class XWalkExtensionProcessHost::RenderProcessMessageFilter : public IPC::ChannelProxy::MessageFilter { public: explicit RenderProcessMessageFilter(XWalkExtensionProcessHost* eph) : eph_(eph) {} // This exists to fulfill the requirement for delayed reply handling, since it // needs to send a message back if the parameters couldn't be correctly read // from the original message received. See DispatchDealyReplyWithSendParams(). bool Send(IPC::Message* message) { if (eph_) return eph_->render_process_host_->Send(message); delete message; return false; } void Invalidate() { eph_ = NULL; } private: // IPC::ChannelProxy::MessageFilter implementation. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderProcessMessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY( XWalkExtensionProcessHostMsg_GetExtensionProcessChannel, OnGetExtensionProcessChannel) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void OnGetExtensionProcessChannel(IPC::Message* reply) { scoped_ptr<IPC::Message> scoped_reply(reply); if (eph_) eph_->OnGetExtensionProcessChannel(scoped_reply.Pass()); } virtual ~RenderProcessMessageFilter() {} XWalkExtensionProcessHost* eph_; }; class ExtensionSandboxedProcessLauncherDelegate : public content::SandboxedProcessLauncherDelegate { public: explicit ExtensionSandboxedProcessLauncherDelegate( content::ChildProcessHost* host) #if defined(OS_POSIX) : ipc_fd_(host->TakeClientFileDescriptor()) {} #endif virtual ~ExtensionSandboxedProcessLauncherDelegate() {} #if defined(OS_WIN) virtual void ShouldSandbox(bool* in_sandbox) OVERRIDE { *in_sandbox = false; } #elif defined(OS_POSIX) virtual int GetIpcFd() OVERRIDE { return ipc_fd_; } #endif private: #if defined(OS_POSIX) int ipc_fd_; #endif DISALLOW_COPY_AND_ASSIGN(ExtensionSandboxedProcessLauncherDelegate); }; bool XWalkExtensionProcessHost::Delegate::OnRegisterPermissions( int render_process_id, const std::string& extension_name, const std::string& perm_table) { return false; } XWalkExtensionProcessHost::XWalkExtensionProcessHost( content::RenderProcessHost* render_process_host, const base::FilePath& external_extensions_path, XWalkExtensionProcessHost::Delegate* delegate, const base::ValueMap& runtime_variables) : ep_rp_channel_handle_(""), render_process_host_(render_process_host), render_process_message_filter_(new RenderProcessMessageFilter(this)), external_extensions_path_(external_extensions_path), is_extension_process_channel_ready_(false), delegate_(delegate), runtime_variables_(runtime_variables) { render_process_host_->GetChannel()->AddFilter(render_process_message_filter_); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&XWalkExtensionProcessHost::StartProcess, base::Unretained(this))); } XWalkExtensionProcessHost::~XWalkExtensionProcessHost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); render_process_message_filter_->Invalidate(); StopProcess(); } namespace { void ToListValue(base::ValueMap* vm, base::ListValue* lv) { lv->Clear(); for (base::ValueMap::iterator it = vm->begin(); it != vm->end(); it++) { base::DictionaryValue* dv = new base::DictionaryValue(); dv->Set(it->first, it->second); lv->Append(dv); } } } // namespace void XWalkExtensionProcessHost::StartProcess() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); CHECK(!process_ || !channel_); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kXWalkRunAsService)) { #if defined(OS_LINUX) std::string channel_id = IPC::Channel::GenerateVerifiedChannelID(std::string()); channel_.reset(new IPC::Channel( channel_id, IPC::Channel::MODE_SERVER, this)); if (!channel_->Connect()) NOTREACHED(); IPC::ChannelHandle channel_handle(channel_id, base::FileDescriptor(channel_->TakeClientFileDescriptor(), true)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &XWalkExtensionProcessHost::Delegate::OnExtensionProcessCreated, base::Unretained(delegate_), render_process_host_->GetID(), channel_handle)); #else NOTIMPLEMENTED(); #endif } else { process_.reset(content::BrowserChildProcessHost::Create( content::PROCESS_TYPE_CONTENT_END, this)); std::string channel_id = process_->GetHost()->CreateChannel(); CHECK(!channel_id.empty()); CommandLine::StringType extension_cmd_prefix; #if defined(OS_POSIX) const CommandLine &browser_command_line = *CommandLine::ForCurrentProcess(); extension_cmd_prefix = browser_command_line.GetSwitchValueNative( switches::kXWalkExtensionCmdPrefix); #endif #if defined(OS_LINUX) int flags = extension_cmd_prefix.empty() ? content::ChildProcessHost::CHILD_ALLOW_SELF : content::ChildProcessHost::CHILD_NORMAL; #else int flags = content::ChildProcessHost::CHILD_NORMAL; #endif base::FilePath exe_path = content::ChildProcessHost::GetChildPath(flags); if (exe_path.empty()) return; scoped_ptr<CommandLine> cmd_line(new CommandLine(exe_path)); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kXWalkExtensionProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); if (!extension_cmd_prefix.empty()) cmd_line->PrependWrapper(extension_cmd_prefix); process_->Launch( new ExtensionSandboxedProcessLauncherDelegate(process_->GetHost()), cmd_line.release()); } base::ListValue runtime_variables_lv; ToListValue(&const_cast<base::ValueMap&>(runtime_variables_), &runtime_variables_lv); Send(new XWalkExtensionProcessMsg_RegisterExtensions( external_extensions_path_, runtime_variables_lv)); } void XWalkExtensionProcessHost::StopProcess() { if (process_) process_.reset(); if (channel_) channel_.reset(); } void XWalkExtensionProcessHost::OnGetExtensionProcessChannel( scoped_ptr<IPC::Message> reply) { pending_reply_for_render_process_ = reply.Pass(); ReplyChannelHandleToRenderProcess(); } bool XWalkExtensionProcessHost::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(XWalkExtensionProcessHost, message) IPC_MESSAGE_HANDLER( XWalkExtensionProcessHostMsg_RenderProcessChannelCreated, OnRenderChannelCreated) IPC_MESSAGE_HANDLER_DELAY_REPLY( XWalkExtensionProcessHostMsg_CheckAPIAccessControl, OnCheckAPIAccessControl) IPC_MESSAGE_HANDLER( XWalkExtensionProcessHostMsg_RegisterPermissions, OnRegisterPermissions) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void XWalkExtensionProcessHost::OnChannelError() { // This function is called just before // BrowserChildProcessHostImpl::OnChildDisconnected gets called. Please refer // to ChildProcessHostImpl::OnChannelError() from child_process_host_impl.cc. // This means that content::BrowserChildProcessHost (process_, in our case) // is about to delete its delegate, which is us! // We should alert our XWalkExtensionProcessHost::Delegate, since it will // most likely have a pointer to us that needs to be invalidated. VLOG(1) << "\n\nExtensionProcess crashed"; if (delegate_) delegate_->OnExtensionProcessDied(this, render_process_host_->GetID()); } void XWalkExtensionProcessHost::OnProcessLaunched() { VLOG(1) << "\n\nExtensionProcess was started!"; } void XWalkExtensionProcessHost::OnRenderChannelCreated( const IPC::ChannelHandle& handle) { is_extension_process_channel_ready_ = true; ep_rp_channel_handle_ = handle; ReplyChannelHandleToRenderProcess(); } void XWalkExtensionProcessHost::ReplyChannelHandleToRenderProcess() { // Replying the channel handle to RP depends on two events: // - EP already notified EPH that new channel was created (for RP<->EP). // - RP already asked for the channel handle. // // The order for this events is not determined, so we call this function from // both, and the second execution will send the reply. if (!is_extension_process_channel_ready_ || !pending_reply_for_render_process_) return; XWalkExtensionProcessHostMsg_GetExtensionProcessChannel::WriteReplyParams( pending_reply_for_render_process_.get(), ep_rp_channel_handle_); render_process_host_->Send(pending_reply_for_render_process_.release()); } void XWalkExtensionProcessHost::ReplyAccessControlToExtension( IPC::Message* reply_msg, RuntimePermission perm) { XWalkExtensionProcessHostMsg_CheckAPIAccessControl ::WriteReplyParams(reply_msg, perm); Send(reply_msg); } void XWalkExtensionProcessHost::OnCheckAPIAccessControl( const std::string& extension_name, const std::string& api_name, IPC::Message* reply_msg) { CHECK(delegate_); delegate_->OnCheckAPIAccessControl(render_process_host_->GetID(), extension_name, api_name, base::Bind(&XWalkExtensionProcessHost::ReplyAccessControlToExtension, base::Unretained(this), reply_msg)); } void XWalkExtensionProcessHost::OnRegisterPermissions( const std::string& extension_name, const std::string& perm_table, bool* result) { CHECK(delegate_); *result = delegate_->OnRegisterPermissions( render_process_host_->GetID(), extension_name, perm_table); } bool XWalkExtensionProcessHost::Send(IPC::Message* msg) { if (process_) return process_->GetHost()->Send(msg); if (channel_) return channel_->Send(msg); return false; } } // namespace extensions } // namespace xwalk <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: enumrepresentation.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2006-03-14 11:22:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 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 * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif /** === end UNO includes === **/ #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <vector> //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= IPropertyEnumRepresentation //==================================================================== class IPropertyEnumRepresentation : public ::rtl::IReference { public: /** retrieves all descriptions of all possible values of the enumeration property */ virtual ::std::vector< ::rtl::OUString > SAL_CALL getDescriptions( ) const = 0; /** converts a given description into a property value */ virtual void SAL_CALL getValueFromDescription( const ::rtl::OUString& _rDescription, ::com::sun::star::uno::Any& _out_rValue ) const = 0; /** converts a given property value into a description */ virtual ::rtl::OUString SAL_CALL getDescriptionForValue( const ::com::sun::star::uno::Any& _rEnumValue ) const = 0; }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX <commit_msg>INTEGRATION: CWS dba204b (1.2.68); FILE MERGED 2006/07/06 14:52:27 fs 1.2.68.1: #i65159# describePropertyLine now returning a LineDescriptor, instead of taking an out parameter / some less warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: enumrepresentation.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2006-07-26 07:55:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 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 * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif /** === end UNO includes === **/ #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #include <vector> //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= IPropertyEnumRepresentation //==================================================================== class SAL_NO_VTABLE IPropertyEnumRepresentation : public ::rtl::IReference { public: /** retrieves all descriptions of all possible values of the enumeration property */ virtual ::std::vector< ::rtl::OUString > SAL_CALL getDescriptions( ) const = 0; /** converts a given description into a property value */ virtual void SAL_CALL getValueFromDescription( const ::rtl::OUString& _rDescription, ::com::sun::star::uno::Any& _out_rValue ) const = 0; /** converts a given property value into a description */ virtual ::rtl::OUString SAL_CALL getDescriptionForValue( const ::com::sun::star::uno::Any& _rEnumValue ) const = 0; virtual ~IPropertyEnumRepresentation() { }; }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_ENUMREPRESENTATION_HXX <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> const bool BLACK = 1; const bool RED = 0; template<typename T> struct Node { T value; bool color; Node* leftNode; Node* rightNode; Node* parNode; }; template<typename T> class RedBlackTree { private: Node<T>* root; Node<T>* NIL; public: RedBlackTree(); ~RedBlackTree(); bool _color(const T& value) const; Node<T>* _root() const; Node<T>* _NIL() const; void left_rotate(Node<T>* currNode); void right_rotate(Node<T>* currNode); void insertFix(Node<T>* currNode); void insert(const T& value); void destroyTree(Node<T>* node); void print(const Node<T>* tempNode, int level) const; Node<T>* findElement(const T& value) const; }; template <typename T> RedBlackTree<T>::RedBlackTree() { NIL = new Node<T>; NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr; NIL->color = BLACK; root = NIL; } template <typename T> RedBlackTree<T>::~RedBlackTree() { destroyTree(root); delete NIL; } template <typename T> void RedBlackTree<T>::destroyTree(Node<T>* node) { if (!node) return; while (node->leftNode != NIL) destroyTree(node->leftNode); while (node->rightNode != NIL) destroyTree(node->rightNode); delete node; } template <typename T> bool RedBlackTree<T>::_color(const T& value) const { return findElement(value)->color; } template <typename T> Node<T>* RedBlackTree<T>::_root() const { return root; } template <typename T> Node<T>* RedBlackTree<T>::_NIL()const { return NIL; } template <typename T> void RedBlackTree<T>::left_rotate(Node<T>* currNode) { Node<T>* tempNode= currNode->rightNode; currNode->rightNode = tempNode->leftNode; if (tempNode->leftNode != NIL) tempNode->leftNode->parNode = currNode; if (tempNode!= NIL) tempNode->parNode = currNode->parNode; if (currNode->parNode != NIL) { if (currNode == currNode->parNode->leftNode) currNode->parNode->leftNode = tempNode; else currNode->parNode->rightNode = tempNode; } else { root = tempNode; } tempNode->leftNode = currNode; if (currNode != NIL) currNode->parNode = tempNode; } template <typename T> void RedBlackTree<T>::right_rotate(Node<T> *currNode) { Node<T> *tempNode= currNode->leftNode; currNode->leftNode = tempNode->rightNode; if (tempNode->rightNode != NIL) tempNode->rightNode->parNode = currNode; if (tempNode!= NIL) tempNode->parNode = currNode->parNode; if (currNode->parNode != NIL) { if (currNode == currNode->parNode->rightNode) currNode->parNode->rightNode = tempNode; else currNode->parNode->leftNode = tempNode; } else { root = tempNode; } tempNode->rightNode = currNode; if (currNode != NIL) currNode->parNode = tempNode; } template <typename T> void RedBlackTree<T>::insertFix(Node<T>* currNode) { while (currNode != root && currNode->parNode->color == RED) { if (currNode->parNode == currNode->parNode->parNode->leftNode) { Node<T>* tempNode= currNode->parNode->parNode->rightNode; if (tempNode->color == RED) { currNode->parNode->color = BLACK; tempNode->color = BLACK; currNode->parNode->parNode->color = RED; currNode = currNode->parNode->parNode; } else { if (currNode == currNode->parNode->rightNode) { currNode = currNode->parNode; left_rotate(currNode); } currNode->parNode->color = BLACK; currNode->parNode->parNode->color = RED; right_rotate(currNode->parNode->parNode); } } else { Node<T>* tempNode= currNode->parNode->parNode->leftNode; if (tempNode->color == RED) { currNode->parNode->color = BLACK; tempNode->color = BLACK; currNode->parNode->parNode->color = RED; currNode = currNode->parNode->parNode; } else { if (currNode == currNode->parNode->leftNode) { currNode = currNode->parNode; right_rotate(currNode); } currNode->parNode->color = BLACK; currNode->parNode->parNode->color = RED; left_rotate(currNode->parNode->parNode); } } } root->color = BLACK; } template <typename T> void RedBlackTree<T>::insert(const T& value) { if (findElement(value)) { throw std::logic_error("This value is already added!\n"); } Node<T>* child = new Node<T>; child->value = value; child->color = RED; child->leftNode = child->rightNode = child->parNode = NIL; Node<T>* parNode = NIL; Node<T>* tempNode= root; if (root == NIL) { root = child; root->color = BLACK; return; } while (tempNode!= NIL) { if (child->value == tempNode->value) return; parNode = tempNode; if (value < tempNode->value) tempNode= tempNode->leftNode; else tempNode= tempNode->rightNode; } if (value < parNode->value) { parNode->leftNode = child; } else { parNode->rightNode = child; } child->parNode = parNode; insertFix(child); } template <typename T> void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const { if (root == NIL) { throw std::logic_error("Error! The tree is empty!\n"); } if (tempNode!= NIL) { print(tempNode->leftNode, level + 1); for (int i = 0; i < level; i++) std::cout << "\t"; std::cout << "(" << tempNode->color << ")"; std::cout << tempNode->value << "\n"; print(tempNode->rightNode, level + 1); } } template <typename T> Node<T>* RedBlackTree<T>::findElement(const T& value) const { Node<T>* currNode = root; while (currNode != NIL) { if (value == currNode->value) return currNode; else { if (value < currNode->value) currNode = currNode->leftNode; else currNode = currNode->rightNode; } } return 0; } <commit_msg>Update red_black_tree.hpp<commit_after>#include <iostream> #include <stdexcept> const bool BLACK = 1; const bool RED = 0; template<typename T> struct Node { T value; bool color; Node* leftNode; Node* rightNode; Node* parNode; }; template<typename T> class RedBlackTree { private: Node<T>* root; Node<T>* NIL; public: RedBlackTree(); ~RedBlackTree(); bool _color(const T& value) const; Node<T>* _root() const; Node<T>* _NIL() const; void left_rotate(Node<T>* currNode); void right_rotate(Node<T>* currNode); void insertFix(Node<T>* currNode); void insert(const T& value); void destroyTree(Node<T>* node); void print(const Node<T>* tempNode, int level) const; Node<T>* findElement(const T& value) const; }; template <typename T> RedBlackTree<T>::RedBlackTree() { NIL = new Node<T>; NIL->leftNode = NIL->parNode = NIL->rightNode = nullptr; NIL->color = BLACK; root = NIL; } template <typename T> bool RedBlackTree<T>::_color(const T& value) const { return findElement(value)->color; } template <typename T> Node<T>* RedBlackTree<T>::_root() const { return root; } template <typename T> Node<T>* RedBlackTree<T>::_NIL()const { return NIL; } template <typename T> void RedBlackTree<T>::left_rotate(Node<T>* currNode) { Node<T>* tempNode= currNode->rightNode; currNode->rightNode = tempNode->leftNode; if (tempNode->leftNode != NIL) tempNode->leftNode->parNode = currNode; if (tempNode!= NIL) tempNode->parNode = currNode->parNode; if (currNode->parNode != NIL) { if (currNode == currNode->parNode->leftNode) currNode->parNode->leftNode = tempNode; else currNode->parNode->rightNode = tempNode; } else { root = tempNode; } tempNode->leftNode = currNode; if (currNode != NIL) currNode->parNode = tempNode; } template <typename T> void RedBlackTree<T>::right_rotate(Node<T> *currNode) { Node<T> *tempNode= currNode->leftNode; currNode->leftNode = tempNode->rightNode; if (tempNode->rightNode != NIL) tempNode->rightNode->parNode = currNode; if (tempNode!= NIL) tempNode->parNode = currNode->parNode; if (currNode->parNode != NIL) { if (currNode == currNode->parNode->rightNode) currNode->parNode->rightNode = tempNode; else currNode->parNode->leftNode = tempNode; } else { root = tempNode; } tempNode->rightNode = currNode; if (currNode != NIL) currNode->parNode = tempNode; } template <typename T> void RedBlackTree<T>::insertFix(Node<T>* currNode) { while (currNode != root && currNode->parNode->color == RED) { if (currNode->parNode == currNode->parNode->parNode->leftNode) { Node<T>* tempNode= currNode->parNode->parNode->rightNode; if (tempNode->color == RED) { currNode->parNode->color = BLACK; tempNode->color = BLACK; currNode->parNode->parNode->color = RED; currNode = currNode->parNode->parNode; } else { if (currNode == currNode->parNode->rightNode) { currNode = currNode->parNode; left_rotate(currNode); } currNode->parNode->color = BLACK; currNode->parNode->parNode->color = RED; right_rotate(currNode->parNode->parNode); } } else { Node<T>* tempNode= currNode->parNode->parNode->leftNode; if (tempNode->color == RED) { currNode->parNode->color = BLACK; tempNode->color = BLACK; currNode->parNode->parNode->color = RED; currNode = currNode->parNode->parNode; } else { if (currNode == currNode->parNode->leftNode) { currNode = currNode->parNode; right_rotate(currNode); } currNode->parNode->color = BLACK; currNode->parNode->parNode->color = RED; left_rotate(currNode->parNode->parNode); } } } root->color = BLACK; } template <typename T> void RedBlackTree<T>::insert(const T& value) { if (findElement(value)) { throw std::logic_error("This value is already added!\n"); } Node<T>* child = new Node<T>; child->value = value; child->color = RED; child->leftNode = child->rightNode = child->parNode = NIL; Node<T>* parNode = NIL; Node<T>* tempNode= root; if (root == NIL) { root = child; root->color = BLACK; return; } while (tempNode!= NIL) { if (child->value == tempNode->value) return; parNode = tempNode; if (value < tempNode->value) tempNode= tempNode->leftNode; else tempNode= tempNode->rightNode; } if (value < parNode->value) { parNode->leftNode = child; } else { parNode->rightNode = child; } child->parNode = parNode; insertFix(child); } template <typename T> void RedBlackTree<T>::print(const Node<T>* tempNode, int level)const { if (root == NIL) { throw std::logic_error("Error! The tree is empty!\n"); } if (tempNode!= NIL) { print(tempNode->leftNode, level + 1); for (int i = 0; i < level; i++) std::cout << "\t"; std::cout << "(" << tempNode->color << ")"; std::cout << tempNode->value << "\n"; print(tempNode->rightNode, level + 1); } } template <typename T> Node<T>* RedBlackTree<T>::findElement(const T& value) const { Node<T>* currNode = root; while (currNode != NIL) { if (value == currNode->value) return currNode; else { if (value < currNode->value) currNode = currNode->leftNode; else currNode = currNode->rightNode; } } return 0; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <memory> #include <vector> #include <cstring> #include <seastar/core/future.hh> #include <seastar/net/byteorder.hh> #include <seastar/net/socket_defs.hh> #include <seastar/net/packet.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/iostream.hh> #include <seastar/util/std-compat.hh> #include "../core/internal/api-level.hh" #include <sys/types.h> namespace seastar { inline bool is_ip_unspecified(const ipv4_addr& addr) { return addr.is_ip_unspecified(); } inline bool is_port_unspecified(const ipv4_addr& addr) { return addr.is_port_unspecified(); } inline socket_address make_ipv4_address(const ipv4_addr& addr) { return socket_address(addr); } inline socket_address make_ipv4_address(uint32_t ip, uint16_t port) { return make_ipv4_address(ipv4_addr(ip, port)); } namespace net { // see linux tcp(7) for parameter explanation struct tcp_keepalive_params { std::chrono::seconds idle; // TCP_KEEPIDLE std::chrono::seconds interval; // TCP_KEEPINTVL unsigned count; // TCP_KEEPCNT }; // see linux sctp(7) for parameter explanation struct sctp_keepalive_params { std::chrono::seconds interval; // spp_hbinterval unsigned count; // spp_pathmaxrt }; using keepalive_params = compat::variant<tcp_keepalive_params, sctp_keepalive_params>; /// \cond internal class connected_socket_impl; class socket_impl; #if SEASTAR_API_LEVEL <= 1 SEASTAR_INCLUDE_API_V1 namespace api_v1 { class server_socket_impl; } #endif SEASTAR_INCLUDE_API_V2 namespace api_v2 { class server_socket_impl; } class udp_channel_impl; class get_impl; /// \endcond class udp_datagram_impl { public: virtual ~udp_datagram_impl() {}; virtual socket_address get_src() = 0; virtual socket_address get_dst() = 0; virtual uint16_t get_dst_port() = 0; virtual packet& get_data() = 0; }; class udp_datagram final { private: std::unique_ptr<udp_datagram_impl> _impl; public: udp_datagram(std::unique_ptr<udp_datagram_impl>&& impl) : _impl(std::move(impl)) {}; socket_address get_src() { return _impl->get_src(); } socket_address get_dst() { return _impl->get_dst(); } uint16_t get_dst_port() { return _impl->get_dst_port(); } packet& get_data() { return _impl->get_data(); } }; class udp_channel { private: std::unique_ptr<udp_channel_impl> _impl; public: udp_channel(); udp_channel(std::unique_ptr<udp_channel_impl>); ~udp_channel(); udp_channel(udp_channel&&); udp_channel& operator=(udp_channel&&); socket_address local_address() const; future<udp_datagram> receive(); future<> send(const socket_address& dst, const char* msg); future<> send(const socket_address& dst, packet p); bool is_closed() const; /// Causes a pending receive() to complete (possibly with an exception) void shutdown_input(); /// Causes a pending send() to complete (possibly with an exception) void shutdown_output(); /// Close the channel and releases all resources. /// /// Must be called only when there are no unfinished send() or receive() calls. You /// can force pending calls to complete soon by calling shutdown_input() and /// shutdown_output(). void close(); }; } /* namespace net */ /// \addtogroup networking-module /// @{ /// A TCP (or other stream-based protocol) connection. /// /// A \c connected_socket represents a full-duplex stream between /// two endpoints, a local endpoint and a remote endpoint. class connected_socket { friend class net::get_impl; std::unique_ptr<net::connected_socket_impl> _csi; public: /// Constructs a \c connected_socket not corresponding to a connection connected_socket(); ~connected_socket(); /// \cond internal explicit connected_socket(std::unique_ptr<net::connected_socket_impl> csi); /// \endcond /// Moves a \c connected_socket object. connected_socket(connected_socket&& cs) noexcept; /// Move-assigns a \c connected_socket object. connected_socket& operator=(connected_socket&& cs) noexcept; /// Gets the input stream. /// /// Gets an object returning data sent from the remote endpoint. input_stream<char> input(); /// Gets the output stream. /// /// Gets an object that sends data to the remote endpoint. /// \param buffer_size how much data to buffer output_stream<char> output(size_t buffer_size = 8192); /// Sets the TCP_NODELAY option (disabling Nagle's algorithm) void set_nodelay(bool nodelay); /// Gets the TCP_NODELAY option (Nagle's algorithm) /// /// \return whether the nodelay option is enabled or not bool get_nodelay() const; /// Sets SO_KEEPALIVE option (enable keepalive timer on a socket) void set_keepalive(bool keepalive); /// Gets O_KEEPALIVE option /// \return whether the keepalive option is enabled or not bool get_keepalive() const; /// Sets TCP keepalive parameters void set_keepalive_parameters(const net::keepalive_params& p); /// Get TCP keepalive parameters net::keepalive_params get_keepalive_parameters() const; /// Disables output to the socket. /// /// Current or future writes that have not been successfully flushed /// will immediately fail with an error. This is useful to abort /// operations on a socket that is not making progress due to a /// peer failure. void shutdown_output(); /// Disables input from the socket. /// /// Current or future reads will immediately fail with an error. /// This is useful to abort operations on a socket that is not making /// progress due to a peer failure. void shutdown_input(); }; /// @} /// \addtogroup networking-module /// @{ /// The seastar socket. /// /// A \c socket that allows a connection to be established between /// two endpoints. class socket { std::unique_ptr<net::socket_impl> _si; public: ~socket(); /// \cond internal explicit socket(std::unique_ptr<net::socket_impl> si); /// \endcond /// Moves a \c seastar::socket object. socket(socket&&) noexcept; /// Move-assigns a \c seastar::socket object. socket& operator=(socket&&) noexcept; /// Attempts to establish the connection. /// /// \return a \ref connected_socket representing the connection. future<connected_socket> connect(socket_address sa, socket_address local = socket_address(::sockaddr_in{AF_INET, INADDR_ANY, {0}}), transport proto = transport::TCP); /// Sets SO_REUSEADDR option (enable reuseaddr option on a socket) virtual void set_reuseaddr(bool reuseaddr); /// Gets O_REUSEADDR option /// \return whether the reuseaddr option is enabled or not virtual bool get_reuseaddr() const; /// Stops any in-flight connection attempt. /// /// Cancels the connection attempt if it's still in progress, and /// terminates the connection if it has already been established. void shutdown(); }; /// @} /// \addtogroup networking-module /// @{ /// The result of an server_socket::accept() call struct accept_result { connected_socket connection; ///< The newly-accepted connection socket_address remote_address; ///< The address of the peer that connected to us }; SEASTAR_INCLUDE_API_V2 namespace api_v2 { /// A listening socket, waiting to accept incoming network connections. class server_socket { std::unique_ptr<net::api_v2::server_socket_impl> _ssi; bool _aborted = false; public: enum class load_balancing_algorithm { // This algorithm tries to distribute all connections equally between all shards. // It does this by sending new connections to a shard with smallest amount of connections. connection_distribution, // This algorithm distributes new connection based on peer's tcp port. Destination shard // is calculated as a port number modulo number of shards. This allows a client to connect // to a specific shard in a server given it knows how many shards server has by choosing // src port number accordingly. port, default_ = connection_distribution }; /// Constructs a \c server_socket not corresponding to a connection server_socket(); /// \cond internal explicit server_socket(std::unique_ptr<net::api_v2::server_socket_impl> ssi); /// \endcond /// Moves a \c server_socket object. server_socket(server_socket&& ss) noexcept; ~server_socket(); /// Move-assigns a \c server_socket object. server_socket& operator=(server_socket&& cs) noexcept; /// Accepts the next connection to successfully connect to this socket. /// /// \return an accept_result representing the connection and /// the socket_address of the remote endpoint. /// /// \see listen(socket_address sa) /// \see listen(socket_address sa, listen_options opts) future<accept_result> accept(); /// Stops any \ref accept() in progress. /// /// Current and future \ref accept() calls will terminate immediately /// with an error. void abort_accept(); /// Local bound address socket_address local_address() const; }; } #if SEASTAR_API_LEVEL <= 1 SEASTAR_INCLUDE_API_V1 namespace api_v1 { class server_socket { api_v2::server_socket _impl; private: static api_v2::server_socket make_v2_server_socket(std::unique_ptr<net::api_v1::server_socket_impl>); public: using load_balancing_algorithm = api_v2::server_socket::load_balancing_algorithm; server_socket(); explicit server_socket(std::unique_ptr<net::api_v1::server_socket_impl> ssi); explicit server_socket(std::unique_ptr<net::api_v2::server_socket_impl> ssi); server_socket(server_socket&& ss) noexcept; server_socket(api_v2::server_socket&& ss); ~server_socket(); operator api_v2::server_socket() &&; server_socket& operator=(server_socket&& cs) noexcept; future<connected_socket, socket_address> accept(); void abort_accept(); socket_address local_address() const; }; } #endif /// @} struct listen_options { bool reuse_address = false; server_socket::load_balancing_algorithm lba = server_socket::load_balancing_algorithm::default_; transport proto = transport::TCP; int listen_backlog = 100; }; class network_stack { public: virtual ~network_stack() {} virtual server_socket listen(socket_address sa, listen_options opts) = 0; // FIXME: local parameter assumes ipv4 for now, fix when adding other AF future<connected_socket> connect(socket_address sa, socket_address = {}, transport proto = transport::TCP); virtual ::seastar::socket socket() = 0; virtual net::udp_channel make_udp_channel(const socket_address& = {}) = 0; virtual future<> initialize() { return make_ready_future(); } virtual bool has_per_core_namespace() = 0; // NOTE: this is not a correct query approach. // This question should be per NIC, but we have no such // abstraction, so for now this is "stack-wide" virtual bool supports_ipv6() const { return false; } }; } <commit_msg>net: socket::{set,get}_reuseaddr() should not be virtual<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <memory> #include <vector> #include <cstring> #include <seastar/core/future.hh> #include <seastar/net/byteorder.hh> #include <seastar/net/socket_defs.hh> #include <seastar/net/packet.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/iostream.hh> #include <seastar/util/std-compat.hh> #include "../core/internal/api-level.hh" #include <sys/types.h> namespace seastar { inline bool is_ip_unspecified(const ipv4_addr& addr) { return addr.is_ip_unspecified(); } inline bool is_port_unspecified(const ipv4_addr& addr) { return addr.is_port_unspecified(); } inline socket_address make_ipv4_address(const ipv4_addr& addr) { return socket_address(addr); } inline socket_address make_ipv4_address(uint32_t ip, uint16_t port) { return make_ipv4_address(ipv4_addr(ip, port)); } namespace net { // see linux tcp(7) for parameter explanation struct tcp_keepalive_params { std::chrono::seconds idle; // TCP_KEEPIDLE std::chrono::seconds interval; // TCP_KEEPINTVL unsigned count; // TCP_KEEPCNT }; // see linux sctp(7) for parameter explanation struct sctp_keepalive_params { std::chrono::seconds interval; // spp_hbinterval unsigned count; // spp_pathmaxrt }; using keepalive_params = compat::variant<tcp_keepalive_params, sctp_keepalive_params>; /// \cond internal class connected_socket_impl; class socket_impl; #if SEASTAR_API_LEVEL <= 1 SEASTAR_INCLUDE_API_V1 namespace api_v1 { class server_socket_impl; } #endif SEASTAR_INCLUDE_API_V2 namespace api_v2 { class server_socket_impl; } class udp_channel_impl; class get_impl; /// \endcond class udp_datagram_impl { public: virtual ~udp_datagram_impl() {}; virtual socket_address get_src() = 0; virtual socket_address get_dst() = 0; virtual uint16_t get_dst_port() = 0; virtual packet& get_data() = 0; }; class udp_datagram final { private: std::unique_ptr<udp_datagram_impl> _impl; public: udp_datagram(std::unique_ptr<udp_datagram_impl>&& impl) : _impl(std::move(impl)) {}; socket_address get_src() { return _impl->get_src(); } socket_address get_dst() { return _impl->get_dst(); } uint16_t get_dst_port() { return _impl->get_dst_port(); } packet& get_data() { return _impl->get_data(); } }; class udp_channel { private: std::unique_ptr<udp_channel_impl> _impl; public: udp_channel(); udp_channel(std::unique_ptr<udp_channel_impl>); ~udp_channel(); udp_channel(udp_channel&&); udp_channel& operator=(udp_channel&&); socket_address local_address() const; future<udp_datagram> receive(); future<> send(const socket_address& dst, const char* msg); future<> send(const socket_address& dst, packet p); bool is_closed() const; /// Causes a pending receive() to complete (possibly with an exception) void shutdown_input(); /// Causes a pending send() to complete (possibly with an exception) void shutdown_output(); /// Close the channel and releases all resources. /// /// Must be called only when there are no unfinished send() or receive() calls. You /// can force pending calls to complete soon by calling shutdown_input() and /// shutdown_output(). void close(); }; } /* namespace net */ /// \addtogroup networking-module /// @{ /// A TCP (or other stream-based protocol) connection. /// /// A \c connected_socket represents a full-duplex stream between /// two endpoints, a local endpoint and a remote endpoint. class connected_socket { friend class net::get_impl; std::unique_ptr<net::connected_socket_impl> _csi; public: /// Constructs a \c connected_socket not corresponding to a connection connected_socket(); ~connected_socket(); /// \cond internal explicit connected_socket(std::unique_ptr<net::connected_socket_impl> csi); /// \endcond /// Moves a \c connected_socket object. connected_socket(connected_socket&& cs) noexcept; /// Move-assigns a \c connected_socket object. connected_socket& operator=(connected_socket&& cs) noexcept; /// Gets the input stream. /// /// Gets an object returning data sent from the remote endpoint. input_stream<char> input(); /// Gets the output stream. /// /// Gets an object that sends data to the remote endpoint. /// \param buffer_size how much data to buffer output_stream<char> output(size_t buffer_size = 8192); /// Sets the TCP_NODELAY option (disabling Nagle's algorithm) void set_nodelay(bool nodelay); /// Gets the TCP_NODELAY option (Nagle's algorithm) /// /// \return whether the nodelay option is enabled or not bool get_nodelay() const; /// Sets SO_KEEPALIVE option (enable keepalive timer on a socket) void set_keepalive(bool keepalive); /// Gets O_KEEPALIVE option /// \return whether the keepalive option is enabled or not bool get_keepalive() const; /// Sets TCP keepalive parameters void set_keepalive_parameters(const net::keepalive_params& p); /// Get TCP keepalive parameters net::keepalive_params get_keepalive_parameters() const; /// Disables output to the socket. /// /// Current or future writes that have not been successfully flushed /// will immediately fail with an error. This is useful to abort /// operations on a socket that is not making progress due to a /// peer failure. void shutdown_output(); /// Disables input from the socket. /// /// Current or future reads will immediately fail with an error. /// This is useful to abort operations on a socket that is not making /// progress due to a peer failure. void shutdown_input(); }; /// @} /// \addtogroup networking-module /// @{ /// The seastar socket. /// /// A \c socket that allows a connection to be established between /// two endpoints. class socket { std::unique_ptr<net::socket_impl> _si; public: ~socket(); /// \cond internal explicit socket(std::unique_ptr<net::socket_impl> si); /// \endcond /// Moves a \c seastar::socket object. socket(socket&&) noexcept; /// Move-assigns a \c seastar::socket object. socket& operator=(socket&&) noexcept; /// Attempts to establish the connection. /// /// \return a \ref connected_socket representing the connection. future<connected_socket> connect(socket_address sa, socket_address local = socket_address(::sockaddr_in{AF_INET, INADDR_ANY, {0}}), transport proto = transport::TCP); /// Sets SO_REUSEADDR option (enable reuseaddr option on a socket) void set_reuseaddr(bool reuseaddr); /// Gets O_REUSEADDR option /// \return whether the reuseaddr option is enabled or not bool get_reuseaddr() const; /// Stops any in-flight connection attempt. /// /// Cancels the connection attempt if it's still in progress, and /// terminates the connection if it has already been established. void shutdown(); }; /// @} /// \addtogroup networking-module /// @{ /// The result of an server_socket::accept() call struct accept_result { connected_socket connection; ///< The newly-accepted connection socket_address remote_address; ///< The address of the peer that connected to us }; SEASTAR_INCLUDE_API_V2 namespace api_v2 { /// A listening socket, waiting to accept incoming network connections. class server_socket { std::unique_ptr<net::api_v2::server_socket_impl> _ssi; bool _aborted = false; public: enum class load_balancing_algorithm { // This algorithm tries to distribute all connections equally between all shards. // It does this by sending new connections to a shard with smallest amount of connections. connection_distribution, // This algorithm distributes new connection based on peer's tcp port. Destination shard // is calculated as a port number modulo number of shards. This allows a client to connect // to a specific shard in a server given it knows how many shards server has by choosing // src port number accordingly. port, default_ = connection_distribution }; /// Constructs a \c server_socket not corresponding to a connection server_socket(); /// \cond internal explicit server_socket(std::unique_ptr<net::api_v2::server_socket_impl> ssi); /// \endcond /// Moves a \c server_socket object. server_socket(server_socket&& ss) noexcept; ~server_socket(); /// Move-assigns a \c server_socket object. server_socket& operator=(server_socket&& cs) noexcept; /// Accepts the next connection to successfully connect to this socket. /// /// \return an accept_result representing the connection and /// the socket_address of the remote endpoint. /// /// \see listen(socket_address sa) /// \see listen(socket_address sa, listen_options opts) future<accept_result> accept(); /// Stops any \ref accept() in progress. /// /// Current and future \ref accept() calls will terminate immediately /// with an error. void abort_accept(); /// Local bound address socket_address local_address() const; }; } #if SEASTAR_API_LEVEL <= 1 SEASTAR_INCLUDE_API_V1 namespace api_v1 { class server_socket { api_v2::server_socket _impl; private: static api_v2::server_socket make_v2_server_socket(std::unique_ptr<net::api_v1::server_socket_impl>); public: using load_balancing_algorithm = api_v2::server_socket::load_balancing_algorithm; server_socket(); explicit server_socket(std::unique_ptr<net::api_v1::server_socket_impl> ssi); explicit server_socket(std::unique_ptr<net::api_v2::server_socket_impl> ssi); server_socket(server_socket&& ss) noexcept; server_socket(api_v2::server_socket&& ss); ~server_socket(); operator api_v2::server_socket() &&; server_socket& operator=(server_socket&& cs) noexcept; future<connected_socket, socket_address> accept(); void abort_accept(); socket_address local_address() const; }; } #endif /// @} struct listen_options { bool reuse_address = false; server_socket::load_balancing_algorithm lba = server_socket::load_balancing_algorithm::default_; transport proto = transport::TCP; int listen_backlog = 100; }; class network_stack { public: virtual ~network_stack() {} virtual server_socket listen(socket_address sa, listen_options opts) = 0; // FIXME: local parameter assumes ipv4 for now, fix when adding other AF future<connected_socket> connect(socket_address sa, socket_address = {}, transport proto = transport::TCP); virtual ::seastar::socket socket() = 0; virtual net::udp_channel make_udp_channel(const socket_address& = {}) = 0; virtual future<> initialize() { return make_ready_future(); } virtual bool has_per_core_namespace() = 0; // NOTE: this is not a correct query approach. // This question should be per NIC, but we have no such // abstraction, so for now this is "stack-wide" virtual bool supports_ipv6() const { return false; } }; } <|endoftext|>
<commit_before>#pragma once #include <xpp/core.hpp> #include <xpp/generic/factory.hpp> #include <xpp/proto/x.hpp> #include "common.hpp" #include "components/screen.hpp" #include "x11/events.hpp" #include "x11/extensions/all.hpp" #include "x11/registry.hpp" #include "x11/types.hpp" POLYBAR_NS namespace detail { template <typename Connection, typename... Extensions> class interfaces : public xpp::x::extension::interface<interfaces<Connection, Extensions...>, Connection>, public Extensions::template interface<interfaces<Connection, Extensions...>, Connection>... { public: const Connection& connection() const { return static_cast<const Connection&>(*this); } }; template <typename Derived, typename... Extensions> class connection_base : public xpp::core, public xpp::generic::error_dispatcher, public detail::interfaces<connection_base<Derived, Extensions...>, Extensions...>, private xpp::x::extension, private xpp::x::extension::error_dispatcher, private Extensions..., private Extensions::error_dispatcher... { public: template <typename... Args> explicit connection_base(Args&&... args) : xpp::core::core(forward<Args>(args)...) , interfaces<connection_base<Derived, Extensions...>, Extensions...>(*this) , Extensions(static_cast<xcb_connection_t*>(*this))... , Extensions::error_dispatcher(static_cast<Extensions&>(*this).get())... { m_root_window = screen_of_display(default_screen())->root; } virtual ~connection_base() {} const Derived& operator=(const Derived& o) { return o; } virtual operator xcb_connection_t*() const { return *static_cast<const core&>(*this); } void operator()(const shared_ptr<xcb_generic_error_t>& error) const { check<xpp::x::extension, Extensions...>(error); } template <typename Extension> const Extension& extension() const { return static_cast<const Extension&>(*this); } template <typename WindowType = xcb_window_t> WindowType root() const { using make = xpp::generic::factory::make<Derived, xcb_window_t, WindowType>; return make()(*this, m_root_window); } shared_ptr<xcb_generic_event_t> wait_for_event() const { try { return core::wait_for_event(); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } shared_ptr<xcb_generic_event_t> wait_for_special_event(xcb_special_event_t* se) const { try { return core::wait_for_special_event(se); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } private: xcb_window_t m_root_window; template <typename Extension, typename Next, typename... Rest> void check(const shared_ptr<xcb_generic_error_t>& error) const { check<Extension>(error); check<Next, Rest...>(error); } template <typename Extension> void check(const shared_ptr<xcb_generic_error_t>& error) const { using error_dispatcher = typename Extension::error_dispatcher; auto& dispatcher = static_cast<const error_dispatcher&>(*this); dispatcher(error); } }; } class connection : public detail::connection_base<connection&, XPP_EXTENSION_LIST> { public: using base_type = detail::connection_base<connection&, XPP_EXTENSION_LIST>; using make_type = connection&; static make_type make(xcb_connection_t* conn = nullptr); template <typename... Args> explicit connection(Args&&... args) : base_type::connection_base(forward<Args>(args)...) {} const connection& operator=(const connection& o) { return o; } // operator Display*() const; void preload_atoms(); void query_extensions(); string id(xcb_window_t w) const; xcb_screen_t* screen(bool realloc = false); void ensure_event_mask(xcb_window_t win, uint32_t event); void clear_event_mask(xcb_window_t win); shared_ptr<xcb_client_message_event_t> make_client_message(xcb_atom_t type, xcb_window_t target) const; void send_client_message(const shared_ptr<xcb_client_message_event_t>& message, xcb_window_t target, uint32_t event_mask = 0xFFFFFF, bool propagate = false) const; xcb_visualtype_t* visual_type(xcb_screen_t* screen, int match_depth = 32); static string error_str(int error_code); void dispatch_event(const shared_ptr<xcb_generic_event_t>& evt) const; template <typename Event, uint32_t ResponseType> void wait_for_response(function<bool(const Event*)> check_event) { int fd = get_file_descriptor(); shared_ptr<xcb_generic_event_t> evt{}; while (!connection_has_error()) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); if (!select(fd + 1, &fds, nullptr, nullptr, nullptr)) { continue; } else if ((evt = shared_ptr<xcb_generic_event_t>(xcb_poll_for_event(*this), free)) == nullptr) { continue; } else if (evt->response_type != ResponseType) { continue; } else if (check_event(reinterpret_cast<const Event*>(&*evt))) { break; } } } template <typename Sink> void attach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.attach(prio, forward<Sink>(sink)); } template <typename Sink> void detach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.detach(prio, forward<Sink>(sink)); } protected: registry m_registry{*this}; xcb_screen_t* m_screen{nullptr}; }; POLYBAR_NS_END <commit_msg>fix(connection): Include cstdlib for std::free<commit_after>#pragma once #include <cstdlib> #include <xpp/core.hpp> #include <xpp/generic/factory.hpp> #include <xpp/proto/x.hpp> #include "common.hpp" #include "components/screen.hpp" #include "x11/events.hpp" #include "x11/extensions/all.hpp" #include "x11/registry.hpp" #include "x11/types.hpp" POLYBAR_NS namespace detail { template <typename Connection, typename... Extensions> class interfaces : public xpp::x::extension::interface<interfaces<Connection, Extensions...>, Connection>, public Extensions::template interface<interfaces<Connection, Extensions...>, Connection>... { public: const Connection& connection() const { return static_cast<const Connection&>(*this); } }; template <typename Derived, typename... Extensions> class connection_base : public xpp::core, public xpp::generic::error_dispatcher, public detail::interfaces<connection_base<Derived, Extensions...>, Extensions...>, private xpp::x::extension, private xpp::x::extension::error_dispatcher, private Extensions..., private Extensions::error_dispatcher... { public: template <typename... Args> explicit connection_base(Args&&... args) : xpp::core::core(forward<Args>(args)...) , interfaces<connection_base<Derived, Extensions...>, Extensions...>(*this) , Extensions(static_cast<xcb_connection_t*>(*this))... , Extensions::error_dispatcher(static_cast<Extensions&>(*this).get())... { m_root_window = screen_of_display(default_screen())->root; } virtual ~connection_base() {} const Derived& operator=(const Derived& o) { return o; } virtual operator xcb_connection_t*() const { return *static_cast<const core&>(*this); } void operator()(const shared_ptr<xcb_generic_error_t>& error) const { check<xpp::x::extension, Extensions...>(error); } template <typename Extension> const Extension& extension() const { return static_cast<const Extension&>(*this); } template <typename WindowType = xcb_window_t> WindowType root() const { using make = xpp::generic::factory::make<Derived, xcb_window_t, WindowType>; return make()(*this, m_root_window); } shared_ptr<xcb_generic_event_t> wait_for_event() const { try { return core::wait_for_event(); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } shared_ptr<xcb_generic_event_t> wait_for_special_event(xcb_special_event_t* se) const { try { return core::wait_for_special_event(se); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } private: xcb_window_t m_root_window; template <typename Extension, typename Next, typename... Rest> void check(const shared_ptr<xcb_generic_error_t>& error) const { check<Extension>(error); check<Next, Rest...>(error); } template <typename Extension> void check(const shared_ptr<xcb_generic_error_t>& error) const { using error_dispatcher = typename Extension::error_dispatcher; auto& dispatcher = static_cast<const error_dispatcher&>(*this); dispatcher(error); } }; } class connection : public detail::connection_base<connection&, XPP_EXTENSION_LIST> { public: using base_type = detail::connection_base<connection&, XPP_EXTENSION_LIST>; using make_type = connection&; static make_type make(xcb_connection_t* conn = nullptr); template <typename... Args> explicit connection(Args&&... args) : base_type::connection_base(forward<Args>(args)...) {} const connection& operator=(const connection& o) { return o; } // operator Display*() const; void preload_atoms(); void query_extensions(); string id(xcb_window_t w) const; xcb_screen_t* screen(bool realloc = false); void ensure_event_mask(xcb_window_t win, uint32_t event); void clear_event_mask(xcb_window_t win); shared_ptr<xcb_client_message_event_t> make_client_message(xcb_atom_t type, xcb_window_t target) const; void send_client_message(const shared_ptr<xcb_client_message_event_t>& message, xcb_window_t target, uint32_t event_mask = 0xFFFFFF, bool propagate = false) const; xcb_visualtype_t* visual_type(xcb_screen_t* screen, int match_depth = 32); static string error_str(int error_code); void dispatch_event(const shared_ptr<xcb_generic_event_t>& evt) const; template <typename Event, uint32_t ResponseType> void wait_for_response(function<bool(const Event*)> check_event) { int fd = get_file_descriptor(); shared_ptr<xcb_generic_event_t> evt{}; while (!connection_has_error()) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); if (!select(fd + 1, &fds, nullptr, nullptr, nullptr)) { continue; } else if ((evt = shared_ptr<xcb_generic_event_t>(xcb_poll_for_event(*this), free)) == nullptr) { continue; } else if (evt->response_type != ResponseType) { continue; } else if (check_event(reinterpret_cast<const Event*>(&*evt))) { break; } } } template <typename Sink> void attach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.attach(prio, forward<Sink>(sink)); } template <typename Sink> void detach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.detach(prio, forward<Sink>(sink)); } protected: registry m_registry{*this}; xcb_screen_t* m_screen{nullptr}; }; POLYBAR_NS_END <|endoftext|>
<commit_before>#pragma once #include <cstdlib> #include <xpp/core.hpp> #include <xpp/generic/factory.hpp> #include <xpp/proto/x.hpp> #include "common.hpp" #include "components/screen.hpp" #include "x11/events.hpp" #include "x11/extensions/all.hpp" #include "x11/registry.hpp" #include "x11/types.hpp" POLYBAR_NS namespace detail { template <typename Connection, typename... Extensions> class interfaces : public xpp::x::extension::interface<interfaces<Connection, Extensions...>, Connection>, public Extensions::template interface<interfaces<Connection, Extensions...>, Connection>... { public: const Connection& connection() const { return static_cast<const Connection&>(*this); } }; template <typename Derived, typename... Extensions> class connection_base : public xpp::core, public xpp::generic::error_dispatcher, public detail::interfaces<connection_base<Derived, Extensions...>, Extensions...>, private xpp::x::extension, private xpp::x::extension::error_dispatcher, private Extensions..., private Extensions::error_dispatcher... { public: template <typename... Args> explicit connection_base(Args&&... args) : xpp::core::core(forward<Args>(args)...) , interfaces<connection_base<Derived, Extensions...>, Extensions...>(*this) , Extensions(static_cast<xcb_connection_t*>(*this))... , Extensions::error_dispatcher(static_cast<Extensions&>(*this).get())... { m_root_window = screen_of_display(default_screen())->root; } virtual ~connection_base() {} const Derived& operator=(const Derived& o) { return o; } virtual operator xcb_connection_t*() const { return *static_cast<const core&>(*this); } void operator()(const shared_ptr<xcb_generic_error_t>& error) const { check<xpp::x::extension, Extensions...>(error); } template <typename Extension> const Extension& extension() const { return static_cast<const Extension&>(*this); } template <typename WindowType = xcb_window_t> WindowType root() const { using make = xpp::generic::factory::make<Derived, xcb_window_t, WindowType>; return make()(*this, m_root_window); } shared_ptr<xcb_generic_event_t> wait_for_event() const { try { return core::wait_for_event(); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } shared_ptr<xcb_generic_event_t> wait_for_special_event(xcb_special_event_t* se) const { try { return core::wait_for_special_event(se); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } private: xcb_window_t m_root_window; template <typename Extension, typename Next, typename... Rest> void check(const shared_ptr<xcb_generic_error_t>& error) const { check<Extension>(error); check<Next, Rest...>(error); } template <typename Extension> void check(const shared_ptr<xcb_generic_error_t>& error) const { using error_dispatcher = typename Extension::error_dispatcher; auto& dispatcher = static_cast<const error_dispatcher&>(*this); dispatcher(error); } }; } class connection : public detail::connection_base<connection&, XPP_EXTENSION_LIST> { public: using base_type = detail::connection_base<connection&, XPP_EXTENSION_LIST>; using make_type = connection&; static make_type make(xcb_connection_t* conn = nullptr); template <typename... Args> explicit connection(Args&&... args) : base_type::connection_base(forward<Args>(args)...) {} const connection& operator=(const connection& o) { return o; } // operator Display*() const; void preload_atoms(); void query_extensions(); string id(xcb_window_t w) const; xcb_screen_t* screen(bool realloc = false); void ensure_event_mask(xcb_window_t win, uint32_t event); void clear_event_mask(xcb_window_t win); shared_ptr<xcb_client_message_event_t> make_client_message(xcb_atom_t type, xcb_window_t target) const; void send_client_message(const shared_ptr<xcb_client_message_event_t>& message, xcb_window_t target, uint32_t event_mask = 0xFFFFFF, bool propagate = false) const; xcb_visualtype_t* visual_type(xcb_screen_t* screen, int match_depth = 32); static string error_str(int error_code); void dispatch_event(const shared_ptr<xcb_generic_event_t>& evt) const; template <typename Event, uint32_t ResponseType> void wait_for_response(function<bool(const Event*)> check_event) { int fd = get_file_descriptor(); shared_ptr<xcb_generic_event_t> evt{}; while (!connection_has_error()) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); if (!select(fd + 1, &fds, nullptr, nullptr, nullptr)) { continue; } else if ((evt = shared_ptr<xcb_generic_event_t>(xcb_poll_for_event(*this), free)) == nullptr) { continue; } else if (evt->response_type != ResponseType) { continue; } else if (check_event(reinterpret_cast<const Event*>(&*evt))) { break; } } } template <typename Sink> void attach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.attach(prio, forward<Sink>(sink)); } template <typename Sink> void detach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.detach(prio, forward<Sink>(sink)); } protected: registry m_registry{*this}; xcb_screen_t* m_screen{nullptr}; }; POLYBAR_NS_END <commit_msg>fix(connection): Address sanitizer patch<commit_after>#pragma once #include <cstdlib> #include <xpp/core.hpp> #include <xpp/generic/factory.hpp> #include <xpp/proto/x.hpp> #include "common.hpp" #include "components/screen.hpp" #include "x11/events.hpp" #include "x11/extensions/all.hpp" #include "x11/registry.hpp" #include "x11/types.hpp" POLYBAR_NS namespace detail { template <typename Connection, typename... Extensions> class interfaces : public xpp::x::extension::interface<interfaces<Connection, Extensions...>, Connection>, public Extensions::template interface<interfaces<Connection, Extensions...>, Connection>... { public: const Connection& connection() const { return static_cast<const Connection&>(*this); } }; template <typename Derived, typename... Extensions> class connection_base : public xpp::core, public xpp::generic::error_dispatcher, public detail::interfaces<connection_base<Derived, Extensions...>, Extensions...>, private xpp::x::extension, private xpp::x::extension::error_dispatcher, private Extensions..., private Extensions::error_dispatcher... { public: template <typename... Args> explicit connection_base(Args&&... args) : xpp::core(forward<Args>(args)...) , interfaces<connection_base<Derived, Extensions...>, Extensions...>(*this) , Extensions(m_c.get())... , Extensions::error_dispatcher(static_cast<Extensions&>(*this).get())... { m_root_window = screen_of_display(default_screen())->root; } virtual ~connection_base() {} const Derived& operator=(const Derived& o) { return o; } void operator()(const shared_ptr<xcb_generic_error_t>& error) const { check<xpp::x::extension, Extensions...>(error); } template <typename Extension> const Extension& extension() const { return static_cast<const Extension&>(*this); } template <typename WindowType = xcb_window_t> WindowType root() const { using make = xpp::generic::factory::make<Derived, xcb_window_t, WindowType>; return make()(*this, m_root_window); } shared_ptr<xcb_generic_event_t> wait_for_event() const { try { return core::wait_for_event(); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } shared_ptr<xcb_generic_event_t> wait_for_special_event(xcb_special_event_t* se) const { try { return core::wait_for_special_event(se); } catch (const shared_ptr<xcb_generic_error_t>& error) { check<xpp::x::extension, Extensions...>(error); } throw; // re-throw exception } private: xcb_window_t m_root_window; template <typename Extension, typename Next, typename... Rest> void check(const shared_ptr<xcb_generic_error_t>& error) const { check<Extension>(error); check<Next, Rest...>(error); } template <typename Extension> void check(const shared_ptr<xcb_generic_error_t>& error) const { using error_dispatcher = typename Extension::error_dispatcher; auto& dispatcher = static_cast<const error_dispatcher&>(*this); dispatcher(error); } }; } class connection : public detail::connection_base<connection&, XPP_EXTENSION_LIST> { public: using base_type = detail::connection_base<connection&, XPP_EXTENSION_LIST>; using make_type = connection&; static make_type make(xcb_connection_t* conn = nullptr); template <typename... Args> explicit connection(Args&&... args) : base_type(forward<Args>(args)...) {} const connection& operator=(const connection& o) { return o; } // operator Display*() const; void preload_atoms(); void query_extensions(); string id(xcb_window_t w) const; xcb_screen_t* screen(bool realloc = false); void ensure_event_mask(xcb_window_t win, uint32_t event); void clear_event_mask(xcb_window_t win); shared_ptr<xcb_client_message_event_t> make_client_message(xcb_atom_t type, xcb_window_t target) const; void send_client_message(const shared_ptr<xcb_client_message_event_t>& message, xcb_window_t target, uint32_t event_mask = 0xFFFFFF, bool propagate = false) const; xcb_visualtype_t* visual_type(xcb_screen_t* screen, int match_depth = 32); static string error_str(int error_code); void dispatch_event(const shared_ptr<xcb_generic_event_t>& evt) const; template <typename Event, uint32_t ResponseType> void wait_for_response(function<bool(const Event*)> check_event) { int fd = get_file_descriptor(); shared_ptr<xcb_generic_event_t> evt{}; while (!connection_has_error()) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); if (!select(fd + 1, &fds, nullptr, nullptr, nullptr)) { continue; } else if ((evt = shared_ptr<xcb_generic_event_t>(xcb_poll_for_event(*this), free)) == nullptr) { continue; } else if (evt->response_type != ResponseType) { continue; } else if (check_event(reinterpret_cast<const Event*>(&*evt))) { break; } } } template <typename Sink> void attach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.attach(prio, forward<Sink>(sink)); } template <typename Sink> void detach_sink(Sink&& sink, registry::priority prio = 0) { m_registry.detach(prio, forward<Sink>(sink)); } protected: registry m_registry{*this}; xcb_screen_t* m_screen{nullptr}; }; POLYBAR_NS_END <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 <iostream> #include <iterator> #include <fstream> #include "boost/bind.hpp" #include "boost/version.hpp" #if BOOST_VERSION >= 103600 #define BOOST_SPIRIT_USE_OLD_NAMESPACE #include "boost/spirit/include/classic.hpp" #else #include "boost/spirit.hpp" #endif #include "IECore/OBJReader.h" #include "IECore/CompoundData.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/MessageHandler.h" #include "IECore/NumericParameter.h" #include "IECore/TypedParameter.h" #include "IECore/MeshPrimitive.h" #include "IECore/CompoundParameter.h" #include "IECore/FileNameParameter.h" #include "IECore/ObjectParameter.h" #include "IECore/NullObject.h" using namespace std; using namespace IECore; using namespace Imath; using namespace boost; using namespace boost::spirit; IE_CORE_DEFINERUNTIMETYPED(OBJReader); // syntactic sugar for specifying our grammar typedef boost::spirit::rule<boost::spirit::phrase_scanner_t> srule; const Reader::ReaderDescription<OBJReader> OBJReader::m_readerDescription("obj"); OBJReader::OBJReader( const string &name ) : Reader(name, "Alias Wavefront OBJ 3D data reader", new ObjectParameter("result", "the loaded 3D object", new NullObject, MeshPrimitive::staticTypeId())) { m_fileNameParameter->setTypedValue(name); } bool OBJReader::canRead( const string &fileName ) { // there really are no magic numbers, .obj is a simple ascii text file // so: enforce at least that the file has '.obj' extension if(fileName.rfind(".obj") != fileName.length() - 4) return false; // attempt to open the file ifstream in(fileName.c_str()); return in.is_open(); } ObjectPtr OBJReader::doOperation(ConstCompoundObjectPtr operands) { // for now we are going to retrieve vertex, texture, normal coordinates, faces. // later (when we have the primitives), we will handle a larger subset of the // OBJ format IntVectorDataPtr vpf = new IntVectorData(); m_vpf = &vpf->writable(); IntVectorDataPtr vids = new IntVectorData(); m_vids = &vids->writable(); PrimitiveVariable::Interpolation i = PrimitiveVariable::Vertex; MeshPrimitivePtr mesh = new MeshPrimitive(); V3fVectorDataPtr vertices = new V3fVectorData(); m_vertices = &vertices->writable(); mesh->variables.insert(PrimitiveVariableMap::value_type("P", PrimitiveVariable(i, vertices))); // separate texture coordinates FloatVectorDataPtr sTextureCoordinates = new FloatVectorData(); m_sTextureCoordinates = &sTextureCoordinates->writable(); mesh->variables.insert(PrimitiveVariableMap::value_type("s", PrimitiveVariable(i, sTextureCoordinates))); FloatVectorDataPtr tTextureCoordinates = new FloatVectorData(); m_tTextureCoordinates = &tTextureCoordinates->writable(); mesh->variables.insert(PrimitiveVariableMap::value_type("t", PrimitiveVariable(i, tTextureCoordinates))); // build normals V3fVectorDataPtr normals = new V3fVectorData(); m_normals = &normals->writable(); mesh->variables.insert(PrimitiveVariableMap::value_type("N", PrimitiveVariable(i, normals))); // parse the file parseOBJ(); // create our MeshPrimitive mesh->setTopology(vpf, vids, "linear"); return mesh; } // parse a vertex void OBJReader::parseVertex(const char * begin, const char * end) { vector<float> vec; srule vertex = "v" >> real_p[append(vec)] >> real_p[append(vec)] >> real_p[append(vec)]; parse_info<> result = parse(begin, vertex, space_p); // build v V3f v; v[0] = vec[0]; v[1] = vec[1]; v[2] = vec[2]; // add this vertex m_vertices->push_back(v); } // parse a texture coordinate void OBJReader::parseTextureCoordinate(const char * begin, const char * end) { vector<float> vec; srule vertex = "vt" >> real_p[append(vec)] >> real_p[append(vec)] >> *(real_p[append(vec)]); parse_info<> result = parse(begin, vertex, space_p); // build v V3f vt; vt[0] = vec[0]; vt[1] = vec[1]; vt[2] = vec.size() == 3 ? vec[2] : 0.0f; // add this texture coordinate m_introducedTextureCoordinates.push_back(vt); } // parse a normal void OBJReader::parseNormal(const char * begin, const char * end) { vector<float> vec; srule vertex = "vn" >> real_p[append(vec)] >> real_p[append(vec)] >> real_p[append(vec)]; parse_info<> result = parse(begin, vertex, space_p); // build v V3f vn; vn[0] = vec[0]; vn[1] = vec[1]; vn[2] = vec[2]; // add this normal m_introducedNormals.push_back(vn); } // parse face void OBJReader::parseFace(const char * begin, const char * end) { vector<int> vec; vector<int> tvec; vector<int> nvec; srule entry = int_p[append(vec)] >> ( ("/" >> (int_p[append(tvec)] | epsilon_p) >> "/" >> (int_p[append(nvec)] | epsilon_p)) | epsilon_p ); srule face = "f" >> entry >> entry >> entry >> *(entry); parse_info<> result = parse(begin, face, space_p); // push back the degree of the face m_vpf->push_back(vec.size()); // merge in the edges. we index from 0, so shift them down. // also, vertices may be indexed negatively, in which case they are relative to // the current set of vertices for(vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i) { m_vids->push_back(*i > 0 ? *i - 1 : m_vertices->size() + *i); } // merge in texture coordinates and normals, if present // OBJ format requires an encoding for faces which uses one of the vertex/texture/normal specifications // consistently across the entire face. eg. we can have all v/vt/vn, or all v//vn, or all v, but not // v//vn then v/vt/vn ... if(!nvec.empty()) { if(nvec.size() != vec.size()) throw Exception("invalid face specification"); // copy in these references to normal vectors to the mesh's normal vector for(vector<int>::const_iterator i = nvec.begin(); i != nvec.end(); ++i) { m_normals->push_back(m_introducedNormals[*i > 0 ? *i - 1 : m_introducedNormals.size() + *i]); } } // otherwise, check if we have specified normals in some previous face // if so, and no normals were given here (examples, encoders that do this?), pump in // default normal. the default normal defined here is the zero normal, which is by // definition orthogonal to every other vector. this might result in odd lighting. else { V3f zero(0.0f, 0.0f, 0.0f); for(unsigned int i = 0; i < nvec.size(); ++i) { m_normals->push_back(zero); } } // // merge in texture coordinates, if present // if(!tvec.empty()) { if(tvec.size() != vec.size()) throw Exception("invalid face specification"); for(unsigned int i = 0; i < tvec.size(); ++i) { int index = tvec[i] > 0 ? tvec[i] - 1 : m_introducedTextureCoordinates.size() + tvec[i]; m_sTextureCoordinates->push_back(m_introducedTextureCoordinates[index][0]); m_tTextureCoordinates->push_back(m_introducedTextureCoordinates[index][1]); } } else { for(unsigned int i = 0; i < tvec.size(); ++i) { m_sTextureCoordinates->push_back(0.0f); m_tTextureCoordinates->push_back(0.0f); } } } void OBJReader::parseGroup(const char *begin, const char *end) { // set current group vector<string> groupNames; srule grouping = "g" >> *(lexeme_d[alnum_p >> *(alnum_p)][append(groupNames)]); parse_info<> result = parse(begin, grouping, space_p); // from 'http://local.wasp.uwa.edu.au/~pbourke/dataformats/obj/': // The default group name is default. if(groupNames.empty()) { groupNames.push_back("default"); } // \todo associate mesh objects with group names } void OBJReader::parseOBJ() { srule comment = comment_p("#"); // see // http://local.wasp.uwa.edu.au/~pbourke/dataformats/obj/ // vertices srule vertex = ("v" >> real_p >> real_p >> real_p) [bind(&OBJReader::parseVertex, ref(this), _1, _2)]; srule vertex_texture = ("vt" >> real_p >> real_p) [bind(&OBJReader::parseTextureCoordinate, ref(this), _1, _2)]; srule vertex_normal = ("vn" >> real_p >> real_p >> real_p) [bind(&OBJReader::parseNormal, ref(this), _1, _2)]; //srule vertex_parameter_space = "vp" >> real_p >> real_p >> real_p; // srule cs_types = ("bmatrix" | "bezier" | "bspline" | "cardinal" | "taylor"); // srule vertex_curve_or_surface = "cstype" >> "rat" >> cs_types; // srule vertex_degree = "deg" >> real_p >> real_p; // srule vertex_basis_matrix = "bmat"; // srule vertex_step_size = "step" >> int_p >> int_p; srule vertex_type = vertex | vertex_texture | vertex_normal; // elements srule point = "p" >> real_p >> *(real_p); srule line = "l" >> int_p >> int_p >> *(int_p); srule face = (ch_p('f') >> *(anychar_p))[bind(&OBJReader::parseFace, ref(this), _1, _2)]; // srule curve = "curv"; // srule curve_2d = "curv2"; // srule surface = "surf"; srule element = point | line | face; // free-form curve / surface statements // srule parameter = "parm"; // srule trim_loop = "trim"; // srule hole_loop = "hole"; // srule special_curve = "scrv"; // srule special_point = "sp"; // srule end_statement = "end"; // connectivity //srule connect = "con"; // grouping srule group_name = ("g" >> *(anychar_p))[bind(&OBJReader::parseGroup, ref(this), _1, _2)]; // srule smoothing_group = "s"; // srule merging_group = "mg"; srule object_name = "o" >> int_p; srule grouping = group_name | object_name; // display and render attributes // srule bevel_interpretation = "bevel"; // srule color_interpolation = "c_interp"; // srule dissolve_interpolation = "d_interp"; // srule level_of_detail = "lod"; // srule material_name = "usemtl"; // srule material_library = "mtllib"; // srule shadow_casting = "shadow_obj"; // srule ray_tracing = "trace_obj"; // srule curve_approximation_technique = "ctech"; // srule surface_approximation_technique = "stech"; ifstream in(fileName().c_str()); string str; while(getline(in, str)) parse(str.c_str(), vertex_type | element | grouping | comment, space_p); } <commit_msg>Correcting interpolation of texture coordinates and normals to be FaceVarying, courtesy of Roberto Hradec. Also only adding these primvars if they actually contain data, to avoid adding invalid variables.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 <iostream> #include <iterator> #include <fstream> #include "boost/bind.hpp" #include "boost/version.hpp" #if BOOST_VERSION >= 103600 #define BOOST_SPIRIT_USE_OLD_NAMESPACE #include "boost/spirit/include/classic.hpp" #else #include "boost/spirit.hpp" #endif #include "IECore/OBJReader.h" #include "IECore/CompoundData.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/MessageHandler.h" #include "IECore/NumericParameter.h" #include "IECore/TypedParameter.h" #include "IECore/MeshPrimitive.h" #include "IECore/CompoundParameter.h" #include "IECore/FileNameParameter.h" #include "IECore/ObjectParameter.h" #include "IECore/NullObject.h" using namespace std; using namespace IECore; using namespace Imath; using namespace boost; using namespace boost::spirit; IE_CORE_DEFINERUNTIMETYPED(OBJReader); // syntactic sugar for specifying our grammar typedef boost::spirit::rule<boost::spirit::phrase_scanner_t> srule; const Reader::ReaderDescription<OBJReader> OBJReader::m_readerDescription("obj"); OBJReader::OBJReader( const string &name ) : Reader(name, "Alias Wavefront OBJ 3D data reader", new ObjectParameter("result", "the loaded 3D object", new NullObject, MeshPrimitive::staticTypeId())) { m_fileNameParameter->setTypedValue(name); } bool OBJReader::canRead( const string &fileName ) { // there really are no magic numbers, .obj is a simple ascii text file // so: enforce at least that the file has '.obj' extension if(fileName.rfind(".obj") != fileName.length() - 4) return false; // attempt to open the file ifstream in(fileName.c_str()); return in.is_open(); } ObjectPtr OBJReader::doOperation(ConstCompoundObjectPtr operands) { // for now we are going to retrieve vertex, texture, normal coordinates, faces. // later (when we have the primitives), we will handle a larger subset of the // OBJ format IntVectorDataPtr vpf = new IntVectorData(); m_vpf = &vpf->writable(); IntVectorDataPtr vids = new IntVectorData(); m_vids = &vids->writable(); V3fVectorDataPtr vertices = new V3fVectorData(); m_vertices = &vertices->writable(); // separate texture coordinates FloatVectorDataPtr sTextureCoordinates = new FloatVectorData(); m_sTextureCoordinates = &sTextureCoordinates->writable(); FloatVectorDataPtr tTextureCoordinates = new FloatVectorData(); m_tTextureCoordinates = &tTextureCoordinates->writable(); // build normals V3fVectorDataPtr normals = new V3fVectorData(); m_normals = &normals->writable(); // parse the file parseOBJ(); // create our MeshPrimitive MeshPrimitivePtr mesh = new MeshPrimitive( vpf, vids, "linear", vertices ); if( sTextureCoordinates->readable().size() ) { mesh->variables.insert(PrimitiveVariableMap::value_type("s", PrimitiveVariable( PrimitiveVariable::FaceVarying, sTextureCoordinates))); } if( tTextureCoordinates->readable().size() ) { mesh->variables.insert(PrimitiveVariableMap::value_type("t", PrimitiveVariable( PrimitiveVariable::FaceVarying, tTextureCoordinates))); } if( normals->readable().size() ) { mesh->variables.insert(PrimitiveVariableMap::value_type("N", PrimitiveVariable( PrimitiveVariable::FaceVarying, normals))); } return mesh; } // parse a vertex void OBJReader::parseVertex(const char * begin, const char * end) { vector<float> vec; srule vertex = "v" >> real_p[append(vec)] >> real_p[append(vec)] >> real_p[append(vec)]; parse_info<> result = parse(begin, vertex, space_p); // build v V3f v; v[0] = vec[0]; v[1] = vec[1]; v[2] = vec[2]; // add this vertex m_vertices->push_back(v); } // parse a texture coordinate void OBJReader::parseTextureCoordinate(const char * begin, const char * end) { vector<float> vec; srule vertex = "vt" >> real_p[append(vec)] >> real_p[append(vec)] >> *(real_p[append(vec)]); parse_info<> result = parse(begin, vertex, space_p); // build v V3f vt; vt[0] = vec[0]; vt[1] = vec[1]; vt[2] = vec.size() == 3 ? vec[2] : 0.0f; // add this texture coordinate m_introducedTextureCoordinates.push_back(vt); } // parse a normal void OBJReader::parseNormal(const char * begin, const char * end) { vector<float> vec; srule vertex = "vn" >> real_p[append(vec)] >> real_p[append(vec)] >> real_p[append(vec)]; parse_info<> result = parse(begin, vertex, space_p); // build v V3f vn; vn[0] = vec[0]; vn[1] = vec[1]; vn[2] = vec[2]; // add this normal m_introducedNormals.push_back(vn); } // parse face void OBJReader::parseFace(const char * begin, const char * end) { vector<int> vec; vector<int> tvec; vector<int> nvec; srule entry = int_p[append(vec)] >> ( ("/" >> (int_p[append(tvec)] | epsilon_p) >> "/" >> (int_p[append(nvec)] | epsilon_p)) | epsilon_p ); srule face = "f" >> entry >> entry >> entry >> *(entry); parse_info<> result = parse(begin, face, space_p); // push back the degree of the face m_vpf->push_back(vec.size()); // merge in the edges. we index from 0, so shift them down. // also, vertices may be indexed negatively, in which case they are relative to // the current set of vertices for(vector<int>::const_iterator i = vec.begin(); i != vec.end(); ++i) { m_vids->push_back(*i > 0 ? *i - 1 : m_vertices->size() + *i); } // merge in texture coordinates and normals, if present // OBJ format requires an encoding for faces which uses one of the vertex/texture/normal specifications // consistently across the entire face. eg. we can have all v/vt/vn, or all v//vn, or all v, but not // v//vn then v/vt/vn ... if(!nvec.empty()) { if(nvec.size() != vec.size()) throw Exception("invalid face specification"); // copy in these references to normal vectors to the mesh's normal vector for(vector<int>::const_iterator i = nvec.begin(); i != nvec.end(); ++i) { m_normals->push_back(m_introducedNormals[*i > 0 ? *i - 1 : m_introducedNormals.size() + *i]); } } // otherwise, check if we have specified normals in some previous face // if so, and no normals were given here (examples, encoders that do this?), pump in // default normal. the default normal defined here is the zero normal, which is by // definition orthogonal to every other vector. this might result in odd lighting. else { V3f zero(0.0f, 0.0f, 0.0f); for(unsigned int i = 0; i < nvec.size(); ++i) { m_normals->push_back(zero); } } // // merge in texture coordinates, if present // if(!tvec.empty()) { if(tvec.size() != vec.size()) throw Exception("invalid face specification"); for(unsigned int i = 0; i < tvec.size(); ++i) { int index = tvec[i] > 0 ? tvec[i] - 1 : m_introducedTextureCoordinates.size() + tvec[i]; m_sTextureCoordinates->push_back(m_introducedTextureCoordinates[index][0]); m_tTextureCoordinates->push_back(m_introducedTextureCoordinates[index][1]); } } else { for(unsigned int i = 0; i < tvec.size(); ++i) { m_sTextureCoordinates->push_back(0.0f); m_tTextureCoordinates->push_back(0.0f); } } } void OBJReader::parseGroup(const char *begin, const char *end) { // set current group vector<string> groupNames; srule grouping = "g" >> *(lexeme_d[alnum_p >> *(alnum_p)][append(groupNames)]); parse_info<> result = parse(begin, grouping, space_p); // from 'http://local.wasp.uwa.edu.au/~pbourke/dataformats/obj/': // The default group name is default. if(groupNames.empty()) { groupNames.push_back("default"); } // \todo associate mesh objects with group names } void OBJReader::parseOBJ() { srule comment = comment_p("#"); // see // http://local.wasp.uwa.edu.au/~pbourke/dataformats/obj/ // vertices srule vertex = ("v" >> real_p >> real_p >> real_p) [bind(&OBJReader::parseVertex, ref(this), _1, _2)]; srule vertex_texture = ("vt" >> real_p >> real_p) [bind(&OBJReader::parseTextureCoordinate, ref(this), _1, _2)]; srule vertex_normal = ("vn" >> real_p >> real_p >> real_p) [bind(&OBJReader::parseNormal, ref(this), _1, _2)]; //srule vertex_parameter_space = "vp" >> real_p >> real_p >> real_p; // srule cs_types = ("bmatrix" | "bezier" | "bspline" | "cardinal" | "taylor"); // srule vertex_curve_or_surface = "cstype" >> "rat" >> cs_types; // srule vertex_degree = "deg" >> real_p >> real_p; // srule vertex_basis_matrix = "bmat"; // srule vertex_step_size = "step" >> int_p >> int_p; srule vertex_type = vertex | vertex_texture | vertex_normal; // elements srule point = "p" >> real_p >> *(real_p); srule line = "l" >> int_p >> int_p >> *(int_p); srule face = (ch_p('f') >> *(anychar_p))[bind(&OBJReader::parseFace, ref(this), _1, _2)]; // srule curve = "curv"; // srule curve_2d = "curv2"; // srule surface = "surf"; srule element = point | line | face; // free-form curve / surface statements // srule parameter = "parm"; // srule trim_loop = "trim"; // srule hole_loop = "hole"; // srule special_curve = "scrv"; // srule special_point = "sp"; // srule end_statement = "end"; // connectivity //srule connect = "con"; // grouping srule group_name = ("g" >> *(anychar_p))[bind(&OBJReader::parseGroup, ref(this), _1, _2)]; // srule smoothing_group = "s"; // srule merging_group = "mg"; srule object_name = "o" >> int_p; srule grouping = group_name | object_name; // display and render attributes // srule bevel_interpretation = "bevel"; // srule color_interpolation = "c_interp"; // srule dissolve_interpolation = "d_interp"; // srule level_of_detail = "lod"; // srule material_name = "usemtl"; // srule material_library = "mtllib"; // srule shadow_casting = "shadow_obj"; // srule ray_tracing = "trace_obj"; // srule curve_approximation_technique = "ctech"; // srule surface_approximation_technique = "stech"; ifstream in(fileName().c_str()); string str; while(getline(in, str)) parse(str.c_str(), vertex_type | element | grouping | comment, space_p); } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * 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. */ #ifdef HAVE_LINUX_INPUT #include "input_linux.hpp" #endif #include "application.hpp" #include "application_events.hpp" #include "application_wsi.hpp" #include "vulkan_headers.hpp" #include "global_managers_init.hpp" #include <string.h> #include <signal.h> using namespace std; using namespace Vulkan; namespace Granite { struct WSIPlatformDisplay; static WSIPlatformDisplay *global_display; static void signal_handler(int); static bool vulkan_update_display_mode(unsigned *width, unsigned *height, const VkDisplayModePropertiesKHR *mode, unsigned desired_width, unsigned desired_height) { unsigned visible_width = mode->parameters.visibleRegion.width; unsigned visible_height = mode->parameters.visibleRegion.height; if (!desired_width || !desired_height) { /* Strategy here is to pick something which is largest resolution. */ unsigned area = visible_width * visible_height; if (area > (*width) * (*height)) { *width = visible_width; *height = visible_height; return true; } else return false; } else { /* For particular resolutions, find the closest. */ int delta_x = int(desired_width) - int(visible_width); int delta_y = int(desired_height) - int(visible_height); int old_delta_x = int(desired_width) - int(*width); int old_delta_y = int(desired_height) - int(*height); int dist = delta_x * delta_x + delta_y * delta_y; int old_dist = old_delta_x * old_delta_x + old_delta_y * old_delta_y; if (dist < old_dist) { *width = visible_width; *height = visible_height; return true; } else return false; } } struct WSIPlatformDisplay : Granite::GraniteWSIPlatform { public: bool init(unsigned width_, unsigned height_) { width = width_; height = height_; if (!Context::init_loader(nullptr)) { LOGE("Failed to initialize Vulkan loader.\n"); return false; } auto *em = GRANITE_EVENT_MANAGER(); if (em) { em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Running); } global_display = this; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_handler = signal_handler; sa.sa_flags = SA_RESTART | SA_RESETHAND; sigaction(SIGINT, &sa, nullptr); sigaction(SIGTERM, &sa, nullptr); #ifdef HAVE_LINUX_INPUT if (!input_manager.init( LINUX_INPUT_MANAGER_JOYPAD_BIT | LINUX_INPUT_MANAGER_KEYBOARD_BIT | LINUX_INPUT_MANAGER_MOUSE_BIT | LINUX_INPUT_MANAGER_TOUCHPAD_BIT, &get_input_tracker())) { LOGI("Failed to initialize input manager.\n"); } #endif return true; } ~WSIPlatformDisplay() { auto *em = GRANITE_EVENT_MANAGER(); if (em) { em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped); } } bool alive(Vulkan::WSI &) override { return is_alive; } void poll_input() override { #ifdef HAVE_LINUX_INPUT input_manager.poll(); #endif get_input_tracker().dispatch_current_state(get_frame_timer().get_frame_time()); } vector<const char *> get_instance_extensions() override { #ifdef KHR_DISPLAY_ACQUIRE_XLIB return { "VK_KHR_surface", "VK_KHR_display", "VK_EXT_acquire_xlib_display" }; #else return { "VK_KHR_surface", "VK_KHR_display" }; #endif } VkSurfaceKHR create_surface(VkInstance instance, VkPhysicalDevice gpu) override { VkSurfaceKHR surface = VK_NULL_HANDLE; auto gpa = Vulkan::Context::get_instance_proc_addr(); #define SYM(x) PFN_##x p_##x; do { PFN_vkVoidFunction vf = gpa(instance, #x); memcpy(&p_##x, &vf, sizeof(vf)); } while(0) SYM(vkGetPhysicalDeviceDisplayPropertiesKHR); SYM(vkGetPhysicalDeviceDisplayPlanePropertiesKHR); SYM(vkGetDisplayModePropertiesKHR); SYM(vkGetDisplayPlaneSupportedDisplaysKHR); SYM(vkGetDisplayPlaneCapabilitiesKHR); SYM(vkCreateDisplayPlaneSurfaceKHR); uint32_t display_count; p_vkGetPhysicalDeviceDisplayPropertiesKHR(gpu, &display_count, nullptr); vector<VkDisplayPropertiesKHR> displays(display_count); p_vkGetPhysicalDeviceDisplayPropertiesKHR(gpu, &display_count, displays.data()); uint32_t plane_count; p_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(gpu, &plane_count, nullptr); vector<VkDisplayPlanePropertiesKHR> planes(plane_count); p_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(gpu, &plane_count, planes.data()); #ifdef KHR_DISPLAY_ACQUIRE_XLIB VkDisplayKHR best_display = VK_NULL_HANDLE; #endif VkDisplayModeKHR best_mode = VK_NULL_HANDLE; uint32_t best_plane = UINT32_MAX; const char *desired_display = getenv("GRANITE_DISPLAY_NAME"); unsigned actual_width = 0; unsigned actual_height = 0; VkDisplayPlaneAlphaFlagBitsKHR alpha_mode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; for (unsigned dpy = 0; dpy < display_count; dpy++) { VkDisplayKHR display = displays[dpy].display; best_mode = VK_NULL_HANDLE; best_plane = UINT32_MAX; if (desired_display && strstr(displays[dpy].displayName, desired_display) != displays[dpy].displayName) continue; uint32_t mode_count; p_vkGetDisplayModePropertiesKHR(gpu, display, &mode_count, nullptr); vector<VkDisplayModePropertiesKHR> modes(mode_count); p_vkGetDisplayModePropertiesKHR(gpu, display, &mode_count, modes.data()); for (unsigned i = 0; i < mode_count; i++) { const VkDisplayModePropertiesKHR &mode = modes[i]; if (vulkan_update_display_mode(&actual_width, &actual_height, &mode, 0, 0)) best_mode = mode.displayMode; } if (best_mode == VK_NULL_HANDLE) continue; for (unsigned i = 0; i < plane_count; i++) { uint32_t supported_count = 0; VkDisplayPlaneCapabilitiesKHR plane_caps; p_vkGetDisplayPlaneSupportedDisplaysKHR(gpu, i, &supported_count, nullptr); if (!supported_count) continue; vector<VkDisplayKHR> supported(supported_count); p_vkGetDisplayPlaneSupportedDisplaysKHR(gpu, i, &supported_count, supported.data()); unsigned j; for (j = 0; j < supported_count; j++) { if (supported[j] == display) { if (best_plane == UINT32_MAX) best_plane = j; break; } } if (j == supported_count) continue; if (planes[i].currentDisplay == VK_NULL_HANDLE || planes[i].currentDisplay == display) best_plane = j; else continue; p_vkGetDisplayPlaneCapabilitiesKHR(gpu, best_mode, i, &plane_caps); if (plane_caps.supportedAlpha & VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR) { best_plane = j; alpha_mode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; #ifdef KHR_DISPLAY_ACQUIRE_XLIB best_display = display; #endif goto out; } } } out: if (best_mode == VK_NULL_HANDLE) return VK_NULL_HANDLE; if (best_plane == UINT32_MAX) return VK_NULL_HANDLE; VkDisplaySurfaceCreateInfoKHR create_info = { VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR }; create_info.displayMode = best_mode; create_info.planeIndex = best_plane; create_info.planeStackIndex = planes[best_plane].currentStackIndex; create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; create_info.globalAlpha = 1.0f; create_info.alphaMode = alpha_mode; create_info.imageExtent.width = actual_width; create_info.imageExtent.height = actual_height; this->width = actual_width; this->height = actual_height; #ifdef KHR_DISPLAY_ACQUIRE_XLIB xlib_dpy = XOpenDisplay(nullptr); if (xlib_dpy) { SYM(vkAcquireXlibDisplayEXT); if (p_vkAcquireXlibDisplayEXT(gpu, xlib_dpy, best_display) != VK_SUCCESS) LOGE("Failed to acquire Xlib display. Surface creation may fail.\n"); } #endif if (p_vkCreateDisplayPlaneSurfaceKHR(instance, &create_info, NULL, &surface) != VK_SUCCESS) return VK_NULL_HANDLE; get_input_tracker().set_relative_mouse_rect(0.0, 0.0, double(this->width), double(this->height)); get_input_tracker().mouse_enter(0.5 * this->width, 0.5 * this->height); get_input_tracker().set_relative_mouse_speed(0.35, 0.35); return surface; } uint32_t get_surface_width() override { return width; } uint32_t get_surface_height() override { return height; } void notify_resize(unsigned width_, unsigned height_) { resize = true; width = width_; height = height_; } void signal_die() { is_alive = false; } private: unsigned width = 0; unsigned height = 0; #ifdef KHR_DISPLAY_ACQUIRE_XLIB Display *xlib_dpy = nullptr; #endif bool is_alive = true; #ifdef HAVE_LINUX_INPUT LinuxInputManager input_manager; #endif }; static void signal_handler(int) { LOGI("SIGINT or SIGTERM received.\n"); global_display->signal_die(); } } namespace Granite { int application_main(Application *(*create_application)(int, char **), int argc, char *argv[]) { Global::init(); auto app = unique_ptr<Granite::Application>(create_application(argc, argv)); if (app) { auto platform = make_unique<Granite::WSIPlatformDisplay>(); if (!platform->init(1280, 720)) return 1; if (!app->init_wsi(move(platform))) return 1; Granite::Global::start_audio_system(); while (app->poll()) app->run_frame(); Granite::Global::stop_audio_system(); app.reset(); Granite::Global::deinit(); return 0; } else return 1; } } <commit_msg>Allow KHR_DISPLAY platform to build on Win32.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * 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. */ #ifdef HAVE_LINUX_INPUT #include "input_linux.hpp" #endif #include "application.hpp" #include "application_events.hpp" #include "application_wsi.hpp" #include "vulkan_headers.hpp" #include "global_managers_init.hpp" #include <string.h> #ifndef _WIN32 #include <signal.h> #endif using namespace std; using namespace Vulkan; namespace Granite { struct WSIPlatformDisplay; static WSIPlatformDisplay *global_display; #ifndef _WIN32 static void signal_handler(int); #endif static bool vulkan_update_display_mode(unsigned *width, unsigned *height, const VkDisplayModePropertiesKHR *mode, unsigned desired_width, unsigned desired_height) { unsigned visible_width = mode->parameters.visibleRegion.width; unsigned visible_height = mode->parameters.visibleRegion.height; if (!desired_width || !desired_height) { /* Strategy here is to pick something which is largest resolution. */ unsigned area = visible_width * visible_height; if (area > (*width) * (*height)) { *width = visible_width; *height = visible_height; return true; } else return false; } else { /* For particular resolutions, find the closest. */ int delta_x = int(desired_width) - int(visible_width); int delta_y = int(desired_height) - int(visible_height); int old_delta_x = int(desired_width) - int(*width); int old_delta_y = int(desired_height) - int(*height); int dist = delta_x * delta_x + delta_y * delta_y; int old_dist = old_delta_x * old_delta_x + old_delta_y * old_delta_y; if (dist < old_dist) { *width = visible_width; *height = visible_height; return true; } else return false; } } struct WSIPlatformDisplay : Granite::GraniteWSIPlatform { public: bool init(unsigned width_, unsigned height_) { width = width_; height = height_; if (!Context::init_loader(nullptr)) { LOGE("Failed to initialize Vulkan loader.\n"); return false; } auto *em = GRANITE_EVENT_MANAGER(); if (em) { em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Running); } global_display = this; #ifndef _WIN32 struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_handler = signal_handler; sa.sa_flags = SA_RESTART | SA_RESETHAND; sigaction(SIGINT, &sa, nullptr); sigaction(SIGTERM, &sa, nullptr); #endif #ifdef HAVE_LINUX_INPUT if (!input_manager.init( LINUX_INPUT_MANAGER_JOYPAD_BIT | LINUX_INPUT_MANAGER_KEYBOARD_BIT | LINUX_INPUT_MANAGER_MOUSE_BIT | LINUX_INPUT_MANAGER_TOUCHPAD_BIT, &get_input_tracker())) { LOGI("Failed to initialize input manager.\n"); } #endif return true; } ~WSIPlatformDisplay() { auto *em = GRANITE_EVENT_MANAGER(); if (em) { em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Paused); em->dequeue_all_latched(ApplicationLifecycleEvent::get_type_id()); em->enqueue_latched<ApplicationLifecycleEvent>(ApplicationLifecycle::Stopped); } } bool alive(Vulkan::WSI &) override { return is_alive; } void poll_input() override { #ifdef HAVE_LINUX_INPUT input_manager.poll(); #endif get_input_tracker().dispatch_current_state(get_frame_timer().get_frame_time()); } vector<const char *> get_instance_extensions() override { #ifdef KHR_DISPLAY_ACQUIRE_XLIB return { "VK_KHR_surface", "VK_KHR_display", "VK_EXT_acquire_xlib_display" }; #else return { "VK_KHR_surface", "VK_KHR_display" }; #endif } VkSurfaceKHR create_surface(VkInstance instance, VkPhysicalDevice gpu) override { VkSurfaceKHR surface = VK_NULL_HANDLE; auto gpa = Vulkan::Context::get_instance_proc_addr(); #define SYM(x) PFN_##x p_##x; do { PFN_vkVoidFunction vf = gpa(instance, #x); memcpy(&p_##x, &vf, sizeof(vf)); } while(0) SYM(vkGetPhysicalDeviceDisplayPropertiesKHR); SYM(vkGetPhysicalDeviceDisplayPlanePropertiesKHR); SYM(vkGetDisplayModePropertiesKHR); SYM(vkGetDisplayPlaneSupportedDisplaysKHR); SYM(vkGetDisplayPlaneCapabilitiesKHR); SYM(vkCreateDisplayPlaneSurfaceKHR); uint32_t display_count; p_vkGetPhysicalDeviceDisplayPropertiesKHR(gpu, &display_count, nullptr); vector<VkDisplayPropertiesKHR> displays(display_count); p_vkGetPhysicalDeviceDisplayPropertiesKHR(gpu, &display_count, displays.data()); uint32_t plane_count; p_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(gpu, &plane_count, nullptr); vector<VkDisplayPlanePropertiesKHR> planes(plane_count); p_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(gpu, &plane_count, planes.data()); #ifdef KHR_DISPLAY_ACQUIRE_XLIB VkDisplayKHR best_display = VK_NULL_HANDLE; #endif VkDisplayModeKHR best_mode = VK_NULL_HANDLE; uint32_t best_plane = UINT32_MAX; const char *desired_display = getenv("GRANITE_DISPLAY_NAME"); unsigned actual_width = 0; unsigned actual_height = 0; VkDisplayPlaneAlphaFlagBitsKHR alpha_mode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; for (unsigned dpy = 0; dpy < display_count; dpy++) { VkDisplayKHR display = displays[dpy].display; best_mode = VK_NULL_HANDLE; best_plane = UINT32_MAX; if (desired_display && strstr(displays[dpy].displayName, desired_display) != displays[dpy].displayName) continue; uint32_t mode_count; p_vkGetDisplayModePropertiesKHR(gpu, display, &mode_count, nullptr); vector<VkDisplayModePropertiesKHR> modes(mode_count); p_vkGetDisplayModePropertiesKHR(gpu, display, &mode_count, modes.data()); for (unsigned i = 0; i < mode_count; i++) { const VkDisplayModePropertiesKHR &mode = modes[i]; if (vulkan_update_display_mode(&actual_width, &actual_height, &mode, 0, 0)) best_mode = mode.displayMode; } if (best_mode == VK_NULL_HANDLE) continue; for (unsigned i = 0; i < plane_count; i++) { uint32_t supported_count = 0; VkDisplayPlaneCapabilitiesKHR plane_caps; p_vkGetDisplayPlaneSupportedDisplaysKHR(gpu, i, &supported_count, nullptr); if (!supported_count) continue; vector<VkDisplayKHR> supported(supported_count); p_vkGetDisplayPlaneSupportedDisplaysKHR(gpu, i, &supported_count, supported.data()); unsigned j; for (j = 0; j < supported_count; j++) { if (supported[j] == display) { if (best_plane == UINT32_MAX) best_plane = j; break; } } if (j == supported_count) continue; if (planes[i].currentDisplay == VK_NULL_HANDLE || planes[i].currentDisplay == display) best_plane = j; else continue; p_vkGetDisplayPlaneCapabilitiesKHR(gpu, best_mode, i, &plane_caps); if (plane_caps.supportedAlpha & VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR) { best_plane = j; alpha_mode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR; #ifdef KHR_DISPLAY_ACQUIRE_XLIB best_display = display; #endif goto out; } } } out: if (best_mode == VK_NULL_HANDLE) return VK_NULL_HANDLE; if (best_plane == UINT32_MAX) return VK_NULL_HANDLE; VkDisplaySurfaceCreateInfoKHR create_info = { VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR }; create_info.displayMode = best_mode; create_info.planeIndex = best_plane; create_info.planeStackIndex = planes[best_plane].currentStackIndex; create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; create_info.globalAlpha = 1.0f; create_info.alphaMode = alpha_mode; create_info.imageExtent.width = actual_width; create_info.imageExtent.height = actual_height; this->width = actual_width; this->height = actual_height; #ifdef KHR_DISPLAY_ACQUIRE_XLIB xlib_dpy = XOpenDisplay(nullptr); if (xlib_dpy) { SYM(vkAcquireXlibDisplayEXT); if (p_vkAcquireXlibDisplayEXT(gpu, xlib_dpy, best_display) != VK_SUCCESS) LOGE("Failed to acquire Xlib display. Surface creation may fail.\n"); } #endif if (p_vkCreateDisplayPlaneSurfaceKHR(instance, &create_info, NULL, &surface) != VK_SUCCESS) return VK_NULL_HANDLE; get_input_tracker().set_relative_mouse_rect(0.0, 0.0, double(this->width), double(this->height)); get_input_tracker().mouse_enter(0.5 * this->width, 0.5 * this->height); get_input_tracker().set_relative_mouse_speed(0.35, 0.35); return surface; } uint32_t get_surface_width() override { return width; } uint32_t get_surface_height() override { return height; } void notify_resize(unsigned width_, unsigned height_) { resize = true; width = width_; height = height_; } void signal_die() { is_alive = false; } private: unsigned width = 0; unsigned height = 0; #ifdef KHR_DISPLAY_ACQUIRE_XLIB Display *xlib_dpy = nullptr; #endif bool is_alive = true; #ifdef HAVE_LINUX_INPUT LinuxInputManager input_manager; #endif }; #ifndef _WIN32 static void signal_handler(int) { LOGI("SIGINT or SIGTERM received.\n"); global_display->signal_die(); } #endif } namespace Granite { int application_main(Application *(*create_application)(int, char **), int argc, char *argv[]) { Global::init(); auto app = unique_ptr<Granite::Application>(create_application(argc, argv)); if (app) { auto platform = make_unique<Granite::WSIPlatformDisplay>(); if (!platform->init(1280, 720)) return 1; if (!app->init_wsi(move(platform))) return 1; Granite::Global::start_audio_system(); while (app->poll()) app->run_frame(); Granite::Global::stop_audio_system(); app.reset(); Granite::Global::deinit(); return 0; } else return 1; } } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <cstdint> #include <exception> #include <functional> #include <type_traits> #include <utility> #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/actor_config.hpp" #include "caf/actor_system.hpp" #include "caf/behavior.hpp" #include "caf/check_typed_input.hpp" #include "caf/delegated.hpp" #include "caf/duration.hpp" #include "caf/error.hpp" #include "caf/fwd.hpp" #include "caf/message.hpp" #include "caf/message_handler.hpp" #include "caf/message_id.hpp" #include "caf/message_priority.hpp" #include "caf/monitorable_actor.hpp" #include "caf/response_promise.hpp" #include "caf/response_type.hpp" #include "caf/resumable.hpp" #include "caf/spawn_options.hpp" #include "caf/typed_actor.hpp" #include "caf/typed_response_promise.hpp" #include "caf/detail/typed_actor_util.hpp" namespace caf { /// Base class for actors running on this node, either /// living in an own thread or cooperatively scheduled. class local_actor : public monitorable_actor { public: // -- member types ----------------------------------------------------------- /// Defines a monotonic clock suitable for measuring intervals. using clock_type = std::chrono::steady_clock; // -- constructors, destructors, and assignment operators -------------------- local_actor(actor_config& cfg); ~local_actor() override; void on_destroy() override; // -- pure virtual modifiers ------------------------------------------------- virtual void launch(execution_unit* eu, bool lazy, bool hide) = 0; // -- time ------------------------------------------------------------------- /// Returns the current time. clock_type::time_point now() const noexcept; /// Returns the difference between `t0` and `t1`, allowing the clock to /// return any arbitrary value depending on the measurement that took place. clock_type::duration difference(atom_value measurement, clock_type::time_point t0, clock_type::time_point t1); // -- timeout management ----------------------------------------------------- /// Requests a new timeout for `mid`. /// @pre `mid.valid()` void request_response_timeout(const duration& d, message_id mid); // -- spawn functions -------------------------------------------------------- template <class T, spawn_options Os = no_spawn_options, class... Ts> infer_handle_from_class_t<T> spawn(Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<T, make_unbound(Os)>( cfg, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options> infer_handle_from_state_t<T> spawn() { using impl = composable_behavior_based_actor<T>; actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<impl, make_unbound(Os)>(cfg)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> infer_handle_from_fun_t<F> spawn(F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_functor<make_unbound(Os)>( cfg, fun, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class Groups, class... Ts> actor spawn_in_groups(const Groups& gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_group(const group& grp, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, first, first + 1, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class Groups, class F, class... Ts> actor spawn_in_groups(const Groups& gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_group(const group& grp, F fun, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, first, first + 1, fun, std::forward<Ts>(xs)...)); } // -- sending asynchronous messages ------------------------------------------ /// Sends an exit message to `dest`. void send_exit(const actor_addr& whom, error reason); void send_exit(const strong_actor_ptr& dest, error reason); /// Sends an exit message to `dest`. template <class ActorHandle> void send_exit(const ActorHandle& dest, error reason) { dest->eq_impl(make_message_id(), ctrl(), context(), exit_msg{address(), std::move(reason)}); } // -- miscellaneous actor operations ----------------------------------------- /// Returns the execution unit currently used by this actor. inline execution_unit* context() const { return context_; } /// Sets the execution unit for this actor. inline void context(execution_unit* x) { context_ = x; } /// Returns the hosting actor system. inline actor_system& system() const { CAF_ASSERT(context_); return context_->system(); } /// Returns the clock of the actor system. inline actor_clock& clock() const { return home_system().clock(); } /// @cond PRIVATE void monitor(abstract_actor* ptr); /// @endcond /// Returns a pointer to the sender of the current message. /// @pre `current_mailbox_element() != nullptr` inline strong_actor_ptr& current_sender() { CAF_ASSERT(current_element_); return current_element_->sender; } /// Returns the ID of the current message. inline message_id current_message_id() { CAF_ASSERT(current_element_); return current_element_->mid; } /// Returns the ID of the current message and marks the ID stored in the /// current mailbox element as answered. inline message_id take_current_message_id() { CAF_ASSERT(current_element_); auto result = current_element_->mid; current_element_->mid.mark_as_answered(); return result; } /// Marks the current message ID as answered. inline void drop_current_message_id() { CAF_ASSERT(current_element_); current_element_->mid.mark_as_answered(); } /// Returns a pointer to the next stage from the forwarding path of the /// current message or `nullptr` if the path is empty. inline strong_actor_ptr current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) stages.back(); return nullptr; } /// Returns a pointer to the next stage from the forwarding path of the /// current message and removes it from the path. Returns `nullptr` if the /// path is empty. inline strong_actor_ptr take_current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) { auto result = stages.back(); stages.pop_back(); return result; } return nullptr; } /// Returns the forwarding stack from the current mailbox element. const mailbox_element::forwarding_stack& current_forwarding_stack() { CAF_ASSERT(current_element_); return current_element_->stages; } /// Moves the forwarding stack from the current mailbox element. mailbox_element::forwarding_stack take_current_forwarding_stack() { CAF_ASSERT(current_element_); return std::move(current_element_->stages); } /// Returns a pointer to the currently processed mailbox element. inline mailbox_element* current_mailbox_element() { return current_element_; } /// Returns a pointer to the currently processed mailbox element. /// @private inline void current_mailbox_element(mailbox_element* ptr) { current_element_ = ptr; } /// Adds a unidirectional `monitor` to `whom`. /// @note Each call to `monitor` creates a new, independent monitor. template <class Handle> void monitor(const Handle& whom) { monitor(actor_cast<abstract_actor*>(whom)); } /// Removes a monitor from `whom`. void demonitor(const actor_addr& whom); /// Removes a monitor from `whom`. inline void demonitor(const actor& whom) { demonitor(whom.address()); } /// Can be overridden to perform cleanup code after an actor /// finished execution. virtual void on_exit(); /// Creates a `typed_response_promise` to respond to a request later on. /// `make_response_promise<typed_response_promise<int, int>>()` /// is equivalent to `make_response_promise<int, int>()`. template <class... Ts> typename detail::make_response_promise_helper<Ts...>::type make_response_promise() { auto& ptr = current_element_; if (!ptr) return {}; auto& mid = ptr->mid; if (mid.is_answered()) return {}; return {this->ctrl(), *ptr}; } /// Creates a `response_promise` to respond to a request later on. inline response_promise make_response_promise() { return make_response_promise<response_promise>(); } /// Creates a `typed_response_promise` and responds immediately. /// Return type is deduced from arguments. /// Return value is implicitly convertible to untyped response promise. template <class... Ts, class R = typename detail::make_response_promise_helper< typename std::decay<Ts>::type... >::type> R response(Ts&&... xs) { auto promise = make_response_promise<R>(); promise.deliver(std::forward<Ts>(xs)...); return promise; } const char* name() const override; /// Serializes the state of this actor to `sink`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error save_state(serializer& sink, unsigned int version); /// Deserializes the state of this actor from `source`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error load_state(deserializer& source, unsigned int version); /// Returns the currently defined fail state. If this reason is not /// `none` then the actor will terminate with this error after executing /// the current message handler. inline const error& fail_state() const { return fail_state_; } // -- here be dragons: end of public interface ------------------------------- /// @cond PRIVATE template <class ActorHandle> inline ActorHandle eval_opts(spawn_options opts, ActorHandle res) { if (has_monitor_flag(opts)) monitor(res->address()); if (has_link_flag(opts)) link_to(res->address()); return res; } // returns 0 if last_dequeued() is an asynchronous or sync request message, // a response id generated from the request id otherwise inline message_id get_response_id() const { auto mid = current_element_->mid; return (mid.is_request()) ? mid.response_id() : message_id(); } template <message_priority P = message_priority::normal, class Handle = actor, class... Ts> typename response_type< typename Handle::signatures, detail::implicit_conversions_t<typename std::decay<Ts>::type>... >::delegated_type delegate(const Handle& dest, Ts&&... xs) { static_assert(sizeof...(Ts) > 0, "nothing to delegate"); using token = detail::type_list< typename detail::implicit_conversions< typename std::decay<Ts>::type >::type...>; static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid, "receiver does not accept given message"); auto mid = current_element_->mid; current_element_->mid = P == message_priority::high ? mid.with_high_priority() : mid.with_normal_priority(); dest->enqueue(make_mailbox_element(std::move(current_element_->sender), mid, std::move(current_element_->stages), std::forward<Ts>(xs)...), context()); return {}; } virtual void initialize(); bool cleanup(error&& fail_state, execution_unit* host) override; message_id new_request_id(message_priority mp); protected: // -- member variables ------------------------------------------------------- // identifies the execution unit this actor is currently executed by execution_unit* context_; // pointer to the sender of the currently processed message mailbox_element* current_element_; // last used request ID message_id last_request_id_; /// Factory function for returning initial behavior in function-based actors. std::function<behavior (local_actor*)> initial_behavior_fac_; }; } // namespace caf <commit_msg>Add convenience getter for retrieving the config<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <cstdint> #include <exception> #include <functional> #include <type_traits> #include <utility> #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/actor_config.hpp" #include "caf/actor_system.hpp" #include "caf/behavior.hpp" #include "caf/check_typed_input.hpp" #include "caf/delegated.hpp" #include "caf/duration.hpp" #include "caf/error.hpp" #include "caf/fwd.hpp" #include "caf/message.hpp" #include "caf/message_handler.hpp" #include "caf/message_id.hpp" #include "caf/message_priority.hpp" #include "caf/monitorable_actor.hpp" #include "caf/response_promise.hpp" #include "caf/response_type.hpp" #include "caf/resumable.hpp" #include "caf/spawn_options.hpp" #include "caf/typed_actor.hpp" #include "caf/typed_response_promise.hpp" #include "caf/detail/typed_actor_util.hpp" namespace caf { /// Base class for actors running on this node, either /// living in an own thread or cooperatively scheduled. class local_actor : public monitorable_actor { public: // -- member types ----------------------------------------------------------- /// Defines a monotonic clock suitable for measuring intervals. using clock_type = std::chrono::steady_clock; // -- constructors, destructors, and assignment operators -------------------- local_actor(actor_config& cfg); ~local_actor() override; void on_destroy() override; // -- pure virtual modifiers ------------------------------------------------- virtual void launch(execution_unit* eu, bool lazy, bool hide) = 0; // -- time ------------------------------------------------------------------- /// Returns the current time. clock_type::time_point now() const noexcept; /// Returns the difference between `t0` and `t1`, allowing the clock to /// return any arbitrary value depending on the measurement that took place. clock_type::duration difference(atom_value measurement, clock_type::time_point t0, clock_type::time_point t1); // -- timeout management ----------------------------------------------------- /// Requests a new timeout for `mid`. /// @pre `mid.valid()` void request_response_timeout(const duration& d, message_id mid); // -- spawn functions -------------------------------------------------------- template <class T, spawn_options Os = no_spawn_options, class... Ts> infer_handle_from_class_t<T> spawn(Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<T, make_unbound(Os)>( cfg, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options> infer_handle_from_state_t<T> spawn() { using impl = composable_behavior_based_actor<T>; actor_config cfg{context()}; return eval_opts(Os, system().spawn_class<impl, make_unbound(Os)>(cfg)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> infer_handle_from_fun_t<F> spawn(F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_functor<make_unbound(Os)>( cfg, fun, std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class Groups, class... Ts> actor spawn_in_groups(const Groups& gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, Ts&&... xs) { actor_config cfg{context()}; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, gs.begin(), gs.end(), std::forward<Ts>(xs)...)); } template <class T, spawn_options Os = no_spawn_options, class... Ts> actor spawn_in_group(const group& grp, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_class_in_groups<T, make_unbound(Os)>( cfg, first, first + 1, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class Groups, class F, class... Ts> actor spawn_in_groups(const Groups& gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_groups(std::initializer_list<group> gs, F fun, Ts&&... xs) { actor_config cfg{context()}; return eval_opts( Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, gs.begin(), gs.end(), fun, std::forward<Ts>(xs)...)); } template <spawn_options Os = no_spawn_options, class F, class... Ts> actor spawn_in_group(const group& grp, F fun, Ts&&... xs) { actor_config cfg{context()}; auto first = &grp; return eval_opts(Os, system().spawn_fun_in_groups<make_unbound(Os)>( cfg, first, first + 1, fun, std::forward<Ts>(xs)...)); } // -- sending asynchronous messages ------------------------------------------ /// Sends an exit message to `dest`. void send_exit(const actor_addr& whom, error reason); void send_exit(const strong_actor_ptr& dest, error reason); /// Sends an exit message to `dest`. template <class ActorHandle> void send_exit(const ActorHandle& dest, error reason) { dest->eq_impl(make_message_id(), ctrl(), context(), exit_msg{address(), std::move(reason)}); } // -- miscellaneous actor operations ----------------------------------------- /// Returns the execution unit currently used by this actor. inline execution_unit* context() const { return context_; } /// Sets the execution unit for this actor. inline void context(execution_unit* x) { context_ = x; } /// Returns the hosting actor system. inline actor_system& system() const { CAF_ASSERT(context_); return context_->system(); } /// Returns the config of the hosting actor system. inline const actor_system_config& config() const { return system().config(); } /// Returns the clock of the actor system. inline actor_clock& clock() const { return home_system().clock(); } /// @cond PRIVATE void monitor(abstract_actor* ptr); /// @endcond /// Returns a pointer to the sender of the current message. /// @pre `current_mailbox_element() != nullptr` inline strong_actor_ptr& current_sender() { CAF_ASSERT(current_element_); return current_element_->sender; } /// Returns the ID of the current message. inline message_id current_message_id() { CAF_ASSERT(current_element_); return current_element_->mid; } /// Returns the ID of the current message and marks the ID stored in the /// current mailbox element as answered. inline message_id take_current_message_id() { CAF_ASSERT(current_element_); auto result = current_element_->mid; current_element_->mid.mark_as_answered(); return result; } /// Marks the current message ID as answered. inline void drop_current_message_id() { CAF_ASSERT(current_element_); current_element_->mid.mark_as_answered(); } /// Returns a pointer to the next stage from the forwarding path of the /// current message or `nullptr` if the path is empty. inline strong_actor_ptr current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) stages.back(); return nullptr; } /// Returns a pointer to the next stage from the forwarding path of the /// current message and removes it from the path. Returns `nullptr` if the /// path is empty. inline strong_actor_ptr take_current_next_stage() { CAF_ASSERT(current_element_); auto& stages = current_element_->stages; if (!stages.empty()) { auto result = stages.back(); stages.pop_back(); return result; } return nullptr; } /// Returns the forwarding stack from the current mailbox element. const mailbox_element::forwarding_stack& current_forwarding_stack() { CAF_ASSERT(current_element_); return current_element_->stages; } /// Moves the forwarding stack from the current mailbox element. mailbox_element::forwarding_stack take_current_forwarding_stack() { CAF_ASSERT(current_element_); return std::move(current_element_->stages); } /// Returns a pointer to the currently processed mailbox element. inline mailbox_element* current_mailbox_element() { return current_element_; } /// Returns a pointer to the currently processed mailbox element. /// @private inline void current_mailbox_element(mailbox_element* ptr) { current_element_ = ptr; } /// Adds a unidirectional `monitor` to `whom`. /// @note Each call to `monitor` creates a new, independent monitor. template <class Handle> void monitor(const Handle& whom) { monitor(actor_cast<abstract_actor*>(whom)); } /// Removes a monitor from `whom`. void demonitor(const actor_addr& whom); /// Removes a monitor from `whom`. inline void demonitor(const actor& whom) { demonitor(whom.address()); } /// Can be overridden to perform cleanup code after an actor /// finished execution. virtual void on_exit(); /// Creates a `typed_response_promise` to respond to a request later on. /// `make_response_promise<typed_response_promise<int, int>>()` /// is equivalent to `make_response_promise<int, int>()`. template <class... Ts> typename detail::make_response_promise_helper<Ts...>::type make_response_promise() { auto& ptr = current_element_; if (!ptr) return {}; auto& mid = ptr->mid; if (mid.is_answered()) return {}; return {this->ctrl(), *ptr}; } /// Creates a `response_promise` to respond to a request later on. inline response_promise make_response_promise() { return make_response_promise<response_promise>(); } /// Creates a `typed_response_promise` and responds immediately. /// Return type is deduced from arguments. /// Return value is implicitly convertible to untyped response promise. template <class... Ts, class R = typename detail::make_response_promise_helper< typename std::decay<Ts>::type... >::type> R response(Ts&&... xs) { auto promise = make_response_promise<R>(); promise.deliver(std::forward<Ts>(xs)...); return promise; } const char* name() const override; /// Serializes the state of this actor to `sink`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error save_state(serializer& sink, unsigned int version); /// Deserializes the state of this actor from `source`. This function is /// only called if this actor has set the `is_serializable` flag. /// The default implementation throws a `std::logic_error`. virtual error load_state(deserializer& source, unsigned int version); /// Returns the currently defined fail state. If this reason is not /// `none` then the actor will terminate with this error after executing /// the current message handler. inline const error& fail_state() const { return fail_state_; } // -- here be dragons: end of public interface ------------------------------- /// @cond PRIVATE template <class ActorHandle> inline ActorHandle eval_opts(spawn_options opts, ActorHandle res) { if (has_monitor_flag(opts)) monitor(res->address()); if (has_link_flag(opts)) link_to(res->address()); return res; } // returns 0 if last_dequeued() is an asynchronous or sync request message, // a response id generated from the request id otherwise inline message_id get_response_id() const { auto mid = current_element_->mid; return (mid.is_request()) ? mid.response_id() : message_id(); } template <message_priority P = message_priority::normal, class Handle = actor, class... Ts> typename response_type< typename Handle::signatures, detail::implicit_conversions_t<typename std::decay<Ts>::type>... >::delegated_type delegate(const Handle& dest, Ts&&... xs) { static_assert(sizeof...(Ts) > 0, "nothing to delegate"); using token = detail::type_list< typename detail::implicit_conversions< typename std::decay<Ts>::type >::type...>; static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid, "receiver does not accept given message"); auto mid = current_element_->mid; current_element_->mid = P == message_priority::high ? mid.with_high_priority() : mid.with_normal_priority(); dest->enqueue(make_mailbox_element(std::move(current_element_->sender), mid, std::move(current_element_->stages), std::forward<Ts>(xs)...), context()); return {}; } virtual void initialize(); bool cleanup(error&& fail_state, execution_unit* host) override; message_id new_request_id(message_priority mp); protected: // -- member variables ------------------------------------------------------- // identifies the execution unit this actor is currently executed by execution_unit* context_; // pointer to the sender of the currently processed message mailbox_element* current_element_; // last used request ID message_id last_request_id_; /// Factory function for returning initial behavior in function-based actors. std::function<behavior (local_actor*)> initial_behavior_fac_; }; } // namespace caf <|endoftext|>
<commit_before>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiAnalyticsObject.h" #include "NativeMapViewObject.h" #include <QSettings> #include <bb/cascades/Application> #include <bb/device/HardwareInfo> #include "TiGenericFunctionObject.h" #include <QUuid> #include <bps/bps.h> #include <bps/netstatus.h> /** A BlackBerry analytics event payload has the follow values seq - increment counter for each even sent during the app life cycle ver - used by server must be > 2 id - a uuid that is unique to each event sid - a unique value that identifies the entire life-cycle of the app mid - mobile device id, every BlackBerry device has a unique id aguid - the id of the application, generated when the application is first created event - the name of the event, ti.enroll (app first runs), ti.start, ti.end, ti.foreground, ti.background, featureEvent type - the name of the event, ti.enroll (app first runs), ti.start, ti.end, ti.foreground, ti.background, featureEvent ts - UTC time stamp of event platform - always blackberry deploytype - development or production app_version - the version of the application as it appears in the tiapp.xml file feature_data - when users call Ti.Analytics.featureEvent(name, data) feature_data holds the json data */ // Application properties defined at compile in tiapp.xml // can be read using this settings instance. It is read only. static QSettings defaultSettings("app/native/assets/app_properties.ini", QSettings::IniFormat); // Singleton TiAnalyticsObject::TiAnalyticsObject() : TiProxy("Analytics"), appStart(true), sequence_(1) { objectFactory_ = NULL; } // Singleton TiAnalyticsObject::TiAnalyticsObject(NativeObjectFactory* objectFactory) : TiProxy("Analytics"), appStart(true), sequence_(1) { objectFactory_ = objectFactory; // if analytics is false just return bool analytics = defaultSettings.value("analytics").toBool(); if (analytics == true) { // get unique application id QString aguid = defaultSettings.value("aguid").toString(); aguid_ = aguid.toLocal8Bit(); // get unique mobile device id bb::device::HardwareInfo hdi; QString mid = hdi.pin(); mid_ = mid.toLocal8Bit(); // generate the session id QString sid = QUuid::createUuid().toString(); sid.replace("{", ""); sid.replace("}", ""); sid_ = sid.toLocal8Bit(); // get deploy type if development or production QString deployType = defaultSettings.value("deploytype").toString(); deployType_ = deployType.toLocal8Bit(); // application version QString appVersion = defaultSettings.value("version").toString(); appVersion_ = appVersion.toLocal8Bit(); QUrl analyticsSite("https://api.appcelerator.net/p/v3/mobile-track/" + aguid); request_.setUrl(analyticsSite); // hook the manualExit Cascades app callback bb::cascades::Application::instance()->setAutoExit(false); // async callbacks to notify application of HTTP events eventHandler_ = new TiAnalyticsHandler(this, ""); QObject::connect(&networkAccessManager_, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), eventHandler_, SLOT(errors(QNetworkReply*))); // Hook application life cycle events QObject::connect(bb::cascades::Application::instance(), SIGNAL(thumbnail()), eventHandler_, SLOT(thumbnail())); QObject::connect(bb::cascades::Application::instance(), SIGNAL(fullscreen()), eventHandler_, SLOT(fullscreen())); QObject::connect(bb::cascades::Application::instance(), SIGNAL(manualExit()), eventHandler_, SLOT(manualExit())); if (createAnalyticsDatabase()) { addAnalyticsEvent("ti.enroll"); } // set up timer and every 30 seconds send out analytics events if any are pending // usually because of unavailable network access TiAnalyticsHandler* eventHandler = new TiAnalyticsHandler(this, ""); timer_ = new QTimer(eventHandler); QObject::connect(timer_, SIGNAL(timeout()), eventHandler, SLOT(sendPendingRequests())); timer_->start(30000); } } TiAnalyticsObject::~TiAnalyticsObject() { } void TiAnalyticsObject::addObjectToParent(TiObject* parent, NativeObjectFactory* objectFactory) { TiAnalyticsObject* obj = new TiAnalyticsObject(objectFactory); parent->addMember(obj); obj->release(); } void TiAnalyticsObject::onCreateStaticMembers() { TiProxy::onCreateStaticMembers(); TiGenericFunctionObject::addGenericFunctionToParent(this, "featureEvent", this, _featureEvent); } bool TiAnalyticsObject::createAnalyticsDatabase() { sqlite3_stmt* stmt; int rc; bool dbCreate = false; rc = sqlite3_open_v2("app/native/analytics.db", &db, SQLITE_OPEN_READWRITE, NULL); if(rc){ //TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); // TODO check errmsg and make sure that it's caused by no db, create if that is the error dbCreate = true; rc = sqlite3_open_v2("app/native/analytics.db", &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL); if(rc){ TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); return(false); } // create the events table string cmd = "CREATE TABLE IF NOT EXISTS events (uid TEXT, event TEXT)"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); return(false); } if (sqlite3_step(stmt) != SQLITE_DONE) { TiLogger::getInstance().log("\nCould not step (execute) stmt.\n"); return (false); } sqlite3_reset(stmt); } return dbCreate ; } void TiAnalyticsObject::addAnalyticsEvent(std::string const& name, std::string const& data, std::string const& typeArg) { sqlite3_stmt* stmt; int rc; string type; string cmd = "INSERT INTO events VALUES (?, ?)"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); } // generate the event time stamp QDateTime utc = QDateTime::currentDateTime(); QString displayDate = utc.toString("yyyy-d-mTh:m:s.z"); QByteArray ts = displayDate.toLocal8Bit(); // generate the uid QString uid = QUuid::createUuid().toString(); uid.replace("{", ""); uid.replace("}", ""); QByteArray id = uid.toLocal8Bit(); if (name.find("app.feature") == std::string::npos) { type = name; } else { type = typeArg; } // TODO guard against 1024 overrun char json[1024]; sprintf(json, "[{\"seq\":%d,\"ver\":\"2\",\"id\":\"%s\",\"sid\":\"%s\",\"mid\":\"%s\",\"aguid\":\"%s\",\"type\":\"%s\",\"event\":\"%s\",\"ts\":\"%s\",\"data\":{\"platform\":\"blackberry\",\"deploytype\":\"%s\",\"app_version\":\"%s\",\"feature_data\":\"%s\"}}]", sequence_, id.data(), sid_.data(), mid_.data(), aguid_.data(), name.c_str(), type.c_str(), ts.data(), deployType_.data(), appVersion_.data(), data.c_str()); sqlite3_bind_text(stmt, 1, id.data(), strlen(id.data()), 0); sqlite3_bind_text(stmt, 2, json, strlen(json), 0); if (sqlite3_step(stmt) != SQLITE_DONE) { TiLogger::getInstance().log("\nCould not step (execute) stmt.\n"); } sequence_++; sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); if (name == "ti.end" ) { bb::cascades::Application::instance()->exit(0); } else { sendPendingAnalyticsEvents(); } } void TiAnalyticsObject::sendPendingAnalyticsEvents() { sqlite3_stmt* stmt; int rc; string cmd = "SELECT * FROM events"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); } while (true) { int s; s = sqlite3_step (stmt); if (s == SQLITE_ROW) { const unsigned char* uid; const unsigned char* json; uid = sqlite3_column_text (stmt, 0); json = sqlite3_column_text (stmt, 1); bool is_available = true; netstatus_get_availability(&is_available); if (is_available) { // do not send an http post if a reply is pending std::string id = std::string((const char*)uid, strlen((const char*)uid)); if (pendingHttpReplies.find(id) == pendingHttpReplies.end()) { TiAnalyticsHandler* requestHandler = new TiAnalyticsHandler(this, (const char*)uid); pendingHttpReplies[id] = requestHandler; bool log = defaultSettings.value("analytics-log").toBool(); if (log) { TiLogger::getInstance().log("Sending Analytic Event: "); TiLogger::getInstance().log((const char*)json); } // send HTTP POST Asynchronously QByteArray postDataSize = QByteArray::number(strlen((const char*)json)); request_.setRawHeader("Content-Length", postDataSize); QNetworkReply* reply = networkAccessManager_.post(request_, (const char*)json); QObject::connect(reply, SIGNAL(finished()), requestHandler, SLOT(finished())); } } } else if (s == SQLITE_DONE) { break; } else { break; } } sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); } Handle<Value> TiAnalyticsObject::_featureEvent(void* userContext, TiObject*, const Arguments& args) { TiAnalyticsObject* obj = (TiAnalyticsObject*) userContext; string type = TiObject::getSTDStringFromValue(args[0]); string data = TiObject::getSTDStringFromValue(args[1]); obj->addAnalyticsEvent("app.feature", data, type); return Undefined(); } TiAnalyticsHandler::TiAnalyticsHandler(TiAnalyticsObject* tiAnalyticsObject, string uid) { tiAnalyticsObject_ = tiAnalyticsObject; uid_ = uid; } TiAnalyticsHandler::~TiAnalyticsHandler() { } void TiAnalyticsHandler::finished() { sqlite3_stmt* stmt; int rc; string cmd = "DELETE FROM events WHERE uid=?"; rc = sqlite3_prepare_v2(tiAnalyticsObject_->db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(tiAnalyticsObject_->db)); sqlite3_close(tiAnalyticsObject_->db); } sqlite3_bind_text(stmt, 1, uid_.c_str(), strlen(uid_.c_str()), 0); int stepResult = sqlite3_step(stmt); if (stepResult == SQLITE_DONE) { bool log = defaultSettings.value("analytics-log").toBool(); if (log) { TiLogger::getInstance().log("Clearing Analytic Event from DB for ID: "); TiLogger::getInstance().log(uid_.c_str()); } } sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); // remove the pending http reply tiAnalyticsObject_->pendingHttpReplies.erase(uid_); this->deleteLater(); } void TiAnalyticsHandler::errors(QNetworkReply* reply) { TiLogger::getInstance().log("\nHTTP error while sending analytic event.\n"); this->deleteLater(); } void TiAnalyticsHandler::sendPendingRequests() { tiAnalyticsObject_->sendPendingAnalyticsEvents(); } void TiAnalyticsHandler::thumbnail() { tiAnalyticsObject_->addAnalyticsEvent("ti.background"); } void TiAnalyticsHandler::fullscreen() { if (tiAnalyticsObject_->appStart == true) { tiAnalyticsObject_->addAnalyticsEvent("ti.start"); tiAnalyticsObject_->appStart = false; } else { tiAnalyticsObject_->addAnalyticsEvent("ti.foreground"); } } void TiAnalyticsHandler::manualExit() { tiAnalyticsObject_->addAnalyticsEvent("ti.end"); } <commit_msg>fixed analytics issue with bad date format<commit_after>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiAnalyticsObject.h" #include "NativeMapViewObject.h" #include <QSettings> #include <bb/cascades/Application> #include <bb/device/HardwareInfo> #include "TiGenericFunctionObject.h" #include <QUuid> #include <bps/bps.h> #include <bps/netstatus.h> /** A BlackBerry analytics event payload has the follow values seq - increment counter for each even sent during the app life cycle ver - used by server must be > 2 id - a uuid that is unique to each event sid - a unique value that identifies the entire life-cycle of the app mid - mobile device id, every BlackBerry device has a unique id aguid - the id of the application, generated when the application is first created event - the name of the event, ti.enroll (app first runs), ti.start, ti.end, ti.foreground, ti.background, featureEvent type - the name of the event, ti.enroll (app first runs), ti.start, ti.end, ti.foreground, ti.background, featureEvent ts - UTC time stamp of event platform - always blackberry deploytype - development or production app_version - the version of the application as it appears in the tiapp.xml file feature_data - when users call Ti.Analytics.featureEvent(name, data) feature_data holds the json data */ // Application properties defined at compile in tiapp.xml // can be read using this settings instance. It is read only. static QSettings defaultSettings("app/native/assets/app_properties.ini", QSettings::IniFormat); // Singleton TiAnalyticsObject::TiAnalyticsObject() : TiProxy("Analytics"), appStart(true), sequence_(1) { objectFactory_ = NULL; } // Singleton TiAnalyticsObject::TiAnalyticsObject(NativeObjectFactory* objectFactory) : TiProxy("Analytics"), appStart(true), sequence_(1) { objectFactory_ = objectFactory; // if analytics is false just return bool analytics = defaultSettings.value("analytics").toBool(); if (analytics == true) { // get unique application id QString aguid = defaultSettings.value("aguid").toString(); aguid_ = aguid.toLocal8Bit(); // get unique mobile device id bb::device::HardwareInfo hdi; QString mid = hdi.pin(); mid_ = mid.toLocal8Bit(); // generate the session id QString sid = QUuid::createUuid().toString(); sid.replace("{", ""); sid.replace("}", ""); sid_ = sid.toLocal8Bit(); // get deploy type if development or production QString deployType = defaultSettings.value("deploytype").toString(); deployType_ = deployType.toLocal8Bit(); // application version QString appVersion = defaultSettings.value("version").toString(); appVersion_ = appVersion.toLocal8Bit(); QUrl analyticsSite("https://api.appcelerator.net/p/v3/mobile-track/" + aguid); request_.setUrl(analyticsSite); // hook the manualExit Cascades app callback bb::cascades::Application::instance()->setAutoExit(false); // async callbacks to notify application of HTTP events eventHandler_ = new TiAnalyticsHandler(this, ""); QObject::connect(&networkAccessManager_, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), eventHandler_, SLOT(errors(QNetworkReply*))); // Hook application life cycle events QObject::connect(bb::cascades::Application::instance(), SIGNAL(thumbnail()), eventHandler_, SLOT(thumbnail())); QObject::connect(bb::cascades::Application::instance(), SIGNAL(fullscreen()), eventHandler_, SLOT(fullscreen())); QObject::connect(bb::cascades::Application::instance(), SIGNAL(manualExit()), eventHandler_, SLOT(manualExit())); if (createAnalyticsDatabase()) { addAnalyticsEvent("ti.enroll"); } // set up timer and every 30 seconds send out analytics events if any are pending // usually because of unavailable network access TiAnalyticsHandler* eventHandler = new TiAnalyticsHandler(this, ""); timer_ = new QTimer(eventHandler); QObject::connect(timer_, SIGNAL(timeout()), eventHandler, SLOT(sendPendingRequests())); timer_->start(30000); } } TiAnalyticsObject::~TiAnalyticsObject() { } void TiAnalyticsObject::addObjectToParent(TiObject* parent, NativeObjectFactory* objectFactory) { TiAnalyticsObject* obj = new TiAnalyticsObject(objectFactory); parent->addMember(obj); obj->release(); } void TiAnalyticsObject::onCreateStaticMembers() { TiProxy::onCreateStaticMembers(); TiGenericFunctionObject::addGenericFunctionToParent(this, "featureEvent", this, _featureEvent); } bool TiAnalyticsObject::createAnalyticsDatabase() { sqlite3_stmt* stmt; int rc; bool dbCreate = false; rc = sqlite3_open_v2("app/native/analytics.db", &db, SQLITE_OPEN_READWRITE, NULL); if(rc){ //TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); // TODO check errmsg and make sure that it's caused by no db, create if that is the error dbCreate = true; rc = sqlite3_open_v2("app/native/analytics.db", &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL); if(rc){ TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); return(false); } // create the events table string cmd = "CREATE TABLE IF NOT EXISTS events (uid TEXT, event TEXT)"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); return(false); } if (sqlite3_step(stmt) != SQLITE_DONE) { TiLogger::getInstance().log("\nCould not step (execute) stmt.\n"); return (false); } sqlite3_reset(stmt); } return dbCreate ; } void TiAnalyticsObject::addAnalyticsEvent(std::string const& name, std::string const& data, std::string const& typeArg) { sqlite3_stmt* stmt; int rc; string type; string cmd = "INSERT INTO events VALUES (?, ?)"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); } // generate the event time stamp QDateTime utc = QDateTime::currentDateTime(); QString displayDate = utc.toString("yyyy-MM-ddThh:mm:ss.z"); QByteArray ts = displayDate.toLocal8Bit(); // generate the uid QString uid = QUuid::createUuid().toString(); uid.replace("{", ""); uid.replace("}", ""); QByteArray id = uid.toLocal8Bit(); if (name.find("app.feature") == std::string::npos) { type = name; } else { type = typeArg; } // TODO guard against 1024 overrun char json[1024]; sprintf(json, "[{\"seq\":%d,\"ver\":\"2\",\"id\":\"%s\",\"sid\":\"%s\",\"mid\":\"%s\",\"aguid\":\"%s\",\"type\":\"%s\",\"event\":\"%s\",\"ts\":\"%s\",\"data\":{\"platform\":\"blackberry\",\"deploytype\":\"%s\",\"app_version\":\"%s\",\"feature_data\":\"%s\"}}]", sequence_, id.data(), sid_.data(), mid_.data(), aguid_.data(), name.c_str(), type.c_str(), ts.data(), deployType_.data(), appVersion_.data(), data.c_str()); sqlite3_bind_text(stmt, 1, id.data(), strlen(id.data()), 0); sqlite3_bind_text(stmt, 2, json, strlen(json), 0); if (sqlite3_step(stmt) != SQLITE_DONE) { TiLogger::getInstance().log("\nCould not step (execute) stmt.\n"); } sequence_++; sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); if (name == "ti.end" ) { bb::cascades::Application::instance()->exit(0); } else { sendPendingAnalyticsEvents(); } } void TiAnalyticsObject::sendPendingAnalyticsEvents() { sqlite3_stmt* stmt; int rc; string cmd = "SELECT * FROM events"; rc = sqlite3_prepare_v2(db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(db)); sqlite3_close(db); } while (true) { int s; s = sqlite3_step (stmt); if (s == SQLITE_ROW) { const unsigned char* uid; const unsigned char* json; uid = sqlite3_column_text (stmt, 0); json = sqlite3_column_text (stmt, 1); bool is_available = true; netstatus_get_availability(&is_available); if (is_available) { // do not send an http post if a reply is pending std::string id = std::string((const char*)uid, strlen((const char*)uid)); if (pendingHttpReplies.find(id) == pendingHttpReplies.end()) { TiAnalyticsHandler* requestHandler = new TiAnalyticsHandler(this, (const char*)uid); pendingHttpReplies[id] = requestHandler; bool log = defaultSettings.value("analytics-log").toBool(); if (log) { TiLogger::getInstance().log("Sending Analytic Event: "); TiLogger::getInstance().log((const char*)json); } // send HTTP POST Asynchronously QByteArray postDataSize = QByteArray::number(strlen((const char*)json)); request_.setRawHeader("Content-Length", postDataSize); QNetworkReply* reply = networkAccessManager_.post(request_, (const char*)json); QObject::connect(reply, SIGNAL(finished()), requestHandler, SLOT(finished())); } } } else if (s == SQLITE_DONE) { break; } else { break; } } sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); } Handle<Value> TiAnalyticsObject::_featureEvent(void* userContext, TiObject*, const Arguments& args) { TiAnalyticsObject* obj = (TiAnalyticsObject*) userContext; string type = TiObject::getSTDStringFromValue(args[0]); string data = TiObject::getSTDStringFromValue(args[1]); obj->addAnalyticsEvent("app.feature", data, type); return Undefined(); } TiAnalyticsHandler::TiAnalyticsHandler(TiAnalyticsObject* tiAnalyticsObject, string uid) { tiAnalyticsObject_ = tiAnalyticsObject; uid_ = uid; } TiAnalyticsHandler::~TiAnalyticsHandler() { } void TiAnalyticsHandler::finished() { sqlite3_stmt* stmt; int rc; string cmd = "DELETE FROM events WHERE uid=?"; rc = sqlite3_prepare_v2(tiAnalyticsObject_->db, cmd.c_str(), strlen(cmd.c_str()) + 1, &stmt, NULL); if( rc ) { TiLogger::getInstance().log(sqlite3_errmsg(tiAnalyticsObject_->db)); sqlite3_close(tiAnalyticsObject_->db); } sqlite3_bind_text(stmt, 1, uid_.c_str(), strlen(uid_.c_str()), 0); int stepResult = sqlite3_step(stmt); if (stepResult == SQLITE_DONE) { bool log = defaultSettings.value("analytics-log").toBool(); if (log) { TiLogger::getInstance().log("Clearing Analytic Event from DB for ID: "); TiLogger::getInstance().log(uid_.c_str()); } } sqlite3_reset(stmt); sqlite3_clear_bindings(stmt); // remove the pending http reply tiAnalyticsObject_->pendingHttpReplies.erase(uid_); this->deleteLater(); } void TiAnalyticsHandler::errors(QNetworkReply* reply) { TiLogger::getInstance().log("\nHTTP error while sending analytic event.\n"); this->deleteLater(); } void TiAnalyticsHandler::sendPendingRequests() { tiAnalyticsObject_->sendPendingAnalyticsEvents(); } void TiAnalyticsHandler::thumbnail() { tiAnalyticsObject_->addAnalyticsEvent("ti.background"); } void TiAnalyticsHandler::fullscreen() { if (tiAnalyticsObject_->appStart == true) { tiAnalyticsObject_->addAnalyticsEvent("ti.start"); tiAnalyticsObject_->appStart = false; } else { tiAnalyticsObject_->addAnalyticsEvent("ti.foreground"); } } void TiAnalyticsHandler::manualExit() { tiAnalyticsObject_->addAnalyticsEvent("ti.end"); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "filter.h" #include "level_parser.h" typedef bool filter_apply_cb (void *context, const log4j_event<> *event); typedef void filter_destroy_cb (void *context); struct _filter { void *context; filter_apply_cb *apply; filter_destroy_cb *destroy; }; void filter_destroy (filter *self) { self->destroy (self->context); free (self); } bool filter_apply (const filter *self, const log4j_event<> *event) { return self->apply (self->context, event); } static bool _filter_equals (const filter *x, const filter *y) { return x->context == y->context && x->apply == y->apply && x->destroy == y->destroy; } #pragma region Level lilter struct _filter_level_context { int32_t min; int32_t max; }; static void _filter_level_destroy (void *context); static bool _filter_level_apply (void *context, const log4j_event<> *event); void filter_init_level_i (filter **self, int32_t min, int32_t max) { auto context = (_filter_level_context *) malloc (sizeof (_filter_level_context)); *context = {min, max}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_level_apply, &_filter_level_destroy}; *self = result; } void filter_init_level_c (filter **self, const char *min, const char *max) { auto min_i = level_parser<char>::instance.get_value (min); auto max_i = level_parser<char>::instance.get_value (max); filter_init_level_i (self, min_i, max_i); } static void _filter_level_destroy (void *context) { auto context_l = (_filter_level_context *) context; *context_l = {0, 0}; free (context_l); } static bool _filter_level_apply (void *context, const log4j_event<> *event) { auto context_l = (_filter_level_context *) context; auto val_string = event->get_level (); int32_t value = level_parser<char>::instance.get_value (val_string.value (), val_string.size ()); return context_l->min <= value && value <= context_l->max; } #pragma endregion #pragma region Logger filter struct _filter_logger_context { char *logger; size_t logger_size; }; static void _filter_logger_destroy (void *context); static bool _filter_logger_apply (void *context, const log4j_event<> *event); void filter_init_logger_fs (filter **self, const char *logger, const size_t logger_size) { auto context = (_filter_logger_context *) malloc (sizeof (_filter_logger_context)); // Reminder: logger_size must be multiplied by sizeof (Ch) if this code is reused for non-char // strings (e.g. wchar strings). auto context_logger = (char *) malloc (logger_size); memcpy (context_logger, logger, logger_size); *context = {context_logger, logger_size}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_logger_apply, &_filter_logger_destroy}; *self = result; } void filter_init_logger_nt (filter **self, const char *logger) { auto logger_size = strlen (logger); filter_init_logger_fs (self, logger, logger_size); } static void _filter_logger_destroy (void *context) { auto context_l = (_filter_logger_context *) context; free (context_l->logger); context_l->logger = nullptr; context_l->logger_size = 0; free (context); } static bool _filter_logger_apply (void *context, const log4j_event<> *event) { auto context_l = (_filter_logger_context *) context; auto value = event->get_logger (); auto logger = context_l->logger; auto logger_size = context_l->logger_size; return value.size () >= logger_size && _strnicmp (value.value (), logger, logger_size) == 0; } #pragma endregion #pragma region Message filter struct _filter_message_context { char *message; size_t message_size; }; static void _filter_message_destroy (void *context); static bool _filter_message_apply (void *context, const log4j_event<> *event); void filter_init_message_fs (filter **self, const char *message, const size_t message_size) { auto context = (_filter_message_context *) malloc (sizeof (_filter_message_context)); // Reminder: message_size must be multiplied by sizeof (Ch) if this code is reused for non-char // strings (e.g. wchar strings). auto context_message = (char *) malloc (message_size); memcpy (context_message, message, message_size); *context = {context_message, message_size}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_message_apply, &_filter_message_destroy}; *self = result; } void filter_init_message_nt (filter **self, const char *message) { auto message_size = strlen (message); filter_init_message_fs (self, message, message_size); } static void _filter_message_destroy (void *context) { auto context_m = (_filter_message_context *) context; free (context_m->message); context_m->message = nullptr; context_m->message_size = 0; free (context); } static bool _filter_message_apply (void *context, const log4j_event<> *event) { auto context_m = (_filter_message_context *) context; if (context_m->message_size == 0) { return true; } auto message = event->get_message (); size_t value_size = message.size (); if (value_size < context_m->message_size) { return false; } const char *value = message.value (); const char message_head = *context_m->message; const char *message_tail = context_m->message + 1; const size_t message_tail_size = context_m->message_size - 1; do { char sc; do { sc = *value; ++value; --value_size; if (value_size < message_tail_size) { return false; } } while (sc != message_head); } while (strncmp (value, message_tail, message_tail_size) != 0); return true; } #pragma endregion #pragma region Timestamp filter struct _filter_timestamp_context { int64_t min; int64_t max; }; static void _filter_timestamp_destroy (void *context); static bool _filter_timestamp_apply (void *context, const log4j_event<> *event); void filter_init_timestamp (filter **self, int64_t min, int64_t max) { auto context = (_filter_timestamp_context *) malloc (sizeof (_filter_timestamp_context)); *context = {min, max}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_timestamp_apply, &_filter_timestamp_destroy}; *self = result; } static void _filter_timestamp_destroy (void *context) { auto context_t = (_filter_timestamp_context *) context; *context_t = {0, 0}; free (context_t); } static bool _filter_timestamp_apply (void *context, const log4j_event<> *event) { auto context_t = (_filter_timestamp_context *) context; auto value = event->get_time (); return context_t->min <= value && value <= context_t->max; } #pragma endregion // Composite filters struct _filter_entry { filter *filter; _filter_entry *next; }; static void _filter_list_destroy (_filter_entry *head) { if (head->next) { _filter_list_destroy (head->next); } *head = {nullptr, nullptr}; free (head); } static _filter_entry *_filter_list_add (_filter_entry *head, filter *filter) { auto result = (_filter_entry *) malloc (sizeof (_filter_entry)); *result = {filter, head}; return result; } static _filter_entry *_filter_list_remove (_filter_entry *head, filter *filter) { auto current = head; auto prev_ptr = &head; while (current) { if (_filter_equals (current->filter, filter)) { *prev_ptr = current->next; *current = {nullptr, nullptr}; free (current); break; } prev_ptr = &(current->next); current = current->next; } return head; } #pragma region All filter struct _filter_all_context { _filter_entry *children_head; }; static void _filter_all_destroy (void *context); static bool _filter_all_apply (void *context, const log4j_event<> *event); void filter_init_all (filter **self) { auto context = (_filter_all_context *) malloc (sizeof (_filter_all_context)); *context = {nullptr}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_all_apply, &_filter_all_destroy}; *self = result; } static void _filter_all_destroy (void *context) { auto context_a = (_filter_all_context *) context; if (context_a->children_head) { _filter_list_destroy (context_a->children_head); } context_a = {nullptr}; free (context); } void filter_all_add (filter *self, filter *child) { auto context = (_filter_all_context *) self->context; context->children_head = _filter_list_add (context->children_head, child); } void filter_all_remove (filter *self, filter *child) { auto context = (_filter_all_context *) self->context; context->children_head = _filter_list_remove (context->children_head, child); } static bool _filter_all_apply (void *context, const log4j_event<> *event) { auto context_a = (_filter_all_context *) context; auto current = context_a->children_head; bool result = true; while (current && result) { result = result && filter_apply (current->filter, event); current = current->next; } return result; } #pragma endregion #pragma region Any filter struct _filter_any_context { _filter_entry *children_head; }; static void _filter_any_destroy (void *context); static bool _filter_any_apply (void *context, const log4j_event<> *event); void filter_init_any (filter **self) { auto context = (_filter_any_context *) malloc (sizeof (_filter_any_context)); *context = {nullptr}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_any_apply, &_filter_any_destroy}; *self = result; } static void _filter_any_destroy (void *context) { auto context_a = (_filter_any_context *) context; if (context_a->children_head) { _filter_list_destroy (context_a->children_head); } context_a = {nullptr}; free (context); } void filter_any_add (filter *self, filter *child) { auto context = (_filter_any_context *) self->context; context->children_head = _filter_list_add (context->children_head, child); } void filter_any_remove (filter *self, filter *child) { auto context = (_filter_any_context *) self->context; context->children_head = _filter_list_remove (context->children_head, child); } static bool _filter_any_apply (void *context, const log4j_event<> *event) { auto context_a = (_filter_any_context *) context; auto current = context_a->children_head; bool result = false; while (current && !result) { result = result || filter_apply (current->filter, event); current = current->next; } return result; } #pragma endregion #pragma region Not filter struct _filter_not_context { filter *child_filter; }; static void _filter_not_destroy (void *context); static bool _filter_not_apply (void *context, const log4j_event<> *event); void filter_init_not (filter **self, filter *child_filter) { auto context = (_filter_not_context *) malloc (sizeof (_filter_not_context)); *context = {child_filter}; auto result = (filter *) malloc (sizeof (filter)); *result = {context, &_filter_not_apply, &_filter_not_destroy}; *self = result; } static void _filter_not_destroy (void *context) { auto context_n = (_filter_not_context *) context; *context_n = {nullptr}; free (context); } static bool _filter_not_apply (void *context, const log4j_event<> *event) { auto context_n = (_filter_not_context *) context; return !filter_apply (context_n->child_filter, event); } #pragma endregion <commit_msg>Embedded filter context data in the filter struct.<commit_after>#include "stdafx.h" #include "filter.h" #include "level_parser.h" typedef bool filter_apply_cb (const filter *self, const log4j_event<> *event); typedef void filter_destroy_cb (filter *self); struct _filter { filter_apply_cb *apply; filter_destroy_cb *destroy; }; void filter_destroy (filter *self) { self->destroy (self); *self = {nullptr, nullptr}; free (self); } bool filter_apply (const filter *self, const log4j_event<> *event) { return self->apply (self, event); } static inline bool _filter_equals (const filter *x, const filter *y) { return x == y; } #pragma region Level lilter struct _filter_level { struct _filter base; int32_t min; int32_t max; }; static void _filter_level_destroy (filter *context); static bool _filter_level_apply (const filter *context, const log4j_event<> *event); void filter_init_level_i (filter **self, int32_t min, int32_t max) { auto result = (_filter_level *) malloc (sizeof (_filter_level)); *result = {{&_filter_level_apply, &_filter_level_destroy}, min, max}; *self = (_filter *) result; } void filter_init_level_c (filter **self, const char *min, const char *max) { auto min_i = level_parser<char>::instance.get_value (min); auto max_i = level_parser<char>::instance.get_value (max); filter_init_level_i (self, min_i, max_i); } static void _filter_level_destroy (filter *self) { auto self_l = (_filter_level *) self; self_l->min = 0; self_l->max = 0; } static bool _filter_level_apply (const filter *self, const log4j_event<> *event) { auto self_l = (const _filter_level *) self; auto val_string = event->get_level (); int32_t value = level_parser<char>::instance.get_value (val_string.value (), val_string.size ()); return self_l->min <= value && value <= self_l->max; } #pragma endregion #pragma region Logger filter struct _filter_logger { struct _filter base; char *logger; size_t logger_size; }; static void _filter_logger_destroy (filter *context); static bool _filter_logger_apply (const filter *context, const log4j_event<> *event); void filter_init_logger_fs (filter **self, const char *logger, const size_t logger_size) { // Reminder: logger_size must be multiplied by sizeof (Ch) if this code is reused for non-char // strings (e.g. wchar strings). auto context_logger = (char *) malloc (logger_size); memcpy (context_logger, logger, logger_size); auto result = (_filter_logger *) malloc (sizeof (_filter_logger)); *result = {{&_filter_logger_apply, &_filter_logger_destroy}, context_logger, logger_size}; *self = (filter *) result; } void filter_init_logger_nt (filter **self, const char *logger) { auto logger_size = strlen (logger); filter_init_logger_fs (self, logger, logger_size); } static void _filter_logger_destroy (filter *self) { auto self_l = (_filter_logger *) self; free (self_l->logger); self_l->logger = nullptr; self_l->logger_size = 0; } static bool _filter_logger_apply (const filter *self, const log4j_event<> *event) { auto self_l = (const _filter_logger *) self; auto value = event->get_logger (); auto logger = self_l->logger; auto logger_size = self_l->logger_size; return value.size () >= logger_size && _strnicmp (value.value (), logger, logger_size) == 0; } #pragma endregion #pragma region Message filter struct _filter_message { struct _filter base; char *message; size_t message_size; }; static void _filter_message_destroy (filter *self); static bool _filter_message_apply (const filter *self, const log4j_event<> *event); void filter_init_message_fs (filter **self, const char *message, const size_t message_size) { // Reminder: message_size must be multiplied by sizeof (Ch) if this code is reused for non-char // strings (e.g. wchar strings). auto context_message = (char *) malloc (message_size); memcpy (context_message, message, message_size); auto result = (_filter_message *) malloc (sizeof (_filter_message)); *result = {{&_filter_message_apply, &_filter_message_destroy}, context_message, message_size}; *self = (filter *) result; } void filter_init_message_nt (filter **self, const char *message) { auto message_size = strlen (message); filter_init_message_fs (self, message, message_size); } static void _filter_message_destroy (filter *self) { auto self_m = (_filter_message *) self; free (self_m->message); self_m->message = nullptr; self_m->message_size = 0; } static bool _filter_message_apply (const filter *self, const log4j_event<> *event) { auto self_m = (const _filter_message *) self; if (self_m->message_size == 0) { return true; } auto message = event->get_message (); size_t value_size = message.size (); if (value_size < self_m->message_size) { return false; } const char *value = message.value (); const char message_head = *self_m->message; const char *message_tail = self_m->message + 1; const size_t message_tail_size = self_m->message_size - 1; do { char sc; do { sc = *value; ++value; --value_size; if (value_size < message_tail_size) { return false; } } while (sc != message_head); } while (strncmp (value, message_tail, message_tail_size) != 0); return true; } #pragma endregion #pragma region Timestamp filter struct _filter_timestamp { struct _filter base; int64_t min; int64_t max; }; static void _filter_timestamp_destroy (filter *self); static bool _filter_timestamp_apply (const filter *self, const log4j_event<> *event); void filter_init_timestamp (filter **self, int64_t min, int64_t max) { auto result = (_filter_timestamp *) malloc (sizeof (_filter_timestamp)); *result = {{&_filter_timestamp_apply, &_filter_timestamp_destroy}, min, max}; *self = (filter *) result; } static void _filter_timestamp_destroy (filter *self) { auto self_t = (_filter_timestamp *) self; self_t->min = 0; self_t->max = 0; } static bool _filter_timestamp_apply (const filter *self, const log4j_event<> *event) { auto self_t = (const _filter_timestamp *) self; auto value = event->get_time (); return self_t->min <= value && value <= self_t->max; } #pragma endregion // Composite filters struct _filter_entry { filter *filter; _filter_entry *next; }; static void _filter_list_destroy (_filter_entry *head) { if (head->next) { _filter_list_destroy (head->next); } *head = {nullptr, nullptr}; free (head); } static _filter_entry *_filter_list_add (_filter_entry *head, filter *filter) { auto result = (_filter_entry *) malloc (sizeof (_filter_entry)); *result = {filter, head}; return result; } static _filter_entry *_filter_list_remove (_filter_entry *head, filter *filter) { auto current = head; auto prev_ptr = &head; while (current) { if (_filter_equals (current->filter, filter)) { *prev_ptr = current->next; *current = {nullptr, nullptr}; free (current); break; } prev_ptr = &(current->next); current = current->next; } return head; } #pragma region All filter struct _filter_all { struct _filter base; _filter_entry *children_head; }; static void _filter_all_destroy (filter *self); static bool _filter_all_apply (const filter *self, const log4j_event<> *event); void filter_init_all (filter **self) { auto result = (_filter_all *) malloc (sizeof (_filter_all)); *result = {{&_filter_all_apply, &_filter_all_destroy}, nullptr}; *self = (filter *) result; } static void _filter_all_destroy (filter *self) { auto self_a = (_filter_all *) self; if (self_a->children_head) { _filter_list_destroy (self_a->children_head); } self_a->children_head = nullptr; } void filter_all_add (filter *self, filter *child) { auto self_a = (_filter_all *) self; self_a->children_head = _filter_list_add (self_a->children_head, child); } void filter_all_remove (filter *self, filter *child) { auto self_a = (_filter_all *) self; self_a->children_head = _filter_list_remove (self_a->children_head, child); } static bool _filter_all_apply (const filter *self, const log4j_event<> *event) { auto self_a = (const _filter_all *) self; auto current = self_a->children_head; bool result = true; while (current && result) { result = result && filter_apply (current->filter, event); current = current->next; } return result; } #pragma endregion #pragma region Any filter struct _filter_any { struct _filter base; _filter_entry *children_head; }; static void _filter_any_destroy (filter *self); static bool _filter_any_apply (const filter *self, const log4j_event<> *event); void filter_init_any (filter **self) { auto result = (_filter_any *) malloc (sizeof (_filter_any)); *result = {{&_filter_any_apply, &_filter_any_destroy}, nullptr}; *self = (filter *) result; } static void _filter_any_destroy (filter *self) { auto self_a = (_filter_any *) self; if (self_a->children_head) { _filter_list_destroy (self_a->children_head); } self_a->children_head = nullptr; } void filter_any_add (filter *self, filter *child) { auto self_a = (_filter_any *) self; self_a->children_head = _filter_list_add (self_a->children_head, child); } void filter_any_remove (filter *self, filter *child) { auto self_a = (_filter_any *) self; self_a->children_head = _filter_list_remove (self_a->children_head, child); } static bool _filter_any_apply (const filter *self, const log4j_event<> *event) { auto self_a = (const _filter_any *) self; auto current = self_a->children_head; bool result = false; while (current && !result) { result = result || filter_apply (current->filter, event); current = current->next; } return result; } #pragma endregion #pragma region Not filter struct _filter_not { struct _filter base; filter *child_filter; }; static void _filter_not_destroy (filter *context); static bool _filter_not_apply (const filter *context, const log4j_event<> *event); void filter_init_not (filter **self, filter *child_filter) { auto result = (_filter_not *) malloc (sizeof (_filter_not)); *result = {{&_filter_not_apply, &_filter_not_destroy}, child_filter}; *self = (filter *) result; } static void _filter_not_destroy (filter *self) { auto self_n = (_filter_not *) self; self_n->child_filter = nullptr; } static bool _filter_not_apply (const filter *self, const log4j_event<> *event) { auto self_n = (const _filter_not *) self; return !filter_apply (self_n->child_filter, event); } #pragma endregion <|endoftext|>
<commit_before>#ifndef _TCUANDROIDINTERNALS_HPP #define _TCUANDROIDINTERNALS_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Access to Android internals that are not a part of the NDK. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "deDynamicLibrary.hpp" #include <vector> #include <errno.h> struct ANativeWindowBuffer; namespace android { class GraphicBuffer; class android_native_base_t; } namespace tcu { namespace Android { // These classes and enums reflect internal android definitions namespace internal { // utils/Errors.h enum { OK = 0, UNKNOWN_ERROR = (-2147483647-1), NO_MEMORY = -ENOMEM, INVALID_OPERATION = -ENOSYS, BAD_VALUE = -EINVAL, BAD_TYPE = (UNKNOWN_ERROR + 1), NAME_NOT_FOUND = -ENOENT, PERMISSION_DENIED = -EPERM, NO_INIT = -ENODEV, ALREADY_EXISTS = -EEXIST, DEAD_OBJECT = -EPIPE, FAILED_TRANSACTION = (UNKNOWN_ERROR + 2), JPARKS_BROKE_IT = -EPIPE, BAD_INDEX = -E2BIG, NOT_ENOUGH_DATA = (UNKNOWN_ERROR + 3), WOULD_BLOCK = (UNKNOWN_ERROR + 4), TIMED_OUT = (UNKNOWN_ERROR + 5), UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6), FDS_NOT_ALLOWED = (UNKNOWN_ERROR + 7), }; typedef deInt32 status_t; // ui/PixelFormat.h, system/graphics.h enum { PIXEL_FORMAT_UNKNOWN = 0, PIXEL_FORMAT_NONE = 0, PIXEL_FORMAT_CUSTOM = -4, PIXEL_FORMAT_TRANSLUCENT = -3, PIXEL_FORMAT_TRANSPARENT = -2, PIXEL_FORMAT_OPAQUE = -1, PIXEL_FORMAT_RGBA_8888 = 1, PIXEL_FORMAT_RGBX_8888 = 2, PIXEL_FORMAT_RGB_888 = 3, PIXEL_FORMAT_RGB_565 = 4, PIXEL_FORMAT_BGRA_8888 = 5, PIXEL_FORMAT_RGBA_5551 = 6, PIXEL_FORMAT_RGBA_4444 = 7, }; typedef deInt32 PixelFormat; // ui/GraphicBuffer.h struct GraphicBufferFunctions { typedef void (*genericFunc) (); typedef status_t (*initCheckFunc) (android::GraphicBuffer* buffer); typedef status_t (*lockFunc) (android::GraphicBuffer* buffer, deUint32 usage, void** vaddr); typedef status_t (*unlockFunc) (android::GraphicBuffer* buffer); typedef ANativeWindowBuffer* (*getNativeBufferFunc) (const android::GraphicBuffer* buffer); genericFunc constructor; genericFunc destructor; lockFunc lock; unlockFunc unlock; getNativeBufferFunc getNativeBuffer; initCheckFunc initCheck; }; // system/window.h struct NativeBaseFunctions { typedef void (*incRefFunc) (android::android_native_base_t* base); typedef void (*decRefFunc) (android::android_native_base_t* base); incRefFunc incRef; decRefFunc decRef; }; struct LibUIFunctions { GraphicBufferFunctions graphicBuffer; }; class LibUI { public: struct Functions { GraphicBufferFunctions graphicBuffer; }; LibUI (void); const Functions& getFunctions (void) const { return m_functions; } private: Functions m_functions; de::DynamicLibrary m_library; }; class GraphicBuffer { public: // ui/GraphicBuffer.h, hardware/gralloc.h enum { USAGE_SW_READ_NEVER = 0x00000000, USAGE_SW_READ_RARELY = 0x00000002, USAGE_SW_READ_OFTEN = 0x00000003, USAGE_SW_READ_MASK = 0x0000000f, USAGE_SW_WRITE_NEVER = 0x00000000, USAGE_SW_WRITE_RARELY = 0x00000020, USAGE_SW_WRITE_OFTEN = 0x00000030, USAGE_SW_WRITE_MASK = 0x000000f0, USAGE_SOFTWARE_MASK = USAGE_SW_READ_MASK | USAGE_SW_WRITE_MASK, USAGE_PROTECTED = 0x00004000, USAGE_HW_TEXTURE = 0x00000100, USAGE_HW_RENDER = 0x00000200, USAGE_HW_2D = 0x00000400, USAGE_HW_COMPOSER = 0x00000800, USAGE_HW_VIDEO_ENCODER = 0x00010000, USAGE_HW_MASK = 0x00071F00, }; GraphicBuffer (const LibUI& lib, deUint32 width, deUint32 height, PixelFormat format, deUint32 usage); ~GraphicBuffer (); status_t lock (deUint32 usage, void** vaddr); status_t unlock (void); ANativeWindowBuffer* getNativeBuffer (void) const; private: const GraphicBufferFunctions& m_functions; NativeBaseFunctions m_baseFunctions; android::GraphicBuffer* m_impl; }; } // internal } // Android } // tcu #endif // _TCUANDROIDINTERNALS_HPP <commit_msg>Stop being silly. am: ded9c531f5<commit_after>#ifndef _TCUANDROIDINTERNALS_HPP #define _TCUANDROIDINTERNALS_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Access to Android internals that are not a part of the NDK. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "deDynamicLibrary.hpp" #include <vector> #include <errno.h> struct ANativeWindowBuffer; namespace android { class GraphicBuffer; class android_native_base_t; } namespace tcu { namespace Android { // These classes and enums reflect internal android definitions namespace internal { // utils/Errors.h enum { OK = 0, UNKNOWN_ERROR = (-2147483647-1), NO_MEMORY = -ENOMEM, INVALID_OPERATION = -ENOSYS, BAD_VALUE = -EINVAL, BAD_TYPE = (UNKNOWN_ERROR + 1), NAME_NOT_FOUND = -ENOENT, PERMISSION_DENIED = -EPERM, NO_INIT = -ENODEV, ALREADY_EXISTS = -EEXIST, DEAD_OBJECT = -EPIPE, FAILED_TRANSACTION = (UNKNOWN_ERROR + 2), BAD_INDEX = -E2BIG, NOT_ENOUGH_DATA = (UNKNOWN_ERROR + 3), WOULD_BLOCK = (UNKNOWN_ERROR + 4), TIMED_OUT = (UNKNOWN_ERROR + 5), UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6), FDS_NOT_ALLOWED = (UNKNOWN_ERROR + 7), }; typedef deInt32 status_t; // ui/PixelFormat.h, system/graphics.h enum { PIXEL_FORMAT_UNKNOWN = 0, PIXEL_FORMAT_NONE = 0, PIXEL_FORMAT_CUSTOM = -4, PIXEL_FORMAT_TRANSLUCENT = -3, PIXEL_FORMAT_TRANSPARENT = -2, PIXEL_FORMAT_OPAQUE = -1, PIXEL_FORMAT_RGBA_8888 = 1, PIXEL_FORMAT_RGBX_8888 = 2, PIXEL_FORMAT_RGB_888 = 3, PIXEL_FORMAT_RGB_565 = 4, PIXEL_FORMAT_BGRA_8888 = 5, PIXEL_FORMAT_RGBA_5551 = 6, PIXEL_FORMAT_RGBA_4444 = 7, }; typedef deInt32 PixelFormat; // ui/GraphicBuffer.h struct GraphicBufferFunctions { typedef void (*genericFunc) (); typedef status_t (*initCheckFunc) (android::GraphicBuffer* buffer); typedef status_t (*lockFunc) (android::GraphicBuffer* buffer, deUint32 usage, void** vaddr); typedef status_t (*unlockFunc) (android::GraphicBuffer* buffer); typedef ANativeWindowBuffer* (*getNativeBufferFunc) (const android::GraphicBuffer* buffer); genericFunc constructor; genericFunc destructor; lockFunc lock; unlockFunc unlock; getNativeBufferFunc getNativeBuffer; initCheckFunc initCheck; }; // system/window.h struct NativeBaseFunctions { typedef void (*incRefFunc) (android::android_native_base_t* base); typedef void (*decRefFunc) (android::android_native_base_t* base); incRefFunc incRef; decRefFunc decRef; }; struct LibUIFunctions { GraphicBufferFunctions graphicBuffer; }; class LibUI { public: struct Functions { GraphicBufferFunctions graphicBuffer; }; LibUI (void); const Functions& getFunctions (void) const { return m_functions; } private: Functions m_functions; de::DynamicLibrary m_library; }; class GraphicBuffer { public: // ui/GraphicBuffer.h, hardware/gralloc.h enum { USAGE_SW_READ_NEVER = 0x00000000, USAGE_SW_READ_RARELY = 0x00000002, USAGE_SW_READ_OFTEN = 0x00000003, USAGE_SW_READ_MASK = 0x0000000f, USAGE_SW_WRITE_NEVER = 0x00000000, USAGE_SW_WRITE_RARELY = 0x00000020, USAGE_SW_WRITE_OFTEN = 0x00000030, USAGE_SW_WRITE_MASK = 0x000000f0, USAGE_SOFTWARE_MASK = USAGE_SW_READ_MASK | USAGE_SW_WRITE_MASK, USAGE_PROTECTED = 0x00004000, USAGE_HW_TEXTURE = 0x00000100, USAGE_HW_RENDER = 0x00000200, USAGE_HW_2D = 0x00000400, USAGE_HW_COMPOSER = 0x00000800, USAGE_HW_VIDEO_ENCODER = 0x00010000, USAGE_HW_MASK = 0x00071F00, }; GraphicBuffer (const LibUI& lib, deUint32 width, deUint32 height, PixelFormat format, deUint32 usage); ~GraphicBuffer (); status_t lock (deUint32 usage, void** vaddr); status_t unlock (void); ANativeWindowBuffer* getNativeBuffer (void) const; private: const GraphicBufferFunctions& m_functions; NativeBaseFunctions m_baseFunctions; android::GraphicBuffer* m_impl; }; } // internal } // Android } // tcu #endif // _TCUANDROIDINTERNALS_HPP <|endoftext|>
<commit_before> #include <sofa/gui/qt/QVisitorControlPanel.h> #include <sofa/simulation/common/Visitor.h> #ifdef SOFA_QT4 #include <QPushButton> #include <QCheckBox> #include <QSpinBox> #include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #else #include <qpushbutton.h> #include <qcheckbox.h> #include <qspinbox.h> #include <qlabel.h> #include <qlayout.h> #endif namespace sofa { namespace gui { namespace qt { QVisitorControlPanel::QVisitorControlPanel(QWidget* parent): QWidget(parent) { QVBoxLayout *vbox=new QVBoxLayout(this); //Parameters to configure the export of the state vectors QWidget *exportStateParameters = new QWidget(this); QHBoxLayout *hboxParameters=new QHBoxLayout(exportStateParameters); QCheckBox *activation=new QCheckBox(QString("Trace State Vector"), exportStateParameters); QSpinBox *spinIndex = new QSpinBox(exportStateParameters); spinIndex->setMinValue(0); spinIndex->setValue(sofa::simulation::Visitor::GetFirstIndexStateVector()); QSpinBox *spinRange = new QSpinBox(exportStateParameters); spinRange->setValue(sofa::simulation::Visitor::GetRangeStateVector()); connect(activation, SIGNAL(toggled(bool)), this, SLOT(activateTraceStateVectors(bool))); connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(changeFirstIndex(int))); connect(spinRange, SIGNAL(valueChanged(int)), this, SLOT(changeRange(int))); hboxParameters->addWidget(activation); hboxParameters->addWidget(spinIndex); hboxParameters->addWidget(new QLabel(QString("First Index"))); hboxParameters->addWidget(spinRange); hboxParameters->addWidget(new QLabel(QString("Range"))); hboxParameters->addStretch(); activateTraceStateVectors(sofa::simulation::Visitor::IsExportStateVectorEnabled()); //Filter the results to quickly find a visitor QWidget *filterResult = new QWidget(this); QHBoxLayout *hboxFilers=new QHBoxLayout(filterResult); textFilter = new QLineEdit(filterResult); QPushButton *findFilter = new QPushButton(QString("Find"), filterResult); findFilter->setAutoDefault(true); hboxFilers->addWidget(new QLabel(QString("Focus on:"))); hboxFilers->addWidget(textFilter); hboxFilers->addWidget(findFilter); connect(findFilter, SIGNAL(clicked()), this, SLOT(filterResults())); connect(textFilter, SIGNAL(returnPressed()), this, SLOT(filterResults())); //Configure the main window vbox->addWidget(exportStateParameters); vbox->addWidget(filterResult); } void QVisitorControlPanel::activateTraceStateVectors(bool active) { sofa::simulation::Visitor::EnableExportStateVector(active); } void QVisitorControlPanel::changeFirstIndex(int idx) { sofa::simulation::Visitor::SetFirstIndexStateVector(idx); } void QVisitorControlPanel::changeRange(int range) { sofa::simulation::Visitor::SetRangeStateVector(range); } void QVisitorControlPanel::filterResults() { emit focusOn(textFilter->text()); } } // qt } // gui } //sofa <commit_msg>r6413/sofa-dev : FIX: compilation with qt3?<commit_after> #include <sofa/gui/qt/QVisitorControlPanel.h> #include <sofa/simulation/common/Visitor.h> #ifdef SOFA_QT4 #include <QPushButton> #include <QCheckBox> #include <QSpinBox> #include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #else #include <qpushbutton.h> #include <qcheckbox.h> #include <qspinbox.h> #include <qlabel.h> #include <qlayout.h> #endif namespace sofa { namespace gui { namespace qt { QVisitorControlPanel::QVisitorControlPanel(QWidget* parent): QWidget(parent) { QVBoxLayout *vbox=new QVBoxLayout(this); //Parameters to configure the export of the state vectors QWidget *exportStateParameters = new QWidget(this); QHBoxLayout *hboxParameters=new QHBoxLayout(exportStateParameters); QCheckBox *activation=new QCheckBox(QString("Trace State Vector"), exportStateParameters); QSpinBox *spinIndex = new QSpinBox(exportStateParameters); spinIndex->setMinValue(0); spinIndex->setValue(sofa::simulation::Visitor::GetFirstIndexStateVector()); QSpinBox *spinRange = new QSpinBox(exportStateParameters); spinRange->setValue(sofa::simulation::Visitor::GetRangeStateVector()); connect(activation, SIGNAL(toggled(bool)), this, SLOT(activateTraceStateVectors(bool))); connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(changeFirstIndex(int))); connect(spinRange, SIGNAL(valueChanged(int)), this, SLOT(changeRange(int))); hboxParameters->addWidget(activation); hboxParameters->addWidget(spinIndex); hboxParameters->addWidget(new QLabel(QString("First Index"), exportStateParameters)); hboxParameters->addWidget(spinRange); hboxParameters->addWidget(new QLabel(QString("Range"), exportStateParameters)); hboxParameters->addStretch(); activateTraceStateVectors(sofa::simulation::Visitor::IsExportStateVectorEnabled()); //Filter the results to quickly find a visitor QWidget *filterResult = new QWidget(this); QHBoxLayout *hboxFilers=new QHBoxLayout(filterResult); textFilter = new QLineEdit(filterResult); QPushButton *findFilter = new QPushButton(QString("Find"), filterResult); findFilter->setAutoDefault(true); hboxFilers->addWidget(new QLabel(QString("Focus on:"), filterResult)); hboxFilers->addWidget(textFilter); hboxFilers->addWidget(findFilter); connect(findFilter, SIGNAL(clicked()), this, SLOT(filterResults())); connect(textFilter, SIGNAL(returnPressed()), this, SLOT(filterResults())); //Configure the main window vbox->addWidget(exportStateParameters); vbox->addWidget(filterResult); } void QVisitorControlPanel::activateTraceStateVectors(bool active) { sofa::simulation::Visitor::EnableExportStateVector(active); } void QVisitorControlPanel::changeFirstIndex(int idx) { sofa::simulation::Visitor::SetFirstIndexStateVector(idx); } void QVisitorControlPanel::changeRange(int range) { sofa::simulation::Visitor::SetRangeStateVector(range); } void QVisitorControlPanel::filterResults() { emit focusOn(textFilter->text()); } } // qt } // gui } //sofa <|endoftext|>
<commit_before>#include "Framework.hpp" #include "../core/jni_helper.hpp" #include "coding/internal/file_data.hpp" #include "platform/mwm_version.hpp" #include "storage/storage.hpp" #include "std/bind.hpp" #include "std/shared_ptr.hpp" namespace data { using namespace storage; enum ItemCategory : uint32_t { NEAR_ME, DOWNLOADED, ALL, }; jclass g_listClass; jmethodID g_listAddMethod; jclass g_countryItemClass; Storage & GetStorage() { return g_framework->Storage(); } void PrepareClassRefs(JNIEnv * env) { if (g_listClass) return; g_listClass = jni::GetGlobalClassRef(env, "java/util/List"); g_listAddMethod = env->GetMethodID(g_listClass, "add", "(Ljava/lang/Object;)Z"); g_countryItemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/CountryItem"); } } // namespace data extern "C" { using namespace storage; using namespace data; // static boolean nativeMoveFile(String oldFile, String newFile); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_MapStorage_nativeMoveFile(JNIEnv * env, jclass clazz, jstring oldFile, jstring newFile) { return my::RenameFileX(jni::ToNativeString(env, oldFile), jni::ToNativeString(env, newFile)); } // static native boolean nativeIsLegacyMode(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsLegacyMode(JNIEnv * env, jclass clazz) { return g_framework->NeedMigrate(); } // static void nativeMigrate(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeMigrate(JNIEnv * env, jclass clazz) { g_framework->Migrate(); } // static int nativeGetDownloadedCount(); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetDownloadedCount(JNIEnv * env, jclass clazz) { return GetStorage().GetDownloadedFilesCount(); } // static String nativeGetRootNode(); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetRootNode(JNIEnv * env, jclass clazz) { return jni::ToJavaString(env, Storage().GetRootId()); } // static @Nullable UpdateInfo nativeGetUpdateInfo(); JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetUpdateInfo(JNIEnv * env, jclass clazz) { static Storage::UpdateInfo info = { 0 }; if (!GetStorage().GetUpdateInfo(info)) return nullptr; static jclass const infoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/UpdateInfo"); ASSERT(infoClass, (jni::DescribeException())); static jmethodID const ctor = jni::GetConstructorID(env, infoClass, "(II)V"); ASSERT(ctor, (jni::DescribeException())); return env->NewObject(infoClass, ctor, info.m_numberOfMwmFilesToUpdate, info.m_totalUpdateSizeInBytes); } static void UpdateItem(JNIEnv * env, jobject item, NodeAttrs const & attrs) { static jfieldID const countryItemFieldName = env->GetFieldID(g_countryItemClass, "name", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentName = env->GetFieldID(g_countryItemClass, "parentName", "Ljava/lang/String;"); static jfieldID const countryItemFieldSize = env->GetFieldID(g_countryItemClass, "size", "J"); static jfieldID const countryItemFieldTotalSize = env->GetFieldID(g_countryItemClass, "totalSize", "J"); static jfieldID const countryItemFieldChildCount = env->GetFieldID(g_countryItemClass, "childCount", "I"); static jfieldID const countryItemFieldTotalChildCount = env->GetFieldID(g_countryItemClass, "totalChildCount", "I"); static jfieldID const countryItemFieldStatus = env->GetFieldID(g_countryItemClass, "status", "I"); static jfieldID const countryItemFieldErrorCode = env->GetFieldID(g_countryItemClass, "errorCode", "I"); static jfieldID const countryItemFieldPresent = env->GetFieldID(g_countryItemClass, "present", "Z"); static jfieldID const countryItemFieldProgress = env->GetFieldID(g_countryItemClass, "progress", "I"); // Localized name jni::TScopedLocalRef const name(env, jni::ToJavaString(env, attrs.m_nodeLocalName)); env->SetObjectField(item, countryItemFieldName, name.get()); // Info about parent[s]. Do not specify if there are multiple parents or none. if (attrs.m_parentInfo.size() == 1) { CountryIdAndName const & info = attrs.m_parentInfo[0]; jni::TScopedLocalRef const parentId(env, jni::ToJavaString(env, info.m_id)); env->SetObjectField(item, countryItemFieldParentId, parentId.get()); jni::TScopedLocalRef const parentName(env, jni::ToJavaString(env, info.m_localName)); env->SetObjectField(item, countryItemFieldParentName, parentName.get()); } else { env->SetObjectField(item, countryItemFieldParentId, nullptr); env->SetObjectField(item, countryItemFieldParentName, nullptr); } // Sizes env->SetLongField(item, countryItemFieldSize, attrs.m_localMwmSize); env->SetLongField(item, countryItemFieldTotalSize, attrs.m_mwmSize); // Child counts env->SetIntField(item, countryItemFieldChildCount, attrs.m_localMwmCounter); env->SetIntField(item, countryItemFieldTotalChildCount, attrs.m_mwmCounter); // Status and error code env->SetIntField(item, countryItemFieldStatus, static_cast<jint>(attrs.m_status)); env->SetIntField(item, countryItemFieldErrorCode, static_cast<jint>(attrs.m_error)); // Presence flag env->SetBooleanField(item, countryItemFieldPresent, attrs.m_present); // Progress env->SetIntField(item, countryItemFieldProgress,static_cast<jint>(attrs.m_downloadingMwmSize)); } static void PutItemsToList(JNIEnv * env, jobject const list, vector<TCountryId> const & children, TCountryId const & parent, int category) { static jmethodID const countryItemCtor = jni::GetConstructorID(env, g_countryItemClass, "(Ljava/lang/String;)V"); static jfieldID const countryItemFieldCategory = env->GetFieldID(g_countryItemClass, "category", "I"); NodeAttrs attrs; for (TCountryId const & child : children) { GetStorage().GetNodeAttrs(child, attrs); jni::TScopedLocalRef const id(env, jni::ToJavaString(env, child)); jni::TScopedLocalRef const item(env, env->NewObject(g_countryItemClass, countryItemCtor, id.get())); env->SetIntField(item.get(), countryItemFieldCategory, category); UpdateItem(env, item.get(), attrs); // Put to resulting list env->CallBooleanMethod(list, g_listAddMethod, item.get()); } } // static void nativeListItems(@Nullable String parent, List<CountryItem> result); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeListItems(JNIEnv * env, jclass clazz, jstring parent, jobject result) { PrepareClassRefs(env); Storage const & storage = GetStorage(); TCountryId const parentId = (parent ? jni::ToNativeString(env, parent) : storage.GetRootId()); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); if (parent) { vector<TCountryId> children; storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } else { // TODO (trashkalmar): Countries near me // Downloaded vector<TCountryId> children; storage.GetDownloadedChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::DOWNLOADED); // All storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } } // static void nativeUpdateItem(CountryItem item); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetAttributes(JNIEnv * env, jclass clazz, jobject item) { PrepareClassRefs(env); NodeAttrs attrs; static jfieldID countryItemFieldId = env->GetFieldID(g_countryItemClass, "id", "Ljava/lang/String;"); jstring id = static_cast<jstring>(env->GetObjectField(item, countryItemFieldId)); GetStorage().GetNodeAttrs(jni::ToNativeString(env, id), attrs); UpdateItem(env, item, attrs); } // static @Nullable String nativeFindCountry(double lat, double lon); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeFindCountry(JNIEnv * env, jclass clazz, jdouble lat, jdouble lon) { return jni::ToJavaString(env, g_framework->NativeFramework()->CountryInfoGetter().GetRegionCountryId(MercatorBounds::FromLatLon(lat, lon))); } // static boolean nativeIsDownloading(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsDownloading(JNIEnv * env, jclass clazz) { return GetStorage().IsDownloadInProgress(); } // static boolean nativeDownload(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDownload(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeRetry(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeRetry(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().RetryDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeUpdate(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUpdate(JNIEnv * env, jclass clazz, jstring root) { // FIXME (trashkalmar): Uncomment after method is implemented. //return GetStorage().UpdateNode(jni::ToNativeString(env, root)); return true; } // static boolean nativeCancel(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeCancel(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().CancelDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeDelete(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDelete(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DeleteNode(jni::ToNativeString(env, root)); } static void StatusChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); // TODO: The core will do this itself NodeAttrs attrs; GetStorage().GetNodeAttrs(countryId, attrs); jmethodID const methodID = jni::GetMethodID(env, *listenerRef.get(), "onStatusChanged", "(Ljava/lang/String;I)V"); env->CallVoidMethod(*listenerRef.get(), methodID, jni::ToJavaString(env, countryId), attrs.m_status); } static void ProgressChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId, TLocalAndRemoteSize const & sizes) { JNIEnv * env = jni::GetEnv(); jmethodID const methodID = jni::GetMethodID(env, *listenerRef.get(), "onProgress", "(Ljava/lang/String;JJ)V"); env->CallVoidMethod(*listenerRef.get(), methodID, jni::ToJavaString(env, countryId), sizes.first, sizes.second); } // static int nativeSubscribe(StorageCallback listener); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribe(JNIEnv * env, jclass clazz, jobject listener) { PrepareClassRefs(env); return GetStorage().Subscribe(bind(&StatusChangedCallback, jni::make_global_ref(listener), _1), bind(&ProgressChangedCallback, jni::make_global_ref(listener), _1, _2)); } // static void nativeUnsubscribe(int slot); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribe(JNIEnv * env, jclass clazz, jint slot) { GetStorage().Unsubscribe(slot); } static jobject g_countryChangedListener; // static void nativeSubscribeOnCountryChanged(CurrentCountryChangedListener listener); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribeOnCountryChanged(JNIEnv * env, jclass clazz, jobject listener) { ASSERT(!g_countryChangedListener, ()); g_countryChangedListener = env->NewGlobalRef(listener); auto const callback = [](TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); jmethodID methodID = jni::GetMethodID(env, g_countryChangedListener, "onCurrentCountryChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(g_countryChangedListener, methodID, jni::TScopedLocalRef(env, jni::ToJavaString(env, countryId)).get()); }; TCountryId const & prev = g_framework->NativeFramework()->GetLastReportedCountry(); g_framework->NativeFramework()->SetCurrentCountryChangedListener(callback); // Report previous value callback(prev); } // static void nativeUnsubscribeOnCountryChanged(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribeOnCountryChanged(JNIEnv * env, jclass clazz) { g_framework->NativeFramework()->SetCurrentCountryChangedListener(nullptr); ASSERT(g_countryChangedListener, ()); env->DeleteGlobalRef(g_countryChangedListener); g_countryChangedListener = nullptr; } } // extern "C" <commit_msg>[new downloader] Fixed Android build<commit_after>#include "Framework.hpp" #include "../core/jni_helper.hpp" #include "coding/internal/file_data.hpp" #include "platform/mwm_version.hpp" #include "storage/storage.hpp" #include "std/bind.hpp" #include "std/shared_ptr.hpp" namespace data { using namespace storage; enum ItemCategory : uint32_t { NEAR_ME, DOWNLOADED, ALL, }; jclass g_listClass; jmethodID g_listAddMethod; jclass g_countryItemClass; Storage & GetStorage() { return g_framework->Storage(); } void PrepareClassRefs(JNIEnv * env) { if (g_listClass) return; g_listClass = jni::GetGlobalClassRef(env, "java/util/List"); g_listAddMethod = env->GetMethodID(g_listClass, "add", "(Ljava/lang/Object;)Z"); g_countryItemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/CountryItem"); } } // namespace data extern "C" { using namespace storage; using namespace data; // static boolean nativeMoveFile(String oldFile, String newFile); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_MapStorage_nativeMoveFile(JNIEnv * env, jclass clazz, jstring oldFile, jstring newFile) { return my::RenameFileX(jni::ToNativeString(env, oldFile), jni::ToNativeString(env, newFile)); } // static native boolean nativeIsLegacyMode(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsLegacyMode(JNIEnv * env, jclass clazz) { return g_framework->NeedMigrate(); } // static void nativeMigrate(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeMigrate(JNIEnv * env, jclass clazz) { g_framework->Migrate(); } // static int nativeGetDownloadedCount(); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetDownloadedCount(JNIEnv * env, jclass clazz) { return GetStorage().GetDownloadedFilesCount(); } // static String nativeGetRootNode(); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetRootNode(JNIEnv * env, jclass clazz) { return jni::ToJavaString(env, Storage().GetRootId()); } // static @Nullable UpdateInfo nativeGetUpdateInfo(); JNIEXPORT jobject JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetUpdateInfo(JNIEnv * env, jclass clazz) { static Storage::UpdateInfo info = { 0 }; if (!GetStorage().GetUpdateInfo(GetStorage().GetRootId(), info)) return nullptr; static jclass const infoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/downloader/UpdateInfo"); ASSERT(infoClass, (jni::DescribeException())); static jmethodID const ctor = jni::GetConstructorID(env, infoClass, "(II)V"); ASSERT(ctor, (jni::DescribeException())); return env->NewObject(infoClass, ctor, info.m_numberOfMwmFilesToUpdate, info.m_totalUpdateSizeInBytes); } static void UpdateItem(JNIEnv * env, jobject item, NodeAttrs const & attrs) { static jfieldID const countryItemFieldName = env->GetFieldID(g_countryItemClass, "name", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); static jfieldID const countryItemFieldParentName = env->GetFieldID(g_countryItemClass, "parentName", "Ljava/lang/String;"); static jfieldID const countryItemFieldSize = env->GetFieldID(g_countryItemClass, "size", "J"); static jfieldID const countryItemFieldTotalSize = env->GetFieldID(g_countryItemClass, "totalSize", "J"); static jfieldID const countryItemFieldChildCount = env->GetFieldID(g_countryItemClass, "childCount", "I"); static jfieldID const countryItemFieldTotalChildCount = env->GetFieldID(g_countryItemClass, "totalChildCount", "I"); static jfieldID const countryItemFieldStatus = env->GetFieldID(g_countryItemClass, "status", "I"); static jfieldID const countryItemFieldErrorCode = env->GetFieldID(g_countryItemClass, "errorCode", "I"); static jfieldID const countryItemFieldPresent = env->GetFieldID(g_countryItemClass, "present", "Z"); static jfieldID const countryItemFieldProgress = env->GetFieldID(g_countryItemClass, "progress", "I"); // Localized name jni::TScopedLocalRef const name(env, jni::ToJavaString(env, attrs.m_nodeLocalName)); env->SetObjectField(item, countryItemFieldName, name.get()); // Info about parent[s]. Do not specify if there are multiple parents or none. if (attrs.m_parentInfo.size() == 1) { CountryIdAndName const & info = attrs.m_parentInfo[0]; jni::TScopedLocalRef const parentId(env, jni::ToJavaString(env, info.m_id)); env->SetObjectField(item, countryItemFieldParentId, parentId.get()); jni::TScopedLocalRef const parentName(env, jni::ToJavaString(env, info.m_localName)); env->SetObjectField(item, countryItemFieldParentName, parentName.get()); } else { env->SetObjectField(item, countryItemFieldParentId, nullptr); env->SetObjectField(item, countryItemFieldParentName, nullptr); } // Sizes env->SetLongField(item, countryItemFieldSize, attrs.m_localMwmSize); env->SetLongField(item, countryItemFieldTotalSize, attrs.m_mwmSize); // Child counts env->SetIntField(item, countryItemFieldChildCount, attrs.m_localMwmCounter); env->SetIntField(item, countryItemFieldTotalChildCount, attrs.m_mwmCounter); // Status and error code env->SetIntField(item, countryItemFieldStatus, static_cast<jint>(attrs.m_status)); env->SetIntField(item, countryItemFieldErrorCode, static_cast<jint>(attrs.m_error)); // Presence flag env->SetBooleanField(item, countryItemFieldPresent, attrs.m_present); // Progress env->SetIntField(item, countryItemFieldProgress,static_cast<jint>(attrs.m_downloadingMwmSize)); } static void PutItemsToList(JNIEnv * env, jobject const list, vector<TCountryId> const & children, TCountryId const & parent, int category) { static jmethodID const countryItemCtor = jni::GetConstructorID(env, g_countryItemClass, "(Ljava/lang/String;)V"); static jfieldID const countryItemFieldCategory = env->GetFieldID(g_countryItemClass, "category", "I"); NodeAttrs attrs; for (TCountryId const & child : children) { GetStorage().GetNodeAttrs(child, attrs); jni::TScopedLocalRef const id(env, jni::ToJavaString(env, child)); jni::TScopedLocalRef const item(env, env->NewObject(g_countryItemClass, countryItemCtor, id.get())); env->SetIntField(item.get(), countryItemFieldCategory, category); UpdateItem(env, item.get(), attrs); // Put to resulting list env->CallBooleanMethod(list, g_listAddMethod, item.get()); } } // static void nativeListItems(@Nullable String parent, List<CountryItem> result); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeListItems(JNIEnv * env, jclass clazz, jstring parent, jobject result) { PrepareClassRefs(env); Storage const & storage = GetStorage(); TCountryId const parentId = (parent ? jni::ToNativeString(env, parent) : storage.GetRootId()); static jfieldID const countryItemFieldParentId = env->GetFieldID(g_countryItemClass, "parentId", "Ljava/lang/String;"); if (parent) { vector<TCountryId> children; storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } else { // TODO (trashkalmar): Countries near me // Downloaded vector<TCountryId> children; storage.GetDownloadedChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::DOWNLOADED); // All storage.GetChildren(parentId, children); PutItemsToList(env, result, children, parentId, ItemCategory::ALL); } } // static void nativeUpdateItem(CountryItem item); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeGetAttributes(JNIEnv * env, jclass clazz, jobject item) { PrepareClassRefs(env); NodeAttrs attrs; static jfieldID countryItemFieldId = env->GetFieldID(g_countryItemClass, "id", "Ljava/lang/String;"); jstring id = static_cast<jstring>(env->GetObjectField(item, countryItemFieldId)); GetStorage().GetNodeAttrs(jni::ToNativeString(env, id), attrs); UpdateItem(env, item, attrs); } // static @Nullable String nativeFindCountry(double lat, double lon); JNIEXPORT jstring JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeFindCountry(JNIEnv * env, jclass clazz, jdouble lat, jdouble lon) { return jni::ToJavaString(env, g_framework->NativeFramework()->CountryInfoGetter().GetRegionCountryId(MercatorBounds::FromLatLon(lat, lon))); } // static boolean nativeIsDownloading(); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeIsDownloading(JNIEnv * env, jclass clazz) { return GetStorage().IsDownloadInProgress(); } // static boolean nativeDownload(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDownload(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeRetry(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeRetry(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().RetryDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeUpdate(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUpdate(JNIEnv * env, jclass clazz, jstring root) { // FIXME (trashkalmar): Uncomment after method is implemented. //return GetStorage().UpdateNode(jni::ToNativeString(env, root)); return true; } // static boolean nativeCancel(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeCancel(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().CancelDownloadNode(jni::ToNativeString(env, root)); } // static boolean nativeDelete(String root); JNIEXPORT jboolean JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeDelete(JNIEnv * env, jclass clazz, jstring root) { return GetStorage().DeleteNode(jni::ToNativeString(env, root)); } static void StatusChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); // TODO: The core will do this itself NodeAttrs attrs; GetStorage().GetNodeAttrs(countryId, attrs); jmethodID const methodID = jni::GetMethodID(env, *listenerRef.get(), "onStatusChanged", "(Ljava/lang/String;I)V"); env->CallVoidMethod(*listenerRef.get(), methodID, jni::ToJavaString(env, countryId), attrs.m_status); } static void ProgressChangedCallback(shared_ptr<jobject> const & listenerRef, TCountryId const & countryId, TLocalAndRemoteSize const & sizes) { JNIEnv * env = jni::GetEnv(); jmethodID const methodID = jni::GetMethodID(env, *listenerRef.get(), "onProgress", "(Ljava/lang/String;JJ)V"); env->CallVoidMethod(*listenerRef.get(), methodID, jni::ToJavaString(env, countryId), sizes.first, sizes.second); } // static int nativeSubscribe(StorageCallback listener); JNIEXPORT jint JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribe(JNIEnv * env, jclass clazz, jobject listener) { PrepareClassRefs(env); return GetStorage().Subscribe(bind(&StatusChangedCallback, jni::make_global_ref(listener), _1), bind(&ProgressChangedCallback, jni::make_global_ref(listener), _1, _2)); } // static void nativeUnsubscribe(int slot); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribe(JNIEnv * env, jclass clazz, jint slot) { GetStorage().Unsubscribe(slot); } static jobject g_countryChangedListener; // static void nativeSubscribeOnCountryChanged(CurrentCountryChangedListener listener); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeSubscribeOnCountryChanged(JNIEnv * env, jclass clazz, jobject listener) { ASSERT(!g_countryChangedListener, ()); g_countryChangedListener = env->NewGlobalRef(listener); auto const callback = [](TCountryId const & countryId) { JNIEnv * env = jni::GetEnv(); jmethodID methodID = jni::GetMethodID(env, g_countryChangedListener, "onCurrentCountryChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(g_countryChangedListener, methodID, jni::TScopedLocalRef(env, jni::ToJavaString(env, countryId)).get()); }; TCountryId const & prev = g_framework->NativeFramework()->GetLastReportedCountry(); g_framework->NativeFramework()->SetCurrentCountryChangedListener(callback); // Report previous value callback(prev); } // static void nativeUnsubscribeOnCountryChanged(); JNIEXPORT void JNICALL Java_com_mapswithme_maps_downloader_MapManager_nativeUnsubscribeOnCountryChanged(JNIEnv * env, jclass clazz) { g_framework->NativeFramework()->SetCurrentCountryChangedListener(nullptr); ASSERT(g_countryChangedListener, ()); env->DeleteGlobalRef(g_countryChangedListener); g_countryChangedListener = nullptr; } } // extern "C" <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <random> #include <xmmintrin.h> #include "benchmark.hpp" #include "ngraph/file_util.hpp" #include "ngraph/runtime/backend.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/runtime/tensor.hpp" #include "ngraph/serializer.hpp" #include "ngraph/util.hpp" using namespace std; using namespace ngraph; static default_random_engine s_random_engine; void set_denormals_flush_to_zero() { #if defined(__x86_64__) || defined(__amd64__) // Avoids perf impact from denormals while benchmarking with random data _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); #endif } template <typename T> void init_int_tv(shared_ptr<runtime::Tensor> tv, T min, T max) { size_t size = tv->get_element_count(); uniform_int_distribution<T> dist(min, max); vector<T> vec(size); for (T& element : vec) { element = dist(s_random_engine); } tv->write(vec.data(), 0, vec.size() * sizeof(T)); } template <> void init_int_tv<char>(shared_ptr<runtime::Tensor> tv, char min, char max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<char> vec(size); for (char& element : vec) { element = static_cast<char>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(char)); } template <> void init_int_tv<int8_t>(shared_ptr<runtime::Tensor> tv, int8_t min, int8_t max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<int8_t> vec(size); for (int8_t& element : vec) { element = static_cast<int8_t>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(int8_t)); } template <> void init_int_tv<uint8_t>(shared_ptr<runtime::Tensor> tv, uint8_t min, uint8_t max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<uint8_t> vec(size); for (uint8_t& element : vec) { element = static_cast<uint8_t>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(uint8_t)); } template <typename T> void init_real_tv(shared_ptr<runtime::Tensor> tv, T min, T max) { size_t size = tv->get_element_count(); uniform_real_distribution<T> dist(min, max); vector<T> vec(size); for (T& element : vec) { element = dist(s_random_engine); } tv->write(vec.data(), 0, vec.size() * sizeof(T)); } static void random_init(shared_ptr<runtime::Tensor> tv) { element::Type et = tv->get_element_type(); if (et == element::boolean) { init_int_tv<char>(tv, 0, 1); } else if (et == element::f32) { init_real_tv<float>(tv, -1, 1); } else if (et == element::f64) { init_real_tv<double>(tv, -1, 1); } else if (et == element::i8) { init_int_tv<int8_t>(tv, -1, 1); } else if (et == element::i16) { init_int_tv<int16_t>(tv, -1, 1); } else if (et == element::i32) { init_int_tv<int32_t>(tv, 0, 1); } else if (et == element::i64) { init_int_tv<int64_t>(tv, -1, 1); } else if (et == element::u8) { init_int_tv<uint8_t>(tv, 0, 1); } else if (et == element::u16) { init_int_tv<uint16_t>(tv, 0, 1); } else if (et == element::u32) { init_int_tv<uint32_t>(tv, 0, 1); } else if (et == element::u64) { init_int_tv<uint64_t>(tv, 0, 1); } else { throw runtime_error("unsupported type"); } } vector<runtime::PerformanceCounter> run_benchmark(shared_ptr<Function> f, const string& backend_name, size_t iterations, bool timing_detail, int warmup_iterations, bool copy_data) { stopwatch timer; timer.start(); auto backend = runtime::Backend::create(backend_name); backend->enable_performance_data(f, timing_detail); backend->compile(f); timer.stop(); cout.imbue(locale("")); cout << "compile time: " << timer.get_milliseconds() << "ms" << endl; vector<shared_ptr<runtime::HostTensor>> arg_data; vector<shared_ptr<runtime::Tensor>> args; vector<bool> args_cacheable; for (shared_ptr<op::Parameter> param : f->get_parameters()) { auto tensor = backend->create_tensor(param->get_element_type(), param->get_shape()); auto tensor_data = make_shared<runtime::HostTensor>(param->get_element_type(), param->get_shape()); random_init(tensor_data); args.push_back(tensor); arg_data.push_back(tensor_data); args_cacheable.push_back(param->get_cacheable()); } set_denormals_flush_to_zero(); vector<shared_ptr<runtime::HostTensor>> result_data; vector<shared_ptr<runtime::Tensor>> results; for (shared_ptr<Node> out : f->get_results()) { auto result = backend->create_tensor(out->get_element_type(), out->get_shape()); auto tensor_data = make_shared<runtime::HostTensor>(out->get_element_type(), out->get_shape()); results.push_back(result); result_data.push_back(tensor_data); } for (size_t i = 0; i < args.size(); i++) { if (args_cacheable[i]) { args[i]->set_stale(false); } } if (warmup_iterations) { for (int i = 0; i < warmup_iterations; i++) { backend->call(f, results, args); } } stopwatch t1; t1.start(); for (size_t i = 0; i < iterations; i++) { if (copy_data) { for (size_t arg_index = 0; arg_index < args.size(); arg_index++) { const shared_ptr<runtime::Tensor>& arg = args[arg_index]; if (arg->get_stale()) { const shared_ptr<runtime::HostTensor>& data = arg_data[arg_index]; arg->write(data->get_data_ptr(), 0, data->get_element_count() * data->get_element_type().size()); } } } backend->call(f, results, args); if (copy_data) { for (size_t result_index = 0; result_index < results.size(); result_index++) { const shared_ptr<runtime::HostTensor>& data = result_data[result_index]; const shared_ptr<runtime::Tensor>& result = results[result_index]; result->read(data->get_data_ptr(), 0, data->get_element_count() * data->get_element_type().size()); } } } t1.stop(); float time = t1.get_milliseconds(); cout << time / iterations << "ms per iteration" << endl; vector<runtime::PerformanceCounter> perf_data = backend->get_performance_data(f); return perf_data; } <commit_msg>Fix uninitialized parameter tensor data in nbench (#2114)<commit_after>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <random> #include <xmmintrin.h> #include "benchmark.hpp" #include "ngraph/file_util.hpp" #include "ngraph/runtime/backend.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/runtime/tensor.hpp" #include "ngraph/serializer.hpp" #include "ngraph/util.hpp" using namespace std; using namespace ngraph; static default_random_engine s_random_engine; void set_denormals_flush_to_zero() { #if defined(__x86_64__) || defined(__amd64__) // Avoids perf impact from denormals while benchmarking with random data _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); #endif } template <typename T> void init_int_tv(shared_ptr<runtime::Tensor> tv, T min, T max) { size_t size = tv->get_element_count(); uniform_int_distribution<T> dist(min, max); vector<T> vec(size); for (T& element : vec) { element = dist(s_random_engine); } tv->write(vec.data(), 0, vec.size() * sizeof(T)); } template <> void init_int_tv<char>(shared_ptr<runtime::Tensor> tv, char min, char max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<char> vec(size); for (char& element : vec) { element = static_cast<char>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(char)); } template <> void init_int_tv<int8_t>(shared_ptr<runtime::Tensor> tv, int8_t min, int8_t max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<int8_t> vec(size); for (int8_t& element : vec) { element = static_cast<int8_t>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(int8_t)); } template <> void init_int_tv<uint8_t>(shared_ptr<runtime::Tensor> tv, uint8_t min, uint8_t max) { size_t size = tv->get_element_count(); uniform_int_distribution<int16_t> dist(static_cast<short>(min), static_cast<short>(max)); vector<uint8_t> vec(size); for (uint8_t& element : vec) { element = static_cast<uint8_t>(dist(s_random_engine)); } tv->write(vec.data(), 0, vec.size() * sizeof(uint8_t)); } template <typename T> void init_real_tv(shared_ptr<runtime::Tensor> tv, T min, T max) { size_t size = tv->get_element_count(); uniform_real_distribution<T> dist(min, max); vector<T> vec(size); for (T& element : vec) { element = dist(s_random_engine); } tv->write(vec.data(), 0, vec.size() * sizeof(T)); } static void random_init(shared_ptr<runtime::Tensor> tv) { element::Type et = tv->get_element_type(); if (et == element::boolean) { init_int_tv<char>(tv, 0, 1); } else if (et == element::f32) { init_real_tv<float>(tv, -1, 1); } else if (et == element::f64) { init_real_tv<double>(tv, -1, 1); } else if (et == element::i8) { init_int_tv<int8_t>(tv, -1, 1); } else if (et == element::i16) { init_int_tv<int16_t>(tv, -1, 1); } else if (et == element::i32) { init_int_tv<int32_t>(tv, 0, 1); } else if (et == element::i64) { init_int_tv<int64_t>(tv, -1, 1); } else if (et == element::u8) { init_int_tv<uint8_t>(tv, 0, 1); } else if (et == element::u16) { init_int_tv<uint16_t>(tv, 0, 1); } else if (et == element::u32) { init_int_tv<uint32_t>(tv, 0, 1); } else if (et == element::u64) { init_int_tv<uint64_t>(tv, 0, 1); } else { throw runtime_error("unsupported type"); } } vector<runtime::PerformanceCounter> run_benchmark(shared_ptr<Function> f, const string& backend_name, size_t iterations, bool timing_detail, int warmup_iterations, bool copy_data) { stopwatch timer; timer.start(); auto backend = runtime::Backend::create(backend_name); backend->enable_performance_data(f, timing_detail); backend->compile(f); timer.stop(); cout.imbue(locale("")); cout << "compile time: " << timer.get_milliseconds() << "ms" << endl; vector<shared_ptr<runtime::HostTensor>> arg_data; vector<shared_ptr<runtime::Tensor>> args; vector<bool> args_cacheable; for (shared_ptr<op::Parameter> param : f->get_parameters()) { auto tensor = backend->create_tensor(param->get_element_type(), param->get_shape()); auto tensor_data = make_shared<runtime::HostTensor>(param->get_element_type(), param->get_shape()); random_init(tensor_data); tensor->write(tensor_data->get_data_ptr(), 0, tensor_data->get_element_count() * tensor_data->get_element_type().size()); args.push_back(tensor); arg_data.push_back(tensor_data); args_cacheable.push_back(param->get_cacheable()); } set_denormals_flush_to_zero(); vector<shared_ptr<runtime::HostTensor>> result_data; vector<shared_ptr<runtime::Tensor>> results; for (shared_ptr<Node> out : f->get_results()) { auto result = backend->create_tensor(out->get_element_type(), out->get_shape()); auto tensor_data = make_shared<runtime::HostTensor>(out->get_element_type(), out->get_shape()); results.push_back(result); result_data.push_back(tensor_data); } for (size_t i = 0; i < args.size(); i++) { if (args_cacheable[i]) { args[i]->set_stale(false); } } if (warmup_iterations) { for (int i = 0; i < warmup_iterations; i++) { backend->call(f, results, args); } } stopwatch t1; t1.start(); for (size_t i = 0; i < iterations; i++) { if (copy_data) { for (size_t arg_index = 0; arg_index < args.size(); arg_index++) { const shared_ptr<runtime::Tensor>& arg = args[arg_index]; if (arg->get_stale()) { const shared_ptr<runtime::HostTensor>& data = arg_data[arg_index]; arg->write(data->get_data_ptr(), 0, data->get_element_count() * data->get_element_type().size()); } } } backend->call(f, results, args); if (copy_data) { for (size_t result_index = 0; result_index < results.size(); result_index++) { const shared_ptr<runtime::HostTensor>& data = result_data[result_index]; const shared_ptr<runtime::Tensor>& result = results[result_index]; result->read(data->get_data_ptr(), 0, data->get_element_count() * data->get_element_type().size()); } } } t1.stop(); float time = t1.get_milliseconds(); cout << time / iterations << "ms per iteration" << endl; vector<runtime::PerformanceCounter> perf_data = backend->get_performance_data(f); return perf_data; } <|endoftext|>
<commit_before>/* * Appcelerator Titanium Mobile * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "ProxyFactory.h" #include <map> #include <stdio.h> #include <v8.h> #include "AndroidUtil.h" #include "JavaObject.h" #include "JNIUtil.h" #include "KrollBindings.h" #include "Proxy.h" #include "TypeConverter.h" #include "V8Runtime.h" #include "V8Util.h" #define TAG "ProxyFactory" using namespace v8; namespace titanium { typedef struct { FunctionTemplate* v8ProxyTemplate; jmethodID javaProxyCreator; } ProxyInfo; typedef std::map<jclass, ProxyInfo> ProxyFactoryMap; static ProxyFactoryMap factories; #define GET_PROXY_INFO(jclass, info) \ ProxyFactoryMap::iterator i = factories.find(jclass); \ info = i != factories.end() ? &i->second : NULL #define LOG_JNIENV_ERROR(msgMore) \ LOGE(TAG, "Unable to find class %s", msgMore) Handle<Object> ProxyFactory::createV8Proxy(jclass javaClass, jobject javaProxy) { LOGV(TAG, "create v8 proxy"); JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while creating Java proxy."); return Handle<Object>(); } ENTER_V8(V8Runtime::globalContext); Local<Function> creator; LOGV(TAG, "get proxy info"); ProxyInfo* info; GET_PROXY_INFO(javaClass, info); if (!info) { // No info has been registered for this class yet, fall back // to the binding lookup table jstring javaClassName = JNIUtil::getClassName(javaClass); Handle<Value> className = TypeConverter::javaStringToJsString(javaClassName); env->DeleteLocalRef(javaClassName); Handle<Object> exports = KrollBindings::getBinding(className->ToString()); if (exports.IsEmpty()) { String::Utf8Value classStr(className); LOGE(TAG, "Failed to find class for %s", *classStr); LOG_JNIENV_ERROR("while creating V8 Proxy."); return Handle<Object>(); } // TODO: The first value in exports should be the type that's exported // But there's probably a better way to do this Handle<Array> names = exports->GetPropertyNames(); if (names->Length() >= 1) { creator = Local<Function>::Cast(exports->Get(names->Get(0))); } } else { creator = info->v8ProxyTemplate->GetFunction(); } Local<Value> external = External::New(javaProxy); Local<Object> v8Proxy = creator->NewInstance(1, &external); // set the pointer back on the java proxy jlong ptr = (jlong) *Persistent<Object>::New(v8Proxy); jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, ptr); env->SetObjectField(javaProxy, JNIUtil::krollProxyKrollObjectField, javaV8Object); env->DeleteLocalRef(javaV8Object); return scope.Close(v8Proxy); } jobject ProxyFactory::createJavaProxy(jclass javaClass, Local<Object> v8Proxy, const Arguments& args) { ProxyInfo* info; GET_PROXY_INFO(javaClass, info); if (!info) { JNIUtil::logClassName("ProxyFactory: failed to find class for %s", javaClass, true); LOGE(TAG, "No proxy info found for class."); return NULL; } JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while creating Java proxy."); return NULL; } // Create a persistent handle to the V8 proxy // and cast it to a pointer. The Java proxy needs // a reference to the V8 proxy for later use. jlong pv8Proxy = (jlong) *Persistent<Object>::New(v8Proxy); // We also pass the creation URL of the proxy so we can track relative URLs Handle<Value> sourceUrl = args.Callee()->GetScriptOrigin().ResourceName(); String::Utf8Value sourceUrlValue(sourceUrl); const char *url = "app://app.js"; jstring javaSourceUrl = NULL; if (sourceUrlValue.length() > 0) { url = *sourceUrlValue; javaSourceUrl = env->NewStringUTF(url); } // Determine if this constructor call was made within // the createXYZ() wrapper function. This can be tested by checking // if an Arguments object was passed as the sole argument. bool calledFromCreate = false; if (args.Length() == 1 && args[0]->IsObject()) { if (V8Util::constructorNameMatches(args[0]->ToObject(), "Arguments")) { calledFromCreate = true; } } // Convert the V8 arguments into Java types so they can be // passed to the Java creator method. Which converter we use // depends how this constructor was called. jobjectArray javaArgs; if (calledFromCreate) { Local<Object> arguments = args[0]->ToObject(); int length = arguments->Get(Proxy::lengthSymbol)->Int32Value(); int start = 0; // Get the scope variables if provided and extract the source URL. // We need to send that to the Java side when creating the proxy. if (length > 0) { Local<Object> scopeVars = arguments->Get(0)->ToObject(); if (V8Util::constructorNameMatches(scopeVars, "ScopeVars")) { Local<Value> sourceUrl = scopeVars->Get(Proxy::sourceUrlSymbol); javaSourceUrl = TypeConverter::jsValueToJavaString(sourceUrl); } } javaArgs = TypeConverter::jsObjectIndexPropsToJavaArray(arguments, start, length); } else { javaArgs = TypeConverter::jsArgumentsToJavaArray(args); } jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, pv8Proxy); // Create the java proxy using the creator static method provided. // Send along a pointer to the v8 proxy so the two are linked. jobject javaProxy = env->CallStaticObjectMethod(JNIUtil::krollProxyClass, info->javaProxyCreator, javaClass, javaV8Object, javaArgs, javaSourceUrl); if (javaSourceUrl) { LOGV(TAG, "delete source url!"); env->DeleteLocalRef(javaSourceUrl); } env->DeleteLocalRef(javaV8Object); env->DeleteLocalRef(javaArgs); return javaProxy; } jobject ProxyFactory::unwrapJavaProxy(const Arguments& args) { if (args.Length() != 1) return NULL; Local<Value> firstArgument = args[0]; return firstArgument->IsExternal() ? (jobject)External::Unwrap(firstArgument) : NULL; } void ProxyFactory::registerProxyPair(jclass javaProxyClass, FunctionTemplate* v8ProxyTemplate) { JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while registering proxy pair."); return; } ProxyInfo info; info.v8ProxyTemplate = v8ProxyTemplate; info.javaProxyCreator = JNIUtil::krollProxyCreateProxyMethod; factories[javaProxyClass] = info; } } <commit_msg>Fix the build.<commit_after>/* * Appcelerator Titanium Mobile * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "ProxyFactory.h" #include <map> #include <stdio.h> #include <v8.h> #include "AndroidUtil.h" #include "JavaObject.h" #include "JNIUtil.h" #include "KrollBindings.h" #include "Proxy.h" #include "TypeConverter.h" #include "V8Runtime.h" #include "V8Util.h" #define TAG "ProxyFactory" using namespace v8; namespace titanium { typedef struct { FunctionTemplate* v8ProxyTemplate; jmethodID javaProxyCreator; } ProxyInfo; typedef std::map<jclass, ProxyInfo> ProxyFactoryMap; static ProxyFactoryMap factories; #define GET_PROXY_INFO(jclass, info) \ ProxyFactoryMap::iterator i = factories.find(jclass); \ info = i != factories.end() ? &i->second : NULL #define LOG_JNIENV_ERROR(msgMore) \ LOGE(TAG, "Unable to find class %s", msgMore) Handle<Object> ProxyFactory::createV8Proxy(jclass javaClass, jobject javaProxy) { LOGV(TAG, "create v8 proxy"); JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while creating Java proxy."); return Handle<Object>(); } ENTER_V8(V8Runtime::globalContext); Local<Function> creator; LOGV(TAG, "get proxy info"); ProxyInfo* info; GET_PROXY_INFO(javaClass, info); if (!info) { // No info has been registered for this class yet, fall back // to the binding lookup table jstring javaClassName = JNIUtil::getClassName(javaClass); Handle<Value> className = TypeConverter::javaStringToJsString(javaClassName); env->DeleteLocalRef(javaClassName); Handle<Object> exports = KrollBindings::getBinding(className->ToString()); if (exports.IsEmpty()) { String::Utf8Value classStr(className); LOGE(TAG, "Failed to find class for %s", *classStr); LOG_JNIENV_ERROR("while creating V8 Proxy."); return Handle<Object>(); } // TODO: The first value in exports should be the type that's exported // But there's probably a better way to do this Handle<Array> names = exports->GetPropertyNames(); if (names->Length() >= 1) { creator = Local<Function>::Cast(exports->Get(names->Get(0))); } } else { creator = info->v8ProxyTemplate->GetFunction(); } Local<Value> external = External::New(javaProxy); Local<Object> v8Proxy = creator->NewInstance(1, &external); // set the pointer back on the java proxy jlong ptr = (jlong) *Persistent<Object>::New(v8Proxy); jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, ptr); env->SetObjectField(javaProxy, JNIUtil::krollProxyKrollObjectField, javaV8Object); env->DeleteLocalRef(javaV8Object); return scope.Close(v8Proxy); } jobject ProxyFactory::createJavaProxy(jclass javaClass, Local<Object> v8Proxy, const Arguments& args) { ProxyInfo* info; GET_PROXY_INFO(javaClass, info); if (!info) { JNIUtil::logClassName("ProxyFactory: failed to find class for %s", javaClass, true); LOGE(TAG, "No proxy info found for class."); return NULL; } JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while creating Java proxy."); return NULL; } // Create a persistent handle to the V8 proxy // and cast it to a pointer. The Java proxy needs // a reference to the V8 proxy for later use. jlong pv8Proxy = (jlong) *Persistent<Object>::New(v8Proxy); // We also pass the creation URL of the proxy so we can track relative URLs Handle<Value> sourceUrl = args.Callee()->GetScriptOrigin().ResourceName(); String::Utf8Value sourceUrlValue(sourceUrl); const char *url = "app://app.js"; jstring javaSourceUrl = NULL; if (sourceUrlValue.length() > 0) { url = *sourceUrlValue; javaSourceUrl = env->NewStringUTF(url); } // Determine if this constructor call was made within // the createXYZ() wrapper function. This can be tested by checking // if an Arguments object was passed as the sole argument. bool calledFromCreate = false; if (args.Length() == 1 && args[0]->IsObject()) { if (V8Util::constructorNameMatches(args[0]->ToObject(), "Arguments")) { calledFromCreate = true; } } // Convert the V8 arguments into Java types so they can be // passed to the Java creator method. Which converter we use // depends how this constructor was called. jobjectArray javaArgs; if (calledFromCreate) { Local<Object> arguments = args[0]->ToObject(); int length = arguments->Get(Proxy::lengthSymbol)->Int32Value(); int start = 0; // Get the scope variables if provided and extract the source URL. // We need to send that to the Java side when creating the proxy. if (length > 0) { Local<Object> scopeVars = arguments->Get(0)->ToObject(); if (V8Util::constructorNameMatches(scopeVars, "ScopeVars")) { Local<Value> sourceUrl = scopeVars->Get(Proxy::sourceUrlSymbol); javaSourceUrl = TypeConverter::jsValueToJavaString(sourceUrl); start = 1; } } javaArgs = TypeConverter::jsObjectIndexPropsToJavaArray(arguments, start, length); } else { javaArgs = TypeConverter::jsArgumentsToJavaArray(args); } jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass, JNIUtil::v8ObjectInitMethod, pv8Proxy); // Create the java proxy using the creator static method provided. // Send along a pointer to the v8 proxy so the two are linked. jobject javaProxy = env->CallStaticObjectMethod(JNIUtil::krollProxyClass, info->javaProxyCreator, javaClass, javaV8Object, javaArgs, javaSourceUrl); if (javaSourceUrl) { LOGV(TAG, "delete source url!"); env->DeleteLocalRef(javaSourceUrl); } env->DeleteLocalRef(javaV8Object); env->DeleteLocalRef(javaArgs); return javaProxy; } jobject ProxyFactory::unwrapJavaProxy(const Arguments& args) { if (args.Length() != 1) return NULL; Local<Value> firstArgument = args[0]; return firstArgument->IsExternal() ? (jobject)External::Unwrap(firstArgument) : NULL; } void ProxyFactory::registerProxyPair(jclass javaProxyClass, FunctionTemplate* v8ProxyTemplate) { JNIEnv* env = JNIScope::getEnv(); if (!env) { LOG_JNIENV_ERROR("while registering proxy pair."); return; } ProxyInfo info; info.v8ProxyTemplate = v8ProxyTemplate; info.javaProxyCreator = JNIUtil::krollProxyCreateProxyMethod; factories[javaProxyClass] = info; } } <|endoftext|>
<commit_before><commit_msg>Set snapshot in transaction and read options.<commit_after><|endoftext|>
<commit_before><commit_msg>remove unused lambda capture (#17503)<commit_after><|endoftext|>
<commit_before>#include "core/utf8.h" #include "tests/stringeq.h" #include "catch.hpp" #include <vector> #include <string> using namespace euphoria::core; namespace { using T = std::vector<unsigned int>; std::pair<bool, T> parse_to_codepoints(const std::string& str) { auto ret = T{}; const auto r = utf8_to_codepoints(str, [&](unsigned int cp) { ret.push_back(cp); }); return std::make_pair(r, ret); } } TEST_CASE("utf8_tests") { SECTION("empty") { const auto [ok, code_points] = parse_to_codepoints(u8""); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{})); } SECTION("Dollar sign") { const auto [ok, code_points] = parse_to_codepoints(u8"$"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{044})); } SECTION("Cent sign") { const auto [ok, code_points] = parse_to_codepoints(u8"¢"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{0242})); } SECTION("Devanagari character") { const auto [ok, code_points] = parse_to_codepoints(u8"ह"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{004471})); } SECTION("Euro sign") { const auto [ok, code_points] = parse_to_codepoints(u8"€"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{020254})); } SECTION("Hwair") { const auto [ok, code_points] = parse_to_codepoints(u8"𐍈"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{0201510})); } } <commit_msg>fix: utf8 tests work on windows too<commit_after>#include "core/utf8.h" #include "tests/stringeq.h" #include "catch.hpp" #include <vector> #include <string> using namespace euphoria::core; namespace { using T = std::vector<unsigned int>; std::pair<bool, T> parse_to_codepoints(const std::string& str) { auto ret = T{}; const auto r = utf8_to_codepoints(str, [&](unsigned int cp) { ret.push_back(cp); }); return std::make_pair(r, ret); } } TEST_CASE("utf8_tests") { SECTION("empty") { const auto [ok, code_points] = parse_to_codepoints(""); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{})); } SECTION("Dollar sign") { const auto [ok, code_points] = parse_to_codepoints("$"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{ 044 })); } SECTION("Cent sign") { const auto [ok, code_points] = parse_to_codepoints("¢"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{ 0242 })); } SECTION("Devanagari character") { const auto [ok, code_points] = parse_to_codepoints("ह"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{ 004471 })); } SECTION("Euro sign") { const auto [ok, code_points] = parse_to_codepoints("€"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{ 020254 })); } SECTION("Hwair") { const auto [ok, code_points] = parse_to_codepoints("𐍈"); CHECK(ok); CHECK_THAT(code_points, Catch::Equals(T{ 0201510 })); } } <|endoftext|>
<commit_before>/** This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Its purpose is to calculate zero-dimensional persistence diagrams of spectra. This is supposed to yield a simple feature descriptor which in turn might be used in machine learning pipepline. Input: filename Output: persistence diagram The persistence diagram represents the superlevel set filtration of the input data. This permits us to quantify the number of maxima in a data set. Original author: Bastian Rieck */ #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/ConnectedComponents.hh> #include <aleph/topology/io/FlexSpectrum.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <algorithm> #include <iomanip> #include <iostream> #include <string> #include <tuple> #include <cassert> #include <cmath> #include <getopt.h> using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; int main( int argc, char** argv ) { bool normalize = false; std::string mode = "diagram"; { static option commandLineOptions[] = { { "mode" , required_argument, nullptr, 'm' }, { "normalize", no_argument , nullptr, 'n' }, { nullptr , 0 , nullptr, 0 } }; int option = 0; while( ( option = getopt_long( argc, argv, "m:n", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'm': mode = optarg; break; case 'n': normalize = true; break; } } } if( ( argc - optind ) < 1 ) return -1; std::string input = argv[optind++]; // Parse input ------------------------------------------------------- std::cerr << "* Reading '" << input << "'..."; SimplicialComplex K; aleph::topology::io::FlexSpectrumReader reader; if( normalize ) reader.normalize( true ); reader( input, K ); std::cerr << "finished\n"; // Calculate persistent homology ------------------------------------- std::cerr << "* Calculating persistent homology..."; using PersistencePairing = aleph::PersistencePairing<VertexType>; using Traits = aleph::traits::PersistencePairingCalculation<PersistencePairing>; auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram<Simplex, Traits>( K ); std::cerr << "finished\n"; auto&& D = std::get<0>( tuple ); auto&& pairing = std::get<1>( tuple ); // Output ------------------------------------------------------------ if( mode == "diagram" ) { assert( D.dimension() == 0 ); assert( D.betti() == 1 ); D.removeDiagonal(); // This ensures that the global maximum is paired with the global // minimum of the persistence diagram. This is valid because each // function has finite support and is bounded from below. std::transform( D.begin(), D.end(), D.begin(), [] ( const PersistenceDiagram::Point& p ) { // TODO: we should check whether zero is really the smallest // value if( p.isUnpaired() ) return PersistenceDiagram::Point( p.x(), DataType() ); else return PersistenceDiagram::Point( p ); } ); std::cout << std::setprecision(11) << D << "\n"; } // Transform the (normalized) spectrum into a plane where the // $y$-value indicates the persistence of a peak. Thus, it is // easier to filter away peaks. else if( mode == "transformation" ) { auto&& map = reader.getIndexToValueMap(); // TODO: there is surely a better way to report the transformed // function, but the map sorts values automatically, which sure // is nice. std::map<double, double> transformedFunction; for( auto&& pair : pairing ) { auto&& creator = pair.first; auto&& destroyer = pair.second; auto&& sigma = K.at( creator ); auto&& tau = destroyer < K.size() ? K.at( destroyer ) : Simplex( {0,1}, DataType() ); assert( sigma.dimension() == 0 ); assert( tau.dimension() == 1 ); auto persistence = std::abs( double( sigma.data() ) - double( tau.data() ) ); auto x = map.at( sigma[0] ); transformedFunction[x] = persistence; } for( auto&& pair : transformedFunction ) std::cout << std::setprecision(11) << pair.first << "\t" << pair.second << "\n"; } // Perform *no* transformation at all, thereby essentially making the // program into a simple converter. The normalization flag is will be // honoured, though. else if( mode == "identity" ) { auto&& map_x = reader.getIndexToValueMap(); auto&& map_y = reader.getIndexToIntensityMap(); for( auto&& pair : map_x ) { auto& i = pair.first; auto& x = pair.second; auto& y = map_y.at(i); std::cout << std::setprecision(11) << x << "\t" << y << "\n"; } } } <commit_msg>Calculating diagonal elements along with the persistence pairing<commit_after>/** This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Its purpose is to calculate zero-dimensional persistence diagrams of spectra. This is supposed to yield a simple feature descriptor which in turn might be used in machine learning pipepline. Input: filename Output: persistence diagram The persistence diagram represents the superlevel set filtration of the input data. This permits us to quantify the number of maxima in a data set. Original author: Bastian Rieck */ #include <aleph/persistenceDiagrams/PersistenceDiagram.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/ConnectedComponents.hh> #include <aleph/topology/io/FlexSpectrum.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <algorithm> #include <iomanip> #include <iostream> #include <string> #include <tuple> #include <cassert> #include <cmath> #include <getopt.h> using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; using PersistenceDiagram = aleph::PersistenceDiagram<DataType>; int main( int argc, char** argv ) { bool normalize = false; std::string mode = "diagram"; { static option commandLineOptions[] = { { "mode" , required_argument, nullptr, 'm' }, { "normalize", no_argument , nullptr, 'n' }, { nullptr , 0 , nullptr, 0 } }; int option = 0; while( ( option = getopt_long( argc, argv, "m:n", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'm': mode = optarg; break; case 'n': normalize = true; break; } } } if( ( argc - optind ) < 1 ) return -1; std::string input = argv[optind++]; // Parse input ------------------------------------------------------- std::cerr << "* Reading '" << input << "'..."; SimplicialComplex K; aleph::topology::io::FlexSpectrumReader reader; if( normalize ) reader.normalize( true ); reader( input, K ); std::cerr << "finished\n"; // Calculate persistent homology ------------------------------------- std::cerr << "* Calculating persistent homology..."; using PersistencePairing = aleph::PersistencePairing<VertexType>; using PairingCalculationTraits = aleph::traits::PersistencePairingCalculation<PersistencePairing>; using ElementCalculationTraits = aleph::traits::DiagonalElementCalculation; auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram< Simplex, PairingCalculationTraits, ElementCalculationTraits>( K ); std::cerr << "finished\n"; auto&& D = std::get<0>( tuple ); auto&& pairing = std::get<1>( tuple ); // Output ------------------------------------------------------------ if( mode == "diagram" ) { assert( D.dimension() == 0 ); assert( D.betti() == 1 ); D.removeDiagonal(); // This ensures that the global maximum is paired with the global // minimum of the persistence diagram. This is valid because each // function has finite support and is bounded from below. std::transform( D.begin(), D.end(), D.begin(), [] ( const PersistenceDiagram::Point& p ) { // TODO: we should check whether zero is really the smallest // value if( p.isUnpaired() ) return PersistenceDiagram::Point( p.x(), DataType() ); else return PersistenceDiagram::Point( p ); } ); std::cout << std::setprecision(11) << D << "\n"; } // Transform the (normalized) spectrum into a plane where the // $y$-value indicates the persistence of a peak. Thus, it is // easier to filter away peaks. else if( mode == "transformation" ) { auto&& map = reader.getIndexToValueMap(); // TODO: there is surely a better way to report the transformed // function, but the map sorts values automatically, which sure // is nice. std::map<double, double> transformedFunction; for( auto&& pair : pairing ) { auto&& creator = pair.first; auto&& destroyer = pair.second; auto&& sigma = K.at( creator ); auto&& tau = destroyer < K.size() ? K.at( destroyer ) : Simplex( {0,1}, DataType() ); assert( sigma.dimension() == 0 ); assert( tau.dimension() == 1 ); auto persistence = std::abs( double( sigma.data() ) - double( tau.data() ) ); auto x = map.at( sigma[0] ); transformedFunction[x] = persistence; } for( auto&& pair : transformedFunction ) std::cout << std::setprecision(11) << pair.first << "\t" << pair.second << "\n"; } // Perform *no* transformation at all, thereby essentially making the // program into a simple converter. The normalization flag is will be // honoured, though. else if( mode == "identity" ) { auto&& map_x = reader.getIndexToValueMap(); auto&& map_y = reader.getIndexToIntensityMap(); for( auto&& pair : map_x ) { auto& i = pair.first; auto& x = pair.second; auto& y = map_y.at(i); std::cout << std::setprecision(11) << x << "\t" << y << "\n"; } } } <|endoftext|>
<commit_before>/* * Copyright 2001-2007 Adrian Thurston <thurston@complang.org> */ /* This file is part of Colm. * * Colm 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. * * Colm 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 Colm; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "colm.h" #include "parsedata.h" using namespace std; void ParseData::writeTransList( PdaState *state ) { for ( TransMap::Iter trans = state->transMap; trans.lte(); trans++ ) { /* Write out the from and to states. */ out << "\t" << state->stateNum << " -> " << trans->value->toState->stateNum; /* Begin the label. */ out << " [ label = \""; long key = trans->key; KlangEl *lel = langElIndex[key]; if ( lel != 0 ) out << lel->name; else out << (char)key; if ( trans->value->actions.length() > 0 ) { out << " / "; for ( ActDataList::Iter act = trans->value->actions; act.lte(); act++ ) { switch ( *act & 0x3 ) { case 1: out << "S(" << trans->value->actOrds[act.pos()] << ")"; break; case 2: { out << "R(" << prodIdIndex[(*act >> 2)]->data << ", " << trans->value->actOrds[act.pos()] << ")"; break; } case 3: { out << "SR(" << prodIdIndex[(*act >> 2)]->data << ", " << trans->value->actOrds[act.pos()] << ")"; break; }} if ( ! act.last() ) out << ", "; } } out << "\" ];\n"; } } void ParseData::writeDotFile( PdaGraph *graph ) { out << "digraph " << parserName << " {\n" " rankdir=LR;\n" " ranksep=\"0\"\n" " nodesep=\"0.25\"\n" "\n"; /* Define the psuedo states. Transitions will be done after the states * have been defined as either final or not final. */ out << " node [ shape = point ];\n"; for ( int i = 0; i < graph->entryStateSet.length(); i++ ) out << "\tENTRY" << i << " [ label = \"\" ];\n"; out << "\n" " node [ shape = circle, fixedsize = true, height = 0.2 ];\n"; /* Walk the states. */ for ( PdaStateList::Iter st = graph->stateList; st.lte(); st++ ) out << " " << st->stateNum << " [ label = \"\" ];\n"; out << "\n"; /* Walk the states. */ for ( PdaStateList::Iter st = graph->stateList; st.lte(); st++ ) writeTransList( st ); /* Start state and other entry points. */ for ( PdaStateSet::Iter st = graph->entryStateSet; st.lte(); st++ ) out << "\tENTRY" << st.pos() << " -> " << (*st)->stateNum << " [ label = \"\" ];\n"; out << "}\n"; } void ParseData::writeDotFile() { writeDotFile( pdaGraph ); } <commit_msg>label the states<commit_after>/* * Copyright 2001-2007 Adrian Thurston <thurston@complang.org> */ /* This file is part of Colm. * * Colm 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. * * Colm 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 Colm; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "colm.h" #include "parsedata.h" using namespace std; void ParseData::writeTransList( PdaState *state ) { for ( TransMap::Iter trans = state->transMap; trans.lte(); trans++ ) { /* Write out the from and to states. */ out << "\t" << state->stateNum << " -> " << trans->value->toState->stateNum; /* Begin the label. */ out << " [ label = \""; long key = trans->key; KlangEl *lel = langElIndex[key]; if ( lel != 0 ) out << lel->name; else out << (char)key; if ( trans->value->actions.length() > 0 ) { out << " / "; for ( ActDataList::Iter act = trans->value->actions; act.lte(); act++ ) { switch ( *act & 0x3 ) { case 1: out << "S(" << trans->value->actOrds[act.pos()] << ")"; break; case 2: { out << "R(" << prodIdIndex[(*act >> 2)]->data << ", " << trans->value->actOrds[act.pos()] << ")"; break; } case 3: { out << "SR(" << prodIdIndex[(*act >> 2)]->data << ", " << trans->value->actOrds[act.pos()] << ")"; break; }} if ( ! act.last() ) out << ", "; } } out << "\" ];\n"; } } void ParseData::writeDotFile( PdaGraph *graph ) { out << "digraph " << parserName << " {\n" " rankdir=LR;\n" " ranksep=\"0\"\n" " nodesep=\"0.25\"\n" "\n"; /* Define the psuedo states. Transitions will be done after the states * have been defined as either final or not final. */ out << " node [ shape = point ];\n"; for ( int i = 0; i < graph->entryStateSet.length(); i++ ) out << "\tENTRY" << i << " [ label = \"\" ];\n"; out << "\n" " node [ shape = circle, fixedsize = true, height = 0.6 ];\n"; /* Walk the states. */ for ( PdaStateList::Iter st = graph->stateList; st.lte(); st++ ) out << " " << st->stateNum << " [ label = \"" << st->stateNum << "\" ];\n"; out << "\n"; /* Walk the states. */ for ( PdaStateList::Iter st = graph->stateList; st.lte(); st++ ) writeTransList( st ); /* Start state and other entry points. */ for ( PdaStateSet::Iter st = graph->entryStateSet; st.lte(); st++ ) out << "\tENTRY" << st.pos() << " -> " << (*st)->stateNum << " [ label = \"\" ];\n"; out << "}\n"; } void ParseData::writeDotFile() { writeDotFile( pdaGraph ); } <|endoftext|>